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:
Python: How do you insert into a list by slicing?
I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks
A:
>>> a = [1,2,3]
>>> a[:0] =... | Python: How do you insert into a list by slicing? | I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks
| [
">>> a = [1,2,3]\n>>> a[:0] = [4]\n>>> a\n[4, 1, 2, 3]\n\na[:0] is the \"slice of list a beginning before any elements and ending before index 0\", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original... | [
68,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002947872_list_python.txt |
Q:
strip spaces in python
ok I know that this should be simple... anyways say:
line = "$W5M5A,100527,142500,730301c44892fd1c,2,686.5 4,333.96,0,0,28.6,123,75,-0.4,1.4*49"
I want to strip out the spaces. I thought you would just do this
line = line.strip()
but now line is still '$W5M5A,100527,142500,730301c44892fd1... | strip spaces in python | ok I know that this should be simple... anyways say:
line = "$W5M5A,100527,142500,730301c44892fd1c,2,686.5 4,333.96,0,0,28.6,123,75,-0.4,1.4*49"
I want to strip out the spaces. I thought you would just do this
line = line.strip()
but now line is still '$W5M5A,100527,142500,730301c44892fd1c,2,686.5 4,333.96,0,0,28.6... | [
"line = line.replace(' ', '')\n\n",
"another way of doing it\nline = ''.join(line.split())\n\n"
] | [
11,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002950448_python_string.txt |
Q:
how to change headers data
i have the following class
class AssetTableModel(QtCore.QAbstractTableModel):
def __init__(self,filename=''):
super(AssetTableModel,self).__init__()
self.fileName=filename
self.dirty = False
self.assets = []
self.setHeaderData(0,QtCore.Qt.Hori... | how to change headers data | i have the following class
class AssetTableModel(QtCore.QAbstractTableModel):
def __init__(self,filename=''):
super(AssetTableModel,self).__init__()
self.fileName=filename
self.dirty = False
self.assets = []
self.setHeaderData(0,QtCore.Qt.Horizontal,QtCore.QVariant('moayyad'... | [
"The headers of the columns or the rows will be obtained from your model by the view. The function used to obtain the header data is virtual QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const (C++ documentation). In order to change the headers shown, you should be a... | [
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0002918704_pyqt_pyqt4_python_qt_qt4.txt |
Q:
Start app from within python
I'm trying to start an application using Python. I've seen that some people use startfile but I also read that it only works with Windows. I'm using Mac systems and hoping for it to work with them.
Thanks,
Aaron
A:
Python has the subprocess module for that, you can read about it her... | Start app from within python | I'm trying to start an application using Python. I've seen that some people use startfile but I also read that it only works with Windows. I'm using Mac systems and hoping for it to work with them.
Thanks,
Aaron
| [
"Python has the subprocess module for that, you can read about it here: http://docs.python.org/library/subprocess.html\nIn it's simplest form:\nsubprocess.call(['your_command', 'params'])\n\n",
"You can use os.system(\"/path/to/myapp\").\nSee http://docs.python.org/library/os.html#os.system for documentation.\nIf... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002951182_python.txt |
Q:
Django - count date between
I have many record in my database which contains datetime field (e.g. 2010-05-23 17:45:57).
I want to count all records between e.g. 15:00 and 15:59 (it all can by from other day, month or year). How can I do this?
A:
You can convert the datetime fields into Julian Dates
and then do a... | Django - count date between | I have many record in my database which contains datetime field (e.g. 2010-05-23 17:45:57).
I want to count all records between e.g. 15:00 and 15:59 (it all can by from other day, month or year). How can I do this?
| [
"You can convert the datetime fields into Julian Dates\nand then do a straight comparison:\n# Input is a list with the time of all the records, t_record_all\n\n# Loop over all the records \ncounter = 0\njd_low = ... #(this is your lower time limit in JD)\njd_hi = ... # (this is your higher time limit in JD)\n\nfor ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002943174_django_python.txt |
Q:
Copy files in folder up one directory in python
I have a folder with a few files that I would like to copy one directory up (this folder also has some files that I don't want to copy). I know there is the os.chdir("..") command to move me to the directory. However, I'm not sure how to copy those files I need into ... | Copy files in folder up one directory in python | I have a folder with a few files that I would like to copy one directory up (this folder also has some files that I don't want to copy). I know there is the os.chdir("..") command to move me to the directory. However, I'm not sure how to copy those files I need into this directory. Any help would be greatly appreciated... | [
"The shutil module can do this, specifically the copyfile, copy, copy2 and copytree functions. http://docs.python.org/library/shutil.html\nYou probably want something along these lines:\nimport os\nimport shutil\n\nfileList = os.listdir('path/to/source_dir')\nfileList = ['path/to/source_dir/'+filename for filename ... | [
9
] | [] | [] | [
"copy",
"file",
"python"
] | stackoverflow_0002951659_copy_file_python.txt |
Q:
Type-aware rendering (and editing) of tabular data in pyqt4
I would like to have a very short / minimal example of how to create some tabular widget with different types of item in it.
In the first round let's say I'd like to render [["Hello", 12, True], ["World", 13, False]] (Hello as string, 12 as number (right-... | Type-aware rendering (and editing) of tabular data in pyqt4 | I would like to have a very short / minimal example of how to create some tabular widget with different types of item in it.
In the first round let's say I'd like to render [["Hello", 12, True], ["World", 13, False]] (Hello as string, 12 as number (right-align), True as a checkbox for eg.), but it would be nice to have... | [
"The examples provided with Qt are fairly complete for this sort of thing, but cover your different parts in different examples. Also, they are in C++ (although you should be able to translate the examples fairly easily).\nThe main example page for item views is a good start. In particular, the Dir View and Chart... | [
1
] | [] | [] | [
"datagrid",
"pyqt4",
"python",
"qt4",
"user_interface"
] | stackoverflow_0002924842_datagrid_pyqt4_python_qt4_user_interface.txt |
Q:
Editing XML file content with Python
I am trying to use Python to read in an XML file containing some parameter names and values, e.g.
...
<parameter name='par1'>
<value>24</value>
</parameter>
<parameter name='par2'>
<value>Blue/Red/Green</value>
</parameter>
...
and then pass i... | Editing XML file content with Python | I am trying to use Python to read in an XML file containing some parameter names and values, e.g.
...
<parameter name='par1'>
<value>24</value>
</parameter>
<parameter name='par2'>
<value>Blue/Red/Green</value>
</parameter>
...
and then pass it a dictionary with the parameter names {'... | [
"My first suggestion is to use lxml or some other Python XML parser rather than using regular expressions. XML is not a language that can be parsed with regular expressions reliably. (If you consistently try to parse XML with regular expressions bad things happen)\n",
"xml.etree.ElementTree is much more pythoni... | [
3,
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002951071_python_xml.txt |
Q:
Replace text in file with Python
I'm trying to replace some text in a file with a value. Everything works fine but when I look at the file after its completed there is a new (blank) line after each line in the file. Is there something I can do to prevent this from happening.
Here is the code as I have it:
impo... | Replace text in file with Python | I'm trying to replace some text in a file with a value. Everything works fine but when I look at the file after its completed there is a new (blank) line after each line in the file. Is there something I can do to prevent this from happening.
Here is the code as I have it:
import fileinput
for line in fileinput... | [
"Each line is read from the file with its ending newline, and the print adds one of its own.\nYou can:\nprint line,\n\nWhich won't add a newline after the line.\n",
"The print line automatically adds a newline. You'd best do a sys.stdout.write(line) instead.\n",
"print adds a new-line character:\n\nA '\\n' char... | [
3,
2,
0
] | [] | [] | [
"file",
"python",
"replace",
"text"
] | stackoverflow_0002951827_file_python_replace_text.txt |
Q:
eliminating multiple occurrences of whitespace in a string in python
If I have a string
"this is a string"
How can I shorten it so that I only have one space between the words rather than multiple? (The number of white spaces is random)
"this is a string"
A:
You could use string.split and " ".join(list) t... | eliminating multiple occurrences of whitespace in a string in python | If I have a string
"this is a string"
How can I shorten it so that I only have one space between the words rather than multiple? (The number of white spaces is random)
"this is a string"
| [
"You could use string.split and \" \".join(list) to make this happen in a reasonably pythonic way - there are probably more efficient algorithms but they won't look as nice.\nIncidentally, this is a lot faster than using a regex, at least on the sample string:\nimport re\nimport timeit\n\ns = \"this is a s... | [
13,
6,
2,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002951051_python_string.txt |
Q:
Py2exe, PyQt4 and Postgre Driver (QPSQL)
I`m trying to freeze my application using Py2exe.
My app uses PyQt4 and it apparently works fine with py2exe. But once I`ve uninstalled PyQt, it shows the following error:
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QPSQL7 QPSQL
Which doesn't make... | Py2exe, PyQt4 and Postgre Driver (QPSQL) | I`m trying to freeze my application using Py2exe.
My app uses PyQt4 and it apparently works fine with py2exe. But once I`ve uninstalled PyQt, it shows the following error:
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QPSQL7 QPSQL
Which doesn't make any sense at all. The driver is available, bu... | [
"Found it.\nJust copy the file 'libpq.dll' to the application folder and it works like a charm.\n"
] | [
1
] | [] | [] | [
"py2exe",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0002885150_py2exe_pyqt4_python_qt_qt4.txt |
Q:
large amount of data in many text files - how to process?
I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over o... | large amount of data in many text files - how to process? | I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and... | [
"(3) is not necessarily a bad idea -- Python makes it easy to process \"CSV\" file (and despite the C standing for Comma, tab as a separator is just as easy to handle) and of course gets just about as much bandwidth in I/O ops as any other language. As for other recommendations, numpy, besides fast computation (wh... | [
14,
14,
6,
4,
4,
2,
2,
1
] | [] | [] | [
"large_data_volumes",
"large_files",
"python",
"r",
"sql"
] | stackoverflow_0002937619_large_data_volumes_large_files_python_r_sql.txt |
Q:
Error running celeryd
I'm posting this question (and answer) so if anybody else has this problem in the future, you'll be able to google it.
If you are trying to run celeryd in Django like so:
python manage.py celeryd
You can receive the following error immediately after it has started:
celery@eric-desktop-dev ha... | Error running celeryd | I'm posting this question (and answer) so if anybody else has this problem in the future, you'll be able to google it.
If you are trying to run celeryd in Django like so:
python manage.py celeryd
You can receive the following error immediately after it has started:
celery@eric-desktop-dev has started.
Traceback (most ... | [
"You're missing a celery setting in settings.py. In my case it was caused by a typo (I missed an 'S' in BROKER_PASSWORD). Double check you included all the required settings and that each one is spelled everything correctly, and you'll avoid making as ass of yourself like I did today :)\n"
] | [
1
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0002952446_celery_django_python.txt |
Q:
return sql query in xml format in python
When I first started working at the company that i work at now, I created a java application that would run batches of jasper-reports. In order to determine which parameters to use for each report in the set of reports, I run a sql query (on sqlserver). I wrote the applicat... | return sql query in xml format in python | When I first started working at the company that i work at now, I created a java application that would run batches of jasper-reports. In order to determine which parameters to use for each report in the set of reports, I run a sql query (on sqlserver). I wrote the application to take an xml file with a set of paramete... | [
"I would imagine that executing the sql query you have using 'FOR XML AUTO' will give you a recordset with one record in it (the xml). You would then retrieve the first record and continue with your application from there.\nExample using pyodbc:\ncursor.execute(\"select user_name from users where user_id=? for xml... | [
1
] | [] | [] | [
"python",
"sql",
"xml"
] | stackoverflow_0002952544_python_sql_xml.txt |
Q:
Robustly killing Windows programs stuck reporting 'problems'
I am looking for a means to kill a Windows exe program that, when being tested from a python script, crashes and presents a dialog to the user; as this program is invoked many times, and may crash repeatedly, this is not suitable.
The problem dialog is t... | Robustly killing Windows programs stuck reporting 'problems' | I am looking for a means to kill a Windows exe program that, when being tested from a python script, crashes and presents a dialog to the user; as this program is invoked many times, and may crash repeatedly, this is not suitable.
The problem dialog is the standard reporting of a Windows error:
"Foo.exe has encountered... | [
"Wouldn't it be easier to disable the error reporting feature?\n",
"If you were to use CreateProcessEx or a WinAPI specific function, you might be able to call TerminateProcess or TerminateThread to forcibly end the process.\n"
] | [
3,
0
] | [] | [] | [
"kill",
"process",
"python",
"windows",
"windows_error_reporting"
] | stackoverflow_0002952443_kill_process_python_windows_windows_error_reporting.txt |
Q:
python sqlite3 won't execute a join, but sqlite3 alone will
Using the sqlite3 standard library in python 2.6.4, the following query works fine on sqlite3 command line:
select segmentid, node_t, start, number,title from
((segments inner join position using (segmentid))
left outer join titles using (legid... | python sqlite3 won't execute a join, but sqlite3 alone will | Using the sqlite3 standard library in python 2.6.4, the following query works fine on sqlite3 command line:
select segmentid, node_t, start, number,title from
((segments inner join position using (segmentid))
left outer join titles using (legid, segmentid))
left outer join numbers using (start, legid, v... | [
"A solution (to my problem using the python library) appears to be to introduce an entirely spurious table name:\nSELECT legid, version, segmentid, html, node_t, start, number, title \n from ((segments inner join position using (segmentid)) \n left outer join titles using (legid, segmentid)) as LT \n left... | [
1,
0,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0002945594_python_sqlite.txt |
Q:
Aptana Studio is opening but not ever closing a python.exe process
I am developing a small testing website using Django 1.2 in Aptana Studio build 2.0.4.1268158907. I have a Django project that I test by running the command "runserver 8001" on my project. This command runs the project on a small server that comes... | Aptana Studio is opening but not ever closing a python.exe process | I am developing a small testing website using Django 1.2 in Aptana Studio build 2.0.4.1268158907. I have a Django project that I test by running the command "runserver 8001" on my project. This command runs the project on a small server that comes with Django.
However the problem arises that every time I run this com... | [
"You should try adding --noreload to the runserver argument\n"
] | [
2
] | [] | [] | [
"aptana",
"django",
"python"
] | stackoverflow_0002952957_aptana_django_python.txt |
Q:
taking intersection of N-many lists in python
what's the easiest way to take the intersection of N-many lists in python?
if I have two lists a and b, I know I can do:
a = set(a)
b = set(b)
intersect = a.intersection(b)
but I want to do something like a & b & c & d & ... for an arbitrary set of lists (ideally with... | taking intersection of N-many lists in python | what's the easiest way to take the intersection of N-many lists in python?
if I have two lists a and b, I know I can do:
a = set(a)
b = set(b)
intersect = a.intersection(b)
but I want to do something like a & b & c & d & ... for an arbitrary set of lists (ideally without converting to a set first, but if that's the ea... | [
"This works for 1 or more lists. The 0 lists case is not so easy, because it would have to return a set that contains all possible values.\ndef intersection(first, *others):\n return set(first).intersection(*others)\n\n",
"This works with 1 or more lists and does not use multiple parameters:\n>>> def intersect... | [
14,
3,
2
] | [] | [] | [
"list",
"numpy",
"python",
"scipy"
] | stackoverflow_0002953280_list_numpy_python_scipy.txt |
Q:
Force import module from Python standard library instead of PYTHONPATH default
I have a custom module in one of the directories in my PYTHONPATH with the same name as one of the standard library modules, so that when I import module_name, that module gets loaded. If I want to use the original standard library modu... | Force import module from Python standard library instead of PYTHONPATH default | I have a custom module in one of the directories in my PYTHONPATH with the same name as one of the standard library modules, so that when I import module_name, that module gets loaded. If I want to use the original standard library module, is there any way to force Python to import from the standard library rather than... | [
"The ideal solution would be to rename your module to something not in the standard library.\nYou can also switch absolute imports on if you're on Python 2.5+:\nfrom __future__ import absolute_import\n\n",
"Don't.\nIf you have accidentally chosen a standard library module name, change your module name to end the ... | [
12,
12,
7
] | [] | [] | [
"import",
"module",
"python",
"pythonpath",
"standard_library"
] | stackoverflow_0002952045_import_module_python_pythonpath_standard_library.txt |
Q:
regex help using repreated groups
I'm trying to match rc-update -s output in python.
m = re.match(r"^\s*(\w+)\s*\|{\s*(\w+)\s*}*$", " network | level1 level2 leveln ")
but m is always None
the hard part for me is getting the regex to match the n levels. I thought that using {}* would match the n levels, but as ... | regex help using repreated groups | I'm trying to match rc-update -s output in python.
m = re.match(r"^\s*(\w+)\s*\|{\s*(\w+)\s*}*$", " network | level1 level2 leveln ")
but m is always None
the hard part for me is getting the regex to match the n levels. I thought that using {}* would match the n levels, but as soon as I add the {} nothing matches.
... | [
"The {} are odd here, they are not meta characters when used this way, what is there purpose because at the moment they are attempting to match a literal { and the match fails.\nReplace them with normal parenthesis and it will work\n",
"The curly braces (\"{}\") do not do what you think they do, at least in this ... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002953357_python_regex.txt |
Q:
Split based by a-z character in an alphanumeric string in python
I have strings like "5d4h2s", where I want to get 5, 4, and 2 from that string, but I also want to know that 5 was paired with d, and that 4 was paired with h, etc etc. Is there an easy way of doing this without parsing char by char?
A:
If your inp... | Split based by a-z character in an alphanumeric string in python | I have strings like "5d4h2s", where I want to get 5, 4, and 2 from that string, but I also want to know that 5 was paired with d, and that 4 was paired with h, etc etc. Is there an easy way of doing this without parsing char by char?
| [
"If your input does not get more complicated than 5d4h2s:\n>>> import re\n>>> s = \"5d4h2s\"\n>>> p = re.compile(\"([0-9])([a-z])\")\n>>> for m in p.findall(s):\n... print m\n... \n('5', 'd')\n('4', 'h')\n('2', 's')\n\nAnd if it gets, you can easily adjust the regular expression, e.g.\n>>> p = re.compile(\"([0-9]... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0002953421_python.txt |
Q:
Accessing relative path in Python
I'm running a Mac OS X environment and am used to using ~/ to provide the access to the current user's directory.
For example, in my python script I'm just trying to use
os.chdir("/Users/aaron/Desktop/testdir/")
But would like to use
os.chdir("~/Desktop/testdir/")
I'm getting ... | Accessing relative path in Python | I'm running a Mac OS X environment and am used to using ~/ to provide the access to the current user's directory.
For example, in my python script I'm just trying to use
os.chdir("/Users/aaron/Desktop/testdir/")
But would like to use
os.chdir("~/Desktop/testdir/")
I'm getting a no such file or directory error when ... | [
"You'll need to use os.path.expanduser(path) \nos.chdir(\"~/Desktop/testdir/\") is looking for a directory named \"~\" in the current working directory.\nAlso pay attention to the documentation of that function - specifically that you'll need the $HOME environment variable set properly to ensure that the expansion ... | [
17,
2
] | [] | [] | [
"path",
"python"
] | stackoverflow_0002953828_path_python.txt |
Q:
Python unicode Decode Error SUDs
OK so I have # -*- coding: utf-8 -*- at the top of my script and it worked for being able to pull data from the database that had funny chars(Ñ ,Õ,é,—,–,’,…) in it and store that data into variables...but I have run into other problems, see I pull my data, organize it, and then dum... | Python unicode Decode Error SUDs | OK so I have # -*- coding: utf-8 -*- at the top of my script and it worked for being able to pull data from the database that had funny chars(Ñ ,Õ,é,—,–,’,…) in it and store that data into variables...but I have run into other problems, see I pull my data, organize it, and then dump it into a variables like so:
title =... | [
"#-*- coding: xxx -*- has nothing to do with this error, it only applies to the encoding of the source file it is declared in, not the content of variables coming from a database.\nYour error says that you try to pass a str type object containing non ASCII characters to the unicode() constructor (which is called at... | [
10
] | [] | [] | [
"python",
"suds",
"unicode"
] | stackoverflow_0002953651_python_suds_unicode.txt |
Q:
Python parse comma-separated number into int
How would I parse the string 1,000,000 (one million) into it's integer value in Python?
A:
>>> a = '1,000,000'
>>> int(a.replace(',', ''))
1000000
>>>
A:
There's also a simple way to do this that should handle internationalization issues as well:
>>> import locale
... | Python parse comma-separated number into int | How would I parse the string 1,000,000 (one million) into it's integer value in Python?
| [
">>> a = '1,000,000'\n>>> int(a.replace(',', ''))\n1000000\n>>> \n\n",
"There's also a simple way to do this that should handle internationalization issues as well:\n>>> import locale\n>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\n'en_US.UTF-8'\n>>> locale.atoi(\"1,000,000\")\n1000000\n>>> \n\nI found that ... | [
149,
56,
12
] | [] | [] | [
"python",
"string_conversion"
] | stackoverflow_0002953746_python_string_conversion.txt |
Q:
hosting simple python scripts in a container to handle concurrency, configuration, caching, etc
My first real-world Python project is to write a simple framework (or re-use/adapt an existing one) which can wrap small python scripts (which are used to gather custom data for a monitoring tool) with a "container" to ... | hosting simple python scripts in a container to handle concurrency, configuration, caching, etc | My first real-world Python project is to write a simple framework (or re-use/adapt an existing one) which can wrap small python scripts (which are used to gather custom data for a monitoring tool) with a "container" to handle boilerplate tasks like:
fetching a script's configuration from a file (and keeping that info ... | [
"Have a look at SQL Alchemy for dealing with database stuff in python. Also to make script writing easier for dealing with concurrency look into Stackless Python.\n"
] | [
0
] | [] | [] | [
"dependency_injection",
"ioc_container",
"plugins",
"python"
] | stackoverflow_0002953799_dependency_injection_ioc_container_plugins_python.txt |
Q:
Changing floating point behavior in Python to Numpy style
Is there a way to make Python floating point numbers follow numpy's rules regarding +/- Inf and NaN? For instance, making 1.0/0.0 = Inf.
>>> from numpy import *
>>> ones(1)/0
array([ Inf])
>>> 1.0/0.0
Traceback (most recent call last):
File "<stdin>", li... | Changing floating point behavior in Python to Numpy style | Is there a way to make Python floating point numbers follow numpy's rules regarding +/- Inf and NaN? For instance, making 1.0/0.0 = Inf.
>>> from numpy import *
>>> ones(1)/0
array([ Inf])
>>> 1.0/0.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division
Numpy's di... | [
"I tried to do something similar, and I never figured out how to do it nicely. But, I can tell you a few things I tried, that didn't work:\n\nSetting float = numpy.float -- python still uses the old float\ntrying to change float.div to a user-defined function -- \"TypeError: can't set attributes of built-in/exten... | [
1,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002952119_numpy_python.txt |
Q:
Parsing line with delimiter in Python
I have lines of data which I want to parse.
The data looks like this:
a score=216 expect=1.05e-06
a score=180 expect=0.0394
What I want to do is to have a subroutine
that parse them and return 2 values (score and expect) for
each line.
However this function of mine doesn't se... | Parsing line with delimiter in Python | I have lines of data which I want to parse.
The data looks like this:
a score=216 expect=1.05e-06
a score=180 expect=0.0394
What I want to do is to have a subroutine
that parse them and return 2 values (score and expect) for
each line.
However this function of mine doesn't seem to work:
def scoreEvalFromMaf(mafLines):... | [
"If mafLines if a list of lines, and you want to look just at the first one, .split that line to obtain the words. For example:\ndef scoreEvalFromMaf(mafLines):\n theScore = None\n theEval = None\n for word in mafLines[0].split:\n if word.startswith('score='):\n _, theScore = word.partit... | [
2,
2,
1
] | [] | [] | [
"linux",
"python",
"unix"
] | stackoverflow_0002954440_linux_python_unix.txt |
Q:
Run python in a separate process
I'm looking for a quick bash script or program that will allow me to kick off a python script in a separate process. What's the best way to do this? I know this is incredibly simple, just curious if there's a preferred way to do it.
A:
Just use the ampersand (&) in order to lau... | Run python in a separate process | I'm looking for a quick bash script or program that will allow me to kick off a python script in a separate process. What's the best way to do this? I know this is incredibly simple, just curious if there's a preferred way to do it.
| [
"Just use the ampersand (&) in order to launch the Python process in the background. Python already is executed in a separate process from the BASH script, so saying to run it \"in a separate thread\" doesn't make much sense -- I'm assuming you simply want it to run in the background:\n#! /bin/bash\npython path/to/... | [
23,
7,
4,
2
] | [] | [] | [
"process",
"python"
] | stackoverflow_0002954516_process_python.txt |
Q:
wxPython ListCtrl Column Ignores Specific Fields
I'm rewriting this post to clarify some things and provide a full class definition for the Virtual List I'm having trouble with. The class is defined like so:
from wx import ListCtrl, LC_REPORT, LC_VIRTUAL, LC_HRULES, LC_VRULES, \
EVT_LIST_COL_CLICK, EVT_LIST_CA... | wxPython ListCtrl Column Ignores Specific Fields | I'm rewriting this post to clarify some things and provide a full class definition for the Virtual List I'm having trouble with. The class is defined like so:
from wx import ListCtrl, LC_REPORT, LC_VIRTUAL, LC_HRULES, LC_VRULES, \
EVT_LIST_COL_CLICK, EVT_LIST_CACHE_HINT, EVT_LIST_COL_RIGHT_CLICK, \
ImageList, IMA... | [
"Are you building on the wxPython demo code for virtual list controls? There are a couple of bookkeeping things you need to do, like set the ItemCount property.\nOne comment about your OnGetItemText method: Since there's no other return statement, it will return None if data is None, so your test has no effect.\nHo... | [
0,
0
] | [] | [] | [
"listctrl",
"python",
"wxpython"
] | stackoverflow_0002914816_listctrl_python_wxpython.txt |
Q:
getting smallest of coordinates that differ by N or more in Python
suppose I have a list of coordinates:
data = [
[(10, 20), (100, 120), (0, 5), (50, 60)],
[(13, 20), (300, 400), (100, 120), (51, 62)]
]
and I want to take all tuples that either appear in each list in data, or any tuple that differs from a... | getting smallest of coordinates that differ by N or more in Python | suppose I have a list of coordinates:
data = [
[(10, 20), (100, 120), (0, 5), (50, 60)],
[(13, 20), (300, 400), (100, 120), (51, 62)]
]
and I want to take all tuples that either appear in each list in data, or any tuple that differs from all tuples in lists other than its own by 3 or less. How can I do this e... | [
"A naive implementation of this will be slow: O(n^2), testing for each node against each other node. Use a tree to speed it up.\nThis implementation uses a simple quadtree to make searching more efficient. This doesn't make any attempt to balance the tree, so a badly-ordered list of points could make it very inef... | [
1,
0,
0
] | [] | [] | [
"database",
"numpy",
"python",
"scipy"
] | stackoverflow_0002953878_database_numpy_python_scipy.txt |
Q:
Python character count
I have been going over python tutorials in this resource. Everything is pretty clear in the below code which counts number of characters. Only section that i dont understand is the section where count assigned to a list and multiplied by 120. Can anyone explain what is the purpose of this in... | Python character count | I have been going over python tutorials in this resource. Everything is pretty clear in the below code which counts number of characters. Only section that i dont understand is the section where count assigned to a list and multiplied by 120. Can anyone explain what is the purpose of this in plain english please.
def d... | [
"128 * [0] creates a list of 128 elements, each with a value of 0.\n>>> 3 * [0]\n[0, 0, 0]\n\nThen, since valid ASCII characters are in the range 0-127, each letter accesses an index in counts (ord(letter) will return the numeric value of a character), and increments the value at that index.\nFor example, the chara... | [
6,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002954683_python.txt |
Q:
File encryption with Python
Is there a way to encrypt files (.zip, .doc, .exe, ... any type of file) with Python?
I've looked at a bunch of crypto libraries for Python including pycrypto and ezpycrypto but as far as I see they only offer string encryption.
A:
In Python versions prior to version 3.0, the read me... | File encryption with Python | Is there a way to encrypt files (.zip, .doc, .exe, ... any type of file) with Python?
I've looked at a bunch of crypto libraries for Python including pycrypto and ezpycrypto but as far as I see they only offer string encryption.
| [
"In Python versions prior to version 3.0, the read method of a file object will return a string, provide this string to the encryption library of your choice, the resulting string can be written to a file.\nKeep in mind that on Windows-based operating systems, the default mode used when reading files may not accura... | [
2,
1
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0002938757_encryption_python.txt |
Q:
gtk+ checkbutton settings
Is there a way to use set_active on a gtkCheckButton but without the user being able to press/toggle the said button?
In other words, I want to programmatically control the active state of the CheckButton but I don't want the user to be able to change it.
A:
The "active" property of the... | gtk+ checkbutton settings | Is there a way to use set_active on a gtkCheckButton but without the user being able to press/toggle the said button?
In other words, I want to programmatically control the active state of the CheckButton but I don't want the user to be able to change it.
| [
"The \"active\" property of the gtk.ToggleButton combined with the \"sensitive\" property of the gtk.Widget should do what you want. You should just be able to do\ncheckbox1.set_sensitive(False)\ncheckbox1.set_active(True)\n\n...to check it and have it remain unchangeable.\n"
] | [
2
] | [] | [] | [
"c",
"gtk",
"python"
] | stackoverflow_0002954461_c_gtk_python.txt |
Q:
how to tell if a string is base64 or not
I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.
When I receive these emails, I wish to decode the name. but there are other names wh... | how to tell if a string is base64 or not | I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.
When I receive these emails, I wish to decode the name. but there are other names which are
not base64. How can I differentiate wh... | [
"The header value tells you this:\n\n=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\n\n\"=?\" introduces an encoded value\n\"gb2312\" denotes the character encoding of the original value\n\"B\" denotes that B-encoding (equal to Base64) was used (the alternative \n is \"Q\", which refers to something close t... | [
21,
12,
7,
2,
0,
0
] | [] | [] | [
"base64",
"jython",
"mime",
"python"
] | stackoverflow_0000271657_base64_jython_mime_python.txt |
Q:
receive string with chars
i am quite new in python.
I am receiving (through pyserial) string with data values.
How can I parse these data to particular data structure?
I know that
0-1 byte : id
2-5 byte : time1 =>but little endian (lsb first)
6-9 byte : time2 =>but little endian (lsb first)
and I looking for a... | receive string with chars | i am quite new in python.
I am receiving (through pyserial) string with data values.
How can I parse these data to particular data structure?
I know that
0-1 byte : id
2-5 byte : time1 =>but little endian (lsb first)
6-9 byte : time2 =>but little endian (lsb first)
and I looking for a function:
def parse_data(strin... | [
"The struct module should be exactly what you're looking for.\nimport struct\n# ...\ndata['id'], data['time1'], data['time2'] = struct.unpack(\"<HII\", string)\n\nIn the format string, < means \"interpret everything as little endian, and don't use native alignment\", H means \"unsigned short\" and I means \"unsigne... | [
2,
2
] | [] | [] | [
"endianness",
"parsing",
"python"
] | stackoverflow_0002955918_endianness_parsing_python.txt |
Q:
Can I set env vars for dependencies in setup-tools?
Is it possible to set env vars to be used by dependencies set in the setup.py file of a package?
Specifically; the lxml package is a dependency of one of my packages. To help ease deployment I want to set STATIC_DEPS=true and some CFLAGS for lxml in the setup.py... | Can I set env vars for dependencies in setup-tools? | Is it possible to set env vars to be used by dependencies set in the setup.py file of a package?
Specifically; the lxml package is a dependency of one of my packages. To help ease deployment I want to set STATIC_DEPS=true and some CFLAGS for lxml in the setup.py file for my package, so that our users can just easy_ins... | [
"Isn't that the default behaviour?\nJust\nexport STATIC_DEPS=true; easy_install lxml\n\n"
] | [
1
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0002956076_python_setuptools.txt |
Q:
Importing ctype; embedding python in C++ application
I'm trying to embed python within a C++ based programming language (CCL: The compuatational control language, not that any of you have heard of it). Thus, I don't really have a "main" function to make calls from.
I have made a test .cc program with a main, and w... | Importing ctype; embedding python in C++ application | I'm trying to embed python within a C++ based programming language (CCL: The compuatational control language, not that any of you have heard of it). Thus, I don't really have a "main" function to make calls from.
I have made a test .cc program with a main, and when I compile it and run it, I am able to import my own py... | [
"The Python runtime is effectively a collection of libraries that your program uses. Those libraries take strings, convert them to Python bytecode and then interpret the bytecode. The error you're getting is that as part of interpreting the program, the Python runtime needs to call a function (PyType_GenericNew),... | [
1
] | [] | [] | [
"c++",
"ctypes",
"embedding",
"import",
"python"
] | stackoverflow_0002954581_c++_ctypes_embedding_import_python.txt |
Q:
Django or Drupal, which one should I use that suits best my needs?
I want to learn and use Drupal or Django for the following:
dynamic web sites, medium database, multi-level users, paypal integration, content managment, speed (developing), security
I like MVC, ORM and object-oriented prg.
Which is better to jum... | Django or Drupal, which one should I use that suits best my needs? | I want to learn and use Drupal or Django for the following:
dynamic web sites, medium database, multi-level users, paypal integration, content managment, speed (developing), security
I like MVC, ORM and object-oriented prg.
Which is better to jump into ? Which one is more mature, powerful, understandable, object-ori... | [
"I've built several sites on Drupal and Django, my conclusion is: if you need to create something similar to the standard drupal (or Ubercart) feature-set, you don't have much time for development, and you don't expect hight load pressure on a site - you should pick Drupal.\nBut if you do need to create something m... | [
6,
5,
3,
2,
2,
0,
0
] | [] | [] | [
"django",
"drupal",
"php",
"python"
] | stackoverflow_0002954036_django_drupal_php_python.txt |
Q:
gtk+ signal emitted when window/dialog is "presented"
Is there a signal that is emitted when a window/dialog is presented in GTK+?
Example: when issuing this command to the GTK widget dialog:
dialog.present()
is there a resulting signal? Or is there any signal that denotes the "showing" of a window/dialog?
A:
I... | gtk+ signal emitted when window/dialog is "presented" | Is there a signal that is emitted when a window/dialog is presented in GTK+?
Example: when issuing this command to the GTK widget dialog:
dialog.present()
is there a resulting signal? Or is there any signal that denotes the "showing" of a window/dialog?
| [
"I believe the \"show\" signal (inherited from Widget) will do this. \n",
"The notify::visible signal will be emitted whenever the visibility state changes, i.e. the window is shown or hidden. The show signal isn't documented but from the source it appears that it is an action signal; you can call it yourself usi... | [
1,
1
] | [] | [] | [
"c",
"gtk",
"python"
] | stackoverflow_0002954412_c_gtk_python.txt |
Q:
Replace ",**" with a linebreak using RegEx (or something else)
I'm getting started with RegEx and I was wondering if anyone could help me craft a statement to convert coordinates as follows:
145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,-37.80301,16
to
145.00694,-37.80421
145.00686,-... | Replace ",**" with a linebreak using RegEx (or something else) | I'm getting started with RegEx and I was wondering if anyone could help me craft a statement to convert coordinates as follows:
145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,-37.80301,16
to
145.00694,-37.80421
145.00686,-37.80382
145.00595,-37.8035
145.00586,-37.80301
(Strip off the las... | [
"\n\"Some people, when confronted with a\n problem, think 'I know, I'll use\n regular expressions.' Now they have\n two problems.\" --Jamie Zawinski\n\nAvoid that problem and use string methods:\ns=\"145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,37.80301,16\"\n\nlines = s.split(' ')... | [
3,
2,
1,
0
] | [] | [] | [
"kml",
"python",
"regex",
"string"
] | stackoverflow_0002956044_kml_python_regex_string.txt |
Q:
How do I implement secure authentication using xml-rpc in python?
I have a basic xml-rpc web service service running.
What is the simplest way(I'm a newbie) to implement secure authentication?
I just need some direction.
A:
You could checkout This code for a simple XML-RPC server over HTTPS. Authentication can... | How do I implement secure authentication using xml-rpc in python? | I have a basic xml-rpc web service service running.
What is the simplest way(I'm a newbie) to implement secure authentication?
I just need some direction.
| [
"You could checkout This code for a simple XML-RPC server over HTTPS. Authentication can work in any way you wish ... they could authenticate with some credentials and you provide a cookie for the rest of the session.\nThe Python docs for xmlrpc include details of using the HTTP 'Authorization' header for passing i... | [
7
] | [] | [] | [
"authentication",
"python",
"web_services",
"xml_rpc"
] | stackoverflow_0002956778_authentication_python_web_services_xml_rpc.txt |
Q:
Weird behaviour with optparse and bash tab completion
I am building a script for users new to Linux, so please understand why I am asking this :)
My script runs like this:
python script.py -f filename.txt
I am using the optparse module for this. However, I noticed the following when doing tab completion.
The tab ... | Weird behaviour with optparse and bash tab completion | I am building a script for users new to Linux, so please understand why I am asking this :)
My script runs like this:
python script.py -f filename.txt
I am using the optparse module for this. However, I noticed the following when doing tab completion.
The tab completion works when I do:
python script.py <tab completio... | [
"This is more to do with how bash works than how python works. Experimenting a bit, it looks as if the second and further TAB actually causes bash to expand.\nEdit: The probable reason that bash is only expanding the *.py and *.pyc files is because the first word on the line is python. If you add #! /usr/bin/env py... | [
4,
1,
0
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0002955746_bash_python.txt |
Q:
element-wise lookup on one ndarray to another ndarray of different shapes
I am new to numpy. Am wonder is there a way to do lookup of two ndarray of different shapes?
for example, i have 2 ndarrays as below:
X = array([[0, 3, 6],
[3, 3, 3],
[6, 0, 3]])
Y = array([[0, 100],
[3, 500],
[6... | element-wise lookup on one ndarray to another ndarray of different shapes | I am new to numpy. Am wonder is there a way to do lookup of two ndarray of different shapes?
for example, i have 2 ndarrays as below:
X = array([[0, 3, 6],
[3, 3, 3],
[6, 0, 3]])
Y = array([[0, 100],
[3, 500],
[6, 800]])
and would like to lookup each element of X in Y, then be able to retu... | [
"You can directly use NumPy's efficient array operations:\nY_dict = dict(Y)\nZ = vectorize(lambda x: Y_dict[x])(X)\n\nThis approach has the advantage of working whatever the dimension of X (1-dimensional array, 2- or N-dimensional array…).\nThe vectorized function automatically applies the dictionary look-up to eac... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002956459_numpy_python.txt |
Q:
Django URL resolving infrastructure stops working
We recently launched a new Django-powered website, and we are experiencing the oddest bug:
The site is running under Apache with mod_fastcgi. Everything works fine for a while, and then the URL tag and reverse() functionality stops working. Instead of returning the... | Django URL resolving infrastructure stops working | We recently launched a new Django-powered website, and we are experiencing the oddest bug:
The site is running under Apache with mod_fastcgi. Everything works fine for a while, and then the URL tag and reverse() functionality stops working. Instead of returning the expected URL, they return "".
We haven't noticed anyt... | [
"This has happened to me before. Normally it's due to a 'broken' urls.py file. There are two things that make this kind of bug really hard to fix:\n\nIt could be the urls.py file in any of the apps that breaks the reverse() function, so knowing that reverse() breaks for app X doesn't mean the error is in that parti... | [
7,
2
] | [] | [] | [
"django",
"django_urls",
"fastcgi",
"python"
] | stackoverflow_0002917687_django_django_urls_fastcgi_python.txt |
Q:
running a python script on a remote computer
I have a python script and am wondering is there any way that I can ensure that the script run's continuously on a remote computer? Like for example, if the script crashes for whatever reason, is there a way to start it up automatically instead of having to remote deskt... | running a python script on a remote computer | I have a python script and am wondering is there any way that I can ensure that the script run's continuously on a remote computer? Like for example, if the script crashes for whatever reason, is there a way to start it up automatically instead of having to remote desktop. Are there any other factors I have to be aware... | [
"Many ways - In the case of windows, even a simple looping batch file would probably do - just have it start the script in a loop (whenever it crashes it would return to the shell and be restarted).\n",
"Maybe you can use XMLRPC to call functions and pass data. Some time ago I did something like that you ask by u... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002957588_python.txt |
Q:
Python - alternative to list.remove(x)?
I wish to compare two lists. Generally this is not a problem as I usually use a nested for loop and append the intersection to a new list. In this case, I need to delete the intersection of A and B from A.
A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]
B =... | Python - alternative to list.remove(x)? | I wish to compare two lists. Generally this is not a problem as I usually use a nested for loop and append the intersection to a new list. In this case, I need to delete the intersection of A and B from A.
A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]
B = [['ab'], ['hi'], ['op'], ['ej']]
My objecti... | [
"If possible (meaning if the order and the fact that you have \"sublists\" does not matter), I would first flatten the lists, create sets and then you can easily remove the elements from A that are in B:\n>>> from itertools import chain\n>>> A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]\n>>> B = [[... | [
9,
4,
1
] | [] | [] | [
"comparison",
"list",
"python"
] | stackoverflow_0002958029_comparison_list_python.txt |
Q:
simply way to add another webapp framework to my project
one webapp project has many url
and i have to change this:
('/addTopic', AddTopic),
('/delTopic', DeleteTopic),
('/addPost', AddPost),
('/delPost', DeletePost),
to this:
('/tribes/addTopic', AddTopic),
('/tribes/delTopic', DeleteTopic),
('/tribes/addPo... | simply way to add another webapp framework to my project | one webapp project has many url
and i have to change this:
('/addTopic', AddTopic),
('/delTopic', DeleteTopic),
('/addPost', AddPost),
('/delPost', DeletePost),
to this:
('/tribes/addTopic', AddTopic),
('/tribes/delTopic', DeleteTopic),
('/tribes/addPost', AddPost),
('/tribes/delPost', DeletePost),
but ,if i a... | [
"I'm not quite sure I understand what you're asking. URL patterns in webapp are regular expressions, and they're evaluated in order, first to last. You can include captured groups in the regex, and they will be extracted and passed as arguments to the handler. For example:\n('/articles/2003/(.*)', Articles2003),\n(... | [
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"templates",
"url"
] | stackoverflow_0002956207_google_app_engine_python_templates_url.txt |
Q:
Determine site domain in BaseHTTPServer
I try to implement simple server on python based on HTTPServer.
How can i extract information about site domain served in current request?
I mean it can serv several domains such as site1.com and site2.com for example, how can i get it in this code:
from BaseHTTPServer impor... | Determine site domain in BaseHTTPServer | I try to implement simple server on python based on HTTPServer.
How can i extract information about site domain served in current request?
I mean it can serv several domains such as site1.com and site2.com for example, how can i get it in this code:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class M... | [
"I guess you should be able to read the Host header.\nThe headers can be accessed from BaseHTTPRequestHandler.headers\n"
] | [
1
] | [] | [] | [
"dns",
"python"
] | stackoverflow_0002958408_dns_python.txt |
Q:
Python: Mat-File into hex-values
filename = r"C:\Dokumente und Einstellungen\sschnei1\Desktop\a.mat"
print open(filename, "r").read().encode("hex")
The code above only work for text files. But I want to read out the hex-values of mat-files.
EDIT: my little hex-editor
from textwrap import fill
filename = r"C:\a.ma... | Python: Mat-File into hex-values | filename = r"C:\Dokumente und Einstellungen\sschnei1\Desktop\a.mat"
print open(filename, "r").read().encode("hex")
The code above only work for text files. But I want to read out the hex-values of mat-files.
EDIT: my little hex-editor
from textwrap import fill
filename = r"C:\a.mat"
hexvalues = open(filename, "rb").re... | [
"try open(filename,\"rb\") - open it as a binary file\n"
] | [
2
] | [] | [] | [
"encoding",
"hex",
"matlab",
"python"
] | stackoverflow_0002958839_encoding_hex_matlab_python.txt |
Q:
CherryPy configuration tools.staticdir.root problem
How can I make my static-file root directories relative to my application root folder (instead of a hard-coded path)?
In accordance with CP instructions (http://www.cherrypy.org/wiki/StaticContent) I have tried the following in my configuration file:
tree.cpapp =... | CherryPy configuration tools.staticdir.root problem | How can I make my static-file root directories relative to my application root folder (instead of a hard-coded path)?
In accordance with CP instructions (http://www.cherrypy.org/wiki/StaticContent) I have tried the following in my configuration file:
tree.cpapp = cherrypy.Application(cpapp.Root())
tools.staticdir.root ... | [
"When you refer to a module inside configuration entries, CherryPy first looks for that module in sys.modules. So one solution would be to import cpapp just before you call quickstart.\nBut if that lookup in sys.modules fails, CherryPy tries to __import__ the module. Since that is also failing, you might need to in... | [
2
] | [] | [] | [
"cherrypy",
"configuration",
"python",
"relative_path"
] | stackoverflow_0002954370_cherrypy_configuration_python_relative_path.txt |
Q:
What are the advantages or difference in “assert False” and “self.assertFalse”
I am writing tests and I have heard some people saying to use self.assertFalse rather than assert False. Why is this and are there any advantages to be had?
A:
If you run
import unittest
class Test_Unittest(unittest.TestCase):
de... | What are the advantages or difference in “assert False” and “self.assertFalse” | I am writing tests and I have heard some people saying to use self.assertFalse rather than assert False. Why is this and are there any advantages to be had?
| [
"If you run\nimport unittest\n\nclass Test_Unittest(unittest.TestCase):\n def test_assert(self):\n assert False\n def test_assertFalse(self):\n self.assertFalse(True)\n\nif __name__ == '__main__':\n unittest.main()\n\nYou get the same logging information, the same failure:\nFF\n==============... | [
46,
37,
12
] | [] | [] | [
"assert",
"python",
"unit_testing"
] | stackoverflow_0002958169_assert_python_unit_testing.txt |
Q:
Are many Dojo Toolkit users also using Python?
I've coming to be more interested in Dojo Toolkit which I find great, but are many Dojo users also using Python also? And why is it like that?
I heard of Cherry Py (and why not Django?).
A:
My Python team has been using Dojo on the client-side for a few years now,... | Are many Dojo Toolkit users also using Python? | I've coming to be more interested in Dojo Toolkit which I find great, but are many Dojo users also using Python also? And why is it like that?
I heard of Cherry Py (and why not Django?).
| [
"My Python team has been using Dojo on the client-side for a few years now, and we settled on CherryPy as our server-side about a year ago, and are pretty pleased with it. It's fairly minimal as web servers go, and enables us to customize the server behavior as needed. Initially we looked at Django and Turbogears a... | [
1
] | [] | [] | [
"dojo",
"python"
] | stackoverflow_0002956904_dojo_python.txt |
Q:
Python template engine
Could it be possible if somebody could help me get started in writing a python template engine? I'm new to python and as I learn the language I've managed to write a little MVC framework running in its own light-weight-WSGI-like server.
I've managed to write a script that finds and replaces ... | Python template engine | Could it be possible if somebody could help me get started in writing a python template engine? I'm new to python and as I learn the language I've managed to write a little MVC framework running in its own light-weight-WSGI-like server.
I've managed to write a script that finds and replaces keys for values:
(Obviously ... | [
"There are many powerful template languages supported by Python out there. I prefer Jinja2. Also take a look at Mako and Genshi.\nMako is fastest among three, but it's ideology allows to have a complex code logic right in template that provoke MVC principles violation from time to time.\nGenshi has excellent concep... | [
20,
4,
1
] | [] | [] | [
"python",
"templates"
] | stackoverflow_0002955615_python_templates.txt |
Q:
Python - Code snippet not working on Python 2.5.6, using IDLE
I am using a piece of self-modifying code for a college project.
Here it is:
import datetime
import inspect
import re
import sys
def main():
# print the time it is last run
lastrun = 'Mon Jun 8 16:31:27 2009'
print "This program was last ... | Python - Code snippet not working on Python 2.5.6, using IDLE | I am using a piece of self-modifying code for a college project.
Here it is:
import datetime
import inspect
import re
import sys
def main():
# print the time it is last run
lastrun = 'Mon Jun 8 16:31:27 2009'
print "This program was last run at ",
print lastrun
# read in the source code of itsel... | [
"It runs perfectly when run outside of IDLE -- so therefore the problem is not in your code alone, but in the environment where you are executing it. When you run the erroring portion of your code in IDLE you get this output:\n>>> import inspect\n>>> sys.modules[__name__]\n<module '__main__' from 'C:\\Python26\\Li... | [
4,
3
] | [] | [] | [
"python",
"python_2.5",
"python_idle",
"self_modifying"
] | stackoverflow_0002959906_python_python_2.5_python_idle_self_modifying.txt |
Q:
Find&Replace using Python - Binary file
I'm attempting to do a "find and replace" in a file on a Mac OS X computer. Although it appears to work correctly. It seems that the file is somehow altered. The text editor that I use (Text Wrangler) is unable to even open the file once this is completed.
Here is the code a... | Find&Replace using Python - Binary file | I'm attempting to do a "find and replace" in a file on a Mac OS X computer. Although it appears to work correctly. It seems that the file is somehow altered. The text editor that I use (Text Wrangler) is unable to even open the file once this is completed.
Here is the code as I have it:
import fileinput
for line ... | [
"Your code worked for me fine. However, I would suggest a different approach: don't try overwriting the file directly. I never like changing the file directly because if you have a bug or something like that the file is lost. Generate a new file then copy it over manually (or within python, if you really want to).\... | [
0,
0
] | [] | [] | [
"python",
"replace",
"text"
] | stackoverflow_0002959267_python_replace_text.txt |
Q:
Parse text of element with empty element inside
I'm trying to convert an XHTML document that uses lots of tables into a semantic XML document in Python using xml.etree. However, I'm having some trouble converting this XHTML
<TD>
Textline1<BR/>
Textline2<BR/>
Textline3
</TD>
into something like this
<lines>
... | Parse text of element with empty element inside | I'm trying to convert an XHTML document that uses lots of tables into a semantic XML document in Python using xml.etree. However, I'm having some trouble converting this XHTML
<TD>
Textline1<BR/>
Textline2<BR/>
Textline3
</TD>
into something like this
<lines>
<line>Textline1</line>
<line>Textline2</line>
<... | [
"You need to use the .tail property of the <br> elements.\nimport xml.etree.ElementTree as et\n\ndoc = \"\"\"<TD>\n Textline1<BR/>\n Textline2<BR/>\n Textline3\n</TD>\n\"\"\"\n\ne = et.fromstring(doc)\n\nitems = []\nfor x in e.getiterator():\n if x.text is not None:\n items.append(x.text.strip())\n ... | [
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002959978_python_xml.txt |
Q:
Python script names in tasklist
I am wondering, is there a way to change the name of a script so that it is not called "python.exe" in the tasklist. The reason I am asking is that I am trying to make a batch file that run's a python script. I want the batch file to check to see if the script is already running. if... | Python script names in tasklist | I am wondering, is there a way to change the name of a script so that it is not called "python.exe" in the tasklist. The reason I am asking is that I am trying to make a batch file that run's a python script. I want the batch file to check to see if the script is already running. if the script is already running then t... | [
"Maybe you can try this : http://code.google.com/p/procname/\n",
"This library does not work on Windows, and shouldn't be used in production code. Manipulation the argv array is a rather dirty hack.\nGenerally I'd not try to identify processes by scanning the process table. This is not really reliable, as proce... | [
1,
0,
0,
0,
0
] | [] | [] | [
"batch_file",
"python"
] | stackoverflow_0002958246_batch_file_python.txt |
Q:
consuming soap in python on appengine
i want to write an app (python) which reads the soap i get from the soap generating service on appengine. the services docs says: '...you will get the SOAP call with the XML packet...'
i get this packet on an url i can set.
how can i read this xml packet and parse the values i... | consuming soap in python on appengine | i want to write an app (python) which reads the soap i get from the soap generating service on appengine. the services docs says: '...you will get the SOAP call with the XML packet...'
i get this packet on an url i can set.
how can i read this xml packet and parse the values i need?
| [
"You should use a SOAP client framework, like for instance this: https://fedorahosted.org/suds/\n"
] | [
0
] | [] | [] | [
"http",
"python",
"soap",
"xml"
] | stackoverflow_0002960602_http_python_soap_xml.txt |
Q:
Help converting code using httlib2 to use urllib2
What am I trying to do?
Visit a site, retrieve cookie, visit the next page by sending in the cookie info. It all works but httplib2 is giving me one too many problems with socks proxy on one site.
http = httplib2.Http()
main_url = 'http://mywebsite.com/get.aspx?id... | Help converting code using httlib2 to use urllib2 | What am I trying to do?
Visit a site, retrieve cookie, visit the next page by sending in the cookie info. It all works but httplib2 is giving me one too many problems with socks proxy on one site.
http = httplib2.Http()
main_url = 'http://mywebsite.com/get.aspx?id='+ id +'&rows=25'
response, content = http.request(mai... | [
"Use cookielib, it'll handle all the cookie related work as automatically as a web browser would.\nExample:\nimport urllib2\nimport cookielib\n\ncookie_jar = cookielib.LWPCookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))\n\n#Get the first page with the cookie, installing it in the ... | [
3
] | [] | [] | [
"httplib2",
"python",
"screen_scraping",
"urllib2"
] | stackoverflow_0002960571_httplib2_python_screen_scraping_urllib2.txt |
Q:
How to make item view render rich (html) text in PyQt?
I'm trying to translate code from this thread in python:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
__data__ = [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna... | How to make item view render rich (html) text in PyQt? | I'm trying to translate code from this thread in python:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
__data__ = [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud ex... | [
"The code doesn't respect the desired target drawing area (option.rect):\nctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height())\n\nThe above clips the portion of the QTextDocument drawn to the specified region. You really want to translate the painter so that the it starts painting at t... | [
6
] | [] | [] | [
"pyqt",
"python",
"qlistview",
"qstyleditemdelegate"
] | stackoverflow_0002959850_pyqt_python_qlistview_qstyleditemdelegate.txt |
Q:
What is (self) in the python code? (OOP question)
class MyController(BaseController):
def index(self):
# Return a rendered template
#return render('/test.mako')
# or, return a response
return ''
Why does the function "index" have "self"?
I got this code from Pylons controller
... | What is (self) in the python code? (OOP question) | class MyController(BaseController):
def index(self):
# Return a rendered template
#return render('/test.mako')
# or, return a response
return ''
Why does the function "index" have "self"?
I got this code from Pylons controller
| [
"Many languages, like C++ and Java, have an implicit pointer inside member functions. In those languages, it is \"this\". Python, on the other hand, requires an EXPLICIT name to be given to that pointer. By convention, it is \"self\", although you could actually put anything you like in there as long as it is a ... | [
3,
2,
1
] | [] | [] | [
"controller",
"model_view_controller",
"oop",
"pylons",
"python"
] | stackoverflow_0002960878_controller_model_view_controller_oop_pylons_python.txt |
Q:
regex in python, can this be improved upon?
I have this piece of code that finds words that begin with @ or #,
p = re.findall(r'@\w+|#\w+', str)
Now what irks me about this is repeating \w+. I am sure there is a way to do something like
p = re.findall(r'(@|#)\w+', str)
That will produce the same result but it do... | regex in python, can this be improved upon? | I have this piece of code that finds words that begin with @ or #,
p = re.findall(r'@\w+|#\w+', str)
Now what irks me about this is repeating \w+. I am sure there is a way to do something like
p = re.findall(r'(@|#)\w+', str)
That will produce the same result but it doesn't, it instead returns only # and @. How can t... | [
"The solution\nYou have two options:\n\nUse non-capturing group: (?:@|#)\\w+\nOr even better, a character class: [@#]\\w+\n\nReferences\n\nregular-expressions.info/Character Class and Groups\n\n\nUnderstanding findall\nThe problem you were having is due to how findall return matches depending on how many capturing ... | [
10
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002960969_python_regex.txt |
Q:
Get the previous date in Mysql
I have a table formatted similar to this:
Date | ID | Value | Difference
I need to get the difference between a record's value column, and the previous record's value column based off of the date.
I.E
2 days ago | cow | 1 | Null
Yesterday | cow | 2 | Null
Today | cow | 3 | Null
Yeste... | Get the previous date in Mysql | I have a table formatted similar to this:
Date | ID | Value | Difference
I need to get the difference between a record's value column, and the previous record's value column based off of the date.
I.E
2 days ago | cow | 1 | Null
Yesterday | cow | 2 | Null
Today | cow | 3 | Null
Yesterdays difference would be 1, and tod... | [
"Use a SELECT... WHERE date <= NOW() && date >= ( NOW() - 90000 ) (90,000 is 25 hours, giving you a little leeway with the insert time), and then take the difference between the rows in python.\n",
"In Python, or stored procedure, or other language :\nQuery Data using your criteria\nFetch first record\nBegin Loop... | [
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002960481_mysql_python.txt |
Q:
How to stop Python from adding whitespace while iterating?
My Python code:
mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
for row in mapArray:
for cell in row:
print cell,
print
print
prints this:
# # #
# # #
# # #
why not this:
###
###
###
Thanks much!
A:
Change your print cell, t... | How to stop Python from adding whitespace while iterating? | My Python code:
mapArray = [["#","#","#"],["#","#","#"],["#","#","#"]]
for row in mapArray:
for cell in row:
print cell,
print
print
prints this:
# # #
# # #
# # #
why not this:
###
###
###
Thanks much!
| [
"Change your print cell, to sys.stdout.write(cell). After importing sys, of course.\n",
"My preferred solution when I want Python to only print what I tell it to without inserting newlines or spaces is to use sys.stdout:\nfrom sys import stdout\nmapArray = [[\"#\",\"#\",\"#\"],[\"#\",\"#\",\"#\"],[\"#\",\"#\",\"... | [
2,
2,
2
] | [] | [] | [
"arrays",
"iteration",
"multidimensional_array",
"python"
] | stackoverflow_0002960978_arrays_iteration_multidimensional_array_python.txt |
Q:
merging in python
I have the following 4 arrays ( grouped in 2 groups ) that I would like to merge in ascending order by the keys array.
I can use also dictionaries as structure if it is easier.
Has python any command or something to make this quickly possible?
Regards
MN
# group 1
[7, 2, 3, 5] #keys
[10,11,12... | merging in python | I have the following 4 arrays ( grouped in 2 groups ) that I would like to merge in ascending order by the keys array.
I can use also dictionaries as structure if it is easier.
Has python any command or something to make this quickly possible?
Regards
MN
# group 1
[7, 2, 3, 5] #keys
[10,11,12,26] #values
[0, 4... | [
"I would recommend that you use dictionaries, then you can use d.update to update one dictionary with keys and values from the other.\nNote that dictionaries in Python are not ordered. Instead when you need to iterate you can get their keys, order those and iterate over the keys in order getting the corresponding v... | [
6,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002960855_python.txt |
Q:
"Slice" out one element from a python dictionary
I have a dictionary:
D = { "foo" : "bar", "baz" : "bip" }
and I want to create new dictionary that has a copy of one of it's elements k. So if k = "baz":
R = { "baz" : "bip" }
what I've got now is:
R = { k : D[k] }
But in my case k is a complex expression and I'v... | "Slice" out one element from a python dictionary | I have a dictionary:
D = { "foo" : "bar", "baz" : "bip" }
and I want to create new dictionary that has a copy of one of it's elements k. So if k = "baz":
R = { "baz" : "bip" }
what I've got now is:
R = { k : D[k] }
But in my case k is a complex expression and I've got a whole stack of these. Caching k in a temporary... | [
"def take(dictionary, key):\n return {key: dictionary[key]}\n\nR = take(D, k)\n\n",
"You can't get much \"cleaner\" than what you have. Assuming your definition of clean is fewer characters.\nAdding a function call to do such a simple task seems like it would do more to confuse your code than make it cleaner.... | [
3,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002960779_dictionary_python.txt |
Q:
Replacement for PyString_AS_STRING in python 3.x
In python 2.x versions there is a function named as PyString_AS_STRING to convert a pyobject pointer to a string or char pointer.
How can we achieve the same functionality in python 3?
A:
There's a PyUnicode_AS_UNICODE macro.
BTW: PyString_AS_STRING only works for... | Replacement for PyString_AS_STRING in python 3.x | In python 2.x versions there is a function named as PyString_AS_STRING to convert a pyobject pointer to a string or char pointer.
How can we achieve the same functionality in python 3?
| [
"There's a PyUnicode_AS_UNICODE macro.\nBTW: PyString_AS_STRING only works for string objects, returning a C string.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002960847_python.txt |
Q:
Example when request.POST contain query string in django
Please post example code when request.POST contain query string in django, because i think my django version is bugged.
EDIT:
You simple can't, query string is always in GET, and this was my problem.
A:
If your request is post:
request.method == 'POST'
b... | Example when request.POST contain query string in django | Please post example code when request.POST contain query string in django, because i think my django version is bugged.
EDIT:
You simple can't, query string is always in GET, and this was my problem.
| [
"If your request is post:\n\nrequest.method == 'POST'\n\nbut the requested url contains a query string. e.g:\n/your-url?param1=value-one\nyou can still take POST parameters through:\n\nrequest.POST.get(\"my-field\", None)\n\nand query string parameters through:\n\nrequest.GET.get(\"param1\")\n\nalthrough, you pick ... | [
41
] | [] | [] | [
"django",
"post",
"python"
] | stackoverflow_0002961317_django_post_python.txt |
Q:
Controlling processes from Python
I want to control several subprocesses of the same type from python (I am under linux).
I want to:
Start them.
Stop them.
Ask if they are still running.
I can start a processes with with spawnl, and get the pid. Using this pid I can stop it with kill. And I am sure there is also... | Controlling processes from Python | I want to control several subprocesses of the same type from python (I am under linux).
I want to:
Start them.
Stop them.
Ask if they are still running.
I can start a processes with with spawnl, and get the pid. Using this pid I can stop it with kill. And I am sure there is also a way to ask if it is running with the... | [
"You can use subprocess.Popen to start the other process, and save the resulting Popen object. With methods on that object, you can check if the process still alive, wait for it to finish, terminate it, kill it -- all without any risk of pid-based confusion! As a plus, this is also a more cross-platform approach,... | [
7
] | [] | [] | [
"pid",
"python"
] | stackoverflow_0002961660_pid_python.txt |
Q:
Segmentation fault while redirecting sys.stdout to Tkinter.Text widget
I'm in the process of building a GUI-based application with Python/Tkinter that builds on top of the existing Python bdb module. In this application, I want to silence all stdout/stderr from the console and redirect it to my GUI. To accomplis... | Segmentation fault while redirecting sys.stdout to Tkinter.Text widget | I'm in the process of building a GUI-based application with Python/Tkinter that builds on top of the existing Python bdb module. In this application, I want to silence all stdout/stderr from the console and redirect it to my GUI. To accomplish this purpose, I've written a specialized Tkinter.Text object (code at the ... | [
"I'm assuming this is part of a larger, threaded program. \nInstead of using a lock, have your code write to a thread-safe queue object. Then, in your main thread you poll the queue and write to the text widget. You can do the polling using the event loop (versus writing your own loop) by running the polling job wh... | [
4,
4
] | [] | [] | [
"python",
"redirect",
"segmentation_fault",
"stdout",
"tkinter"
] | stackoverflow_0002914603_python_redirect_segmentation_fault_stdout_tkinter.txt |
Q:
importing symbols from python package into caller's namespace
I have a little internal DSL written in a single Python file that has grown to a point where I would like to split the contents across a number of different directories + files.
The new directory structure currently looks like this:
dsl/
__init__.py... | importing symbols from python package into caller's namespace | I have a little internal DSL written in a single Python file that has grown to a point where I would like to split the contents across a number of different directories + files.
The new directory structure currently looks like this:
dsl/
__init__.py
types/
__init__.py
type1.py
type2.py
... | [
"You'll have to say\nfrom dsl import *\n\n",
"This is what I would do\nIn dsl/init__.py, add\ndef import_symbols(namespace):\n namespace['type1'] = dsl.types.type1\n namespace['type2'] = dsl.types.type2\n\nFrom the caller, do\nimport dsl\n\ndsl.import_symbols(globals())\n\nNo only can you import symbols fro... | [
3,
2,
1,
0
] | [] | [] | [
"import",
"namespaces",
"package",
"python"
] | stackoverflow_0002959109_import_namespaces_package_python.txt |
Q:
Why do most web hosting services support only PHP as the server-side language?
I have been working with Java and Python, so I found a nice web host which has support for these.
But my question is, why is it so hard to find such hosts?
I understand that PHP is easy, and I also understand that Oracle host is hard to... | Why do most web hosting services support only PHP as the server-side language? | I have been working with Java and Python, so I found a nice web host which has support for these.
But my question is, why is it so hard to find such hosts?
I understand that PHP is easy, and I also understand that Oracle host is hard to find ($$$ of course), but what do they have against some good open-source, complete... | [
"With Java, hosting is more complicated. You can't just load mod_java and go, you need Tomcat or JBoss, or some other Servlet/JSP hosting environment, and they're non-trivial to configure and maintain.\nWith Python, I think it's just that it's not as commonly used for web services. I use much more Python than PHP, ... | [
2,
0,
0,
0
] | [
"I haven't seen Python support missing from any webhosts ... I'm not sure where you're looking. Checkout out Webfaction - they really are the best for smaller stuff bar none.\n"
] | [
-2
] | [
"java",
"open_source",
"python",
"server_side"
] | stackoverflow_0002961535_java_open_source_python_server_side.txt |
Q:
What is the pythonic way to setattr() for a module?
In a class method, I can add attributes using the built-in function:
setattr(self, "var_name", value).
If I want to do the same thing within a module, I can do something like:
globals()["var_name"] = value
Is this the best way to do this, or is there a more... | What is the pythonic way to setattr() for a module? | In a class method, I can add attributes using the built-in function:
setattr(self, "var_name", value).
If I want to do the same thing within a module, I can do something like:
globals()["var_name"] = value
Is this the best way to do this, or is there a more pythonic solution?
| [
"Your suggested approach\nglobals()[\"var_name\"] = value\n\nis indeed the most Pythonic way. In particular, it's significantly more Pythonic than using eval, which would be your main (though not only) alternative.\nHowever, if you still want to use setattr, you may do so by using sys.modules to get a reference to... | [
6
] | [] | [] | [
"attributes",
"module",
"python"
] | stackoverflow_0002962281_attributes_module_python.txt |
Q:
Python: Attractive, clean, packagable windows GUI library
I need to create a simple windows based GUI for a desktop application that will be downloaded by end users. The application is written in python and will be packaged as an installer or executable.
The functionality I need is simple - selecting from various... | Python: Attractive, clean, packagable windows GUI library | I need to create a simple windows based GUI for a desktop application that will be downloaded by end users. The application is written in python and will be packaged as an installer or executable.
The functionality I need is simple - selecting from various lists, showing progress bars, etc. No animations, sprites, or ... | [
"tkinter's major advantage (IMHO!) is that it comes with Python (at least on Windows). It looks ugly, and there's no progress bar or something like that (at least not builtin). Being a thin wrapper around Tk, its API doesn't feel very elegant or intuitive. However, there are quite a few good Tkinter resources on th... | [
3,
3,
3,
1,
1
] | [] | [] | [
"python",
"tkinter",
"user_interface",
"wxpython"
] | stackoverflow_0002962194_python_tkinter_user_interface_wxpython.txt |
Q:
Python retrieving windows service information
Can python retrieve the name of the user that owns a windows service?
I've had a fiddle with win32serviceutil but to no avail, nor can I find much documentation on it beyond starting and stopping services.
Thanks!
A:
Sorted, I had the service run a python script with... | Python retrieving windows service information | Can python retrieve the name of the user that owns a windows service?
I've had a fiddle with win32serviceutil but to no avail, nor can I find much documentation on it beyond starting and stopping services.
Thanks!
| [
"Sorted, I had the service run a python script with win32api.GetUserName() as it's output.\n"
] | [
1
] | [] | [] | [
"python",
"windows",
"windows_services"
] | stackoverflow_0002962597_python_windows_windows_services.txt |
Q:
Where is python freeze utility
I just installed python 2.6 on my mac, mainly because I couldn't find freeze in my 2.5 distribution. I am wondering where freeze is. Is it even installed at all in the mac distribution?
A:
In addition to the built-in freeze, you might want to look at some of the third-party variati... | Where is python freeze utility | I just installed python 2.6 on my mac, mainly because I couldn't find freeze in my 2.5 distribution. I am wondering where freeze is. Is it even installed at all in the mac distribution?
| [
"In addition to the built-in freeze, you might want to look at some of the third-party variations on the same idea. I keep this list bookmarked.\n",
"I don't think it's installed as part of the Mac distribution; you can find it online here, or perhaps more conveniently download and unpack the sources separately ... | [
4,
3,
1,
0
] | [] | [] | [
"freeze",
"macos",
"python"
] | stackoverflow_0002946909_freeze_macos_python.txt |
Q:
Remove certain filetypes in Python
I am running a script that walks a directory structure and generates new files in each folder in the directory. I want to delete some of the files right after creation. This is my idea, but it is quite wrong I imagine:
directory = os.path.dirname(obj)
m = MeshExporterApplication(... | Remove certain filetypes in Python | I am running a script that walks a directory structure and generates new files in each folder in the directory. I want to delete some of the files right after creation. This is my idea, but it is quite wrong I imagine:
directory = os.path.dirname(obj)
m = MeshExporterApplication(directory)
os.remove(os.path.join(direct... | [
"You can use the glob module:\nimport glob\nglob.glob(\"*.mesh.xml\")\n\nto get a list of matching files. Then you delete them, one by one.\ndirectory = os.path.dirname(obj)\nm = MeshExporterApplication(directory)\n\n# you can use absolute pathes in the glob\n# to ensure, that you're purging the files in \n# the ri... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0002962683_python.txt |
Q:
How do I make C++/wxWidgets code accessible to a wxPython app?
I have a code library which is written in C++ and makes extensive use of the wxWidgets library. I'm now trying to wrap my library (currently using SWIG) so that it's callable from wxPython, but I've hit a wall:
------ Build started: Project: MyLibLib, ... | How do I make C++/wxWidgets code accessible to a wxPython app? | I have a code library which is written in C++ and makes extensive use of the wxWidgets library. I'm now trying to wrap my library (currently using SWIG) so that it's callable from wxPython, but I've hit a wall:
------ Build started: Project: MyLibLib, Configuration: Release_SWIG_OutputForBin Win32 ------
Performing Cus... | [
"Looks like your Mylib.i is not emitting in its generated C file to #include the header(s) defining wxCharBuffer and so on (or maybe missing #defines that make those include actually perform the needed function definitions, but that's less likely). Do you have the needed\n%{\n #include \"wxwhatever.h\"\n%}\n\nand ... | [
0
] | [] | [] | [
"c++",
"python",
"swig",
"wxwidgets"
] | stackoverflow_0002962497_c++_python_swig_wxwidgets.txt |
Q:
How do I use django settings in my logging.ini file?
I have a BASE_DIR setting in my settings.py file:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
I need to use this variable in my logging.ini file to setup my file handler paths.
The initialization of logging happens in the same file, the settings.py fi... | How do I use django settings in my logging.ini file? | I have a BASE_DIR setting in my settings.py file:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
I need to use this variable in my logging.ini file to setup my file handler paths.
The initialization of logging happens in the same file, the settings.py file, below my BASE_DIR variable. Here I tell it the path of... | [
"As per the docs,\nlogging.fileConfig(fname[, defaults])\n\n\nReads the logging configuration from a\n ConfigParser-format file named fname.\n This function can be called several\n times from an application, allowing an\n end user the ability to select from\n various pre-canned configurations (if\n the develo... | [
3
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0002962666_django_logging_python.txt |
Q:
String replacement on a whole text file in Python 3.x?
How can I replace a string with another string, within a given text file. Do I just loop through readline() and run the replacement while saving out to a new file? Or is there a better way?
I'm thinking that I could read the whole thing into memory, but I'm ... | String replacement on a whole text file in Python 3.x? | How can I replace a string with another string, within a given text file. Do I just loop through readline() and run the replacement while saving out to a new file? Or is there a better way?
I'm thinking that I could read the whole thing into memory, but I'm looking for a more elegant solution...
Thanks in advance
| [
"fileinput is the module from the Python standard library that supports \"what looks like in-place updating of text files\" as well as various other related tasks.\nfor line in fileinput.input(['thefile.txt'], inplace=True):\n print(line.replace('old stuff', 'shiny new stuff'), end='')\n\nThis code is all you ne... | [
12,
4
] | [] | [] | [
"python",
"python_3.x",
"replace",
"string"
] | stackoverflow_0002961524_python_python_3.x_replace_string.txt |
Q:
Best practice: How to persist simple data without a database in django?
I'm building a website that doesn't require a database because a REST API "is the database". (Except you don't want to be putting site-specific things in there, since the API is used by mostly mobile clients)
However there's a few things that ... | Best practice: How to persist simple data without a database in django? | I'm building a website that doesn't require a database because a REST API "is the database". (Except you don't want to be putting site-specific things in there, since the API is used by mostly mobile clients)
However there's a few things that normally would be put in a database, for example the "jobs" page. You have ma... | [
"Why not still keep it in a database? Your remote REST store is all well and funky, but if you've got local data, there's nothing (unless there's spec saying so) to stop you storing some stuff in a local db. Doesn't have to be anything v glamorous - could be sqlite, or you could have some fun with redis, etc.\n",
... | [
5,
2,
1
] | [] | [] | [
"django",
"persistence",
"python"
] | stackoverflow_0002959503_django_persistence_python.txt |
Q:
virtualenv on Windows: not over-riding installed package
My current setup is Python 2.5/ Django 1.1.1 on Windows. I want to start using Django 1.2 on some projects, but can't use it for everything. Which is just the sort of thing I've got virtualenv for. However, I'm running into a problem I've never encountered a... | virtualenv on Windows: not over-riding installed package | My current setup is Python 2.5/ Django 1.1.1 on Windows. I want to start using Django 1.2 on some projects, but can't use it for everything. Which is just the sort of thing I've got virtualenv for. However, I'm running into a problem I've never encountered and it's hard to Google for: installing Django 1.2 into a virtu... | [
"Based on the bug you filed at bitbucket, it looks like you're using the PYTHONPATH environment variable to point to a directory with some packages, including Django 1.1.1. By design, PYTHONPATH always comes first in your sys.path, even when you have a virtualenv activated (because PYTHONPATH is under your direct a... | [
9,
2
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0002961103_python_virtualenv.txt |
Q:
Is PyOpenGL a good place to start learning opengl programming?
I want to start learning OpenGL but I don't really want to have to learn another language to do it. I already am pretty proficient in python and enjoy the language. I just want to know how close it is to the regular api? Will I be able to pretty easily... | Is PyOpenGL a good place to start learning opengl programming? | I want to start learning OpenGL but I don't really want to have to learn another language to do it. I already am pretty proficient in python and enjoy the language. I just want to know how close it is to the regular api? Will I be able to pretty easily follow tutorials and books without too much trouble?
I know C++ giv... | [
"With the caveat that I have done very little OpenGL programming myself, I believe that for the purposes of learning, PyOpenGL is a good choice. The main reason is that PyOpenGL, like most other OpenGL wrappers, is just that: a thin wrapper around the OpenGL API. \nOne large benefit of PyOpenGL is that while in C ... | [
13,
0
] | [] | [] | [
"graphics",
"pyopengl",
"python"
] | stackoverflow_0002962571_graphics_pyopengl_python.txt |
Q:
Python: Find X to Y in a list of strings
I have a list of maybe a 100 or so elements that is actually an email with each line as an element. The list is slightly variable because lines that have a \n in them are put in a separate element so I can't simply slice using fixed values. I essentially need a variable s... | Python: Find X to Y in a list of strings | I have a list of maybe a 100 or so elements that is actually an email with each line as an element. The list is slightly variable because lines that have a \n in them are put in a separate element so I can't simply slice using fixed values. I essentially need a variable start and stop phrase (needs to be a partial se... | [
">>> email = ['apples','bananas','cats','dogs','elephants','fish','gee']\n>>> start, stop = 'ban', 'ele'\n>>> ind_s = next(i for i, j in enumerate(email) if j.startswith(start))\n>>> ind_e = next(i for i, j in enumerate(email) if j.startswith(stop) and i > ind_s)\n>>> email[ind_s+1:ind_e]\n['cats', 'dogs']\n\nTo sa... | [
5,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0002959643_python.txt |
Q:
How to call a specific, unknown Python object attribute?
I'm working to create a simple Python script that will ultimately tell you how many blog entries were posted in a given month, and the pyblog app is proving very helpful.
However, when I create the blog object, I don't know how to access it's various attribu... | How to call a specific, unknown Python object attribute? | I'm working to create a simple Python script that will ultimately tell you how many blog entries were posted in a given month, and the pyblog app is proving very helpful.
However, when I create the blog object, I don't know how to access it's various attributes. I can print them all out by printing one item from the di... | [
"If blog.get_recent_posts(1) was a dictionary, the print would show leading and trailing braces, while what you're showing starts in the middle of nowhere and ends in another middle of nowhere -- absolutely absurd.\nI'm going to assume you made some weird copy and past error and that the thing is a dictionary. In ... | [
2
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0002963035_python_xml_rpc.txt |
Q:
Python and MySQLdb
I have the following query that I'm executing using a Python script (by using the MySQLdb module).
conn=MySQLdb.connect (host = "localhost", user = "root",passwd = "<password>",db = "test")
cursor = conn.cursor ()
preamble='set @radius=%s; set @o_lat=%s; set @o_lon=%s; '%(radius,latitude,longit... | Python and MySQLdb | I have the following query that I'm executing using a Python script (by using the MySQLdb module).
conn=MySQLdb.connect (host = "localhost", user = "root",passwd = "<password>",db = "test")
cursor = conn.cursor ()
preamble='set @radius=%s; set @o_lat=%s; set @o_lon=%s; '%(radius,latitude,longitude)
query='SELECT *, (6... | [
"AFAIK you can't run multiple statements using execute().\nYou can, however, let MySQLdb handle the value substitutions. \nNote that there are two arguments being passed to execute().\nAlso, just running execute() doesn't actually return any results.\nYou need to use fetchone() or fetchmany() or fetchall().\ncurso... | [
3,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002963114_mysql_python.txt |
Q:
Managing Instances in Python
I am new to Python and this is my first time asking a stackOverflow question, but a long time reader. I am working on a simple card based game but am having trouble managing instances of my Hand class. If you look below you can see that the hand class is a simple container for cards(... | Managing Instances in Python | I am new to Python and this is my first time asking a stackOverflow question, but a long time reader. I am working on a simple card based game but am having trouble managing instances of my Hand class. If you look below you can see that the hand class is a simple container for cards(which are just int values) and eac... | [
"\nFrom my experience in C and Java it seems that I am somehow making my Hand class static.\n\nActually, that is basically what you're doing. Well, not really making the class static, but making the variable static.\nWhen you write declarations like this:\nclass Hand:\n cards = []\n\nthat variable (cards) is ass... | [
4,
3,
0
] | [] | [] | [
"class",
"initialization",
"instances",
"python",
"static"
] | stackoverflow_0002962989_class_initialization_instances_python_static.txt |
Q:
Windows environment variables change when opening command line?
Sometimes when I change my environment variables in Windows, and then use software the depends on those variables, they are not properly updated.
And good example is to change a variable, then open up Windows Command Line and echo the variable and see... | Windows environment variables change when opening command line? | Sometimes when I change my environment variables in Windows, and then use software the depends on those variables, they are not properly updated.
And good example is to change a variable, then open up Windows Command Line and echo the variable and see that it hasn't been changed, even though you properly changed it in ... | [
"When you change an environment variable in the System Properties tab, the new value will propagate to the Windows Explorer, and any apps (such as cmd.exe) opened from the Windows Explorer (or the Run box, Start Menu, etc.) should see the new value.\nHowever, if you're running a program such as an editor or python ... | [
3
] | [] | [] | [
"command_line",
"environment_variables",
"python",
"windows_7"
] | stackoverflow_0002963331_command_line_environment_variables_python_windows_7.txt |
Q:
How refresh a DrawingArea in PyGTK?
I have an interface created with Glade. It contains a DrawingArea and buttons.
I tried to create a Thread to refresh every X time my Canva. After a few seconds, I get error messages like:
"X Window Server 0.0", "Fatal Error IO 11"
Here is my code :
import pygtk
pygtk.require("2.... | How refresh a DrawingArea in PyGTK? | I have an interface created with Glade. It contains a DrawingArea and buttons.
I tried to create a Thread to refresh every X time my Canva. After a few seconds, I get error messages like:
"X Window Server 0.0", "Fatal Error IO 11"
Here is my code :
import pygtk
pygtk.require("2.0")
import gtk
import Canvas
import threa... | [
"To use Python threads in PyGTK, you need to surround any access to shared GTK objects with gtk.gdk.threads_enter() and gtk.gdk.threads_leave(). See also the threads_enter() method.\nYou might even be better off using GTKs functions for periodic function calls, such as timeout_add(...) and timeout_add_seconds(...) ... | [
1
] | [] | [] | [
"drawing",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0002963585_drawing_multithreading_pygtk_python.txt |
Q:
Python: avoiding fraction simplification
I'm working on a music app' in Python and would like to use the fractions module to handle time signatures amongst other things. My problem is that fractions get simplified, i.e.:
>>> from fractions import Fraction
>>> x = Fraction(4, 4)
>>> x
Fraction(1, 1)
However, it is... | Python: avoiding fraction simplification | I'm working on a music app' in Python and would like to use the fractions module to handle time signatures amongst other things. My problem is that fractions get simplified, i.e.:
>>> from fractions import Fraction
>>> x = Fraction(4, 4)
>>> x
Fraction(1, 1)
However, it is important from a musical point of view that 4... | [
"Yes: make a custom class for it.\nMusical time signatures are not fractions, so it doesn't make sense to represent them with a math class.\n",
"You should use some data structure other than Fraction. Just a plain tuple would be simplest, though you could also make your own class. If you need to do calculations... | [
9,
3,
0
] | [] | [] | [
"fractions",
"music_notation",
"python"
] | stackoverflow_0002863270_fractions_music_notation_python.txt |
Q:
How do I debug a HTTP 502 error?
I have a Python Tornado server sitting behind a nginx frontend. Every now and then, but not every time, I get a 502 error. I look in the nginx access log and I see this:
127.0.0.1 - - [02/Jun/2010:18:04:02 -0400] "POST /a/question/updates HTTP/1.1" 502 173 "http://localhost/tagge... | How do I debug a HTTP 502 error? | I have a Python Tornado server sitting behind a nginx frontend. Every now and then, but not every time, I get a 502 error. I look in the nginx access log and I see this:
127.0.0.1 - - [02/Jun/2010:18:04:02 -0400] "POST /a/question/updates HTTP/1.1" 502 173 "http://localhost/tagged/python" "Mozilla/5.0 (X11; U; Linux ... | [
"The line from the error log is very informative in my opinion. It says the connection was refused by the upstream, it contains client IP, Nginx server config, request line, hostname, upstream URL and referrer.\nIt is pretty clear you must look at the upstream (or firewall) to find out the reason.\nIn case you'd li... | [
3
] | [] | [] | [
"http",
"nginx",
"python"
] | stackoverflow_0002962439_http_nginx_python.txt |
Q:
finding and returning a string with a specified prefix
I am close but I am not sure what to do with the restuling match object. If I do
p = re.search('[/@.* /]', str)
I'll get any words that start with @ and end up with a space. This is what I want. However this returns a Match object that I dont' know what to d... | finding and returning a string with a specified prefix | I am close but I am not sure what to do with the restuling match object. If I do
p = re.search('[/@.* /]', str)
I'll get any words that start with @ and end up with a space. This is what I want. However this returns a Match object that I dont' know what to do with. What's the most computationally efficient way of fin... | [
"The following regular expression do what you need:\nimport re\ns = \"Hi there @guy\"\np = re.search(r'@(\\w+)', s)\nprint p.group(1)\n\nIt will also work for the following string formats:\n\ns = \"Hi there @guy \" # notice the trailing space\ns = \"Hi there @guy,\" # notice the trailing comma\ns = \"Hi there @guy ... | [
3,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0002956353_python_regex_string.txt |
Q:
best CAPTCHA framework for gae
i need a CAPTCHA framework on google-app-engine
what a CAPTCHA framework you are using .
thanks
like this :http://recaptcha.net/learnmore.html
A:
reCAPTCHA is nice. Heres a tutorial on how to make it work in google app engine.
| best CAPTCHA framework for gae | i need a CAPTCHA framework on google-app-engine
what a CAPTCHA framework you are using .
thanks
like this :http://recaptcha.net/learnmore.html
| [
"reCAPTCHA is nice. Heres a tutorial on how to make it work in google app engine.\n"
] | [
2
] | [] | [] | [
"captcha",
"frameworks",
"google_app_engine",
"python"
] | stackoverflow_0002963939_captcha_frameworks_google_app_engine_python.txt |
Q:
How do I copy a python function to a remote machine and then execute it?
I'm trying to create a construct in Python 3 that will allow me to easily execute a function on a remote machine.
Assuming I've already got a python tcp server that will run the functions it receives, running on the remote server, I'm current... | How do I copy a python function to a remote machine and then execute it? | I'm trying to create a construct in Python 3 that will allow me to easily execute a function on a remote machine.
Assuming I've already got a python tcp server that will run the functions it receives, running on the remote server, I'm currently looking at using a decorator like
@execute_on(address, port)
This would cr... | [
"The approach you outline is extremely risky unless the remote server is somehow very strongly protected or \"extremely sandboxed\" (e.g a BSD \"jail\") -- anybody who can send functions to it would be able to run arbitrary code there.\nAssuming you have an authentication system that you trust entirely, comes the \... | [
3,
3,
1,
0,
0
] | [] | [] | [
"parsing",
"python",
"remote_execution"
] | stackoverflow_0002962531_parsing_python_remote_execution.txt |
Q:
Meaning of leading underscore in list of tuples used to define choice fields?
I've seen a few examples defining choice fields like so:
COUNTRIES = (
('fr', _('France')),
('de', _('Germany')),
...
)
(Source: http://code.djangoproject.com/ticket/5446
Also see: http://djangosnippets.org/snippets/494/)
Wh... | Meaning of leading underscore in list of tuples used to define choice fields? | I've seen a few examples defining choice fields like so:
COUNTRIES = (
('fr', _('France')),
('de', _('Germany')),
...
)
(Source: http://code.djangoproject.com/ticket/5446
Also see: http://djangosnippets.org/snippets/494/)
What is the meaning of the leading underscores? And why is the second value in the tu... | [
"The leading underscore is the commonly used function alias for the one of the ugettext functions used by the internationalization (i18n) mechanics. \nIt means that when you have i18n running, the choicefield labels will be translated into the appropriate end-user language, if a translation is available. \nAt the ... | [
92
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0002964244_django_internationalization_python.txt |
Q:
sorting in python
I have a hashmap like so:
results[tweet_id] = {"score" : float(dot(query,doc) / (norm(query) * norm(doc))), "tweet" : tweet}
What I'd like to do is to sort results by the innser "score" key. I don't know how possible this is, I saw many sorting tutorials but they were for simple (not nested) dat... | sorting in python | I have a hashmap like so:
results[tweet_id] = {"score" : float(dot(query,doc) / (norm(query) * norm(doc))), "tweet" : tweet}
What I'd like to do is to sort results by the innser "score" key. I don't know how possible this is, I saw many sorting tutorials but they were for simple (not nested) data structures.
| [
">>> results=[{\"s\":1,\"score\":100},{\"s\":2,\"score\":101},{\"s\":3,\"score\":99},{\"s\":4,\"score\":1},{\"s\":5,\"score\":1000}]\n\n>>> from operator import itemgetter\n\n>>> sorted(results, key=itemgetter(\"score\"))\n[{'s': 4, 'score': 1}, {'s': 3, 'score': 99}, {'s': 1, 'score': 100}, {'s': 2, 'score': 101},... | [
4,
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002963959_python_regex.txt |
Q:
Python: How should I make instance variables available?
Suppose I have:
class myclass:
def __init__(self):
self.foo = "bar"
where the value of foo needs to be available to users of myclass. Is it OK to just read the value of foo directly from an instance of myclass? Should I add a get_foo method to myclass ... | Python: How should I make instance variables available? | Suppose I have:
class myclass:
def __init__(self):
self.foo = "bar"
where the value of foo needs to be available to users of myclass. Is it OK to just read the value of foo directly from an instance of myclass? Should I add a get_foo method to myclass or perhaps add a foo property? What's the best practice here?... | [
"The applicable Python maxim would be \"we're all adults here\" - if users need direct access to the value of foo, let them access it directly. A getter or property would make sense if you need to run some code when it's accessed, otherwise the direct way is best. \nAlso, you can always transparently turn it into a... | [
8,
1,
1,
1,
1
] | [] | [] | [
"class_design",
"python"
] | stackoverflow_0002964230_class_design_python.txt |
Q:
How can you dispatch on request method in Django URLpatterns?
It's clear how to create a URLPattern which dispatches from a URL regex:
(r'^books/$', books),
where books can further dispatch on request method:
def books(request):
if request.method == 'POST':
...
else:
...
I'd like to know ... | How can you dispatch on request method in Django URLpatterns? | It's clear how to create a URLPattern which dispatches from a URL regex:
(r'^books/$', books),
where books can further dispatch on request method:
def books(request):
if request.method == 'POST':
...
else:
...
I'd like to know if there is an idiomatic way to include the request method inside t... | [
"The reason it's done as a single view method is that you're usually rendering some kind of page content as context for the form you're about to submit.\nAnyway, my reason for replying it this: from your sample URLConf there it looks like you're building a REST webservice with Django -- if this is the case, you mig... | [
8,
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0002964334_django_django_urls_python.txt |
Q:
Is there an OR filter? - Django
is there any way of doing the following
Unicorn.objects.or_filter(magical=True).or_filter(unicorn_length=15).or_filter(skin_color='White').or_filter(skin_color='Blue')
where or_filter stands for an isolated match
I remember using something similar but cannot find the function anym... | Is there an OR filter? - Django | is there any way of doing the following
Unicorn.objects.or_filter(magical=True).or_filter(unicorn_length=15).or_filter(skin_color='White').or_filter(skin_color='Blue')
where or_filter stands for an isolated match
I remember using something similar but cannot find the function anymore!
Help would be great! Thanks :)
| [
"You're looking for Q objects.\n"
] | [
7
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python",
"sql"
] | stackoverflow_0002964540_django_django_models_django_queryset_python_sql.txt |
Q:
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support?
I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.
As I was googling, it turned out, that mod... | Where to get/How to build Windows binary of mod_wsgi with python 3.0 support? | I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.
As I was googling, it turned out, that mod_python, for some reasons, will not be able to support python 3.0.
The only other a... | [
"Binaries for Windows are now being supplied from the mod_wsgi site for Apache 2.2 and Python 2.6 and 3.0. Python 3.0 is only supported for mod_wsgi 3.0 onwards. See:\nhttp://code.google.com/p/modwsgi/downloads/list\n\nUPDATE July 2015\nThe above link is no longer valid. Instead see:\n\nhttps://github.com/GrahamDum... | [
10,
1,
0,
0
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"visual_c++"
] | stackoverflow_0000447015_apache_mod_wsgi_python_visual_c++.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.