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:
App Engine Session Timeout
When do user sessions (Users API in Python) timeout when logging in with Google Accounts?
A:
This is configurable in the dashboard, under Administration -> Application Settings.
The default is 1 day, but you can set it as high as 2 weeks.
| App Engine Session Timeout | When do user sessions (Users API in Python) timeout when logging in with Google Accounts?
| [
"This is configurable in the dashboard, under Administration -> Application Settings.\nThe default is 1 day, but you can set it as high as 2 weeks.\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006902663_google_app_engine_python.txt |
Q:
Mac osx Django PIL error / usr/bin/cc file error on re-install
I am getting the ever famous The _imaging C module is not installed error with a django form Image upload. I am trying to work through the many re-install tuts out there but every time I try to install pil with either pip install or brew install I get... | Mac osx Django PIL error / usr/bin/cc file error on re-install | I am getting the ever famous The _imaging C module is not installed error with a django form Image upload. I am trying to work through the many re-install tuts out there but every time I try to install pil with either pip install or brew install I get a directory not found error at /usr/bin/cc.
Has anyone ran into th... | [
"Are you sure you totally installed the Developer Tools? On Mac OS X 10.7 Lion, when you get Xcode 4.1 from the Mac App Store, it downloads an installer into /Applications. You then have to manually run that installer. That will add the expected links for /usr/bin/cc and other tools.\n"
] | [
2
] | [] | [] | [
"django",
"macos",
"python",
"python_imaging_library"
] | stackoverflow_0006902976_django_macos_python_python_imaging_library.txt |
Q:
Why does __init__ not get called if __new__ called with no args
I am trying to create (not exactly restore) an object which has its attributes saved in a database. Therefore, I do not want to call __init__. This desire appears to be inline with Guido's intended use for __new__. I do not understand why __init__ is ... | Why does __init__ not get called if __new__ called with no args | I am trying to create (not exactly restore) an object which has its attributes saved in a database. Therefore, I do not want to call __init__. This desire appears to be inline with Guido's intended use for __new__. I do not understand why __init__ is not getting called.
Take the following snippet for example, it return... | [
"The constructor (User()) is responsible for calling the allocator (User.__new__()) and the initializer (User.__init__()) in turn. Since the constructor is never invoked, the initializer is never called.\n",
"Because you're bypassing the usual construction mechanism, by calling __new__ directly. The __init__-afte... | [
13,
10
] | [] | [] | [
"python"
] | stackoverflow_0006903355_python.txt |
Q:
General programming question about scope
This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Goo... | General programming question about scope | This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Google for more information about it I would grea... | [
"\nI am not too sure what the name of this is called...\n\nI am having trouble following your pseudo-code, but you might be able to accomplish what you're looking for via:\n\nInheritance, which allows derived classes to access protected variables from a base class (static or instance variables)\nFriend functions (C... | [
2,
2,
0,
0,
0,
0
] | [] | [] | [
"c++",
"java",
"python"
] | stackoverflow_0006902981_c++_java_python.txt |
Q:
Lexer that recognizes indented blocks
I want to write a compiler for a language that denotes program blocks with white spaces, like in Python. I prefer to do this in Python, but C++ is also an option. Is there an open-source lexer that can help me do this easily, for example by generating INDENT and DEDENT identif... | Lexer that recognizes indented blocks | I want to write a compiler for a language that denotes program blocks with white spaces, like in Python. I prefer to do this in Python, but C++ is also an option. Is there an open-source lexer that can help me do this easily, for example by generating INDENT and DEDENT identifiers properly like the Python lexer does? A... | [
"LEPL is pure Python and supports offside parsing.\n",
"If you're using something like lex, you can do it this way:\n^[ \\t]+ { int new_indent = count_indent(yytext);\n if (new_indent > current_indent) {\n current_indent = new_indent;\n ... | [
4,
1
] | [] | [] | [
"compiler_construction",
"lexer",
"python",
"whitespace"
] | stackoverflow_0006903361_compiler_construction_lexer_python_whitespace.txt |
Q:
Why doesn't NetBeans recognize Django syntax?
I installed the 3 python plugins from tools >> plugins >> available plugins >> search "python" and then restarted Netbeans. Yet when I open a file with the following content:
{% block foo %}
// hi
{% endblock %}
putting my cursor on the opening block tag does not... | Why doesn't NetBeans recognize Django syntax? | I installed the 3 python plugins from tools >> plugins >> available plugins >> search "python" and then restarted Netbeans. Yet when I open a file with the following content:
{% block foo %}
// hi
{% endblock %}
putting my cursor on the opening block tag does not cause the ending block tag to be highlighted. This... | [
"Can't leave this unanswered... Because Python != Django\nDjango is a framework, and it does not comes with python, so netbeans doesn't supports Django template syntax by default, this is normal.\n"
] | [
4
] | [] | [] | [
"django",
"ide",
"netbeans",
"python"
] | stackoverflow_0006318518_django_ide_netbeans_python.txt |
Q:
Developing T.120 protocol in Python
I am creating a chat application which supports chat, group chat, file sharing, whiteboard(not mandatory). I make it own to contribute fedora. if anyone wants to join to grow it welcome(shantanubanerjee75@gmail.com). Netmeeting works on T.120 protocol but didn't find any way to ... | Developing T.120 protocol in Python | I am creating a chat application which supports chat, group chat, file sharing, whiteboard(not mandatory). I make it own to contribute fedora. if anyone wants to join to grow it welcome(shantanubanerjee75@gmail.com). Netmeeting works on T.120 protocol but didn't find any way to use it. Is there any protocol in linux wh... | [
"The Jabber protocol may suit your needs (not sure about the whiteboard part). There are many implementations of client and servers in many languages including python.\nIf you want a more generic aproach you may try with telepathy\nThere is also a more low level aproach libpurple. I did not found any recent libpurp... | [
1
] | [] | [] | [
"pygtk",
"python",
"sockets"
] | stackoverflow_0006902617_pygtk_python_sockets.txt |
Q:
How To Use Python for a Web App?
I am creating a school management system that handles file uploads and downloads from teachers and students. Furthermore, there will be a large amount of database writes and reads (e.g. which classes a student is taking, what the student's grades are etc.)
I want dynamic web pages ... | How To Use Python for a Web App? | I am creating a school management system that handles file uploads and downloads from teachers and students. Furthermore, there will be a large amount of database writes and reads (e.g. which classes a student is taking, what the student's grades are etc.)
I want dynamic web pages updated with python using an AJAX mode... | [
"\nI don't see how pyramid helps me accomplish what I can do in PHP, and if it does do this, why so complicated?\n\n\nA web framework like Pyramid is not a web framework like PHP. They're different.\nComplexity is a matter of \"experience\". If you're experienced with PHP, Python seems complex. If your experienc... | [
5,
4,
0
] | [] | [] | [
"pyramid",
"python",
"web2py"
] | stackoverflow_0006903172_pyramid_python_web2py.txt |
Q:
Defining multiple objects of the same class in python
is there any shorthand method of defining multiple objects of the same class in one line. (I'm not talking about lists or array of objects)..
i mean something like
p1,p2,p3 = Point()
any suggestions?
A:
It may be slightly more efficient to use a generator co... | Defining multiple objects of the same class in python | is there any shorthand method of defining multiple objects of the same class in one line. (I'm not talking about lists or array of objects)..
i mean something like
p1,p2,p3 = Point()
any suggestions?
| [
"It may be slightly more efficient to use a generator comprehension rather than a list comprehension:\np1, p2, p3 = (Point() for _ in range(3)) # use xrange() in versions of Python where range() does not return an iterator for more efficiency\n\nThere's also the simple solution of\np1, p2, p3 = Point(), Point(), Po... | [
6,
3,
2,
1
] | [] | [] | [
"object",
"python"
] | stackoverflow_0006903619_object_python.txt |
Q:
python:[[1,2],[3,4],[5,6],[7,8]] transform into [[1],[2,3],[4,5],[6,7],[8]] and vice versa
my current solution-pointers would be
ether via a iterator class which yields the new assembled inner lists
or via a iter function which yields the new assembled inner lists
is there another, better way to solve this chal... | python:[[1,2],[3,4],[5,6],[7,8]] transform into [[1],[2,3],[4,5],[6,7],[8]] and vice versa | my current solution-pointers would be
ether via a iterator class which yields the new assembled inner lists
or via a iter function which yields the new assembled inner lists
is there another, better way to solve this challenge?
Edit
@Glenn: good objection.
I wasn't thinking of that because I experienced lists not or... | [
"Well, here is the solutions with yield:\n# transform forwards\ndef transform_pairs( lst ):\n it = iter(lst)\n a,last = next(it)\n yield [a]\n for a,b in it:\n yield last, a\n last = b\n yield [last]\n\nTransforming the list back should look very similar, but I'll leave that to the read... | [
1,
1,
0,
0,
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"swap"
] | stackoverflow_0003496634_list_python_python_3.x_swap.txt |
Q:
Python MYSQLdb documentation missing details?
I am trying to make sense of MySQLdb documentation. I was just wondering if there are things missing from there. For example, I am trying to see what "rowcount" (a constant) actually does, but am not seeing it anywhere in the documentation.
So is the documentation inc... | Python MYSQLdb documentation missing details? | I am trying to make sense of MySQLdb documentation. I was just wondering if there are things missing from there. For example, I am trying to see what "rowcount" (a constant) actually does, but am not seeing it anywhere in the documentation.
So is the documentation incomplete or am I just looking at the wrong place?
Th... | [
"The primary source of documentation for Python database modules is the DB-API 2.0 specification:\n\n.rowcount \n\n This read-only attribute specifies the number of rows that\n the last .execute*() produced (for DQL statements like\n 'select') or affected (for DML statements like 'update' or\n ... | [
2,
2,
1,
0
] | [] | [] | [
"database",
"mysql_python",
"python"
] | stackoverflow_0006902638_database_mysql_python_python.txt |
Q:
Copying files recursively with skipping some directories in Python?
I want to copy a directory to another directory recursively. I also want to ignore some files (eg. all hidden files; everything starting with ".") and then run a function on all the other files (after copying them). This is simple to do in the she... | Copying files recursively with skipping some directories in Python? | I want to copy a directory to another directory recursively. I also want to ignore some files (eg. all hidden files; everything starting with ".") and then run a function on all the other files (after copying them). This is simple to do in the shell, but I need a Python script.
I tried using shutil.copytree, which has ... | [
"You can use os.walk to iterate over each file, apply your custom filtering function and copying over only the ones you care.\n\nos.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])\n\nGenerate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in th... | [
7,
4
] | [] | [] | [
"python"
] | stackoverflow_0006904069_python.txt |
Q:
Django static files in an egg file
I'm want to deploy my django project as an egg file which I am able to. The problem is when serving static files, how do I setup apache (using mod_wsgi) to serve content from an egg file, is it possible ?
A:
" is it possible ?" No.
Apache can only serve files. Simple files.
... | Django static files in an egg file | I'm want to deploy my django project as an egg file which I am able to. The problem is when serving static files, how do I setup apache (using mod_wsgi) to serve content from an egg file, is it possible ?
| [
"\" is it possible ?\" No.\nApache can only serve files. Simple files.\nOr -- for non files -- redirect to some other processing like mod_wsgi.\nIf you want to serve something packed inside a Python egg (really a Zip archive) you should unpack that member into an ordinary file system location.\nPython's setup.py ... | [
2
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"static_content"
] | stackoverflow_0006904128_django_mod_wsgi_python_static_content.txt |
Q:
How can I run django with mod_wsgi and use the multiprocess module?
The workflow I am dealing with (user-wise) looks like this:
User submits information and files with a form
Form is saved
Additional post-save processing is done
This is fine, but the post-save processing takes quite a while, so I'm looking to d... | How can I run django with mod_wsgi and use the multiprocess module? | The workflow I am dealing with (user-wise) looks like this:
User submits information and files with a form
Form is saved
Additional post-save processing is done
This is fine, but the post-save processing takes quite a while, so I'm looking to do it in the background and issue an HttpResponseRedirect to a message inf... | [
"Use celery.\nThe mod_wsgi environment can multi-threaded -- depending on your configuration. You do not want to interfere with how Apache, mod_wsgi, and Django are already using threads and processes to manage web server throughput.\nYou have to assume that your Django operation is a single thread and cannot do a... | [
4,
3
] | [] | [] | [
"django",
"mod_wsgi",
"multiprocessing",
"python"
] | stackoverflow_0006903564_django_mod_wsgi_multiprocessing_python.txt |
Q:
How can we figure out why certain uuencoded files are not decoding properly using Python?
We are trying to decode some uuencoded PDF files that are embedded in a txt file.
The problem we have is that most of the PDF files decoded just fine using Python's uuencode library. Here is the code:
try:
decoded_file,m=... | How can we figure out why certain uuencoded files are not decoding properly using Python? | We are trying to decode some uuencoded PDF files that are embedded in a txt file.
The problem we have is that most of the PDF files decoded just fine using Python's uuencode library. Here is the code:
try:
decoded_file,m=uudecode(fileString)
except:
decoded_file=''
However, some of the files cannot be opened a... | [
">>> uu.decode(open('0000000000-11-005978.txt'))\nWarning: Trailing garbage\n\nThe source data itself is damaged. This is further evidenced by the .. at the beginning of a line near the end.\n",
"$ python -c \"import urllib2; print len(urllib2.urlopen('http://www.sec.gov/Archives/edgar/data/914257/000000000011005... | [
1,
0
] | [] | [] | [
"python",
"uuencode"
] | stackoverflow_0006904126_python_uuencode.txt |
Q:
I don't understand how this unit test is failing
Here is part of the unit test:
from nose.tools import *
from testing import *
def test_directions():
assert_equal(scan("north"), [('direction', 'north')])
result = scan("north south east")
assert_equal(result, [('direction', 'north'), ('dire... | I don't understand how this unit test is failing | Here is part of the unit test:
from nose.tools import *
from testing import *
def test_directions():
assert_equal(scan("north"), [('direction', 'north')])
result = scan("north south east")
assert_equal(result, [('direction', 'north'), ('direction', 'south'), ('direction', 'east')])
And here i... | [
"Because your function is printing the result instead of returning it:\nwhile i < len(direction_words):\n if direction_words[i] in s.split():\n s= string.lower(s)\n print [('direction', direction_words[i] ) ] # <--- HERE\n i+=1 \n\nI haven't read through all of LPTHW yet, so I can't tell you... | [
4,
1,
0,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006904178_python_python_2.7.txt |
Q:
use Chameleon ZPT templates to write out print statements
I am using Pyramid and I know that this is probably not the preferred way to do things but it would be really cool. I have a bunch of Python scripts which print to stdout. Now I want to run these scripts as part of a request/ response in Pyramid. I mean I w... | use Chameleon ZPT templates to write out print statements | I am using Pyramid and I know that this is probably not the preferred way to do things but it would be really cool. I have a bunch of Python scripts which print to stdout. Now I want to run these scripts as part of a request/ response in Pyramid. I mean I want to capture the stdout of the scripts and write it to the te... | [
"You could pass a StringIO.StringIO object to stdout, then also pass it to the template via the context dictionary and just call StringIO.StringIO.getvalue() at the proper times in the template:\nimport sys\n\ndef my_view(request):\n old_stdout = sys.stdout\n new_stdout = StringIO.StringIO()\n sys.stdout =... | [
3,
3
] | [] | [] | [
"chameleon",
"pyramid",
"python"
] | stackoverflow_0006901846_chameleon_pyramid_python.txt |
Q:
Python mxTextTools ImportError: DLL load failed
I'm running python 2.7 on windows 7 and trying to get SimpleParse to work. This means I need mxTextTools, which I downloaded from . But when I try to import mx.TextTools, I get an ImportError saying it can't load a DLL (its nice that it doesn't tell me which one). He... | Python mxTextTools ImportError: DLL load failed | I'm running python 2.7 on windows 7 and trying to get SimpleParse to work. This means I need mxTextTools, which I downloaded from . But when I try to import mx.TextTools, I get an ImportError saying it can't load a DLL (its nice that it doesn't tell me which one). Here is all the code needed to get the error to come up... | [
"Maybe you made the same mistake that I made, which was that when I downloaded eGenix mx Base, I didn't notice the drop down box for selecting the appropriate version of Python, and ended up installing the wrong version.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003861851_python.txt |
Q:
How can I write color text to a textbox using python and the win32 api's?
Basically I want to write colored text to a textbox window of another application using python.
The general idea is to:
win32gui.SendMessage( hwnd, EM_SETCHARFORMAT, SCF_SELECTION, format);
where format is a CHARFORMAT.
My problem is that E... | How can I write color text to a textbox using python and the win32 api's? | Basically I want to write colored text to a textbox window of another application using python.
The general idea is to:
win32gui.SendMessage( hwnd, EM_SETCHARFORMAT, SCF_SELECTION, format);
where format is a CHARFORMAT.
My problem is that EM_SETCHARFORMAT and SCF_SELECTION are not included in the win32con library (I t... | [
"It turns out that this is quite difficult to achieve. The problem is that the EM_SETCHARFORMAT passes a structure by reference. The EM_SETCHARFORMAT is not one of the common Windows messages, it's in the WM_USER range. The memory pointed to by lParam is not marshalled across the process boundary. The receiver of t... | [
2
] | [] | [] | [
"colors",
"python",
"sendmessage",
"winapi"
] | stackoverflow_0006903692_colors_python_sendmessage_winapi.txt |
Q:
Improve speed of an optimization problem
I have the following app that optimize the following pb. The code works but i found it a little bit slow. Any idea of performance improvements ( without writing c code ) that can be done to better use python, numpy and scipy? It seems me that the interpolate function is the... | Improve speed of an optimization problem | I have the following app that optimize the following pb. The code works but i found it a little bit slow. Any idea of performance improvements ( without writing c code ) that can be done to better use python, numpy and scipy? It seems me that the interpolate function is the main time consuming part.
from scipy.optimize... | [
"You should try to vectorize the summations and the calls to the interpolation routine. For example, like this:\nimport numpy as np\n\nclass Bond(object):\n def __init__(self, years, cpn):\n self.years = years\n self.coupon = cpn\n\n self.cashflows = np.zeros((self.years + 1, 2))\n self.cashflows[:,0] ... | [
2,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0006276847_python_scipy.txt |
Q:
Python file dialog issue
I am trying to use Tkinter to choose a file and then import that filename into an argument to pass in a function. The program simply stops after the file is chosen. I included a print statement just to see if it returns the path and it does so I am not sure why it won't work in the functio... | Python file dialog issue | I am trying to use Tkinter to choose a file and then import that filename into an argument to pass in a function. The program simply stops after the file is chosen. I included a print statement just to see if it returns the path and it does so I am not sure why it won't work in the function.
#Main
from Tkinter import ... | [
"This (shortened version) works just fine:\nfrom Tkinter import *\nimport tkFileDialog\n\nfileOpen = Tk()\nfileOpen.withdraw() #hiding tkinter window\n\nfile_path = tkFileDialog.askopenfilename(\n title=\"Open file\", filetypes=[(\"txt file\",\".txt\"),(\"All files\",\".*\")])\n\nif file_path != \"\":\n print ... | [
3
] | [] | [] | [
"dialog",
"python",
"text_files"
] | stackoverflow_0006904646_dialog_python_text_files.txt |
Q:
Why doesn't this assign a copy
I have the following code and I'm wondering why it returns the same list instead of a copy:
x = [2,1,3]
y = x
y.sort()
print y
print x
Why does this return the same sorted list?
A:
Because it's modified in-place.
Python lists have reference semantics, meaning that when you assign ... | Why doesn't this assign a copy | I have the following code and I'm wondering why it returns the same list instead of a copy:
x = [2,1,3]
y = x
y.sort()
print y
print x
Why does this return the same sorted list?
| [
"Because it's modified in-place.\nPython lists have reference semantics, meaning that when you assign a list to another variable, they're actually pointing at the same list.\nIf you want to make a copy, do this:\nx = [2,1,3]\ny = x[:]\ny.sort()\nprint y\nprint x\n\nThe slice notation does cause the list (in this ca... | [
5,
4,
2,
0,
0,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0006904856_python_sorting.txt |
Q:
Django User ID fields
I am creating a new User object using the following code:
user = User(username=new_data['username'], email=new_data['email'], first_name=new_data['email'])
user.save()
user_id = user.id
Now, I need to retrieve the id of the user into a variable called user_id. However, when I do this, user_i... | Django User ID fields | I am creating a new User object using the following code:
user = User(username=new_data['username'], email=new_data['email'], first_name=new_data['email'])
user.save()
user_id = user.id
Now, I need to retrieve the id of the user into a variable called user_id. However, when I do this, user_id has the value of "Nothing... | [
"Try\nuser_id = user.pk\ninstead of\nuser_id = user.id\n",
"If you want to create a User, you could try the following:\nuser = User.objects.create_user(username=new_data['username'], email=new_data['email'])\nprint user.pk #Already works as create_user saves the new instance.\nuser.first_name = new_data['email'] ... | [
5,
3,
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0006898260_django_postgresql_python.txt |
Q:
How to handle nested form tags with lxml
I want to scrape some html pages that have nested form elements with lxml. Even BeautifulSoup chokes on these pages, the only parser I've found that can handle them so far is MinimalSoup which has no knowledge of which tags can be nested or not.
Does lxml have any parsers t... | How to handle nested form tags with lxml | I want to scrape some html pages that have nested form elements with lxml. Even BeautifulSoup chokes on these pages, the only parser I've found that can handle them so far is MinimalSoup which has no knowledge of which tags can be nested or not.
Does lxml have any parsers that don't care about about nested form tags?
A... | [
"How about lxml.etree.HTMLParser? That should work relatively well, right?\nimport urllib2\nimport lxml.etree as etree\npage = urllib2.urlopen(url)\nparser = etree.HTMLParser()\ntree = etree.parse(page,parser)\n\nAnd you have your tree!\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"lxml",
"python"
] | stackoverflow_0006620330_beautifulsoup_lxml_python.txt |
Q:
python findall, group and pipe
x = "type='text'"
re.findall("([A-Za-z])='(.*?)')", x) # this will work like a charm and produce
# ['type', 'text']
However, my problem is that I'd like to implement a pipe (alternation) so that the same regex will apply to
x = 'type="text"' # s... | python findall, group and pipe | x = "type='text'"
re.findall("([A-Za-z])='(.*?)')", x) # this will work like a charm and produce
# ['type', 'text']
However, my problem is that I'd like to implement a pipe (alternation) so that the same regex will apply to
x = 'type="text"' # see the quotes
Basically, the follow... | [
"shlex would do a better job here, but if you insist on re, use ([A-Za-z]+)=(?P<quote>['\"])(.+?)(?P=quote)\n",
"The problem is, that in ([A-Za-z]+)=('(.*?)'|\"(.*?)\") you have four groups and you need only two (this is probably where you found results strange). If you use ([A-Za-z]+)=('.*?'|\".*?\") then should... | [
5,
1
] | [] | [] | [
"findall",
"pipe",
"python",
"regex"
] | stackoverflow_0006904993_findall_pipe_python_regex.txt |
Q:
For in range involving tuple and last tuple
im running a for to check a list of tuples. something in the lines of
for i in range of b:
actual=i
temp1=(actual[0]+1,actual[1])
temp2=(actual[0],actual[1]-1)
temp3=(actual[0],actual[1]+1)
temp4=(actual[0]-1,actual[1])
And i want to make sure the temp's ... | For in range involving tuple and last tuple | im running a for to check a list of tuples. something in the lines of
for i in range of b:
actual=i
temp1=(actual[0]+1,actual[1])
temp2=(actual[0],actual[1]-1)
temp3=(actual[0],actual[1]+1)
temp4=(actual[0]-1,actual[1])
And i want to make sure the temp's NEVER take the value of the tuple verified on the... | [
"First, it seems that there's a problem with your code. range accepts integer input, so if b is an integer, for i in range(b) will give you integers [0, 1, 2, .. , b-1 ] in a list. You can't index into i using [], as you do on the next two lines.\nIf b is not an integer, but a collection, then you should use some... | [
0,
0
] | [] | [] | [
"algorithm",
"graph",
"logic",
"python"
] | stackoverflow_0004720139_algorithm_graph_logic_python.txt |
Q:
How to match--but not capture--in Python regular expressions?
I've got a function spitting out "Washington D.C., DC, USA" as output. I need to capture "Washington, DC" for reasons that have to do with how I handle every single other city in the country. (Note: this is not the same as "D.C.", I need the comma to be... | How to match--but not capture--in Python regular expressions? | I've got a function spitting out "Washington D.C., DC, USA" as output. I need to capture "Washington, DC" for reasons that have to do with how I handle every single other city in the country. (Note: this is not the same as "D.C.", I need the comma to be between "Washington" and "DC", whitespace is fine)
I can't for the... | [
"That's a clever way indeed, but not-capturing doesn't mean removing it from match. It just mean, that it's not considered as an output group.\nYou should try to do something similar to the following:\nmatch = re.search(r'(\\w+)\\s(?:D\\.C\\.), (\\w\\w)\\W', location).groups()\n\nThis prints ('Washington', 'DC').\n... | [
13,
6,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006905344_python_regex.txt |
Q:
How to properly check object types in Python?
Problem: I have to check that the a returned value is a Python dictionary.
Q1. Which of these options is the proper way to do this?
type(x) == dict
type(x) == type(dict)
isinstance(d, dict)
Then there are the other variants using is operator instead of ==.
Q2. Many ... | How to properly check object types in Python? | Problem: I have to check that the a returned value is a Python dictionary.
Q1. Which of these options is the proper way to do this?
type(x) == dict
type(x) == type(dict)
isinstance(d, dict)
Then there are the other variants using is operator instead of ==.
Q2. Many people say that checking the type of an object is g... | [
"\nQ1. Which of these options is the proper way to do this?\n\nDon't waste time on type checking.\nIt's error-prone because it's based on assumptions.\n\nQ2. ... do I have any other choice?\n\nYes do this.\ntry:\n x.the_dict_operation()\nexcept TypeError:\n # x was not the expected type for the operation\n ... | [
8,
2,
1
] | [] | [] | [
"comparison",
"isinstance",
"python",
"types"
] | stackoverflow_0006905655_comparison_isinstance_python_types.txt |
Q:
How to create a simple network connection in Python?
I was wondering if anyone had any good resources or suggestions for adding network functionality to a program in Python, specifically: if the sockets module would best fit my needs, and if there are any resources that anyone has found particularly enlightening.
... | How to create a simple network connection in Python? | I was wondering if anyone had any good resources or suggestions for adding network functionality to a program in Python, specifically: if the sockets module would best fit my needs, and if there are any resources that anyone has found particularly enlightening.
Background:
I am trying to create a fantasy football appli... | [
"The easiest solution would probably be to have your server just be a very basic XMLRPC server. There's a python class to do exactly that (SimpleXMLRPCServer). Then, have your clients connect to that server every couple of minutes to get updated data.\nSee http://docs.python.org/library/simplexmlrpcserver.html for... | [
3,
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0006903359_python_sockets.txt |
Q:
Write into a python slice?
Attempting to simply write into an existing (already filled) slice in python.
data = list([0] * 80)
bytes = [72, 101, 108, 108, 111]
print len(data) # 80
data[0:] = bytes
print (len(data)) # 5
What I really wanted was to only modify the first 5 integers and leave the rest of the data li... | Write into a python slice? | Attempting to simply write into an existing (already filled) slice in python.
data = list([0] * 80)
bytes = [72, 101, 108, 108, 111]
print len(data) # 80
data[0:] = bytes
print (len(data)) # 5
What I really wanted was to only modify the first 5 integers and leave the rest of the data list as zeros. However, what I di... | [
"data = list([0] * 80)\nbytes = [72, 101, 108, 108, 111]\ndata[:5] = bytes\n\nThe slice data[0:] represents the entire array, so the entire array will be replaced with what you provide. If you only want to replace a specific slice, you should specify it. Here, I've specified the slice data[:5], which is the first 5... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006905966_python.txt |
Q:
Python conditional list joins
I have a list that looks like this:
[
'A',
'must',
'see',
'is',
'the',
'Willaurie',
',',
'which',
'sank',
'after',
'genoegfuuu',
'damaged',
'in',
'a',
'storm',
'in',
'1989',
'.'
]
As you can see, there is punctuation. I want to call .join using ... | Python conditional list joins | I have a list that looks like this:
[
'A',
'must',
'see',
'is',
'the',
'Willaurie',
',',
'which',
'sank',
'after',
'genoegfuuu',
'damaged',
'in',
'a',
'storm',
'in',
'1989',
'.'
]
As you can see, there is punctuation. I want to call .join using a blank space except for the cases ... | [
"The string module has a list containing all punctuation characters.\nimport string\nstring = ''.join([('' if c in string.punctuation else ' ')+c for c in wordlist]).strip()\n\n",
"You have your answer already, but just would like to add, that not all punctuation should be stuck to a left-hand side. If you want t... | [
16,
4,
3,
1,
1
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0006905636_list_python_string.txt |
Q:
Python list comprehension troubles
I have some text manipulation to do, here's a for loop that does it:
for p in paras[:]:
pidx = paras.index(p)
for sent in p:
sidx = p.index(sent)
sent = ' '.join(w[0] for w in sent)
paras[pidx][sidx] = sent
paras[pidx] = 'start' + '... | Python list comprehension troubles | I have some text manipulation to do, here's a for loop that does it:
for p in paras[:]:
pidx = paras.index(p)
for sent in p:
sidx = p.index(sent)
sent = ' '.join(w[0] for w in sent)
paras[pidx][sidx] = sent
paras[pidx] = 'start' + ' '.join(paras[pidx]) + 'end'
Here is my... | [
"A nested LC\n[[' '.join(w[0] for w in sent) for sent in p] for p in paras]\n\nshould give each para as a separate list\n",
"If a sentence is a list of words, then:\n[\"see\", \"spot\", \"run\"]\n\nis a sentence. And if a paragraph is a list of sentences, then:\n[ [\"see\", \"spot\", \"run\"], [\"see\", \"dick\",... | [
2,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0006906155_list_comprehension_python.txt |
Q:
Segfault in the C code when using a Python tool called guppy ( heapy )
So I am using Python Stackless with heapy on two diffrent machines with the same architectures but slightly different C compilers. Heapy works perfectly fine on the first one, but I get a core dump on the second one.
Python 2.7.1 Stackless 3... | Segfault in the C code when using a Python tool called guppy ( heapy ) | So I am using Python Stackless with heapy on two diffrent machines with the same architectures but slightly different C compilers. Heapy works perfectly fine on the first one, but I get a core dump on the second one.
Python 2.7.1 Stackless 3.1b3 060516 (release27-maint, Jul 20 2011, 13:26:38)
[GCC 3.4.3 (MontaVista 3... | [
"Post this question and the stack trace to the Guppy mailing list. I'd say this is a bit too specialised a problem for the general population of StackOverflow to be able to help with, but if the crash is in heapy, the developers can probably point you in the right direction.\n",
"\nI don't know how to tackle this... | [
5,
4,
1
] | [
"Why are you using two differentversions of Python (release27-maint) that were built with two different compilers? It is not that difficult to build Python so that you have consistent versions on both machines, built with the same GCC version. If the machine architectures are different, you can cross-compile if you... | [
-2
] | [
"c",
"cython",
"memory_management",
"python",
"python_stackless"
] | stackoverflow_0006796714_c_cython_memory_management_python_python_stackless.txt |
Q:
In python. How do I have a user change a dictionary value, when that dictionary is in a class?
So I had a similar question that was answered in another thread.
How do I update a dictionary value having the user choose the key to update and then the new value, in Python?
Basically, how did one get a nested dictiona... | In python. How do I have a user change a dictionary value, when that dictionary is in a class? | So I had a similar question that was answered in another thread.
How do I update a dictionary value having the user choose the key to update and then the new value, in Python?
Basically, how did one get a nested dictionary value changed via raw_input. I used the solution and it worked well, but I wanted to write the pr... | [
"First of all, the traceback that accompanies the Key error, will tell you which line in your program triggered it, and if it is not obvious from reviewing the code, then inserting a print statement before that line should make it obvious.\nSecond, you are using user input as a key. User input is not reliable. You... | [
1,
1
] | [] | [] | [
"class",
"dictionary",
"python",
"raw_input"
] | stackoverflow_0006906132_class_dictionary_python_raw_input.txt |
Q:
Generic List View raises Attribute Error: "'function' object has no attribute '_clone'
An odd error here, perhaps someone can help track down source as it's attempting to extend the Django CMS project & attempts to use uses some logic written as part of that project which I'm not fully clear on. In short, using:
u... | Generic List View raises Attribute Error: "'function' object has no attribute '_clone' | An odd error here, perhaps someone can help track down source as it's attempting to extend the Django CMS project & attempts to use uses some logic written as part of that project which I'm not fully clear on. In short, using:
urls.py
======================
from django.conf.urls.defaults import *
from cmsplugin_flat_ne... | [
"The _clone errors are a red herring caused by you passing a function as an argument to a generic view where a QuerySet is expected. The version of your code which passes News.published.all() to the generic views is correct, as generic views will try to clone the QuerySet they are given, to avoid caching the first ... | [
9,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002621440_django_python.txt |
Q:
Python search HTML document for capital letters
So I have all these html documents that have strings of capital letter in various places in alt tags, title tage, link text...etc.
<li><a title='BUY FOOD' href="http://www.example.com/food.html'>BUY FOOD</a></li>
What I need to do is replace all letters except the ... | Python search HTML document for capital letters | So I have all these html documents that have strings of capital letter in various places in alt tags, title tage, link text...etc.
<li><a title='BUY FOOD' href="http://www.example.com/food.html'>BUY FOOD</a></li>
What I need to do is replace all letters except the first letter with lowercase letting. Like so:
<li><a ... | [
"I think you need a HTML parser like BeautifulSoup, the rest would be details.\n",
"There may be noteworthy exceptions for which fully automatic editing is not a good idea, but if you have a regex capable editor you might search for /[A-Z][A-Z]+/ and replace by hand.\n",
"I suggest you use Beautiful Soup to par... | [
0,
0,
0
] | [] | [] | [
"capitalize",
"coda",
"letters",
"python",
"regex"
] | stackoverflow_0006905508_capitalize_coda_letters_python_regex.txt |
Q:
Dictionaries in Python
What do these two statements mean in Python?
distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec)
d=distances[(clust[i].id,clust[j].id)]
I am guessing that the first statement assigns clust[i].id and clust[j].id keys of the distances map to the result of the distance(..... | Dictionaries in Python | What do these two statements mean in Python?
distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec)
d=distances[(clust[i].id,clust[j].id)]
I am guessing that the first statement assigns clust[i].id and clust[j].id keys of the distances map to the result of the distance(..) function. However, I am co... | [
"Dictionary literals use {}. Indexing operations use [], regardless of type.\n",
"distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec)\n\ndistances is a dictionary where keys are tuples of probably integers and the value is the distance measured between them by the distance function.\nin the s... | [
6,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0006906662_python.txt |
Q:
Help adding threading for GUI progress
I have an FTP function that traces the progress of running upload but my understanding of threading is limited and i have been unable to implement a working solution... I'd like to add a GUI progress bar to my current Application by using threading. Can someone show me a basi... | Help adding threading for GUI progress | I have an FTP function that traces the progress of running upload but my understanding of threading is limited and i have been unable to implement a working solution... I'd like to add a GUI progress bar to my current Application by using threading. Can someone show me a basic function using asynchronous threads that c... | [
"Here's a quick overview of threading, just in case :) I won't go into too much detail into the GUI stuff, other than to say that you should check out wxWidgets. Whenever you do something that takes a long time, like:\nfrom time import sleep\nfor i in range(5):\n sleep(10)\n\nYou'll notice that to the user, the ... | [
1
] | [] | [] | [
"ftp",
"multithreading",
"python"
] | stackoverflow_0006906439_ftp_multithreading_python.txt |
Q:
Problem accessing user uploaded video in temporary memory
I'm trying to submit a user uploaded video to youtube using an html input type file and the python module youtube-upload. When the form is submitted it is handled like so:
if request.method == 'POST':
video = request.FILES['file']
v=str(video)
... | Problem accessing user uploaded video in temporary memory | I'm trying to submit a user uploaded video to youtube using an html input type file and the python module youtube-upload. When the form is submitted it is handled like so:
if request.method == 'POST':
video = request.FILES['file']
v=str(video)
command = 'youtube-upload --email=email@gmail.com --password=... | [
"In fact django save the files on memory, but large files are saved in a path.\nThe size of \"large file\" can be defined in settings using FILE_UPLOAD_MAX_MEMORY_SIZE\nand\nThe FILE_UPLOAD_HANDLERS by default are:\n(\"django.core.files.uploadhandler.MemoryFileUploadHandler\",\n \"django.core.files.uploadhandler.T... | [
5
] | [] | [] | [
"django",
"python",
"youtube"
] | stackoverflow_0006906935_django_python_youtube.txt |
Q:
limiting the data to the desired values
I have a code plotting the lines in the image on left hand side above. I would like to select an area (a rectangular showed on the right side of the image above) and figure out which lines corresponds within that area.
The code plots the image on left is:
datfiles = glob.glo... | limiting the data to the desired values | I have a code plotting the lines in the image on left hand side above. I would like to select an area (a rectangular showed on the right side of the image above) and figure out which lines corresponds within that area.
The code plots the image on left is:
datfiles = glob.glob("*.dat")
for asc_filename in datfiles:
... | [
"It's not too simple, but it's not incredibly hard, either. In general, you'd want to use a full-fledged gui toolkit of some sort (e.g. Qt, wx, GTK, TK, etc) for this, but you can do it with \"pure\" matplotlib. (Matplotlib is, of course, just using whichever gui your install is configured to use behind-the-scenes... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006906118_matplotlib_python.txt |
Q:
How do I Pass Html form image arrays to the Google App Engine(Python)?
I'm using the Python implementation of the Google App Engine. When I try to pass an array of image input tags from an html form, I can't seem to pick it up in the Python controller.
The Html:
<form action="/addImages" method="post" enctype="mu... | How do I Pass Html form image arrays to the Google App Engine(Python)? | I'm using the Python implementation of the Google App Engine. When I try to pass an array of image input tags from an html form, I can't seem to pick it up in the Python controller.
The Html:
<form action="/addImages" method="post" enctype="multipart/form-data">
<input type="file" name="images" />
<input type="fil... | [
"You need to include the\nenctype=\"multipart/form-data\"\n\nattribute on your form tag, see i.e. http://www.mail-archive.com/google-appengine@googlegroups.com/msg03314.html. Googling for your error turns up several other instances of the problem.\nIf you still have problems once you've added the enctype, just try ... | [
3
] | [] | [] | [
"forms",
"google_app_engine",
"html",
"http_post",
"python"
] | stackoverflow_0006907257_forms_google_app_engine_html_http_post_python.txt |
Q:
hide header and footer on text files when direct print using win32 and python
I am stuck here when printing directly to text files using this code
win32api.ShellExecute (0, "print", "datafile.txt", None, ".", 0)
it always print the header "datafile.txt" and footer "Page1". I want to hide or remove this when print... | hide header and footer on text files when direct print using win32 and python | I am stuck here when printing directly to text files using this code
win32api.ShellExecute (0, "print", "datafile.txt", None, ".", 0)
it always print the header "datafile.txt" and footer "Page1". I want to hide or remove this when printing on continous form paper. I do not want to install another third party software.... | [
"I'm sure you're just a simple search away from finding a module that will handle this problem much better than this hack (e.g. use Reportlab and ShellExecute the PDF). Also, the default application for printing text files on Windows is Notepad. If you wish to configure the header/footer setting permanently, just c... | [
4,
0
] | [] | [] | [
"python",
"pywin32",
"system.printing",
"text_files"
] | stackoverflow_0006906551_python_pywin32_system.printing_text_files.txt |
Q:
How come my function is only looping through three elements within my list
I am trying to loop through all the elements (8 of them) in my list, but my function is only providing me with 4 of them. This is for an application I am making as a personal project.
import urllib
def get_followers():
count = 0
li... | How come my function is only looping through three elements within my list | I am trying to loop through all the elements (8 of them) in my list, but my function is only providing me with 4 of them. This is for an application I am making as a personal project.
import urllib
def get_followers():
count = 0
link = ['http://twitter.com/statuses/user_timeline.xml?screen_name=beratmahmuzlu'... | [
"You are popping the list and basing your loop off of the count of the list.\ntry a for loop instead:\nfor lnk in link:\n print lnk\n\n",
"link.pop() removes an element and len(link) gives you the new length of the list at each iteration, looping thus thru only the half of your list.\ndef get_followers():\n ... | [
9,
3,
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0006907075_loops_python.txt |
Q:
Pythonic way of closing/terminating an object
I have a Whoosh (file indexer) writer object
>>> a
<whoosh.filedb.filewriting.SegmentWriter object at 0x013DFE10>
As whoosh doesnt allow mutiple writers and implement thread safety (AFAIK!!), I would like to close that object when it has been used.
>>> a.is_closed
Fal... | Pythonic way of closing/terminating an object | I have a Whoosh (file indexer) writer object
>>> a
<whoosh.filedb.filewriting.SegmentWriter object at 0x013DFE10>
As whoosh doesnt allow mutiple writers and implement thread safety (AFAIK!!), I would like to close that object when it has been used.
>>> a.is_closed
False
But it has no close method. I was assured that ... | [
"If it has __enter__ and __exit__ methods, that means it implements the context manager protocol, and you should use it like this:\nwith constructor(args) as a:\n # do stuff with a\n pass\n# here a is closed even if you had an error above\n\nWhere constructor is either the class itself or whatever factory fun... | [
7,
5
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0006907717_multithreading_python.txt |
Q:
Using embedded C library in Python emulation
Short Question
Which would be easier to emulate (in Python) a complex (SAE J1939) communication stack from an existing embedded C library:
1) Full port - meaning manually convert all of the C functions to python modules
2) Wrap the stack in a Python wrapper - meaning ca... | Using embedded C library in Python emulation | Short Question
Which would be easier to emulate (in Python) a complex (SAE J1939) communication stack from an existing embedded C library:
1) Full port - meaning manually convert all of the C functions to python modules
2) Wrap the stack in a Python wrapper - meaning call the real c code in Python
Background Informat... | [
"My advice would be to wrap it.\nReasons for that:\n\nif you convert function by function, you'll introduce new bugs (we're just human) and this kind of stuff is pretty hard to test\nwrapping for python is done easily, using swig or even ctypes to load a dll on the fly, you'll find tons of tutorial\nif your lib get... | [
3,
3
] | [] | [] | [
"c",
"embedded",
"network_protocols",
"python"
] | stackoverflow_0006907583_c_embedded_network_protocols_python.txt |
Q:
Dict value as Class instance for method call
Have stored Abc class instances as dict values with a number as the key. I then want to use the dict key to find an instance and call the function 'here' for that instance. The (Python 3.2 on MS Win 7) code:
class Abc():
def __init__ ( self, num ):
self.num... | Dict value as Class instance for method call | Have stored Abc class instances as dict values with a number as the key. I then want to use the dict key to find an instance and call the function 'here' for that instance. The (Python 3.2 on MS Win 7) code:
class Abc():
def __init__ ( self, num ):
self.num = num
print ( 'Starting sess no - ', self... | [
"Are you a rubyist? In python parentheses are always mandatory to call a method:\nsees [i % 3].here\n\nhas to be\nsees[i % 3].here()\n\n",
"sess [i % 3].here\n\ndoes nothing. You want to call it:\nsess[i % 3].here()\n\n",
"Don't indent the definition of here() underneath __init__ - it should be at the same leve... | [
2,
1,
0
] | [] | [] | [
"class",
"dictionary",
"function",
"python"
] | stackoverflow_0006907961_class_dictionary_function_python.txt |
Q:
How to check if a file exists in python?
Possible Duplicate:
Pythonic way to check if a file exists?
How to check if a file exists in python?
Scripting in Windows
A:
This is very easy using the os module.
from os.path import exists
print exists("C:\somefile.txt")
A:
Check the manual, this is a really easy qu... | How to check if a file exists in python? |
Possible Duplicate:
Pythonic way to check if a file exists?
How to check if a file exists in python?
Scripting in Windows
| [
"This is very easy using the os module.\nfrom os.path import exists\nprint exists(\"C:\\somefile.txt\")\n\n",
"Check the manual, this is a really easy question:\nhttp://docs.python.org/library/os.path.html#os.path.exists\n\nos.path.exists(path)\n\nReturn True if path refers to an existing path. Returns False for ... | [
13,
5,
4
] | [] | [] | [
"file",
"python",
"windows"
] | stackoverflow_0006908003_file_python_windows.txt |
Q:
Reading a big file cost too much memory in Python 2.7
I used .readline() to parse file line by line, because I need
to find out the start position to extract data into a list, and the end
point to pause extracting, then repeat until the end of file.
My file to read is formatted like this:
blabla...
useless....
..... | Reading a big file cost too much memory in Python 2.7 | I used .readline() to parse file line by line, because I need
to find out the start position to extract data into a list, and the end
point to pause extracting, then repeat until the end of file.
My file to read is formatted like this:
blabla...
useless....
...
/sign/
data block(e.g. 10 cols x 1000 rows)
... blank li... | [
"You have quite a lot of non-pythonic ambiguous lines in your code. I am not sure but think that you can modify your code the following way first and then check it again against memory usage:\ndata=[]\n\nwith open('myfile','r') as f:\n for line in f:\n # find the extract beginning - think you can add here ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006908083_python.txt |
Q:
ModelForms with ManyToMany relationship Models in Django
I have a question on ModelForms in Django. If I'm creating a form from a model using ModelForms, then how the form fields will be linked to these M2M relationships ? what I mean is if I have :
Models.py
class Recipe(models.Model):
title = models.CharFiel... | ModelForms with ManyToMany relationship Models in Django | I have a question on ModelForms in Django. If I'm creating a form from a model using ModelForms, then how the form fields will be linked to these M2M relationships ? what I mean is if I have :
Models.py
class Recipe(models.Model):
title = models.CharField(max_length=100)
category = models.ForeignKey(Category)
... | [
"1.Should I create 1 model form for the 2 models related to each other as I did ?\nNo, you cant. Django use's this list to do a model field to form field mapping. Related fields are shown as select/drop down box. These select/drop down box are populated with existing instances of the related field. \n2.Model form f... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0006904436_django_django_forms_django_models_python.txt |
Q:
PyAudio, how to tell frequency and amplitude while recording?
I've used the PyAudio default recording example, and added numpy and scipy.
I can only use scipy.io.wavefile.read('FILE.wav'), after recording the file, however, and it also gives me this random tuple, eg:
(44100, array([[ 0, 0],
[-2, 0],
... | PyAudio, how to tell frequency and amplitude while recording? | I've used the PyAudio default recording example, and added numpy and scipy.
I can only use scipy.io.wavefile.read('FILE.wav'), after recording the file, however, and it also gives me this random tuple, eg:
(44100, array([[ 0, 0],
[-2, 0],
[ 0, -2],
...,
[-2, -2],
[ 1, 3],
... | [
"The array is not random data, it's the wave data of your stereo sound, and 44100 is the sampling rate. use the following code to plot the wave of left channel:\nimport scipy.io.wavfile as wavfile\nimport numpy as np\nimport pylab as pl\nrate, data = wavfile.read('FILE.wav')\nt = np.arange(len(data[:,0]))*1.0/rate\... | [
12
] | [] | [] | [
"audio",
"numpy",
"pyaudio",
"python",
"scipy"
] | stackoverflow_0006908540_audio_numpy_pyaudio_python_scipy.txt |
Q:
Sorting by values in a sublist in python
My list contains a number of elements in this format
(23, (12,16,42))
my rudimentary sort right now will sort by the first value in the sublist by default.
value = sorted(list, key=itemgetter(1))
I want to use a second level sort option as described http://wiki.python.org... | Sorting by values in a sublist in python | My list contains a number of elements in this format
(23, (12,16,42))
my rudimentary sort right now will sort by the first value in the sublist by default.
value = sorted(list, key=itemgetter(1))
I want to use a second level sort option as described http://wiki.python.org/moin/HowTo/Sorting/
sorted(student_tuples, ke... | [
"Define it yourself:\nsorted(list, key=lambda item: item[0][1])\n# or whatever other sort of indexing you want\n\nIn your case, the indexing you want is:\nsorted(list, key=lambda item: (item[1][0], item[1][1]))\n\nsince comparing tuples works by comparing elements pairwise. key is any callable that transforms the i... | [
4,
2,
-1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0006908167_python_sorting.txt |
Q:
How to get rid of mouse hover coordinates using PyPlot?
Hej, I'm fairly new to programming. I need to include some PyPlot Figures onto a Tkinter GUI (using Python 2.6). So far so good, made that work, the only annoying thing is that a mouse over effect is automatically applied in the toolbar, which yields exact co... | How to get rid of mouse hover coordinates using PyPlot? | Hej, I'm fairly new to programming. I need to include some PyPlot Figures onto a Tkinter GUI (using Python 2.6). So far so good, made that work, the only annoying thing is that a mouse over effect is automatically applied in the toolbar, which yields exact coordinates of the mouse position. How can I suppress that func... | [
"Have you tried passing 'break' to the application from the listener?\ndef ignore(event):\n return \"break\"\ntoolbar.bind(\"<Enter>\", ignore)\n\nMore details here.\n",
"I eventually found the solution for anyone that faces similar problems in the future: you need to edit the function: mouse_move in the modul... | [
0,
0
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0006832001_matplotlib_python_tkinter.txt |
Q:
How to convert a namedtuple into a list of values and preserving the order of properties?
from collections import namedtuple
Gaga = namedtuple('Gaga', ['id', 'subject', 'recipient'])
g = Gaga(id=1, subject='hello', recipient='Janitor')
I want to be able to obtain this list (which preserves the order of the proper... | How to convert a namedtuple into a list of values and preserving the order of properties? | from collections import namedtuple
Gaga = namedtuple('Gaga', ['id', 'subject', 'recipient'])
g = Gaga(id=1, subject='hello', recipient='Janitor')
I want to be able to obtain this list (which preserves the order of the properties):
[1, 'hello', 'Janitor']
I could create this list myself manually but there must be an e... | [
"Why not just list?\n>>> list(g)\n[1, 'hello', 'Janitor']\n\n"
] | [
57
] | [] | [] | [
"python"
] | stackoverflow_0006908986_python.txt |
Q:
Testing Django Facebook App
I'm making a Django app with Fandjango and I'm trying to unit test it with Django's test framework. The only thing is, in order to test effectively I need a "signed_request" parameter that Facebook sends with every request. Right now I'm logging the requests my server gets from Facebook... | Testing Django Facebook App | I'm making a Django app with Fandjango and I'm trying to unit test it with Django's test framework. The only thing is, in order to test effectively I need a "signed_request" parameter that Facebook sends with every request. Right now I'm logging the requests my server gets from Facebook and copying + pasting the signed... | [
"You can use Test Users: \nhttp://developers.facebook.com/docs/test_users/\nI think the access token never expires, or at less until you delete the Test User.\n"
] | [
4
] | [
"Well, I understand it's also possible to authenticate fully server side, using just OAuth without Javascript SDK. In that case you should be able to aquire a valid token yourself. There are, I think some libraries that can be used for that like:\nhttp://pypi.python.org/pypi/django-social-auth/\nHowever please note... | [
-1
] | [
"django",
"django_testing",
"facebook",
"python"
] | stackoverflow_0006755870_django_django_testing_facebook_python.txt |
Q:
gmail style date formatting in python
I can format date with strftime in python, but now I want to show
date in format relative to current time.
i.e. if date is near today, show in time.
if it is within week, show as yesterday etc.
if it is within month just show as last week or month.
if it is older than that s... | gmail style date formatting in python | I can format date with strftime in python, but now I want to show
date in format relative to current time.
i.e. if date is near today, show in time.
if it is within week, show as yesterday etc.
if it is within month just show as last week or month.
if it is older than that show as actual value.
I can do it with lots ... | [
"There is a library\nFrom the documentation,\n[python]\n>>> from relativeDates import *\n>>> import time\n>>> x = time.time()-1000\n>>> getRelativeTime(x)\n'17 minutes ago'\n>>> x-=12345\n>>> getRelativeTime(x)\n'3 hours ago'\n>>> x+=543211\n>>> getRelativeTime(x)\n'in 6 days'\n>>> getRelativeTime(x,accuracy=2)\n'i... | [
6,
3
] | [] | [] | [
"date",
"format",
"python"
] | stackoverflow_0006909134_date_format_python.txt |
Q:
How can I sort a specific range of elements in a list?
Suppose I have a list,
lst = [5, 3, 5, 1, 4, 7]
and I want to get it ordered from the second element 3 to the end.
I thought I could do it by:
lst[1:].sort()
But, this doesn't work.
How can I do it?
A:
lst = lst[0:1] + sorted(lst[1:])
A:
lst = [5, 3, 5, ... | How can I sort a specific range of elements in a list? | Suppose I have a list,
lst = [5, 3, 5, 1, 4, 7]
and I want to get it ordered from the second element 3 to the end.
I thought I could do it by:
lst[1:].sort()
But, this doesn't work.
How can I do it?
| [
"lst = lst[0:1] + sorted(lst[1:])\n\n",
"lst = [5, 3, 5, 1, 4, 7]\nlst[1:] = sorted(lst[1:])\nprint(lst) # prints [5, 1, 3, 4, 5, 7]\n\n",
"so = lambda x, index: x[:index]+sorted(x[index:])\n\nso call it as so(lst, 1)\nIn [2]: x = [5, 3, 5, 1, 4, 7]\nIn [3]: so(lst, 1)\nOut[4]: [5, 1, 3, 4, 5, 7]\n\n",
"You c... | [
20,
7,
1,
0,
0
] | [] | [] | [
"algorithm",
"list",
"python",
"range",
"sorting"
] | stackoverflow_0006908384_algorithm_list_python_range_sorting.txt |
Q:
Multidimension histogram in python
I have a multidimensional histogram
H=histogramdd((x,y,z),bins=(nbins,nbins,nbins),range=((0,1),(0,1),(0,1)))
I need to print in an array the values of H which are different from zero and I also need to know the coordinate/the bins where this happens.
I am not familiar with t... | Multidimension histogram in python | I have a multidimensional histogram
H=histogramdd((x,y,z),bins=(nbins,nbins,nbins),range=((0,1),(0,1),(0,1)))
I need to print in an array the values of H which are different from zero and I also need to know the coordinate/the bins where this happens.
I am not familiar with tuples. Can you help me?
| [
"use where to find the index of nozeros in H, and use the index to get the coordinate:\nimport numpy as np\nx = np.random.random(1000)\ny = np.random.random(1000)\nz = np.random.random(1000)\nnbins = 10\nH, [bx, by, bz]=np.histogramdd((x,y,z),bins=(nbins,nbins,nbins),range=((0,1),(0,1),(0,1)))\n\nix, iy, iz = np.wh... | [
5
] | [] | [] | [
"histogram",
"numpy",
"python",
"tuples"
] | stackoverflow_0006909247_histogram_numpy_python_tuples.txt |
Q:
Parsing form data / multi-part requests with Pythons WSGI
Is there a recommendable library to parse form data and/or multi-part requests with Python and WSGI?
A:
You can use cgi.FieldStorage to parse form posts etc.
You may be better off though using Werkzeug/Flask which has its own implementation which works a ... | Parsing form data / multi-part requests with Pythons WSGI | Is there a recommendable library to parse form data and/or multi-part requests with Python and WSGI?
| [
"You can use cgi.FieldStorage to parse form posts etc.\nYou may be better off though using Werkzeug/Flask which has its own implementation which works a lot better, plus you get higher level stuff which makes things a lot easier.\n"
] | [
1
] | [] | [] | [
"form_data",
"multipartform_data",
"python",
"wsgi"
] | stackoverflow_0006869107_form_data_multipartform_data_python_wsgi.txt |
Q:
python store variable in function and use it later
is it possible to store a variable from a while loop to a function and then call that same variable from the function at the end of the loop
for eg:during while loop, problem here is that when i try to retrieve the variable from store() it fails...as it needs arg... | python store variable in function and use it later | is it possible to store a variable from a while loop to a function and then call that same variable from the function at the end of the loop
for eg:during while loop, problem here is that when i try to retrieve the variable from store() it fails...as it needs arguments to be passed..
def store(a,b,c):
x1 = a
y... | [
"Technically speaking, if you had a deep, burning desire to do this with functions, you can always do it with a closure (which is, as we all know, a poor man's object):\ndef store(a,b,c):\n def closure():\n return (a,b,c)\n return closure\n\nstored = store(1,2,3)\nprint stored()\n\nprints in (1,2,3)\n"... | [
11,
10,
7,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0006910071_python.txt |
Q:
how do i import from a unicode (utf-8) csv file into a numpy array
im not trying to do this smart or fast, just trying to do it at all.
i have a file looks like this :
$ cat all_user_token_counts.csv
@5raphaels,in,15
@5raphaels,for,15
@5raphaels,unless,11
@5raphaels,you,11
i know its uncode utf-8 encoded becaus... | how do i import from a unicode (utf-8) csv file into a numpy array | im not trying to do this smart or fast, just trying to do it at all.
i have a file looks like this :
$ cat all_user_token_counts.csv
@5raphaels,in,15
@5raphaels,for,15
@5raphaels,unless,11
@5raphaels,you,11
i know its uncode utf-8 encoded because i created it, like this
debug('opening ' + ALL_USER_TOKEN_COUNTS_F... | [
"This can be done easily with np.loadtxt:\nimport numpy as np\narr=np.loadtxt('all_user_token_counts.csv',delimiter=',',\n dtype = '|U10,<U10,int')\nprint(arr)\n\n# [(u'@5raphaels', u'in', 15) (u'@5raphaels', u'for', 15)\n# (u'@5raphaels', u'unless', 11) (u'@5raphaels', u'you', 11)]\n\n"
] | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006911044_numpy_python.txt |
Q:
Is there a workaround in sqlalchemy for loading a table from DB without any primary keys?
I have a situation where i load all tables from legacy database. but it gives an error since it does not have any primary keys.
Can anyone give me a solution for this error ?
A:
You can add the primary key information to th... | Is there a workaround in sqlalchemy for loading a table from DB without any primary keys? | I have a situation where i load all tables from legacy database. but it gives an error since it does not have any primary keys.
Can anyone give me a solution for this error ?
| [
"You can add the primary key information to the autoloaded table.\ne.g.\nclass Subscrib(Base):\n\n __tablename__ = 'mytable'\n __table_args__ = {'autoload' : True}\n\n thepk = Column(Integer, primary_key=True)\n\n"
] | [
1
] | [] | [] | [
"mysql",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0006855400_mysql_orm_python_sqlalchemy.txt |
Q:
Choosing axis in numpy array using select method
I have following arrays.
In [1]: a = np.array([["aa", "bb", "cc"], ["cc", "bb", "aa"]])
In [2]: a
Out[2]:
array([['aa', 'bb', 'cc'],
['cc', 'bb', 'aa']],
dtype='|S2')
In [3]: b = np.array([[11, 12, 13], [21, 22, 23]])
In [4]: b
Out[4]:
array([[11, 12,... | Choosing axis in numpy array using select method | I have following arrays.
In [1]: a = np.array([["aa", "bb", "cc"], ["cc", "bb", "aa"]])
In [2]: a
Out[2]:
array([['aa', 'bb', 'cc'],
['cc', 'bb', 'aa']],
dtype='|S2')
In [3]: b = np.array([[11, 12, 13], [21, 22, 23]])
In [4]: b
Out[4]:
array([[11, 12, 13],
[21, 22, 23]])
Relation between a and b ... | [
"In [13]: a==c[:,np.newaxis]\nOut[13]: \narray([[False, True, False],\n [False, False, True]], dtype=bool)\n\nIn [14]: b[a==c[:,np.newaxis]]\nOut[14]: array([12, 23])\n\n"
] | [
2
] | [] | [] | [
"numpy",
"python",
"select"
] | stackoverflow_0006911508_numpy_python_select.txt |
Q:
Search list: match only exact word/string
How to match exact string/word while searching a list. I have tried, but its not correct. below I have given the sample list, my code and the test results
list = ['Hi, hello', 'hi mr 12345', 'welcome sir']
my code:
for str in list:
if s in str:
print str
test res... | Search list: match only exact word/string | How to match exact string/word while searching a list. I have tried, but its not correct. below I have given the sample list, my code and the test results
list = ['Hi, hello', 'hi mr 12345', 'welcome sir']
my code:
for str in list:
if s in str:
print str
test results:
s = "hello" ~ expected output: 'Hi, hell... | [
"It looks like you need to perform this search not only once so I would recommend to convert your list into dictionary:\n>>> l = ['Hi, hello', 'hi mr 12345', 'welcome sir']\n>>> d = dict()\n>>> for item in l:\n... for word in item.split():\n... d.setdefault(word, list()).append(item)\n...\n\nSo now ... | [
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"string",
"string_matching"
] | stackoverflow_0006909623_python_string_string_matching.txt |
Q:
how to add Tkinter support to python2 on my gentoo?
The default python version on my gentoo is python2,
and the default python installed on gentoo has no Tkinter support.
After I added the following line to /etc/portage/package.use
dev-lang/python tk
then emerge python, it only shows:
[ebuild R ] dev-lang/p... | how to add Tkinter support to python2 on my gentoo? | The default python version on my gentoo is python2,
and the default python installed on gentoo has no Tkinter support.
After I added the following line to /etc/portage/package.use
dev-lang/python tk
then emerge python, it only shows:
[ebuild R ] dev-lang/python-3.1.3-r1 USE="examples gdbm ipv6 ncurses readline ... | [
"Have you tried to explicitly specify the Python version you want to install, e.g. emerge =python-2.7.2-r2?\n"
] | [
1
] | [] | [] | [
"gentoo",
"python",
"tkinter"
] | stackoverflow_0006911926_gentoo_python_tkinter.txt |
Q:
Fun with GAE: using key_name as PK?
I want to insert new entities programatically as well as manually. For this I was thinking about using key_name to uniquely identify an entity.
The problem is that I don't know how to get the model to generate a new unique key name when I create the entity.
On the other hand, I ... | Fun with GAE: using key_name as PK? | I want to insert new entities programatically as well as manually. For this I was thinking about using key_name to uniquely identify an entity.
The problem is that I don't know how to get the model to generate a new unique key name when I create the entity.
On the other hand, I cannot create the ID (which is unique acr... | [
"If you really need a string id (as opposed to an automatically assigned integer id), you could use a random string generator, or unique id generator like uuid.uuid4.\n",
"I don't really understand your question. If you want an automatically-generated key name, just leave out the key when you instantiate the obje... | [
2,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006908827_google_app_engine_python.txt |
Q:
Execute if no exception thrown
I have some code I want to execute if an exception is not thrown.
Currently I'm doing this:
try:
return type, self.message_handlers[type](self, length - 1)
finally:
if not any(self.exc_info()):
self.last_recv_time = time.time()
Can this be improved on? Is this the be... | Execute if no exception thrown | I have some code I want to execute if an exception is not thrown.
Currently I'm doing this:
try:
return type, self.message_handlers[type](self, length - 1)
finally:
if not any(self.exc_info()):
self.last_recv_time = time.time()
Can this be improved on? Is this the best way to do it?
Update0
The option... | [
"try:\n tmp = type, self.message_handlers[type](self, length - 1)\nexcept Exception:\n pass #or handle error, or just \"raise\" to re-raise\nelse:\n self.last_recv_time = time.time()\n return tmp\n\n",
"Your code suggests that you don't want to catch the exception if it occurs, so why not simply\nresult =... | [
28,
9
] | [] | [] | [
"exception",
"finally",
"python",
"python_3.x",
"try_catch"
] | stackoverflow_0006911999_exception_finally_python_python_3.x_try_catch.txt |
Q:
Problems beginning a new project with Django on Windows 7 OS
I am trying to begin a project(first one ever) with Django on a Windows 7 machine, and am encountering issues with 'startproject.' I have made sure Django is installed correctly and it seems as though it is working fine, however I run into a problem whe... | Problems beginning a new project with Django on Windows 7 OS | I am trying to begin a project(first one ever) with Django on a Windows 7 machine, and am encountering issues with 'startproject.' I have made sure Django is installed correctly and it seems as though it is working fine, however I run into a problem when I try "django-admin.py startproject sitename"
I have tried using... | [
"If you are using Windows 7, make sure that you are running the Windows command prompt as Administrator. However, I'm afraid that without knowing more details about the exact issue that you are finding it will be very difficult to help you.\nYou mention that you are going to do your fist Django project. If you stil... | [
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0006907411_django_django_admin_python.txt |
Q:
Webapp technology questions and advices
I decided to write a long introduction in order to give you a better idea of what I'm trying to achieve. This will be my first real... commercialy aimed application.
Disclaimer: Even though I've been reading anything I can get my hands on for the past 3 years regarding web d... | Webapp technology questions and advices | I decided to write a long introduction in order to give you a better idea of what I'm trying to achieve. This will be my first real... commercialy aimed application.
Disclaimer: Even though I've been reading anything I can get my hands on for the past 3 years regarding web dev and for the past year anything python rela... | [
"\nYou have a highly structured dataset, with predictable elements. To me, this indicates that a traditional relational database would be a better fit than any of the NoSQL solutions - although they could be made to work.\nFlask is a micro-framework. It's best for small apps and web services. I like it a lot, but f... | [
5,
2
] | [] | [] | [
"cloud",
"flask",
"linux",
"nginx",
"python"
] | stackoverflow_0006912440_cloud_flask_linux_nginx_python.txt |
Q:
Python Graphical sample application
Is there any sample Python GUI Application with source code for learning purposes available. Any simple GUI application will do.
Thanks
A:
Well it depends on the UI library/framework you want to use:
Tkinter comes with python for example - you should find plenty examples her... | Python Graphical sample application | Is there any sample Python GUI Application with source code for learning purposes available. Any simple GUI application will do.
Thanks
| [
"Well it depends on the UI library/framework you want to use:\nTkinter comes with python for example - you should find plenty examples here: Python Wiki\nOther toolkits include wxWidgets: This site could get you started.\nApart from this there is QT (already mentioned by BrainStorm) or GTK (quick googeling turned u... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006912104_python.txt |
Q:
How to split list and pass them as separate parameter?
My problem is I have values in a list. And I want to separate these values and send them as a separate parameter.
My code is:
def egg():
return "egg"
def egg2(arg1, arg2):
print arg1
print arg2
argList = ["egg1", "egg2"]
arg = ', '.join(argList)... | How to split list and pass them as separate parameter? | My problem is I have values in a list. And I want to separate these values and send them as a separate parameter.
My code is:
def egg():
return "egg"
def egg2(arg1, arg2):
print arg1
print arg2
argList = ["egg1", "egg2"]
arg = ', '.join(argList)
egg2(arg.split())
This line of code (egg2(arg.split())) ... | [
">>> argList = [\"egg1\", \"egg2\"]\n>>> egg2(*argList)\negg1\negg2\n\nYou can use *args (arguments) and **kwargs (for keyword arguments) when calling a function.\nHave a look at this blog on how to use it properly.\n",
"There is a special syntax for argument unpacking:\negg2(*argList)\n\n",
"arg.split() does n... | [
90,
14,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006913084_list_python.txt |
Q:
How to search for ZCatalog object names
I want to Search for an Object name.
If i have this Structure:
/de/myspace/media/justAnotherPdf.pdf
Then i want to Search for the name "justAnotherPdf" to find it or something like "justAnot"
I have Indexed the pdf files.
But i cant search it with TextIndexNG2 or PathIndex.
... | How to search for ZCatalog object names | I want to Search for an Object name.
If i have this Structure:
/de/myspace/media/justAnotherPdf.pdf
Then i want to Search for the name "justAnotherPdf" to find it or something like "justAnot"
I have Indexed the pdf files.
But i cant search it with TextIndexNG2 or PathIndex.
| [
"import os.path\nname = os.path.splitext(os.path.split(url)[1])[0]\n\nexplaining the code:\nfrom os.path import split, splitext\nurl = '/de/myspace/media/justAnotherPdf.pdf'\npath, name_with_ext = split(url)\nname_without_ext, ext = splitext(name_with_ext)\n\n",
"Currently this is not supported out-of-the-box. Ob... | [
3,
3
] | [] | [] | [
"dhtml",
"python",
"zope"
] | stackoverflow_0006912241_dhtml_python_zope.txt |
Q:
How to keep a list static in Python?
Alright, so I have a long list of numbers, like so:
q = [3495790.0, 2386479.0, 2398462.0]
and so on and so on about 300 times. I want to get another version of this list with all the numbers added by 1800, while retaining the original list for comparison purposes. Thank you fo... | How to keep a list static in Python? | Alright, so I have a long list of numbers, like so:
q = [3495790.0, 2386479.0, 2398462.0]
and so on and so on about 300 times. I want to get another version of this list with all the numbers added by 1800, while retaining the original list for comparison purposes. Thank you for all your help!
| [
"q1 = [x + 1800 for x in q]\n\nshould do the trick.\n",
"q2 = [x + 1800.0 for x in q]\n\nwill create a new list with 1800 added to each entry.\n",
"In Python, you can just assign the result of a list comprehension to another list:\n# Given:\nq = [3495790.0, 2386479.0, 2398462.0]\n\n# You could do...\nr = [x + 1... | [
5,
3,
2,
1
] | [] | [] | [
"addition",
"list",
"python"
] | stackoverflow_0006913161_addition_list_python.txt |
Q:
Python: Pass inequality as string in dict for evaluation
I need to pass inequalities to a function for evaluation within the function. Is there a way to evaluation the inequality if passed as a string? Or must I pass a representation of the inequality and use if/else statements to generate the sign?
A:
You could... | Python: Pass inequality as string in dict for evaluation | I need to pass inequalities to a function for evaluation within the function. Is there a way to evaluation the inequality if passed as a string? Or must I pass a representation of the inequality and use if/else statements to generate the sign?
| [
"You could use the operator module, and pass the appropriate method on it:\nimport operator\n\ndef check(op, a, b)\n return op(a,b)\n\nop = operator.ne\ncheck(op, 2,3)\n\n\n>>> True\n\n",
"Your question is a little vague, but it sounds like you want to evaluate a string containing an expression (such as x > 5)... | [
4,
4
] | [] | [] | [
"function",
"inequality",
"python",
"sign"
] | stackoverflow_0006913167_function_inequality_python_sign.txt |
Q:
SSH into Django Shell
I'm attempting to write a simple one-line script to ssh into a remote host, CD to my Django app's directory, and run manage.py shell. So far I have:
ssh -i mysite.pem root@remotehost "cd /usr/local/myapp; /bin/bash -i -c \"python manage.py shell;\""
This seems to work with the caveat that I ... | SSH into Django Shell | I'm attempting to write a simple one-line script to ssh into a remote host, CD to my Django app's directory, and run manage.py shell. So far I have:
ssh -i mysite.pem root@remotehost "cd /usr/local/myapp; /bin/bash -i -c \"python manage.py shell;\""
This seems to work with the caveat that I can't see any output from m... | [
"Pass the -t option to ssh.\n\nForce pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.\n\nBy default, running ssh host command... | [
17
] | [] | [] | [
"django",
"python",
"ssh"
] | stackoverflow_0006913283_django_python_ssh.txt |
Q:
Comparable classes in Python 3
What is the standard way of making a class comparable in Python 3? (For example, by id.)
A:
To make classes comparable, you only need to implement __lt__ and decorate the class with functools.total_ordering. You should also provide an __eq__ method if possible. This provides the r... | Comparable classes in Python 3 | What is the standard way of making a class comparable in Python 3? (For example, by id.)
| [
"To make classes comparable, you only need to implement __lt__ and decorate the class with functools.total_ordering. You should also provide an __eq__ method if possible. This provides the rest of the comparison operators so you don't have to write any of them yourself.\n",
"For a full set of comparison functions... | [
35,
15,
0,
0,
0
] | [] | [] | [
"class",
"comparable",
"python",
"python_3.x"
] | stackoverflow_0006907323_class_comparable_python_python_3.x.txt |
Q:
How do I match words in different languages
How can I write a regular expression to efficiently match both Swedish and English words?
I must be able to match the likes of Å, é and '. I think 123 is also a word. I even think 1:e and 1st are words...
How would I proceed if I wish to match words from Russian and Jap... | How do I match words in different languages | How can I write a regular expression to efficiently match both Swedish and English words?
I must be able to match the likes of Å, é and '. I think 123 is also a word. I even think 1:e and 1st are words...
How would I proceed if I wish to match words from Russian and Japanese also.
Thanks,
Barry
P.S. The following are... | [
"\nJapanese\n\nDetecting word boundaries in CJK texts requires knowledge of the language at a fluent level; These texts are not written with any sort of word separation, and lack a distinct structure in written form that distinguishes one word from the next. More on the subject.\nRoman texts (English, Swedish) an... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006913277_python.txt |
Q:
Want to create a view which can dump mysql database as a sql file
I seem to be having a problem. I want to write some code that can dump a mysql database, when an administrator user clicks on a button. I have tried writing some code in my views.py below.
Views.py
@login_required
def dbbackup(request):
... | Want to create a view which can dump mysql database as a sql file | I seem to be having a problem. I want to write some code that can dump a mysql database, when an administrator user clicks on a button. I have tried writing some code in my views.py below.
Views.py
@login_required
def dbbackup(request):
if not (request.user.is_authenticated() and request.user.is_staff):... | [
"You need to return a valid HttpResponse object from the end of your method. For example, if you wanted to return the gzip file:\n@login_required\ndef dbbackup(request):\n if not (request.user.is_authenticated() and request.user.is_staff):\n raise http.Http404\n os.chdir('/usr/local/src/djcode/c2duo_m... | [
2
] | [] | [] | [
"database",
"django",
"mysql",
"mysqldump",
"python"
] | stackoverflow_0006912695_database_django_mysql_mysqldump_python.txt |
Q:
PyQt Timeline Gui
I need to make a timeline like this:
using PyQt for the gui.
Basically, this timeline is for a car. On the timeline is all the stages of production the car goes through with dates and to the left is the team(s) involved in that specific stage.
i.e the Testing stage starts on the 21st January and... | PyQt Timeline Gui | I need to make a timeline like this:
using PyQt for the gui.
Basically, this timeline is for a car. On the timeline is all the stages of production the car goes through with dates and to the left is the team(s) involved in that specific stage.
i.e the Testing stage starts on the 21st January and ends on the 4th Februa... | [
"Of course, there are many ways to do this, but I would use QGraphicsView. I primarily use C++/Qt so can't comment how easy this would be to do in Python.\nI would have each \"stage\" be a QGraphicsItem, and draw the Months/Days as the QGraphicsView background. I would override the mouse events for the graphics ite... | [
3
] | [] | [] | [
"pyqt",
"python",
"qt",
"timeline",
"widget"
] | stackoverflow_0006909495_pyqt_python_qt_timeline_widget.txt |
Q:
Realtime serial data logging with Python - design advice
I am having to design a small program that reads the GPRMC sentence from a GPS logging device on a laptop computer. I am reading the raw values over serial connection. Once I read the raw value I will parse the GPRMC sentence (12 comma delimited values) and ... | Realtime serial data logging with Python - design advice | I am having to design a small program that reads the GPRMC sentence from a GPS logging device on a laptop computer. I am reading the raw values over serial connection. Once I read the raw value I will parse the GPRMC sentence (12 comma delimited values) and put them into a sqllite database so that another application c... | [
"Depends on whether or not the program must be embeddable. If not, there is Redis (http://redis.io) with a very efficient time series implementation. And there is a Django Dash 2011 app Staste that does just that - http://staste.unfoldthat.com/. I didn't test it myself, but the code looks fine and the demo is promi... | [
1
] | [] | [] | [
"python",
"serial_port",
"software_design",
"software_quality"
] | stackoverflow_0006913285_python_serial_port_software_design_software_quality.txt |
Q:
python socket file read timeout?
I'm using a python socket as a file to talk to another process:
def connect(self):
try:
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect( (self.target, self.port) )
self.fobj = self.sock.makefile()
Normally I'd write a co... | python socket file read timeout? | I'm using a python socket as a file to talk to another process:
def connect(self):
try:
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect( (self.target, self.port) )
self.fobj = self.sock.makefile()
Normally I'd write a command through the socket and expect a ... | [
"Taken from Python's documentation about socket.makefile():\n\nsocket.makefile([mode[, bufsize]])\nReturn a file object associated with the socket. (File objects are described in File Objects.) The file object references a dup()ped version of the socket file descriptor, so the file object and socket object may be c... | [
2
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0006914161_python_sockets.txt |
Q:
Is this an efficient MySQL database design?
I am working on a project wherein I have a set of keywords [abc, xyz, klm]`. I also have a bunch of text files with content [1.txt, 2.txt, 3.txt].
What I am doing is bumping the keywords against the text files to find the line where the keyword occurs and it can do so m... | Is this an efficient MySQL database design? | I am working on a project wherein I have a set of keywords [abc, xyz, klm]`. I also have a bunch of text files with content [1.txt, 2.txt, 3.txt].
What I am doing is bumping the keywords against the text files to find the line where the keyword occurs and it can do so multiple times. So I want to store the ID (text fi... | [
"Don't do that. No database library is optimized for dynamic table names and you'll end up having to create your query from scratch each time you want to access a table. Also, how would you answer questions like \"what data did I find on line 34 of file 12\"?\nYou'll want three tables. In PostgreSQL syntax [*], tha... | [
6,
5,
2,
1
] | [] | [] | [
"database_design",
"memory_efficient",
"mysql",
"python"
] | stackoverflow_0006914009_database_design_memory_efficient_mysql_python.txt |
Q:
How to translate this bit of Python to idiomatic Javascript
My code so far:
// The q constant of the Glicko system.
var q = Math.log(10) / 400;
function Player(rating, rd) {
this.rating = rating || 1500;
this.rd = rd || 200;
}
Player.prototype.preRatingRD = function(this, t, c) {
// Set default value... | How to translate this bit of Python to idiomatic Javascript | My code so far:
// The q constant of the Glicko system.
var q = Math.log(10) / 400;
function Player(rating, rd) {
this.rating = rating || 1500;
this.rd = rd || 200;
}
Player.prototype.preRatingRD = function(this, t, c) {
// Set default values of t and c
this.t = t || 1;
this.c = c || 63.2;
// ... | [
"In Javascript you don't need o pass the self explicitly (Python is the \"weird\" one here, actually)\nPlayer.prototype.e = function(rating_list, RD_list){\n //replace \"self\" with \"this\" here:\n var tempSum = 0; //if you don't use the \"var\", tempSum will be a global\n // instead of a... | [
3
] | [] | [] | [
"javascript",
"python",
"translation"
] | stackoverflow_0006914515_javascript_python_translation.txt |
Q:
Is there a better solution for this ternary condition?
Imagine the following ternary condition:
foreground = self.foreground if self.foreground else c4d.COLOR_TRANS
In this case, I need to call self.foreground twice just to check if it is True or not.
Is there a way where I only need to call it once ?
A:
An equ... | Is there a better solution for this ternary condition? | Imagine the following ternary condition:
foreground = self.foreground if self.foreground else c4d.COLOR_TRANS
In this case, I need to call self.foreground twice just to check if it is True or not.
Is there a way where I only need to call it once ?
| [
"An equivalent expression is\nforeground = self.foreground or c4d.COLOR_TRANS\n\n",
"You can use the boolean operators:\nforeground = self.foreground or c4d.COLOR_TRANS\n\n"
] | [
7,
3
] | [] | [] | [
"if_statement",
"python",
"ternary",
"variable_assignment"
] | stackoverflow_0006914853_if_statement_python_ternary_variable_assignment.txt |
Q:
Python adding variable as value in a dict
I'm a beginner in Python and have a problem. I can't add the value of a variable to a dictionary.
f.e
name=input('Input the name: ')
dict['Name']=name
and here's the error:
TypeError: 'type' object does not support item assignment
Could anyone help me?
A:
Don't nam... | Python adding variable as value in a dict | I'm a beginner in Python and have a problem. I can't add the value of a variable to a dictionary.
f.e
name=input('Input the name: ')
dict['Name']=name
and here's the error:
TypeError: 'type' object does not support item assignment
Could anyone help me?
| [
"Don't name your dictionary dict. That's a built-in. Name it something else, and you example should work, provided the dict object is initialized.\nmy_dict = {}\nname=input('Input the name: ')\nmy_dict['Name']=name \n\n",
"You have to instantiate the dictionary before:\nd = dict()\nd['Name'] = name\n\n",
"Giv... | [
17,
4,
3,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006914880_python.txt |
Q:
give an array a-z until possibly ZZZ... key with php or python
Let's say i have an unknown string in an array, it will look like
$arr = array(
'string 1',
'string 2',
'string 3',
'string 4',
'string 5',
// up to a certain unknown amount
1. How can we give them a value like below?
'string 1' => a,
'string 2' => b... | give an array a-z until possibly ZZZ... key with php or python | Let's say i have an unknown string in an array, it will look like
$arr = array(
'string 1',
'string 2',
'string 3',
'string 4',
'string 5',
// up to a certain unknown amount
1. How can we give them a value like below?
'string 1' => a,
'string 2' => b,
'string 26' => z,
'string 27' => A,
'string 52' => Z,
'string 53'... | [
"In Python it's relatively easy to have an infinite array using generators, as well as arbitrarily long ones, lazily evaluated ones, etc. What you'd want to do to map this kind of thing to keys is to have an infinitely long, lazily evaluated list, or generator.\nimport itertools\nimport string\n\nFirst you want it... | [
2,
1,
0,
0,
0
] | [] | [] | [
"logic",
"php",
"python"
] | stackoverflow_0006914624_logic_php_python.txt |
Q:
Python parsing GPRMC string with CSV
I have GPRMC string which consists of 12 comma delimited values. When I run my code it does in fact split the commas, but it prints each character in the comma separated value on a new line - instead of grouping all characters in between a comma together.
For example:
>>> gprm... | Python parsing GPRMC string with CSV | I have GPRMC string which consists of 12 comma delimited values. When I run my code it does in fact split the commas, but it prints each character in the comma separated value on a new line - instead of grouping all characters in between a comma together.
For example:
>>> gprmc = "$GPRMC,1244.0,A,3111.334505,N,90729.3... | [
"Try this:\nimport csv\nreader = csv.reader(open(filename, 'r'))\n\nfor row in reader:\n if row and row[0].strip() == '$GPRMC':\n for val in row:\n print val\n print \"_____________________\"\n\nTo check my code i have created file that contains one row with the following text:\n$GPRMC,... | [
0
] | [] | [] | [
"csv",
"parsing",
"python"
] | stackoverflow_0006914987_csv_parsing_python.txt |
Q:
simplejson.loads usage
I want to display a random link + its name from an RSS feed.
The code I use is:
def updateFeed(url):
query_args = { 'q': 'http://news.google.com/?output=rss', 'v':'1.0', 'num': '15', 'output': 'json' }
qs = urllib.urlencode(query_args)
loader = 'http://ajax.googleapis.com/ajax/s... | simplejson.loads usage | I want to display a random link + its name from an RSS feed.
The code I use is:
def updateFeed(url):
query_args = { 'q': 'http://news.google.com/?output=rss', 'v':'1.0', 'num': '15', 'output': 'json' }
qs = urllib.urlencode(query_args)
loader = 'http://ajax.googleapis.com/ajax/services/feed/load'
loadu... | [
"When you load JSON in Python, it's converted into (nested) dicts and lists. { ... } objects become dictionaries, and [ ... ] comma-separated items become lists.\nFor example, to get the feed URL, you can do:\nfeedUrl = news[u'responseData'][u'feed'][u'feedUrl']\n\nTo select a random element from a dictionary, you ... | [
3
] | [] | [] | [
"json",
"python",
"rss",
"simplejson"
] | stackoverflow_0006915247_json_python_rss_simplejson.txt |
Q:
How to translate this duck-typing (Python) to Java generics?
Consider the following simple Python function by way of example:
def quantize(data, nlevels, quantizer=lambda x, d: int(floor(x/d))):
llim = min(data)
delta = (max(data) - llim)/(nlevels - 1) # last level x == max(data) only
y = type(data)
... | How to translate this duck-typing (Python) to Java generics? | Consider the following simple Python function by way of example:
def quantize(data, nlevels, quantizer=lambda x, d: int(floor(x/d))):
llim = min(data)
delta = (max(data) - llim)/(nlevels - 1) # last level x == max(data) only
y = type(data)
if delta == 0:
return y([0] * len(data))
else:
... | [
"One solution to the input/output type question might be to use the Number class and its subclasses along with wildcards. If you wanted to accept any type of numerical argument, you could either specify the input type to be Number OR ? extends Number. If the input is a list, the latter form has an advantage as it w... | [
4,
1
] | [] | [] | [
"duck_typing",
"generics",
"java",
"python",
"types"
] | stackoverflow_0006915265_duck_typing_generics_java_python_types.txt |
Q:
Where to download the pyflix library?
I want to download the 'pyflix' library that was previously hosted at http://svn.pyflix.python-hosting.com/trunk/.
That site now gives a 404 error. I found however a cached copy of the code via Google code search.
Is there an easy way of checking out/downloading this cached co... | Where to download the pyflix library? | I want to download the 'pyflix' library that was previously hosted at http://svn.pyflix.python-hosting.com/trunk/.
That site now gives a 404 error. I found however a cached copy of the code via Google code search.
Is there an easy way of checking out/downloading this cached code from Google code search?
| [
"The waybackmachine is often useful for digging into the past. The pyflix trac site for 2009 can be found at:\nhttp://web.archive.org/web/20090408033407/http://pyflix.python-hosting.com/\n"
] | [
3
] | [] | [] | [
"netflix",
"python"
] | stackoverflow_0006914055_netflix_python.txt |
Q:
How do I add text to multiple filenames using Python?
I have a series of files that I need to add the creation year (2007) to the end of the filename:
Currently:
NewZealand_cities.shp
NewZealand_roads.shp
etc.
Need:
NewZealand_cities2007.shp
NewZealand_roads2007.shp
I have been able to remove segments of text but ... | How do I add text to multiple filenames using Python? | I have a series of files that I need to add the creation year (2007) to the end of the filename:
Currently:
NewZealand_cities.shp
NewZealand_roads.shp
etc.
Need:
NewZealand_cities2007.shp
NewZealand_roads2007.shp
I have been able to remove segments of text but cannot add for some reason. Any help would be much appreci... | [
"Did you try this:\nimport os\nname, ext = os.path.splitext(fname)\nos.rename(fname, name + '2007' + ext)\n\n"
] | [
3
] | [] | [] | [
"addition",
"file_rename",
"python"
] | stackoverflow_0006915698_addition_file_rename_python.txt |
Q:
CGI Script in Python to search a database and print the results
I would like to write a CGI script that takes the form data, sends it to a search engine, searches, then displays the results on the webpage where my cgi script it run. I have been trying to use urllib and urllib2.
In my script: hello.py
if form.has_k... | CGI Script in Python to search a database and print the results | I would like to write a CGI script that takes the form data, sends it to a search engine, searches, then displays the results on the webpage where my cgi script it run. I have been trying to use urllib and urllib2.
In my script: hello.py
if form.has_key("data_search"):
datasearch = form["data_search"].value
ur... | [
"Not sure how you are getting your form data, but it appears that datasearch = form[\"data_search\"].value returns the value of your data_search param already. Use urlparse.urlparse to parse a full url, i.e., http://somesite.com/?datasearch=TTBAR. So with that in mind you can do this:\nimport urllib2\n\nurl = 'http... | [
1
] | [] | [] | [
"cgi",
"python",
"urllib"
] | stackoverflow_0006913388_cgi_python_urllib.txt |
Q:
Uninterpreted strings in YAML
Is there a way to have uninterpreted strings within a YAML file? My goal is to have regular expressions that contain certain escape sequences like \w. Currently, Python's YAML complains: found unknown escape character 'w'.
I know I could escape them, but this is going to obfuscate t... | Uninterpreted strings in YAML | Is there a way to have uninterpreted strings within a YAML file? My goal is to have regular expressions that contain certain escape sequences like \w. Currently, Python's YAML complains: found unknown escape character 'w'.
I know I could escape them, but this is going to obfuscate the actual regular expression. Any ... | [
"Appears that using single quotes doesn't interpret the escaped characters.\nE.g.,\nkey1: [ 'tron' ]\nkey2: [ 'not/escaped/[\\w-]*/.*' ]\n\nWorks.\n",
"Try using literal scalar syntax?\n"
] | [
16,
9
] | [] | [] | [
"python",
"yaml"
] | stackoverflow_0006915756_python_yaml.txt |
Q:
Check if file descriptor is valid
How do I check to see if a given file descriptor is valid? I want to write to fd=3 if it's available; otherwise, I want to write to stdout. I'm aware that I could wrap every os.write call with try-except statement, but I would like to know ahead of time if fd=3 is writable or not.... | Check if file descriptor is valid | How do I check to see if a given file descriptor is valid? I want to write to fd=3 if it's available; otherwise, I want to write to stdout. I'm aware that I could wrap every os.write call with try-except statement, but I would like to know ahead of time if fd=3 is writable or not.
| [
"You could use os.fstat to determine if the file descriptor is valid before each write, but you will need to wrap it in a try/except anyway because invalid file descriptors will raise an OSError. You are probably better off just creating your own write function with a try/except.\ndef write(data, fd=3):\n try:\... | [
9,
3
] | [] | [] | [
"file_descriptor",
"python",
"python_2.6"
] | stackoverflow_0006916033_file_descriptor_python_python_2.6.txt |
Q:
multiprocessing.Pool seems to work in Windows but not in ubuntu?
SOLVED: The problem was Wingware Python IDE. I guess the natural question now is how it is possible and how this could be fixed.
I asked a question yesterday ( Problem with multiprocessing.Pool in Python ) and this question is almost the same but I h... | multiprocessing.Pool seems to work in Windows but not in ubuntu? | SOLVED: The problem was Wingware Python IDE. I guess the natural question now is how it is possible and how this could be fixed.
I asked a question yesterday ( Problem with multiprocessing.Pool in Python ) and this question is almost the same but I have figured out that it seems to work on a Windows computer and not in... | [
"I don't have a solution for your first problem. In fact, I can run your code repeatedly without fail on my 64-bit Ubuntu box with Enthought's Python 2.7.1 [EPD 7.0-2 (64-bit)]. edit: It turns out the problem was being caused by your IDE (Wingware). The obvious workaround is to run the script from outside the IDE.\... | [
7,
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0006914240_multiprocessing_python.txt |
Q:
Utility that helps in file locking - expert tips wanted
I've written a subclass of file that a) provides methods to conveniently lock it (using fcntl, so it only supports unix, which is however OK for me atm) and b) when reading or writing asserts that the file is appropriately locked.
Now I'm not an expert at su... | Utility that helps in file locking - expert tips wanted | I've written a subclass of file that a) provides methods to conveniently lock it (using fcntl, so it only supports unix, which is however OK for me atm) and b) when reading or writing asserts that the file is appropriately locked.
Now I'm not an expert at such stuff (I've just read one paper [de] about it) and would a... | [
"I am also not an expert, but there is one thing you should change, and a couple others to consider:\nFirst off, using assert this way is a bad idea: if python is run with -O or -OO asserts are turned off and your two assert_*_lock() methods would always return True.\nSecond -- you need some tests. :) I took the... | [
2
] | [] | [] | [
"fcntl",
"locking",
"python",
"unix"
] | stackoverflow_0002908826_fcntl_locking_python_unix.txt |
Q:
python iterator through tree with list of children
i don't get the full grasp on python iterators,
i got an object with a list of children, and i want to iterate through this structure.
I want to get the same behaviour as with the printall function but with an iterator.
class t:
def __init__(self,... | python iterator through tree with list of children | i don't get the full grasp on python iterators,
i got an object with a list of children, and i want to iterate through this structure.
I want to get the same behaviour as with the printall function but with an iterator.
class t:
def __init__(self, i):
self.l = []
... | [
"It sounds like you want the iterator to act as a tree traversal. Study the itertools module and you can really go places.\nfrom itertools import chain, imap\n\nclass t:\n def __init__(self, value):\n self.value = value\n self.children = []\n def __iter__(self):\n \"implement the iterator protocol\"\n ... | [
21,
10,
5
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0006914803_iterator_python.txt |
Q:
Passing Cookies to a HTTP GET inside of a django middleware for single sign on
I need to implement a single sign for a django app that needs to interact with a 3rd parties single sign on system. The person starts off logged into the other system and they get redirected over to the django app. The django app needs ... | Passing Cookies to a HTTP GET inside of a django middleware for single sign on | I need to implement a single sign for a django app that needs to interact with a 3rd parties single sign on system. The person starts off logged into the other system and they get redirected over to the django app. The django app needs to check every few minutes if that person's session is still active. This is done by... | [
"Spoofing cookies isn't SSO, it's just spoofing cookies.\nThe way this \"should\" work is that either the domain cookie's expiry is literally the same as the session expiry or there's some kind of hash that other apps can use to poll the SSO app for the user's state.\nIf you're stuck and the SSO vendor is telling y... | [
0
] | [] | [] | [
"cookies",
"django",
"http",
"python",
"single_sign_on"
] | stackoverflow_0006915235_cookies_django_http_python_single_sign_on.txt |
Q:
Is there a clean way to check if a given user exists on a computer through python?
Currently I am using pwd.getpwall(), which shows me the entire password database. But I just want the users accounts of the computer. And with using getpwall() I am unable to do this ...
if 'foo' in pwd.getpwall():
do stuff
si... | Is there a clean way to check if a given user exists on a computer through python? | Currently I am using pwd.getpwall(), which shows me the entire password database. But I just want the users accounts of the computer. And with using getpwall() I am unable to do this ...
if 'foo' in pwd.getpwall():
do stuff
since pwd.getpwall() returns a list of objects. And if I wanted to check if a user exist I... | [
"In the same page of the manual:\n\npwd.getpwnam(name)\n\nReturn the password database entry for the given user name.\n\nThis is the result for an existent and an inexistent user:\n>>> import pwd\n>>> pwd.getpwnam('root')\npwd.struct_passwd(pw_name='root', pw_passwd='*', pw_uid=0, pw_gid=0, pw_gecos='System Adminis... | [
9,
1,
0
] | [] | [] | [
"operating_system",
"pwd",
"python"
] | stackoverflow_0006916208_operating_system_pwd_python.txt |
Q:
Py2App: File Needs to Be Included, but it is Too Large
At the moment, I'm using py2app to convert python scripts to a standalone application. However, my scripts require a 2GB unix executable. Py2App isn't able to process a file that large as an included file or resource, as it produces an error in the creation of... | Py2App: File Needs to Be Included, but it is Too Large | At the moment, I'm using py2app to convert python scripts to a standalone application. However, my scripts require a 2GB unix executable. Py2App isn't able to process a file that large as an included file or resource, as it produces an error in the creation of the standalone file. Is there anyway I can include this fil... | [
"I have more experience with Pyinstaller, but do you have to put the executable through Py2App? Might it be possible to package it with your executable in the same directory so it will be found and run? Is producing a single file very important, or could you include it in a directory with other dependencies?\n"
] | [
0
] | [] | [] | [
"compression",
"py2app",
"python"
] | stackoverflow_0006915473_compression_py2app_python.txt |
Q:
How to crop a region selected with mouse click, using Python?
I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select ... | How to crop a region selected with mouse click, using Python? | I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select the coordinates to croped the image with mouse clicks?
To better e... | [
"You could use matplotlib.widgets.RectangleSelector (thanks to Joe Kington for this suggestion) to handle button press events:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Image\nimport matplotlib.widgets as widgets\n\ndef onselect(eclick, erelease):\n if eclick.ydata>erelease.ydata:\n ecl... | [
8,
0
] | [] | [] | [
"image_processing",
"matplotlib",
"python",
"python_imaging_library"
] | stackoverflow_0006916054_image_processing_matplotlib_python_python_imaging_library.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.