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 |
|---|---|---|---|---|---|---|---|---|---|
How can I get the current week using Python? | 2,003,841 | 10 | 2010-01-05T02:42:57Z | 2,004,013 | 16 | 2010-01-05T03:32:44Z | [
"python",
"datetime",
"calendar"
] | Using Python...
How can I get a list of the days in a specific week?
Something like...
```
{
'1' : ['01/03/2010','01/04/2010','01/05/2010','01/06/2010','01/07/2010','01/08/2010','01/09/2010'],
'2' : ['01/10/2010','01/11/2010','01/12/2010','01/13/2010','01/14/2010','01/15/2010','01/16/2010']
}
```
The key of the ... | Beware! If you want to define YOUR OWN week numbers, you could use the generator expression provided [in your first question](http://stackoverflow.com/questions/2003870/how-can-i-select-all-of-the-sundays-for-a-year-using-python) which, by the way, got an awesome answer). If you want to follow the ISO convention for we... |
where is the '__path__' comes from | 2,003,859 | 2 | 2010-01-05T02:47:09Z | 2,003,940 | 8 | 2010-01-05T03:10:59Z | [
"python"
] | i can't find who defined the `'__path__'`,why `'__path__'` can be use.
```
import os
import sys
import warnings
import ConfigParser # ConfigParser is not a virtualenv module, so we can use it to find the stdlib
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(ConfigParser.__file__), 'distutil... | You really need to read some Python documentation and learn the basics of the language.
I checked, and you seem to speak Chinese. Here are Python documentation resources in Chinese:
<http://www6.uniovi.es/python/doc/NonEnglish.html#chinese>
Now, to answer your question. I wasn't sure what the answer was, so I used G... |
How can I select all of the Sundays for a year using Python? | 2,003,870 | 11 | 2010-01-05T02:48:54Z | 2,003,906 | 26 | 2010-01-05T03:02:11Z | [
"python",
"datetime",
"calendar"
] | Using Python...
How can I select all of the Sundays (or any day for that matter) in a year?
```
[ '01/03/2010','01/10/2010','01/17/2010','01/24/2010', ...]
```
These dates represent the Sundays for 2010. This could also apply to any day of the week I suppose. | You can use `date` from the [`datetime`](http://docs.python.org/library/datetime.html) module to find the first Sunday in a year and then keep adding seven days, generating new Sundays:
```
from datetime import date, timedelta
def allsundays(year):
d = date(year, 1, 1) # January 1st
d += time... |
UnicodeEncodeError on joining file name | 2,004,137 | 4 | 2010-01-05T04:20:05Z | 2,004,179 | 7 | 2010-01-05T04:34:15Z | [
"python",
"unicode",
"filenames"
] | It throws out "UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 2: ordinal not in range(128)" when executing following code:
```
filename = 'Spywaj.ttf'
print repr(filename)
>> 'Sp\xc2\x88ywaj.ttf'
filepath = os.path.join('/dirname', filename)
```
But the file is valid and existed on disk. Filenam... | In both Latin-1 (ISO-8859-1) and Windows-1252, 0xc2 would a capital A with a circumflex accent... doesn't seem to be anywhere in the code you show! Can you please add a
```
print repr(filename)
```
before the `os.path.join` call (and also put the `'/dirname'` in a variable and print its repr for completeness?). I'm t... |
Get original filename google app engine | 2,004,476 | 4 | 2010-01-05T06:11:39Z | 2,006,424 | 8 | 2010-01-05T13:57:18Z | [
"python",
"google-app-engine",
"upload"
] | When receiving a file upload on google app engine, [the example](http://code.google.com/appengine/docs/python/images/usingimages.html) assumes you're receiving a .png. However you only konw what the type of the image is by the extension on the filename.
How do you get the original filename uploaded on GAE? | The filename of the file that is being uploaded can be determined by looking at the *filename* property of the variable that holds the file. For example, let's say that your form has a field named *content*:
```
<input type="file" name="content" />
```
Inside your Handler, you could find the name of the file with:
`... |
Force CherryPy Child Threads | 2,004,514 | 9 | 2010-01-05T06:24:29Z | 2,007,568 | 11 | 2010-01-05T16:48:50Z | [
"python",
"multithreading",
"cherrypy"
] | Well, I want cherrypy to kill all child threads on auto-reload instead of "Waiting for child threads to terminate" because my program has threads of its own and I don't know how to get past this. CherryPy keeps hanging on that one line and I don't know what to do to get the 'child threads' to terminate...
`
```
[05/J... | You need to write code that stops your threads, and register it as a listener for the 'stop' event:
```
from cherrypy.process import plugins
class MyFeature(plugins.SimplePlugin):
"""A feature that does something."""
def start(self):
self.bus.log("Starting my feature")
self.threads = mylib.st... |
If I have this string in Python, how do I decode it? | 2,004,574 | 5 | 2010-01-05T06:41:04Z | 2,004,587 | 14 | 2010-01-05T06:47:17Z | [
"python",
"encoding"
] | s = 'Tara%2520Stiles%2520Living'
How do I turn it into:
```
Tara Stiles Living
``` | You need to use [`urllib.unquote`](http://docs.python.org/library/urllib.html#urllib.unquote), but it appears you need to use it *twice*:
```
>>> import urllib
>>> s = 'Tara%2520Stiles%2520Living'
>>> urllib.unquote(urllib.unquote(s))
'Tara Stiles Living'
```
After unquoting once, your "%2520" turns into "%20", which... |
Why is Django's Meta an old-style class? | 2,005,150 | 17 | 2010-01-05T09:45:17Z | 2,007,514 | 14 | 2010-01-05T16:40:36Z | [
"python",
"django",
"class"
] | I noticed that in Django models, there is a `class Meta` which makes some additional definitions about the model.
My question is, why is this done as an old-style class? (i.e. not subclassing `object`?) Is there a reason for this or is this just a custom? Could I do it as a new-style class in my projects? | I believe that there is no real reason (including history, since new-style classes exist since Python 2.2) and that not only can you choose to use a new-style class instead, but that it would probably be a good idea for you to do so (for all the usual reasons). |
Why is Django's Meta an old-style class? | 2,005,150 | 17 | 2010-01-05T09:45:17Z | 2,007,686 | 7 | 2010-01-05T17:04:42Z | [
"python",
"django",
"class"
] | I noticed that in Django models, there is a `class Meta` which makes some additional definitions about the model.
My question is, why is this done as an old-style class? (i.e. not subclassing `object`?) Is there a reason for this or is this just a custom? Could I do it as a new-style class in my projects? | Since class Meta is never anything but a simple namespace container, there is zero advantage to subclassing object; just eight extra characters to type. Won't hurt anything to do so if you feel like it, though. |
Asynchronous data through Bloomberg's new data API (COM v3) with Python? | 2,005,234 | 8 | 2010-01-05T10:03:25Z | 2,054,374 | 19 | 2010-01-13T04:20:22Z | [
"python",
"asynchronous",
"win32com",
"bloomberg"
] | Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version.
Does anyone know the corresponding code for the new version?
```
from win32com.client import DispatchWithEvents
from pyt... | I finally figured it out. I did a fair bit of combrowse.py detective work, and I compared with the JAVA, C, C++, and .NET examples in the BBG API download. Interestingly enough the Bloomberg Helpdesk people knew pretty much null when it came to these things, or perhaps I was just talking to the wrong person.
Here is m... |
Handle Arbitrary Exception, Print Default Exception Message | 2,005,680 | 16 | 2010-01-05T11:29:03Z | 2,005,712 | 15 | 2010-01-05T11:33:47Z | [
"python",
"exception-handling"
] | I have a program, a part of which executes a loop. During the execution of this loop, there are exceptions. Obviously, I would like my program to run without errors, but for the sake of progress, I would like the program to execute over the entire input and not stop when an exception is thrown. The easiest way to do th... | ```
try:
#stuff
except Exception as e:
print e
```
The `traceback` module provides various functions for extracting more information from the exception object (`e`, above).
Source [Errors and Exceptions](https://docs.python.org/2/tutorial/errors.html) |
Handle Arbitrary Exception, Print Default Exception Message | 2,005,680 | 16 | 2010-01-05T11:29:03Z | 2,005,909 | 12 | 2010-01-05T12:18:36Z | [
"python",
"exception-handling"
] | I have a program, a part of which executes a loop. During the execution of this loop, there are exceptions. Obviously, I would like my program to run without errors, but for the sake of progress, I would like the program to execute over the entire input and not stop when an exception is thrown. The easiest way to do th... | Consider using the Python logging module, this is will give you a lot of the functionality to log problems for later inspection. Below is a simple example of using the logging module to to log exceptions:
```
import logging
LOG_FILE = '/tmp/exceptions.log'
logging.basicConfig(filename=LOG_FILE,level=logging.ERROR)
wh... |
What are Python metaclasses useful for? | 2,005,878 | 27 | 2010-01-05T12:12:19Z | 2,005,894 | 10 | 2010-01-05T12:15:51Z | [
"python",
"class",
"decorator",
"metaclass"
] | What can be done with metaclasses that can't be in any other way?
Alex Martelli told that there are tasks that can't be achieved without metaclasses here <http://stackoverflow.com/questions/1779372/python-metaclasses-vs-class-decorators>
I'd like to know which are? | Add extra flexibility to your programming:
But according to this [Metaclass programming in Python](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) you might not need them ( yet )
> *Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (t... |
What are Python metaclasses useful for? | 2,005,878 | 27 | 2010-01-05T12:12:19Z | 2,006,875 | 7 | 2010-01-05T15:13:05Z | [
"python",
"class",
"decorator",
"metaclass"
] | What can be done with metaclasses that can't be in any other way?
Alex Martelli told that there are tasks that can't be achieved without metaclasses here <http://stackoverflow.com/questions/1779372/python-metaclasses-vs-class-decorators>
I'd like to know which are? | I use metaclasses with some frequency, and they're an extremely powerful tool to have in the toolbox. Sometimes your solution to a problem can be more elegant, less code, with them than without.
The thing I find myself using metaclasses for most often, is post-processing the class attributes during class creation. For... |
What are Python metaclasses useful for? | 2,005,878 | 27 | 2010-01-05T12:12:19Z | 2,007,641 | 17 | 2010-01-05T16:58:28Z | [
"python",
"class",
"decorator",
"metaclass"
] | What can be done with metaclasses that can't be in any other way?
Alex Martelli told that there are tasks that can't be achieved without metaclasses here <http://stackoverflow.com/questions/1779372/python-metaclasses-vs-class-decorators>
I'd like to know which are? | Metaclasses are indispensable if you want to have class objects (as opposed to **instances** of class objects) equipped with "special customized behavior", since an object's behavior depends on special methods on the **type** of the object, and a class object's type is, exactly a synonym for, the metaclass.
For exampl... |
How do nested functions work in Python? | 2,005,956 | 34 | 2010-01-05T12:29:20Z | 2,005,992 | 33 | 2010-01-05T12:37:17Z | [
"python",
"function",
"nested",
"closures",
"nested-function"
] | ```
def maker(n):
def action(x):
return x ** n
return action
f = maker(2)
print(f)
print(f(3))
print(f(4))
g = maker(3)
print(g(3))
print(f(3)) # still remembers 2
```
Why does the nested function remember the first value `2` even though `maker()` has returned and exited by the time `action()` is ca... | You are basically creating a [closure](http://en.wikipedia.org/wiki/Closure%5F%28computer%5Fscience%29).
> In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables.
Related reading: <http://st... |
How do nested functions work in Python? | 2,005,956 | 34 | 2010-01-05T12:29:20Z | 2,005,994 | 13 | 2010-01-05T12:37:54Z | [
"python",
"function",
"nested",
"closures",
"nested-function"
] | ```
def maker(n):
def action(x):
return x ** n
return action
f = maker(2)
print(f)
print(f(3))
print(f(4))
g = maker(3)
print(g(3))
print(f(3)) # still remembers 2
```
Why does the nested function remember the first value `2` even though `maker()` has returned and exited by the time `action()` is ca... | You are defining TWO functions. When you call
```
f = maker(2)
```
you're defining a function that returns twice the number, so
```
f(2) --> 4
f(3) --> 6
```
Then, you define ANOTHER DIFFERENT FUNCTION
```
g = maker(3)
```
that return three times the number
```
g(3) ---> 9
```
But they are TWO different functio... |
How do nested functions work in Python? | 2,005,956 | 34 | 2010-01-05T12:29:20Z | 2,006,009 | 9 | 2010-01-05T12:39:41Z | [
"python",
"function",
"nested",
"closures",
"nested-function"
] | ```
def maker(n):
def action(x):
return x ** n
return action
f = maker(2)
print(f)
print(f(3))
print(f(4))
g = maker(3)
print(g(3))
print(f(3)) # still remembers 2
```
Why does the nested function remember the first value `2` even though `maker()` has returned and exited by the time `action()` is ca... | That is what's called "[closure](http://en.wikipedia.org/wiki/Closure_%28computer_science%29)". Simply put, for most if not all programming languages that treat functions as [first-class object](http://en.wikipedia.org/wiki/First_class_object), any variables that are used within a function object are enclosed (i.e. rem... |
How do nested functions work in Python? | 2,005,956 | 34 | 2010-01-05T12:29:20Z | 2,006,017 | 19 | 2010-01-05T12:41:12Z | [
"python",
"function",
"nested",
"closures",
"nested-function"
] | ```
def maker(n):
def action(x):
return x ** n
return action
f = maker(2)
print(f)
print(f(3))
print(f(4))
g = maker(3)
print(g(3))
print(f(3)) # still remembers 2
```
Why does the nested function remember the first value `2` even though `maker()` has returned and exited by the time `action()` is ca... | You can see it as all the variables originating in the parent function being replaced by their actual value inside the child function. This way, there is no need to keep track of the scope of the parent function to make the child function run correctly.
See it as "dynamically creating a function".
```
def maker(n):
... |
python equivalent of '#define func() ' or how to comment out a function call in python | 2,006,190 | 8 | 2010-01-05T13:12:20Z | 2,006,640 | 15 | 2010-01-05T14:33:39Z | [
"python",
"comments",
"preprocessor",
"commenting"
] | my python code is interlaced with lots of function calls used for (debugging|profiling|tracing etc.)
for example:
```
import logging
logging.root.setLevel(logging.DEBUG)
logging.debug('hello')
j = 0
for i in range(10):
j += i
logging.debug('i %d j %d' % (i,j))
print(j)
logging.debug('bye')
```
i want to #def... | Python does not have a preprocessor, although you could run your python source through an external preprocessor to get the same effect - e.g. `sed "/logging.debug/d"` will strip out all the debug logging commands. This is not very elegant though - you will end up needing some sort of build system to run all your module... |
making undo in python | 2,006,404 | 3 | 2010-01-05T13:54:40Z | 2,006,426 | 12 | 2010-01-05T13:58:23Z | [
"python",
"image",
"wxpython",
"python-imaging-library",
"undo"
] | first of all .. sorry if my english was bad. its my 3rd language
im working on a paint software that draw over images and save them again ( for commenting propose )
i use pile and wxpython.
but im still having problems with some features ..
what is the ideal way to make the undo option ?
another question .... | The canonical strategy is to use the [**Command pattern**](http://en.wikipedia.org/wiki/Command_pattern). You'll represent the things you can do as Command objects, and each object is placed on a stack. The state of the application is then defined by an initial state plus everything that the stack has. Thus, the "undo"... |
making undo in python | 2,006,404 | 3 | 2010-01-05T13:54:40Z | 2,007,604 | 7 | 2010-01-05T16:53:06Z | [
"python",
"image",
"wxpython",
"python-imaging-library",
"undo"
] | first of all .. sorry if my english was bad. its my 3rd language
im working on a paint software that draw over images and save them again ( for commenting propose )
i use pile and wxpython.
but im still having problems with some features ..
what is the ideal way to make the undo option ?
another question .... | Also, keep in mind that Python's functions are first-class objects, which can make implementing the Command pattern very smooth:
```
actions = []
def do_action1(arg1, arg2):
# .. do the action ..
# remember we did the action:
actions.append(do_action1, (arg1, arg2))
def do_action2(arg1, arg2):
# .. ... |
How to share data between python processes without writing to disk | 2,006,624 | 13 | 2010-01-05T14:31:04Z | 2,006,721 | 8 | 2010-01-05T14:48:02Z | [
"python",
"ipc",
"mmap",
"json-rpc",
"pc104"
] | Helllo,
I would like to share small amounts of data (< 1K) between python and processes. The data is physical pc/104 IO data which changes rapidly and often (24x7x365). There will be a single "server" writing the data and multiple clients reading portions of it.
The system this will run on uses flash memory (CF card) r... | An alternative to writing the data to file in the server process might be to directly write to the client processes:
Use UNIX domain sockets (or TCP/IP sockets if the clients run on different machines) to connect each client to the server, and have the server write into those sockets. Depending on your particular proc... |
Email multiple contacts in Python | 2,006,648 | 10 | 2010-01-05T14:34:45Z | 2,006,665 | 7 | 2010-01-05T14:38:12Z | [
"python"
] | I am trying to send an email to multiple addresses. The code below shows what I'm attempting to achieve. When I add two addresses the email does not send to the second address. The code is:
```
me = '[email protected]'
you = '[email protected], [email protected]'
msg['Subject'] = "Some Subject"
msg['From'] = me
msg['To'] = you
#... | You want this:
```
from email.utils import COMMASPACE
...
you = ["[email protected]", "[email protected]"]
...
msg['To'] = COMMASPACE.join(you)
...
s.sendmail(me, you, msg.as_string())
``` |
Email multiple contacts in Python | 2,006,648 | 10 | 2010-01-05T14:34:45Z | 2,006,667 | 11 | 2010-01-05T14:38:25Z | [
"python"
] | I am trying to send an email to multiple addresses. The code below shows what I'm attempting to achieve. When I add two addresses the email does not send to the second address. The code is:
```
me = '[email protected]'
you = '[email protected], [email protected]'
msg['Subject'] = "Some Subject"
msg['From'] = me
msg['To'] = you
#... | Try
```
s.sendmail(me, you.split(","), msg.as_string())
```
If you do `you = ['[email protected]', '[email protected]']`
Try
```
msg['To'] = ",".join(you)
...
s.sendmail(me, you, msg.as_string())
``` |
Learn Go Or Improve My Python/Ruby Knowledge | 2,009,194 | 5 | 2010-01-05T21:24:56Z | 2,009,206 | 9 | 2010-01-05T21:26:55Z | [
"python",
"ruby",
"go"
] | I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: **Learn Go or improve my Python or Ruby knowledge?**
Years developing with Python: 1
Years developing with Ruby: 0.3 | In reality, you should do both; if it's what you want. For me though, out of the two, I'd only look at Python. I have no real interest in languages that are so new. |
Learn Go Or Improve My Python/Ruby Knowledge | 2,009,194 | 5 | 2010-01-05T21:24:56Z | 2,009,485 | 17 | 2010-01-05T22:10:55Z | [
"python",
"ruby",
"go"
] | I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: **Learn Go or improve my Python or Ruby knowledge?**
Years developing with Python: 1
Years developing with Ruby: 0.3 | If you're just looking to have fun and expand your horizons, then I'd learn Go, since you already know some Python.
If you're looking to improve as a developer, I'd personally recommend working on an actual project (using Python, as it's the language you have the most experience with):
* This will take your (Python a... |
Learn Go Or Improve My Python/Ruby Knowledge | 2,009,194 | 5 | 2010-01-05T21:24:56Z | 2,009,489 | 8 | 2010-01-05T22:11:41Z | [
"python",
"ruby",
"go"
] | I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: **Learn Go or improve my Python or Ruby knowledge?**
Years developing with Python: 1
Years developing with Ruby: 0.3 | It depends on what your goals and your needs are.
If you're looking to develop your skills for a job, then go with Python or Ruby. You're unlikely to see Go show up in the workplace for quite some time (if ever) unless you're working at Google. (Even then it's questionable.)
If you want to have fun, do what you want.... |
How to Speed Up Python's urllib2 when doing multiple requests | 2,009,243 | 18 | 2010-01-05T21:32:14Z | 6,272,067 | 24 | 2011-06-07T21:55:40Z | [
"python",
"http",
"urllib2"
] | I am making several http requests to a particular host using python's urllib2 library. Each time a request is made a new tcp and http connection is created which takes a noticeable amount of time. Is there any way to keep the tcp/http connection alive using urllib2? | If you switch to [httplib](https://docs.python.org/2/library/httplib.html), you will have finer control over the underlying connection.
For example:
```
import httplib
conn = httplib.HTTPConnection(url)
conn.request('GET', '/foo')
r1 = conn.getresponse()
r1.read()
conn.request('GET', '/bar')
r2 = conn.getresponse(... |
Python multiprocessing: Permission denied | 2,009,278 | 41 | 2010-01-05T21:37:06Z | 2,009,505 | 56 | 2010-01-05T22:15:45Z | [
"python",
"linux"
] | I'm getting an error when trying to execute python program that uses multiprocessing package:
```
File "/usr/local/lib/python2.6/multiprocessing/__init__.py", line 178, in RLock
return RLock()
File "/usr/local/lib/python2.6/multiprocessing/synchronize.py", line 142, in __init__
SemLock.__init__(self, RECUR... | For POSIX semaphores to work, the users need r/w access to shared memory (`/dev/shm`).
Check the permissions to `/dev/shm`. On my laptop (Ubuntu) it looks like this:
```
$ ls -ld /dev/shm
drwxrwxrwt 2 root root 40 2010-01-05 20:34 shm
```
To permanently set the correct permissions (even after a reboot), add... |
Interpolate Question | 2,009,379 | 5 | 2010-01-05T21:54:11Z | 2,085,669 | 7 | 2010-01-18T11:36:14Z | [
"python",
"scipy"
] | ```
import re
from decimal import *
import numpy
from scipy.signal import cspline1d, cspline1d_eval
import scipy.interpolate
import scipy
import math
import numpy
from scipy import interpolate
Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60200199999999993, 0.640... | I believe it's due to the X1 values not being ordered from smallest to largest plus also you have one duplicate x point, i.e, you need to sort the values for X1 and Y1 before you can use the splrep and remove duplicates.
splrep from the docs seem to be low level access to FITPACK libraries which expects a sorted, non-... |
Read/Write Python Closures | 2,009,402 | 24 | 2010-01-05T21:57:06Z | 2,009,424 | 15 | 2010-01-05T22:00:59Z | [
"python",
"language-design",
"closures",
"readonly"
] | Closures are an incredibly useful language feature. They let us do clever things that would otherwise take a lot of code, and often enable us to write code that is more elegant and more clear. In Python 2.x, closures variable names cannot be rebound; that is, a function defined inside another lexical scope cannot do so... | `nonlocal` in 3.x should remedy this. |
Read/Write Python Closures | 2,009,402 | 24 | 2010-01-05T21:57:06Z | 2,009,474 | 19 | 2010-01-05T22:09:13Z | [
"python",
"language-design",
"closures",
"readonly"
] | Closures are an incredibly useful language feature. They let us do clever things that would otherwise take a lot of code, and often enable us to write code that is more elegant and more clear. In Python 2.x, closures variable names cannot be rebound; that is, a function defined inside another lexical scope cannot do so... | You could do this and it would work more or less the same way:
```
class counter(object):
def __init__(self, count=0):
self.count = count
def __call__(self):
self.count += 1
return self.count
```
Or, a bit of a hack:
```
def counter():
count = [0]
def incr(n):
n[0] += ... |
Read/Write Python Closures | 2,009,402 | 24 | 2010-01-05T21:57:06Z | 2,009,545 | 13 | 2010-01-05T22:19:49Z | [
"python",
"language-design",
"closures",
"readonly"
] | Closures are an incredibly useful language feature. They let us do clever things that would otherwise take a lot of code, and often enable us to write code that is more elegant and more clear. In Python 2.x, closures variable names cannot be rebound; that is, a function defined inside another lexical scope cannot do so... | I would use a generator:
```
>>> def counter():
count = 0
while True:
count += 1
yield(count)
>>> c = counter()
>>> c.next()
1
>>> c.next()
2
>>> c.next()
3
```
**EDIT**: I believe the ultimate answer to your question is [PEP-3104](http://www.python.org/dev/peps/pep-3104/):
> In most languag... |
Read/Write Python Closures | 2,009,402 | 24 | 2010-01-05T21:57:06Z | 2,009,645 | 22 | 2010-01-05T22:34:44Z | [
"python",
"language-design",
"closures",
"readonly"
] | Closures are an incredibly useful language feature. They let us do clever things that would otherwise take a lot of code, and often enable us to write code that is more elegant and more clear. In Python 2.x, closures variable names cannot be rebound; that is, a function defined inside another lexical scope cannot do so... | To expand on Ignacio's answer:
```
def counter():
count = 0
def c():
nonlocal count
count += 1
return count
return c
x = counter()
print([x(),x(),x()])
```
gives [1,2,3] in Python 3; invocations of `counter()` give independent counters. Other solutions - especially using `itertool... |
Please help me find the official name of this programming approach | 2,010,132 | 7 | 2010-01-06T00:16:18Z | 2,010,507 | 7 | 2010-01-06T01:55:01Z | [
"python",
"algorithm",
"language-agnostic",
"set",
"bit-fields"
] | I [surely re] invented this [wheel] when I wanted to compute the union and the intersection and diff of two sets (stored as lists) at the same time. Initial code (not the tightest):
```
dct = {}
for a in lst1:
dct[a] = 1
for b in lst2:
if b in dct:
dct[b] -= 1
else:
dct[b] = -1
union = [k for k in dct]
... | Using an N bit integer to represent N booleans is a special case of the data structure known as a **perfect hash table**. Notice you're explicitly using dicts (which are general hash tables) in the idea that prompted you to think about bitsets. It's a hash table because you use hashes to find a value, and it's perfect ... |
Speeding up the python "import" loader | 2,010,255 | 18 | 2010-01-06T00:47:29Z | 2,010,354 | 9 | 2010-01-06T01:13:01Z | [
"python"
] | I'm getting seriously frustrated at how slow python startup is. Just importing more or less basic modules takes a second, since python runs down the sys.path looking for matching files (and generating 4 `stat()` calls - ["foo", "foo.py", "foo.pyc", "foo.so"] - for each check). For a complicated project environment, wit... | zipping up as many `pyc` files as feasible (with proper directory structure for packages), and putting that zipfile as the very first entry in sys.path (on the best available local disk, ideally) can speed up startup times a lot. |
where is the 'itertools' file | 2,010,413 | 7 | 2010-01-06T01:29:14Z | 2,010,443 | 16 | 2010-01-06T01:37:50Z | [
"python"
] | ```
import itertools
print itertools#ok
```
the code is ok
but i can't find the itertools file.
who can tell me where is the 'itertools file'
---
my code is run python2.5
```
import itertools
print itertools.__file__
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <modul... | ```
>>> import itertools
>>> itertools.__file__
'/usr/lib64/python2.6/lib-dynload/itertools.so'
```
The fact that the filename ends with `.so` means it's an extension module written in C (rather than a normal Python module). If you want to take a look at the source code, download the Python source and look into `Modul... |
SQLAlchemy filter query by related object | 2,010,454 | 6 | 2010-01-06T01:41:10Z | 2,015,755 | 9 | 2010-01-06T19:55:54Z | [
"python",
"sqlalchemy"
] | Using [SQLAlchemy](http://en.wikipedia.org/wiki/SQLAlchemy), I have a one to many relation with two tables - users and scores. I am trying to query the top 10 users sorted by their aggregate score over the past X amount of days.
```
users:
id
user_name
score
scores:
user
score_amount
create... | The single-joined-row way, with a `group_by` added in for all user columns although MySQL will let you group on just the "id" column if you choose:
```
sess.query(User, func.sum(Score.amount).label('score_increase')).\
join(User.scores).\
filter(Score.created_at > someday).\
... |
How do you get all the rows from a particular table using BeautifulSoup? | 2,010,481 | 9 | 2010-01-06T01:47:40Z | 2,010,535 | 19 | 2010-01-06T02:03:25Z | [
"python",
"beautifulsoup"
] | I am learning Python and BeautifulSoup to scrape data from the web, and read a HTML table. I can read it into Open Office and it says that it is Table #11.
It seems like BeautifulSoup is the preferred choice, but can anyone tell me how to grab a particular table and all the rows? I have looked at the module documentat... | This should be pretty straight forward if you have a chunk of HTML to parse with BeautifulSoup. The general idea is to navigate to your table using the `findChildren` method, then you can get the text value inside the cell with the `string` property.
```
>>> from BeautifulSoup import BeautifulSoup
>>>
>>> html = """
... |
What does "mro()" do in Python? | 2,010,692 | 77 | 2010-01-06T03:04:16Z | 2,010,706 | 60 | 2010-01-06T03:08:58Z | [
"python"
] | In `django.utils.functional.py`:
```
for t in type(res).mro():#<-----this
if t in self.__dispatch:
return self.__dispatch[t][funcname](res, *args, **kw)
```
I don't understand mro.
What does "mro()" do?
What does mro mean? | `mro()` stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods. |
What does "mro()" do in Python? | 2,010,692 | 77 | 2010-01-06T03:04:16Z | 2,010,732 | 138 | 2010-01-06T03:17:19Z | [
"python"
] | In `django.utils.functional.py`:
```
for t in type(res).mro():#<-----this
if t in self.__dispatch:
return self.__dispatch[t][funcname](res, *args, **kw)
```
I don't understand mro.
What does "mro()" do?
What does mro mean? | Follow along...:
```
>>> class A(object): pass
...
>>> A.__mro__
(<class '__main__.A'>, <type 'object'>)
>>> class B(A): pass
...
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
>>> class C(A): pass
...
>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
>>>
```
... |
how to check the character count of a file in python | 2,011,048 | 5 | 2010-01-06T05:00:43Z | 2,011,055 | 8 | 2010-01-06T05:03:19Z | [
"python",
"size",
"character"
] | I have a python code which reads many files.
but some files are extremely large due to which i have errors coming in other codes.
i want a way in which i can check for the character count of the files so that i avoid reading those extremely large files.
Thanks. | ```
os.stat(filepath).st_size
```
Assuming by âcharactersâ you mean bytes. ETA:
> i need total character count just like what the command 'wc filename' gives me unix
In which mode? `wc` on it own will give you a line, word and byte count (same as `stat`), not Unicode characters.
There *is* a switch `-m` which w... |
how to check the character count of a file in python | 2,011,048 | 5 | 2010-01-06T05:00:43Z | 2,011,063 | 7 | 2010-01-06T05:05:18Z | [
"python",
"size",
"character"
] | I have a python code which reads many files.
but some files are extremely large due to which i have errors coming in other codes.
i want a way in which i can check for the character count of the files so that i avoid reading those extremely large files.
Thanks. | If you want the unicode **character** count for a text file given a specific encoding, you will have to read in the entire file to do that.
However, if you want the **byte** count for a given file, you want `os.path.getsize()`, which should only need to do a `stat` on the file as long as your OS has `stat()` or an equ... |
any() function in Python with a callback | 2,012,611 | 37 | 2010-01-06T11:39:35Z | 2,012,631 | 77 | 2010-01-06T11:43:32Z | [
"python",
"functional-programming",
"callback",
"any"
] | The Python standard library defines an [`any()`](http://docs.python.org/library/functions.html#any) function that
> Return True if any element of the iterable is true. If the iterable is empty, return False.
It checks only if the elements evaluate to `True`. What I want it to be able so specify a callback to tell if ... | How about:
```
>>> any(isinstance(e, int) and e > 0 for e in [1,2,'joe'])
True
```
It also works with `all()` of course:
```
>>> all(isinstance(e, int) and e > 0 for e in [1,2,'joe'])
False
``` |
any() function in Python with a callback | 2,012,611 | 37 | 2010-01-06T11:39:35Z | 2,012,640 | 7 | 2010-01-06T11:45:16Z | [
"python",
"functional-programming",
"callback",
"any"
] | The Python standard library defines an [`any()`](http://docs.python.org/library/functions.html#any) function that
> Return True if any element of the iterable is true. If the iterable is empty, return False.
It checks only if the elements evaluate to `True`. What I want it to be able so specify a callback to tell if ... | Yo should use a "generator expression" - that is, a language construct that can consume iterators and apply filter and expressions on then on a single line:
For example `(i ** 2 for i in xrange(10))` is a generator for the square of the first 10 natural numbers (0 to 9)
They also allow an "if" clause to filter the it... |
any() function in Python with a callback | 2,012,611 | 37 | 2010-01-06T11:39:35Z | 2,012,710 | 17 | 2010-01-06T11:54:44Z | [
"python",
"functional-programming",
"callback",
"any"
] | The Python standard library defines an [`any()`](http://docs.python.org/library/functions.html#any) function that
> Return True if any element of the iterable is true. If the iterable is empty, return False.
It checks only if the elements evaluate to `True`. What I want it to be able so specify a callback to tell if ... | **any** function returns True when any condition is True.
```
>>> any(isinstance(e, int) and e > 0 for e in [0 ,0, 1])
True # Returns True because 1 is greater than 0.
>>> any(isinstance(e, int) and e > 0 for e in [0 ,0, 0])
False # Returns False because not a single condition is True.
```
Actually,the concept of *... |
Deleting files which start with a name Python | 2,012,670 | 3 | 2010-01-06T11:48:52Z | 2,012,718 | 9 | 2010-01-06T11:56:47Z | [
"python"
] | I have a few files I want to delete, they have the same name at the start but have different version numbers. Does anyone know how to delete files using the start of their name?
```
Eg.
version_1.1
version_1.2
```
Is there a way of delting any file that starts with the name version?
Thanks | ```
import os, glob
for filename in glob.glob("mypath/version*"):
os.remove(filename)
```
Substitute the correct path (or `.` (= current directory)) for `mypath`. And make sure you don't get the path wrong :)
This will raise an Exception if a file is currently in use. |
attribute assignment order in class definition | 2,013,067 | 4 | 2010-01-06T13:09:09Z | 2,014,002 | 7 | 2010-01-06T15:29:50Z | [
"python"
] | Hi my problem is that:
I want to define a class in this way:
```
class List(Base):
hp = Column(int,...)
name = Column(str,...)
```
This class represents a list, I can define/modify/code the `Base` and the `Column` class.
There's a way to know the order in which I defined the attributes hp/names?
For example I... | Internally, attribute definitions are stored in a dictionary, which does not retain the order of the elements. You could probably change the attribute handling in the Base class, or you store the creation order, like this:
```
class Column:
creation_counter = 0
def __init__(self):
self.creation_co... |
Got Django and Buildout working, but what about PIL and Postgres? | 2,013,789 | 5 | 2010-01-06T15:03:04Z | 2,087,050 | 8 | 2010-01-18T15:29:00Z | [
"python",
"postgresql",
"python-imaging-library",
"buildout"
] | I'm on Mac OSX 10.5.8. I have followed Jacob Kaplan-Moss's article on setting up Django with Buildout: <http://jacobian.org/writing/django-apps-with-buildout/>
Finally, I have got this Buildout to work! ...but I'm now needing PIL and Postgres for a complete isolated Django development area. I've tried to modify my bui... | In theory, you should just be able to add `PIL` and `psycopg2` to your `eggs` directive:
```
eggs = myproject
PIL
psycopg2
```
This works on some systems and in some situations.
However, there are two problems that can prevent it from working everywhere, and especially on OSX:
1. `PIL`'s packaging is.... |
Django: How should I store a money value? | 2,013,835 | 53 | 2010-01-06T15:09:00Z | 2,013,860 | 18 | 2010-01-06T15:13:05Z | [
"python",
"django",
"django-models",
"decimal",
"money"
] | I'm running into a paradigm problem here. I don't know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this:
**PayPal requires 2 decimal places**, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across t... | I think you should store it in a decimal format and format it to 00.00 format **only** then sending it to PayPal, like this:
```
pricestr = "%01.2f" % price
```
If you want, you can add a method to your model:
```
def formattedprice(self):
return "%01.2f" % self.price
``` |
Django: How should I store a money value? | 2,013,835 | 53 | 2010-01-06T15:09:00Z | 2,013,866 | 8 | 2010-01-06T15:14:10Z | [
"python",
"django",
"django-models",
"decimal",
"money"
] | I'm running into a paradigm problem here. I don't know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this:
**PayPal requires 2 decimal places**, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across t... | I suggest to avoid mixing representation with storage. Store the data as a decimal value with 2 places.
In the UI layer, display it in a form which is suitable for the user (so maybe omit the ".00").
When you send the data to PayPal, format it as the interface requires. |
Django: How should I store a money value? | 2,013,835 | 53 | 2010-01-06T15:09:00Z | 2,014,635 | 58 | 2010-01-06T16:58:09Z | [
"python",
"django",
"django-models",
"decimal",
"money"
] | I'm running into a paradigm problem here. I don't know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this:
**PayPal requires 2 decimal places**, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across t... | You might want to use the `.quantize()` method. This will round a decimal value to a certain number of places, the argument you provide specifies the number of places:
```
>>> from decimal import Decimal
>>> Decimal("12.234").quantize(Decimal("0.00"))
Decimal("12.23")
```
It can also take an argument to specify what ... |
Django: How should I store a money value? | 2,013,835 | 53 | 2010-01-06T15:09:00Z | 11,611,863 | 9 | 2012-07-23T11:43:48Z | [
"python",
"django",
"django-models",
"decimal",
"money"
] | I'm running into a paradigm problem here. I don't know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this:
**PayPal requires 2 decimal places**, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across t... | Money should be stored in money field, which sadly does not exist. Since money is two dimensional value (amount, currency).
There is **python-money** lib, that has many forks, yet I haven't found working one.
---
Recommendations:
**python-money** probably the best fork <https://bitbucket.org/acoobe/python-money>
*... |
Django: How should I store a money value? | 2,013,835 | 53 | 2010-01-06T15:09:00Z | 16,471,927 | 13 | 2013-05-09T22:06:29Z | [
"python",
"django",
"django-models",
"decimal",
"money"
] | I'm running into a paradigm problem here. I don't know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this:
**PayPal requires 2 decimal places**, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across t... | My late to the party version that adds South migrations.
```
from decimal import Decimal
from django.db import models
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
SOUTH = False
else:
SOUTH = True
class CurrencyField(models.DecimalField):
__metaclass__ = models.Su... |
Null pattern in Python underused? | 2,014,105 | 17 | 2010-01-06T15:44:21Z | 2,014,141 | 13 | 2010-01-06T15:49:07Z | [
"python",
"error-handling",
null
] | Every now and then I come across code like this:
```
foo = Foo()
...
if foo.bar is not None and foo.bar.baz == 42:
shiny_happy(...)
```
Which seems, well, unpythonic, to me.
In Objective-C, you can send messages to nil and get nil as the answer. I've always thought that's quite handy. Of course it is possible to ... | Couldn't you do a try except? The Pythonic way says [It is Easier to Ask for Forgiveness than Permission](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Exceptions).
So:
```
try:
if foo.bar.baz == 42:
shiny_happy(...)
except AttributeError:
pass #or whatever
```
Or do it without possibly si... |
Null pattern in Python underused? | 2,014,105 | 17 | 2010-01-06T15:44:21Z | 2,014,404 | 10 | 2010-01-06T16:25:42Z | [
"python",
"error-handling",
null
] | Every now and then I come across code like this:
```
foo = Foo()
...
if foo.bar is not None and foo.bar.baz == 42:
shiny_happy(...)
```
Which seems, well, unpythonic, to me.
In Objective-C, you can send messages to nil and get nil as the answer. I've always thought that's quite handy. Of course it is possible to ... | The handiness comes at the expense of dumb mistakes not being detected at the earliest possible time, as close to the buggy line of code as possible.
I think the handiness of this particular feature would be occasional at best, whereas dumb mistakes happen *all the time*.
---
Certainly a SQL-like NULL would be bad f... |
Null pattern in Python underused? | 2,014,105 | 17 | 2010-01-06T15:44:21Z | 2,014,423 | 19 | 2010-01-06T16:28:21Z | [
"python",
"error-handling",
null
] | Every now and then I come across code like this:
```
foo = Foo()
...
if foo.bar is not None and foo.bar.baz == 42:
shiny_happy(...)
```
Which seems, well, unpythonic, to me.
In Objective-C, you can send messages to nil and get nil as the answer. I've always thought that's quite handy. Of course it is possible to ... | [PEP 336 - Make None Callable](http://www.python.org/dev/peps/pep-0336/) proposed a similar feature:
> None should be a callable object that when called with any arguments
> has no side effect and returns None.
The reason for why it was rejected was simply "It is considered a feature that None raises an error when ca... |
Null pattern in Python underused? | 2,014,105 | 17 | 2010-01-06T15:44:21Z | 2,014,589 | 13 | 2010-01-06T16:51:20Z | [
"python",
"error-handling",
null
] | Every now and then I come across code like this:
```
foo = Foo()
...
if foo.bar is not None and foo.bar.baz == 42:
shiny_happy(...)
```
Which seems, well, unpythonic, to me.
In Objective-C, you can send messages to nil and get nil as the answer. I've always thought that's quite handy. Of course it is possible to ... | I'm sorry, but that code is pythonic. I think most would agree that "explicit is better than implicit" in Python. Python is a language that is easy to read compared to most, and people should not defeat that by writing cryptic code. Make the meaning very clear.
```
foo = Foo()
...
if foo.bar is not None and foo.bar.ba... |
Force python mechanize/urllib2 to only use A requests? | 2,014,534 | 10 | 2010-01-06T16:43:31Z | 6,319,043 | 14 | 2011-06-11T23:03:20Z | [
"python",
"mechanize",
"ipv6",
"urllib"
] | Here is a related question but I could not figure out how to apply the answer to mechanize/urllib2: <http://stackoverflow.com/questions/1540749/how-to-force-python-httplib-library-to-use-only-a-requests>
Basically, given this simple code:
```
#!/usr/bin/python
import urllib2
print urllib2.urlopen('http://python.org/'... | Suffering from the same problem, here is an ugly hack (use at your own risk..) based on the information given by J.J. .
This basically forces the `family` parameter of `socket.getaddrinfo(..)` to `socket.AF_INET` instead of using `socket.AF_UNSPEC` (zero, which is what seems to be used in `socket.create_connection`), ... |
Find the newest folder in a directory in Python | 2,014,554 | 12 | 2010-01-06T16:46:29Z | 2,014,704 | 27 | 2010-01-06T17:06:24Z | [
"python"
] | I am trying to have an automated script that enters into the most recently created folder.
I have some code below
```
import datetime, os, shutil
today = datetime.datetime.now().isoformat()
file_time = datetime.datetime.fromtimestamp(os.path.getmtime('/folders*'))
if file_time < today:
changedirectory('/fol... | There is no actual trace of the "time created" in most OS / filesystems: what you get as `mtime` is the time a file or directory was **modified** (so for example creating a file in a directory updates the directory's mtime) -- and from `ctime`, when offered, the time of the latest inode change (so it would be updated b... |
Forcing tuples within tuples? | 2,014,767 | 2 | 2010-01-06T17:16:02Z | 2,014,782 | 10 | 2010-01-06T17:17:47Z | [
"python",
"list",
"tuples"
] | I've got a python function that should loop through a tuple of coordinates and print their contents:
```
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
```
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through t... | Use a trailing comma for singleton tuples.
```
x = ((5, 5),)
``` |
How to create class instance inside that class method? | 2,015,306 | 5 | 2010-01-06T18:40:50Z | 2,015,324 | 9 | 2010-01-06T18:43:52Z | [
"python",
"class",
"instance"
] | I want to create class instance inside itself. I tried to it by this way:
```
class matrix:
(...)
def det(self):
(...)
m = self(sz-1, sz-1)
(...)
(...)
```
but I got error:
> ```
> m = self(sz-1, sz-1)
> ```
>
> AttributeError: matrix instance has no `__call__` method
So, I tried... | ```
m = self.__class__(sz-1, sz-1)
```
or
```
m = type(self)(sz-1, sz-1)
``` |
What's the difference between quantize() and str.format()? | 2,015,359 | 3 | 2010-01-06T18:49:11Z | 2,015,477 | 7 | 2010-01-06T19:11:11Z | [
"python",
"django",
"string",
"quantization"
] | I don't mean what's the technical difference, but rather, what's the faster/more logical or Pythonic, etc. way to do this:
```
def __quantized_price(self):
TWOPLACES = Decimal(10) ** -2
return self.price.quantize(TWOPLACES)
```
or
```
def __formatted_price(self):
TWOPLACES = Decimal(1... | `Decimal.quantize` returns a new `Decimal` that has a different value.
`''.format()` formats a string.
In this particular case printing the result yields the same output. Other than that they are totally different operations returning totally different types. |
Real-world examples of nested functions | 2,017,101 | 11 | 2010-01-06T23:22:08Z | 2,017,131 | 7 | 2010-01-06T23:28:18Z | [
"python",
"function",
"nested"
] | I asked previously how the [nested functions](http://stackoverflow.com/questions/2005956/nested-functions-in-python) work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?
Many thanks | [Decorators](http://www.artima.com/weblogs/viewpost.jsp?thread=240808) are a very popular use for nested functions. Here's an example of a decorator that prints a statement before and after any call to the decorated function.
```
def entry_exit(f):
def new_f(*args, **kwargs):
print "Entering", f.__name__
... |
Real-world examples of nested functions | 2,017,101 | 11 | 2010-01-06T23:22:08Z | 2,017,288 | 10 | 2010-01-07T00:08:56Z | [
"python",
"function",
"nested"
] | I asked previously how the [nested functions](http://stackoverflow.com/questions/2005956/nested-functions-in-python) work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?
Many thanks | Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.
One very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the enclosing ... |
Why aren't "and" and "or" operators in Python? | 2,017,230 | 19 | 2010-01-06T23:52:50Z | 2,017,249 | 40 | 2010-01-06T23:58:58Z | [
"python",
"operators",
"language-design",
"boolean",
"keyword"
] | I wasn't aware of this, but apparently the `and` and `or` keywords aren't operators. They don't appear in the [list of python operators](http://docs.python.org/reference/lexical_analysis.html#operators). Just out of sheer curiosity, why is this? And if they aren't operators, what exactly are they? | Because they're control flow constructs. Specifically:
* if the left argument to `and` evaluates to False, the right argument doesn't get evaluated at all
* if the left argument to `or` evaluates to True, the right argument doesn't get evaluated at all
Thus, it is not simply a matter of being reserved words. They don... |
Is it possible to have an actual memory leak in Python because of your code? | 2,017,381 | 15 | 2010-01-07T00:27:33Z | 2,017,431 | 37 | 2010-01-07T00:39:47Z | [
"python",
"memory-leaks"
] | I don't have a code example, but I'm curious whether it's possible to write Python code that results in essentially a memory leak. | It is possible, yes.
It depends on what kind of memory leak you are talking about. Within pure python code, it's not possible to "forget to free" memory such as in C, but it is possible to leave a reference hanging somewhere. Some examples of such:
* an unhandled traceback object that is keeping an entire stack frame... |
Get memory usage of computer in Windows with Python | 2,017,545 | 11 | 2010-01-07T01:09:40Z | 2,017,608 | 11 | 2010-01-07T01:27:57Z | [
"python",
"memory",
"winapi",
"memory-management",
"pywin32"
] | How can I tell what the computer's overall memory usage is from Python, running on Windows XP? | You'll want to use the [wmi](http://timgolden.me.uk/python/wmi/index.html) module. Something like this:
```
import wmi
comp = wmi.WMI()
for i in comp.Win32_ComputerSystem():
print i.TotalPhysicalMemory, "bytes of physical memory"
for os in comp.Win32_OperatingSystem():
print os.FreePhysicalMemory, "bytes of av... |
Get memory usage of computer in Windows with Python | 2,017,545 | 11 | 2010-01-07T01:09:40Z | 2,017,659 | 17 | 2010-01-07T01:42:13Z | [
"python",
"memory",
"winapi",
"memory-management",
"pywin32"
] | How can I tell what the computer's overall memory usage is from Python, running on Windows XP? | You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python:
```
import ctypes
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
... |
why defined '__new__' and '__init__' all in a class | 2,017,876 | 9 | 2010-01-07T02:41:09Z | 2,017,936 | 9 | 2010-01-07T02:58:37Z | [
"python",
"class"
] | i think you can defined either '`__init__`' or '`__new__`' in a class,but why all defined in django.utils.datastructures.py.
my code:
```
class a(object):
def __init__(self):
print 'aaa'
def __new__(self):
print 'sss'
a()#print 'sss'
class b:
def __init__(self):
print 'aaa'
... | `__new__` and `__init__` do completely different things. The method `__init__` initiates a new instance of a class --- it is a constructor. `__new__` is a far more subtle thing --- it can change arguments and, in fact, the class of the initiated object. For example, the following code:
```
class Meters(object):
de... |
why defined '__new__' and '__init__' all in a class | 2,017,876 | 9 | 2010-01-07T02:41:09Z | 2,017,980 | 18 | 2010-01-07T03:13:43Z | [
"python",
"class"
] | i think you can defined either '`__init__`' or '`__new__`' in a class,but why all defined in django.utils.datastructures.py.
my code:
```
class a(object):
def __init__(self):
print 'aaa'
def __new__(self):
print 'sss'
a()#print 'sss'
class b:
def __init__(self):
print 'aaa'
... | You can define either or both of `__new__` and `__init__`.
`__new__` must return an object -- which can be a new one (typically that task is delegated to `type.__new__`), an existing one (to implement singletons, "recycle" instances from a pool, and so on), or even one that's *not* an instance of the class. If `__new_... |
What are the differences between the urllib, urllib2, and requests module? | 2,018,026 | 340 | 2010-01-07T03:26:35Z | 2,018,038 | 10 | 2010-01-07T03:29:44Z | [
"python",
"urllib2",
"urllib",
"python-requests"
] | In Python, what are the differences between the `urllib`, `urllib2`, and [`requests`](http://docs.python-requests.org/en/latest/index.html) module? Why are there three? They seem to do the same thing... | urllib2.urlopen accepts an instance of the Request class or a url, whereas urllib.urlopen only accepts a url.
A similar discussion took place here:
<http://www.velocityreviews.com/forums/t326690-urllib-urllib2-what-is-the-difference.html> |
What are the differences between the urllib, urllib2, and requests module? | 2,018,026 | 340 | 2010-01-07T03:26:35Z | 2,018,074 | 138 | 2010-01-07T03:43:08Z | [
"python",
"urllib2",
"urllib",
"python-requests"
] | In Python, what are the differences between the `urllib`, `urllib2`, and [`requests`](http://docs.python-requests.org/en/latest/index.html) module? Why are there three? They seem to do the same thing... | urllib2 provides some extra functionality, namely the `urlopen()` function can allow you to specify headers (normally you'd have had to use httplib in the past, which is far more verbose.) More importantly though, urllib2 provides the `Request` class, which allows for a more declarative approach to doing a request:
``... |
What are the differences between the urllib, urllib2, and requests module? | 2,018,026 | 340 | 2010-01-07T03:26:35Z | 2,018,103 | 8 | 2010-01-07T03:51:08Z | [
"python",
"urllib2",
"urllib",
"python-requests"
] | In Python, what are the differences between the `urllib`, `urllib2`, and [`requests`](http://docs.python-requests.org/en/latest/index.html) module? Why are there three? They seem to do the same thing... | I like the `urllib.urlencode` function, and it doesn't appear to exist in `urllib2`.
```
>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'
``` |
What are the differences between the urllib, urllib2, and requests module? | 2,018,026 | 340 | 2010-01-07T03:26:35Z | 14,804,320 | 357 | 2013-02-11T00:32:09Z | [
"python",
"urllib2",
"urllib",
"python-requests"
] | In Python, what are the differences between the `urllib`, `urllib2`, and [`requests`](http://docs.python-requests.org/en/latest/index.html) module? Why are there three? They seem to do the same thing... | I know its been said already, but I'd highly recommend the Requests python package:
<http://docs.python-requests.org/en/latest/index.html>
If you've used languages other than python, you're probably thinking urllib and urllib2 are easy to use, not much code, and highly capable, that's how I used to think. But the Requ... |
reading tar file contents without untarring it, in python script | 2,018,512 | 31 | 2010-01-07T05:58:08Z | 2,018,523 | 7 | 2010-01-07T06:01:43Z | [
"python",
"tar"
] | I have a tar file which has number of files within it.
I need to write a python script which will read the contents of the files and gives the count o total characters, including total number of letters, spaces, newline characters, everything, without untarring the tar file. | you need to use the tarfile module. Specifically, you use an instance of the class TarFile to access the file, and then access the names with TarFile.getnames()
```
| getnames(self)
| Return the members of the archive as a list of their names. It has
| the same order as the list returned by getmembers().... |
reading tar file contents without untarring it, in python script | 2,018,512 | 31 | 2010-01-07T05:58:08Z | 2,018,576 | 61 | 2010-01-07T06:17:30Z | [
"python",
"tar"
] | I have a tar file which has number of files within it.
I need to write a python script which will read the contents of the files and gives the count o total characters, including total number of letters, spaces, newline characters, everything, without untarring the tar file. | you can use getmembers()
```
>>> import tarfile
>>> tar = tarfile.open("test.tar")
>>> tar.getmembers()
```
After that, you can use extractfile() to extract the members as file object. Just an example
```
import tarfile,os
import sys
os.chdir("/tmp/foo")
tar = tarfile.open("test.tar")
for member in tar.getmembers()... |
building boost python examples using Visual Studio 2008 | 2,018,908 | 9 | 2010-01-07T07:40:04Z | 2,020,097 | 9 | 2010-01-07T12:08:05Z | [
"c++",
"python",
"boost-python"
] | I'm using Boost Python library to create python extensions to my C++ code. I'd like to be able to invoke from python the 'greet' function from the C++ code shown below:
```
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_e... | Firstly, make sure you only try to import the release version from Python; importing the debug version will fail because the runtime library versions don't match. I also change my project properties so that the release version outputs a .pyd file:
Properties >> Linker >> Output:
```
$(OutDir)\$(ProjectName).pyd
```
... |
Python's CSV reader and iteration | 2,019,573 | 10 | 2010-01-07T10:29:46Z | 2,019,690 | 9 | 2010-01-07T10:55:15Z | [
"python",
"csv",
"iteration"
] | I have a CSV file that looks like this:
```
"Company, Inc.",,,,,,,,,,,,10/30/09
A/R Summary Aged Analysis Report,,,,,,,,,,,,10:35:01
All Clients,,,,,,,,,,,,USER
Client Account,Customer Name,15-Jan,16 - 30,31 - 60,61 - 90,91 - 120,120 - Over,Total,Status,Credit Limit
1000001111,CLIENT A,0,0,"3,711.32",0,0,"18,629.64",... | you can do it like this, by setting flag
```
import csv
file = "file"
f=0
reader = csv.reader(open(file),delimiter=',')
for row in reader:
if "Grand Total" in row: break
if "Client Account" in row: f=1;continue
if f:
if row[0].isdigit():
print row
``` |
Python's CSV reader and iteration | 2,019,573 | 10 | 2010-01-07T10:29:46Z | 2,019,990 | 10 | 2010-01-07T11:47:15Z | [
"python",
"csv",
"iteration"
] | I have a CSV file that looks like this:
```
"Company, Inc.",,,,,,,,,,,,10/30/09
A/R Summary Aged Analysis Report,,,,,,,,,,,,10:35:01
All Clients,,,,,,,,,,,,USER
Client Account,Customer Name,15-Jan,16 - 30,31 - 60,61 - 90,91 - 120,120 - Over,Total,Status,Credit Limit
1000001111,CLIENT A,0,0,"3,711.32",0,0,"18,629.64",... | Via generators. You can build all kinds of complexity from simple generator-filter functions. While considerably more complex than your filter, this is more extensible and can easily handle really complex spreadsheets.
```
def skip_blank( rdr ):
for row in rdr:
if len(row) == 0: continue
if all(len... |
sftp using ftplib | 2,019,780 | 6 | 2010-01-07T11:12:02Z | 2,019,800 | 8 | 2010-01-07T11:15:52Z | [
"python",
"sftp",
"ftplib"
] | Hi All
I need to download a file from a host using sFTP.
Do you know if is it possible to do that using python ftplib?
I saw [an example here](http://stackoverflow.com/questions/432385/sftp-in-python-platform-independent), but when I try to connect I receive `EOFError`.
I tried this code:
```
import ftplib
ftp = ftp... | As [the question you linked to](http://stackoverflow.com/questions/432385/sftp-in-python-platform-independent) states, ftplib doesn't support sftp (which is FTP over SSH and has nothing to do with FTPS, FTP over SSL). Use the [recommended](http://stackoverflow.com/questions/432385/sftp-in-python-platform-independent/43... |
How do I sort this list? | 2,019,951 | 4 | 2010-01-07T11:40:52Z | 2,019,973 | 10 | 2010-01-07T11:44:47Z | [
"c#",
"python",
"ruby",
"sorting",
"haskell"
] | I have a list of lists.
```
List<List<T>> li = {
{a1,a2,a3 ... aN},
{b1,b2,b3 ... bN},
...
};
double foo(List<T> list)
{
// do something
// e.g {1,2,3}
// it = 1 + 2 + 3
return it;
}
```
Now I want to sort `li` in such a way that higher the `foo(x)` for a `x` higher it should appear in a ... | With a little bit of LINQ:
```
var q = from el in li
orderby foo(el)
select el;
li = q.ToList();
``` |
How do I sort this list? | 2,019,951 | 4 | 2010-01-07T11:40:52Z | 2,020,129 | 10 | 2010-01-07T12:14:50Z | [
"c#",
"python",
"ruby",
"sorting",
"haskell"
] | I have a list of lists.
```
List<List<T>> li = {
{a1,a2,a3 ... aN},
{b1,b2,b3 ... bN},
...
};
double foo(List<T> list)
{
// do something
// e.g {1,2,3}
// it = 1 + 2 + 3
return it;
}
```
Now I want to sort `li` in such a way that higher the `foo(x)` for a `x` higher it should appear in a ... | The Haskell solution is particularly elegant with the [`on`](http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Data-Function.html#v%3Aon) combinator from Data.Function.
```
import Data.Function (on)
import Data.List (sortBy)
lists = [ [ 5, 6, 8 ]
, [ 1, 2, 3 ]
]
main = do
print $ s... |
Get fully qualified class name of an object in Python | 2,020,014 | 59 | 2010-01-07T11:50:28Z | 2,020,061 | 15 | 2010-01-07T11:58:56Z | [
"python",
"python-datamodel"
] | For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about `x.__class__.__name__`, but is there a simple method to get the package and module? | Consider using the `inspect` module which has functions like `getmodule` which might be what are looking for:
```
>>>import inspect
>>>import xml.etree.ElementTree
>>>et = xml.etree.ElementTree.ElementTree()
>>>inspect.getmodule(et)
<module 'xml.etree.ElementTree' from
'D:\tools\python2.5.2\lib\xml\etree\Elem... |
Get fully qualified class name of an object in Python | 2,020,014 | 59 | 2010-01-07T11:50:28Z | 2,020,083 | 57 | 2010-01-07T12:03:02Z | [
"python",
"python-datamodel"
] | For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about `x.__class__.__name__`, but is there a simple method to get the package and module? | With the following program
```
#! /usr/bin/env python
import foo
def fullname(o):
return o.__module__ + "." + o.__class__.__name__
bar = foo.Bar()
print fullname(bar)
```
and `Bar` defined as
```
class Bar(object):
def __init__(self, v=42):
self.val = v
```
the output is
```
$ ./prog.py
foo.Bar
``` |
Get fully qualified class name of an object in Python | 2,020,014 | 59 | 2010-01-07T11:50:28Z | 13,653,312 | 7 | 2012-11-30T21:17:43Z | [
"python",
"python-datamodel"
] | For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about `x.__class__.__name__`, but is there a simple method to get the package and module? | Here's one based on Greg Bacon's excellent answer, but with a couple of extra checks:
`__module__` can be `None` (according to the docs), and also for a type like `str` it can be `__builtin__` (which you might not want appearing in logs or whatever). The following checks for both those possibilities:
```
def fullname... |
Get fully qualified class name of an object in Python | 2,020,014 | 59 | 2010-01-07T11:50:28Z | 16,763,814 | 12 | 2013-05-26T21:23:33Z | [
"python",
"python-datamodel"
] | For logging purposes I want to retrieve the fully qualified class name of a Python object. (With fully qualified I mean the class name including the package and module name.)
I know about `x.__class__.__name__`, but is there a simple method to get the package and module? | The provided answers don't deal with nested classes. Though it's not available until Python 3.3 ([PEP 3155](http://www.python.org/dev/peps/pep-3155)), you really want to use `__qualname__` of the class. Eventually (3.4? [PEP 395](http://www.python.org/dev/peps/pep-0395)), `__qualname__` will also exist for modules to d... |
In Python how should I test if a variable is None, True or False | 2,020,598 | 57 | 2010-01-07T13:32:36Z | 2,020,606 | 63 | 2010-01-07T13:33:24Z | [
"python"
] | I have a function that can return one of three things:
* success (`True`)
* failure (`False`)
* error reading/parsing stream (`None`)
My question is, if I'm not supposed to test against `True` or `False`, how should I see what the result is. Below is how I'm currently doing it:
```
result = simulate(open("myfile"))
... | ```
if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
```
keep it simple and explicit. You can of course pre-define a dictionary.
```
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
```
If you plan on modifying your `... |
In Python how should I test if a variable is None, True or False | 2,020,598 | 57 | 2010-01-07T13:32:36Z | 2,020,704 | 64 | 2010-01-07T13:46:51Z | [
"python"
] | I have a function that can return one of three things:
* success (`True`)
* failure (`False`)
* error reading/parsing stream (`None`)
My question is, if I'm not supposed to test against `True` or `False`, how should I see what the result is. Below is how I'm currently doing it:
```
result = simulate(open("myfile"))
... | Don't fear the Exception! Having your program just log and continue is as easy as:
```
try:
result = simulate(open("myfile"))
except SimulationException as sim_exc:
print "error parsing stream", sim_exc
else:
if result:
print "result pass"
else:
print "result fail"
# execution continue... |
In Python how should I test if a variable is None, True or False | 2,020,598 | 57 | 2010-01-07T13:32:36Z | 2,021,257 | 13 | 2010-01-07T15:15:28Z | [
"python"
] | I have a function that can return one of three things:
* success (`True`)
* failure (`False`)
* error reading/parsing stream (`None`)
My question is, if I'm not supposed to test against `True` or `False`, how should I see what the result is. Below is how I'm currently doing it:
```
result = simulate(open("myfile"))
... | Never, never, never say
```
if something == True:
```
Never. It's crazy, since you're redundantly repeating what is redundantly specified as the redundant condition rule for an if-statement.
Worse, still, never, never, never say
```
if something == False:
```
You have `not`. Feel free to use it.
Finally, doing `a... |
Python based web reporting tool? | 2,021,252 | 4 | 2010-01-07T15:15:10Z | 2,021,281 | 7 | 2010-01-07T15:17:43Z | [
"python",
"reporting"
] | I have a question for those of you doing web work with python. Is
anyone familiar with a python based reporting tool? I am about to
start on a pretty big web app and will need the ability to do some end
user reporting (invoices, revenue reports, etc). It can be an existing
django app or anything python based so I can h... | [ReportLab](http://www.reportlab.org/)
> Welcome to the ReportLab Open Source site. ReportLab is a library for programatically creating PDF documents. It's a fast, flexible, cross platform solution written in Python. |
How do I execute (not import) a python script from a python prompt? | 2,021,345 | 6 | 2010-01-07T15:25:15Z | 2,021,400 | 11 | 2010-01-07T15:32:12Z | [
"python",
"bash",
"import",
"module"
] | I need to execute a Python script from an already started Python session, as if it were launched from the command line. I'm thinking of similar to doing `source` in bash or sh. | In Python 2, the builtin function [`execfile`](http://docs.python.org/library/functions.html#execfile) does this.
```
execfile(filename)
``` |
Download file using urllib in Python with the wget -c feature | 2,021,519 | 7 | 2010-01-07T15:46:42Z | 2,021,586 | 7 | 2010-01-07T15:53:27Z | [
"python",
"http",
"download",
"urllib2",
"urllib"
] | I am programming a software in Python to download HTTPÂ PDF from a database.
Sometimes the download stop with this message :
```
retrieval incomplete: got only 3617232 out of 10689634 bytes
```
How can I ask the download to restart where it stops using the `206 Partial Content` HTTPÂ feature ?
I can do it using `wge... | You can request a partial download by sending a GET with the `Range` header:
```
import urllib2
req = urllib2.Request('http://www.python.org/')
#
# Here we request that bytes 18000--19000 be downloaded.
# The range is inclusive, and starts at 0.
#
req.headers['Range'] = 'bytes=%s-%s' % (18000, 19000)
f = urllib2.urlop... |
What linux distro is better suited for Python web development? | 2,021,803 | 5 | 2010-01-07T16:21:36Z | 2,021,832 | 11 | 2010-01-07T16:24:47Z | [
"python",
"windows",
"linux",
"preferences"
] | Which linux distro is better suited for Python web development?
*Background:*
I currently develop on Windows and it's fine, but I am looking to move my core Python development to Linux. I'm sure most any distro will work fine, but does anyone have any reasons to believe one distro is better than another? | Largely distribution won't matter, as Python is present and largely self sufficient on virtually all Linux distributions.
If you're wanting to focus on development, I'd recommend Ubuntu. Ubuntu is arguably one of the most fully featured "ready for the user" distributions that makes system administration a snap, so you... |
Python append() vs. + operator on lists, why do these give different results? | 2,022,031 | 48 | 2010-01-07T16:56:58Z | 2,022,044 | 84 | 2010-01-07T16:58:39Z | [
"python",
"list",
"append",
"nested-lists"
] | Why do these two operations (`append()` resp. `+`) give different results?
```
>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>>
```
In the last case there's actually an infinite recursion. `c[-1]` and `c` are the same. Why is it differe... | ### To explain "why":
The [`+` operation](http://docs.python.org/reference/datamodel.html#object.__add__) adds the [array](http://docs.python.org/library/array.html) elements to the original array. The [`array.append`](http://docs.python.org/library/array.html?highlight=append#array.array.append) operation inserts the... |
Python append() vs. + operator on lists, why do these give different results? | 2,022,031 | 48 | 2010-01-07T16:56:58Z | 2,022,052 | 12 | 2010-01-07T16:59:50Z | [
"python",
"list",
"append",
"nested-lists"
] | Why do these two operations (`append()` resp. `+`) give different results?
```
>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>>
```
In the last case there's actually an infinite recursion. `c[-1]` and `c` are the same. Why is it differe... | `append` is appending an element to a list. if you want to extend the list with the new list you need to use `extend`.
```
>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]
``` |
Python append() vs. + operator on lists, why do these give different results? | 2,022,031 | 48 | 2010-01-07T16:56:58Z | 2,022,059 | 7 | 2010-01-07T17:00:49Z | [
"python",
"list",
"append",
"nested-lists"
] | Why do these two operations (`append()` resp. `+`) give different results?
```
>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>>
```
In the last case there's actually an infinite recursion. `c[-1]` and `c` are the same. Why is it differe... | Python lists are heterogeneous that is the elements in the same list can be any type of object. The expression: `c.append(c)` appends the object `c` what ever it may be to the list. In the case it makes the list itself a member of the list.
The expression `c += c` adds two lists together and assigns the result to the ... |
what does yield as assignment do? myVar = (yield) | 2,022,218 | 27 | 2010-01-07T17:26:26Z | 2,022,300 | 11 | 2010-01-07T17:38:22Z | [
"python",
"yield"
] | I'm familiar with yield to return a value thanks mostly to [this question](http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement)
but what does yield do when it is on the right side of an assignment?
```
@coroutine
def protocol(target=None):
while True:
c = (yield)
de... | You can send values to the generator using the `send` function.
If you execute:
```
p = protocol()
p.next() # advance to the yield statement, otherwise I can't call send
p.send(5)
```
then `yield` will return 5, so inside the generator `c` will be 5.
Also, if you call `p.next()`, `yield` will return `None`.
You ca... |
what does yield as assignment do? myVar = (yield) | 2,022,218 | 27 | 2010-01-07T17:26:26Z | 2,022,303 | 30 | 2010-01-07T17:38:57Z | [
"python",
"yield"
] | I'm familiar with yield to return a value thanks mostly to [this question](http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement)
but what does yield do when it is on the right side of an assignment?
```
@coroutine
def protocol(target=None):
while True:
c = (yield)
de... | The `yield` statement used in a function turns that function into a "generator" (a function that creates an iterator). The resulting iterator is normally resumed by calling `next()`. However it is possible to send values to the function by calling the method `send()` instead of `next()` to resume it:
```
cr.send(1)
``... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.