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 |
|---|---|---|---|---|---|---|---|---|---|
Optimizing find and replace over large files in Python | 3,800,086 | 6 | 2010-09-26T22:26:57Z | 3,800,226 | 11 | 2010-09-26T23:11:22Z | [
"python",
"optimization",
"replace"
] | I am a **complete beginner** to Python or any serious programming language for that matter. I finally got a prototype code to work but I think it will be too slow.
My goal is to find and replace some Chinese characters across all files (they are csv) in a directory with integers as per a csv file I have. The files are... | In your current code, you're reading the whole file into memory at once. Since they're 500Mb files, that means 500Mb strings. And then you do repeated replacements of them, which means Python has to create a new 500Mb string with the first replacement, then destroy the first string, then create a second 500Mb string fo... |
Python 2D image generation | 3,800,925 | 3 | 2010-09-27T03:27:50Z | 3,800,959 | 8 | 2010-09-27T03:34:54Z | [
"python",
"image",
"image-processing"
] | What are some of the better libraries for image generation in Python? If I were to implement a GOTCHA (for example's sake), thereby having to manipulate an image on the pixel level, what would my options be? Ideally I would like to save resulting image as a low-resolution jpeg, but this is mere wishing, I'll settle for... | The Python Imaging Library (PIL) is the *de facto* image manipulation library on Python. You can find it [here](http://www.pythonware.com/products/pil/), or through **easy\_install** or **pip** if you have them.
Edit: PIL has not been updated in a while, but it has been forked and maintained under the name **[pillow](... |
Kindly review the python code to boost its performance | 3,801,072 | 4 | 2010-09-27T04:14:31Z | 3,801,100 | 18 | 2010-09-27T04:21:31Z | [
"python",
"performance",
"information-retrieval"
] | I'm doing an Information Retrieval task. I built a simple searchengine. The InvertedIndex is a python dictionary object which is serialized (pickled in python terminology) to a file. Size of this file is InvertedIndex is just 6.5MB.
So, my Code just unpickles it and searches it for query & ranks the matching documents... | It's definitely your code, but since you choose to hide it from us it's impossible for us to help any further. All I can tell you based on the very scarce info you choose to supply is that unpickling a dict (in the right way) is much faster, and indexing into it (assuming that's what you mean by "searches it for query"... |
How can I use redis with Django? | 3,801,379 | 72 | 2010-09-27T05:48:42Z | 3,805,221 | 52 | 2010-09-27T15:17:05Z | [
"python",
"django",
"redis"
] | I've heard of redis-cache but how exactly does it work? Is it used as a layer between django and my rdbms, by caching the rdbms queries somehow?
Or is it supposed to be used directly as the database? Which I doubt, since that github page doesn't cover any login details, no setup.. just tells you to set some config pro... | This Python module for Redis has a clear usage example in the readme: <http://github.com/andymccurdy/redis-py>
Redis is designed to be a RAM cache. It supports basic GET and SET of keys plus the storing of collections such as dictionaries. You can cache RDBMS queries by storing their output in Redis. The goal would be... |
How can I use redis with Django? | 3,801,379 | 72 | 2010-09-27T05:48:42Z | 6,724,328 | 14 | 2011-07-17T14:00:09Z | [
"python",
"django",
"redis"
] | I've heard of redis-cache but how exactly does it work? Is it used as a layer between django and my rdbms, by caching the rdbms queries somehow?
Or is it supposed to be used directly as the database? Which I doubt, since that github page doesn't cover any login details, no setup.. just tells you to set some config pro... | Redis is basically an 'in memory' KV store with loads of bells and whistles. It is extremely flexible. You can use it as a temporary store, like a cache, or a permanent store, like a database (with caveats as mentioned in other answers).
When combined with Django the best/most common use case for Redis is probably to ... |
How can I use redis with Django? | 3,801,379 | 72 | 2010-09-27T05:48:42Z | 7,722,260 | 50 | 2011-10-11T06:40:02Z | [
"python",
"django",
"redis"
] | I've heard of redis-cache but how exactly does it work? Is it used as a layer between django and my rdbms, by caching the rdbms queries somehow?
Or is it supposed to be used directly as the database? Which I doubt, since that github page doesn't cover any login details, no setup.. just tells you to set some config pro... | Just because Redis stores things in-memory does not mean that it is meant to be a cache. I have seen people using it as a persistent store for data.
That it can be used as a cache is a hint that it is useful as a high-performance storage. If your Redis system goes down though you might loose data that was not been wri... |
Overriding a parent class's methods | 3,801,484 | 14 | 2010-09-27T06:15:14Z | 3,801,507 | 7 | 2010-09-27T06:22:54Z | [
"python",
"class",
"methods",
"subclass",
"overriding"
] | Something that I see people doing all the time is:
```
class Man(object):
def say_hi(self):
print('Hello, World.')
class ExcitingMan(Man):
def say_hi(self):
print('Wow!')
super(ExcitingMan, self).say_hi() # Calling the parent version once done with custom stuff.
```
Something that I ... | I'd argue that explicitly returning the return value of the super class method is more prudent (except in the rare case where the child wants to suppress it). Especially when you don't know what exactly super is doing. Agreed, in Python you can usually look up the super class method and find out what it does, but still... |
Querying in redis | 3,801,777 | 8 | 2010-09-27T07:17:46Z | 3,802,035 | 10 | 2010-09-27T08:09:42Z | [
"python",
"nosql",
"redis"
] | Recently I am learning redis and honestly very impressed and dying to use it. One of the things that keep bothering me is "how do I query redis". To be specific I am trying to resolve following
Say I have a millions of hashes stored as below
```
usage:1 = {created: 20100521, quantity:9, resource:1033, user:1842, ...}... | For Redis, it's best to understand what sort of query patterns you want over your data before you decide how you're going to store it.
For example, if you want to do a date range query over a set of data, you can store that data as a sorted set where the keys are the data items you want to query over, and the score is... |
Querying in redis | 3,801,777 | 8 | 2010-09-27T07:17:46Z | 6,121,986 | 7 | 2011-05-25T09:06:33Z | [
"python",
"nosql",
"redis"
] | Recently I am learning redis and honestly very impressed and dying to use it. One of the things that keep bothering me is "how do I query redis". To be specific I am trying to resolve following
Say I have a millions of hashes stored as below
```
usage:1 = {created: 20100521, quantity:9, resource:1033, user:1842, ...}... | the queries you mention are highly dependant on time. In this instance you would be wise to use a sorted set. You could use the datetime stamp as the score for each entry.
For example, you could do the following:
```
hmset usage:1 created 20100521 quantity 9 resource 1033 user 1842
hmset usage:2 created 20100812 quan... |
Is it possible to unpack a tuple in Python without creating unwanted variables? | 3,802,410 | 24 | 2010-09-27T09:15:34Z | 3,802,418 | 44 | 2010-09-27T09:16:24Z | [
"python",
"tuples",
"iterable-unpacking"
] | Is there a way to write the following function so that my IDE doesn't complain that *column* is an unused variable?
```
def get_selected_index(self):
(path, column) = self._tree_view.get_cursor()
return path[0]
```
In this case I don't care about the second item in the tuple and just want to discard the refer... | In Python the `_` is often used as an ignored placeholder.
```
(path, _) = self._treeView.get_cursor()
```
You could also avoid unpacking as a tuple is indexable.
```
def get_selected_index(self):
return self._treeView.get_cursor()[0][0]
``` |
Convert partial function to method in python | 3,803,517 | 9 | 2010-09-27T11:57:01Z | 3,803,562 | 9 | 2010-09-27T12:04:51Z | [
"python"
] | Consider the following (broken) code:
```
import functools
class Foo(object):
def __init__(self):
def f(a,self,b): ... | This will work. But I'm not sure if this is what you are looking for
```
class Foo(object):
def __init__(self):
def f(a,self,b):
print a+b ... |
Convert partial function to method in python | 3,803,517 | 9 | 2010-09-27T11:57:01Z | 3,803,829 | 18 | 2010-09-27T12:39:22Z | [
"python"
] | Consider the following (broken) code:
```
import functools
class Foo(object):
def __init__(self):
def f(a,self,b): ... | There are two issues at hand here. First, for a function to be turned into a method it must be stored on the **class**, not the instance. A demonstration:
```
class Foo(object):
def a(*args):
print 'a', args
def b(*args):
print 'b', args
Foo.b = b
x = Foo()
def c(*args):
print 'c', args
x.c = ... |
Using regex in python | 3,804,149 | 3 | 2010-09-27T13:18:23Z | 3,804,176 | 7 | 2010-09-27T13:22:35Z | [
"python",
"regex"
] | i have the following problem.
I want to escape all special characters in a python string.
```
str='eFEx-x?k=;-'
re.sub("([^a-zA-Z0-9])",r'\\1', str)
'eFEx\\1x\\1k\\1\\1\\1'
str='eFEx-x?k=;-'
re.sub("([^a-zA-Z0-9])",r'\1', str)
'eFEx-x?k=;-'
re.sub("([^a-zA-Z0-9])",r'\\\1', str)
```
I can't seem to win here. '\1... | Use `r'\\\1'`. That's a backslash (escaped, so denoted `\\`) followed by `\1`.
To verify that this works, try:
```
str = 'eFEx-x?k=;-'
print re.sub("([^a-zA-Z0-9])",r'\\\1', str)
```
This prints:
```
eFEx\-x\?k\=\;\-
```
which I think is what you want. Don't be confused when the interpreter outputs `'eFEx\\-x\\?k\... |
python, subprocess: reading output from subprocess | 3,804,727 | 10 | 2010-09-27T14:21:22Z | 3,805,707 | 13 | 2010-09-27T16:13:31Z | [
"python",
"subprocess",
"stdout"
] | I have following script:
```
#!/usr/bin/python
while True:
x = raw_input()
print x[::-1]
```
I am calling it from `ipython`:
```
In [5]: p = Popen('./script.py', stdin=PIPE)
In [6]: p.stdin.write('abc\n')
cba
```
and it works fine.
However, when I do this:
```
In [7]: p = Popen('./script.py', stdin=PIPE... | I believe there are two problems at work here:
1) Your parent script calls `p.stdout.read()`, which will read all data until end-of-file. However, your child script runs in an infinite loop so end-of-file will never happen. Probably you want `p.stdout.readline()`?
2) In interactive mode, most programs do buffer only ... |
How to cache query result in django? | 3,804,984 | 7 | 2010-09-27T14:50:01Z | 3,805,451 | 7 | 2010-09-27T15:45:28Z | [
"python",
"django",
"memcached"
] | I am trying to cache query results on my django app. However, it seems that it is caching the whole app. I tried following logi:
```
def cacheView():
result = cache.get('key')
if result is None:
result = Model.objects.get(id=1)
cache.set('key', 'result')
```
I am calling this method when user logs in. How... | RTFM :) Official Django Docs: [Caching and QuerySets](http://docs.djangoproject.com/en/dev/topics/db/queries/#caching-and-querysets)
> Each QuerySet contains a cache, to minimize database access. (...)
and:
> In a newly created QuerySet, the cache is empty. The first time a QuerySet is evaluated -- and, hence, a dat... |
How to delete a record in Django models? | 3,805,958 | 67 | 2010-09-27T16:48:06Z | 3,805,981 | 161 | 2010-09-27T16:51:50Z | [
"python",
"django",
"django-models"
] | I want to delete a particular record. Such as
```
delete from table_name where id = 1;
```
How can I do this in a `django model`? | There are a couple of ways:
To delete it directly:
```
SomeModel.objects.filter(id=id).delete()
```
To delete it from an instance:
```
instance = SomeModel.objects.get(id=id)
instance.delete()
``` |
python - Week number of the month | 3,806,473 | 7 | 2010-09-27T17:57:31Z | 16,804,556 | 12 | 2013-05-29T02:30:30Z | [
"python",
"time",
"week-number"
] | Does python offer a way to easily get the current week **of the month** (1:4) ? | In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the mont... |
Subsetting data in python | 3,806,878 | 15 | 2010-09-27T18:56:02Z | 3,807,051 | 17 | 2010-09-27T19:18:53Z | [
"python",
"arrays",
"numpy",
"subset"
] | I want to use the equivalent of the subset command in R for some python code I am writing.
Here is my data:
```
col1 col2 col3 col4 col5
100002 2006 1.1 0.01 6352
100002 2006 1.2 0.84 304518
100002 2006 2 1.52 148219
100002 2007 1.1 0.01 6292
10002 2006 1.1 0.01 5968
... | While the iterator-based answers are perfectly fine, if you're working with numpy arrays (as you mention that you are) there are better and faster ways of selecting things:
```
import numpy as np
data = np.array([
[100002, 2006, 1.1, 0.01, 6352],
[100002, 2006, 1.2, 0.84, 304518],
[100002, 2006... |
Is the Python standard library really standard? | 3,807,111 | 5 | 2010-09-27T19:26:02Z | 3,809,432 | 7 | 2010-09-28T03:14:50Z | [
"python",
"standard-library"
] | Is the Python standard library standard in the sense that if Python is installed, then the standard library is installed too?
The [documentation](http://docs.python.org/library/) reads
> For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packagin... | It's not a Python issue. You can teach that the batteries are included. They are.
It's the distributions that are incomplete.
We've been unhappy with the Red Hat Enterprise Linux having old versions of Python. However, there are recipes for upgrades.
It's a common security practice to turn off all developer packages... |
twisted: unhelpful "AlreadyCalled" error | 3,807,666 | 5 | 2010-09-27T20:39:27Z | 3,808,405 | 7 | 2010-09-27T22:34:41Z | [
"python",
"debugging",
"twisted"
] | My twisted python program keeps spewing this message ever so often:
```
Unhandled error in Deferred:
Traceback (most recent call last):
File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 757, in gotResult
_inlineCallbacks(r, g, deferred)
File "c:\python25\lib\site-packages\twisted\internet\d... | If you don't have any other hints about what's going wrong (like your unit tests pointing out the specific cases which cause this, or if pyfunc's answer doesn't make it obvious why this would be happening) then enable Deferred debugging to get information about where the first (and only allowed) result of the Deferred ... |
How to change the message in a Python AssertionError? | 3,807,694 | 21 | 2010-09-27T20:43:13Z | 3,808,078 | 31 | 2010-09-27T21:34:10Z | [
"python",
"exception",
"assertions",
"nose"
] | I'm writing per the following, in which I try to produce a decent error message when comparing two multiline blocks of Unicode text. The interior method that does the comparison raises an assertion, but the default explanation is useless to me
I need to add something to code such as this below:
```
def assert_long_st... | ```
assert expression, info
```
For instance,
```
>>> assert False, "Oopsie"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Oopsie
```
---
From the [docs](http://docs.python.org/reference/simple_stmts.html#the-assert-statementtrace.):
> Assert statements are a convenient w... |
How to change the message in a Python AssertionError? | 3,807,694 | 21 | 2010-09-27T20:43:13Z | 15,111,472 | 23 | 2013-02-27T11:54:49Z | [
"python",
"exception",
"assertions",
"nose"
] | I'm writing per the following, in which I try to produce a decent error message when comparing two multiline blocks of Unicode text. The interior method that does the comparison raises an assertion, but the default explanation is useless to me
I need to add something to code such as this below:
```
def assert_long_st... | Use `e.args`, `e.message` is deprecated.
```
try:
assert False, "Hello!"
except AssertionError as e:
e.args += ('some other', 'important', 'information', 42)
raise
```
This preserves the original traceback. Its last part then looks like this:
```
AssertionError: ('Hello!', 'some other', 'important', 'inf... |
Pass success_url to the activate | 3,808,241 | 3 | 2010-09-27T22:00:23Z | 3,808,362 | 7 | 2010-09-27T22:23:55Z | [
"python",
"django",
"django-registration"
] | Docs say :
```
``success_url``
The name of a URL pattern to redirect to on successful
acivation. This is optional; if not specified, this will be
obtained by calling the backend's
``post_activation_redirect()`` method.
```
How can I do it ? | You can do it in your `urls.py`, e.g.:
```
url(r'^account/activate/(?P<activation_key>\w+)/$', 'registration.views.activate', {'success_url': 'registration_activation_complete'}, name='registration_activate'),
url(r'^account/activate/success/$', direct_to_template, {'template': 'registration/activation_complete.html',... |
Problem loading Django fixture: IntegrityError: (1062, "Duplicate entry '4' for key 'user_id'") | 3,809,242 | 4 | 2010-09-28T02:17:54Z | 13,454,387 | 13 | 2012-11-19T13:01:27Z | [
"python",
"mysql",
"django",
"fixtures",
"mysql-error-1062"
] | I used the following commands to generate 2 fixtures:
```
./manage.py dumpdata --format=json --indent=4 --natural auth.User > fixtures/user.json
./manage.py dumpdata --format=json --indent=4 --natural --exclude=contenttypes --exclude=auth > fixtures/full.json
```
I've got the following fixture named user.json:
```
[... | As per Ashok's comment, when I had the same problem, it was solved by changing my signal handler to check for whether it is running in "raw" mode which apparently means a fixture is being loaded:
```
def create_user_profile(sender, instance, created, **kwargs):
if created and not kwargs.get('raw', False):
... |
numpy matrix multiplication | 3,809,265 | 4 | 2010-09-28T02:23:49Z | 3,809,287 | 7 | 2010-09-28T02:31:57Z | [
"python",
"matrix",
"numpy"
] | I am trying to figure out how to do a kind of scalar matrix multiplication in numpy.
I have
```
a = array(((1,2,3),(4,5,6)))
b = array((11,12))
```
and i want to do
```
a op b
```
to result in
```
array(((1*11,2*11,3*11),(4*12,5*12,6*12))
```
right now I am using the following expression
c= a \* array((b, b, b)... | Taking advantage of [broadcasting](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html):
```
(a.T * b).T
``` |
How to install both Python 2.x and Python 3.x in Windows 7 | 3,809,314 | 107 | 2010-09-28T02:40:30Z | 3,809,404 | 32 | 2010-09-28T03:07:40Z | [
"python",
"windows",
"compatibility",
"backwards-compatibility",
"build-environment"
] | I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.
Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I "choose" which version of Python should run it? ... | I have multiple versions in windows.
I just change the exe name of the version I'm not defaulting to.
> python.exe --> python26.exe
>
> pythonw.exe --> pythonw26.exe
As for package installers, most exe installers allow you to choose the python install to add the package too.
For manual installation check out the --pr... |
How to install both Python 2.x and Python 3.x in Windows 7 | 3,809,314 | 107 | 2010-09-28T02:40:30Z | 18,197,237 | 67 | 2013-08-12T21:48:53Z | [
"python",
"windows",
"compatibility",
"backwards-compatibility",
"build-environment"
] | I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.
Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I "choose" which version of Python should run it? ... | I found that the formal way to do this is as follows:
Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).
Follow the instuctions below, changing the parameters for your needs.
Create the following environment variable (to default on double click):
```
N... |
How to install both Python 2.x and Python 3.x in Windows 7 | 3,809,314 | 107 | 2010-09-28T02:40:30Z | 22,626,734 | 29 | 2014-03-25T06:13:36Z | [
"python",
"windows",
"compatibility",
"backwards-compatibility",
"build-environment"
] | I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.
Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I "choose" which version of Python should run it? ... | What I did was download both 2.7.6 and 3.3.4. Python 3.3.4 has the option to add the path to it in the environment variable so that was done. So basically I just manually added Python 2.7.6.
How to...
1. Start > in the search type in environment select "Edit environment variables to your account"1
2. Scroll down to P... |
How to install both Python 2.x and Python 3.x in Windows 7 | 3,809,314 | 107 | 2010-09-28T02:40:30Z | 26,405,013 | 11 | 2014-10-16T12:54:34Z | [
"python",
"windows",
"compatibility",
"backwards-compatibility",
"build-environment"
] | I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.
Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I "choose" which version of Python should run it? ... | If you use Anaconda Python, you can easily install various environments.
Say you had Anaconda Python 2.7 installed and you wanted a python 3.4 environment:
```
conda create -n py34 python=3.4 anaconda
```
Then to activate the environment:
```
activate py34
```
And to deactive:
```
deactivate py34
```
(With Linux... |
Smart Loop List Creation in Python for Django Choice fields | 3,809,856 | 4 | 2010-09-28T05:12:53Z | 3,809,938 | 14 | 2010-09-28T05:29:58Z | [
"python",
"django"
] | So. The following isn't very 'smart' ;)
```
MONTHS = (
('Jan', 'Jan'),
('Feb', 'Feb'),
('Mar', 'Mar'),
('Apr', 'Apr'),
('May', 'May'),
('Jun', 'Jun'),
('Jul', 'Jul'),
('Aug', 'Aug'),
('Sep', 'Sep'),
('Oct', 'Oct'),
('Nov', 'Nov'),
('Dec', 'Dec'),
)
YEARS = (
('1995'... | ```
In [17]: from datetime import datetime
In [18]: tuple((str(n), str(n)) for n in range(1995, datetime.now().year + 1))
Out[18]:
(('1995', '1995'),
('1996', '1996'),
('1997', '1997'),
('1998', '1998'),
('1999', '1999'),
('2000', '2000'),
('2001', '2001'),
('2002', '2002'),
('2003', '2003'),
('2004', '2004')... |
Ruby or Python instead of PHP? | 3,809,981 | 2 | 2010-09-28T05:39:41Z | 3,809,994 | 19 | 2010-09-28T05:42:46Z | [
"php",
"python",
"ruby",
"programming-languages"
] | I'm considering learning a new language as an alternative to PHP. I'm considering Python and Ruby. Which one is a better language based on the following four criteria, and any other qualifiers you may have?
* Which is more stable?
* Which is more scaleable?
* Which is more secure?
* Which is easier to learn?
**EDIT:*... | ```
Both are stable
Both are scalable
both are as secure
Both are easier to learn !!
```
So what matters?
Your taste. Taste them both and proceed with one that seems more palatable :) |
What's wrong with my try: except: syntax? | 3,810,279 | 2 | 2010-09-28T06:40:22Z | 3,810,285 | 18 | 2010-09-28T06:41:41Z | [
"python",
"exception-handling",
"syntax-error"
] | Choking code:
```
while port < 0 or port > 65535:
try:
port = int(raw_input("Enter port: ")
except ValueError:
print "Invalid port number."
```
Result:
```
File "/Users/.../Documents/.../CS 176A/TCPServer.py", line 10
except ValueError:
^
SyntaxError: invalid syntax
``` | Missing right parenthesis. Change to `port = int(raw_input("Enter port: "))` |
What's wrong with my try: except: syntax? | 3,810,279 | 2 | 2010-09-28T06:40:22Z | 3,810,358 | 11 | 2010-09-28T06:53:51Z | [
"python",
"exception-handling",
"syntax-error"
] | Choking code:
```
while port < 0 or port > 65535:
try:
port = int(raw_input("Enter port: ")
except ValueError:
print "Invalid port number."
```
Result:
```
File "/Users/.../Documents/.../CS 176A/TCPServer.py", line 10
except ValueError:
^
SyntaxError: invalid syntax
``` | BTW, as a rule, whenever you receive interpreter/compiler errors, start looking for problems one line **before** the reported line. |
python multiple inheritance from different paths with same method name | 3,810,410 | 5 | 2010-09-28T07:05:13Z | 3,810,460 | 7 | 2010-09-28T07:14:51Z | [
"python",
"multiple-inheritance"
] | With the following code sample, can `super` be used, or `C` has to call `A.foo` and `B.foo` explicitly?
```
class A(object):
def foo(self):
print 'A.foo()'
class B(object):
def foo(self):
print 'B.foo()'
class C(A, B):
def foo(self):
print 'C.foo()'
A.foo(self)
B.f... | `super()` will only ever resolve a single class type for a given method, so if you're inheriting from multiple classes and want to call the method in both of them, you'll need to do it explicitly. |
python multiple inheritance from different paths with same method name | 3,810,410 | 5 | 2010-09-28T07:05:13Z | 3,810,720 | 12 | 2010-09-28T07:53:30Z | [
"python",
"multiple-inheritance"
] | With the following code sample, can `super` be used, or `C` has to call `A.foo` and `B.foo` explicitly?
```
class A(object):
def foo(self):
print 'A.foo()'
class B(object):
def foo(self):
print 'B.foo()'
class C(A, B):
def foo(self):
print 'C.foo()'
A.foo(self)
B.f... | `super` is indeed intended for this situation, but it only works if you use it consistently. If the base classes don't also all use `super` it won't work, and unless the method is in `object` you have to use something like a common base class to terminate the chain of `super` calls.
```
class FooBase(object):
def ... |
how to install python distutils | 3,810,521 | 9 | 2010-09-28T07:24:48Z | 17,774,646 | 7 | 2013-07-21T16:52:09Z | [
"python",
"distutils"
] | I just got some space on a VPS server(running on ubuntu 8.04), and I'm trying to install django on it. The server has python 2.5 installed, but I guess its non standard installation. When I run install script for django, I get
```
amitoj@ninja:~/Django-1.2.1$ python setup.py install
Traceback (most recent call last):
... | I ran across this error on a Beaglebone Black using the standard Angstrom distribution. It is currently running Python 2.7.3, but does not include distutils. The solution for me was to install distutils. (It required su privileges.)
```
su
opkg install python-distutils
```
After that installation, the previou... |
Most elegant way to find node's predecessors with networkX | 3,810,782 | 8 | 2010-09-28T08:02:07Z | 4,097,968 | 20 | 2010-11-04T15:00:10Z | [
"python",
"networkx",
"parents"
] | I'm working on a graphical model project with python using [NetworkX](http://networkx.lanl.gov/). NetworkX provides simple and good functionality using dictionaries:
```
import networkx as nx
G = nx.DiGraph() # a directed graph
G.add_edge('a', 'b')
print G['a'] # prints {'b': {}}
print G['b'] # prints {}
```
I want t... | There is a predecessor (and predecessor\_iter) method:
<http://networkx.lanl.gov/reference/generated/networkx.DiGraph.predecessors.html#networkx.DiGraph.predecessors>
Also there is nothing stopping you from accessing the data structure directly as G.pred
```
In [1]: import networkx as nx
In [2]: G = nx.DiGraph() # ... |
Matplotlib: "Unknown projection '3d'" error | 3,810,865 | 44 | 2010-09-28T08:15:16Z | 3,812,324 | 51 | 2010-09-28T11:42:15Z | [
"python",
"matplotlib"
] | I just installed matplotlib and am trying to run one of there example scripts. However I run into the error detailed below. What am I doing wrong?
```
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax... | First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.
Which version are you using? (Try running: `python -c 'import matplotlib; print matplotlib.__version__'`)
I'm guessing you're running version 0.99, in which case you'll need to either use ... |
Matplotlib: "Unknown projection '3d'" error | 3,810,865 | 44 | 2010-09-28T08:15:16Z | 26,272,853 | 13 | 2014-10-09T07:39:47Z | [
"python",
"matplotlib"
] | I just installed matplotlib and am trying to run one of there example scripts. However I run into the error detailed below. What am I doing wrong?
```
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax... | Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at <http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html> which shows projection='3d' working in combination with the Axes3D import.
```
from mpl_toolkits.mplot3d ... |
Flask/Werkzeug how to attach HTTP content-length header to file download | 3,811,595 | 16 | 2010-09-28T09:55:53Z | 3,814,104 | 10 | 2010-09-28T15:01:23Z | [
"python",
"http-headers",
"download",
"flask",
"werkzeug"
] | I am using Flask (based on Werkzeug) which uses Python.
The user can download a file, I'm using the [`send_from_directory`-function](http://flask.pocoo.org/docs/api/?highlight=send_from_directory#flask.send_from_directory).
However when actually downloading the file, the HTTP header `content-length` is not set. So th... | I believe you'd do something like this (untested):
```
from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))
```
See: [Werkzug's Headers object](http://werkzeug.pocoo.org/documentation/dev/datastructures.html#werkzeug.Headers) and [Flask's Respons... |
Flask/Werkzeug how to attach HTTP content-length header to file download | 3,811,595 | 16 | 2010-09-28T09:55:53Z | 9,335,615 | 35 | 2012-02-17T21:24:27Z | [
"python",
"http-headers",
"download",
"flask",
"werkzeug"
] | I am using Flask (based on Werkzeug) which uses Python.
The user can download a file, I'm using the [`send_from_directory`-function](http://flask.pocoo.org/docs/api/?highlight=send_from_directory#flask.send_from_directory).
However when actually downloading the file, the HTTP header `content-length` is not set. So th... | Since version 0.6 the canonical way to add headers to a response object is via the `make_response` method (see [Flask docs](http://flask.pocoo.org/docs/api/#flask.make_response)).
```
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are... |
Flask/Werkzeug how to attach HTTP content-length header to file download | 3,811,595 | 16 | 2010-09-28T09:55:53Z | 9,908,561 | 38 | 2012-03-28T13:29:43Z | [
"python",
"http-headers",
"download",
"flask",
"werkzeug"
] | I am using Flask (based on Werkzeug) which uses Python.
The user can download a file, I'm using the [`send_from_directory`-function](http://flask.pocoo.org/docs/api/?highlight=send_from_directory#flask.send_from_directory).
However when actually downloading the file, the HTTP header `content-length` is not set. So th... | I needed this also, but for every requests, so here's what I did (based on the doc) :
```
from flask import Flask
app = Flask(__name__)
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
return response
``` |
Convert URL to screenshot (script) | 3,811,674 | 6 | 2010-09-28T10:08:39Z | 3,811,738 | 8 | 2010-09-28T10:16:42Z | [
"php",
"python",
"django",
"url",
"screenshot"
] | There is the URL of page on the Internet. I need to get a screenshot of this page (no matter in which browser).
I need a script (PHP, Python (even Django framework)) that receives the URL (string) and output screenshot-file at the exit (file gif, png, jpg).
**UPD:**
I need dynamically create a page where opposite to... | Why do you need a script when you can use a service from another site?
Check for example what I am using: WebSnapr <http://www.websnapr.com/>
Or check <http://www.google.ro/search?ie=UTF-8&q=website+thumbnail> if something else fits your request. |
Is python's "set" stable? | 3,812,429 | 12 | 2010-09-28T12:00:38Z | 3,812,600 | 11 | 2010-09-28T12:21:52Z | [
"python",
"set"
] | The question arose when answering to another SO question ([there](http://stackoverflow.com/questions/3811794/how-do-i-track-down-a-heisenbug-in-some-python-code/3812011#3812011)).
When I iterate several times over a python set (without changing it between calls), can I assume it will always return elements in the same... | There's no formal guarantee about the stability of sets (or dicts, for that matter.) However, in the CPython implementation, as long as nothing changes the set, the items will be produced in the same order. Sets are implemented as open-addressing hashtables (with a prime probe), so inserting or removing items can compl... |
How to check whether a directory is a sub directory of another directory | 3,812,849 | 21 | 2010-09-28T12:50:23Z | 3,814,192 | 8 | 2010-09-28T15:10:00Z | [
"python",
"security",
"validation",
"filesystems"
] | I like to write a template system in Python, which allows to include files.
e.g.
```
This is a template
You can safely include files with safe_include`othertemplate.rst`
```
As you know, including files might be dangerous. For example, if I use the template system in a web application which allows users to c... | os.path.realpath(path): Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).
Use it on directory and subdirectory name, then check latter starts with former. |
How to check whether a directory is a sub directory of another directory | 3,812,849 | 21 | 2010-09-28T12:50:23Z | 18,115,684 | 9 | 2013-08-07T23:48:07Z | [
"python",
"security",
"validation",
"filesystems"
] | I like to write a template system in Python, which allows to include files.
e.g.
```
This is a template
You can safely include files with safe_include`othertemplate.rst`
```
As you know, including files might be dangerous. For example, if I use the template system in a web application which allows users to c... | ```
def is_subdir(path, directory):
path = os.path.realpath(path)
directory = os.path.realpath(directory)
relative = os.path.relpath(path, directory)
return not relative.startswith(os.pardir + os.sep)
``` |
Interesting Python Idiom for removing the only item in a single entry list | 3,812,858 | 3 | 2010-09-28T12:51:02Z | 3,813,386 | 7 | 2010-09-28T13:46:50Z | [
"python"
] | Stumbled across this today, thought it might be worthy of discussing.
> Python idiom for taking the single
> item from a list
>
> It sometimes happens in code that I
> have a list, letâs call it `stuff`, and
> I know for certain that this list
> contains exactly one item. And I want
> to get this item and put it in ... | The blog poster wants a single statement to function as (1) extracting an item from a list, (2) an assert, and (3) as a comment telling the user that the list has only one item.
I'm a huge fan of minimizing the number of lines of code, but I vastly prefer the following:
```
assert len(stuff) == 1, "stuff should have ... |
Ubuntu packages needed to compile Python 2.7 | 3,813,092 | 11 | 2010-09-28T13:17:54Z | 6,390,579 | 11 | 2011-06-17T19:05:35Z | [
"python",
"ubuntu",
"packages",
"ubuntu-10.04"
] | I've tried to compile Python 2.7 on Ubuntu 10.4, but got the following error message after running `make`:
```
Python build finished, but the necessary bits to build these modules were not found:
_bsddb bsddb185 sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for... | Assuming that you have all the dependencies installed (on Ubuntu that would be bunch of things like `sudo apt-get install libdb4.8-dev` and various other -dev packages, then this is how I build Python.
```
tar zxvf Python-2.7.1.tgz
cd Python-2.7.1
# 64 bit self-contained build in /opt
export TARG=/opt/python272
expor... |
How to mock chained function calls in python? | 3,813,688 | 12 | 2010-09-28T14:17:48Z | 3,815,047 | 10 | 2010-09-28T16:43:44Z | [
"python",
"django",
"mocking"
] | I'm using the [mock](http://www.voidspace.org.uk/python/mock/) library written by Michael Foord to help with my testing on a django application.
I'd like to test that I'm setting up my query properly, but I don't think I need to actually hit the database, so I'm trying to mock out the query.
I can mock out the first ... | Each mock object holds onto the mock object that it returned when it is called. You can get a hold of it using your mock object's return\_value property.
For your example,
```
self.assertTrue(query_mock.distinct.called)
```
distinct wasn't called on your mock, it was called on the return value of the filter method o... |
In Python, how to specify a format when converting int to string? | 3,813,735 | 9 | 2010-09-28T14:22:30Z | 3,813,785 | 11 | 2010-09-28T14:27:18Z | [
"python",
"string"
] | In Python, how do I specify a format when converting int to string?
More precisely, I want my format to add leading zeros to have a string
with constant length. For example, if the constant length is set to 4:
* 1 would be converted into "0001"
* 12 would be converted into "0012"
* 165 would be converted into "0165"
... | `"%04d"` where the 4 is the constant length will do what you described.
You can read about string formatting [here.](http://docs.python.org/release/2.5.2/lib/typesseq-strings.html) |
What is the Python "with" statement used for? | 3,813,886 | 4 | 2010-09-28T14:37:23Z | 3,813,936 | 9 | 2010-09-28T14:42:44Z | [
"python",
"flask"
] | I am trying to understand the with statement in python. Everywhere I look it talks of opening and closing a file, and is meant to replace the try-finally block. Could someone post some other examples too. I am just trying out flask and there are with statements galore in it. Definitely request someone to provide some c... | There's a very nice explanation [here](http://effbot.org/zone/python-with-statement.htm). Basically, the with statement calls two special methods on the associated object. The \_\_enter\_\_ and \_\_exit\_\_ methods. The enter method returns the variable associated with the "with" statement. While the \_\_exit\_\_ metho... |
What is the Python "with" statement used for? | 3,813,886 | 4 | 2010-09-28T14:37:23Z | 4,930,699 | 9 | 2011-02-08T07:44:33Z | [
"python",
"flask"
] | I am trying to understand the with statement in python. Everywhere I look it talks of opening and closing a file, and is meant to replace the try-finally block. Could someone post some other examples too. I am just trying out flask and there are with statements galore in it. Definitely request someone to provide some c... | The idea of the `with` statement is to make "doing the right thing" the path of least resistance. While the file example is the simplest, threading locks actually provide a more classic example of non-obviously buggy code:
```
try:
lock.acquire()
# do stuff
finally:
lock.release()
```
This code is broken ... |
Python in my webpage? | 3,814,637 | 4 | 2010-09-28T15:53:34Z | 3,814,872 | 14 | 2010-09-28T16:19:05Z | [
"python",
"html"
] | If I want to write a webpage in Python, where do I begin?
* Do I save my file as "index.py"?
* Can I mix Python and HTML? what does that look like?
**EDIT:**
I want to learn how the Python process works on the web. I want to know if I can put Python into an existing webpage and having it render the Python code. I'm ... | At its most basic level, a Python script works like any CGI program. A Web request is sent to the server. The server sees that the URL is mapped to a Python script, so it runs your program, passing along information about the request (HTTP request headers, etc.). Your script receives those parameters and returns HTTP r... |
Implementing C's enum and union in python | 3,814,952 | 4 | 2010-09-28T16:27:53Z | 3,815,026 | 8 | 2010-09-28T16:39:06Z | [
"python",
"c",
"struct",
"unions"
] | I'm trying to figure out some C code so that I can port it into python. The code is for reading a proprietary binary data file format. It has been straightforward thus far -- it's mainly been structs and I have been using the `struct` library to ask for particular ctypes from the file. However, I just came up on this b... | Enums: There are no enums in the language. Various idioms have been proposed, but none is really widespread. The most straightforward (and in this case sufficient) solution is
```
TEEG_EVENT_TAB1 = 1
TEEG_EVENT_TAB2 = 2
```
Unions: [ctypes](http://docs.python.org/py3k/library/ctypes.html) has [unions](http://docs.pyt... |
Numpy/Python performing terribly vs. Matlab | 3,815,357 | 8 | 2010-09-28T17:19:23Z | 3,816,301 | 27 | 2010-09-28T19:24:48Z | [
"python",
"matlab",
"numpy"
] | Novice programmer here. I'm writing a program that analyzes the relative spatial locations of points (cells). The program gets boundaries and cell type off an array with the x coordinate in column 1, y coordinate in column 2, and cell type in column 3. It then checks each cell for cell type and appropriate distance fro... | Here are some ways to speed up your python code.
**First:** Don't make np arrays when you are only storing one value. You do this many times over in your code. For instance,
```
if firstcelltype == np.array((cellrecord[basecell,2])):
```
can just be
```
if firstcelltype == cellrecord[basecell,2]:
```
I'll show yo... |
while (1) Vs. for while(True) -- Why is there a difference? | 3,815,359 | 88 | 2010-09-28T17:19:45Z | 3,815,387 | 109 | 2010-09-28T17:23:33Z | [
"python"
] | Intrigued by this question about infinite loops in perl: <http://stackoverflow.com/questions/885908/while-1-vs-for-is-there-a-speed-difference>, I decided to run a similar comparison in python. I expected that the compiler would generate the same byte code for `while(True): pass` and `while(1): pass`, but this is actua... | In Python 2.x, `True` is not a keyword, but just a [built-in global constant](http://docs.python.org/library/constants.html#True) that is defined to 1 in the `bool` type. Therefore the interpreter still has to load the contents of `True`. In other words, `True` is reassignable:
```
Python 2.7 (r27:82508, Jul 3 2010, ... |
simple encrypt/decrypt lib in python with private key | 3,815,656 | 20 | 2010-09-28T17:57:32Z | 3,815,681 | 16 | 2010-09-28T18:00:54Z | [
"python",
"encryption"
] | is there a simple way to encrypt/decrypt a string with a key.
somthing like:
```
key = '1234'
string = 'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)
```
i couldn't find anything simple to do that. | <http://www.dlitz.net/software/pycrypto/> should do what you want.
Taken from their docs page.
```
>>> from Crypto.Cipher import DES
>>> obj=DES.new('abcdefgh', DES.MODE_ECB)
>>> plain="Guido van Rossum is a space alien."
>>> len(plain)
34
>>> obj.encrypt(plain)
Traceback (innermost last):
File "<stdin>", line 1, i... |
simple encrypt/decrypt lib in python with private key | 3,815,656 | 20 | 2010-09-28T17:57:32Z | 11,813,249 | 18 | 2012-08-05T01:22:28Z | [
"python",
"encryption"
] | is there a simple way to encrypt/decrypt a string with a key.
somthing like:
```
key = '1234'
string = 'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)
```
i couldn't find anything simple to do that. | [**pyDES**](http://sourceforge.net/projects/pydes/) is a DES and Triple-DES implementation written completely in python.
Here's a simple example that should be secure enough for basic string encryption needs. Just put the pyDES module in the same folder as your program and try it out:
**Sender's computer**
```
>>> f... |
simple encrypt/decrypt lib in python with private key | 3,815,656 | 20 | 2010-09-28T17:57:32Z | 14,139,824 | 9 | 2013-01-03T13:25:10Z | [
"python",
"encryption"
] | is there a simple way to encrypt/decrypt a string with a key.
somthing like:
```
key = '1234'
string = 'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)
```
i couldn't find anything simple to do that. | for python 2, you should use keyczar <http://www.keyczar.org/>
for python 3, until keyczar is available, i have written simple-crypt <http://pypi.python.org/pypi/simple-crypt>
i'm answering this two years late as things have changed since the question was asked.
note that the previous answers to this question use we... |
Tornado Request Handler | 3,816,105 | 2 | 2010-09-28T18:58:25Z | 3,816,176 | 7 | 2010-09-28T19:06:40Z | [
"python",
"class",
"request",
"tornado",
"setcookie"
] | For some reason i am unable to instantiate the set\_cookie outside of the MainHandler..
This is a little code to show what im wanting to do..
Can Anyone help??
```
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from GenCookie import... | I thought that explains itself.
set\_cookie is a method of tornado.web.RequestHandler
while in your code "self.set\_cookie", self refers to object of class GenCookie.
Your code can be modified to pass the necessary reference
```
class MainHandler(tornado.web.RequestHandler):
   def get(self):
    g=GenC... |
Proper way to test Django signals | 3,817,213 | 17 | 2010-09-28T21:34:28Z | 28,542,235 | 8 | 2015-02-16T13:13:36Z | [
"python",
"django",
"unit-testing",
"tdd"
] | I'm trying to test sent signal and it's providing\_args. Signal triggered inside `contact_question_create` view just after form submission.
My TestCase is something like:
```
def test_form_should_post_proper_data_via_signal(self):
form_data = {'name': 'Jan Nowak'}
signals.question_posted.send(send... | I have an alternative suggestion using the `mock` library, which is now part of the `unittest.mock` standard library in Python 3 (if you're using Python 2, you'll have to `pip install mock`).
```
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
def test_form_should_post_... |
Proper way to test Django signals | 3,817,213 | 17 | 2010-09-28T21:34:28Z | 30,197,682 | 13 | 2015-05-12T17:27:50Z | [
"python",
"django",
"unit-testing",
"tdd"
] | I'm trying to test sent signal and it's providing\_args. Signal triggered inside `contact_question_create` view just after form submission.
My TestCase is something like:
```
def test_form_should_post_proper_data_via_signal(self):
form_data = {'name': 'Jan Nowak'}
signals.question_posted.send(send... | Simplest way to do what you asked in 2015:
```
from mock import patch
@patch('full.path.to.signals.question_posted.send')
def test_question_posted_signal_triggered(self, mock):
form = YourForm()
form.cleaned_data = {'name': 'Jan Nowak'}
form.save()
# Check that your signal was called.
self.assert... |
argparse missing in python 3 | 3,817,481 | 5 | 2010-09-28T22:29:46Z | 3,817,517 | 12 | 2010-09-28T22:36:11Z | [
"python",
"command-line",
"python-3.x",
"argparse"
] | does somebody know, why the argparse module didn't make it in python 3? it's new in python 2.7, but the 2.x branch is running out with 2.7. it makes no sense to me not to support it in the actual python 3 branch. | It will be in Python 3.2. It was just added in Python 2.7, which was released just this July; Python 3.2 will be the next 3.x release after that date. |
Python Ignore Exception and Go Back to Where I Was | 3,817,748 | 11 | 2010-09-28T23:26:00Z | 3,817,752 | 9 | 2010-09-28T23:27:50Z | [
"python",
"exception-handling"
] | I know using below code to ignore a certain exception, but how to let the code go back to where it got exception and keep executing? Say if the exception 'Exception' raises in do\_something1, how to make the code ignore it and keep finishing do\_something1 and process do\_something2? My code just go to finally block af... | update. The way to ignore specific exceptions is to catch the type of exception that you want, test it to see if you want to ignore it and re-raise it if you dont.
```
try:
do_something1
except TheExceptionTypeThatICanHandleError, e:
if e.strerror != 10001:
raise
finally:
clean_up
```
Note also, ... |
Python Ignore Exception and Go Back to Where I Was | 3,817,748 | 11 | 2010-09-28T23:26:00Z | 3,817,768 | 7 | 2010-09-28T23:31:39Z | [
"python",
"exception-handling"
] | I know using below code to ignore a certain exception, but how to let the code go back to where it got exception and keep executing? Say if the exception 'Exception' raises in do\_something1, how to make the code ignore it and keep finishing do\_something1 and process do\_something2? My code just go to finally block af... | There's no direct way for the code to go back inside the try-except block. If, however, you're looking at trying to execute these different independant actions and keep executing when one fails (without copy/pasting the try/except block), you're going to have to write something like this:
```
actions = (
do_someth... |
Python Ignore Exception and Go Back to Where I Was | 3,817,748 | 11 | 2010-09-28T23:26:00Z | 3,817,771 | 10 | 2010-09-28T23:32:29Z | [
"python",
"exception-handling"
] | I know using below code to ignore a certain exception, but how to let the code go back to where it got exception and keep executing? Say if the exception 'Exception' raises in do\_something1, how to make the code ignore it and keep finishing do\_something1 and process do\_something2? My code just go to finally block af... | This is pretty much missing the point of exceptions.
If the first statement has thrown an exception, the system is in an indeterminate state and you have to treat the following statement as unsafe to run.
If you know which statements might fail, and how they might fail, then you can use exception handling to specific... |
Are there any keyboard shortcuts for formatting in Python? | 3,818,405 | 2 | 2010-09-29T02:47:22Z | 3,818,446 | 7 | 2010-09-29T02:59:33Z | [
"python",
"matlab",
"formatting",
"keyboard-shortcuts"
] | After we write a code in Matlab we can use `ctrl+A+ctrl+I` and `ctrl+A+ctrl+J` to format our code (comments, loops alignment etc). Is there something similar or any helpful keyboard shortcuts in Python?
Also, just like we can use upward arrow to copy our previous command window history in Matlab, is it possible or som... | Python is a programming language, not an integrated development environment (IDE), therefore it has no "keyboard shortcuts" or the like. Each given development environment may offer different facilities or the like. You appear to consider GNU Readline (typically used in the simple text-mode interpreter environment that... |
How to tell if python script is being run in a terminal or via GUI? | 3,818,511 | 7 | 2010-09-29T03:25:37Z | 3,818,551 | 7 | 2010-09-29T03:37:46Z | [
"python",
"user-interface",
"shell",
"testing"
] | I'm working in Linux and am wondering how to have python tell whether it is being run directly from a terminal or via a GUI (like alt-F2) where output will need to be sent to a window rather than stdout which will appear in a terminal.
In bash, this done by:
```
if [ -t 0 ] ; then
echo "I'm in a terminal"
else
... | ```
$ echo ciao | python -c 'import sys; print sys.stdin.isatty()'
False
```
Of course, your GUI-based IDE *might* choose to "fool" you by opening a pseudo-terminal instead (you can do it yourself to *other* programs with [pexpect](http://www.noah.org/wiki/Pexpect), and, what's sauce for the goose...!-), in which case... |
Python - what is the correct way to copy an object's attributes over to another? | 3,818,825 | 8 | 2010-09-29T04:53:56Z | 3,818,861 | 15 | 2010-09-29T05:05:25Z | [
"python",
"design-patterns"
] | I have two classes. They're almost identical, except for 2 attributes. I need to copy all the attributes over from one to the other, and I'm just wondering **if there is a pattern** or best practice, **or** if I should just basically do:
```
spam.attribute_one = foo.attribute_one
spam.attribute_two = foo.attribute_two... | The code you give is correct and safe, avoiding "accidentally" binding attributes that should *not* be bound. If you favor automation over safety and correctness, though, you *could* use something like...:
```
def blindcopy(objfrom, objto):
for n, v in inspect.getmembers(objfrom):
setattr(objto, n, v);
```... |
removing duplicate entries from multi-d array in python | 3,819,348 | 5 | 2010-09-29T06:45:28Z | 3,819,368 | 8 | 2010-09-29T06:48:01Z | [
"python",
"arrays"
] | I have a 2-d array
```
xx=[[a,1],[b,2],[c,3]]
```
Now I'm trying to remove duplicate entries from it. For simple 1-D array, simple code like
```
xx=list(set(xx))
```
would work. But trying set on 2-d elements gives an error
```
temp = set(xx)
TypeError: unhashable type: 'list'
```
One workaround would be to seri... | Convert elements to tuple and then use `set`.
```
>>> xx=[['a',1],['b',2],['c',3],['c',3]]
>>> set(tuple(element) for element in xx)
set([('a', 1), ('b', 2), ('c', 3)])
>>>
```
Tuples, unlike lists, can be hashed. Hence. And once you are done, convert the elements back to list. Putting everything together:
```
>>> [... |
In Tkinter is there any way to make a widget not visible? | 3,819,354 | 14 | 2010-09-29T06:46:42Z | 3,819,568 | 23 | 2010-09-29T07:28:45Z | [
"python",
"tkinter"
] | Something like this, would make the widget appear normally:
```
Label(self, text = 'hello', visible ='yes')
```
While something like this, would make the widget not appear at all:
```
Label(self, text = 'hello', visible ='no')
``` | You may be interested by the [`pack_forget`](http://effbot.org/tkinterbook/pack.htm#Tkinter.Pack.pack_forget-method) and [`grid_forget`](http://effbot.org/tkinterbook/grid.htm#Tkinter.Grid.grid_forget-method) methods of a widget. In the following example, the button disappear when clicked
```
from Tkinter import *
de... |
In Tkinter is there any way to make a widget not visible? | 3,819,354 | 14 | 2010-09-29T06:46:42Z | 5,928,294 | 14 | 2011-05-08T15:15:35Z | [
"python",
"tkinter"
] | Something like this, would make the widget appear normally:
```
Label(self, text = 'hello', visible ='yes')
```
While something like this, would make the widget not appear at all:
```
Label(self, text = 'hello', visible ='no')
``` | One option, as explained in another answer, is to use `pack_forget` or `grid_forget`. Another option is to use `lift` and `lower`. This changes the stacking order of widgets. The net effect is that you can hide widgets behind sibling widgets (or descendants of siblings). When you want them to be visible you `lift` them... |
How to uninstall Python 2.7 on a Mac OS X 10.6.4? | 3,819,449 | 149 | 2010-09-29T07:03:39Z | 3,819,829 | 272 | 2010-09-29T08:18:21Z | [
"python",
"osx",
"uninstall",
"python-2.7"
] | I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash\_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 install package. I've got the install package from <http://www... | The complete list is [documented here](http://bugs.python.org/issue7107). Basically, all you need to do is the following:
1. Remove the Python 2.7 framework
`sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7`
2. Remove the Python 2.7 applications directory
`sudo rm -rf "/Applications/Python 2.7"`
3... |
How to uninstall Python 2.7 on a Mac OS X 10.6.4? | 3,819,449 | 149 | 2010-09-29T07:03:39Z | 10,308,509 | 63 | 2012-04-25T02:16:53Z | [
"python",
"osx",
"uninstall",
"python-2.7"
] | I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash\_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 install package. I've got the install package from <http://www... | This one works:
```
cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
```
Description:
It list all the links, removes `@` character and then removes them. |
How to uninstall Python 2.7 on a Mac OS X 10.6.4? | 3,819,449 | 149 | 2010-09-29T07:03:39Z | 11,196,943 | 17 | 2012-06-25T20:35:02Z | [
"python",
"osx",
"uninstall",
"python-2.7"
] | I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash\_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 install package. I've got the install package from <http://www... | If you installed it using the PKG installer, you can do:
```
pkgutil --pkgs
```
or better:
```
pkgutil --pkgs | grep org.python.Python
```
which will output something like:
```
org.python.Python.PythonApplications-2.7
org.python.Python.PythonDocumentation-2.7
org.python.Python.PythonFramework-2.7
org.python.Python... |
Error in django unittest while loading a fixture | 3,819,693 | 4 | 2010-09-29T07:51:17Z | 8,816,700 | 8 | 2012-01-11T09:11:41Z | [
"python",
"django",
"django-testing",
"django-fixtures"
] | I am making unittests for a django app. I need some data in the database for my tests so I am using a json fixture.
I have two fixtures:
1. for users and it works ok.
2. for some webpages
The fixture 2 cause the following error:
```
Problem installing fixture 'C:\Users\luc\Dev\Hg\mnl-adminpub\website\fixtures\websi... | You should use [TEST\_CHARSET](https://docs.djangoproject.com/en/dev/ref/settings/#test-charset), but *inside* DATABASE config. Like that:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_sbet',
'USER': 'test_sbet', ... |
single py file for convert rst to html | 3,819,917 | 11 | 2010-09-29T08:29:12Z | 3,819,981 | 16 | 2010-09-29T08:38:14Z | [
"python",
"google-app-engine",
"restructuredtext"
] | I write blog by using rst, and I manually convert it into html, and post it.
For now, I want to create a simple blog system by using **GAE**,
I know docutils can convert rst to html,
but docutils is big, is there a single py file for convert rst to html?
anyone notice **GAE**? | docutils is a library that you can install. It also installs front end tools to convert from rest to various formats including html.
* <http://docutils.sourceforge.net/docs/user/tools.html#rst2html-py>
This is a stand alone tool that can be used.
Most converters will exploit the docutils library for this. |
single py file for convert rst to html | 3,819,917 | 11 | 2010-09-29T08:29:12Z | 16,596,385 | 9 | 2013-05-16T20:00:38Z | [
"python",
"google-app-engine",
"restructuredtext"
] | I write blog by using rst, and I manually convert it into html, and post it.
For now, I want to create a simple blog system by using **GAE**,
I know docutils can convert rst to html,
but docutils is big, is there a single py file for convert rst to html?
anyone notice **GAE**? | The Sphinx documentation generator Python library includes many restructured text (RST) command-line converters.
Install Sphinx:
```
$ pip install sphinx
```
Then use one of the many rst2\*.py helpers:
```
$ rst2html.py in_file.rst out_file.html
``` |
Python: Write a list of tuples to a file | 3,820,312 | 16 | 2010-09-29T09:30:07Z | 3,820,334 | 27 | 2010-09-29T09:33:44Z | [
"python"
] | How can I write the following list:
```
[(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im'), (5, 'telnetcpcd'), (5, 'etftp'), (5, 'http-alt')]
```
to a text file with two columns `(8 rfa)` and many rows, so that I have something like this:
```
8 rfa
8 acc-raid
7 rapidbas... | ```
with open('daemons.txt', 'w') as fp:
fp.write('\n'.join('%s %s' % x for x in mylist))
``` |
Python: Write a list of tuples to a file | 3,820,312 | 16 | 2010-09-29T09:30:07Z | 3,820,337 | 19 | 2010-09-29T09:34:05Z | [
"python"
] | How can I write the following list:
```
[(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im'), (5, 'telnetcpcd'), (5, 'etftp'), (5, 'http-alt')]
```
to a text file with two columns `(8 rfa)` and many rows, so that I have something like this:
```
8 rfa
8 acc-raid
7 rapidbas... | ```
import csv
with open(<path-to-file>, "w") as the_file:
csv.register_dialect("custom", delimiter=" ", skipinitialspace=True)
writer = csv.writer(the_file, dialect="custom")
for tup in tuples:
writer.write(tup)
```
The [`csv`](http://docs.python.org/library/csv.html#csv-fmt-params) module is very... |
GAE webapp application internationalization with Babel | 3,821,312 | 12 | 2010-09-29T11:51:17Z | 3,828,276 | 11 | 2010-09-30T06:25:17Z | [
"python",
"google-app-engine",
"web-applications",
"internationalization",
"babel"
] | How would you go about internationalizing a Google App Engine webapp application using [BABEL](http://babel.edgewall.org/)? I am looking here for all the stages:
1. Marking the strings to be translated.
2. Extracting them.
3. Traslating
4. Configuring your app to load the right language requested by the browser | 1) use \_() (or gettext()) in your code and templates. Translated strings set in the module globals or class definitions should use some form of lazy gettext(), because i18n won't be available when the modules are imported.
2) Extract all translations using pybabel. Here we pass two directories to be scanned: the temp... |
How to format integers greater than 999 in python to look more readable? | 3,822,006 | 2 | 2010-09-29T13:25:12Z | 3,822,041 | 7 | 2010-09-29T13:28:32Z | [
"python"
] | I have a bunch of numbers that I want to print to the user. Each number is greater than one million so I want to print it as 1.000.000 or 1,000,000 (any of these forms is valid to me). I want to know if is it possible to format integer numbers this way in python using the built-in formating utilities. | Use [`locale.format`](http://docs.python.org/library/locale.html#locale.format). You will need to `setlocale` first, since the formatting style is dependent on location (European countries typically use `.` instead of `,` for separating the digits, for instance).
```
>>> import locale
>>> locale.setlocale(locale.LC_AL... |
"chunksize" parameter in Python's multiprocessing.Pool.map | 3,822,512 | 15 | 2010-09-29T14:22:45Z | 3,822,901 | 14 | 2010-09-29T15:02:15Z | [
"python",
"multithreading"
] | If I have a pool object with 2 processors for example:
```
p=multiprocessing.Pool(2)
```
and I want to iterate over a list of files on directory and use the map function
could someone explain what is the chunksize of this function:
```
p.map(func, iterable[, chunksize])
```
If I set the chunksize for example to 10... | Looking at the [documentation for Pool.map](http://docs.python.org/release/2.6.6/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map) it seems you're almost correct: the `chunksize` parameter will cause the iterable to be split into pieces of **approximately** that size, and each piece is submitt... |
IOError: request data read error | 3,823,280 | 42 | 2010-09-29T15:45:12Z | 4,107,128 | 7 | 2010-11-05T15:01:43Z | [
"python",
"django"
] | I seem to be getting an IOError: request data read error quite a lot when i'm doing an Ajax upload. For example out of every 5 file uploads it errors out on atleast 3.
Other people seem to have had the same issue. Eg.
* <http://stackoverflow.com/questions/2641665/django-upload-failing-on-request-data-read-error>
* <h... | as you might think, this is no django error.
see <https://groups.google.com/group/django-users/browse_thread/thread/946936f69c012d96>
have the error myself (but IE ajax requests only, no file upload, just post data).
will add an complete answer if i ever find out how to fix this. |
IOError: request data read error | 3,823,280 | 42 | 2010-09-29T15:45:12Z | 7,089,413 | 13 | 2011-08-17T07:48:41Z | [
"python",
"django"
] | I seem to be getting an IOError: request data read error quite a lot when i'm doing an Ajax upload. For example out of every 5 file uploads it errors out on atleast 3.
Other people seem to have had the same issue. Eg.
* <http://stackoverflow.com/questions/2641665/django-upload-failing-on-request-data-read-error>
* <h... | I get this exception, too. In the Apache error logfile I see this:
```
[Wed Aug 17 08:30:45 2011] [error] [client 10.114.48.206] (70014)End of file found: mod_wsgi (pid=9722): Unable to get bucket brigade for request., referer: https://egs-work/modwork/beleg/188074/edit/
[Wed Aug 17 08:30:45 2011] [error] [client 10.1... |
How to setup FTS3/FTS4 with python2.7 on Windows | 3,823,659 | 9 | 2010-09-29T16:22:45Z | 4,532,837 | 12 | 2010-12-26T05:09:39Z | [
"python",
"sqlite",
"full-text-search",
"fts3",
"fts4"
] | FTS3/FTS4 doesn't work in python by default (up to 2.7). I get the error:
```
sqlite3.OperationalError: no such module: fts3
```
or
```
sqlite3.OperationalError: no such module: fts4
```
How can this be resolved? | 1. Download the latest [sql dll](http://www.sqlite.org/download.html).
2. Replace sqlite.dll in your python/dll folder. |
Display image as grayscale using matplotlib | 3,823,752 | 81 | 2010-09-29T16:33:03Z | 3,823,800 | 17 | 2010-09-29T16:39:14Z | [
"python",
"matplotlib",
"grayscale"
] | I'm trying to display a grayscale image using **matplotlib.pyplot.imshow()**. My problem is that the grayscale image is displayed as a colormap. I need the grayscale because I want to draw on top of the image with color.
I read in the image and convert to grayscale using **PIL's Image.open().convert("L")**
```
image ... | Try to use a grayscale colormap?
E.g. something like
```
imshow(..., cmap=pyplot.cm.binary)
```
For a list of colormaps, see <http://scipy-cookbook.readthedocs.org/items/Matplotlib_Show_colormaps.html> |
Display image as grayscale using matplotlib | 3,823,752 | 81 | 2010-09-29T16:33:03Z | 3,823,822 | 121 | 2010-09-29T16:40:37Z | [
"python",
"matplotlib",
"grayscale"
] | I'm trying to display a grayscale image using **matplotlib.pyplot.imshow()**. My problem is that the grayscale image is displayed as a colormap. I need the grayscale because I want to draw on top of the image with color.
I read in the image and convert to grayscale using **PIL's Image.open().convert("L")**
```
image ... | ```
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='Greys_r')
plt.show()
``` |
Display image as grayscale using matplotlib | 3,823,752 | 81 | 2010-09-29T16:33:03Z | 9,636,208 | 7 | 2012-03-09T15:00:54Z | [
"python",
"matplotlib",
"grayscale"
] | I'm trying to display a grayscale image using **matplotlib.pyplot.imshow()**. My problem is that the grayscale image is displayed as a colormap. I need the grayscale because I want to draw on top of the image with color.
I read in the image and convert to grayscale using **PIL's Image.open().convert("L")**
```
image ... | try this:
```
import pylab
from scipy import misc
pylab.imshow(misc.lena(),cmap=pylab.gray())
pylab.show()
``` |
Display image as grayscale using matplotlib | 3,823,752 | 81 | 2010-09-29T16:33:03Z | 11,603,881 | 9 | 2012-07-22T20:49:23Z | [
"python",
"matplotlib",
"grayscale"
] | I'm trying to display a grayscale image using **matplotlib.pyplot.imshow()**. My problem is that the grayscale image is displayed as a colormap. I need the grayscale because I want to draw on top of the image with color.
I read in the image and convert to grayscale using **PIL's Image.open().convert("L")**
```
image ... | You can also run once in your code
```
grey()
```
This will show the images in grayscale as default
```
im = array(Image.open('I_am_batman.jpg').convert('L'))
imshow(im)
show()
``` |
paramiko combine stdout and stderr | 3,823,862 | 7 | 2010-09-29T16:44:07Z | 8,045,735 | 10 | 2011-11-08T03:53:13Z | [
"python",
"ssh",
"paramiko"
] | I am trying to combine the output of stdout and stderr. My belief is that this can be done with the set\_combine\_stderr() of a Channel object.
This is what I am doing:
```
SSH = paramiko.SSHClient()
#I connect and everything OK, then:
chan = ssh.invoke_shell()
chan.set_combine_stderr(True)
chan.exec_command('python2... | While it is true that `set_combine_stderr` diverts `stderr` to the `stdout` stream, it does so in chaotic order, so you do not get the result you probably want, namely, the lines combined in the order written, as if you were running the command in a local terminal window. Instead, use `get_pty`. That will cause the ser... |
More pythonic way to write this? | 3,823,980 | 4 | 2010-09-29T16:55:48Z | 3,824,020 | 10 | 2010-09-29T16:59:59Z | [
"python"
] | I have this code here:
```
import re
def get_attr(str, attr):
m = re.search(attr + r'=(\w+)', str)
return None if not m else m.group(1)
str = 'type=greeting hello=world'
print get_attr(str, 'type') # greeting
print get_attr(str, 'hello') # world
print get_attr(str, 'attr') # None
```
Which works, b... | Python *has* a ternary operator. You're using it. It's just in the `X if Y else Z` form.
That said, I'm prone to writing these things out. Fitting things on one line isn't so great if you sacrifice clarity.
```
def get_attr(str, attr):
m = re.search(attr + r'=(\w+)', str)
if m:
return m.group(1)
... |
Create constants in Python using a "settings" module | 3,824,455 | 59 | 2010-09-29T17:57:03Z | 3,824,479 | 102 | 2010-09-29T17:59:40Z | [
"python"
] | I have done searches on Google and here at Stackoverflow but can not find what I am looking for.
I am relatively new to Python. I looking to create a "settings" module where various application specific constants will be stored.
Here is how I am wanting to setup my code
settings.py
```
CONSTANT = 'value'
```
scrip... | The easiest way to do this is to just have settings be a module.
(settings.py)
```
CONSTANT1 = "value1"
CONSTANT2 = "value2"
```
(consumer.py)
```
import settings
print settings.CONSTANT1
print settings.CONSTANT2
```
When you import a python module, you have to prefix the the variables that you pull from it with ... |
Create constants in Python using a "settings" module | 3,824,455 | 59 | 2010-09-29T17:57:03Z | 16,898,269 | 11 | 2013-06-03T13:46:03Z | [
"python"
] | I have done searches on Google and here at Stackoverflow but can not find what I am looking for.
I am relatively new to Python. I looking to create a "settings" module where various application specific constants will be stored.
Here is how I am wanting to setup my code
settings.py
```
CONSTANT = 'value'
```
scrip... | > **step 1: create a new file settings.py on the same directory for easier access.**
```
#database configuration settings
database = dict(
DATABASE = "mysql",
USER = "Lark",
PASS = ""
)
#application predefined constants
app = dict(
VERSION = 1.0,
GITHUB = "{url}"
)
```
> **step 2: ... |
How do I write to the apache log files when using mod_wsgi | 3,824,923 | 9 | 2010-09-29T18:59:13Z | 3,825,257 | 9 | 2010-09-29T19:44:44Z | [
"python",
"apache",
"logging",
"mod-wsgi"
] | I have a Django project where I have been logging to a file using the standard library logging module. For a variety of reasons I would like to change it so that it writes to the Apache log files. I've seen quite a bit of discussion of how to do this with mod\_python, but not mod\_wsgi. How do I do this for a project r... | Mostly, we use logging and write to `sys.stderr`. That seems to write to the Apache error\_log. |
Is there a plugin for vim to auto-import python libraries? | 3,825,073 | 16 | 2010-09-29T19:21:59Z | 4,081,465 | 8 | 2010-11-02T19:38:55Z | [
"python",
"eclipse",
"vim",
"ide",
"text-editor"
] | In eclipse you can hit Ctrl+Shift+o to automatically import all the libraries you reference in your code. Is there any similar plugin for vim to have this feature with python? | There is **[ropevim](http://bitbucket.org/agr/ropevim/src)**. It is available on [pypi](http://pypi.python.org/pypi/ropevim/0.3-rc) as well
The autoimport (adds missing imports) and organizeimport (reorder imports) features work well, but it is a little invasive at times (it will create a .ropeproject folder in your p... |
How to apply a function to every element in a list using Linq in C# like the method reduce() in python? | 3,825,200 | 3 | 2010-09-29T19:38:24Z | 3,825,225 | 11 | 2010-09-29T19:41:02Z | [
"c#",
"python",
"linq"
] | How to apply a function to every element in a list using Linq in C# like the method reduce() in python? | Assuming you're talking about [this reduce function](http://docs.python.org/library/functions.html#reduce), the equivalent in C# and LINQ is [Enumerable.Aggregate](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aggregate.aspx).
Quick example:
```
var list = Enumerable.Range(5, 3); // [5, 6, 7]
Console... |
(Usage of Class Variables) Pythonic - or nasty habit learnt from java? | 3,826,077 | 2 | 2010-09-29T21:41:08Z | 3,826,126 | 7 | 2010-09-29T21:49:28Z | [
"class",
"coding-style",
"python"
] | Hello Pythoneers: the following code is only a mock up of what I'm trying to do, but it should illustrate my question.
I would like to know if this is dirty trick I picked up from Java programming, or a valid and Pythonic way of doing things: basically I'm creating a load of instances, but I need to track 'static' dat... | Class variables are perfectly Pythonic in my opinion.
Just watch out for one thing. An instance variable can hide a class variable:
```
x.counter = 5 # creates an instance variable in the object x.
print x.counter # instance variable, prints 5
print y.counter # class variable, prints 2
print myclass.counter # clas... |
Django RegexField Letters and Numbers only | 3,826,822 | 3 | 2010-09-30T00:13:16Z | 3,826,829 | 7 | 2010-09-30T00:16:17Z | [
"python",
"regex",
"django"
] | I need a regexfield in a django form to only accept letters and numbers, and nothing else. I've tried this, but it didn't work:
```
myfield = forms.RegexField(label=("My Label"), max_length=31, regex=r'[a-zA-Z0-9]',
error_message = ("This value must contain only letters and numbers."),
```
I am not very good ... | regex=r'[a-zA-Z0-9]',
Is one letter.
Do you want more than one letter? Then use a repeat
regex=r'[a-zA-Z0-9]+',
There are numerous tutorials on regular expressions. Please google for "Regular Expression Tutorial." |
match two strings with letters in random order in python | 3,826,867 | 2 | 2010-09-30T00:24:01Z | 3,826,877 | 10 | 2010-09-30T00:26:23Z | [
"python",
"regex"
] | if I have 2 strings like:
```
a = "hello"
b = "olhel"
```
I want to use a regular expression (or something else?) to see if the two strings contain the same letters. In my example a would = b because they have the same letters. How can this be achieved? | ```
a = "hello"
b = "olhel"
print sorted(a) == sorted(b)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.