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:
Writing Sudoku Solver wih Python
Here is my Sudoku Solver written in python language, When I run this program there seems to be a problem with in Update function and Solve function.
No matter how much time I look over and move the codes around, I seem to have no luck
Can anyone Help me?
import copy
def display (... | Writing Sudoku Solver wih Python | Here is my Sudoku Solver written in python language, When I run this program there seems to be a problem with in Update function and Solve function.
No matter how much time I look over and move the codes around, I seem to have no luck
Can anyone Help me?
import copy
def display (A):
if A:
for i in range... | [
"If you want to stabilize your code, then write small test cases for each function which make sure that they work correctly.\nIn your case, run a puzzle, and determine which field is wrong. Then guess which function might produce the wrong output. Call it with the input to see what it really does. Repeat for every ... | [
3,
3,
2,
0
] | [] | [] | [
"python",
"sudoku"
] | stackoverflow_0001781795_python_sudoku.txt |
Q:
app engine: string to datetime?
i have string
date = "11/28/2009"
hour = "23"
minutes = "59"
seconds = "00"
how can i convert to datetime object and store it in datastore?
A:
I apologize if this isn't what you want, but at least for the first part of the question you could probably do it like so?
>>> import da... | app engine: string to datetime? | i have string
date = "11/28/2009"
hour = "23"
minutes = "59"
seconds = "00"
how can i convert to datetime object and store it in datastore?
| [
"I apologize if this isn't what you want, but at least for the first part of the question you could probably do it like so?\n>>> import datetime\n>>> datetime.datetime.strptime(date + ' ' + hour + ':' + minutes + ':' + seconds, '%m/%d/%Y %H:%M:%S')\ndatetime.datetime(2009, 11, 28, 23, 59)\n\n"
] | [
11
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0001782255_datetime_python.txt |
Q:
How do I order this list in Python?
[(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
I want to order this alphabetically, by "PRP, VBD, PRP, and VBP"
It's not the traditional sort, right?
A:
Use itemgetter:
>>> a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VB... | How do I order this list in Python? | [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
I want to order this alphabetically, by "PRP, VBD, PRP, and VBP"
It's not the traditional sort, right?
| [
"Use itemgetter:\n>>> a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]\n>>> import operator\n>>> a.sort(key = operator.itemgetter(1))\n>>> a\n[(u'.', '.'), (u'we', 'PRP'), (u'you', 'PRP'), (u'saw', 'VBD'), (u'bruh', 'VBP')]\n\n",
"The sort method takes a key argument to extrac... | [
15,
7,
1,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0001782253_list_python_sorting.txt |
Q:
How to change firefox proxy from webdriver?
how can I access Firefox proxy settings from Python Webdriver and change them to make Firefox use modified proxy settings without needing to restart it?
A:
I don't think that is possible from the outside of Firefox. Have a look at FoxyProxy. It allows you to define a p... | How to change firefox proxy from webdriver? | how can I access Firefox proxy settings from Python Webdriver and change them to make Firefox use modified proxy settings without needing to restart it?
| [
"I don't think that is possible from the outside of Firefox. Have a look at FoxyProxy. It allows you to define a proxy per URL pattern.\n"
] | [
0
] | [] | [] | [
"firefox",
"proxy",
"python",
"webdriver"
] | stackoverflow_0001782375_firefox_proxy_python_webdriver.txt |
Q:
Convert Perl script to Python: dedupe 2 files based on hash keys
I am new to Python and would like to know if someone would kindly convert an example of a fairly simple Perl script to Python?
The script takes 2 files and outputs only unique lines from the second file by comparing hash keys. It also outputs duplic... | Convert Perl script to Python: dedupe 2 files based on hash keys | I am new to Python and would like to know if someone would kindly convert an example of a fairly simple Perl script to Python?
The script takes 2 files and outputs only unique lines from the second file by comparing hash keys. It also outputs duplicate lines to a file. I have found that this method of deduping is extr... | [
"You can use sets in Python if you don't care about order:\nfile1=set(open(\"file1\").readlines())\nfile2=set(open(\"file2\").readlines())\nintersection = file1 & file2 #common lines\nnon_intersection = file2 - file1 #uncommon lines (in file2 but not file1)\nfor items in intersection:\n print items\nfor nitems ... | [
7,
4,
3
] | [] | [] | [
"hash",
"perl",
"python"
] | stackoverflow_0001782033_hash_perl_python.txt |
Q:
Python programs coexisting on Windows
I'm looking for a way to let multiple Python programs coexist on the same Windows machine.
Here's the problem: suppose program A needs Python 2.5, B needs 2.6, C needs 3, and each of them needs its own version of Qt, Wx or whatever other modules or whatever.
Trying to install ... | Python programs coexisting on Windows | I'm looking for a way to let multiple Python programs coexist on the same Windows machine.
Here's the problem: suppose program A needs Python 2.5, B needs 2.6, C needs 3, and each of them needs its own version of Qt, Wx or whatever other modules or whatever.
Trying to install all these dependencies on the same machine ... | [
"VirtualEnv. \n\nvirtualenv is a tool to create\n isolated Python environments.\nThe basic problem being addressed is\n one of dependencies and versions, and\n indirectly permissions. Imagine you\n have an application that needs version\n 1 of LibFoo, but another application\n requires version 2. How can you ... | [
7,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0001779630_python_windows.txt |
Q:
Why don't these two math functions return the same result?
I'm trying to use fancy indexing instead of looping to speed up a function in Numpy. To the best of my knowledge, I've implemented the fancy indexing version correctly. The problem is that the two functions (loop and fancy-indexed) do not return the same r... | Why don't these two math functions return the same result? | I'm trying to use fancy indexing instead of looping to speed up a function in Numpy. To the best of my knowledge, I've implemented the fancy indexing version correctly. The problem is that the two functions (loop and fancy-indexed) do not return the same result. I'm not sure why. It's worth pointing out that the functi... | [
"The problem is this line:\nmaxdiff[the_diff > maxdiff] = the_diff\n\nThe left side selects only some elements of maxdiff, but the right side contains all elements of the_diff. This should work instead:\nreplaceElements = the_diff > maxdiff\nmaxdiff[replaceElements] = the_diff[replaceElements]\n\nor simply:\nmaxdif... | [
3,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0001782114_numpy_python_scipy.txt |
Q:
Configure MySQL to work with Django
Just installed Django (with easy_install) and created a project, but can't get mysql to work.
python manage.py syncdb throws this error:
.....
File "/Library/Python/2.6/site-packages/Django-1.1.1-py2.6.egg/django/db/backends/mysql/base.py", line 13, in <module>
raise Im... | Configure MySQL to work with Django | Just installed Django (with easy_install) and created a project, but can't get mysql to work.
python manage.py syncdb throws this error:
.....
File "/Library/Python/2.6/site-packages/Django-1.1.1-py2.6.egg/django/db/backends/mysql/base.py", line 13, in <module>
raise ImproperlyConfigured("Error loading MySQLdb... | [
"you need Python library for MySQL access, MySQLdb:\nhttp://sourceforge.net/projects/mysql-python/\n",
"The MySQL egg requires a compiler from the dev tools (download XCode from the apple developers site) and a MySQL installation.\nIf you have installed those, you have set the PATH to include mysql_config.\nexpor... | [
3,
0
] | [] | [] | [
"configuration",
"django",
"installation",
"mysql",
"python"
] | stackoverflow_0001781618_configuration_django_installation_mysql_python.txt |
Q:
WSGI byte ranges serving
I'm looking into supporting HTTP/1.1 Byte serving in WSGI server/application for:
resuming partial downloads
multi-part downloads
better streaming
WSGI PEP 333 mentions that WSGI server may implement handling of byte serving (from RFC 2616 section 14.35.2 defines Accept-Range/Range/Conte... | WSGI byte ranges serving | I'm looking into supporting HTTP/1.1 Byte serving in WSGI server/application for:
resuming partial downloads
multi-part downloads
better streaming
WSGI PEP 333 mentions that WSGI server may implement handling of byte serving (from RFC 2616 section 14.35.2 defines Accept-Range/Range/Content-Range response/request/resp... | [
"I think webob may do the trick, see the end of the file example for a range request implementation which efficiently seeks into the file being served.\n",
"You just need to use WebOb and create the response as Response(conditional_request=True) or subclass the WebOb Response object making conditional_request=Tru... | [
3,
0
] | [] | [] | [
"http",
"http_headers",
"middleware",
"python",
"wsgi"
] | stackoverflow_0000579426_http_http_headers_middleware_python_wsgi.txt |
Q:
What is the most efficent way to implement concurrency in Python?
In a cluster environment using Python what is the least expensive way to develop a concurrent application or what is the pro / con of the various options?
A:
I would say Google app engine is the easiest option since you don't have to worry about a... | What is the most efficent way to implement concurrency in Python? | In a cluster environment using Python what is the least expensive way to develop a concurrent application or what is the pro / con of the various options?
| [
"I would say Google app engine is the easiest option since you don't have to worry about all this things. But if it's a big project, it might not be the cheapest solution. \nAgain, it really depends on the size of your project and what you really want to do.\nYou need to give more details if you want to get a preci... | [
1
] | [] | [] | [
"concurrency",
"multithreading",
"process",
"python"
] | stackoverflow_0001783714_concurrency_multithreading_process_python.txt |
Q:
String preallocation in numpy.arrays
>>> import numpy as np
>>> a = np.array(['zero', 'one', 'two', 'three'])
>>> a[1] = 'thirteen'
>>> print a
['zero' 'thirt' 'two' 'three']
>>>
As you can see, the second element has been truncated to the maximum number of characters in the original array.
Is it possible to work... | String preallocation in numpy.arrays | >>> import numpy as np
>>> a = np.array(['zero', 'one', 'two', 'three'])
>>> a[1] = 'thirteen'
>>> print a
['zero' 'thirt' 'two' 'three']
>>>
As you can see, the second element has been truncated to the maximum number of characters in the original array.
Is it possible to workaround this problem?
| [
"If you don't know the maximum length element, then you can use dtype=object\n>>> import numpy as np\n>>> a = np.array(['zero', 'one', 'two', 'three'], dtype=object)\n>>> a[1] = 'thirteen'\n>>> print a\n['zero' 'thirteen' 'two' 'three']\n>>>\n\n",
"Use the dtype argument in numpy.array, e.g.:\n>>> import numpy as... | [
6,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0001783369_numpy_python.txt |
Q:
How do I unit test Django views on the Google App Engine?
I am struggling to run unit tests using the Django Client class on the Google App Engine. I downloaded GAEUnit (v2.0a for Django) and I am trying to use that as my testing framework (maybe I should rather be using something else?)
I copy all the GAEUnit fil... | How do I unit test Django views on the Google App Engine? | I am struggling to run unit tests using the Django Client class on the Google App Engine. I downloaded GAEUnit (v2.0a for Django) and I am trying to use that as my testing framework (maybe I should rather be using something else?)
I copy all the GAEUnit files into my project root as instructed, and I modify my app.yaml... | [
"I managed to figure out what was wrong here. I made two mistakes:\n\nIn app.yaml, url: /test.* had to be before url:/.* (otherwise the /test URL would be matched to /.* before getting to the /test.* handler)\nBeware of copying all the files from the GAEUnit package into your project root! The GAEUnit folder cont... | [
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001784076_django_google_app_engine_python.txt |
Q:
Django passing a model instance to slightly different model
I'm writing an django app for a project where everybody can change articles but the changes that users commit have to be viewed by someone before they go online. So you see it is a bit like the system used by wikipedia.
class Content(models.Model):
tp... | Django passing a model instance to slightly different model | I'm writing an django app for a project where everybody can change articles but the changes that users commit have to be viewed by someone before they go online. So you see it is a bit like the system used by wikipedia.
class Content(models.Model):
tp = models.DateTimeField(auto_now_add=True)
topic = models.Cha... | [
"The way you have your models coded, I don't think it's going to work like you're expecting. In this case ChangeSet inherits from Content. The way Django implements this is by create a OneToOneField that connects ChangeSet with Content. This means 2 things for your application:\n\nHaving the ForeignKey is pointl... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001782815_django_python.txt |
Q:
Most useful list-comprehension construction?
What Python's user-made list-comprehension construction is the most useful?
I have created the following two quantifiers, which I use to do different verification operations:
def every(f, L): return not (False in [f(x) for x in L])
def some(f, L): return True in [f(x) ... | Most useful list-comprehension construction? | What Python's user-made list-comprehension construction is the most useful?
I have created the following two quantifiers, which I use to do different verification operations:
def every(f, L): return not (False in [f(x) for x in L])
def some(f, L): return True in [f(x) for x in L]
an optimized versions (requres Python... | [
"anyand all are part of standard Python from 2.5. There's no need to make your own versions of these. Also the official version of any and all short-circuit the evaluation if possible, giving a performance improvement. Your versions always iterate over the entire list.\nIf you want a version that accepts a predicat... | [
13,
5,
4,
2
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0001783974_list_list_comprehension_python.txt |
Q:
Python - Strip all drive letters from csv file and replace with Z:
Here is the code example. Basically output.csv needs to remove any drive letter A:-Y: and replace it with Z: I tried to do this with a list (not complete yet) but it generates the error: TypeError: expected a character buffer object
#!/usr/bin/pyth... | Python - Strip all drive letters from csv file and replace with Z: | Here is the code example. Basically output.csv needs to remove any drive letter A:-Y: and replace it with Z: I tried to do this with a list (not complete yet) but it generates the error: TypeError: expected a character buffer object
#!/usr/bin/python
import os.path
import os
import shutil
import csv
import re
# Create... | [
"It seems like the problem is in the loop at the bottom of your code. The string's replace method doesn't receive a list as its first arguments, but another string. You need to loop through your removeDrives list and call line.remove with every item in that list.\n",
"I can see you use some pythonic snippets, wit... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001783994_python.txt |
Q:
Python: For each list element apply a function across the list
Given [1,2,3,4,5], how can I do something like
1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5
I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've... | Python: For each list element apply a function across the list | Given [1,2,3,4,5], how can I do something like
1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5
I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return (1,5).
So basically I would ... | [
"You can do this using list comprehensions and min() (Python 3.0 code):\n>>> nums = [1,2,3,4,5]\n>>> [(x,y) for x in nums for y in nums]\n[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (... | [
42,
10,
3,
3,
1,
1,
0
] | [] | [] | [
"algorithm",
"list",
"list_comprehension",
"python"
] | stackoverflow_0000493367_algorithm_list_list_comprehension_python.txt |
Q:
wxPython. Create a panel with four static sized boxes
I'm trying to create a panel, with four boxes containing some data. These four boxes should have a predefined static size. What I have so far is four boxes that is overlapping to some extent.
Any ideas?
Code:
import wx
class MyFrame(wx.Frame):
def __init_... | wxPython. Create a panel with four static sized boxes | I'm trying to create a panel, with four boxes containing some data. These four boxes should have a predefined static size. What I have so far is four boxes that is overlapping to some extent.
Any ideas?
Code:
import wx
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *... | [
"I'll just answer my own question.\nThe solution is to add a wx.Sizer.SetMinSize() to each wx.StaticBoxSizer() like this.\nsb = wx.StaticBox(self.pl, -1, 'BOX0')\nsat = wx.CheckBox(self.pl, -1, 'Satellite')\ngsm = wx.CheckBox(self.pl, -1, 'GSM')\nwlan = wx.CheckBox(self.pl, -1, 'WLAN')\n\nbox = wx.StaticBoxSizer(sb... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001784026_python_wxpython.txt |
Q:
Python for web scripting
I'm just starting out with Python and have practiced so far in the IDLE interface. Now I'd like to configure Python with MAMP so I can start creating really basic webapps — using Python inside HTML, or well, vice-versa. (I'm assuming HTML is allowed in Python, just like PHP? If not, are th... | Python for web scripting | I'm just starting out with Python and have practiced so far in the IDLE interface. Now I'd like to configure Python with MAMP so I can start creating really basic webapps — using Python inside HTML, or well, vice-versa. (I'm assuming HTML is allowed in Python, just like PHP? If not, are there any modules/template engin... | [
"I think probably the easiest way for you to get started is to work with something like Django. It's a top-to-bottom web development stack which provides you with everything you need to develop and run a backend server. Things can be very simple in that world, no need to mess around with mod_python or FastCGI unl... | [
2,
2,
0
] | [] | [] | [
"fastcgi",
"html",
"python",
"template_engine",
"web_applications"
] | stackoverflow_0001781431_fastcgi_html_python_template_engine_web_applications.txt |
Q:
Designing a multi-process spider in Python
I'm working on a multi-process spider in Python. It should start scraping one page for links and work from there. Specifically, the top-level page contains a list of categories, the second-level pages events in those categories, and the final, third-level pages participan... | Designing a multi-process spider in Python | I'm working on a multi-process spider in Python. It should start scraping one page for links and work from there. Specifically, the top-level page contains a list of categories, the second-level pages events in those categories, and the final, third-level pages participants in the events. I can't predict how many categ... | [
"You might want to look into Scrapy, an asynchronous (based on Twisted) web-scraper. It looks like for your task, the XPath description for the spider would be pretty easy to define! \nGood luck!\n(If you really want to do it yourself, maybe consider having small sqlite db that keeps track of whether each page ha... | [
2,
1
] | [] | [] | [
"multithreading",
"python",
"web_crawler"
] | stackoverflow_0001784632_multithreading_python_web_crawler.txt |
Q:
Speed of many regular expressions in python
I'm writing a python program that deals with a fair amount of strings/files. My problem is that I'm going to be presented with a fairly short piece of text, and I'm going to need to search it for instances of a fairly broad range of words/phrases.
I'm thinking I'll need ... | Speed of many regular expressions in python | I'm writing a python program that deals with a fair amount of strings/files. My problem is that I'm going to be presented with a fairly short piece of text, and I'm going to need to search it for instances of a fairly broad range of words/phrases.
I'm thinking I'll need to compile regular expressions as a way of matchi... | [
"You should try to compile all your regexps into a single one using the | operator. That way, the regexp engine will do most of the optimizations for you. Use the grouping operator () to determine which regexp matched.\n",
"If speed is of the essence, you are better off running some tests before you decide how to... | [
6,
5,
3,
3,
2,
2,
0,
0,
0
] | [] | [] | [
"performance",
"python",
"regex"
] | stackoverflow_0001782586_performance_python_regex.txt |
Q:
term by term division in python (division termino a termino en python )
hello all, need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,
thanks for any response
A:
Unless I'm misunderstanding, this is where numpy ... | term by term division in python (division termino a termino en python ) | hello all, need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,
thanks for any response
| [
"Unless I'm misunderstanding, this is where numpy can be put to good use:\n>>> from numpy import *\n>>> a = array([[1,2,3],[4,5,6],[7,8,9]])\n>>> b = array([[0.5] * 3, [0.5] * 3, [0.5] * 3])\n>>> a / b\narray([[ 2., 4., 6.],\n [ 8., 10., 12.],\n [ 14., 16., 18.]])\n\nThis works for multiplicat... | [
8
] | [] | [] | [
"python"
] | stackoverflow_0001785005_python.txt |
Q:
Tuples in Dicts
Is it possible in python to add a tuple as a value in a dictionary?
And if it is,how can we add a new value, then? And how can we remove and change it?
A:
>>> a = {'tuple': (23, 32)}
>>> a
{'tuple': (23, 32)}
>>> a['tuple'] = (42, 24)
>>> a
{'tuple': (42, 24)}
>>> del a['tuple']
>>> a
{}
if you ... | Tuples in Dicts | Is it possible in python to add a tuple as a value in a dictionary?
And if it is,how can we add a new value, then? And how can we remove and change it?
| [
">>> a = {'tuple': (23, 32)}\n>>> a\n{'tuple': (23, 32)}\n>>> a['tuple'] = (42, 24)\n>>> a\n{'tuple': (42, 24)}\n>>> del a['tuple']\n>>> a\n{}\n\nif you meant to use tuples as keys you could do:\n>>> b = {(23, 32): 'tuple as key'}\n>>> b\n{(23, 32): 'tuple as key'}\n>>> b[23, 32] = 42\n>>> b\n{(23, 32): 42}\n\nGene... | [
29,
7,
2,
1
] | [] | [] | [
"dictionary",
"python",
"tuples"
] | stackoverflow_0001784973_dictionary_python_tuples.txt |
Q:
Managing *args variance in calls to functions
Have a method with the following signature:
def foo(self, bar, *uks):
return other_method(..., uks)
Normally this is called as:
instance.foo(1234, a, b, c, d)
However in some cases I need to do something like this:
p = [a, b, c, d]
instance.foo(1234, p)
At the r... | Managing *args variance in calls to functions | Have a method with the following signature:
def foo(self, bar, *uks):
return other_method(..., uks)
Normally this is called as:
instance.foo(1234, a, b, c, d)
However in some cases I need to do something like this:
p = [a, b, c, d]
instance.foo(1234, p)
At the receiving end this does not work, because other_meth... | [
"Python supports unpacking of argument lists to handle exactly this situation. The two following calls are equivalent:\nRegular call:\ninstance.foo(1234, a, b, c, d)\n\nArgument list expansion:\np = [a, b, c, d]\ninstance.foo(1234, *p)\n\n",
"p = [a, b, c, d]\ninstance.foo(1234, *p)\n\nThe *p form is the crucial... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001784971_python.txt |
Q:
Function not being called in Python, why? and how can I solve it?
I am currently working on python/django site, at the moment I have a template that looks like this
{% extends "shopbase.html" %}
{% block pageid %}products{% endblock %}
{% block right-content %}
<img src="{{MEDIA_URL}}/local/images/assets/product... | Function not being called in Python, why? and how can I solve it? | I am currently working on python/django site, at the moment I have a template that looks like this
{% extends "shopbase.html" %}
{% block pageid %}products{% endblock %}
{% block right-content %}
<img src="{{MEDIA_URL}}/local/images/assets/products.png" alt="Neal and Wolf News" class="position"/>
<div class="prod... | [
"As with many things in Django... someone has already solved this problem and come up with a clean, flexible solution for generating/storing thumbnails of different sizes etc. I'd strongly suggest looking at the sorl-thumbnail project.\nDocs here: http://thumbnail.sorl.net/docs/\nDownloads here: http://code.google.... | [
5,
2
] | [] | [] | [
"django",
"python",
"python_imaging_library"
] | stackoverflow_0001784197_django_python_python_imaging_library.txt |
Q:
Filtering mousePressEvent with installEventFilter
I am having problem filtering the "mousePressEvent" with installEventFilter
MyTestxEdit is a widget that holds QTextEdit
I want that all the events of QTextEdit will be handle by MyTestxEdit
I have used the installEventFilter
This Trick works well for events like ... | Filtering mousePressEvent with installEventFilter | I am having problem filtering the "mousePressEvent" with installEventFilter
MyTestxEdit is a widget that holds QTextEdit
I want that all the events of QTextEdit will be handle by MyTestxEdit
I have used the installEventFilter
This Trick works well for events like keyPressEvent but doesn't handle the mousePressEvent
w... | [
"Try to install the filter on the QTextEdit's viewport instead of the QTextEdit itself...\nI don't know python but something like:\nself.__qTextEdit.viewport().installEventFilter(self)\n\nI hope it helps!\nYou should do something like:\nMyClassFrm::MyClassFrm()\n{\n ...\n // Get your TextEdit from the UI here... | [
6
] | [] | [] | [
"python",
"qt"
] | stackoverflow_0001785251_python_qt.txt |
Q:
Piping Cygwin into a Python program
As a i'm new to the whole Piping thing and Python I had recently encountered a problem trying to pipe Cygwin's stdin & stdout into a python program usin Python's subprocess moudle.
for example I took a simple program:
cygwin = subprocess.Popen('PathToCygwin',shell=False,stdin=su... | Piping Cygwin into a Python program | As a i'm new to the whole Piping thing and Python I had recently encountered a problem trying to pipe Cygwin's stdin & stdout into a python program usin Python's subprocess moudle.
for example I took a simple program:
cygwin = subprocess.Popen('PathToCygwin',shell=False,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
cyg... | [
"Well, your literal code won't work. You are passing a string with the value 'PathToCygwin' and that isn't going to do anything. I assume that you are passing a better string than that, but you didn't show us what.\nI think your PathToCygwin is probably the problem. If you don't get the path right, it won't work... | [
2
] | [] | [] | [
"cygwin",
"pipe",
"python",
"subprocess"
] | stackoverflow_0001785265_cygwin_pipe_python_subprocess.txt |
Q:
Convert \r text to \n so readlines() works as intended
In Python, you can read a file and load its lines into a list by using
f = open('file.txt','r')
lines = f.readlines()
Each individual line is delimited by \n but if the contents of a line have \r then it is not treated as a new line. I need to convert all \r ... | Convert \r text to \n so readlines() works as intended | In Python, you can read a file and load its lines into a list by using
f = open('file.txt','r')
lines = f.readlines()
Each individual line is delimited by \n but if the contents of a line have \r then it is not treated as a new line. I need to convert all \r to \n and get the correct list lines.
If I do .split('\r') i... | [
"f = open('file.txt','rU')\n\nThis opens the file with Python's universal newline support and \\r is treated as an end-of-line.\n",
"If it's a concern, open in binary format and convert with this code:\nfrom __future__ import with_statement\n\nwith open(filename, \"rb\") as f:\n s = f.read().replace('\\r\\n', ... | [
43,
4
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0001785233_python_readline.txt |
Q:
Python 3 - pull down a file object from a web server over a proxy (no-auth)
I have a very simple problem and I am absolutely amazed that I haven't seen anything on this specifically. I am attempting to follow best practices for copying a file that is hosted on a webserver going through a proxy server (which does ... | Python 3 - pull down a file object from a web server over a proxy (no-auth) | I have a very simple problem and I am absolutely amazed that I haven't seen anything on this specifically. I am attempting to follow best practices for copying a file that is hosted on a webserver going through a proxy server (which does not require auth) using python3.
i have done similar things using python 2.5 but ... | [
"here is an function to retrieve a file through an http proxy:\nimport urllib.request\n\ndef retrieve( url, filename ):\n proxy = urllib.request.ProxyHandler( {'http': '127.0.0.1'} )\n opener = urllib.request.build_opener( proxy )\n remote = opener.open( url )\n local = open( filename, 'wb' )\n data ... | [
1
] | [] | [] | [
"http",
"proxy",
"python",
"tunnel"
] | stackoverflow_0001784483_http_proxy_python_tunnel.txt |
Q:
Where in a virtualenv does the custom code go?
What sort of directory structure should one follow when using virtualenv? For instance, if I were building a WSGI application and created a virtualenv called foobar I would start with a directory structure like:
/foobar
/bin
{activate, activate.py, easy_install,... | Where in a virtualenv does the custom code go? | What sort of directory structure should one follow when using virtualenv? For instance, if I were building a WSGI application and created a virtualenv called foobar I would start with a directory structure like:
/foobar
/bin
{activate, activate.py, easy_install, python}
/include
{python2.6/...}
/lib
{... | [
"virtualenv provides a python interpreter instance, not an application instance. You wouldn't normally create your application files within the directories containing a system's default Python, likewise there's no requirement to locate your application within a virtualenv directory. \nFor example, you might have ... | [
98,
63,
32,
3
] | [] | [] | [
"project",
"python",
"virtualenv"
] | stackoverflow_0001783146_project_python_virtualenv.txt |
Q:
Nested Lambdas in Python
I'm a beginning python programmer, and I'd like someone to clarify the following behavior.
I have the following code:
env = lambda id: -1
def add(id, val, myenv):
return lambda x: val if x == id else myenv(id)
test_env = add("a", 1, env)
test_env_2 = add("b", 2, test_env)
When I loo... | Nested Lambdas in Python | I'm a beginning python programmer, and I'd like someone to clarify the following behavior.
I have the following code:
env = lambda id: -1
def add(id, val, myenv):
return lambda x: val if x == id else myenv(id)
test_env = add("a", 1, env)
test_env_2 = add("b", 2, test_env)
When I look up "a" in test_env, it funct... | [
"I think you just confused myenv(id) with myenv(x). Change it and you'll get the desired output.\n"
] | [
5
] | [] | [] | [
"closures",
"functional_programming",
"lambda",
"nested",
"python"
] | stackoverflow_0001785826_closures_functional_programming_lambda_nested_python.txt |
Q:
Efficient way of calling set of functions in Python
I have a set of functions:
functions=set(...)
All the functions need one parameter x.
What is the most efficient way in python of doing something similar to:
for function in functions:
function(x)
A:
The code you give,
for function in functions:
functio... | Efficient way of calling set of functions in Python | I have a set of functions:
functions=set(...)
All the functions need one parameter x.
What is the most efficient way in python of doing something similar to:
for function in functions:
function(x)
| [
"The code you give,\nfor function in functions:\n function(x)\n\n...does not appear to do anything with the result of calling function(x). If that is indeed so, meaning that these functions are called for their side-effects, then there is no more pythonic alternative. Just leave your code as it is.† The point to... | [
7,
1,
0,
0
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0001785867_iteration_python.txt |
Q:
Creation of PyTuple in C++ module crashes
Having some trouble with this code. Trying to return a tuple of tuples (coordinates) from a C++ module Im writing. It looks right to me, the dirty list contains two Coords so len is 2, the x and y values of the items in the list are 0,0 and 0,1 respectively. First time Im ... | Creation of PyTuple in C++ module crashes | Having some trouble with this code. Trying to return a tuple of tuples (coordinates) from a C++ module Im writing. It looks right to me, the dirty list contains two Coords so len is 2, the x and y values of the items in the list are 0,0 and 0,1 respectively. First time Im attempting this so I might very well have misun... | [
"The arguments to PyTuple_Pack, after the first one, must be PyObject pointers.\nYou might want instead\nPy_BuildValue(\"(ii)\", (*i).x, (*i).y)\n\n...assuming the coordinates are actually of type int.\n"
] | [
1
] | [] | [] | [
"python",
"python_c_api"
] | stackoverflow_0001786070_python_python_c_api.txt |
Q:
How to install EasyGUI on Mac OS X 10.6 (Snow Leopard)?
I would like to install EasyGUI on Mac OS X 10.6, but am running into trouble. Has anyone successfully done this? If so, what explicit set of steps did you follow?
Thank you.
A:
It's hard to know what running into trouble means but, nonetheless, something l... | How to install EasyGUI on Mac OS X 10.6 (Snow Leopard)? | I would like to install EasyGUI on Mac OS X 10.6, but am running into trouble. Has anyone successfully done this? If so, what explicit set of steps did you follow?
Thank you.
| [
"It's hard to know what running into trouble means but, nonetheless, something like this seems to work on 10.6:\nmkdir test_easygui\ncd test_easygui\ncurl http://easygui.sourceforge.net/current_version/easygui_v0.93.tar.gz | tar xz\n/usr/bin/python2.6 easygui.py\n\nEDIT: \nUnfortunately, the EasyGui download does n... | [
2
] | [] | [] | [
"easygui",
"macos",
"python"
] | stackoverflow_0001785987_easygui_macos_python.txt |
Q:
How do I copy wsgi.input if I want to process POST data more than once?
In WSGI, post data is consumed by reading the file-like object environ['wsgi.input']. If a second element in the stack also wants to read post data it may hang the program by reading when there's nothing more to read.
How should I copy the POS... | How do I copy wsgi.input if I want to process POST data more than once? | In WSGI, post data is consumed by reading the file-like object environ['wsgi.input']. If a second element in the stack also wants to read post data it may hang the program by reading when there's nothing more to read.
How should I copy the POST data so it can be processed multiple times?
| [
"You could try putting a file-like replica of the stream back in the environment:\nfrom cStringIO import StringIO\n\nlength = int(environ.get('CONTENT_LENGTH', '0'))\nbody = StringIO(environ['wsgi.input'].read(length))\nenviron['wsgi.input'] = body\n\nNeeding to do this is a bit of a smell, though. Ideally only one... | [
12,
8,
1
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0001783383_python_wsgi.txt |
Q:
GAE - How to live with no joins?
Example Problem:
Entities:
User contains name and a list of friends (User references)
Blog Post contains title, content, date and Writer (User)
Requirement:
I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like th... | GAE - How to live with no joins? | Example Problem:
Entities:
User contains name and a list of friends (User references)
Blog Post contains title, content, date and Writer (User)
Requirement:
I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep paging back through ... | [
"If you look at how the SQL solution you provided will be executed, it will go basically like this:\n\nFetch a list of friends for the current user\nFor each user in the list, start an index scan over recent posts\nMerge-join all the scans from step 2, stopping when you've retrieved enough entries\n\nYou can carry ... | [
13,
7,
1,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"join",
"python"
] | stackoverflow_0000445827_google_app_engine_google_cloud_datastore_join_python.txt |
Q:
Python Vs Ruby On Rails : on Size
I am planning to do a small web application that will be distributed as a single installable. I have plans to develop this application in either Python/Django or Ruby On Rails. (I am a Java/C++ programmer, hence both these languages are new to me).
My main concern is about the si... | Python Vs Ruby On Rails : on Size | I am planning to do a small web application that will be distributed as a single installable. I have plans to develop this application in either Python/Django or Ruby On Rails. (I am a Java/C++ programmer, hence both these languages are new to me).
My main concern is about the size and simplicity of final installable ... | [
"I personally prefer Python/django. Size is small given u have necessary things installed. \n",
"With disk space at the current price, size shouldn't matter. Give both a try and figure out which will be easier for you to learn and maintain. Despite the fact that people believe that when you know one language, you... | [
4,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"django",
"python",
"ruby_on_rails"
] | stackoverflow_0001783431_django_python_ruby_on_rails.txt |
Q:
Parsing XML in Python using ElementTree example
I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:
<timeSeriesResponse>
<queryIn... | Parsing XML in Python using ElementTree example | I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:
<timeSeriesResponse>
<queryInfo>
<locationParam>01474500</locationParam>
... | [
"So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted: \nimport elementtree.ElementTree as ET\n\ntree = ET.parse(\"test.xml\")\ndoc = tree.getroot()\nthingy = doc.find('timeSeries')\n\nprint thingy.attrib\n\nand got the following back:\n{'name': 'NWIS Time Series In... | [
49,
22
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0001786476_elementtree_python_xml.txt |
Q:
Why doesn't this division work in Python?
Consider:
>>> numerator = 29
>>> denom = 1009
>>> print str(float(numerator/denom))
0.0
How do I make it return a decimal?
A:
Until version 3, Python's division operator, /, behaved like C's division operator when presented with two integer arguments: it returns an inte... | Why doesn't this division work in Python? | Consider:
>>> numerator = 29
>>> denom = 1009
>>> print str(float(numerator/denom))
0.0
How do I make it return a decimal?
| [
"\nUntil version 3, Python's division operator, /, behaved like C's division operator when presented with two integer arguments: it returns an integer result that's truncated down when there would be a fractional part. See: PEP 238\n\n>>> n = 29\n>>> d = 1009\n>>> print str(float(n)/d)\n0.0287413280476\n\nIn Python... | [
30,
8,
1,
0
] | [] | [] | [
"numbers",
"python"
] | stackoverflow_0001787249_numbers_python.txt |
Q:
Python - Simple algorithmic task on lists (standard question for a job-interview)
There are 2 input lists L and M, for example:
L = ['a', 'ab', 'bba']
M = ['baa', 'aa', 'bb']
How to obtain 2 non-empty output lists U and V such that:
''.join(U) == ''.join(V)) is True,
and every element of U is in L, and eve... | Python - Simple algorithmic task on lists (standard question for a job-interview) | There are 2 input lists L and M, for example:
L = ['a', 'ab', 'bba']
M = ['baa', 'aa', 'bb']
How to obtain 2 non-empty output lists U and V such that:
''.join(U) == ''.join(V)) is True,
and every element of U is in L, and every element of V is in M?
For example, one possible solution for the two input lists abo... | [
"What are you looking for -- all (the countable infinity of) possible solutions? The \"shortest\" (by some measure) non-empty solution, or the set of equal-shortest ones, or...?\nBecause, if any solution will do, setting U and V both to [] meets all the stated conditions, and is O(1) to boot;-).\nEdit: ok, so, jok... | [
9,
4,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0001786504_algorithm_python.txt |
Q:
How to execute Javascript from Python on Windows?
how can I execute Javascript from Python on Windows?
I want to get python-spidermonkey functionality. Just like this:
>>> class Foo:
... def hello(self):
... print "Hello, Javascript world!"
>>> cx.bind_class(Foo, bind_constructor=True)
>>> cx.eval_script("va... | How to execute Javascript from Python on Windows? | how can I execute Javascript from Python on Windows?
I want to get python-spidermonkey functionality. Just like this:
>>> class Foo:
... def hello(self):
... print "Hello, Javascript world!"
>>> cx.bind_class(Foo, bind_constructor=True)
>>> cx.eval_script("var f = new Foo(); f.hello();")
Hello, Javascript world!
... | [
"How about pyv8: http://code.google.com/p/pyv8/\n",
"You could call SpiderMonkey.\n"
] | [
4,
1
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0001764674_javascript_python.txt |
Q:
How different are the semantics between Python and JavaScript?
Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you... | How different are the semantics between Python and JavaScript? | Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports fl... | [
"\nClassical inheritance in Python, Prototypal inheritance in ECMAScript\nECMAScript is a braces and semicolons language while Python is white-space and indent/block based\nNo var keyword in Python, implicit globals in ECMAScript, both are lexically scoped\nClosures in Python 2.5 and lower ( re: Alex Martelli's com... | [
40,
6,
5,
5,
2,
1
] | [] | [] | [
"javascript",
"python",
"semantics"
] | stackoverflow_0001786522_javascript_python_semantics.txt |
Q:
C lib with Python bindings where both want to render
I'm sketching on some fluid dynamics in Python. After a while, I'm looking for a bit more speed, so I rewrote the actual logic in C and put up some Python bindings (using SWIG).
My problem now is that I don't how to render it in a good way. The logic is run pixe... | C lib with Python bindings where both want to render | I'm sketching on some fluid dynamics in Python. After a while, I'm looking for a bit more speed, so I rewrote the actual logic in C and put up some Python bindings (using SWIG).
My problem now is that I don't how to render it in a good way. The logic is run pixel by pixel so pixels are what I want to track and render.
... | [
"Have you tried something like the following to get SDL_Surface* from python object?\nPySurfaceObject *obj;\nSDL_Surface *surf;\nif (!PyArg_ParseTuple(args, 'O!', &PySurface_Type, &obj) {\n return NULL; # or other action for error\n}\nsurf = PySurface_AsSurface(obj);\n\n"
] | [
0
] | [] | [] | [
"c",
"pygame",
"python",
"sdl",
"swig"
] | stackoverflow_0001785604_c_pygame_python_sdl_swig.txt |
Q:
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty
Say I have the following model:
class Schedule(db.Model):
tripCode = db.StringProperty(required=True)
station = db.ReferenceProperty(Station, required=True)
arrivalTime = db.TimeProperty(required=True)
departure... | Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty | Say I have the following model:
class Schedule(db.Model):
tripCode = db.StringProperty(required=True)
station = db.ReferenceProperty(Station, required=True)
arrivalTime = db.TimeProperty(required=True)
departureTime = db.TimeProperty(required=True)
And let's say I have a Station object stored in th... | [
"You shouldn't be inserting user data into a GQL string using string substitution. GQL supports parameter substitution, so you can do this:\ndb.GqlQuery(\"SELECT * FROM Schedule WHERE station = $1\", foo.key())\n\nor, using the Query interface:\nSchedule.all().filter(\"station =\", foo.key())\n\n",
"An even easie... | [
10,
7
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0000852055_google_app_engine_gql_python.txt |
Q:
Catching update errors on MySQLdb
I have a function that updates a MySQL table from a CSV file. The MySQL table contains the client account number -- this is what I use to compare with the CSV file. At some point, some of the queries will fail because the account number being compared from the CSV file has not bee... | Catching update errors on MySQLdb | I have a function that updates a MySQL table from a CSV file. The MySQL table contains the client account number -- this is what I use to compare with the CSV file. At some point, some of the queries will fail because the account number being compared from the CSV file has not been added yet.
How do I get the records f... | [
"An update query returns the number of rows affected.\nChecking the Cursor.rowcount after you made am execute will give that number. If it is not 1, that that update row failed.\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001788000_mysql_python.txt |
Q:
Using contexts in rdflib
I am having trouble finding a clear, sensible example of usage of context with rdflib.
ConjunctiveGraph does not accept contexts, and Graph is deprecated. How am I supposed to create and operate on different contexts within the same global ConjunctiveGraph ?
A:
Yes. This is the code
impo... | Using contexts in rdflib | I am having trouble finding a clear, sensible example of usage of context with rdflib.
ConjunctiveGraph does not accept contexts, and Graph is deprecated. How am I supposed to create and operate on different contexts within the same global ConjunctiveGraph ?
| [
"Yes. This is the code\nimport rdflib\nfrom rdflib.Graph import Graph\n\nconj=rdflib.ConjunctiveGraph()\n\nNS=rdflib.Namespace(\"http://example.com/#\")\nNS_CTX=rdflib.Namespace(\"http://example.com/context/#\")\n\nalice=NS.alice\nbob=NS.bob\ncharlie=NS.charlie\n\npizza=NS.pizza\nmeat=NS.meat\nchocolate=NS.chocolat... | [
14
] | [] | [] | [
"python",
"rdf",
"rdflib"
] | stackoverflow_0001788063_python_rdf_rdflib.txt |
Q:
Python and .NET integration
I'm currently looking at python because I really like the text parsing capabilities and the nltk library, but traditionally I am a .Net/C# programmer. I don't think IronPython is an integration point for me because I am using NLTK and presumably would need a port of that library to the... | Python and .NET integration | I'm currently looking at python because I really like the text parsing capabilities and the nltk library, but traditionally I am a .Net/C# programmer. I don't think IronPython is an integration point for me because I am using NLTK and presumably would need a port of that library to the CLR. I've looked a little at Py... | [
"NLTK is pure-python and thus can be made to run on IronPython easily. A search turned up this ticket - all one has to do is install a couple of extra Python libraries that don't come by default with IronPython.\nThis is probably the easiest way for you to integrate. Otherwise, you'll have to either run Python as a... | [
9,
6,
2
] | [] | [] | [
".net",
"nlp",
"nltk",
"python",
"python.net"
] | stackoverflow_0001787755_.net_nlp_nltk_python_python.net.txt |
Q:
How to read data from file and display in QEditText box in QT
i would like to read a line of data from text file and display that data in Text Edit box
A:
It's quite simple, actually:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
FILENAME = 'textedit_example.py'
class Form(QDialog):
def ... | How to read data from file and display in QEditText box in QT | i would like to read a line of data from text file and display that data in Text Edit box
| [
"It's quite simple, actually:\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\n\nFILENAME = 'textedit_example.py'\n\n\nclass Form(QDialog):\n def __init__(self, parent=None):\n super(Form, self).__init__(parent)\n self.edit = QTextEdit()\n layout = QVBoxLayout()\n ... | [
2,
0
] | [] | [] | [
"c++",
"linux",
"python",
"qt4",
"ubuntu"
] | stackoverflow_0001788062_c++_linux_python_qt4_ubuntu.txt |
Q:
Django: Serving admin media files
I am trying to serve static files from another domain (sub domain of current domain).
To serve all media files I used this settings:
MEDIA_URL =
'http://media.bud-inform.co.ua/'
So when in template I used
{{ MEDIA_URL }}
it was replace with the setting above. Now I am tryin... | Django: Serving admin media files | I am trying to serve static files from another domain (sub domain of current domain).
To serve all media files I used this settings:
MEDIA_URL =
'http://media.bud-inform.co.ua/'
So when in template I used
{{ MEDIA_URL }}
it was replace with the setting above. Now I am trying to serve admin media files from the s... | [
"MEDIA_URL and ADMIN_MEDIA_PREFIX are two different things. One is the location of your media files, while the other is the location of the django admin system's media files.\nYou have to make sure that the ADMIN_MEDIA_PREFIX points to somewhere where you're actually serving the admin media. Django doesn't handle t... | [
2
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0001788274_django_django_admin_python.txt |
Q:
How to determine if data is valid tar file without a file?
My upload form expects a tar file and I want to check whether the uploaded data is valid. The tarfile module supports is_tarfile(), but expects a filename - I don't want to waste resources writing the file to disk just to check if it is valid.
Is there a ... | How to determine if data is valid tar file without a file? | My upload form expects a tar file and I want to check whether the uploaded data is valid. The tarfile module supports is_tarfile(), but expects a filename - I don't want to waste resources writing the file to disk just to check if it is valid.
Is there a way to check the data is a valid tar file without writing to dis... | [
"The tar file format is here on Wikipedia.\nI suspect your best bet would be to check that the header checksum for the first file is valid. You may also want to check the file name for sanity but that may not be reliable, depending on the file names that have been stored in there.\nDuplicating the relevant informat... | [
5,
3,
3,
3
] | [] | [] | [
"python",
"tar",
"tarfile"
] | stackoverflow_0001788236_python_tar_tarfile.txt |
Q:
How do I remove something form a list, plus string matching?
[(',', 52),
('news', 15),
('.', 11),
('bbc', 8),
('and', 8),
('the', 8),
(':', 6),
('music', 5),
('-', 5),
('blog', 4),
('world', 4),
('asia', 4),
('international', 4),
('on', 4),
('itunes', 4),
('online', 4),
('digital', 3)]
Suppose I h... | How do I remove something form a list, plus string matching? | [(',', 52),
('news', 15),
('.', 11),
('bbc', 8),
('and', 8),
('the', 8),
(':', 6),
('music', 5),
('-', 5),
('blog', 4),
('world', 4),
('asia', 4),
('international', 4),
('on', 4),
('itunes', 4),
('online', 4),
('digital', 3)]
Suppose I have this list, with tuples inside.
How do I go through the list ... | [
"the_list = [(a, b) for a, b in the_list if a.isalpha()]\n\n",
"Easiest should be a list comprehension with a regular expression:\nimport re\n\nlst = [...]\nlst = [t for t in lst if re.search(r'\\w', t[0])]\n\n",
"@OP, just go through the list items one by one, and check the first element of each item. This is ... | [
10,
3,
1,
0,
0
] | [] | [] | [
"list",
"python",
"regex"
] | stackoverflow_0001788710_list_python_regex.txt |
Q:
python inheritance and __init__ functions
I came across the folloqing type of code when looking for some pyQt examples :
class DisplayPage(QWizardPage):
def __init__(self, *args):
apply(QWizardPage.__init__, (self, ) + args)
What does *args mean ?
What is the purpose of using apply for this type of co... | python inheritance and __init__ functions | I came across the folloqing type of code when looking for some pyQt examples :
class DisplayPage(QWizardPage):
def __init__(self, *args):
apply(QWizardPage.__init__, (self, ) + args)
What does *args mean ?
What is the purpose of using apply for this type of code ?
| [
"*args means that __init__ takes any number of positional arguments, all of which will be stored in the list args. For more on that, see What does *args and **kwargs mean?\nThis piece of code uses the deprecated apply function. Nowadays you would write this in one of three ways:\n QWizardPage.__init__(self, *args)\... | [
10,
3,
1,
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0001788842_pyqt_python.txt |
Q:
Redirecting CGI error output from STDERR to a file (python AND perl)
I'm moving a website to Hostmonster and asked where the server log is located so I can automatically scan it for CGI errors. I was told, "We're sorry, but we do not have cgi errors go to any files that you have access to."
For organizational reas... | Redirecting CGI error output from STDERR to a file (python AND perl) | I'm moving a website to Hostmonster and asked where the server log is located so I can automatically scan it for CGI errors. I was told, "We're sorry, but we do not have cgi errors go to any files that you have access to."
For organizational reasons I'm stuck with Hostmonster and this awful policy, so as a workaround I... | [
"For Perl, just close and re-open STDERR to point to a file of your choice.\nclose STDERR;\nopen STDERR, '>>', '/path/to/your/log.txt' \n or die \"Couldn't redirect STDERR: $!\";\n\nwarn \"this will go to log.txt\";\n\nAlternatively, you could look into a filehandle multiplexer like File::Tee.\n",
"Python: cgitb... | [
4,
3,
3,
2,
2,
0,
0
] | [] | [] | [
"cgi",
"hostmonster",
"perl",
"python",
"stderr"
] | stackoverflow_0001781436_cgi_hostmonster_perl_python_stderr.txt |
Q:
appengine: how to use validator in Class:Property?
described in http://code.google.com/intl/en/appengine/docs/python/datastore/propertyclass.html#Property
but there is no example code.
i code sth like:
class Model(db.Model):
email = db.EmailProperty(validator=clean_email)
def clean_email(self,value):
if .... | appengine: how to use validator in Class:Property? | described in http://code.google.com/intl/en/appengine/docs/python/datastore/propertyclass.html#Property
but there is no example code.
i code sth like:
class Model(db.Model):
email = db.EmailProperty(validator=clean_email)
def clean_email(self,value):
if ...
| [
"class Model(db.Model):\n\n def clean_email(value):\n if ...\n\n email = db.EmailProperty(validator=clean_email)\n\nuse a argument. and the argument itself is the value of email in this case.\n",
"You need to either define the method before the property, as joetsuihk demonstrates, or define it as a function,... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"validation"
] | stackoverflow_0001788119_google_app_engine_python_validation.txt |
Q:
How to get the next token (int, float or string) from a file in Python?
Is there some way to just get the next token from a file in Python, as for example the Scanner class does in Java?
File file = new File("something");
Scanner myinput = new Scanner(file);
double a = myinput.nextDouble();
String s = myinput.next... | How to get the next token (int, float or string) from a file in Python? | Is there some way to just get the next token from a file in Python, as for example the Scanner class does in Java?
File file = new File("something");
Scanner myinput = new Scanner(file);
double a = myinput.nextDouble();
String s = myinput.next();
I'd like to ignore whitespaces, tabs, newlines and just get the next int... | [
"Check out the shlex-module in the standard library: http://docs.python.org/library/shlex.html\nimport shlex\nimport StringIO # use in place of files\n\nlist(shlex.shlex(StringIO.StringIO('Some tokens. 123, 45.67 \"A string with whitespace\"')))\n\nIt does not handle floats the way you seem to want. Maybe you can e... | [
10,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001789114_python.txt |
Q:
I am trying to determine if a string is a Question. How can I analyze the "?" symbol (python)
This is a question:
"Where is the car?"
This is NOT a question:
"Check this out: http://domain.com/?q=test"
How do I write a function to analyze a string so that we know for sure it is a question and not part of a URL?... | I am trying to determine if a string is a Question. How can I analyze the "?" symbol (python) | This is a question:
"Where is the car?"
This is NOT a question:
"Check this out: http://domain.com/?q=test"
How do I write a function to analyze a string so that we know for sure it is a question and not part of a URL?
| [
"This regex finds question marks following a word character, and followed by either whitespace or the end of the string/line. Not perfect, but should catch most cases...\n\\w\\?[$\\s]\n\nEdit (lack of caffeine strikes...):\nThat should have been:\n\\w\\?(\\s|$)\n\nIn the original, $ is interpreted as a literal char... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"string",
"url"
] | stackoverflow_0001789009_python_regex_string_url.txt |
Q:
Just Curious about Python+Numpy to Realtime Gesture Recognition
i 'm just finish labs meeting with my advisor, previous code is written in matlab and it run offline mode not realtime mode, so i decide to convert to python+numpy (in offline version) but after labs meeting, my advisor raise issue about speed of real... | Just Curious about Python+Numpy to Realtime Gesture Recognition | i 'm just finish labs meeting with my advisor, previous code is written in matlab and it run offline mode not realtime mode, so i decide to convert to python+numpy (in offline version) but after labs meeting, my advisor raise issue about speed of realtime recognition, so i have doubt about speed of python+numpy to do t... | [
"NumPy is very fast if you follow some basic rules. You should avoid Python loops, using the operators provided by NumPy instead whenever you can. This and this should be a good starting points.\nAfter reading through that, why don't you write some simple code in both Matlab and NumPy and compare the performance? I... | [
3,
1,
0
] | [] | [] | [
"c",
"gesture_recognition",
"numpy",
"python"
] | stackoverflow_0001727950_c_gesture_recognition_numpy_python.txt |
Q:
Where does Python's pydoc help function get its content?
I have a lot of callable objects and they all have the __doc__ string correctly filled out, but running help on them produces the help for their class instead of help based on __doc__.
I want to change it so that running help on them produces customized help... | Where does Python's pydoc help function get its content? | I have a lot of callable objects and they all have the __doc__ string correctly filled out, but running help on them produces the help for their class instead of help based on __doc__.
I want to change it so that running help on them produces customized help that looks essentially like what I would get if they were act... | [
"The help function (implemented in the pydoc module) isn't prepared to find per-instance docstrings. I took a quick look through the module to see if there was a way to provide explicit help, but there doesn't seem to be. It uses the inspect module to determine what kind of thing it is, and your myFunc doesn't lo... | [
5,
2
] | [] | [] | [
"introspection",
"pydoc",
"python"
] | stackoverflow_0001787056_introspection_pydoc_python.txt |
Q:
Reference to Part of List - Python
If I have a list in python, how can I create a reference to part of the list? For example:
myList = ["*", "*", "*", "*", "*", "*", "*", "*", "*"]
listPart = myList[0:7:3] #This makes a new list, which is not what I want
myList[0] = "1"
listPart[0]
"1"
Is this possible and i... | Reference to Part of List - Python | If I have a list in python, how can I create a reference to part of the list? For example:
myList = ["*", "*", "*", "*", "*", "*", "*", "*", "*"]
listPart = myList[0:7:3] #This makes a new list, which is not what I want
myList[0] = "1"
listPart[0]
"1"
Is this possible and if so how would I code it?
Cheers,
Joe
| [
"You can write a list view type. Here is something I have written as experiment, it is by no means guaranteed to be complete or bug-free\nclass listview (object):\n def __init__(self, data, start, end):\n self.data = data\n self.start, self.end = start, end\n def __repr__(self):\n return ... | [
5,
4,
3,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001788608_list_python.txt |
Q:
How to parse *.py file with python?
I'd like to parse Python source in order to try making a basic source code converter from Python to Go.
What module should I use?
Should I proceed or not?
If I should proceed, how?
A:
Have a look at the language services packages, particularly the ast.
My guess is that if you... | How to parse *.py file with python? | I'd like to parse Python source in order to try making a basic source code converter from Python to Go.
What module should I use?
Should I proceed or not?
If I should proceed, how?
| [
"Have a look at the language services packages, particularly the ast.\nMy guess is that if you don't already have a solid grasp of both parsing as well as code generation techniques, this is going to be a difficult project to undertake.\ngood luck!\n",
"The Boo Solution\nAre you trying to make a python-like langu... | [
14,
3,
3,
2
] | [] | [] | [
"code_conversion",
"go",
"python"
] | stackoverflow_0001789301_code_conversion_go_python.txt |
Q:
Adding even values to new list Python
If I have a list and I want to create a list with only even values of the original list, how would I do that?
I originally have:
list1 = [1,2,3,4,5]
list2 = []
for v in list1:
if v % 2 == 0:
list2 += v
print list2
A:
List comprehension is the way to go:
list1 = ... | Adding even values to new list Python | If I have a list and I want to create a list with only even values of the original list, how would I do that?
I originally have:
list1 = [1,2,3,4,5]
list2 = []
for v in list1:
if v % 2 == 0:
list2 += v
print list2
| [
"List comprehension is the way to go:\nlist1 = [1,2,3,4,5]\nlist2 = [i for i in list1 if i%2 == 0]\nprint list2 # => [2, 4]\n\n",
"If you want to extend an existing list2 (not necessarily initially empty):\nlist2.extend(v for v in list1 if v % 2 == 0)\n\nIf there's no \"initial value\" for list2, and you just wan... | [
7,
3,
3,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001780904_list_python.txt |
Q:
Python Webdriver doesn't wait until the page is downloaded in Firefox when used with proxy
when I set the Firefox proxy with python webdriver, it doesn't wait until the page is fully downloaded, this doesn't happen when I don't set one. How can I change this behavior? Or how can I check that the page download is o... | Python Webdriver doesn't wait until the page is downloaded in Firefox when used with proxy | when I set the Firefox proxy with python webdriver, it doesn't wait until the page is fully downloaded, this doesn't happen when I don't set one. How can I change this behavior? Or how can I check that the page download is over?
| [
"The simplest thing to do is to poll the page looking for an element you know will be present once the download is complete. The Java webdriver bindings offer a \"Wait\" class for just this purpose, though there isn't (yet) an analogue for this in the python bindings.\n"
] | [
1
] | [] | [] | [
"firefox",
"proxy",
"python",
"webdriver"
] | stackoverflow_0001785607_firefox_proxy_python_webdriver.txt |
Q:
Facebook Connect help
According to the Facebook API documentation, most of the work is handled through javascript.
That means that all the processing is done, and then the front end checks if the user is connected to Facebook/authorized. right?
My question is:
Suppose a user goes to my site for the first time eve... | Facebook Connect help | According to the Facebook API documentation, most of the work is handled through javascript.
That means that all the processing is done, and then the front end checks if the user is connected to Facebook/authorized. right?
My question is:
Suppose a user goes to my site for the first time ever.
He clicks on "facebook c... | [
"Facebook Connect uses a clever (or insane, depending on your point of view) hack to achieve cross-site communication between your site and Facebook's authentication system from within the browser.\nThe way it works is as follows:\n\nYour site includes a very simple static HTML file, known as the cross-domain commu... | [
6,
0,
0
] | [] | [] | [
"facebook",
"javascript",
"python"
] | stackoverflow_0001580504_facebook_javascript_python.txt |
Q:
Creating a tree from a list of tuples
I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that
(id, parent_id, value)
So that it is a representation of the tree as a flattend list of list of tree nodes.
For example the input
(1, None, '...')
(3, 2', '...')
(2, ... | Creating a tree from a list of tuples | I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that
(id, parent_id, value)
So that it is a representation of the tree as a flattend list of list of tree nodes.
For example the input
(1, None, '...')
(3, 2', '...')
(2, 1, '...')
(4, 1, '...')
(5, 2, '...')
(6, N... | [
"Python sorts tuples from left to right, so if you arrange your tuples so the first sort key is the first item and so forth, it'll be reasonably efficient.\nThe mapping from a list of tuples to a tree is not clear from what you're describing. Please draw it out, or explain it more thoroughly. For example, your ex... | [
4,
1,
0
] | [] | [] | [
"python",
"sorting",
"tree"
] | stackoverflow_0000783217_python_sorting_tree.txt |
Q:
Adding Version Control / Numbering (?) to Python Project
With my Java projects at present, I have full version control by declaring it as a Maven project. However I now have a Python project that I'm about to tag 0.2.0 which has no version control. Therefore should I come accross this code at a later date, I won't... | Adding Version Control / Numbering (?) to Python Project | With my Java projects at present, I have full version control by declaring it as a Maven project. However I now have a Python project that I'm about to tag 0.2.0 which has no version control. Therefore should I come accross this code at a later date, I won't no what version it is.
How do I add version control to a Pyt... | [
"First, maven is a build tool and has nothing to do with version control. You don't need a build tool with Python -- there's nothing to \"build\". \nSome folks like to create .egg files for distribution. It's as close to a \"build\" as you get with Python. This is a simple setup.py file.\nYou can use SVN keywor... | [
5,
3,
2
] | [] | [] | [
"python",
"version_control"
] | stackoverflow_0001790235_python_version_control.txt |
Q:
Small "embeddable" database that can also be synced over the network?
I am looking for a small database that can be "embedded" into my Python application without running a separate server, as one can do with SQLite or Metakit. I don't need an SQL database, in fact storing free-form data like Python dictionaries or... | Small "embeddable" database that can also be synced over the network? | I am looking for a small database that can be "embedded" into my Python application without running a separate server, as one can do with SQLite or Metakit. I don't need an SQL database, in fact storing free-form data like Python dictionaries or JSON is preferable.
The other requirement is that to be able to run an in... | [
"From what you describe, it sounds like you could get by using pickle and FTP.\n",
"If you don't need an SQL database, what's wrong with CouchDB? You can spawn a local process to serve the DB, and you could easily write a server wrapper to allow only access from your app. I'm not sure about the access story, but ... | [
2,
1,
1,
1,
1,
0
] | [] | [] | [
"couchdb",
"database",
"python",
"sqlite"
] | stackoverflow_0001779287_couchdb_database_python_sqlite.txt |
Q:
Running average in Python
Is there a pythonic way to build up a list that contains a running average of some function?
After reading a fun little piece about Martians, black boxes, and the Cauchy distribution, I thought it would be fun to calculate a running average of the Cauchy distribution myself:
import math
... | Running average in Python | Is there a pythonic way to build up a list that contains a running average of some function?
After reading a fun little piece about Martians, black boxes, and the Cauchy distribution, I thought it would be fun to calculate a running average of the Cauchy distribution myself:
import math
import random
def cauchy(locat... | [
"You could write a generator:\ndef running_average():\n sum = 0\n count = 0\n while True:\n sum += cauchy(3,1)\n count += 1\n yield sum/count\n\nOr, given a generator for Cauchy numbers and a utility function for a running sum generator, you can have a neat generator expression:\n# Cauchy numbers genera... | [
15,
6,
4
] | [] | [] | [
"list_comprehension",
"moving_average",
"python"
] | stackoverflow_0001790550_list_comprehension_moving_average_python.txt |
Q:
Compact Class DSL in python
I want to have compact class based python DSLs in the following form:
class MyClass(Static):
z = 3
def _init_(cls, x=0):
cls._x = x
def set_x(cls, x):
cls._x = x
def print_x_plus_z(cls):
print cls._x + cls.z
@property
def x(cls):
... | Compact Class DSL in python | I want to have compact class based python DSLs in the following form:
class MyClass(Static):
z = 3
def _init_(cls, x=0):
cls._x = x
def set_x(cls, x):
cls._x = x
def print_x_plus_z(cls):
print cls._x + cls.z
@property
def x(cls):
return cls._x
class MyOtherCla... | [
"To give a class (as opposed to its instances) a property, you need to have that property object as an attribute of the class's metaclass (so you'll probably need to make a custom metaclass to avoid inflicting that property upon other classes with the same metaclass). Similarly for special methods such as __init__ ... | [
2
] | [] | [] | [
"class",
"dsl",
"properties",
"python",
"singleton"
] | stackoverflow_0001790856_class_dsl_properties_python_singleton.txt |
Q:
Django, is possible to run two different versions?
I have a server on which I have two sites built with Django and Python, one site is major site is build with an older version of django, the other with the newer release, I have upgraded to the new release and major aspects of my other site have broken, is it pos... | Django, is possible to run two different versions? | I have a server on which I have two sites built with Django and Python, one site is major site is build with an older version of django, the other with the newer release, I have upgraded to the new release and major aspects of my other site have broken, is it possible to tell the site to use a different version in say... | [
"When you have more than one site on a server, you should consider using something like virtualenv.\nUsing that you can setup different virtual environments and place site specific packages and such in there, instead of messing up your site-packages folder. It also makes development a lot easier as you easily can s... | [
7,
5,
1,
0,
0
] | [] | [] | [
"django",
"hosting",
"python",
"shared_hosting"
] | stackoverflow_0001789285_django_hosting_python_shared_hosting.txt |
Q:
Python: Invalid Syntax with test data using Pyparser
Using pyparser, I am trying to create a very simple parser for the S-Expression language. I have written a very small grammar.
Here is my code:
from pyparsing import *
alphaword = Word(alphas)
integer = Word(nums)
sexp = Forward()
LPAREN = Suppress("(") ... | Python: Invalid Syntax with test data using Pyparser | Using pyparser, I am trying to create a very simple parser for the S-Expression language. I have written a very small grammar.
Here is my code:
from pyparsing import *
alphaword = Word(alphas)
integer = Word(nums)
sexp = Forward()
LPAREN = Suppress("(")
RPAREN = Suppress(")")
sexp << ( alphaword | integer |... | [
"parentheses on a previous line are not closed.\nsexp << ( alphaword | integer | ( LPAREN + ZeroOrMore(sexp) + RPAREN)\n\nNeeds more )'s\n"
] | [
4
] | [] | [] | [
"pyparsing",
"python",
"syntax",
"syntax_error"
] | stackoverflow_0001791269_pyparsing_python_syntax_syntax_error.txt |
Q:
Django ease of building a RESTful interface
I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is
rather straightfor... | Django ease of building a RESTful interface | I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is
rather straightforward to do without the use of frameworks, but som... | [
"This is probably pretty easy to do.\nURL mappings are easy to construct, for example:\nurlpatterns = patterns('books.views',\n (r'^books/$', 'index'),\n (r'^books/(\\d+)/$', 'get'))\n\nDjango supports model serialization, so it's easy to turn models into XML:\nfrom django.core import serializers\nfrom models imp... | [
15,
4,
3,
2,
2,
1
] | [] | [] | [
"django",
"python",
"rest"
] | stackoverflow_0001732452_django_python_rest.txt |
Q:
Genshi: Nested for loops
I need to generate a HTML using a Genshi template. The Html is, basicaly a very long html with tables. The data comes in a simple CSV, so, i read it with python, i put it into a list[] and then i call the template and send the variable (the list)
Actually i solved it by doing something lik... | Genshi: Nested for loops | I need to generate a HTML using a Genshi template. The Html is, basicaly a very long html with tables. The data comes in a simple CSV, so, i read it with python, i put it into a list[] and then i call the template and send the variable (the list)
Actually i solved it by doing something like this in the template:
<html>... | [
"<table>\n<tr py:for=\"i in t\"> \n<td py:for=\"e in tp[i]\">\n${e}s\n</td>\n</tr>\n</table>\n\n"
] | [
2
] | [] | [] | [
"csv",
"genshi",
"python"
] | stackoverflow_0001791252_csv_genshi_python.txt |
Q:
How do I build the 32-bit pypy JIT in 64-bit Linux?
Pypy's JIT will compile on 64-bit Linux ever since it grew 64-bit support, but what if I wanted to compile a 32-bit version? How should I cross-compile a 32-bit JITting pypy on that machine?
A:
You could try compiling it in a chroot.
| How do I build the 32-bit pypy JIT in 64-bit Linux? | Pypy's JIT will compile on 64-bit Linux ever since it grew 64-bit support, but what if I wanted to compile a 32-bit version? How should I cross-compile a 32-bit JITting pypy on that machine?
| [
"You could try compiling it in a chroot.\n"
] | [
2
] | [] | [] | [
"pypy",
"python"
] | stackoverflow_0001785428_pypy_python.txt |
Q:
Creating container relationship in declarative SQLAlchemy
My Python / SQLAlchemy application manages a set of nodes, all derived from a base class Node. I'm using SQLAlchemy's polymorphism features to manage
the nodes in a SQLite3 table. Here's the definition of the base Node class:
class Node(db.Base):
__tab... | Creating container relationship in declarative SQLAlchemy | My Python / SQLAlchemy application manages a set of nodes, all derived from a base class Node. I'm using SQLAlchemy's polymorphism features to manage
the nodes in a SQLite3 table. Here's the definition of the base Node class:
class Node(db.Base):
__tablename__ = 'nodes'
id = Column(Integer, primary_key=True)
... | [
"You need an additional table for many-to-many relation:\nnodes_list_nodes = Table(\n 'nodes_list_nodes', metadata,\n Column('parent_id', None, ForeignKey('nodes_list.id'), nullable=False),\n Column('child_id', None, ForeignKey(Node.id), nullable=False),\n PrimaryKeyConstraint('parent_id', 'child_id'),\... | [
5
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001791713_python_sqlalchemy.txt |
Q:
Python Class with integer emulation
Given is the following example:
class Foo(object):
def __init__(self, value=0):
self.value=value
def __int__(self):
return self.value
I want to have a class Foo, which acts as an integer (or float). So I want to do the following things:
f=Foo(3)
print i... | Python Class with integer emulation | Given is the following example:
class Foo(object):
def __init__(self, value=0):
self.value=value
def __int__(self):
return self.value
I want to have a class Foo, which acts as an integer (or float). So I want to do the following things:
f=Foo(3)
print int(f)+5 # is working
print f+5 # TypeErro... | [
"In Python 2.4+ inheriting from int works:\nclass MyInt(int):pass\nf=MyInt(3)\nassert f + 5 == 8\n\n",
"You need to override __new__, not __init__:\nclass Foo(int):\n def __new__(cls, some_argument=None, value=0):\n i = int.__new__(cls, value)\n i._some_argument = some_argument\n return i\... | [
7,
6,
2
] | [] | [] | [
"emulation",
"floating_point",
"integer",
"python"
] | stackoverflow_0001638229_emulation_floating_point_integer_python.txt |
Q:
Python: dynamic class generation: overwrite members
I have a python class hierarchy, that I want to extend at runtime. Furthermore every class in this hierarchy has a static attribute 'dict', that I want to overwrite in every subclass. Simplyfied it looks like this:
'dict' is a protected (public but with leading u... | Python: dynamic class generation: overwrite members | I have a python class hierarchy, that I want to extend at runtime. Furthermore every class in this hierarchy has a static attribute 'dict', that I want to overwrite in every subclass. Simplyfied it looks like this:
'dict' is a protected (public but with leading underscore) member
class A(object):
_dict = {}
@c... | [
"phild, as you know, when you prefix an attribute name with double-underscore __, the python interpreter automagically changes (mangles) attribute name from __attribute to _CLS__attribute, where CLS is the class name.\nHowever, when you say\nreturn type(name, (cls, ), { '__dict' : {} })\nthe keys in the dictionary ... | [
3,
2,
1
] | [] | [] | [
"dynamic_class_creation",
"inheritance",
"name_mangling",
"python"
] | stackoverflow_0001792104_dynamic_class_creation_inheritance_name_mangling_python.txt |
Q:
Looping through files in a folder
I'm fairly new when it comes to programming, and have started out learning python.
What I want to do is to recolour sprites for a game, and I am given the original colours,
followed by what they are to be turned into. Each sprite has between 20 and 60 angles, so
looping through ea... | Looping through files in a folder | I'm fairly new when it comes to programming, and have started out learning python.
What I want to do is to recolour sprites for a game, and I am given the original colours,
followed by what they are to be turned into. Each sprite has between 20 and 60 angles, so
looping through each one in the folder for each colour is... | [
"os.listdir() returns a list of file names. Thus, filename is a string. You need to open the file before iterating on it, I guess.\nAlso, be careful with backslashes in strings. They are mostly used for special escape sequences, so you need to escape them by doubling them. You could use the constant os.sep to be mo... | [
34,
10,
3
] | [] | [] | [
"file",
"loops",
"python"
] | stackoverflow_0001792312_file_loops_python.txt |
Q:
Updating value in binary file with Python
I'm trying to figure out how to update the data in a binary file using Python.
I'm already comfortable reading and writing complete files using "array", but I'm having trouble with in place editing.
Here's what I've tried:
my_file.seek(100)
my_array = array.array('B')
my_... | Updating value in binary file with Python | I'm trying to figure out how to update the data in a binary file using Python.
I'm already comfortable reading and writing complete files using "array", but I'm having trouble with in place editing.
Here's what I've tried:
my_file.seek(100)
my_array = array.array('B')
my_array.append(0)
my_array.tofile(my_file)
Essen... | [
"According to the documentation of open(), you should open the file in 'rb+' mode to avoid the truncating behavior.\n",
"Are you opening the file in 'r+b' mode?\n"
] | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0001792701_python.txt |
Q:
marking duplicates in a csv file
I'm stumped with a problem illustrated in the sample below:
"ID","NAME","PHONE","REF","DISCARD"
1,"JOHN",12345,,
2,"PETER",6232,,
3,"JON",12345,,
4,"PETERSON",6232,,
5,"ALEX",7854,,
6,"JON",12345,,
I want to detect duplicates in column "PHONE", and mark the subsequent duplicates u... | marking duplicates in a csv file | I'm stumped with a problem illustrated in the sample below:
"ID","NAME","PHONE","REF","DISCARD"
1,"JOHN",12345,,
2,"PETER",6232,,
3,"JON",12345,,
4,"PETERSON",6232,,
5,"ALEX",7854,,
6,"JON",12345,,
I want to detect duplicates in column "PHONE", and mark the subsequent duplicates using the column "REF", with a value po... | [
"The only thing you have to keep in memory while this is running is a map of phone numbers to their IDs.\nmap = {}\nwith open(r'c:\\temp\\input.csv', 'r') as fin:\n reader = csv.reader(fin)\n with open(r'c:\\temp\\output.csv', 'w') as fout:\n writer = csv.writer(fout)\n # omit this if the file h... | [
7,
0,
0,
0,
0
] | [] | [] | [
"csv",
"duplicates",
"python"
] | stackoverflow_0001733166_csv_duplicates_python.txt |
Q:
Django is_valid() not working with modelformset_factory
I've created a simple contact form using the modelformset_factory to build the form in the view using the DB model. The issue that I am having is that the is_valid() check before the save() is not working. When I submit the form with empty fields it still p... | Django is_valid() not working with modelformset_factory | I've created a simple contact form using the modelformset_factory to build the form in the view using the DB model. The issue that I am having is that the is_valid() check before the save() is not working. When I submit the form with empty fields it still passes the is_valid() and attempts to write to the DB.
I woul... | [
"Your issue is that providing 0 items is a valid formset, there is no minimum validation. I'd provide a custom BaseModelFormset subclass that's clean() method just checked for a minimum of one obj.\n",
"Did you really want a formset? I suspect if you have a contacts form with only one instance of the Response i... | [
2,
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0001791942_django_django_forms_django_models_python.txt |
Q:
Packet Queue in Python?
is there any way to queue packets to a socket in Python? I've been looking for something like the libipq library, but can't find anything equivalent.
Here's what I'm trying to accomplish:
Create tcp socket connection between server and client (both under my control).
Try transmitting data... | Packet Queue in Python? | is there any way to queue packets to a socket in Python? I've been looking for something like the libipq library, but can't find anything equivalent.
Here's what I'm trying to accomplish:
Create tcp socket connection between server and client (both under my control).
Try transmitting data (waiting for connection to f... | [
"I suggest you implement an application protocol, so when the client receives data it acknowledges it to the server, with a serial number for each bit of data.\nThe server then keeps note of which serial number the client needs next and sends it. If the connection breaks then the server re-makes it.\nThe data coul... | [
0
] | [] | [] | [
"packet",
"python",
"queue",
"sockets"
] | stackoverflow_0001792320_packet_python_queue_sockets.txt |
Q:
How to treat a returned/stored string like a raw string in Python?
I am trying to .split() a hex string i.e. '\xff\x00' to get a list i.e. ['ff', '00']
This works if I split on a raw string literal i.e. r'\xff\x00' using .split('\\x') but not if I split on a hex string stored in a variable or returned from a func... | How to treat a returned/stored string like a raw string in Python? | I am trying to .split() a hex string i.e. '\xff\x00' to get a list i.e. ['ff', '00']
This works if I split on a raw string literal i.e. r'\xff\x00' using .split('\\x') but not if I split on a hex string stored in a variable or returned from a function (which I presume is not a raw string)
How do I convert or at least ... | [
"x = '\\xff\\x00'\ny = ['%02x' % ord(c) for c in x]\nprint y\n\nOutput:\n['ff', '00']\n\n",
"Here is a solution in the spirit of the original question:\nx = '\\xff\\x00'\neval(\"r\"+repr(x)).split('\\\\x')\n\nIt will return the same thing as r'\\xff\\x00'.split('\\\\x'): ['', 'ff', '00'].\n"
] | [
6,
0
] | [] | [] | [
"escaping",
"python",
"string"
] | stackoverflow_0001792807_escaping_python_string.txt |
Q:
Python urllib2 HTTPS and proxy NTLM authentication
urllib2 doesn't seem to support HTTPS with proxy authentication in general, even less with NTLM authentication. Anyone knows if there is a patch somewhere for HTTPS on proxy with NTLM authentication.
Regards,
Laurent
A:
Late reply. Urllib2 does not support NTLM ... | Python urllib2 HTTPS and proxy NTLM authentication | urllib2 doesn't seem to support HTTPS with proxy authentication in general, even less with NTLM authentication. Anyone knows if there is a patch somewhere for HTTPS on proxy with NTLM authentication.
Regards,
Laurent
| [
"Late reply. Urllib2 does not support NTLM proxying but pycurl does. Excerpt:\nself._connection = pycurl.Curl()\nself._connection.setopt(pycurl.PROXY, PROXY_HOST)\nself._connection.setopt(pycurl.PROXYPORT, PROXY_PORT)\nself._connection.setopt(pycurl.PROXYUSERPWD,\n \"%s:%s\" % (PROXY_USER, PR... | [
6,
2,
1
] | [] | [] | [
"authentication",
"https",
"ntlm",
"proxy",
"python"
] | stackoverflow_0001481398_authentication_https_ntlm_proxy_python.txt |
Q:
Make Dictionary From 2 List
Trying to make dictionary with 2 list one being the key and one being the value but I'm having a problem. This is what I have so far:
d={}
for num in range(10):
for nbr in range(len(key)):
d[num]=key[nbr]
Say my key is a list from 1 to 9, and value list is [2,4,0,9,6,6,8,6,... | Make Dictionary From 2 List | Trying to make dictionary with 2 list one being the key and one being the value but I'm having a problem. This is what I have so far:
d={}
for num in range(10):
for nbr in range(len(key)):
d[num]=key[nbr]
Say my key is a list from 1 to 9, and value list is [2,4,0,9,6,6,8,6,4,5].
How do I assign so it that ... | [
"zip() to the rescue!\n>>> k = range(1,10) # or some list or iterable of sorts\n>>> v = [2,4,0,9,6,6,8,6,4,5]\n>>> d = dict(zip(k,v))\n>>> d\n{1: 2, 2: 4, 3: 0, 4: 9, 5: 6, 6: 6, 7: 8, 8: 6, 9: 4}\n>>>\n\nFor more details, see zip() built-in function, in Python documentation.\nNote, regarding range() and the list... | [
12,
6,
2,
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0001793154_dictionary_list_python.txt |
Q:
Printing several binary data fields from Google DataStore?
I'm using Google App Engine and python for a web service. Some of the models (tables) I have in my web service have several binary data fields in them, and I'd like to present this data to a computer requesting it, all fields at the same time. Now, the pro... | Printing several binary data fields from Google DataStore? | I'm using Google App Engine and python for a web service. Some of the models (tables) I have in my web service have several binary data fields in them, and I'd like to present this data to a computer requesting it, all fields at the same time. Now, the problem is I don't know how to write it out in a way that the other... | [
"Several easy options:\n\nbase64 encode your data - meaning you can still use JSON.\nUse Protocol Buffers.\nPrefix each field with its length - either as a 4- or 8- byte integer, or as a numeric string.\n\n",
"One solution that would leverage your json investment would be to simply convert the binary data to some... | [
2,
1
] | [] | [] | [
"binary",
"google_app_engine",
"json",
"python"
] | stackoverflow_0001791580_binary_google_app_engine_json_python.txt |
Q:
How to use long integers in Python to build a range?
I am trying to build a range with an upper bound bigger than limit of integer in Python. I was looking for something like the following:
import sys
start = 100;
step = 100;
limit = sys.maxint + 1;
result = xrange(start, limit, step);
However, xrange parameters ... | How to use long integers in Python to build a range? | I am trying to build a range with an upper bound bigger than limit of integer in Python. I was looking for something like the following:
import sys
start = 100;
step = 100;
limit = sys.maxint + 1;
result = xrange(start, limit, step);
However, xrange parameters are limited to the integer. According to Python Standard L... | [
"xrange is trivial to roll out on your own, so you can do just that:\ndef xlongrange(start, limit, step):\n n = start\n while n < limit:\n yield n\n n += step\n\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0001793426_python.txt |
Q:
What pure Python library should I use to scrape a website?
I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.
Now I'm trying to port this over to Google App Engine, and keep getting stuck.
I've ported Pyt... | What pure Python library should I use to scrape a website? | I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.
Now I'm trying to port this over to Google App Engine, and keep getting stuck.
I've ported Python Mechanize to work with Google App Engine, but it doesn't sup... | [
"Beautiful Soup.\n",
"lxml -- 100x better than elementtree\n",
"There's also scrapy, might be more up your alley.\n",
"There are a number of examples of web page scrapers written using pyparsing, such as this one (extracts all URL links from yahoo.com) and this one (for extracting the NIST NTP server addresse... | [
11,
6,
4,
0,
0
] | [] | [] | [
"beautifulsoup",
"google_app_engine",
"mechanize",
"python",
"xpath"
] | stackoverflow_0001563165_beautifulsoup_google_app_engine_mechanize_python_xpath.txt |
Q:
Python HTML scraping
It's not really scraping, I'm just trying to find the URLs in a web page where the class has a specific value. For example:
<a class="myClass" href="/url/7df028f508c4685ddf65987a0bd6f22e">
I want to get the href value. Any ideas on how to do this? Maybe regex? Could you post some example code... | Python HTML scraping | It's not really scraping, I'm just trying to find the URLs in a web page where the class has a specific value. For example:
<a class="myClass" href="/url/7df028f508c4685ddf65987a0bd6f22e">
I want to get the href value. Any ideas on how to do this? Maybe regex? Could you post some example code?
I'm guessing html scrapi... | [
"Regex is usally a bad idea, try using BeautifulSoup\nQuick example:\nhtml = #get html\nsoup = BeautifulSoup(html)\nlinks = soup.findAll('a', attrs={'class': 'myclass'})\nfor link in links:\n #process link\n\n",
"Aargh, not regex for parsing HTML!\nLuckily in Python we have BeautifulSoup or lxml to do that job... | [
16,
9,
2,
1,
1,
0,
0
] | [] | [] | [
"html",
"html_content_extraction",
"python",
"regex",
"screen_scraping"
] | stackoverflow_0001793663_html_html_content_extraction_python_regex_screen_scraping.txt |
Q:
Minimal binary diff for similar 1000 byte blocks with static noise?
I need a minimal diff for similar 1000 byte blocks. These blocks will have at most 20% of the bits different. The flipped bits will be like radio static -- randomly flipped bits with a uniform distribution over the whole block. Here's my pseudo co... | Minimal binary diff for similar 1000 byte blocks with static noise? | I need a minimal diff for similar 1000 byte blocks. These blocks will have at most 20% of the bits different. The flipped bits will be like radio static -- randomly flipped bits with a uniform distribution over the whole block. Here's my pseudo code using XOR and lzo compression:
minimal_diff=lzo(XOR(block1,block2))
S... | [
"if its truly random noise then it does not really compress. This means that if you have 8,000 bits (1,000 bytes x 8 bits / byte) and every individual bit has 1/5 (20%) probability of flipping, then you can't encode the changed bits in less than 8,000 x (-4/5 x ln2 4/5 + -1/5 x ln2 1/5) = 8,000 x (-4/5 x -0.322 + -... | [
3,
0
] | [] | [] | [
"algorithm",
"diff",
"python"
] | stackoverflow_0001793253_algorithm_diff_python.txt |
Q:
Passing SQLite variables in Python
I am writing a app in python and utilzing sqlite. I have a list of strings which I would like to add too the database, where each element represents some data which coincides with the column it will be put.
currently I have something like this
cursor.execute("""insert into cre... | Passing SQLite variables in Python | I am writing a app in python and utilzing sqlite. I have a list of strings which I would like to add too the database, where each element represents some data which coincides with the column it will be put.
currently I have something like this
cursor.execute("""insert into credit
values ('Citi','... | [
"Use parameters to .execute():\nquery = \"\"\"\n INSERT INTO credit\n (bank, number, card, int1, value, type, int2)\n VALUES\n (?, ?, ?, ?, ?, ?, ?)\n \"\"\"\ndata = ['Citi', '5567', 'visa', 6000, 9.99, '23', 9000]\n\ncursor.execute(query, data)\n\nAccording to PEP249:\n\n.execute(o... | [
11
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0001793970_python_sqlite.txt |
Q:
Matching multiple regex groups and removing them
I have been given a file that I would like to extract the useful data from. The format of the file goes something like this:
LINE: 1
TOKENKIND: somedata
TOKENKIND: somedata
LINE: 2
TOKENKIND: somedata
LINE: 3
etc...
What I would like to do is remove LINE: and the l... | Matching multiple regex groups and removing them | I have been given a file that I would like to extract the useful data from. The format of the file goes something like this:
LINE: 1
TOKENKIND: somedata
TOKENKIND: somedata
LINE: 2
TOKENKIND: somedata
LINE: 3
etc...
What I would like to do is remove LINE: and the line number as well as TOKENKIND: so I am just left wit... | [
"import re\n\nx = '''LINE: 1\nTOKENKIND: somedata\nTOKENKIND: somedata\nLINE: 2\nTOKENKIND: somedata\nLINE: 3'''\n\njunkre = re.compile(r'(\\s*LINE:\\s*\\d*\\s*)|(\\s*TOKENKIND:)', re.DOTALL)\n\nprint junkre.sub('', x)\n\n",
"no need to use regex in Python. Its Python after all, not Perl. Think simple and use its... | [
4,
2,
1
] | [] | [] | [
"lexical_analysis",
"python",
"regex"
] | stackoverflow_0001791097_lexical_analysis_python_regex.txt |
Q:
operation in arrays
I have a question, as I perform mathematical operations with an array of lists such as I get the sum of each array list getting a new list with the Valar for the sum of each list in the array.
thanks for any response
A:
Try a list comprehension:
>>> list_of_lists = [[1,2],[3,4]]
>>> [sum(li) ... | operation in arrays | I have a question, as I perform mathematical operations with an array of lists such as I get the sum of each array list getting a new list with the Valar for the sum of each list in the array.
thanks for any response
| [
"Try a list comprehension:\n>>> list_of_lists = [[1,2],[3,4]]\n>>> [sum(li) for li in list_of_lists]\n[3, 7]\n\n",
"You can also try mapping the lists with the built-in sum function.\n>>> a = [11, 13, 17, 19, 23]\n>>> b = [29, 31, 37, 41, 43]\n>>> c = [47, 53, 59, 61, 67]\n>>> d = [71, 73, 79, 83, 89]\n>>> map(su... | [
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001793214_python.txt |
Q:
Merge two lists of lists - Python
This is a great primer but doesn't answer what I need:
Combining two sorted lists in Python
I have two Python lists, each is a list of datetime,value pairs:
list_a = [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]]
And:
list_x = [['1241000884000', 16], ['124100... | Merge two lists of lists - Python | This is a great primer but doesn't answer what I need:
Combining two sorted lists in Python
I have two Python lists, each is a list of datetime,value pairs:
list_a = [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]]
And:
list_x = [['1241000884000', 16], ['1241000992000', 16], ['1241001121000', 17], [... | [
"Here's some code that does what you asked for. You can turn your list of pairs into a dictionary straightforwardly. Then keys that are shared can be found by intersecting the sets of keys. Finally, constructing the result dictionary is easy given the set of shared keys.\ndict_a = dict(list_a)\ndict_x = dict(list_x... | [
4,
3,
2,
0
] | [] | [] | [
"django",
"list",
"python"
] | stackoverflow_0000803526_django_list_python.txt |
Q:
Knowing if any key is pressed, wxPython
I have a timer, and need to know if any of the keys is pressed on any cycle. How do I do it?
A:
If you are using Linux it's found in the curses module, if you use Windows it's in the msvcrt module.
I found following article really helpful in describing this topic - Event D... | Knowing if any key is pressed, wxPython | I have a timer, and need to know if any of the keys is pressed on any cycle. How do I do it?
| [
"If you are using Linux it's found in the curses module, if you use Windows it's in the msvcrt module.\nI found following article really helpful in describing this topic - Event Driven Programming\n",
"Try:\nimport sys\nc = sys.stdin.read(1)\n\n",
"If you are using Windows, Use PyHook If you like to know system... | [
1,
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001786194_python_wxpython.txt |
Q:
PyQt: removeChild/addChild QGroupBox
I am developing a system for a customer which is displayed in a set of tabs, and shows a table in the centralwidget with data extracted from a database.
Depending on mouse events, the container (groupBox) must be removed from the centralwidget, or then added with new updated da... | PyQt: removeChild/addChild QGroupBox | I am developing a system for a customer which is displayed in a set of tabs, and shows a table in the centralwidget with data extracted from a database.
Depending on mouse events, the container (groupBox) must be removed from the centralwidget, or then added with new updated data for the table.
Here is a piece of the c... | [
"I don't think calling removeWidget is necessary. Try just calling widget.deleteLater on whatever you want to delete. Then when you want to add it back, recreate it and use layout.insertWidget to put it in its proper place. Does that work?\nIt's working for me here on Windows XP... \nimport sys\n\nfrom PyQt4 im... | [
2,
1,
1,
0
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0001781173_pyqt_python_qt.txt |
Q:
Python on Rails?
Would it be possible to translate the Ruby on Rails code base to Python?
I think many people like Python more than Ruby, but find Ruby on Rails features better (as a whole) than the ones in Python web frameworks.
So that, would it be possible? Or does Ruby on Rails utilize language-specific featur... | Python on Rails? | Would it be possible to translate the Ruby on Rails code base to Python?
I think many people like Python more than Ruby, but find Ruby on Rails features better (as a whole) than the ones in Python web frameworks.
So that, would it be possible? Or does Ruby on Rails utilize language-specific features that would be diffi... | [
"This is a great blog post. Rails developers chose a framework, and coding in Ruby is the afterthought. \nPython developers chose the language for the language, not the framework. On the other hand, that made a lot lower bar to entry for frameworks.\n",
"Many of the methodology used in Rails has been translate... | [
17,
16,
14,
1
] | [] | [] | [
"code_translation",
"metaprogramming",
"python",
"ruby_on_rails"
] | stackoverflow_0001794179_code_translation_metaprogramming_python_ruby_on_rails.txt |
Q:
Python : fork and exec a process to run on different terminal
I am trying to simulate a a network consisting of several clients and servers. I have written node.py which contains client-server code. I want to run multiple instances node.py. But I don't want to do it manually so I have written another file spawn.py... | Python : fork and exec a process to run on different terminal | I am trying to simulate a a network consisting of several clients and servers. I have written node.py which contains client-server code. I want to run multiple instances node.py. But I don't want to do it manually so I have written another file spawn.py which spawns multiple instances of node.py using fork and exec. Ho... | [
"If you want \"real\" (pseudo-;-) terminals, and are using X11 (almost every GUI interface on Linux does;-), you could exec xterm -e python node.py instead of just python node.py -- substitute for xterm whatever terminal emulator program you prefer, of course (I'm sure they all have command-line switches equivalent... | [
1,
0
] | [] | [] | [
"process",
"python"
] | stackoverflow_0001794536_process_python.txt |
Q:
How can I read the memory of another process in Python in Windows?
I'm trying to write a Python script that reads a series of memory locations of a particular process.
How can I do this in Python?
I'll be using Windows if it matters. I have the processes PID that I'm attempting to read/edit.
Am I going to have to... | How can I read the memory of another process in Python in Windows? | I'm trying to write a Python script that reads a series of memory locations of a particular process.
How can I do this in Python?
I'll be using Windows if it matters. I have the processes PID that I'm attempting to read/edit.
Am I going to have to revert to calling ReadProcessMemory() and using ctypes?
| [
"I didn't see anything in the standard python libraries but I found an example using ctypes like you suggested on another site:\nfrom ctypes import *\nfrom ctypes.wintypes import *\n\nOpenProcess = windll.kernel32.OpenProcess\nReadProcessMemory = windll.kernel32.ReadProcessMemory\nCloseHandle = windll.kernel32.Clos... | [
27,
0
] | [
"See http://www.windowsreference.com/windows-xp/dos-commands-and-equivalent-linux-commands/\nYou can use tasklist.exe to list processes, then scrape the results. Then use taskkill.exe (or tstskill.exe) to end them.\nBut ctypes and kernal32 is probably safer.\n"
] | [
-7
] | [
"python"
] | stackoverflow_0001794579_python.txt |
Q:
Chat comet site using python and twisted
i want to build a site similar to www.omegle.com. can any one suggest me some ideas.
I think its built usning twisted , orbiter comet server.
A:
Twisted is a good choice. I used it a few years ago to build a server for a browser-based online game I wrote - it kept track o... | Chat comet site using python and twisted | i want to build a site similar to www.omegle.com. can any one suggest me some ideas.
I think its built usning twisted , orbiter comet server.
| [
"Twisted is a good choice. I used it a few years ago to build a server for a browser-based online game I wrote - it kept track of clients, served them replies to Ajax requests, and used HTML5 Server-Sent DOM Events as well. Worked rather painlessly thanks to Twisted's good HTTP library.\nFor a Python web framework,... | [
3,
2,
1,
1,
1
] | [] | [] | [
"orbited",
"python",
"twisted"
] | stackoverflow_0001047306_orbited_python_twisted.txt |
Q:
How can I generate RSS with arbitrary tags and enclosures
Right now, I'm using PyRSS2Gen to generate an RSS document (resyndicating a modification of an rss feed that was parsed with feedparser), but I can't figure out how to add uncommon tags to the item.
items = [
PyRSS2Gen.RSSItem(
title = x.title,
link... | How can I generate RSS with arbitrary tags and enclosures | Right now, I'm using PyRSS2Gen to generate an RSS document (resyndicating a modification of an rss feed that was parsed with feedparser), but I can't figure out how to add uncommon tags to the item.
items = [
PyRSS2Gen.RSSItem(
title = x.title,
link = x.link,
description = x.summary,
guid = x.link,
... | [
"The documentation explains:\n\nTo add your\n own attributes (needed for namespace\n declarations), redefine\n element_attrs or rss_attrs in your\n subclass [of RSS and RSSData].\n\nThat's the whole point about subclassing, isn't it? :)\n",
"There are two ways. First, you could change the code directly. Edit ... | [
1,
1
] | [] | [] | [
"feedparser",
"python",
"rss"
] | stackoverflow_0001766823_feedparser_python_rss.txt |
Q:
Python: Analyzing complex statements during execution
I am wondering if there is any way to get some meta information about the interpretation of a python statement during execution.
Let's assume this is a complex statement of some single statements joined with or (A, B, ... are boolean functions)
if A or B and ((... | Python: Analyzing complex statements during execution | I am wondering if there is any way to get some meta information about the interpretation of a python statement during execution.
Let's assume this is a complex statement of some single statements joined with or (A, B, ... are boolean functions)
if A or B and ((C or D and E) or F) or G and H:
and I want to know which p... | [
"Could you recode your original code:\nif A or B and ((C or D and E) or F) or G and H:\n\nas, say:\ne = Evaluator()\nif e('A or B and ((C or D and E) or F) or G and H'):\n\n...? If so, there's hope!-). The Evaluator class, upon __call__, would compile its string argument, then eval the result with (an empty real ... | [
3,
1,
0,
0,
0
] | [] | [] | [
"interpreter",
"logic",
"python"
] | stackoverflow_0001793660_interpreter_logic_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.