content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How can I change '>' to '>' and '>' to '>'?
print u'<'
How can I print <
print '>'
How can I print >
A:
You should use HTMLParser module to decode html:
>>> import HTMLParser
>>> h= HTMLParser.HTMLParser()
>>> h.unescape('alpha < β')
u'alpha < \u03b2'
To escape HTML, cgi module is fine:
>>> cgi... | How can I change '>' to '>' and '>' to '>'? | print u'<'
How can I print <
print '>'
How can I print >
| [
"You should use HTMLParser module to decode html:\n>>> import HTMLParser\n>>> h= HTMLParser.HTMLParser()\n>>> h.unescape('alpha < β')\nu'alpha < \\u03b2'\n\nTo escape HTML, cgi module is fine:\n>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')\n'<a>bá</a>\n\n"
] | [
17
] | [] | [] | [
"python"
] | stackoverflow_0001977900_python.txt |
Q:
A multi-part/threaded downloader via python?
I've seen a few threaded downloaders online, and even a few multi-part downloaders (HTTP).
I haven't seen them together as a class/function.
If any of you have a class/function lying around, that I can just drop into any of my applications where I need to grab multiple ... | A multi-part/threaded downloader via python? | I've seen a few threaded downloaders online, and even a few multi-part downloaders (HTTP).
I haven't seen them together as a class/function.
If any of you have a class/function lying around, that I can just drop into any of my applications where I need to grab multiple files, I'd be much obliged.
If there is there a li... | [
"Threadpool by Christopher Arndt may be what you're looking for. I've used this \"easy to use object-oriented thread pool framework\" for the exact purpose you describe and it works great. See the usage examples at the bottom on the linked page. And it really is easy to use: just define three functions (one of whic... | [
1
] | [] | [] | [
"download",
"multipart",
"multithreading",
"python",
"urllib"
] | stackoverflow_0001979435_download_multipart_multithreading_python_urllib.txt |
Q:
Python web server?
I want to develop a tool for my project using python. The requirements are:
Embed a web server to let the user get some static files, but the traffic is not very high.
User can configure the tool using http, I don't want a GUI page, I just need a RPC interface, like XML-RPC? or others?
Besides... | Python web server? | I want to develop a tool for my project using python. The requirements are:
Embed a web server to let the user get some static files, but the traffic is not very high.
User can configure the tool using http, I don't want a GUI page, I just need a RPC interface, like XML-RPC? or others?
Besides the web server, the too... | [
"what about the internal python webserver ?\njust type \"python web server\" in google, and host the 1st result...\n",
"Well, I used web frameworks like TurboGears, my current projects are based on Pylons. The last ist fairly easy to learn and both come with CherryPy. \nTo do some background job you could impleme... | [
3,
1,
1,
0
] | [
"This sounds like a fun project. So, why don't write your own HTTP server? Its not so complicated after all, HTTP is a well-known and easy to implement protocol and you'll gain a lot of new knowledge!\nCheck documentation or manual pages (whatever you prefer) of socket(), bind(), listen(), accept() and so on.\n"
] | [
-3
] | [
"cherrypy",
"python"
] | stackoverflow_0001978791_cherrypy_python.txt |
Q:
How can I access an uploaded file in universal-newline mode?
I am working with a file uploaded using Django's forms.FileField. This returns an object of type InMemoryUploadedFile.
I need to access this file in universal-newline mode. Any ideas on how to do this without saving and then reopening the file?
Thanks
A... | How can I access an uploaded file in universal-newline mode? | I am working with a file uploaded using Django's forms.FileField. This returns an object of type InMemoryUploadedFile.
I need to access this file in universal-newline mode. Any ideas on how to do this without saving and then reopening the file?
Thanks
| [
"If you are using Python 2.6 or higher, you can use the io.StringIO class after having read your file into memory (using the read() method). Example:\n>>> import io\n>>> s = u\"a\\r\\nb\\nc\\rd\"\n>>> sio = io.StringIO(s, newline=None)\n>>> sio.readlines()\n[u'a\\n', u'b\\n', u'c\\n', u'd']\n\nTo actually use this ... | [
18
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001875956_django_django_forms_python.txt |
Q:
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx)
I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.
The server runs CentOS 5.2 and has PHP... | Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx) | I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.
The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I mu... | [
"The Office 2007 file formats are open and well documented. Roughly speaking, all of the new file formats ending in \"x\" are zip compressed XML documents. For example:\n\nTo open a Word 2007 XML file Create a\n temporary folder in which to store the\n file and its parts.\nSave a Word 2007 document, containing\n ... | [
18,
6,
3,
2
] | [] | [] | [
"office_2007",
"parsing",
"perl",
"php",
"python"
] | stackoverflow_0000173246_office_2007_parsing_perl_php_python.txt |
Q:
django query question
Assume I have such simple model:
class Foo(models.Model):
name = models.CharField(max_length=25)
b_date = models.DateField()
Now assume that my query result from Foo.objects.all() , I retrieve something like this:
[
{'name': 'zed', 'b_date': '2009-12-23'},
{'name': 'amy', 'b_... | django query question | Assume I have such simple model:
class Foo(models.Model):
name = models.CharField(max_length=25)
b_date = models.DateField()
Now assume that my query result from Foo.objects.all() , I retrieve something like this:
[
{'name': 'zed', 'b_date': '2009-12-23'},
{'name': 'amy', 'b_date': '2009-12-6'},
{'... | [
"Foo.objects.order_by('b_date').values_list('b_date', flat=True)\n\n"
] | [
7
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0001979951_django_django_templates_django_views_python.txt |
Q:
In Python, use "dict" with keywords or anonymous dictionaries?
Say you want to pass a dictionary of values to a function, or otherwise want to work with a short-lived dictionary that won't be reused. There are two easy ways to do this:
Use the dict() function to create a dictionary:
foo.update(dict(bar=42, baz='qu... | In Python, use "dict" with keywords or anonymous dictionaries? | Say you want to pass a dictionary of values to a function, or otherwise want to work with a short-lived dictionary that won't be reused. There are two easy ways to do this:
Use the dict() function to create a dictionary:
foo.update(dict(bar=42, baz='qux'))
Use an anonymous dictionary:
foo.update({'bar': 42, 'baz': 'qu... | [
"I prefer the anonymous dict option.\nI don't like the dict() option for the same reason I don't like:\n i = int(\"1\")\n\nWith the dict() option you're needlessly calling a function which is adding overhead you don't need:\n>>> from timeit import Timer\n>>> Timer(\"mydict = {'a' : 1, 'b' : 2, 'c' : 'three'}\").tim... | [
20,
6,
4,
2,
2,
1,
1,
1
] | [
"Actually, if the receiving function will only receive a dictionary with not pre-dertermined keywords, I normally use the ** passing convention.\nIn this example, that would be:\nclass Foo(object):\n def update(self, **param_dict):\n for key in param_dict:\n ....\nfoo = Foo()\n....\nfoo.update(bar=... | [
-1
] | [
"python"
] | stackoverflow_0001929274_python.txt |
Q:
Web2py Import Once per Session
I'm using Web2Py and i want to import my program simply once per session... not everytime the page is loaded. is this possible ? such as "import Client" being used on the page but only import it once per session..
A:
In web2py your models and controllers are executed, not imported.... | Web2py Import Once per Session | I'm using Web2Py and i want to import my program simply once per session... not everytime the page is loaded. is this possible ? such as "import Client" being used on the page but only import it once per session..
| [
"In web2py your models and controllers are executed, not imported. They are executed every time a request arrives. If you press the button [compile] in admin, they will be bytecode compiled and some other optimizations are performs.\nIf your app (in models and controllers) does \"import somemodule\", then the impor... | [
6
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0001978426_python_web2py.txt |
Q:
How to render a doctype with Python's xml.dom.minidom?
I tried:
document.doctype = xml.dom.minidom.DocumentType('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"')
There is no doctype in the output. How to fix without inserting it by hand?
A:
You shouldn't instantiate classes from minidom ... | How to render a doctype with Python's xml.dom.minidom? | I tried:
document.doctype = xml.dom.minidom.DocumentType('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"')
There is no doctype in the output. How to fix without inserting it by hand?
| [
"You shouldn't instantiate classes from minidom directly. It's not a supported part of the API, the ownerDocuments won't tie up and you can get some strange misbehaviours. Instead use the proper DOM Level 2 Core methods:\n>>> imp= minidom.getDOMImplementation('')\n>>> dt= imp.createDocumentType('html', '-//W3C//DT... | [
11
] | [] | [] | [
"doctype",
"python",
"xml"
] | stackoverflow_0001980380_doctype_python_xml.txt |
Q:
Django template question
How can I achieve this using the Django template system:
Say I have 2 variable passed to the template system:
days=[1,2,3,4,5]
items=[ {name:"apple,day:3},{name:"orange,day:5} ]
I want to have such output as a table:
1 2 3 4 5
apple n n y n n
orange n n ... | Django template question | How can I achieve this using the Django template system:
Say I have 2 variable passed to the template system:
days=[1,2,3,4,5]
items=[ {name:"apple,day:3},{name:"orange,day:5} ]
I want to have such output as a table:
1 2 3 4 5
apple n n y n n
orange n n n n y
As you can not... | [
"Why don't you define this logic in the django view, and then simply pass arrays of Ys and Ns to the template?\n",
"Here's what Ignacio meant. That said, I probably agree with Daniel that you should do this in the view.\n<table>\n{% for item in items %}\n <tr>\n <td>{% item.name %}</td>\n {% for dday in da... | [
6,
6,
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0001980600_django_django_templates_python.txt |
Q:
Is there any reason to use threading.Lock over multiprocessing.Lock?
If a software project supports a version of Python that multiprocessing has been backported to, is there any reason to use threading.Lock over multiprocessing.Lock? Would a multiprocessing lock not be thread safe as well?
For that matter, is the... | Is there any reason to use threading.Lock over multiprocessing.Lock? | If a software project supports a version of Python that multiprocessing has been backported to, is there any reason to use threading.Lock over multiprocessing.Lock? Would a multiprocessing lock not be thread safe as well?
For that matter, is there a reason to use any synchronization primitives from threading that are ... | [
"The threading module's synchronization primitive are lighter and faster than multiprocessing, due to the lack of dealing with shared semaphores, etc. If you are using threads; use threading's locks. Processes should use multiprocessing's locks.\n",
"I would expect the multi-threading synchronization primitives t... | [
21,
4,
3
] | [] | [] | [
"locking",
"multiprocessing",
"multithreading",
"process",
"python"
] | stackoverflow_0001980479_locking_multiprocessing_multithreading_process_python.txt |
Q:
lisp-style style `let` syntax in Python list-comprehensions
Consider the following code:
>>> colprint([
(name, versions[name][0].summary or '')
for name in sorted(versions.keys())
])
What this code does is to print the elements of the dictionary versions in ascending order of its keys, but sin... | lisp-style style `let` syntax in Python list-comprehensions | Consider the following code:
>>> colprint([
(name, versions[name][0].summary or '')
for name in sorted(versions.keys())
])
What this code does is to print the elements of the dictionary versions in ascending order of its keys, but since the value is another sorted list, only the summary of its firs... | [
"Why not exploit tuples?\ncolprint([(name, version[0].summary or '')\n for (name, version) in sorted(versions.iteritems())])\n\nor, even\ncolprint(sorted([(name, version[0].summary or '')\n for (name, version) in versions.iteritems()]))\n\nAlso, you may consider (in my first example) removing the [... | [
7,
5,
4,
1,
0
] | [] | [] | [
"lisp",
"python",
"refactoring"
] | stackoverflow_0001910003_lisp_python_refactoring.txt |
Q:
Loading an image in Python (Error)
I want to load an image but I get an error-message.
My code:
from PIL import Image
im = Image.open("D:\Python26\PYTHON-PROGRAMME\bild.jpg")
im.show()
I get this error:
Traceback (most recent call last):
File "D:\Python26\PYTHON-PROGRAMME\00000000000000000", line 2, in <module>... | Loading an image in Python (Error) | I want to load an image but I get an error-message.
My code:
from PIL import Image
im = Image.open("D:\Python26\PYTHON-PROGRAMME\bild.jpg")
im.show()
I get this error:
Traceback (most recent call last):
File "D:\Python26\PYTHON-PROGRAMME\00000000000000000", line 2, in <module>
im = Image.open("D:\Python26\PYTHON... | [
"You need to escape the backslashes:\nim = Image.open(\"D:\\\\Python26\\\\PYTHON-PROGRAMME\\\\bild.jpg\")\n\n"
] | [
9
] | [] | [] | [
"image",
"python"
] | stackoverflow_0001981138_image_python.txt |
Q:
Loading an image in Python (Error) part_2
This code didn't show my picture. The picture really exists :)
Does anybody know why this doesnt work?
Thanks in advance!
from PIL import Image
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild.jpg")
im.show()
A:
You probably need to call the load() method to force ... | Loading an image in Python (Error) part_2 | This code didn't show my picture. The picture really exists :)
Does anybody know why this doesnt work?
Thanks in advance!
from PIL import Image
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild.jpg")
im.show()
| [
"You probably need to call the load() method to force the open() method to do its work. open is lazy.\nTry:\nfrom PIL import Image\nim = Image.open(\"D:\\\\Python26\\\\PYTHON-PROGRAMME\\\\bild.jpg\")\nim.load()\nim.show()\n\nIdea #2:\nPatch PIL's file Image.py to have a potentially more robust approach to using the... | [
1
] | [] | [] | [
"image",
"python"
] | stackoverflow_0001981335_image_python.txt |
Q:
Python: find index of item containing X in list
I have a huge list of data, more than 1M records in a form similar (though this is a much simpler form) to this:
[
{'name': 'Colby Karnopp', 'ids': [441, 231, 822]},
{'name': 'Wilmer Lummus', 'ids': [438, 548, 469]},
{'name': 'Hope Teschner', 'ids': [735, 747,... | Python: find index of item containing X in list | I have a huge list of data, more than 1M records in a form similar (though this is a much simpler form) to this:
[
{'name': 'Colby Karnopp', 'ids': [441, 231, 822]},
{'name': 'Wilmer Lummus', 'ids': [438, 548, 469]},
{'name': 'Hope Teschner', 'ids': [735, 747, 488]},
{'name': 'Adolfo Fenrich', 'ids': [515, 21... | [
"Simplest way to get the first index satisfying the condition (in Python 2.6 or better:\nnext((i for i, d in enumerate(hugelist) if 735 in d['ids']), None)\n\nthis gives None if no item satisfies the condition; more generally you could put as the second argument to the next built-in whatever you require in that cas... | [
6,
3,
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001975856_python.txt |
Q:
Protection from accidentally misnaming object attributes in Python?
A friend was "burned" when starting to learn Python, and now sees the language as perhaps fatally flawed.
He was using a library and changed the value of an object's attribute (the class being in the library), but he used the wrong abbreviation fo... | Protection from accidentally misnaming object attributes in Python? | A friend was "burned" when starting to learn Python, and now sees the language as perhaps fatally flawed.
He was using a library and changed the value of an object's attribute (the class being in the library), but he used the wrong abbreviation for the attribute name. It took him "forever" to figure out what was wrong... | [
"\"changed the value of an object's attribute\" Can lead to problems. This is pretty well known. You know it, now, also. That doesn't indict the language. It simply says that you've learned an important lesson in dynamic language programming.\n\nUnit testing absolutely discovers this. You are not forced to mo... | [
12,
7,
5,
5,
2,
1,
1,
0
] | [] | [] | [
"attributes",
"python"
] | stackoverflow_0001981208_attributes_python.txt |
Q:
Python func_dict used to memoize; other useful tricks?
A Python function object has an attribute dictionary called func_dict which is visible from outside the function and is mutable, but which is not modified when the function is called. (I learned this from answers to a question I asked yesterday (#1753232): t... | Python func_dict used to memoize; other useful tricks? | A Python function object has an attribute dictionary called func_dict which is visible from outside the function and is mutable, but which is not modified when the function is called. (I learned this from answers to a question I asked yesterday (#1753232): thanks!) I was reading code (at http://pythonprogramming.jot... | [
"Just be careful: the fib.cache trick only works if fib is indeed the name of the relevant function object in the scope that's active while it's executing (for example, when you decorate it as you have done, you must assign the starting value for the cache to the decorator wrapper, not to the decorated function -- ... | [
7,
1
] | [] | [] | [
"dictionary",
"fibonacci",
"function",
"memoization",
"python"
] | stackoverflow_0001760495_dictionary_fibonacci_function_memoization_python.txt |
Q:
How to tell if Python SQLite database connection or cursor is closed?
Let's say that you have the following code:
import sqlite3
conn = sqlite3.connect('mydb')
cur = conn.cursor()
# some database actions
cur.close()
conn.close()
# more code below
If I try to use the conn or cur objects later on, how could I tell... | How to tell if Python SQLite database connection or cursor is closed? | Let's say that you have the following code:
import sqlite3
conn = sqlite3.connect('mydb')
cur = conn.cursor()
# some database actions
cur.close()
conn.close()
# more code below
If I try to use the conn or cur objects later on, how could I tell that they are closed? I cannot find a .isclosed() method or anything like ... | [
"You could wrap in a try, except statement:\n>>> conn = sqlite3.connect('mydb')\n>>> conn.close()\n>>> try:\n... one_row = conn.execute(\"SELECT * FROM my_table LIMIT 1;\")\n... except sqlite3.ProgrammingError as e:\n... print(e)\nCannot operate on a closed database.\n\nThis relies on a shortcut specific to... | [
12,
0
] | [] | [] | [
"database_connection",
"python",
"sqlite"
] | stackoverflow_0001981392_database_connection_python_sqlite.txt |
Q:
Python change screen resolution virtual machine
In virtualbox, the screen resolution can be anything - even something strange like 993x451, etc. I tried changing it using pywin32 but I failed::
>>> dm = win32api.EnumDisplaySettings(None, 0)
>>> dm.PelsHeight = 451
>>> dm.PelsWidth = 950
>>> win32api.ChangeDisplayS... | Python change screen resolution virtual machine | In virtualbox, the screen resolution can be anything - even something strange like 993x451, etc. I tried changing it using pywin32 but I failed::
>>> dm = win32api.EnumDisplaySettings(None, 0)
>>> dm.PelsHeight = 451
>>> dm.PelsWidth = 950
>>> win32api.ChangeDisplaySettings(dm, 0)
-2L
which ends up being:
DISP_CHANGE_... | [
"Have you configured the virtual machine to actually advertise this mode to the OS?\nedit: VirtualBox automatically sets new resolutions if you change the size of the window. You can set video mode hints from the host OS I believe (look for it in the documentation), but you need guest additions installed. You can a... | [
1,
0,
0
] | [] | [] | [
"python",
"pywin32",
"resolution",
"virtualization",
"winapi"
] | stackoverflow_0001349544_python_pywin32_resolution_virtualization_winapi.txt |
Q:
nesting python list comprehensions to construct a list of lists
I'm a python newb and am having trouble groking nested list comprehensions. I'm trying to write some code to read in a file and construct a list for each character for each line.
so if the file contains
xxxcd
cdcdjkhjasld
asdasdxasda
The resulting ... | nesting python list comprehensions to construct a list of lists | I'm a python newb and am having trouble groking nested list comprehensions. I'm trying to write some code to read in a file and construct a list for each character for each line.
so if the file contains
xxxcd
cdcdjkhjasld
asdasdxasda
The resulting list would be:
[
['x','x','x','c','d']
['c','d','c','d','j','k','h','... | [
"This should help (you'll probably have to play around with it to strip the newlines or format it however you want, but the basic idea should work):\nf = open(r\"temp.txt\")\n[[c for c in line] for line in f]\n\n",
"In your case, you can use the list constructor to handle the inner loop and use list comprehension... | [
19,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0001982134_list_comprehension_python.txt |
Q:
Play Subset of audio file using Pyglet
How can I use the pyglet API for sound to play subsets of a sound file e.g. from 1 second in to 3.5seconds of a 6 second sound clip?
I can load a sound file and play it, and can seek to the start of the interval desired, but am wondering how to stop playback at the point indi... | Play Subset of audio file using Pyglet | How can I use the pyglet API for sound to play subsets of a sound file e.g. from 1 second in to 3.5seconds of a 6 second sound clip?
I can load a sound file and play it, and can seek to the start of the interval desired, but am wondering how to stop playback at the point indicated?
| [
"It doesn't appear that pyglet has support for setting a stop time. Your options are:\n\nPoll the current time and stop playback when you've reached your desired endpoint. This may not be precise enough for you.\nOr, use a sound file library to extract the portion you want into a temporary sound file, then use py... | [
1,
0
] | [] | [] | [
"audio",
"pyglet",
"python"
] | stackoverflow_0001977521_audio_pyglet_python.txt |
Q:
What does python print() function actually do?
I was looking at this question and started wondering what does the print actually do.
I have never found out how to use string.decode() and string.encode() to get an unicode string "out" in the python interactive shell in the same format as the print does. No matter w... | What does python print() function actually do? | I was looking at this question and started wondering what does the print actually do.
I have never found out how to use string.decode() and string.encode() to get an unicode string "out" in the python interactive shell in the same format as the print does. No matter what I do, I get either
UnicodeEncodeError or
the e... | [
"EDIT: (Major changes between this edit and the previous one... Note: I'm using Python 2.6.4 on an Ubuntu box.)\nFirstly, in my first attempt at an answer, I provided some general information on print and str which I'm going to leave below for the benefit of anybody having simpler issues with print and chancing upo... | [
9,
5,
2,
0
] | [] | [] | [
"printing",
"python",
"python_2.x",
"unicode"
] | stackoverflow_0001979234_printing_python_python_2.x_unicode.txt |
Q:
python skipping inner loop in nested for loop
I am using some python to do some variable name generation. For some reason I am only getting part of what I need.
import sys
import csv
params = csv.reader(open('params.csv'), delimiter=',', skipinitialspace=True)
flags_r = []
flags_w = []
numbers_r = []
numbers_w =... | python skipping inner loop in nested for loop | I am using some python to do some variable name generation. For some reason I am only getting part of what I need.
import sys
import csv
params = csv.reader(open('params.csv'), delimiter=',', skipinitialspace=True)
flags_r = []
flags_w = []
numbers_r = []
numbers_w = []
station = ['AC1','DC1','DC1']
drive = ['','Fld'... | [
"In the first iteration of the outer loop you read all lines from params. In the second iteration all the lines from params are already read, so there is nothing left to iterate over in the inner loop.\nTo work around this, you could load all the data sets into a list and then iterate over that list:\nreader = csv.... | [
6,
1,
0
] | [] | [] | [
"nested_loops",
"python"
] | stackoverflow_0001982506_nested_loops_python.txt |
Q:
Easy way to implement dynamic views?
View are useful constructions of Python 3. For those who never noticed (like me): for a dictionary d you can write k = d.keys() and even if you update d the variable k will still be giving you the updated keys. You can write then k1 & k2 and it will always give you d1.keys() & ... | Easy way to implement dynamic views? | View are useful constructions of Python 3. For those who never noticed (like me): for a dictionary d you can write k = d.keys() and even if you update d the variable k will still be giving you the updated keys. You can write then k1 & k2 and it will always give you d1.keys() & d2.keys()
I want to implement this for my ... | [
"Well, there is a collection.UserList class which defines up most of them, perhaps that would mean you don't have to override all of them.\n",
"There is no \"easy\" way to do so, especially if you want the lazy behaviour as stated. But still, there aren't that many logical operators, only three of them: __and__, ... | [
1,
1
] | [] | [] | [
"arrays",
"python",
"python_3.x",
"set"
] | stackoverflow_0001054428_arrays_python_python_3.x_set.txt |
Q:
How to get Python code to work with C++ App?
I have the following python 3 file:
import base64
import xxx
str = xxx.GetString()
str2 = base64.b64encode(str.encode())
str3 = str2.decode()
print str3
xxx is a module exported by some C++ code. This script does not work because calling Py_InitModule on this script r... | How to get Python code to work with C++ App? | I have the following python 3 file:
import base64
import xxx
str = xxx.GetString()
str2 = base64.b64encode(str.encode())
str3 = str2.decode()
print str3
xxx is a module exported by some C++ code. This script does not work because calling Py_InitModule on this script returns NULL. The weird thing is if I create a stub... | [
"I know everybody says this...but:\nBoost has an awesome library for exposing classes to python and getting data to and fro. If you're having problems, and looking for alternatives is an option I'd highly recommend the boost python library of the C interface. I've used them both, boost wins hands down imo. \n",
"... | [
1,
0,
0
] | [] | [] | [
"c++",
"python",
"string"
] | stackoverflow_0001978967_c++_python_string.txt |
Q:
custom prompt in python
I have a script which when first run creates a new thread which logs certain events. After the thread has been created, I ask for some input on user with the following code:
user_input = raw_input('>> ')
So when the script it run the user receives the '>>' prompt, but when the logger from ... | custom prompt in python | I have a script which when first run creates a new thread which logs certain events. After the thread has been created, I ask for some input on user with the following code:
user_input = raw_input('>> ')
So when the script it run the user receives the '>>' prompt, but when the logger from the created thread starts log... | [
"The problem is that your raw_input() is running on a completely different thread, and has no idea that the logger just spewed out some log messages. So there is no way for raw_input() to know that it should re-draw the prompt.\nI don't have any simple solution for you. All I can think of is for the logger thread... | [
2,
1
] | [] | [] | [
"command_line",
"python"
] | stackoverflow_0001982601_command_line_python.txt |
Q:
What's the best way to set up symbolic links to current installs, e.g python -> python2.6
What's the best way to set up symbolic links to current installs, e.g python -> python2.6?
I've just installed python2.6 through Macports at /opt/local/bin/python2.6, I'd now like to set up a symbolic link called python here ... | What's the best way to set up symbolic links to current installs, e.g python -> python2.6 | What's the best way to set up symbolic links to current installs, e.g python -> python2.6?
I've just installed python2.6 through Macports at /opt/local/bin/python2.6, I'd now like to set up a symbolic link called python here /usr/local/bin/. I then want to be able to add this line at the beginning of my pythons script... | [
"By default, MacPorts deliberately and carefully installs everything into a separate directory space: /opt/local. This ensures it does not conflict with anything installed as part of OS X or third-parties. To ensure that MacPorts-installed executables are found first, the recommended solution is to modify your sh... | [
4,
2
] | [
"Not sure about OSX, here is what I do on Ubuntu 9.04:\n>which python\n#/usr/bin/python\n\nJust replace that file with a sym link to the version of Python you actually want to use:\n>sudo ln -s /usr/bin/python2.6/python /usr/bin/python\n\n"
] | [
-3
] | [
"macos",
"macports",
"python"
] | stackoverflow_0001982176_macos_macports_python.txt |
Q:
What makes pylint think my class is abstract?
As I understand it, Python (2.5.2) does not have real support for abstract classes. Why is pylint complaining about this class being an "Abstract class not reference?" Will it do this for any class that has NotImplementedError thrown?
I have each class in its own file ... | What makes pylint think my class is abstract? | As I understand it, Python (2.5.2) does not have real support for abstract classes. Why is pylint complaining about this class being an "Abstract class not reference?" Will it do this for any class that has NotImplementedError thrown?
I have each class in its own file so if this is the case I guess I have no choice but... | [
"FWIW, raising NotImplementedError is enough to make pylint think this is an abstract class (which is absolutely correct). from logilab.org/card/pylintfeatures: W0223: Method %r is abstract in class %r but is not overridden Used when an abstract method (ie raise NotImplementedError) is not overridden in concrete c... | [
12,
1
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0001981978_pylint_python.txt |
Q:
Django, grouping query items
say I have such model:
class Foo(models.Model):
name = models.CharField("name",max_length=25)
type = models.IntegerField("type number")
after doing some query like Foo.objects.filter(), I want to group the query result as such:
[ [{"name":"jb","type:"whiskey"},{"name":"jack daniels... | Django, grouping query items | say I have such model:
class Foo(models.Model):
name = models.CharField("name",max_length=25)
type = models.IntegerField("type number")
after doing some query like Foo.objects.filter(), I want to group the query result as such:
[ [{"name":"jb","type:"whiskey"},{"name":"jack daniels","type:"whiskey"}],
[{"name":"abs... | [
"You can do this with the values method of a queryset:\nhttp://docs.djangoproject.com/en/1.1/ref/models/querysets/#values-fields\n\nvalues(*fields)\nReturns a ValuesQuerySet -- a QuerySet\n that evaluates to a list of\n dictionaries instead of model-instance\n objects.\n\n",
"Check out the regroup template tag... | [
3,
2,
2,
1
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0001981718_django_django_models_django_views_python.txt |
Q:
Clutter does not update screen outside of breakpoints
I have some code:
l1 = clutter.Label()
l1.set_position(100,100)
for i in range(0,10):
l1.set_text(str(i))
time.sleep(1)
That is designed to show a count from 1 to 10 seconds on the screen in clutter, but I'm getting a strange error. When I run the scri... | Clutter does not update screen outside of breakpoints | I have some code:
l1 = clutter.Label()
l1.set_position(100,100)
for i in range(0,10):
l1.set_text(str(i))
time.sleep(1)
That is designed to show a count from 1 to 10 seconds on the screen in clutter, but I'm getting a strange error. When I run the script normally the screen runs as it should do, but there is n... | [
"Not sure if you've already figured out the answer to this but:\nThe reason you are having this problem is because you are blocking the main thread (where all the drawing occurs) with your time.sleep() calls, preventing the library from redrawing the screen.\nE.g. your code is currently doing this:\n\nClutter redra... | [
4,
0
] | [] | [] | [
"clutter_gui",
"graphics",
"linux",
"python"
] | stackoverflow_0001446554_clutter_gui_graphics_linux_python.txt |
Q:
Parsing Python Code From Within Python?
We have an older C++ tool that generates some python code automatically. I tried to slog through the C++ source tool, today and pretty much wanted to shoot my self. The thing is what i want to do, is clean up the source created by the tool and link the classes to our interna... | Parsing Python Code From Within Python? | We have an older C++ tool that generates some python code automatically. I tried to slog through the C++ source tool, today and pretty much wanted to shoot my self. The thing is what i want to do, is clean up the source created by the tool and link the classes to our internal documentation system via adding sphinx tags... | [
"You may tokenize python code to parse individual tokens using tokenize module. e.g. Script to remove Python comments/docstrings \nor you can use the parser module \nor use ast module\n",
"Depending on your needs, you may also want to check out the 2to3 library. It was written to automatically facilitate the conv... | [
16,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0001978515_python.txt |
Q:
Regex for getting content between $ chars from a text
The problem:
I need to extract strings that are between $ characters from a block of text, but i'm a total n00b when it comes to regular expressions.
For instance from this text:
Li Europan lingues $es membres$ del sam familie. Lor $separat existentie es un$ my... | Regex for getting content between $ chars from a text | The problem:
I need to extract strings that are between $ characters from a block of text, but i'm a total n00b when it comes to regular expressions.
For instance from this text:
Li Europan lingues $es membres$ del sam familie. Lor $separat existentie es un$ myth.
i would like to get an array consisting of:
{'es membre... | [
"Import the re module, and use findall():\n>>> import re\n>>> p = re.compile('\\$(.*?)\\$')\n>>> s = \"apple $banana$ coconut $delicious ethereal$ funkytown\"\n>>> p.findall(s)\n['banana', 'delicious ethereal']\n\nThe pattern p represents a dollar sign (\\$), then a non-greedy match group ((...?)) which matches cha... | [
5,
3,
1,
1,
0
] | [
"Valid regex demo in Perl:\nmy $a = 'Li Europan lingues $es membres$ del sam familie. Lor $separat existentie es un$ myth.';\nmy @res;\nwhile ($a =~ /\\$([^\\$]+)\\$/gos)\n{\n push(@res, $1);\n}\n\nforeach my $item (@res)\n{\n print \"item: $item\\n\";\n}\n\nflags: s - treat all input text as single line, g - globa... | [
-1
] | [
"python",
"regex"
] | stackoverflow_0001983126_python_regex.txt |
Q:
Spam Filtering Forms Without Akismet
I'm curious if anyone out there knows of something perhaps like Akismet, but where content doesn't have to go off to a 3rd party server. In a situation with critically sensitive data (patient records for instance) I wouldn't necessarily want that information sent off to another... | Spam Filtering Forms Without Akismet | I'm curious if anyone out there knows of something perhaps like Akismet, but where content doesn't have to go off to a 3rd party server. In a situation with critically sensitive data (patient records for instance) I wouldn't necessarily want that information sent off to another server I don't have control over. I reall... | [
"Have you looked at Project Honey Pot? I think they have some public querying services that you can use.\nI think Project Honey Pot aims is to stop spam before it evens gets to your content processing routine (IP checking/headers analyzing/bot traps and such). It might fits what you're trying to do.\nAnother one I'... | [
4,
1
] | [] | [] | [
"django",
"python",
"spam_prevention"
] | stackoverflow_0001982277_django_python_spam_prevention.txt |
Q:
DBus-Cherrypy merge issue
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected.
Now, I'm merging the services into a single application. My prob... | DBus-Cherrypy merge issue | I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected.
Now, I'm merging the services into a single application. My problem is:
I cannot seem to get bo... | [
"Yes; don't use cherrypy.quickstart. Instead, unpack it:\ncherrypy.config.update(conf)\ncherrypy.tree.mount(USBREST())\ncherrypy.engine.start()\n\nQuickstart does the above, but finishes by calling engine.block(). If your program has some main loop other than CherryPy's, omit the call to engine.block and you should... | [
3,
3
] | [] | [] | [
"cherrypy",
"dbus",
"python"
] | stackoverflow_0001976622_cherrypy_dbus_python.txt |
Q:
who can tell me what can call the built-in functions in next code
i know some of this,ex.
__mod__ will be call /
__eq__will be call == > and <
but i don't know all.
def __nonzero__(self):
# an image is "true" if it contains at least one non-zero pixel
return self.im.getbbox() is not None
... | who can tell me what can call the built-in functions in next code | i know some of this,ex.
__mod__ will be call /
__eq__will be call == > and <
but i don't know all.
def __nonzero__(self):
# an image is "true" if it contains at least one non-zero pixel
return self.im.getbbox() is not None
def __abs__(self):
return self.apply("abs", self)
def __pos_... | [
"Section 3.4 of the Python Language Reference covers the magic methods.\n",
"See the Special Method Names section in the reference manual, including Basic Customization and Emulating Numeric Types.\n",
"__mod__ is called for %, not for / as you state:\n>>> class x(int):\n... def __mod__(self, y):\n... pri... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001983199_python.txt |
Q:
Python ASCII Graph Drawing
I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.
I saw NetworkX and igraph, but didn't see a way to output to ascii.
Do you have experience in this?
Thanks a lot!
Patrick
EDIT 1:
I actually... | Python ASCII Graph Drawing | I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.
I saw NetworkX and igraph, but didn't see a way to output to ascii.
Do you have experience in this?
Thanks a lot!
Patrick
EDIT 1:
I actually found a library doing what I ne... | [
"ascii-plotter might do what you want...\n",
"When you say 'simple network graph in ascii', do you mean something like this?\n.===. .===. .===. .===.\n| a |---| b |---| c |---| d |\n'===' '===' '---' '==='\n\nI suspect there are probably better ways to display whatever information it is that you have ... | [
3,
2,
1
] | [] | [] | [
"ascii",
"graph",
"python"
] | stackoverflow_0000834395_ascii_graph_python.txt |
Q:
i can't found '_weakref.py',where is '_weakref.py'
from _weakref import (
getweakrefcount,
getweakrefs,
ref,
proxy,
CallableProxyType,
ProxyType,
ReferenceType)
A:
It's not a Python-coded module, it's a C-coded Python-extension module.
You can read the extension module's C sour... | i can't found '_weakref.py',where is '_weakref.py' | from _weakref import (
getweakrefcount,
getweakrefs,
ref,
proxy,
CallableProxyType,
ProxyType,
ReferenceType)
| [
"It's not a Python-coded module, it's a C-coded Python-extension module.\nYou can read the extension module's C source code here.\n",
"_weakref is a C module that comes with Python. Having said that, you should never import a module starting with an underscore directly; import the Python module and let it deal wi... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0001983332_python.txt |
Q:
why my code make dead-loop,it is about 'iter(c,a)'
def c():
yield 222
yield 333
a=[1,2,3,4]
b=iter(c,333)
print a,b
for i in b:
print i
how can i get it.
A:
You need to provide the function (which will return the next value) to your iter() call. In your case, that's c().next rather than c.
This sni... | why my code make dead-loop,it is about 'iter(c,a)' | def c():
yield 222
yield 333
a=[1,2,3,4]
b=iter(c,333)
print a,b
for i in b:
print i
how can i get it.
| [
"You need to provide the function (which will return the next value) to your iter() call. In your case, that's c().next rather than c.\nThis snippet below works as expected by producing all the yielded values up to, but exclusive of, the terminating value.\ndef generator():\n yield 1\n yield 2\n yield 3\n ... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001983543_python.txt |
Q:
Python Encapsulate a function to Print to a variable
If I have a function that contains a lot of print statements:
ie.
def funA():
print "Hi"
print "There"
print "Friend"
print "!"
What I want to do is something like this
def main():
##funA() does not print to screen here
a = getPrint(funA()) ##where ... | Python Encapsulate a function to Print to a variable | If I have a function that contains a lot of print statements:
ie.
def funA():
print "Hi"
print "There"
print "Friend"
print "!"
What I want to do is something like this
def main():
##funA() does not print to screen here
a = getPrint(funA()) ##where getPrint is some made up function/object
print a ##print... | [
"You can do almost exactly what you want, as long as you don't mind a tiny syntax difference:\nimport cStringIO\nimport sys\n\ndef getPrint(thefun, *a, **k):\n savstdout = sys.stdout\n sys.stdout = cStringIO.StringIO()\n try:\n thefun(*a, **k)\n finally:\n v = sys.stdout.getvalue()\n sys.stdout = savst... | [
8,
3,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001983401_python.txt |
Q:
"Unknown column 'user_id' error in django view
I'm having an error where I am not sure what caused it.
Here is the error:
Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'user_id' in 'field list'")
Does anyone know why I am getting this error? I can't figure it out. Everything see... | "Unknown column 'user_id' error in django view | I'm having an error where I am not sure what caused it.
Here is the error:
Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'user_id' in 'field list'")
Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine.
My view code is below:
if "login" in... | [
"\nThe user_id field is the FK reference from Idea to User. It looks like you've changed your model, and not updated your database, then you'll have this kind of problem.\nDrop the old table, rerun syncdb.\nYour model tables get an id field by default. You can call it id in your queries. You can also use the syn... | [
6,
4,
0
] | [] | [] | [
"django",
"django_models",
"model",
"python",
"view"
] | stackoverflow_0000293300_django_django_models_model_python_view.txt |
Q:
wxPython GridSizer not attached to panel?
I'm trying to build a level editor for a game I'm working on. It pulls data from a flat file and then based on a byte-by-byte search it'll assemble a grid from pre-set tiles. This part of the app I should have no issues with. The problem is that my test version of the edit... | wxPython GridSizer not attached to panel? | I'm trying to build a level editor for a game I'm working on. It pulls data from a flat file and then based on a byte-by-byte search it'll assemble a grid from pre-set tiles. This part of the app I should have no issues with. The problem is that my test version of the editor which just loads a 16x16 grid of test tiles ... | [
"That's a lot of code and a lot of sizers! But I think maybe your ImgPanels should have the rightPanel as their parent, and not self.\nAlso, do you ever call self.SetSizer(self.h_sizer)? Didn't see that anywhere.\nI recommend creating portions of the layout in separate functions. Then you don't have to worry abou... | [
1
] | [] | [] | [
"image",
"panel",
"python",
"sizer",
"wxpython"
] | stackoverflow_0001983727_image_panel_python_sizer_wxpython.txt |
Q:
Having trouble understanding CherryPy
I read through the tutorial on the cherrypy website, and I'm still having some trouble understanding how it can be implemented in a modular, scalable way.
Could someone show me an example of how to have cherrypy receive a simple http post to its root, process the variable in ... | Having trouble understanding CherryPy | I read through the tutorial on the cherrypy website, and I'm still having some trouble understanding how it can be implemented in a modular, scalable way.
Could someone show me an example of how to have cherrypy receive a simple http post to its root, process the variable in some way, and respond dynamically using tha... | [
"from cherrypy import expose\n\nclass Adder:\n @expose\n def index(self):\n return '''<html>\n <body>\n <form action=\"add\">\n <input name=\"a\" /> + <input name=\"b\"> = \n <input type=\"submit\" />\n </form>... | [
3,
1
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0001982721_cherrypy_python.txt |
Q:
why my code 'next()' function not called in this example?
class a(object):
w={'a':'aaa','b':'bbb'}
def __iter__(self):
return iter(self.w)
def next(self):#this is not be called
print 'sss'
for i in self.w:
return i
b=a()
for i in b:
print i
and what is Relation... | why my code 'next()' function not called in this example? | class a(object):
w={'a':'aaa','b':'bbb'}
def __iter__(self):
return iter(self.w)
def next(self):#this is not be called
print 'sss'
for i in self.w:
return i
b=a()
for i in b:
print i
and what is Relations between __iter__ and next function.
thanks
| [
"In __iter__() you return an iterator on the dict stored in self.w, not on the class itself. Returning self instead will fix that.\n",
"I'm not entirely sure what you are asking, but the next() function isn't called because you never explicitly call it. You define __iter__, which gets called when you do:\nfor i i... | [
1,
1,
1
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0001984184_iterator_python.txt |
Q:
SimpleHTTPServer, shutdown and blocked request handlers
I have an instance of SimpleHTTPServer, however when I try to call
"shutdown" on it and there is a request handler that is blocked - the
whole process will block.
It does so even if I run the "serve_forever" method in a deamon
thread.
See example code at http... | SimpleHTTPServer, shutdown and blocked request handlers | I have an instance of SimpleHTTPServer, however when I try to call
"shutdown" on it and there is a request handler that is blocked - the
whole process will block.
It does so even if I run the "serve_forever" method in a deamon
thread.
See example code at http://codepad.org/cn8EYdfg
| [
"the shutdown method won't take affect until after the GET request is processed.\nAnd that request is blocking because of the queue operation.\nMaybe this will help: Stoppable Interruptable Python HTTP Server\n"
] | [
0
] | [] | [] | [
"http",
"multithreading",
"python"
] | stackoverflow_0001984159_http_multithreading_python.txt |
Q:
iPhone client with a python socket
i am creating a python server socket that sends data to the client reguarding files status... what i have is a list containing dictionaries:
[{'Status': '[2,5%]', 'File': 'SlackwareDVD.iso'},
{'Status': '[21,8%]', 'File': 'Ubuntu_x86.iso'}]
the socket, when asked, sends this da... | iPhone client with a python socket | i am creating a python server socket that sends data to the client reguarding files status... what i have is a list containing dictionaries:
[{'Status': '[2,5%]', 'File': 'SlackwareDVD.iso'},
{'Status': '[21,8%]', 'File': 'Ubuntu_x86.iso'}]
the socket, when asked, sends this data, obviously it is sent as a string typ... | [
"Seems perfectly suited for JSON. On the python side use any of the popular json libraries - for example, simplejson - to convert your python data to json, and on the iPhone side use an iPhone json library to convert it to local data representations. Here's an article that shows how to do that.\n",
"Convert it to... | [
3,
1,
1,
0
] | [] | [] | [
"iphone",
"objective_c",
"python",
"sockets",
"string"
] | stackoverflow_0001982375_iphone_objective_c_python_sockets_string.txt |
Q:
Remove row or column from 2D list if all values (in that row or column) are None
I have a grid (6 rows, 5 columns):
grid = [
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, Non... | Remove row or column from 2D list if all values (in that row or column) are None | I have a grid (6 rows, 5 columns):
grid = [
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None],
]
I augment the grid and it... | [
"It's not the fastest way but I think it's quite easy to understand:\ndef transpose(grid):\n return zip(*grid)\n\ndef removeBlankRows(grid):\n return [list(row) for row in grid if any(row)]\n\nprint removeBlankRows(transpose(removeBlankRows(transpose(grid))))\n\nOutput:\n[[{'some': 'thing'}, None, None],\n [N... | [
7,
1,
1,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001983902_list_python.txt |
Q:
How to use a certain Firefox profile in Python Selenium binding?
I'm looking for a solution similar to presented in this question, except it has to deal with python.
A:
the answer that was accepted is language agnostic. You will need to setup a firefox profile then when starting up selenium rc tell it to use th... | How to use a certain Firefox profile in Python Selenium binding? | I'm looking for a solution similar to presented in this question, except it has to deal with python.
| [
"the answer that was accepted is language agnostic. You will need to setup a firefox profile then when starting up selenium rc tell it to use that profile. \nYou just need to run your tests to use *firefox against the rc that has your profile and when the browser loads it will be the one you are after\n"
] | [
1
] | [] | [] | [
"firefox",
"python",
"selenium"
] | stackoverflow_0001964406_firefox_python_selenium.txt |
Q:
Filter with field has relationship in Django?
I have these models in Django:
class Customer(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200)
class Sale(models.Model):
def __unicode__(self):
return "Sale %s (%i)" % (self.type, self.id)
c... | Filter with field has relationship in Django? | I have these models in Django:
class Customer(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200)
class Sale(models.Model):
def __unicode__(self):
return "Sale %s (%i)" % (self.type, self.id)
customer = models.ForeignKey(Customer)
total = m... | [
"Have a look at aggregation documentation.\nI believe this should do the trick (only with version 1.1 or dev.):\nCustomer.objects.annotate(total=Sum('sale__total'))\n\nEDIT: You can also define a custom method for the class:\nclass Customer(models.Model):\n def __unicode__(self):\n return self.name\n n... | [
1
] | [] | [] | [
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0001985026_django_django_models_django_orm_python.txt |
Q:
Please discuss what are and why use portlets
Why would I want to use java portlets above tomcat and gwt?
Would portlets make it less- or un- necessary for me to use jsp and jsf?
Has Jboss been part of the portlet evolution culture? Does Jboss satisfy the portlet jsrs?
What portlet implementation/brand would run on... | Please discuss what are and why use portlets | Why would I want to use java portlets above tomcat and gwt?
Would portlets make it less- or un- necessary for me to use jsp and jsf?
Has Jboss been part of the portlet evolution culture? Does Jboss satisfy the portlet jsrs?
What portlet implementation/brand would run on gae java and gae python?
Are portlet specs due to... | [
"Portlets were a well-meaning but mis-guided attempt at a reusable widget API for web applications. Think of the personalised google home page, with the portlets like weather, news, mail, etc.\nUnfortunately, they made a bit of a mess of it. The Portlet API is a bit of a pig, a real barrel of not-fun, and there are... | [
6,
2,
1
] | [] | [] | [
".net",
"java",
"portlet",
"python"
] | stackoverflow_0001983282_.net_java_portlet_python.txt |
Q:
Python: Colorbands in the PIL-Module
I have this code from the PIL-handbook but I get an error message.
from PIL import Image, ImageEnhance, ImageChops
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild.jpg")
# split the image into individual bands
source = im.split()
R, G, B = 0, 1, 2
# select regions wher... | Python: Colorbands in the PIL-Module | I have this code from the PIL-handbook but I get an error message.
from PIL import Image, ImageEnhance, ImageChops
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild.jpg")
# split the image into individual bands
source = im.split()
R, G, B = 0, 1, 2
# select regions where red is less than 100
mask = source[R].po... | [
"Code runs fine for me, on a colour image.\nI would expect you to get the quoted error if you tried to operate on an image that only had one colour channel — ie. a black-and-white JPEG. How about im= im.convert('RGB') before the split, to be sure?\n"
] | [
3
] | [] | [] | [
"image",
"python"
] | stackoverflow_0001985178_image_python.txt |
Q:
Interaction between Java App and Python App
I have a python application which I cant edit its a black box from my point of view. The python application knows how to process text and return processed text.
I have another application written in Java which knows how to collect non processed texts.
Current state, the ... | Interaction between Java App and Python App | I have a python application which I cant edit its a black box from my point of view. The python application knows how to process text and return processed text.
I have another application written in Java which knows how to collect non processed texts.
Current state, the python app works in batch mode every x minutes.
I... | [
"I don't know nothing about Jython and the like. I guess it's the best solution if you can execute two programs without executing a new process each time the Java app needs to transform text. Anyway a simple proof of concept is to execute a separate process from the Java App to make it work. Next you can enhance th... | [
7,
6,
5,
0,
0,
0
] | [] | [] | [
"interaction",
"interface",
"java",
"python"
] | stackoverflow_0001984445_interaction_interface_java_python.txt |
Q:
Get request object in a db model?
Is there a way so that I can get access to request object, while saving a db object, without explicitly passing it e.g.
class RequestData(db.Model):
...
def put(self):
# autopopulate fields from current request
I just want a quick way to access request, instead of... | Get request object in a db model? | Is there a way so that I can get access to request object, while saving a db object, without explicitly passing it e.g.
class RequestData(db.Model):
...
def put(self):
# autopopulate fields from current request
I just want a quick way to access request, instead of passing it thru so many layers of view... | [
"Since Google AppEngine uses CGI protocol, the request information is all there in the environment variables (See CGI Environment Variables).\nYou can regenerate the request object just like this:\nreq = google.appengine.ext.webapp.Request(dict(os.environ))\n\n",
"There isn't any pre-built way of achieving this t... | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001952704_google_app_engine_python.txt |
Q:
Using for...else in Python generators
I'm a big fan of Python's for...else syntax - it's surprising how often it's applicable, and how effectively it can simplify code.
However, I've not figured out a nice way to use it in a generator, for example:
def iterate(i):
for value in i:
yield value
else:
... | Using for...else in Python generators | I'm a big fan of Python's for...else syntax - it's surprising how often it's applicable, and how effectively it can simplify code.
However, I've not figured out a nice way to use it in a generator, for example:
def iterate(i):
for value in i:
yield value
else:
print 'i is empty'
In the above ex... | [
"You're breaking the definition of a generator, which should throw a StopIteration exception when iteration is complete (which is automatically handled by a return statement in a generator function)\nSo:\ndef iterate(i):\n for value in i:\n yield value\n return\n\nBest to let the calling code handle th... | [
12,
5,
5,
4,
0
] | [
"What about simple if-else?\ndef iterate(i):\n if len(i) == 0: print 'i is empty'\n else:\n for value in i:\n yield value\n\n"
] | [
-2
] | [
"for_loop",
"generator",
"python",
"syntax",
"yield"
] | stackoverflow_0000603641_for_loop_generator_python_syntax_yield.txt |
Q:
Python asynchronous callbacks and generators
I'm trying to convert a synchronous library to use an internal asynchronous IO framework. I have several methods that look like this:
def foo:
....
sync_call_1() # synchronous blocking call
....
sync_call_2() # synchronous blocking call
....
return bar
... | Python asynchronous callbacks and generators | I'm trying to convert a synchronous library to use an internal asynchronous IO framework. I have several methods that look like this:
def foo:
....
sync_call_1() # synchronous blocking call
....
sync_call_2() # synchronous blocking call
....
return bar
For each of the synchronous functions (sync_call_*... | [
"UPDATE: take this with a grain of salt, as I'm out of touch with modern python async developments, including gevent and asyncio and don't actually have serious experience with async code.\n\nThere are 3 common approaches to thread-less async coding in Python:\n\nCallbacks - ugly but workable, Twisted does this wel... | [
10,
2,
2
] | [] | [] | [
"asynchronous",
"generator",
"python"
] | stackoverflow_0001805958_asynchronous_generator_python.txt |
Q:
How can I approximate Python's or operator for set comparison in Scala?
After hearing the latest Stack Overflow podcast, Peter Norvig's compact Python spell-checker intrigued me, so I decided to implement it in Scala if I could express it well in the functional Scala idiom, and also to see how many lines of code i... | How can I approximate Python's or operator for set comparison in Scala? | After hearing the latest Stack Overflow podcast, Peter Norvig's compact Python spell-checker intrigued me, so I decided to implement it in Scala if I could express it well in the functional Scala idiom, and also to see how many lines of code it would take.
Here's the whole problem. (Let's not compare lines of code yet.... | [
"I'm not sure why you're attempting to use lazy evaluation for known rather than simply using a stream as oxbow_lakes illustrated. A better way of doing what he did:\ndef correct(word: String) = {\n import Stream._\n\n val str = cons(known(Set(word)), \n cons(known(edits1(word)),\n cons(kno... | [
6,
4,
3,
2,
0
] | [] | [] | [
"anonymous_function",
"python",
"scala"
] | stackoverflow_0001780459_anonymous_function_python_scala.txt |
Q:
registering python com server
I have a problem when registering a Python com server, I got a message box that says :
Invalid command line argument. This
programs provides LocalServer com
support for Python COM objects. It is
typically run automatically by COM,
passing passing as arguments The
ProgID o... | registering python com server | I have a problem when registering a Python com server, I got a message box that says :
Invalid command line argument. This
programs provides LocalServer com
support for Python COM objects. It is
typically run automatically by COM,
passing passing as arguments The
ProgID or CLSID of the Python
server(s) t... | [
"Just an idea but have you checked the value of the LocalServer32 registry key of your COM server. see http://msdn.microsoft.com/en-us/library/ms683844%28VS.85%29.aspx\nAny difference in the ways you've installed it on this machine? Does the path contain blanks?\nI hope it helps\n"
] | [
0
] | [] | [] | [
"com",
"python",
"pywin32"
] | stackoverflow_0001982540_com_python_pywin32.txt |
Q:
How to generate permutations of a list without "reverse duplicates" in Python using generators
This is related to question How to generate all permutations of a list in Python
How to generate all permutations that match following criteria: if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]... | How to generate permutations of a list without "reverse duplicates" in Python using generators | This is related to question How to generate all permutations of a list in Python
How to generate all permutations that match following criteria: if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2,1]), they are considered equal and only one of them should be in final result.
Example:
permutations_w... | [
"I have a marvelous followup to SilentGhost's proposal - posting a separate answer since the margins of a comment would be too narrow to contain code :-)\nitertools.permutations is built in (since 2.6) and fast. We just need a filtering condition that for every (perm, perm[::-1]) would accept exactly one of them. ... | [
14,
12,
4,
3,
2,
2,
2,
1,
1
] | [
"itertools.permutations does exactly what you want. you might make of use of reversed built-in as well\n"
] | [
-2
] | [
"algorithm",
"combinatorics",
"generator",
"python"
] | stackoverflow_0000960557_algorithm_combinatorics_generator_python.txt |
Q:
What does the “|” sign mean in Python?
This question originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve.
A:
In Python, the '|' operator is defined by default on integer types and set types.
If ... | What does the “|” sign mean in Python? | This question originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve.
| [
"In Python, the '|' operator is defined by default on integer types and set types. \nIf the two operands are integers, then it will perform a bitwise or, which is a mathematical operation.\nIf the two operands are set types, the '|' operator will return the union of two sets.\na = set([1,2,3])\nb = set([2,3,4])\nc... | [
27,
1,
0
] | [] | [] | [
"python",
"syntax_rules"
] | stackoverflow_0000417396_python_syntax_rules.txt |
Q:
What are the memory requirements for large python list?
I was doing a foolish thing like:
from itertools import *
rows = combinations(range(0, 1140), 17)
all_rows = []
for row in rows:
all_rows.append(row)
No surprise; I run out of memory address space (32 bit python 3.1)
My question is: how do I calculate ho... | What are the memory requirements for large python list? | I was doing a foolish thing like:
from itertools import *
rows = combinations(range(0, 1140), 17)
all_rows = []
for row in rows:
all_rows.append(row)
No surprise; I run out of memory address space (32 bit python 3.1)
My question is: how do I calculate how much memory address space I will need for a large list? In ... | [
"There's a handy function sys.getsizeof() (since Python 2.6) that helps with this:\n>>> import sys\n>>> sys.getsizeof(1) # integer\n12\n>>> sys.getsizeof([]) # empty list\n36\n>>> sys.getsizeof(()) # empty tuple\n28\n>>> sys.getsizeof((1,)) # tuple with one element\n32\n\nFrom that you can see that each integer t... | [
11,
4,
3,
1
] | [] | [] | [
"32bit_64bit",
"memory_management",
"python"
] | stackoverflow_0001985975_32bit_64bit_memory_management_python.txt |
Q:
Gruber’s URL Regular Expression in Python
How do I rewrite this new way to recognise addresses to work in Python?
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
A:
The original source for that states "This pattern should work in most modern regex implementations" and specifically Perl. Pyth... | Gruber’s URL Regular Expression in Python | How do I rewrite this new way to recognise addresses to work in Python?
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
| [
"The original source for that states \"This pattern should work in most modern regex implementations\" and specifically Perl. Python's regex implementation is modern and similar to Perl's but is missing the [:punct:] character class. You can easily build that using this:\n>>> import string, re\n>>> pat = r'\\b(([... | [
12,
5,
2
] | [] | [] | [
"gruber",
"python",
"regex"
] | stackoverflow_0001986059_gruber_python_regex.txt |
Q:
Which is more fundamental: Python functions or Python object-methods?
I am trying to get a conceptual understanding of the nature of Python functions and methods. I get that functions are actually objects, with a method that is called when the function is executed. But is that function-object method actually anoth... | Which is more fundamental: Python functions or Python object-methods? | I am trying to get a conceptual understanding of the nature of Python functions and methods. I get that functions are actually objects, with a method that is called when the function is executed. But is that function-object method actually another function?
For example:
def fred():
pass
If I look at dir(fred), I s... | [
"Short answer: both are fundamental, .__call__() on functions is just a virtual trick.\n\nThe rest of this answer is a bit complicated. You don't have to understand it, but I find the subject interesting. Be warned that I'm going to present a series of lies, progressively fixing them.\nLong answer\nAt the most fu... | [
4,
2,
1
] | [] | [] | [
"function",
"object",
"python"
] | stackoverflow_0001985635_function_object_python.txt |
Q:
Finding all classes that derive from a given base class in python
I'm looking for a way to get a list of all classes that derive from a particular base class in Python.
More specifically I am using Django and I have a abstract base Model and then several Models that derive from that base class...
class Asset(mode... | Finding all classes that derive from a given base class in python | I'm looking for a way to get a list of all classes that derive from a particular base class in Python.
More specifically I am using Django and I have a abstract base Model and then several Models that derive from that base class...
class Asset(models.Model):
name = models.CharField(max_length=500)
last_update ... | [
"Asset.__subclasses__() gives the immediate subclasses of Asset, but whether that's sufficient depends on whether that immediate part is a problem for you -- if you want all descendants to whatever number of levels, you'll need recursive expansion, e.g.:\ndef descendants(aclass):\n directones = aclass.__subclasses... | [
9
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001986335_django_python.txt |
Q:
Why Unexpected Indent?
Why does this happen?
def LoadPackageList():
try:
#Attempts to load package list... Adds each neccessary attribute into array
print("Loading Package List... please wait")
packages = []
packagelisturl = os.getcwd() + "packages.list"
dom = minidom.pa... | Why Unexpected Indent? | Why does this happen?
def LoadPackageList():
try:
#Attempts to load package list... Adds each neccessary attribute into array
print("Loading Package List... please wait")
packages = []
packagelisturl = os.getcwd() + "packages.list"
dom = minidom.parse(urllib.urlopen(packageli... | [
"Try running it through python -t and see if there is a mixture of tabs and spaces somewhere in there.\nAs a side note: use optparse to process command line parameters. It will make your life much easier and produce a nice consistent interface.\n",
"The code you posted works just fine. Therefore, check the lines ... | [
7,
4,
3
] | [] | [] | [
"indentation",
"python"
] | stackoverflow_0001983405_indentation_python.txt |
Q:
Where should I place the one-time operation operation in the Django framework?
I want to perform some one-time operations such as to start a background thread and populate a cache every 30 minutes as initialize action when the Django server is started, so it will not block user from visiting the website. Where sho... | Where should I place the one-time operation operation in the Django framework? | I want to perform some one-time operations such as to start a background thread and populate a cache every 30 minutes as initialize action when the Django server is started, so it will not block user from visiting the website. Where should I place all this code in Django?
Put them into the setting.py file does not wor... | [
"I just create standalone scripts and schedule them with cron. Admittedly it's a bit low-tech, but It Just Works. Just place this at the top of a script in your projects top-level directory and call as needed.\n#!/usr/bin/env python\nfrom django.core.management import setup_environ\nimport settings\nsetup_environ(s... | [
6,
4,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001986060_django_python.txt |
Q:
Python, PyTables - taking advantage of in-kernel searching
I have HDF5 files with multiple groups, where each group contains a data set with >= 25 million rows. At each time step of simulation, each agent outputs the other agents he/she sensed at that time step. There are ~2000 agents in the scenario and thousan... | Python, PyTables - taking advantage of in-kernel searching | I have HDF5 files with multiple groups, where each group contains a data set with >= 25 million rows. At each time step of simulation, each agent outputs the other agents he/she sensed at that time step. There are ~2000 agents in the scenario and thousands of time steps; the O(n^2) nature of the output explains the h... | [
"If you have N=~2k agents, I suggest putting all sightings into a numpy array of size NxN. This easily fits in memory (around 16 meg for integers). Just store a 1 wherever a sighting occurred.\nAssume that you have an array sightings. The first coordinate is Sensing, the second is Sensed. Assume you also have 1-... | [
2
] | [] | [] | [
"optimization",
"pytables",
"python",
"query_optimization"
] | stackoverflow_0001971870_optimization_pytables_python_query_optimization.txt |
Q:
Create a text file in python using values from a sqlite database
I am trying to build a text file which is a combination of predefined strings and variable values which I would like to take from a pre-existing sqlite database. The general format of each line of the text file is as such:
constraint n: value i < v... | Create a text file in python using values from a sqlite database | I am trying to build a text file which is a combination of predefined strings and variable values which I would like to take from a pre-existing sqlite database. The general format of each line of the text file is as such:
constraint n: value i < value j
Where n is an integer which will increase by one every line. V... | [
"The simplest, unoptimized approach would be something like:\nimport sqlite3\nconn = sqlite3.connect('whatever.file')\nc = conn.cursor\n\nout = open('results.txt', 'w')\nn = 1\n\nfor x in range(1, 30):\n for y in range(1, 30):\n c.execute('select value from i where row=? and column=?', (x, y))\n i = c.fetcho... | [
3,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0001986978_python_sqlite.txt |
Q:
Data Structures in Python
All the books I've read on data structures so far seem to use C/C++, and make heavy use of the "manual" pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to implement efficient data structures in thi... | Data Structures in Python | All the books I've read on data structures so far seem to use C/C++, and make heavy use of the "manual" pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to implement efficient data structures in this language, and is there any re... | [
"Python gives you some powerful, highly optimized data structures, both as built-ins and as part of a few modules in the standard library (lists and dicts, of course, but also tuples, sets, arrays in module array, and some other containers in module collections).\nCombinations of these data structures (and maybe so... | [
25,
14,
10,
3,
2,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0001986712_data_structures_python.txt |
Q:
cherrypy: accessing the URI/route parameters inside a tool hook?
I have a tool hook setup for 'before_finalize' like so:
def before_finalize():
d = cherrypy.response.body
location = '%s/views' % cherrypy.request.app.config['/']['application_path']
cherrypy.response.body = Template(file='%s/index.tmpl' ... | cherrypy: accessing the URI/route parameters inside a tool hook? | I have a tool hook setup for 'before_finalize' like so:
def before_finalize():
d = cherrypy.response.body
location = '%s/views' % cherrypy.request.app.config['/']['application_path']
cherrypy.response.body = Template(file='%s/index.tmpl' % location).respond()
What I need to do is find out inside that hook ... | [
"cherrypy.url will get you the complete URI, but I suspect that's not quite what you're looking for...why do you need it? If you're trying to form your 'location' variable based on the URI, you probably want path_info instead of the complete URI:\nlocation = '%s/views' % request.app.config['/']['application_path']\... | [
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0001987042_cherrypy_python.txt |
Q:
How to get Permissions to inherit from User's Groups?
I'm trying to figure out Django Groups and the documentation is pretty bare on the site.
For example, you can use the decorator permission_required() to check the permissions, however, this only checks if you have assigned permissions directly. I have assigned... | How to get Permissions to inherit from User's Groups? | I'm trying to figure out Django Groups and the documentation is pretty bare on the site.
For example, you can use the decorator permission_required() to check the permissions, however, this only checks if you have assigned permissions directly. I have assigned Users to Groups which have Permissions setup. When using ... | [
"Django does automatically inherit permissions from groups. There may be some problem in your installation or database (such as using a custom permission without having done a syncdb), or you might be passing the wrong argument to the decorator.\nIf you have a model named post in an app named blog for example, the... | [
5
] | [] | [] | [
"django",
"django_authentication",
"django_permissions",
"python"
] | stackoverflow_0001987496_django_django_authentication_django_permissions_python.txt |
Q:
What does this code mean: "print >> sys.stderr"
print >> sys.stderr, "Error in atexit._run_exitfuncs:"
Why print '>>' in front of sys.stderr?
Thanks.
A:
This syntax means writes to a file object (sys.stderr in this case) instead of standard output. [Link]
In Python 3.0, print becomes a function instead of a sta... | What does this code mean: "print >> sys.stderr" | print >> sys.stderr, "Error in atexit._run_exitfuncs:"
Why print '>>' in front of sys.stderr?
Thanks.
| [
"This syntax means writes to a file object (sys.stderr in this case) instead of standard output. [Link]\nIn Python 3.0, print becomes a function instead of a statement: [Link]\nprint(\"Error in atexit._run_exitfuncs:\", file=sys.stderr)\n\n",
"From the Python documentation:\n\nprint also has an extended form,\n ... | [
39,
6
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0001987626_python_syntax.txt |
Q:
Any difference between 'b' and 'c'?
class a(object):
b = 'bbbb'
def __init__(self):
self.c = 'cccc'
I think they are the same; is there any difference?
A:
Yes, there is a difference.
b is a class variable... one that is shared by all instances of a, while c is an instance variable which will exi... | Any difference between 'b' and 'c'? | class a(object):
b = 'bbbb'
def __init__(self):
self.c = 'cccc'
I think they are the same; is there any difference?
| [
"Yes, there is a difference.\nb is a class variable... one that is shared by all instances of a, while c is an instance variable which will exist independantly for each instance.\n",
"b is a class variable, while c is a instance variable.\n>>> a.b\n'bbbb'\n>>> a.c\nTraceback (most recent call last):\n File \"<st... | [
9,
5,
2,
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0001987703_class_python.txt |
Q:
Is there any module that allows Django/Python to work with gnupg?
I was wondering if there's any django module, or in such case any python module, that will allow me to create my own application to manage the creation, administration, etc of GnuPG keys, as well as the ability to sign and encrypt documents through ... | Is there any module that allows Django/Python to work with gnupg? | I was wondering if there's any django module, or in such case any python module, that will allow me to create my own application to manage the creation, administration, etc of GnuPG keys, as well as the ability to sign and encrypt documents through this application?
If there's no such module, how can I do that?
Thank y... | [
"I wrote a Django app django-email-extras that does exactly what you're looking for. It lets users manage GPG keys via the Django admin and encrypts all mail to recipients with valid keys and includes support for multi-part templated emails with attachments.\n",
"GnuPGInterface can do all of that -- it's essentia... | [
4,
2
] | [] | [] | [
"django",
"gnupg",
"python"
] | stackoverflow_0001450036_django_gnupg_python.txt |
Q:
Gracefully handling "MySQL has gone away"
I'm writing a small database adapter in Python, mostly for fun. I'm trying to get the code to gracefully recover from a situation where the MySQL connection "goes away," aka wait_timeout is exceeded. I've set wait_timeout at 10 so I can try this.
Here's my code:
def sele... | Gracefully handling "MySQL has gone away" | I'm writing a small database adapter in Python, mostly for fun. I'm trying to get the code to gracefully recover from a situation where the MySQL connection "goes away," aka wait_timeout is exceeded. I've set wait_timeout at 10 so I can try this.
Here's my code:
def select(self, query, params=[]):
try:
... | [
"Can't see from the code, but my guess would be that the db._get_cxn() method is doing some kind of connection pooling and returning the existing connection object instead of making a new one. Is there not a call you can make on db to flush the existing useless connection? (And should you really be calling an inter... | [
12
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001987701_mysql_python.txt |
Q:
Convert an image to RGBA mode with python
I tried the code listed at Using PIL to make all white pixels transparent to convert some .ico files to .png images with transparent background.
It doesn't work on all .ico images, some time it just outputs an image with black background.
Sample .ico files can be located h... | Convert an image to RGBA mode with python | I tried the code listed at Using PIL to make all white pixels transparent to convert some .ico files to .png images with transparent background.
It doesn't work on all .ico images, some time it just outputs an image with black background.
Sample .ico files can be located here
| [
"i tried that script on all icons you put there . and it worked fine. some times it represents transparency with a black background . to make sure that the background is fully transparent . open it in photoshop. \nEdit : make sure that your icon has an alpha channel.\n"
] | [
0
] | [] | [] | [
"image",
"python",
"python_imaging_library",
"transparent"
] | stackoverflow_0001987848_image_python_python_imaging_library_transparent.txt |
Q:
Why is my Python version slower than my Perl version?
I've been a Perl guy for over 10 years but a friend convinced me to try Python and told me how much faster it is than Perl. So just for kicks I ported an app I wrote in Perl to Python and found that it runs about 3x slower. Initially my friend told me that I mu... | Why is my Python version slower than my Perl version? | I've been a Perl guy for over 10 years but a friend convinced me to try Python and told me how much faster it is than Perl. So just for kicks I ported an app I wrote in Perl to Python and found that it runs about 3x slower. Initially my friend told me that I must have done it wrong, so I rewrote and refactored until I ... | [
"The nit-picking answer is that you should compare it to idiomatic Python:\n\nThe original code takes 34 seconds on my machine.\nA for loop (FlorianH's answer) with += and xrange() takes 21. \nPutting the whole thing in a function reduces it to 9 seconds!\nThat's much faster than Perl (15 seconds on my machine)!\n... | [
52,
9,
8,
8,
8,
5,
2,
1,
0
] | [] | [] | [
"performance",
"perl",
"python"
] | stackoverflow_0001984871_performance_perl_python.txt |
Q:
Variables and function
Hey all, is it possible to call a function value instead of calling the whole function?As, if i call the whole function, it will run unnecessarily which i do not want.
For example:
def main():
# Inputing the x-value for the first start point of the line
start_point_x_1()
# Inputi... | Variables and function | Hey all, is it possible to call a function value instead of calling the whole function?As, if i call the whole function, it will run unnecessarily which i do not want.
For example:
def main():
# Inputing the x-value for the first start point of the line
start_point_x_1()
# Inputing the x-value for the 2nd e... | [
"Change\nstart_point_x_1()\n\nto\nx0 = start_point_x_1()\n\nSimilarly, do\nx2 = end_point_x_2()\n\nand finally:\nfirst_calculated_point()\n\nbecomes\nfirst_calculated_point(x0, x2)\n\nThe definition of the function changes to:\ndef first_calculated_point(x0, x2):\n a = int(x2) - int(x0)\n lamda_0 = 0\n x ... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001988533_python.txt |
Q:
How do I get datetime from date object python?
How do I get datetime from date object python?
I think of
import datetime as dt
today = dt.date.today()
date_time = dt.datetime(today.year, today.month, today.day)
Any easier solution?
A:
There are a few ways to do this:
mydatetime = datetime.datetime(d.year, d.mo... | How do I get datetime from date object python? | How do I get datetime from date object python?
I think of
import datetime as dt
today = dt.date.today()
date_time = dt.datetime(today.year, today.month, today.day)
Any easier solution?
| [
"There are a few ways to do this:\nmydatetime = datetime.datetime(d.year, d.month, d.day)\n\nor\nmydatetime = datetime.combine(d, datetime.time())\n\nor \nmydatetime = datetime.datetime.fromordinal(d.toordinal())\n\nI think the first is the most commonly used.\n",
"Try this:\nimport datetime\n\nprint 'Now :', ... | [
10,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0001988599_datetime_python.txt |
Q:
exception not getting caught when not in the right package in python
EDIT:
OK, I managed to isolate the bug and the exact, complete code to to reproduce it. But it appears either something that's by design, or a bug in python.
Create two sibling packages: admin & General, each with it's own __init__.py, of course.... | exception not getting caught when not in the right package in python | EDIT:
OK, I managed to isolate the bug and the exact, complete code to to reproduce it. But it appears either something that's by design, or a bug in python.
Create two sibling packages: admin & General, each with it's own __init__.py, of course.
In the package admin put the file 'test.py' with the following code:
from... | [
"import admin.RunStoppedException\n\nThis is an ambiguous relative import. Do you mean RunStoppedException from the admin top-level module? Or from mypackage.admin when you're in a package? If your current working directory (which is added to the module search path) happens to be inside the package, it could be eit... | [
7,
0,
0
] | [] | [] | [
"exception",
"package",
"python"
] | stackoverflow_0001988475_exception_package_python.txt |
Q:
Sphinx 0.6.3: The languages module cannot be found
I receive the following error message when I try to use the sphinx-quickstart generated make.bat command:
make html
Error: The languages module cannot be found. Did you install Sphinx and its dependencies correctly?
I tried running the sphinx-build command and r... | Sphinx 0.6.3: The languages module cannot be found | I receive the following error message when I try to use the sphinx-quickstart generated make.bat command:
make html
Error: The languages module cannot be found. Did you install Sphinx and its dependencies correctly?
I tried running the sphinx-build command and received the same error.
I am using Python 2.6.4 on Wind... | [
"Grepping through the sphinx package for \"languages\", the only relevant import is:\n/usr/lib/pymodules/python2.5/sphinx/environment.py:from docutils.parsers.rst.languages import en as english\n\nSo most likely there's something wrong with your docutils installation. Admittedly, the error message would be more hel... | [
0
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0001987658_python_python_sphinx.txt |
Q:
Reading values with raw_input in Python
I am trying to do integration in Python but whenever I key in a value my outputs always results in 0. What the reason?
E.g.:
def main():
eq_of_form()
value_of_a()
value_of_b()
value_of_c()
value_of_m()
value_of_n()
value_of_x()
area_under_graph()
d... | Reading values with raw_input in Python | I am trying to do integration in Python but whenever I key in a value my outputs always results in 0. What the reason?
E.g.:
def main():
eq_of_form()
value_of_a()
value_of_b()
value_of_c()
value_of_m()
value_of_n()
value_of_x()
area_under_graph()
def eq_of_form():
print "Eq of the form y =... | [
"Your code at the start is wrong. You need to assign your variables after you read the user input:\nvalue_of_a()\n\nshould be:\na = value_of_a()\n\nIt is also unnecessary to write a separate function for inputting each variable. You could instead have a function that takes a parameter:\ndef get_user_value(name):\n ... | [
5,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001988733_python.txt |
Q:
Qt Python - report in toolbox: QTextDocument and QPainter
I want to build multiple documents report using toolbox. Two pages is an option get a start. Formatting is ok, and can be worked latter.
I tried using QTextDocument in Html, and alternatively QPainter.
Of course, to make a test and keep things simple, I jus... | Qt Python - report in toolbox: QTextDocument and QPainter | I want to build multiple documents report using toolbox. Two pages is an option get a start. Formatting is ok, and can be worked latter.
I tried using QTextDocument in Html, and alternatively QPainter.
Of course, to make a test and keep things simple, I just ask in Qt to show the report title displayed on top of the do... | [
"For page1, the document needs to be displayed by a widget. Add the following to that function\n textEdit = QtGui.QTextEdit(self.page1)\n textEdit.setDocument(document)\n layout = QtGui.QVBoxLayout(self.page1)\n layout.addWidget(textEdit)\n\nFor page2, painting on a widget must be in response to a paint... | [
1
] | [] | [] | [
"html",
"python",
"qpainter",
"qt",
"reportviewer"
] | stackoverflow_0001988150_html_python_qpainter_qt_reportviewer.txt |
Q:
Managing Setup code with TimeIt
As part of a pet project of mine, I need to test the performance of various different implementations of my code in Python. I anticipate this to be something I do alot of, and I want to try to make the code I write to serve this aim as easy to update and modify as possible.
It's sti... | Managing Setup code with TimeIt | As part of a pet project of mine, I need to test the performance of various different implementations of my code in Python. I anticipate this to be something I do alot of, and I want to try to make the code I write to serve this aim as easy to update and modify as possible.
It's still in its infancy at the moment, but ... | [
"Use triple quotes \"\"\"\nsetup_code = \"\"\"\n from PerformanceTests.Vectors import NaiveVector\n left = NaiveVector([1,0,0])\n right = NaiveVector([0,1,0])\n\"\"\"\n\nAnother interesting method is provided in the docs of timeit:\ndef test():\n \"Stupid test function\"\n L = []\n for i in range(100):\... | [
3,
0
] | [] | [] | [
"performance",
"python",
"timeit"
] | stackoverflow_0001988127_performance_python_timeit.txt |
Q:
Why django contains a lot of '__init__.py'?
Many directories in a django project contain a __init__.py and I think it will be used as initialization for something. Where is this __init__.py used?
A:
Python doesn't take every subdirectory of every directory in sys.path to necessarily be a package: only those with... | Why django contains a lot of '__init__.py'? | Many directories in a django project contain a __init__.py and I think it will be used as initialization for something. Where is this __init__.py used?
| [
"Python doesn't take every subdirectory of every directory in sys.path to necessarily be a package: only those with a file called __init__.py. Consider the following shell session:\n$ mkdir adir\n$ echo 'print \"hello world\"' > adir/helo.py\n$ python -c 'import adir.helo'\nTraceback (most recent call last):\n Fil... | [
11,
7
] | [] | [] | [
"django",
"module",
"python"
] | stackoverflow_0001988149_django_module_python.txt |
Q:
why my 'time' class has not 'tzset' attribute
my code:
import time
print hasattr(time.tzset)#error
and why someone do this like next:
if hasattr(time, 'tzset'):
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
... | why my 'time' class has not 'tzset' attribute | my code:
import time
print hasattr(time.tzset)#error
and why someone do this like next:
if hasattr(time, 'tzset'):
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = self.TIME_ZONE
t... | [
"See the docs for tzset: they clearly say\n\nAvailability: Unix.\n\nso you would have it in, say, MacOSX, Solaris, or Linux, but not on Windows.\nAlso: there is no such thing as \"your time class\", despite your Q's title: the time you're trying to use is a module, not a class.\nAnd finally, as @Daniel says, your f... | [
11,
3,
2
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0001988182_python_syntax.txt |
Q:
Asyncore not working properly with Tkinter GUI
At this point I'm still a noob when it comes to GUI and network programming so I'm hoping this will be a very simple fix. I've got a very basic understanding of the tkinter and asyncore modules having built a handful of programs in each of them, however I'm having tro... | Asyncore not working properly with Tkinter GUI | At this point I'm still a noob when it comes to GUI and network programming so I'm hoping this will be a very simple fix. I've got a very basic understanding of the tkinter and asyncore modules having built a handful of programs in each of them, however I'm having trouble using both of them together in a program. I put... | [
"There are several problems here, and I'm not sure which one it is.\nasyncore.loop is a function that never returns, when things are working properly. root.mainloop is probably a function that never returns until you close the window. So things are likely to go wrong because at some point one loop will be starved b... | [
2,
0
] | [] | [] | [
"asyncore",
"python",
"tkinter"
] | stackoverflow_0001988286_asyncore_python_tkinter.txt |
Q:
pkg_resources not found after installing setuptools
I am trying to compile and install python2.6.4 on Debian 5.0.3 (64bit). I installed using 'make altinstall' as I want to keep python 2.5.2 that comes with Deb5.0 as my default python.
Following this, I installed setuptools 0.6c11 using the command 'sudo sh setupt... | pkg_resources not found after installing setuptools | I am trying to compile and install python2.6.4 on Debian 5.0.3 (64bit). I installed using 'make altinstall' as I want to keep python 2.5.2 that comes with Deb5.0 as my default python.
Following this, I installed setuptools 0.6c11 using the command 'sudo sh setuptools-0.6c11-py2.6.egg --prefix=/usr/local'. However, afte... | [
"Packaging and package integration is tricky. Debian has Python 2.6, but for some internal reason it is only in the experimental branch:\n$ rmadison python2.6\n python2.6 | 2.6.2-2 | experimental | source, ia64\n python2.6 | 2.6.4-1 | experimental | source, alpha, amd64, armel, hppa, \\\n ... | [
0
] | [] | [] | [
"debian",
"pkg_resources",
"python",
"setuptools"
] | stackoverflow_0001989355_debian_pkg_resources_python_setuptools.txt |
Q:
Repeating regex groups
I'm trying to get some information from a web site. The information I want is in a table so I made a regex but I don't know the right way to simplify it.
The following are two parts of my regex that I would like to simplify:
<br>(.*)<br>(.*)<br>(.*)
<tr><td>(.+)r>(.+)r>(.+)r>(.+).+</td></tr... | Repeating regex groups | I'm trying to get some information from a web site. The information I want is in a table so I made a regex but I don't know the right way to simplify it.
The following are two parts of my regex that I would like to simplify:
<br>(.*)<br>(.*)<br>(.*)
<tr><td>(.+)r>(.+)r>(.+)r>(.+).+</td></tr> # This part should be repe... | [
"RegEx match open tags except XHTML self-contained tags\n\"Have you tried using an XML parser instead?\"\nEDIT: This is the way to go: Beautiful Soup \n",
"This is the wrong way to go unless you're trying to scrape some data out of a tiny fragment. \nIt would be much better if you used a tolerant HTML. BeautifulS... | [
3,
3,
1
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0001989463_html_python_regex.txt |
Q:
Problems assigning dict values to variables
I am struggling with something that must be one of those 'it is so obvious I am an idiot' problems. I have a csv file that I want to read in and use to create individual 'tables'. I have a variable (RID) that marks the beginning of a new 'table'.
I can't get my indic... | Problems assigning dict values to variables | I am struggling with something that must be one of those 'it is so obvious I am an idiot' problems. I have a csv file that I want to read in and use to create individual 'tables'. I have a variable (RID) that marks the beginning of a new 'table'.
I can't get my indicator variable (currentRow) to advance as I finish... | [
"In the line:\ncurrrentRow=int(line['RID'])\n\nyou have three rs in currrentRow. Reduce them to just two, and things should improve.\n",
"One solution is to add the following somewhere inside the loop:\ncurrentRow += 1\n\nHowever, a better solution may be to use enumerable:\nfor currentRow, line in csv.DictReader... | [
7,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0001989511_csv_python.txt |
Q:
Python - reading checkboxes
I have a few checkboxes with common name and individual variables (ID).
How can I in python read them as list?
Now I'm using
checkbox= request.POST["common_name"]
It isn't work properly, checkbox variable store only the last checked box instead of any list or something.
A:
If you w... | Python - reading checkboxes | I have a few checkboxes with common name and individual variables (ID).
How can I in python read them as list?
Now I'm using
checkbox= request.POST["common_name"]
It isn't work properly, checkbox variable store only the last checked box instead of any list or something.
| [
"If you were using WebOB, request.POST.getall('common_name') would give you a list of all the POST variables with the name 'common_name'. See the WebOB docs for more.\nBut you aren't - you're using Django. See the QueryDict docs for several ways to do this - request.POST.getlist('common_name') is one way to do it.\... | [
6,
2,
0
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0001979986_django_html_python.txt |
Q:
why my code error,I would like to print the parameters of two functions
def c(*x,**y):
print x,y
def a(*x,**y):
print x
def b(*x1,**y1):
c(*(x+x1),**dict(y,**y1))
b()
a(1,2,3,a=1,b=2)(4,5,6,c='222',d='aaa')#error
A:
function a() is not returning a function; actually, it returns None. The... | why my code error,I would like to print the parameters of two functions | def c(*x,**y):
print x,y
def a(*x,**y):
print x
def b(*x1,**y1):
c(*(x+x1),**dict(y,**y1))
b()
a(1,2,3,a=1,b=2)(4,5,6,c='222',d='aaa')#error
| [
"function a() is not returning a function; actually, it returns None. Therefore, the second set of parenthesis is a call on None object - and that's an error.\nDid you intend to return a function, like doing something like return b?\n",
"Replace b() with return b \nRunning this in Python 3.1:\ndef c(*x,**y):\n ... | [
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001989843_python.txt |
Q:
Call Method on Every Ancestor in Python
I have an object of class 'D' in python, and I want to sequentially execute the 'run' method as defined by 'D' and each of it's ancestors ('A', 'B' and 'C').
I'm able to accomplish this like this
class A(object):
def run_all(self):
# I prefer to execute in revere... | Call Method on Every Ancestor in Python | I have an object of class 'D' in python, and I want to sequentially execute the 'run' method as defined by 'D' and each of it's ancestors ('A', 'B' and 'C').
I'm able to accomplish this like this
class A(object):
def run_all(self):
# I prefer to execute in revere MRO order
for cls in reversed(self._... | [
"If you're OK with changing all the run implementations (and calling run instead of run_all in D), this works:\nclass A(object):\n def run(self):\n print \"Running A\"\n\nclass B(A):\n def run(self):\n super(B, self).run()\n print \"Running B\"\n\nclass C(A):\n def run(self):\n ... | [
4,
1,
1
] | [] | [] | [
"datamodel",
"python"
] | stackoverflow_0001989863_datamodel_python.txt |
Q:
How to access fields in a struct imported from a .mat file using loadmat in Python?
Following this question which asks (and answers) how to read .mat files that were created in Matlab using Scipy, I want to know how to access the fields in the imported structs.
I have a file in Matlab from which I can import a str... | How to access fields in a struct imported from a .mat file using loadmat in Python? | Following this question which asks (and answers) how to read .mat files that were created in Matlab using Scipy, I want to know how to access the fields in the imported structs.
I have a file in Matlab from which I can import a struct:
>> load bla % imports a struct called G
>> G
G =
Inp: [40x40x2016 uint8]... | [
"First, I'd recommend to upgrade to Scipy svn if possible - there has been active development of the matlab io with some really dramatic speed ups recently.\nAlso as mentioned it might be worth trying with struct_as_record=True. But otherwise you should be able to get it out by playing around interactively.\nYour G... | [
6
] | [] | [] | [
"file_io",
"mat_file",
"matlab",
"python",
"scipy"
] | stackoverflow_0001984714_file_io_mat_file_matlab_python_scipy.txt |
Q:
Python lists with STL like interface
I have to port a C++ STL application to Python. I am a Python newbie, but have been programming for over a decade. I have a great deal of experience with the STL, and find that it keeps me hooked to using C++. I have been searching for the following items on Google these past s... | Python lists with STL like interface | I have to port a C++ STL application to Python. I am a Python newbie, but have been programming for over a decade. I have a great deal of experience with the STL, and find that it keeps me hooked to using C++. I have been searching for the following items on Google these past several days:
Python STL (in hope of lever... | [
"If I were you I would take the time to learn how to properly use the various data structures available in Python instead of looking for things that are similar to what you know from C++. \nIt's not like you're looking for something fancy, just working with some data structures. In that case I would refer you to P... | [
13,
13,
2,
2,
1,
1
] | [] | [] | [
"c++",
"python",
"stl"
] | stackoverflow_0001988484_c++_python_stl.txt |
Q:
is '__all__' only for 'from some import *'
a.py
__all__=['b','c']
a='aaa'
b='bbb'
def c():
print 'ccc'
def d():
print 'dddd'
b.py
from a import a
print a
from a import *
print a
print d#error
Are there any other uses.
thanks
A:
Yes, it also changes what help(a) documents.
A:
No, the purpose of __all... | is '__all__' only for 'from some import *' | a.py
__all__=['b','c']
a='aaa'
b='bbb'
def c():
print 'ccc'
def d():
print 'dddd'
b.py
from a import a
print a
from a import *
print a
print d#error
Are there any other uses.
thanks
| [
"Yes, it also changes what help(a) documents. \n",
"No, the purpose of __all__ is just to describe exactly what should be imported when you do from foo import *.\n",
"No other uses, except limiting the damage caused by the horrible from ... import * usage.\n"
] | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001990232_python.txt |
Q:
What does this code from types.py do?
try:
raise TypeError
except TypeError:
try:
tb = sys.exc_info()[2]
TracebackType = type(tb)
FrameType = type(tb.tb_frame)
except AttributeError:
# In the restricted environment, exc_info returns (None, None,
# None) Then, tb.... | What does this code from types.py do? | try:
raise TypeError
except TypeError:
try:
tb = sys.exc_info()[2]
TracebackType = type(tb)
FrameType = type(tb.tb_frame)
except AttributeError:
# In the restricted environment, exc_info returns (None, None,
# None) Then, tb.tb_frame gives an attribute error
p... | [
"It's a trick to get a traceback object and a frame object so that TracebackType and FrameType can be assigned their types. It simply raises an exception so it can catch the exception, then get the traceback and frame from sys.exc_info.\n",
"The code tries to find out the types used for the tracebacks returned b... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001990339_python.txt |
Q:
How to get Python error as C string?
I have a C++ application that embeds the Python interpreter. It calls PyImport_Import to load scripts. I need a way of getting any syntax errors as C strings. For example, if the script uses a undefined function, I would like an error saying something like 'Function xxx is unde... | How to get Python error as C string? | I have a C++ application that embeds the Python interpreter. It calls PyImport_Import to load scripts. I need a way of getting any syntax errors as C strings. For example, if the script uses a undefined function, I would like an error saying something like 'Function xxx is undefined.' How would I do this?
| [
"PyErr_Occurred lets your C code check whether an exception has been raised, and, if so, what type; then, PyErr_Fetch lets you fetch all details (as Python objects), and you can get the string representation of the error instance with the usual high-level call PyObject_Str (just the same as except Exception, e: ...... | [
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001990635_python_string.txt |
Q:
How to develop a Python module/package without having to restart the interpreter after every change?
I am developing a Python package using a text editor and IPython. Each time I change any of the module code I have to restart the interpreter to test this. This is a pain since the classes I am developing rely on a... | How to develop a Python module/package without having to restart the interpreter after every change? | I am developing a Python package using a text editor and IPython. Each time I change any of the module code I have to restart the interpreter to test this. This is a pain since the classes I am developing rely on a context that needs to be re-established on each reload.
I am aware of the reload() function, but this app... | [
"A different approach may be to formalise your test driven development, and instead of using the interpreter to test your module, save your tests and run them directly.\nYou probably know of the various ways to do this with python, I imagine the simplest way to start in this direction is to copy and paste what you ... | [
3,
2,
1,
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0001989644_module_package_python.txt |
Q:
Why does this code return 'complex'?
# Example: provide pickling support for complex numbers.
try:
complex
except NameError:
pass
else:
def pickle_complex(c):
return complex, (c.real, c.imag) # why return complex here?
pickle(complex, pickle_complex, complex)
Why?
The following code is ... | Why does this code return 'complex'? | # Example: provide pickling support for complex numbers.
try:
complex
except NameError:
pass
else:
def pickle_complex(c):
return complex, (c.real, c.imag) # why return complex here?
pickle(complex, pickle_complex, complex)
Why?
The following code is the pickle function being called:
dispatch... | [
"complex is the class to use to reconstitute the pickled object. It is returned so that it can be pickled along with the real and imag values. Then when the unpickler comes along, it sees the class and some values to use as arguments to its constructor. The unpickler uses the given class and arguments to create a n... | [
3
] | [] | [] | [
"complex_numbers",
"pickle",
"python"
] | stackoverflow_0001990759_complex_numbers_pickle_python.txt |
Q:
Why does my class not have a 'keys' function?
class a(object):
w='www'
def __init__(self):
for i in self.keys():
print i
def __iter__(self):
for k in self.keys():
yield k
a() # why is there an error here?
Thanks.
Edit: The following class also doesn't... | Why does my class not have a 'keys' function? | class a(object):
w='www'
def __init__(self):
for i in self.keys():
print i
def __iter__(self):
for k in self.keys():
yield k
a() # why is there an error here?
Thanks.
Edit: The following class also doesn't extend any class;
why it can use keys?
class Dict... | [
"Why would you expect it to have keys? You didn't define such a method in your class. Did you intend to inherit from a dictionary?\nTo do that declare class a(dict)\nOr maybe you meant a.__dict__.keys()?\nAs for the large snippet you've posted in the update, read the comment above the class again:\n # Mixin definin... | [
3
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0001990850_inheritance_python.txt |
Q:
Port knocking and RSA encryption
I am doing on my project and there is about port knocking. I have 3 files that separated in server side and client.
In the server contains : portknocking server as a daemon and configuration file [contains sequence of port that must be satisfied and many other configuration detail]... | Port knocking and RSA encryption | I am doing on my project and there is about port knocking. I have 3 files that separated in server side and client.
In the server contains : portknocking server as a daemon and configuration file [contains sequence of port that must be satisfied and many other configuration detail]
In the client contains : portknocking... | [
"\nIs there possible to encrypt sequence port number in file configuration using RSA.\n\nYes.\n\nhow to do that?? \n\nYou might try a bit of searching for a python rsa library.\nHowever, if you're planning on doing this on the client side, then realize in order for the client program to decrypt the data, it will ha... | [
1
] | [] | [] | [
"public_key",
"python",
"rsa"
] | stackoverflow_0001990366_public_key_python_rsa.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.