title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Convert string to a tuple
3,920,751
3
2010-10-13T04:24:07Z
3,920,809
7
2010-10-13T04:37:26Z
[ "python" ]
I have a string like this: '|Action and Adventure|Drama|Science-Fiction|Fantasy|' How can I convert it to a tuple or a list? Thanks.
``` >>> s = '|Action and Adventure|Drama|Science-Fiction|Fantasy|' >>> >>> [item for item in s.split('|') if item.strip()] ['Action and Adventure', 'Drama', 'Science-Fiction', 'Fantasy'] >>> ``` If you'd rather have a tuple then: ``` >>> tuple(item for item in s.split('|') if item.strip()) ('Action and Adventure', '...
Python time differences
3,920,820
12
2010-10-13T04:39:39Z
3,920,857
16
2010-10-13T04:50:18Z
[ "python", "datetime", "time" ]
I have two time objects. Example ``` time.struct_time(tm_year=2010, tm_mon=9, tm_mday=24, tm_hour=19, tm_min=13, tm_sec=37, tm_wday=4, tm_yday=267, tm_isdst=-1) time.struct_time(tm_year=2010, tm_mon=9, tm_mday=25, tm_hour=13, tm_min=7, tm_sec=25, tm_wday=5, tm_yday=268, tm_isdst=-1) ``` I want to have the differenc...
`Time` instances do not support the subtraction operation. Given that one way to solve this would be to convert the time to seconds since epoch and then find the difference, use: ``` >>> t1 = time.localtime() >>> t1 time.struct_time(tm_year=2010, tm_mon=10, tm_mday=13, tm_hour=10, tm_min=12, tm_sec=27, tm_wday=2, tm_y...
Python time differences
3,920,820
12
2010-10-13T04:39:39Z
3,920,862
14
2010-10-13T04:51:43Z
[ "python", "datetime", "time" ]
I have two time objects. Example ``` time.struct_time(tm_year=2010, tm_mon=9, tm_mday=24, tm_hour=19, tm_min=13, tm_sec=37, tm_wday=4, tm_yday=267, tm_isdst=-1) time.struct_time(tm_year=2010, tm_mon=9, tm_mday=25, tm_hour=13, tm_min=7, tm_sec=25, tm_wday=5, tm_yday=268, tm_isdst=-1) ``` I want to have the differenc...
``` >>> t1 = time.mktime(time.strptime("10 Oct 10", "%d %b %y")) >>> t2 = time.mktime(time.strptime("15 Oct 10", "%d %b %y")) >>> print datetime.timedelta(seconds=t2-t1) 5 days, 0:00:00 ```
Python/Django: Adding custom model methods?
3,921,619
6
2010-10-13T07:37:06Z
3,921,785
20
2010-10-13T08:07:13Z
[ "python", "django", "methods", "model" ]
Using for example ``` class model(models.Model) .... def my_custom_method(self, *args, **kwargs): #do something ``` When I try to call this method during pre\_save, save, post\_save etc, Python raises a TypeError; unbound method. How can one add custom model methods which can be executed in the same ...
How are you calling this method? You have defined an *instance* method, which can only be called on an instance of the class, not the class itself. In other words, once you have an instance of `model` called `mymodelinstance`, you can do `mymodelinstance.my_custom_method()`. If you want to call it on the *class*, you ...
Reverting the 'global <var>' statement
3,921,822
2
2010-10-13T08:13:50Z
3,921,881
7
2010-10-13T08:23:13Z
[ "python", "scope", "global", "local" ]
I am learning Python and just had this question. It possibly has no practical worth, I'm asking this out maybe because of a pedantic curiosity. I have a function: ``` def f(): x = 12 #this is a local variable global x #this is a global I declared before x = 14 #changes global x <How can I retu...
Your code isn't doing what you think it is and there's no way to change it do what you describe. You can't "revert" what `globals` does since it has no effect at run time. The `global` keyword is interpreted at **compile time** so in the first line of `f()` where you set `x = 12` this is modifying the global `x` since...
How to interchange data between two python applications?
3,922,135
6
2010-10-13T09:02:30Z
3,922,174
7
2010-10-13T09:09:02Z
[ "python", "process", "pyqt4", "pid" ]
I have two python applications. I need to send commands and data between them (between two processes). What is the best way to do that? One program is a daemon who should accept commands and parameters from another GUI application. How can I make daemon to monitor comands from GUI, while making it's job? I prefer sol...
You can use the following methods for data interchange: 1. Socket Programming : In Qt you can access QtNetwork module. See qt assistant for examples 2. IPC : Use shared Memory implemented in QSharedMemory class. 3. If this application will run on unix os only, then you can try Posix based message queue etc. for data i...
How can I base64-encode unicode strings in JavaScript and Python?
3,922,314
3
2010-10-13T09:32:16Z
3,922,357
9
2010-10-13T09:39:17Z
[ "javascript", "python", "encoding", "base64" ]
I need an encript arithmetic, which encript text to text. the input text could be unicode, and the output should be a-z A-Z 0-9 - . (64 char max) and it could be decrypt to unicode again. it should implement in javascript and python. If there is already some library could do this, great, if there is not, could you ...
You might want to look at the [base64 module](http://docs.python.org/library/base64.html). In Python 2.x (starting with 2.4): ``` >>> import base64 >>> s=u"Rückwärts" >>> s u'R\xfcckw\xe4rts' >>> b=base64.b64encode(s.encode("utf-8")) >>> b 'UsO8Y2t3w6RydHM=' >>> d=base64.b64decode(b) >>> d 'R\xc3\xbcckw\xc3\xa4rts' ...
Find oldest/youngest datetime object in a list
3,922,644
40
2010-10-13T10:20:12Z
3,922,666
7
2010-10-13T10:22:49Z
[ "python", "datetime", "compare" ]
I've got a list of datetime objects, and I want to find the oldest or youngest one. Some of these dates might be in the future. ``` from datetime import datetime datetime_list = [ datetime(2009, 10, 12, 10, 10), datetime(2010, 10, 12, 10, 10), datetime(2010, 10, 12, 10, 10), datetime(2011, 10, 12, 10,...
Datetimes are comparable; so you can use `max(datetimes_list)` and `min(datetimes_list)`
Find oldest/youngest datetime object in a list
3,922,644
40
2010-10-13T10:20:12Z
3,922,675
55
2010-10-13T10:24:14Z
[ "python", "datetime", "compare" ]
I've got a list of datetime objects, and I want to find the oldest or youngest one. Some of these dates might be in the future. ``` from datetime import datetime datetime_list = [ datetime(2009, 10, 12, 10, 10), datetime(2010, 10, 12, 10, 10), datetime(2010, 10, 12, 10, 10), datetime(2011, 10, 12, 10,...
Oldest: ``` oldest = min(datetimes) ``` Youngest before now: ``` now = datetime.datetime.now(pytz.utc) youngest = max(dt for dt in datetimes if dt < now) ```
Find oldest/youngest datetime object in a list
3,922,644
40
2010-10-13T10:20:12Z
3,922,682
13
2010-10-13T10:25:13Z
[ "python", "datetime", "compare" ]
I've got a list of datetime objects, and I want to find the oldest or youngest one. Some of these dates might be in the future. ``` from datetime import datetime datetime_list = [ datetime(2009, 10, 12, 10, 10), datetime(2010, 10, 12, 10, 10), datetime(2010, 10, 12, 10, 10), datetime(2011, 10, 12, 10,...
Given a list of dates `dates`: Max date is `max(dates)` Min date is `min(dates)`
sqlalchemy Move mixin columns to end
3,923,910
9
2010-10-13T13:03:25Z
4,013,184
10
2010-10-25T09:13:06Z
[ "python", "sqlalchemy" ]
I have a sqlalchemy model, where all most all tables/objects have a notes field. So to try follow the DRY principle, I moved the field to a mixin class. ``` class NotesMixin(object): notes = sa.Column(sa.String(4000) , nullable=False, default='') class Service(Base, NotesMixin): __tablename__ = "service" ...
Found a cleaner solution: Use the `sqlalchemy.ext.declarative.declared_attr` decorator in sqlalchemy 0.6.5 (`sqlalchemy.util.classproperty` in sqlalchemy <= 0.6.4) ``` class NotesMixin(object): @declared_attr def notes(cls): return sa.Column(sa.String(4000) , nullable=False, default='') ``` According...
how to use tempfile.NamedTemporaryFile() in python
3,924,117
21
2010-10-13T13:23:07Z
3,924,253
35
2010-10-13T13:34:52Z
[ "python", "file-io", "temporary-files" ]
I want to use `tempfile.NamedTemporaryFile()` to write some contents into it and then open that file. I have written following code: ``` tf = tempfile.NamedTemporaryFile() tfName = tf.name tf.seek(0) tf.write(contents) tf.flush() ``` but I am unable to open this file and see its contents in notepad or similar applica...
This could be one of two reasons: Firstly, by default the temporary file is [deleted as soon as it is closed](http://docs.python.org/library/tempfile.html#tempfile.TemporaryFile). To fix this use: ``` tf = tempfile.NamedTemporaryFile(delete=False) ``` and then delete the file manually once you've finished viewing it...
how to use tempfile.NamedTemporaryFile() in python
3,924,117
21
2010-10-13T13:23:07Z
21,944,302
10
2014-02-21T20:15:19Z
[ "python", "file-io", "temporary-files" ]
I want to use `tempfile.NamedTemporaryFile()` to write some contents into it and then open that file. I have written following code: ``` tf = tempfile.NamedTemporaryFile() tfName = tf.name tf.seek(0) tf.write(contents) tf.flush() ``` but I am unable to open this file and see its contents in notepad or similar applica...
You can also use it with a context manager so that the file will be closed/deleted when it goes out of scope. It will also be cleaned up if the code in the context manager raises. ``` import tempfile with tempfile.NamedTemporaryFile() as temp: temp.write('Some data') temp.flush() # do something interestin...
Python's list comprehension vs .NET LINQ
3,925,093
36
2010-10-13T15:02:37Z
3,925,156
18
2010-10-13T15:09:42Z
[ "c#", "python", "linq", "list-comprehension" ]
The following simple LINQ code ``` string[] words = { "hello", "wonderful", "linq", "beautiful", "world" }; // Get only short words var shortWords = from word in words where word.Length <= 5 select word; // Print each word out shortWords.Dump(); ``` can be translated into python using list comprehension as fo...
Well, you need to distinguish between some different things: * LINQ standard query operators * LINQ query expressions in C# * LINQ query expressions in VB C# doesn't support as much in query expressions as VB does, but here's what it *does* support: * Projections (`select x.foo`) * Filtering (`where x.bar > 5`) * Jo...
Python's list comprehension vs .NET LINQ
3,925,093
36
2010-10-13T15:02:37Z
3,926,105
47
2010-10-13T17:01:55Z
[ "c#", "python", "linq", "list-comprehension" ]
The following simple LINQ code ``` string[] words = { "hello", "wonderful", "linq", "beautiful", "world" }; // Get only short words var shortWords = from word in words where word.Length <= 5 select word; // Print each word out shortWords.Dump(); ``` can be translated into python using list comprehension as fo...
(Warning: Mammoth answer ahead. The part up to the first horizontal line makes a good tl;dr section, I suppose) I'm not sure if I qualify as Python guru... but I have a solid grasp on iteration in Python, so let's try :) First off: Afaik, LINQ queries are executed lazily - if that's the case, generator expressions ar...
Python's list comprehension vs .NET LINQ
3,925,093
36
2010-10-13T15:02:37Z
6,257,477
13
2011-06-06T20:11:43Z
[ "c#", "python", "linq", "list-comprehension" ]
The following simple LINQ code ``` string[] words = { "hello", "wonderful", "linq", "beautiful", "world" }; // Get only short words var shortWords = from word in words where word.Length <= 5 select word; // Print each word out shortWords.Dump(); ``` can be translated into python using list comprehension as fo...
By using the [asq](http://asq.googlecode.com/) Python package you can easily do most things in Python that you can do in C# using LINQ-for-objects. Using asq, your Python example becomes: ``` from asq.initiators import query words = ["hello", "wonderful", "linq", "beautiful", "world"] shortWords = query(words).where(l...
How to get only the last part of a path in Python?
3,925,096
78
2010-10-13T15:03:15Z
3,925,125
11
2010-10-13T15:05:57Z
[ "python", "path", "path-manipulation" ]
In Python, suppose I have a path like this: ``` /folderA/folderB/folderC/folderD/ ``` How can I get just the `folderD` part?
You could do ``` >>> import os >>> os.path.basename('/folderA/folderB/folderC/folderD') ``` **UPDATE1:** This approach works in case you give it /folderA/folderB/folderC/folderD/xx.py. This gives xx.py as the basename. Which is not what you want I guess. So you could do this - ``` >>> import os >>> path = "/folderA/...
How to get only the last part of a path in Python?
3,925,096
78
2010-10-13T15:03:15Z
3,925,147
121
2010-10-13T15:08:39Z
[ "python", "path", "path-manipulation" ]
In Python, suppose I have a path like this: ``` /folderA/folderB/folderC/folderD/ ``` How can I get just the `folderD` part?
Use [`os.path.normpath`](https://docs.python.org/library/os.path.html#os.path.normpath), then [`os.path.basename`](https://docs.python.org/library/os.path.html#os.path.basename): ``` >>> os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/')) 'folderD' ``` The first strips off any trailing slashes, th...
print python stack trace without exception being raised
3,925,248
32
2010-10-13T15:20:47Z
3,925,311
51
2010-10-13T15:28:08Z
[ "python", "debugging", "stack-trace" ]
Something is happening with one of my class's instance variables. I want to make the variable a property, and whenever it is accessed I want to print out the stack trace of all the code leading up to that point, so I can see where it's being messed with. How do I print out the stack trace when no exception has been rai...
[`traceback.print_stack()`](http://docs.python.org/library/traceback.html#traceback.print_stack): ``` >>> def f(): ... def g(): ... traceback.print_stack() ... g() ... >>> f() File "<stdin>", line 1, in <module> File "<stdin>", line 4, in f File "<stdin>", line 3, in g ``` Edit: You can also use [extrac...
Repeating elements in list comprehension
3,925,465
11
2010-10-13T15:44:36Z
3,925,492
9
2010-10-13T15:47:19Z
[ "python", "list-comprehension" ]
I have this list comprehension: ``` [[x,x] for x in range(3)] ``` which results in this list: ``` [[0, 0], [1, 1], [2, 2]] ``` but what I want is this list: ``` [0, 0, 1, 1, 2, 2] ``` What's the easiest to way to generate this list?
``` [y for x in range(3) for y in [x, x]] ```
Automatically expiring variable
3,927,166
3
2010-10-13T19:13:59Z
3,927,214
7
2010-10-13T19:20:15Z
[ "python", "arrays", "variables" ]
How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in the array.
Hmmm, seems weird, but possible. Sounds like you need a class which records the time when `__init__` is called. Then, implement `__getitem__` to check the time when it is called, and only return the item if it's not too late. (It's probably easier to do this than to have a process "running in the background" which act...
Automatically expiring variable
3,927,166
3
2010-10-13T19:13:59Z
3,927,345
7
2010-10-13T19:39:30Z
[ "python", "arrays", "variables" ]
How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in the array.
I actually had to do this for dictionaries. Maybe you'll find the code useful: ``` """Cache which has data that expires after a given period of time.""" from datetime import datetime, timedelta class KeyExpiredError(KeyError): pass def __hax(): class NoArg: pass return NoArg() NoArg = __hax() class DataCac...
How do you get the exact path to "My Documents"?
3,927,259
12
2010-10-13T19:26:02Z
3,927,493
11
2010-10-13T19:55:56Z
[ "python", "windows" ]
In C++ it's not too hard to get the full pathname to the folder that the shell calls "My Documents" in Windows XP and Windows 7 and "Documents" in Vista; see <http://stackoverflow.com/questions/2414828/get-path-to-my-documents> Is there a simple way to do this in Python?
You could use the ctypes module to get the "My Documents" directory: ``` import ctypes from ctypes.wintypes import MAX_PATH dll = ctypes.windll.shell32 buf = ctypes.create_unicode_buffer(MAX_PATH + 1) if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False): print(buf.value) else: print("Failure!") ``` Sourc...
How can I profile python code line-by-line?
3,927,628
59
2010-10-13T20:12:36Z
3,927,671
71
2010-10-13T20:19:45Z
[ "python", "profiling", "line-by-line" ]
I've been using cProfile to profile my code, and it's been working great. I also use [gprof2dot.py](http://code.google.com/p/jrfonseca/wiki/Gprof2Dot) to visualize the results (makes it a little clearer). However, cProfile (and most other python profilers I've seen so far) seem to only profile at the function-call lev...
I believe that's what [Robert Kern's line\_profiler](http://packages.python.org/line_profiler/) is intended for. From the link: ``` File: pystone.py Function: Proc2 at line 149 Total time: 0.606656 s Line # Hits Time Per Hit % Time Line Contents =======================================================...
How can I profile python code line-by-line?
3,927,628
59
2010-10-13T20:12:36Z
28,273,414
12
2015-02-02T08:10:29Z
[ "python", "profiling", "line-by-line" ]
I've been using cProfile to profile my code, and it's been working great. I also use [gprof2dot.py](http://code.google.com/p/jrfonseca/wiki/Gprof2Dot) to visualize the results (makes it a little clearer). However, cProfile (and most other python profilers I've seen so far) seem to only profile at the function-call lev...
You could also use [pprofile](https://github.com/vpelletier/pprofile)([pypi](https://pypi.python.org/pypi/pprofile)). If you want to profile the entire execution, it does not require source code modification. You can also profile a subset of a larger program in two ways: * toggle profiling when reaching a specific poi...
Is it possible to overload from/import in Python?
3,928,023
8
2010-10-13T21:08:10Z
3,928,143
7
2010-10-13T21:22:26Z
[ "python", "import", "operator-overloading" ]
Is it possible to overload the from/import statement in Python? For example, assuming `jvm_object` is an instance of class `JVM`, is it possible to write this code: ``` class JVM(object): def import_func(self, cls): return something... jvm = JVM() # would invoke JVM.import_func from jvm import Foo ```
[This post](http://blog.dowski.com/2008/07/31/customizing-the-python-import-system/) demonstrates how to use functionality introduced in [PEP-302](http://www.python.org/dev/peps/pep-0302/) to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;)
python for loop, how to find next value(object)?
3,929,039
3
2010-10-14T00:08:41Z
3,929,057
11
2010-10-14T00:13:36Z
[ "python", "for-loop" ]
HI, I'm trying to use for loop to find the difference between every two object by minus each other. So, how can I find the next value in a for loop? ``` for entry in entries: first = entry # Present value last = ?????? # The last value how to say? diff = last = first ```
It should be noted that **none** of these solutions work for generators. For that see Glenn Maynards superior solution. use zip for small lists: ``` for current, last in zip(entries[1:], entries): diff = current - last ``` This makes a copy of the list (and a list of tuples from both copies of the list) so it'...
What does |= (ior) do in Python?
3,929,278
17
2010-10-14T01:00:13Z
3,929,285
13
2010-10-14T01:01:56Z
[ "python" ]
Google won't let me search |= so I'm having trouble finding relevant documentation. Anybody know?
In Python, and many other programming languages, `|` is the [bitwise-OR operation](http://en.wikipedia.org/wiki/Bitwise_operation). `|=` is to `|` as `+=` is to `+`.
UTF-8 compatible compression in python
3,929,301
4
2010-10-14T01:03:37Z
3,929,378
8
2010-10-14T01:19:11Z
[ "python", "utf-8" ]
I'd like to include a large compressed string in a json packet, but am having some difficulty. ``` import json,bz2 myString = "A very large string" zString = bz2.compress(myString) json.dumps({ 'compressedData' : zString }) ``` which will result in a ``` UnicodeDecodeError: 'utf8' codec can't decode bytes in posit...
Do you mean "compress *to* UTF-8 strings"? I'll assume that, since any generic compressor will compress UTF-8 strings. However, no real-world compressor is going to compress *to* a UTF-8 string. You can't store 8-bit data like UTF-8 directly in JSON, because JSON strings are defined as Unicode. You'd have to base64-en...
Python Unicode CSV export (using Django)
3,929,327
5
2010-10-14T01:08:17Z
3,929,609
7
2010-10-14T02:21:26Z
[ "python", "unicode", "utf-8", "csv", "ascii" ]
I'm using a Django app to export a string to a CSV file. The string is a message that was submitted through a front end form. However, I've been getting this error when a unicode single quote is provided in the input. ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 200: ordinal no...
You can't encode the Unicode character `u'\u2019'` (U+2019 Right Single Quotation Mark) into ASCII, because ASCII doesn't have that character in it. ASCII is only the basic Latin alphabet, digits and punctuation; you don't get any accented letters or ‘smart quotes’ like this character. So you will have to choose a...
Making Menu options with Checkbutton in Tkinter?
3,929,355
3
2010-10-14T01:13:45Z
3,934,647
7
2010-10-14T15:07:22Z
[ "python", "tkinter" ]
I am making a Menu using Tkinter, but I wanted to put `"add_checkbutton"` instead of `"add_command"` into the menu options, but problem is: how i deselect/select a checkbox? ``` menu = Menu(parent) parent.config(menu=menu) viewMenu = Menu(menu) menu.add_cascade(label="View", menu=viewMenu) viewMenu.add_command(labe...
You need to associate a variable with the checkbutton item(s), then set the variable to cause the item to be checked or unchecked. For example: ``` import tkinter as tk parent = tk.Tk() menubar = tk.Menu(parent) show_all = tk.BooleanVar() show_all.set(True) show_done = tk.BooleanVar() show_not_done = tk.BooleanVar()...
Does Python have an "or equals" function like ||= in Ruby?
3,929,433
33
2010-10-14T01:34:36Z
3,929,441
11
2010-10-14T01:36:47Z
[ "python", "ruby" ]
If not, what is the best way to do this? Right now I'm doing (for a django project): ``` if not 'thing_for_purpose' in request.session: request.session['thing_for_purpose'] = 5 ``` but its pretty awkward. In Ruby it would be: ``` request.session['thing_for_purpose'] ||= 5 ``` which is much nicer.
`dict` has [`setdefault()`](http://docs.python.org/library/stdtypes.html#dict.setdefault). So if `request.session` is a `dict`: ``` request.session.setdefault('thing_for_purpose', 5) ```
Does Python have an "or equals" function like ||= in Ruby?
3,929,433
33
2010-10-14T01:34:36Z
9,587,701
8
2012-03-06T16:22:57Z
[ "python", "ruby" ]
If not, what is the best way to do this? Right now I'm doing (for a django project): ``` if not 'thing_for_purpose' in request.session: request.session['thing_for_purpose'] = 5 ``` but its pretty awkward. In Ruby it would be: ``` request.session['thing_for_purpose'] ||= 5 ``` which is much nicer.
Setting a default makes sense if you're doing it in a middleware or something, but if you need a default value in the context of one request: ``` request.session.get('thing_for_purpose', 5) # gets a default ``` bonus: here's how to really do an `||=` in Python. ``` def test_function(self, d=None): 'a simple test...
Does Python have an "or equals" function like ||= in Ruby?
3,929,433
33
2010-10-14T01:34:36Z
19,964,319
85
2013-11-13T21:05:23Z
[ "python", "ruby" ]
If not, what is the best way to do this? Right now I'm doing (for a django project): ``` if not 'thing_for_purpose' in request.session: request.session['thing_for_purpose'] = 5 ``` but its pretty awkward. In Ruby it would be: ``` request.session['thing_for_purpose'] ||= 5 ``` which is much nicer.
The accepted answer is good for dicts, but the title seeks a general equivalent to Ruby's ||= operator. A common way to do something like ||= in Python is ``` x = x or new_value ```
Python if vs try-except
3,929,837
18
2010-10-14T03:21:10Z
3,929,887
33
2010-10-14T03:33:12Z
[ "python", "performance" ]
I was wondering why the try-except is slower than the if in the program below. ``` def tryway(): try: while True: alist.pop() except IndexError: pass def ifway(): while True: if alist == []: break else: alist.pop() if __name__=='__main__...
You're setting alist only once. The first call to "tryway" clears it, then every successive call does nothing. ``` def tryway(): alist = range(1000) try: while True: alist.pop() except IndexError: pass def ifway(): alist = range(1000) while True: if alist == []:...
python how to convert Nonetype to int or string
3,930,188
35
2010-10-14T04:55:16Z
3,930,234
7
2010-10-14T05:06:50Z
[ "python" ]
I've got an Nonetype value x, it's generally a number, but could be None. I want to divide it by a number, but python says ``` TypeError: int() argument must be a string or a number, not 'NoneType' ``` How could I solve that
That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.
python how to convert Nonetype to int or string
3,930,188
35
2010-10-14T04:55:16Z
3,930,320
156
2010-10-14T05:26:18Z
[ "python" ]
I've got an Nonetype value x, it's generally a number, but could be None. I want to divide it by a number, but python says ``` TypeError: int() argument must be a string or a number, not 'NoneType' ``` How could I solve that
``` int(value or 0) ``` This will use 0 in the case when you provide any value that Python considers `False`, such as None, 0, [], "", etc. Since 0 is `False`, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value). ``` int(0 if value is None else value) ``` This rep...
python how to convert Nonetype to int or string
3,930,188
35
2010-10-14T04:55:16Z
3,930,374
21
2010-10-14T05:37:58Z
[ "python" ]
I've got an Nonetype value x, it's generally a number, but could be None. I want to divide it by a number, but python says ``` TypeError: int() argument must be a string or a number, not 'NoneType' ``` How could I solve that
In one of the comments, you say: > Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object If it's your code, figure out how you're getting `None` when you expect a number and stop **that** from happening. If it's someone else's code, find out the conditions under which it gives `No...
python how to convert Nonetype to int or string
3,930,188
35
2010-10-14T04:55:16Z
3,931,746
8
2010-10-14T09:20:21Z
[ "python" ]
I've got an Nonetype value x, it's generally a number, but could be None. I want to divide it by a number, but python says ``` TypeError: int() argument must be a string or a number, not 'NoneType' ``` How could I solve that
A common "Pythonic" way to handle this kind of situation is known as **EAFP** for "*It's easier to ask forgiveness than permission*". Which usually means writing code that assumes everything is fine, but then wrapping it with a `try..except` block just in case to handle things when it's not. Here's that coding style a...
How do you run nosetest from pycharm?
3,930,422
16
2010-10-14T05:45:41Z
13,359,250
16
2012-11-13T10:39:54Z
[ "python", "unit-testing", "nose", "nosetests", "pycharm" ]
How do you execute nosetest from pycharm to run all unit tests? I know that pycharm supports python's unittest and py.test and that they will properly support nosetests in pycharm 1.1 but I was wondering if there was a work around.
In the current version of Pycharm (2.6) there should be a context menu "run Nosetests in ..." on a test file. If this is missing, go to `file->settings->Project Settings->python integrated tools` and ensure the Default Test Runner is Nosetests. You do of course need to have Nosetests installed - pycharm will offer this...
python: serialize a dictionary into a simple html output
3,930,713
5
2010-10-14T06:42:02Z
3,930,913
8
2010-10-14T07:16:15Z
[ "python" ]
using app engine - yes i know all about django templates and other template engines. Lets say i have a dictionary or a simple object, i dont know its structure and i want to serialize it into html. so if i had ``` {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}...
The example made by pyfunc could easily be modified to generate simple nested html lists. ``` z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}} def printItems(dictObj, indent): print ' '*indent + '<ul>\n' for k,v in dictObj.iteritems(): if is...
Python Check if all of the following items is in a list
3,931,541
32
2010-10-14T08:52:05Z
3,931,598
37
2010-10-14T08:58:09Z
[ "list", "python", "inclusion" ]
I found, that there is related question, about how to find if at least one item exists in a list: <http://stackoverflow.com/questions/740287/python-check-if-one-of-the-following-items-is-in-a-list> But what is the best and pythonic way to find whether all items exists in a list? Searching througth the docs I found ...
I would probably use [`set`](http://rgruet.free.fr/PQR26/PQR2.6.html#Sets) in the following manner : ``` set(l).issuperset(set(['a','b'])) ``` or the other way round : ``` set(['a','b']).issubset(set(l)) ``` I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/inters...
Python Check if all of the following items is in a list
3,931,541
32
2010-10-14T08:52:05Z
3,931,655
14
2010-10-14T09:05:34Z
[ "list", "python", "inclusion" ]
I found, that there is related question, about how to find if at least one item exists in a list: <http://stackoverflow.com/questions/740287/python-check-if-one-of-the-following-items-is-in-a-list> But what is the best and pythonic way to find whether all items exists in a list? Searching througth the docs I found ...
Operators like `<=` in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me. Use the equivalent and more clearly-named method, `set.issubset`. Note that you don't need to convert the a...
Is it possible to issue a "VACUUM ANALYZE <tablename>" from psycopg2 or sqlalchemy for PostgreSQL?
3,931,951
4
2010-10-14T09:49:28Z
3,932,055
9
2010-10-14T10:04:18Z
[ "python", "postgresql", "sqlalchemy", "psycopg2", "vacuum" ]
Well, the question pretty much summarises it. My db activity is very update intensive, and I want to programmatically issue a Vacuum Analyze. However I get an error that says that the query cannot be executed within a transaction. Is there some other way to do it?
This is a flaw in the Python DB-API: it starts a transaction for you. It shouldn't do that; whether and when to start a transaction should be up to the programmer. Low-level, core APIs like this shouldn't babysit the developer and do things like starting transactions behind our backs. We're big boys--we can start trans...
Slice notation in scala?
3,932,582
27
2010-10-14T11:20:42Z
3,932,646
47
2010-10-14T11:32:03Z
[ "python", "scala", "slice" ]
Is there something similar to [slice notation in python](http://docs.python.org/tutorial/introduction.html#strings) in scala ? I think this is really a useful operation that should be incorporated in all languages.
Equivalent method in Scala (with a slightly different syntax) exists for all kinds of sequences: ``` scala> "Hello world" slice(0,4) res0: String = Hell scala> (1 to 10) slice(3,5) res1: scala.collection.immutable.Range = Range(4, 5) ``` The biggest difference compared to slicing in Python is that start and end indi...
Slice notation in scala?
3,932,582
27
2010-10-14T11:20:42Z
3,932,745
19
2010-10-14T11:47:03Z
[ "python", "scala", "slice" ]
Is there something similar to [slice notation in python](http://docs.python.org/tutorial/introduction.html#strings) in scala ? I think this is really a useful operation that should be incorporated in all languages.
``` scala> import collection.IterableLike import collection.IterableLike scala> implicit def pythonicSlice[A, Repr](coll: IterableLike[A, Repr]) = new { | def apply(subrange: (Int, Int)): Repr = coll.slice(subrange._1, subrange._2) | } pythonicSlice: [A,Repr](coll: scala.collection.IterableLike[A,Repr])jav...
Calling staticmethod inside class level containers initialization
3,932,948
14
2010-10-14T12:14:44Z
3,933,062
16
2010-10-14T12:27:46Z
[ "python", "static-methods" ]
Given the following example class: ``` class Foo: def aStaticMethod(): return "aStaticMethod" aVariable = staticmethod(aStaticMethod) aTuple = (staticmethod(aStaticMethod),) aList = [staticmethod(aStaticMethod)] print Foo.aVariable() print Foo.aTuple[0]() print Foo.aList[0]() ``` Why would ...
It's because a static method is a descriptor. When you attach it to a class and call it with the usual syntax, then python calls its `__get__` method which returns a callable object. When you deal with it as a bare descriptor, python never calls its `__get__` method and you end up attempting to call the descriptor dire...
In Python, why do we need readlines() when we can iterate over the file handle itself?
3,933,223
21
2010-10-14T12:47:54Z
3,933,251
17
2010-10-14T12:50:30Z
[ "python" ]
In Python, after ``` fh = open('file.txt') ``` one may do the following to iterate over lines: ``` for l in fh: pass ``` Then why do we have `fh.readlines()`?
I would imagine that it's from before files were iteratators and is maintained for backwards compatibility. Even for a one-liner, it's totally1 fairly redundant as `list(fh)` will do the same thing in a more intuitive way. That also gives you the freedom to do `set(fh)`, `tuple(fh)`, etc. 1 See [gnibbler's answer](htt...
In Python, why do we need readlines() when we can iterate over the file handle itself?
3,933,223
21
2010-10-14T12:47:54Z
3,933,557
16
2010-10-14T13:22:18Z
[ "python" ]
In Python, after ``` fh = open('file.txt') ``` one may do the following to iterate over lines: ``` for l in fh: pass ``` Then why do we have `fh.readlines()`?
Mostly it is there for backward compatibility. readlines was there way before file objects were iterable Using readlines with the size argument is also one of the fastest ways to read from files because it reads a bunch of data in one hit, but doesn't need to allocate memory for the entire file all at once
accessing python dictionary
3,933,478
5
2010-10-14T13:15:45Z
3,933,534
11
2010-10-14T13:20:07Z
[ "python", "dictionary" ]
I am writing code that will search twitter for key words and store them in a python dictionary: ``` base_url = 'http://search.twitter.com/search.json?rpp=100&q=4sq.com/' query = '7bOHRP' url_string = base_url + query logging.info("url string = " + url_string) json_text = fetch(u...
``` result[0][u'from_user'] ``` The `u` prefix means that it's a [`unicode`](http://farmdev.com/talks/unicode/) instead of a `str`.
Best Practices for Python UnicodeDecodeError
3,933,911
4
2010-10-14T13:56:18Z
3,933,973
10
2010-10-14T14:01:58Z
[ "python", "unicode", "exception-handling", "pylons", "mako" ]
I use **Pylons** framework, **Mako** template for a web based application. I wasn't really bother too deep into the way Python handles the unicode strings. I had tense moment when I did see my site crash when the page is rendered and later I came to know that it was related to [UnicodeDecodeError](http://wiki.python.or...
If you have influence on it, this is the painless way: * know your input encoding (or decode with ignore) and `decode(encoding)` the data as soon as it hits your app * work internally only with unicode (`u'something'` is unicode), also in the database * for rendering, export etc, anytime it leaves your app, `encode('u...
Java: automatic memoization
3,934,777
11
2010-10-14T15:22:56Z
9,755,364
10
2012-03-18T01:53:44Z
[ "java", "python", "annotations", "decorator", "memoization" ]
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
Spring 3.1 now provides a [`@Cacheable` annotation](http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html), which does exactly this. > As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache...
What does raise in Python raise?
3,935,603
29
2010-10-14T17:00:03Z
3,935,643
15
2010-10-14T17:05:21Z
[ "python", "exception" ]
Consider the following code: ``` try: raise Exception("a") except: try: raise Exception("b") finally: raise ``` This will raise `Exception: a`. I expected it to raise `Exception: b` (need I explain why?). Why does the final `raise` raise the original exception rather than (what I thought) ...
On python2.6 I guess, you are expecting the finally block to be tied with the "try" block where you raise the exception "B". The finally block is attached to the first "try" block. If you added an except block in the inner try block, then the finally block will raise exception B. ``` try: raise Exception("a") exce...
What does raise in Python raise?
3,935,603
29
2010-10-14T17:00:03Z
3,937,424
25
2010-10-14T20:48:52Z
[ "python", "exception" ]
Consider the following code: ``` try: raise Exception("a") except: try: raise Exception("b") finally: raise ``` This will raise `Exception: a`. I expected it to raise `Exception: b` (need I explain why?). Why does the final `raise` raise the original exception rather than (what I thought) ...
> Raise is re-raising the last exception you caught, not the last exception you raised (reposted from comments for clarity)
Python reclaiming memory after deleting items in a dictionary
3,935,675
10
2010-10-14T17:09:10Z
3,935,766
18
2010-10-14T17:21:35Z
[ "python", "memory-management" ]
I have a relatively large dictionary in Python and would like to be able to not only delete items from it, but actually *reclaim* the memory back from these deletions in my program. I am running across a problem whereby although I delete items from the dictionary and even run the garbage collector manually, Python does...
A lot of factors go into whether Python returns this memory to the underlying OS or not, which is probably how you're trying to tell if memory is being freed. CPython has a pooled allocator system that tends to hold on to freed memory so that it can be reused in an efficient manner (but these subsequent allocations won...
Differences and uses between WSGI, CGI, FastCGI, and mod_python in regards to Python?
3,937,224
46
2010-10-14T20:22:45Z
3,937,236
28
2010-10-14T20:24:39Z
[ "python", "cgi", "fastcgi", "wsgi", "mod-python" ]
I'm just wondering what the differences and advantages are for the different CGI's out there. Which one would be best for python scripts, and how would I tell the script what to use?
A part answer to your question, including scgi. * <http://stackoverflow.com/questions/257481/whats-the-difference-between-scgi-and-wsgi> * <http://stackoverflow.com/questions/1747266/is-there-a-speed-difference-between-wsgi-and-fcgi> * <http://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-f...
Differences and uses between WSGI, CGI, FastCGI, and mod_python in regards to Python?
3,937,224
46
2010-10-14T20:22:45Z
9,931,709
12
2012-03-29T18:59:52Z
[ "python", "cgi", "fastcgi", "wsgi", "mod-python" ]
I'm just wondering what the differences and advantages are for the different CGI's out there. Which one would be best for python scripts, and how would I tell the script what to use?
There's also a good background reader on CGI, WSGI and other options, in the form of an official python HOWTO: <http://docs.python.org/howto/webservers.html>
Python Method Placement
3,937,450
4
2010-10-14T20:50:48Z
3,937,484
12
2010-10-14T20:54:29Z
[ "python" ]
Can someone give me a solution to this ``` dosomething() def dosomething(): print 'do something' ``` I don't want my method defines up at the top of the file, is there a way around this?
The "standard" way is to do things inside a `main` function at the top of your file and then call `main()` at the bottom. E.g. ``` def main(): print 'doing stuff' foo() bar() def foo(): print 'inside foo' def bar(): print 'inside bar' if __name__ == '__main__': main() ``` if `if __name__ ==...
fitting exponential decay with no initial guessing
3,938,042
13
2010-10-14T22:18:32Z
3,938,548
29
2010-10-15T00:14:17Z
[ "python", "numpy", "scipy" ]
Does anyone know a scipy/numpy module which will allow to fit exponential decay to data? Google search returned a few blog posts, for example - <http://exnumerus.blogspot.com/2010/04/how-to-fit-exponential-decay-example-in.html> , but that solution requires y-offset to be pre-specified, which is not always possible E...
You have two options: 1. Linearize the system, and fit a line to the log of the data. 2. Use a non-linear solver (e.g. [`scipy.optimize.curve_fit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) The first option is by far the fastest and most robust. However, it requires that you k...
Python save matplotlib figure on an PIL Image object
3,938,676
6
2010-10-15T00:45:33Z
4,302,192
12
2010-11-29T09:03:22Z
[ "python", "image", "matplotlib", "python-imaging-library" ]
HI, is it possible that I created a image from matplotlib and I save it on an image object I created from PIL? Sounds very hard? Who can help me?
To render Matplotlib images in a webpage in the Django Framework: * create the matplotlib plot * save it as a png file * store this image in a string buffer (using PIL) * pass this buffer to Django's ***HttpResponse*** (set *mime type* image/png) * which returns a *response object* (the rendered plot in this case). I...
Iterator (iter()) function in Python
3,938,927
11
2010-10-15T01:53:33Z
3,938,962
15
2010-10-15T02:03:36Z
[ "python", "iterator" ]
For dictionary, I can use iter() for iterating over keys of the dictionary. ``` y = {"x":10, "y":20} for val in iter(y): print val ``` When I have the iterator as follows, ``` class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): re...
All of these work fine, except for a typo--you probably mean: ``` x = Counter(3,8) for i in x: print i ``` rather than ``` x = Counter(3,8) for i in x: print x ```
Run command line arguments in python script
3,939,196
2
2010-10-15T03:02:47Z
3,939,226
7
2010-10-15T03:09:30Z
[ "python", "shell" ]
I have a program that is run from the command line like this ``` python program.py 100 rfile ``` How can I write a *new* script so that instead of running it with just the '100' argument, I can run it consecutively with a list of arguments like [50, 100, 150, 200]? Edit: The reason I am asking is that I want to reco...
If you create a bash file like this ``` #!/bin/bash for i in 1 2 3 4 5 do python program.py $i rfile done ``` then do `chmod +x` on that file, when you run it, it will run these consecutively: ``` python program.py 1 rfile python program.py 2 rfile python program.py 3 rfile python program.py 4 rfile python program...
Remove specific characters from a string in python
3,939,361
215
2010-10-15T03:46:21Z
3,939,381
313
2010-10-15T03:50:38Z
[ "python", "string", "immutability" ]
I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. ``` for char in line: if char in " ?.!/;:": line.replace(char,'') ``` How do I do this properly?
Strings in Python are *immutable* (can't be changed). Because of this, the effect of `line.replace(...)` is just to create a new string, rather than changing the old one. You need to *rebind* (assign) it to `line` in order to have that variable take the new value, with those characters removed. Also, the way you are d...
Remove specific characters from a string in python
3,939,361
215
2010-10-15T03:46:21Z
3,939,403
11
2010-10-15T03:59:40Z
[ "python", "string", "immutability" ]
I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. ``` for char in line: if char in " ?.!/;:": line.replace(char,'') ``` How do I do this properly?
``` line = line.translate(None, " ?.!/;:") ```
Remove specific characters from a string in python
3,939,361
215
2010-10-15T03:46:21Z
3,939,473
13
2010-10-15T04:18:18Z
[ "python", "string", "immutability" ]
I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. ``` for char in line: if char in " ?.!/;:": line.replace(char,'') ``` How do I do this properly?
``` >>> line = "abc#@!?efg12;:?" >>> ''.join( c for c in line if c not in '?:!/;' ) 'abc#@efg12' ```
Remove specific characters from a string in python
3,939,361
215
2010-10-15T03:46:21Z
3,942,100
79
2010-10-15T12:11:54Z
[ "python", "string", "immutability" ]
I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. ``` for char in line: if char in " ?.!/;:": line.replace(char,'') ``` How do I do this properly?
Am I missing the point here, or is it just the following: ``` >>> string = "ab1cd1ef" >>> string.replace("1","") 'abcdef' >>> ``` Put it in a loop: ``` >>> >>> a = "a!b@c#d$" >>> b = "!@#$" >>> for char in b: ... a = a.replace(char,"") ... >>> print a abcd >>> ```
Remove specific characters from a string in python
3,939,361
215
2010-10-15T03:46:21Z
8,509,424
7
2011-12-14T18:03:11Z
[ "python", "string", "immutability" ]
I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. ``` for char in line: if char in " ?.!/;:": line.replace(char,'') ``` How do I do this properly?
The asker almost had it. Like most things in Python, the answer is simpler than you think. ``` >>> line = "H E?.LL!/;O:: " >>> for char in ' ?.!/;:': ... line = line.replace(char,'') ... >>> print line HELLO ``` You don't have to do the nested if/for loop thing, but you DO need to check each character individu...
Remove specific characters from a string in python
3,939,361
215
2010-10-15T03:46:21Z
21,357,173
9
2014-01-25T22:39:18Z
[ "python", "string", "immutability" ]
I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. ``` for char in line: if char in " ?.!/;:": line.replace(char,'') ``` How do I do this properly?
For the inverse requirement of **only *allowing* certain characters** in a string, you can use regular expressions with a set complement operator `[^ABCabc]`. For example, to remove everything except ascii letters, digits, and the hyphen: ``` >>> import string >>> import re >>> >>> phrase = ' There were "nine" (9) ch...
Sieve of Eratosthenes - Finding Primes Python
3,939,660
43
2010-10-15T05:16:42Z
3,941,967
59
2010-10-15T11:54:15Z
[ "python", "math", "primes", "sieve-of-eratosthenes" ]
Just to clarify, this is not a homework problem :) I wanted to find primes for a math application I am building & came across [**Sieve of Eratosthenes**](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) approach. I have written an implementation of it in Python. But it's terribly slow. For say, if I want to find a...
You're not quite implementing the correct algorithm: In your first example, `primes_sieve` doesn't maintain a list of primality flags to strike/unset (as in the algorithm), but instead resizes a list of integers continuously, which is very expensive: removing an item from a list requires shifting all subsequent items ...
pydev not recognizing python installation with django
3,939,877
14
2010-10-15T06:11:43Z
3,941,289
12
2010-10-15T10:14:35Z
[ "python", "django", "eclipse", "pydev" ]
I have python installed with django. I know the installation is there because I installed it following the directions and in the command line I can do "import python" and there is no crash. When I try creating a django project in pydev, I get an error: "Django not found." What could the problem be?
go in the menu to **window -> preference -> pydev -> Interpreter - Python** ; and add the python interpreter there, if you installed the django in a virtual environment you should add the python interpreter of the virtual env ; after adding the interpreter by clicking on **new** you should now click on **Apply** , you ...
pydev not recognizing python installation with django
3,939,877
14
2010-10-15T06:11:43Z
4,241,222
21
2010-11-22T00:12:19Z
[ "python", "django", "eclipse", "pydev" ]
I have python installed with django. I know the installation is there because I installed it following the directions and in the command line I can do "import python" and there is no crash. When I try creating a django project in pydev, I get an error: "Django not found." What could the problem be?
I had the same problem and this is what I did just after installing eclipse: * Preferences > Interpreter Python * Pressed Auto-config * Selected /Library/Python/x.x/site-packages, which was not selected (some django folders were in there, persumably the installation) * Clicked apply / OK Creating a Django project a...
exhausted iterators - what to do about them?
3,940,072
5
2010-10-15T06:47:52Z
3,940,095
7
2010-10-15T06:53:13Z
[ "python", "filter", "iterator", "python-3.x" ]
(In Python 3.1) (Somewhat related to [another question I asked](http://stackoverflow.com/questions/3939960/python-filter-max-combo-checking-for-empty-iterator), but this question is about iterators being exhausted.) ``` # trying to see the ratio of the max and min element in a container c filtered = filter(lambda x : ...
The [`itertools.tee`](http://docs.python.org/dev/library/itertools.html#itertools.tee) function can help here: ``` import itertools f1, f2 = itertools.tee(filtered, 2) ratio = max(f1) / min(f2) ```
Is it technically possible to take a screenshot of a website programmatically?
3,940,098
6
2010-10-15T06:53:39Z
3,940,169
14
2010-10-15T07:06:51Z
[ "python", "google-app-engine", "screenshot" ]
Do you think is technically possible to take a screeshot of a website programmatically? I would like to craft a scheduled Python task that crawls a list of websites taking an homepage screenshot of them. Do you think is technically feasible or do you know third party website that offer a service like that (`Input: ur...
Are you looking for functionality like what [browsershots.org](http://browsershots.org) offers? Source code available at [Google Code/Browsershots](http://code.google.com/p/browsershots/).
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
3,940,137
668
2010-10-15T07:01:12Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
``` >>> L = [0,10,20,40] >>> L[::-1] [40, 20, 10, 0] ``` Extended slice syntax is explained well here: <http://docs.python.org/release/2.3.5/whatsnew/section-slices.html> By special request in a comment [this is the most current slice documentation](http://docs.python.org/library/functions.html#slice).
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
3,940,140
12
2010-10-15T07:01:53Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
``` for x in array[::-1]: do stuff ```
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
3,940,144
479
2010-10-15T07:02:20Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
You can make use of the [`reversed`](http://docs.python.org/release/2.4.4/whatsnew/node7.html) function for this as: ``` >>> array=[0,10,20,40] >>> for i in reversed(array): ... print i ``` Note that `reversed(...)` does not return a list. You can get a reversed list using `list(reversed(array))`.
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
3,940,149
178
2010-10-15T07:03:02Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
``` >>> L = [0,10,20,40] >>> L.reverse() >>> L [40, 20, 10, 0] ``` Or ``` >>> L[::-1] [40, 20, 10, 0] ```
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
28,937,092
18
2015-03-09T07:36:43Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
This is to duplicate list ``` L = [0,10,20,40] p=L[::-1] Here p will be having reversed list ``` This is to reverse the same list ``` L.reverse() Here L will be having reversed list ```
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
34,705,677
7
2016-01-10T13:02:32Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
Possible ways, ``` list1 = [3,4,3,545,6,4,34,243] list1.reverse() list1[::-1] ```
How can I reverse a list in python?
3,940,128
395
2010-10-15T06:59:39Z
35,630,643
10
2016-02-25T14:51:49Z
[ "python", "list" ]
How can I do this in python? ``` array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) ``` I need to have the elements of an array but from the end to the beginning.
Using slicing, e.g. array = array[::-1], is a neat trick and very pythonistic but a little obscure for newbies maybe, using the reverse() method is a good way to go in day to day coding. However if you need to reverse a list in place as in an interview question, you will likely not be able to use built in methods like...
How to split this string with python?
3,940,721
8
2010-10-15T08:44:14Z
3,940,744
15
2010-10-15T08:47:36Z
[ "python", "string", "split" ]
I have strings that look like this example: "AAABBBCDEEEEBBBAA" Any character is possible in the string. I want to split it to a list like: ['AAA','BBB','C','D','EEEE','BBB','AA'] so every continuous stretch of the same characters goes to separate element of the split list. I know that I can iterate over characters...
We could use Regex: ``` >>> import re >>> r = re.compile(r'(.)\1*') >>> [m.group() for m in r.finditer('AAABBBCDEEEEBBBAA')] ['AAA', 'BBB', 'C', 'D', 'EEEE', 'BBB', 'AA'] ``` --- Alternatively, we could use [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby). ``` >>> import iterto...
How to split this string with python?
3,940,721
8
2010-10-15T08:44:14Z
3,940,755
9
2010-10-15T08:50:16Z
[ "python", "string", "split" ]
I have strings that look like this example: "AAABBBCDEEEEBBBAA" Any character is possible in the string. I want to split it to a list like: ['AAA','BBB','C','D','EEEE','BBB','AA'] so every continuous stretch of the same characters goes to separate element of the split list. I know that I can iterate over characters...
``` >>> from itertools import groupby >>> [''.join(g) for k, g in groupby('AAAABBBCCD')] ['AAAA', 'BBB', 'CC', 'D'] ``` And by normal string manipulation ``` >>> a=[];S="";p="" >>> s 'AAABBBCDEEEEBBBAA' >>> for c in s: ... if c != p: a.append(S);S="" ... S=S+c ... p=c ... >>> a.append(S) >>> a ['', 'AAA',...
x,y = getPos() vs. (x, y) = getPos()
3,941,407
5
2010-10-15T10:31:26Z
3,941,450
8
2010-10-15T10:37:47Z
[ "python", "tuples" ]
Consider this function getPos() which returns a tuple. What is the difference between the two following assignments? Somewhere I saw an example where the first assignment was used but when I just tried the second one, I was surprised it also worked. So, is there really a difference, or does Python just figure out that ...
Read about [tuples](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences): > A tuple consists of a number of values separated by commas (...) So parenthesis does not make a tuple a tuple. The commas do it. Parenthesis are only needed if you have weird nested structures: ``` x, (y, (w, z)), r ```
Converting list to *args in Python
3,941,517
45
2010-10-15T10:48:44Z
3,941,529
82
2010-10-15T10:50:49Z
[ "python", "list", "arguments" ]
In Python, how do I convert a list to \*args? I need to know because the function ``` scikits.timeseries.lib.reportlib.Report.__init__(*args) ``` wants several time\_series objects passed as \*args, whereas I have a list of timeseries objects. Any help is greatly appreciated :)
You can use the `*` operator before an iterable to expand it within the function call. For example: ``` timeseries_list = [timeseries1 timeseries2 ...] r = scikits.timeseries.lib.reportlib.Report(*timeseries_list) ``` (notice the `*` before `timeseries_list`) From the [python documentation](https://docs.python.org/2...
Converting list to *args in Python
3,941,517
45
2010-10-15T10:48:44Z
3,941,775
8
2010-10-15T11:27:36Z
[ "python", "list", "arguments" ]
In Python, how do I convert a list to \*args? I need to know because the function ``` scikits.timeseries.lib.reportlib.Report.__init__(*args) ``` wants several time\_series objects passed as \*args, whereas I have a list of timeseries objects. Any help is greatly appreciated :)
yes, using \*arg passing args to a function will make python unpack the values in arg and pass it to the function. so: ``` >>> def printer(*args): print args >>> printer(2,3,4) (2, 3, 4) >>> printer(*range(2, 5)) (2, 3, 4) >>> printer(range(2, 5)) ([2, 3, 4],) >>> ```
How to set a python property in __init__
3,941,919
11
2010-10-15T11:49:12Z
3,941,952
11
2010-10-15T11:52:40Z
[ "python", "properties" ]
I have a class with an attribute I wish to turn into a property, but this attribute is set within `__init__`. Not sure how this should be done. Without setting the propert in `__init__` this is easy and works well ``` import datetime class STransaction(object): """A statement transaction""" def __init__(self)...
I do not see any real problem with your code. In `__init__`, the class is fully created and thus the properties accessible.
How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this?
3,942,303
42
2010-10-15T12:42:36Z
3,942,321
13
2010-10-15T12:46:01Z
[ "python", "methods", "comparison", "set" ]
I need to create a 'container' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objects are deemed to be identical, one (either one) is removed. My first thought was to use a `set([])` as the containing object, to complete this requir...
I am afraid you will have to provide a `__hash__()` method. But you can code it the way, that it does not depend on the mutable attributes of your `Item`.
How does a Python set([]) check if two objects are equal? What methods does an object need to define to customise this?
3,942,303
42
2010-10-15T12:42:36Z
17,302,732
29
2013-06-25T16:31:07Z
[ "python", "methods", "comparison", "set" ]
I need to create a 'container' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objects are deemed to be identical, one (either one) is removed. My first thought was to use a `set([])` as the containing object, to complete this requir...
Yes, you need a `__hash__()`-method AND the comparing-operator which you already provided. ``` class Item(object): def __init__(self, foo, bar): self.foo = foo self.bar = bar def __repr__(self): return "Item(%s, %s)" % (self.foo, self.bar) def __eq__(self, other): if isinsta...
Display NumPy array as continuously updating image with Glumpy
3,942,549
7
2010-10-15T13:15:31Z
14,494,168
10
2013-01-24T04:48:04Z
[ "python", "opengl", "numpy", "plot", "glumpy" ]
I've got a simulation model running in Python using NumPy and SciPy and it produces a 2D NumPy array as the output each iteration. I've been displaying this output as an image using matplotlib and the imshow function. However, I've found out about Glumpy, and on its documentation page it says: *Thanks to the IPython s...
The Glumpy documentation is fairly nonexistent! Here's an example of a simple simulation, comparing array visualisation with `glumpy` against `matplotlib`: ``` import numpy as np import glumpy from OpenGL import GLUT as glut from time import time from matplotlib.pyplot import subplots,close from matplotlib import cm ...
How to do unit testing of functions writing files using python unittest
3,942,820
37
2010-10-15T13:49:09Z
3,943,697
31
2010-10-15T15:29:12Z
[ "python", "unit-testing", "file" ]
I have a Python function that writes an output file to disk. I want to write a unit test for it using Python unittest module. How should I assert equality of files? I would like to get an error if the file content differs from the expected one + list of differences. As in the output of unix diff command. Is there an...
The simplest thing is to write the output file, then read its contents, read the contents of the gold (expected) file, and compare them with simple string equality. If they are the same, delete the output file. If they are different, raise an assertion. This way, when the tests are done, every failed test will be repr...
How to do unit testing of functions writing files using python unittest
3,942,820
37
2010-10-15T13:49:09Z
3,945,057
29
2010-10-15T18:32:47Z
[ "python", "unit-testing", "file" ]
I have a Python function that writes an output file to disk. I want to write a unit test for it using Python unittest module. How should I assert equality of files? I would like to get an error if the file content differs from the expected one + list of differences. As in the output of unix diff command. Is there an...
I prefer to have output functions explicitly accept a file *handle* (or file-like *object*), rather than accept a file *name* and opening the file themselves. This way, I can pass a [`StringIO.StringIO`](http://docs.python.org/library/stringio.html#StringIO.StringIO) (or more usually a [`cStringIO.StringIO`](http://doc...
Freeze in Python?
3,942,825
7
2010-10-15T13:49:26Z
3,942,838
11
2010-10-15T13:50:59Z
[ "python", "ruby", "list", "freeze" ]
I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I just came across a Ruby feature that I don't know how to replicate in Python. It's Ruby's `freeze` method. ``` irb(main):001:0> a = [1,2,3] => [1, 2, 3] irb(main):002:0> a[1] = 'chicken' =>...
``` >>> a = [1,2,3] >>> a[1] = 'chicken' >>> a [1, 'chicken', 3] >>> a = tuple(a) >>> a[1] = 'tuna' Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> a[1] = 'tuna' TypeError: 'tuple' object does not support item assignment ``` Also, cf. `set` vs. `frozenset`, `bytearray` vs. `bytes`. Nu...
Freeze in Python?
3,942,825
7
2010-10-15T13:49:26Z
3,943,320
9
2010-10-15T14:45:58Z
[ "python", "ruby", "list", "freeze" ]
I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I just came across a Ruby feature that I don't know how to replicate in Python. It's Ruby's `freeze` method. ``` irb(main):001:0> a = [1,2,3] => [1, 2, 3] irb(main):002:0> a[1] = 'chicken' =>...
You could always subclass `list` and add the "frozen" flag which would block `__setitem__` doing anything: ``` class freezablelist(list): def __init__(self,*args,**kwargs): list.__init__(self, *args) self.frozen = kwargs.get('frozen', False) def __setitem__(self, i, y): if self.frozen:...
UnicodeEncodeError: 'latin-1' codec can't encode character
3,942,888
34
2010-10-15T13:57:07Z
3,943,061
13
2010-10-15T14:14:23Z
[ "python", "mysql", "unicode", "pylons" ]
What could be causing this error when I try to insert a foreign character into the database? ``` >>UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256) ``` And how do I resolve it? Thanks!
I hope your database is at least UTF-8. Then you will need to run `yourstring.encode('utf-8')` before you try putting it into the database.
UnicodeEncodeError: 'latin-1' codec can't encode character
3,942,888
34
2010-10-15T13:57:07Z
3,943,139
31
2010-10-15T14:22:20Z
[ "python", "mysql", "unicode", "pylons" ]
What could be causing this error when I try to insert a foreign character into the database? ``` >>UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256) ``` And how do I resolve it? Thanks!
Character U+201C Left Double Quotation Mark is not present in the Latin-1 (ISO-8859-1) encoding. It *is* present in code page 1252 (Western European). This is a Windows-specific encoding that is based on ISO-8859-1 but which puts extra characters into the range 0x80-0x9F. Code page 1252 is often confused with ISO-8859...
UnicodeEncodeError: 'latin-1' codec can't encode character
3,942,888
34
2010-10-15T13:57:07Z
12,064,483
51
2012-08-21T23:28:39Z
[ "python", "mysql", "unicode", "pylons" ]
What could be causing this error when I try to insert a foreign character into the database? ``` >>UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256) ``` And how do I resolve it? Thanks!
I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here: [Using UTF8 with Python MySQLdb](http://www.dasprids.de/blog/2007/12/17/python-mysqldb-and-utf-8) Edit: Quote from ...
Reading and interpreting data from a binary file in Python
3,943,149
11
2010-10-15T14:23:49Z
3,943,272
25
2010-10-15T14:40:07Z
[ "python", "binary", "bitwise-operators" ]
i want to read a file byte by byte and check if the last bit of each byte is set: ``` #!/usr/bin/python def main(): fh = open('/tmp/test.txt', 'rb') try: byte = fh.read(1) while byte != "": if (int(byte,16) & 0x01) is 0x01: print 1 else: ...
Try using the [`bytearray`](http://docs.python.org/py3k/library/functions.html#bytearray) type (Python 2.6 and later), it's much better suited to dealing with byte data. Your `try` block would be just: ``` ba = bytearray(fh.read()) for byte in ba: print byte & 1 ``` or to create a list of results: ``` low_bit_li...
Python unittests almost never check types
3,943,808
3
2010-10-15T15:43:14Z
3,943,830
15
2010-10-15T15:46:26Z
[ "java", "python", "unit-testing" ]
I was going through a few tests written in Java using JUnit and I could'nt help noticing the emphasis which is laid on checking the "type" of objects. This is something I have never seen in Python test-suites. Java being statically-typed and Python being dynamically-typed, should'nt the reverse be the case?
In dynamically-typed languages, developers often follow the [duck typing principle](http://en.wikipedia.org/wiki/Duck_typing) -- "if it looks like a duck and walks like a duck, it is a duck". As long as the object does what all the tests require, does it really matter what kind of object it is? Duck typing says no.
Psycopg2 using wildcard causes TypeError
3,944,276
4
2010-10-15T16:39:59Z
3,944,404
10
2010-10-15T16:58:47Z
[ "python", "psycopg2" ]
Currently I am attempting to search a database to grab certain events. My query is as such ``` SELECT * FROM events WHERE summary ILIKE E'%test%' AND start_time > '2010-10-01' ``` Simply put I need the query to look through a database of calendar events and return anything with a summary with 'test' in it and after t...
Not sure if this is the full root of your problem, but I think you need to escape your wildcards or the parameterization logic will get confused. ``` SELECT * FROM events WHERE summary ILIKE E'%%test%%' AND start_time > %(begin)s ``` I think %% is the correct escaping, but it could be \%
Casting an int to a string in Python
3,944,876
25
2010-10-15T18:08:49Z
3,944,892
18
2010-10-15T18:10:39Z
[ "python", "string", "integer", "concatenation" ]
I want to be able to generate a number of text files with the names fileX.txt where X is some integer: ``` for i in range(key): filename = "ME" + i + ".txt" //Error here! Can't concat a string and int filenum = filename filenum = open(filename , 'w') ``` Does anyone else know how to do the filename = "ME"...
For Python versions prior to 2.6, use the [string formatting operator `%`](http://docs.python.org/library/stdtypes.html#string-formatting-operations): ``` filename = "ME%d.txt" % i ``` For 2.6 and later, use the [`str.format()`](http://docs.python.org/library/string.html#formatstrings) method: ``` filename = "ME{0}....