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
PyPI role maintenance - Owners vs. Maintainers
12,857,123
7
2012-10-12T10:30:10Z
12,858,181
10
2012-10-12T11:33:54Z
[ "python", "pypi" ]
Am I reading correctly in assuming that only 'Owners' can push new versions, or can 'Maintainers' do so as well? The Maintainer's role is listed as "Can submit and update info for a particular package name.". Specifically what info can a maintainer edit?
A Maintainer can: * Edit package info * Add and remove releases * Add and remove files for releases * Edit release info Someone with the Admin role can, in addition, also assign roles and remove the package altogether.
Python - How to check if Redis server is available
12,857,604
14
2012-10-12T10:59:52Z
12,860,302
7
2012-10-12T13:37:11Z
[ "python", "redis" ]
I'm developing a Python Service(Class) for accessing Redis Server. I want to know how to check if Redis Server is running or not. And also if somehow I'm not able to connect to it. Here is a part of my code ``` import redis rs = redis.Redis("localhost") print rs ``` It prints the following ``` <redis.client.Redis o...
As you said, the connection to the Redis Server is only established when you try to execute a command on the server. If you do not want to go head forward without checking that the server is available, you can just send a random query to the server and check the response. Something like : ``` try: response = rs.cl...
Python - How to check if Redis server is available
12,857,604
14
2012-10-12T10:59:52Z
12,968,704
15
2012-10-19T06:38:54Z
[ "python", "redis" ]
I'm developing a Python Service(Class) for accessing Redis Server. I want to know how to check if Redis Server is running or not. And also if somehow I'm not able to connect to it. Here is a part of my code ``` import redis rs = redis.Redis("localhost") print rs ``` It prints the following ``` <redis.client.Redis o...
The official way to check if redis server availability is ping ( <http://redis.io/topics/quickstart> ). One solution is to subclass redis and do 2 things: 1. check for a connection at instantiation 2. write an exception handler in the case of no connectivity when making requests
How to convert data values into color information for matplotlib?
12,857,925
7
2012-10-12T11:19:22Z
12,858,391
14
2012-10-12T11:47:13Z
[ "python", "colors", "numpy", "matplotlib", "scipy" ]
I am using the class matplotlib.patches.Polygon to draw polygons on a map. In fact, the information about the coordinates of the corners of the polygons and a floating point data value for each "polygon" are given. Now I'd like to convert these data values (ranging from 0 to 3e15) into color information to visualize it...
In the RGB color system two bits of data are used for each color, red, green, and blue. That means that each color runs on a scale from 0 to 255. Black would be 00,00,00, while white would be 255,255,255. Matplotlib has lots of pre-defined colormaps for you to use. They are all normalized to 255, so they run from 0 to ...
Serving a request from gunicorn
12,858,674
9
2012-10-12T12:04:55Z
12,859,371
16
2012-10-12T12:44:41Z
[ "python", "linux", "centos", "wsgi", "gunicorn" ]
Trying to setup a server on Rackspace.com. Have done the following things: * Installed Centos 6.3 * Installed Python 2.7 * Installed gunicorn using the "Quick Start" on their home page: [gunicorn.org/](http://gunicorn.org/) In the quick start, a "hello world" application seems to be initialized: Create file "**myap...
since gunicorn is a Web server on your case Nginx will act as a back proxy passing the an HTTP request from Nginx to gunicorn. So, I will put here the steps to take for a simple Nginx and Gunicorn configuration running on the same machine. * **Starting with nginx configuration** Go to your **/etc/nginx/nginx.conf** ...
Serving a request from gunicorn
12,858,674
9
2012-10-12T12:04:55Z
12,859,441
8
2012-10-12T12:48:20Z
[ "python", "linux", "centos", "wsgi", "gunicorn" ]
Trying to setup a server on Rackspace.com. Have done the following things: * Installed Centos 6.3 * Installed Python 2.7 * Installed gunicorn using the "Quick Start" on their home page: [gunicorn.org/](http://gunicorn.org/) In the quick start, a "hello world" application seems to be initialized: Create file "**myap...
looking at the quickstart guide, you probably should have run ``` (tutorial) $ ../bin/gunicorn -w 4 myapp:app ``` which should have produced a line that looks a bit like: ``` Listening at: http://127.0.0.1:8000 ``` Among others. see if you can access your site at that address. Also Note that `127.0.0.1` is the loo...
easy_install : ImportError: Entry point ('console_scripts', 'easy_install') not found
12,858,779
27
2012-10-12T12:10:43Z
12,859,645
9
2012-10-12T12:59:53Z
[ "python", "osx", "easy-install" ]
I used easy\_install to install pip, pip to install django, virtualenv, and virtualenvwrapper. I have just returned to it a few weeks later and django does not seem to work anymore, but more concerning is I can't start the process over again as easy\_install is returning the following error: ``` Traceback (most recen...
You seem to have a version conflict; note the `setuptools-0.6c11-py2.7.egg` path, but the `/usr/bin/easy_install-2.7` script wants to load `0.6c12dev-r88846` instead. The latter is a development version; it has the revision number of a subversion repository embedded in the version (`dev-r88846`). I suspect you have *...
Python Pandas : pivot table with aggfunc = count unique distinct
12,860,421
14
2012-10-12T13:43:47Z
12,862,196
19
2012-10-12T15:19:00Z
[ "python", "pandas", "pivot-table" ]
``` df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']}) X Y Z 0 X1 Y2 Z3 1 X1 Y1 Z1 2 X1 Y1 Z1 3 X1 Y1 Z2 g=df2.groupby('X') pd.pivot_table(g, values='X', rows='Y', cols='Z', margins=False, aggfunc='count') ``` > Traceback (most recent c...
Do you mean something like this? ``` In [39]: df2.pivot_table(values='X', rows='Y', cols='Z', aggfunc=lambda x: len(x.unique())) Out[39]: Z Z1 Z2 Z3 Y Y1 1 1 NaN Y2 NaN NaN 1 ``` Note that using `len` assumes you don't have `NA`s in your DataFrame. You can do `x.value...
How to do elif statments more elegantly if appending to array in python
12,860,804
9
2012-10-12T14:04:36Z
12,860,873
9
2012-10-12T14:08:57Z
[ "python", "loops" ]
I am trying to do a more elegant version of this code. This just basically appends a string to categorynumber depending on the number. Would appreciate any help. ``` number = [100,150,200,500] categoryNumber = [] for i in range (0,len(number)): if (number [i] >=1000): categoryNumber.append('number > 1000...
How about: ``` labels = ( (1000, 'number >= 1000'), (200, '200 <= number < 1000'), (100, '100 <= number < 200'), (50, '50 <= number < 100'), (0, 'number < 50'), ) for i in number: for limit, label in labels: if i >= limit: categoryNumber.append(label) ...
Python - import in if
12,860,841
8
2012-10-12T14:07:31Z
12,860,988
7
2012-10-12T14:14:55Z
[ "python", "if-statement", "python-import" ]
I wrote little wrapper for urllib (python3). Is it **proper** and **safe** to import module *in if*? ``` if self.response_encoding == 'gzip': import gzip ``` I didn't find any PEP about this code. However, it bothers me.
This is a reasonably common idiom actually. You'll sometimes see it to pick between different modules: ``` if system == 'linux': import linuxdeps as deps elif system == 'win32': import win32deps as deps ``` Then, assuming both `linuxdeps` and `win32deps` have the same functions, you can just use it: ``` deps.f...
Python - import in if
12,860,841
8
2012-10-12T14:07:31Z
12,861,052
9
2012-10-12T14:17:58Z
[ "python", "if-statement", "python-import" ]
I wrote little wrapper for urllib (python3). Is it **proper** and **safe** to import module *in if*? ``` if self.response_encoding == 'gzip': import gzip ``` I didn't find any PEP about this code. However, it bothers me.
The Python standard library uses it, so it is most definitely proper and safe. See the [`os` module source](http://hg.python.org/cpython/file/2.7/Lib/os.py) for an excellent example: > ``` > if 'posix' in _names: > name = 'posix' > linesep = '\n' > from posix import * > try: > from posix import...
Interleave rows of two numpy arrays in Python
12,861,314
8
2012-10-12T14:34:02Z
12,861,513
11
2012-10-12T14:44:00Z
[ "python", "arrays", "numpy" ]
I wanted to interleave the rows of two numpy arrays of the same size. I came up with this solution. ``` # A and B are same-shaped arrays A = numpy.ones((4,3)) B = numpy.zeros_like(A) C = numpy.array(zip(A[::1], B[::1])).reshape(A.shape[0]*2, A.shape[1]) print C ``` Outputs ``` [[ 1. 1. 1.] [ 0. 0. 0.] [ 1. 1....
It is maybe a bit clearer to do: ``` A = np.ones((4,3)) B = np.zeros_like(A) C = np.empty((A.shape[0]+B.shape[0],A.shape[1])) C[::2,:] = A C[1::2,:] = B ``` and it's probably a bit faster as well, I'm guessing.
Python: how to make an histogram with equally *sized* bins
12,863,059
4
2012-10-12T16:07:11Z
12,863,239
8
2012-10-12T16:21:24Z
[ "python", "histogram", "spacing", "binning" ]
I have a set of data, and want to make an histogram of it. I need the bins to have the same *size*, by which I mean that they must contain the same number of objects, rather than the more common (numpy.histogram) problem of having *equally spaced* bins. This will naturally come at the expenses of the bins widths, which...
Using your example case (bins of 2 points, 6 total data points): ``` from scipy import stats bin_edges = stats.mstats.mquantiles(data, [0, 2./6, 4./6, 1]) >> array([1. , 1.24666667, 2.05333333, 2.12]) ```
Python pass instance of itself as an argument to another function
12,863,580
3
2012-10-12T16:44:06Z
12,863,608
11
2012-10-12T16:45:28Z
[ "python" ]
I have a UserModel class that will essentially do everything like login and update things. I'm trying to pass the instance of itself (the full class) as an argument to another function of another class. For example: (obviously not the code, but you get the idea) ``` from Car import CarFactory class UserModel: d...
``` c = CarFactory(car_id, self) ``` doesnt work? on a side note it would be `self.settings()` not `self.settings` ... unless you define settings to be a property
Tracing and Returning a Path in Depth First Search
12,864,004
11
2012-10-12T17:13:34Z
12,864,196
19
2012-10-12T17:25:32Z
[ "python", "algorithm", "artificial-intelligence" ]
So I have a problem that I want to use depth first search to solve, returning the first path that DFS finds. Here is my (incomplete) DFS function: ``` start = problem.getStartState() stack = Stack() visited = [] stack.push(start) if problem.isGoalState(problem.getStartState): return somethi...
You are right - you cannot simply return the stack, it indeed contains a lot of unvisited nodes. However, by maintaining a map (dictionary): `map:Vertex->Vertex` such that `parentMap[v] = the vertex we used to discover v`, you can get your path. The modification you will need to do is pretty much in the for loop: ``...
python matrix vs numpy matrix. What am I doing wrong?
12,864,368
2
2012-10-12T17:38:30Z
12,864,408
7
2012-10-12T17:41:49Z
[ "python", "numpy" ]
I am experimenting with some 3d rendering in Python. I keep reading that Python is soooooooo very slow! I simply MUST harness the C-awesomeness of Numpy for all the matrix stuff I can't do in the shaders! Otherwise nothing will work, yadda, yadda (paraphrasing here..). BUT: I did some testing! Here's a random matrix,...
You're inverting the matrix analytically (which is possible since you know the dimensions and since they're not too big). numpy must invert the matrix using some other (numerical) algorithm which works if the matrix is 4x4 as well as 10000x10000. In other words, the general problem is much harder than the simple 4x4 ca...
Numpy meshgrid points
12,864,445
2
2012-10-12T17:44:16Z
12,891,609
13
2012-10-15T08:11:37Z
[ "python", "numpy" ]
I want to create the list of points that would correspond to a grid. So if I want to create a grid of the region from (0,0) to (1,1), it would contain the points (0,0), (0,1), (1,0), (1,0). I know that that this can be done with the following code: ``` g = np.meshgrid([0,1],[0,1]) np.append(g[0].reshape(-1,1),g[1].re...
I just noticed that the documentation in numpy provides an even faster way to do this: ``` X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([X.ravel(), Y.ravel()]) ``` This can easily be generalized to more dimensions using the linked meshgrid2 function and mapping 'ravel' to the resulting grid. ...
Generating a url with the same GET parameters as the current page in a Django template
12,864,616
8
2012-10-12T17:58:40Z
12,864,701
11
2012-10-12T18:05:30Z
[ "python", "django" ]
I have a certain link to a url in a Django template. I would like to grab all the GET parameters of the current page url and add them to the url of the template's link. The current page might have zero GET parameters.
Include the [`django.core.context_processors.request`](https://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request) context processor in your `settings.py`, then use the `request` object in your template's links: ``` <a href="{% url 'my_url' %}?{{ request.META.QUERY_STRING }}"> ``` ...
python split a string with at least 2 whitespaces
12,866,631
10
2012-10-12T20:28:59Z
12,866,648
22
2012-10-12T20:30:20Z
[ "python", "split", "python-2.7" ]
I would like to split a string only where there are at least two or more whitespaces. For example ``` str = '10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1' print str.split() ``` Results: ``` ['10DEUTSCH', 'GGS', 'Neue', 'Heide', '25-27', 'Wahn-Heide', '-1', '-1'] ``` and i would like it to see ...
``` In [4]: import re In [5]: text = '10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1' In [7]: re.split(r'\s{2,}', text) Out[7]: ['10DEUTSCH', 'GGS Neue Heide 25-27', 'Wahn-Heide', '-1', '-1'] ```
Complex query with Django (posts from all friends)
12,866,920
6
2012-10-12T20:50:29Z
12,866,989
8
2012-10-12T20:56:31Z
[ "python", "django", "django-models", "django-filter" ]
I'm new to Python and Django, so please be patient with me. I have the following models: ``` class User(models.Model): name = models.CharField(max_length = 50) ... class Post(models.Model): userBy = models.ForeignKey(User, related_name='post_user') userWall = models.ForeignKey(User, related_name='receive...
``` from django.db.models import Q Post.objects.filter( \ Q(userBy=some_user) | \ Q(userBy__accept_user__user1=some_user) | \ Q(userBy__request_user__user2=some_user)).distinct() ``` **UPDATE** Sorry, that was my fault. I didn't pay attention to your `related_name` values. See updated code above. Using `...
Python MySQLDB: Get the result of fetchall in a list
12,867,140
15
2012-10-12T21:08:48Z
12,867,429
27
2012-10-12T21:35:12Z
[ "python", "django", "mysql-python" ]
I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries. For example, ``` cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor query = "Select id from bs" cursor.execute(query) row = cursor.fetchall() ``` Now, the problem is the res...
And what about list comprehensions? If result is `((123,), (234,), (345,))`: ``` >>> row = [item[0] for item in cursor.fetchall()] >>> row [123, 234, 345] ``` If result is `({'id': 123}, {'id': 234}, {'id': 345})`: ``` >>> row = [item['id'] for item in cursor.fetchall()] >>> row [123, 234, 345] ```
Python MySQLDB: Get the result of fetchall in a list
12,867,140
15
2012-10-12T21:08:48Z
18,598,771
8
2013-09-03T18:06:14Z
[ "python", "django", "mysql-python" ]
I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries. For example, ``` cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor query = "Select id from bs" cursor.execute(query) row = cursor.fetchall() ``` Now, the problem is the res...
I'm sure that after all this time, you've solved this problem, however, for some people who may not know how to get the values of a cursor as a dictionary using MySQLdb, you can use this method found [here](http://zetcode.com/db/mysqlpython/): ``` import MySQLdb as mdb con = mdb.connect('localhost', 'testuser', 'test...
pandas: count things
12,867,178
24
2012-10-12T21:12:33Z
12,874,054
45
2012-10-13T14:29:37Z
[ "python", "pandas" ]
In the following, male\_trips is a big pandas data frame and stations is a small pandas data frame. For each station id I'd like to know how many male trips took place. The following does the job, but takes a long time: ``` mc = [ sum( male_trips['start_station_id'] == id ) for id in stations['id'] ] ``` how should I...
I'd do like Vishal but instead of using sum() using size() to get a count of the number of rows allocated to each group of 'start\_station\_id'. So: ``` df = male_trips.groupby('start_station_id').size() ```
pandas: count things
12,867,178
24
2012-10-12T21:12:33Z
12,874,135
16
2012-10-13T14:39:56Z
[ "python", "pandas" ]
In the following, male\_trips is a big pandas data frame and stations is a small pandas data frame. For each station id I'd like to know how many male trips took place. The following does the job, but takes a long time: ``` mc = [ sum( male_trips['start_station_id'] == id ) for id in stations['id'] ] ``` how should I...
My answer below works in Pandas 0.7.3. Not sure about the new releases. This is what the `pandas.Series.value_counts` method is for: ``` count_series = male_trips.start_station_id.value_counts() ``` It should be straight-forward to then inspect `count_series` based on the values in `stations['id']`. However, if you ...
Why wasn't PyPy included in standard Python?
12,867,263
145
2012-10-12T21:20:35Z
12,867,292
60
2012-10-12T21:22:43Z
[ "python", "pypy" ]
I was looking at [PyPy](http://pypy.org/) and I was just wondering why it hasn't been adopted into the mainline Python distributions. Wouldn't things like JIT compilation and lower memory footprint greatly improve the speeds of all Python code? In short, what are the main drawbacks of PyPy that cause it to remain a se...
For one, it's [not 100% compatible](http://pypy.org/compat.html) with Python 2.x, and has only [preliminary support](http://pypy.org/py3donate.html) for 3.x. It's also not something that could be merged - The Python implementation that is provided by PyPy is generated using a framework they have created, which is extr...
Why wasn't PyPy included in standard Python?
12,867,263
145
2012-10-12T21:20:35Z
12,867,345
14
2012-10-12T21:27:27Z
[ "python", "pypy" ]
I was looking at [PyPy](http://pypy.org/) and I was just wondering why it hasn't been adopted into the mainline Python distributions. Wouldn't things like JIT compilation and lower memory footprint greatly improve the speeds of all Python code? In short, what are the main drawbacks of PyPy that cause it to remain a se...
One reason might be that according to [PyPy](http://pypy.org/features.html) site, it currently runs only on 32- and 64-bit Intel x86 architecture, while CPython runs on other platforms as well. This is probably due to platform-specific speed enhancements in PyPy. While speed is a good thing, people often want language ...
Why wasn't PyPy included in standard Python?
12,867,263
145
2012-10-12T21:20:35Z
12,867,349
45
2012-10-12T21:28:04Z
[ "python", "pypy" ]
I was looking at [PyPy](http://pypy.org/) and I was just wondering why it hasn't been adopted into the mainline Python distributions. Wouldn't things like JIT compilation and lower memory footprint greatly improve the speeds of all Python code? In short, what are the main drawbacks of PyPy that cause it to remain a se...
See [this video by Guido van Rossum](https://www.youtube.com/watch?v=EBRMq2Ioxsc#t=12m30s). He talks about the same question you asked at 12 min 33 secs. Highlights: * lack of Python 3 compatibility * lack of extension support * not appropriate as glue code * speed is not everything After all, he's the one to decide...
Why wasn't PyPy included in standard Python?
12,867,263
145
2012-10-12T21:20:35Z
12,867,428
231
2012-10-12T21:35:10Z
[ "python", "pypy" ]
I was looking at [PyPy](http://pypy.org/) and I was just wondering why it hasn't been adopted into the mainline Python distributions. Wouldn't things like JIT compilation and lower memory footprint greatly improve the speeds of all Python code? In short, what are the main drawbacks of PyPy that cause it to remain a se...
PyPy is not a fork of CPython, so it could never be merged directly into CPython. Theoretically the Python community could universally adopt PyPy, PyPy could be made the reference implementation, and CPython could be discontinued. However, PyPy has its own weaknesses: * CPython is easy to integrate with Python module...
Why wasn't PyPy included in standard Python?
12,867,263
145
2012-10-12T21:20:35Z
12,875,397
8
2012-10-13T17:52:09Z
[ "python", "pypy" ]
I was looking at [PyPy](http://pypy.org/) and I was just wondering why it hasn't been adopted into the mainline Python distributions. Wouldn't things like JIT compilation and lower memory footprint greatly improve the speeds of all Python code? In short, what are the main drawbacks of PyPy that cause it to remain a se...
I recommend watching this keynote by [David Beazley](http://pyvideo.org/video/659/keynote-david-beazley) for more insights. It answers your question by giving clarity on nature & intricacies of PyPy.
How to get elasticsearch to perform an exact match query?
12,867,578
3
2012-10-12T21:49:12Z
12,867,852
8
2012-10-12T22:16:18Z
[ "python", "elasticsearch" ]
This is a two-part question. My documents look like this: ``` {"url": "https://someurl.com", "content": "searchable content here", "hash": "c54cc9cdd4a79ca10a891b8d1b7783c295455040", "headings": "more searchable content", "title": "Page Title"} ``` My first question is how to retrieve all documents where 'ti...
You have to define a mapping for fields. If you are looking for exact values (case sensitive), you can set index property to `not_analyzed`. Something like : ``` "url" : {"type" : "string", "index" : "not_analyzed"} ```
Pyramid schema migrations
12,868,078
3
2012-10-12T22:41:11Z
12,869,461
12
2012-10-13T02:35:14Z
[ "python", "sqlalchemy", "pyramid", "database-migration", "sqlalchemy-migrate" ]
I'm using "vanilla" Pyramid 1.4 under Gentoo and I want to make changes to my tables and commit them without having to delete the table (and all of it's data) and then recreate it. I've heard the solution to this is schema migrations. Being a long-time Django user, I've been using `django-south`, but now I'm using Pyr...
While that doesn't directly answer your question: Did you consider [Alembic](https://alembic.readthedocs.org/en/latest/) instead, a new SQLAlchemy migration tool by Mike Bayer himself (SQLAlchemy's author)? Development on sqlalchemy-migrate seems to have stopped in January whereas Alembic is quite active.
Performance of Redis vs Disk in caching application
12,868,222
17
2012-10-12T22:59:04Z
12,871,072
17
2012-10-13T07:44:39Z
[ "python", "performance", "caching", "redis", "generator" ]
I wanted to create a redis cache in python, and as any self respecting scientist I made a bench mark to test the performance. Interestingly, redis did not fare so well. Either Python is doing something magic (storing the file) or my version of redis is stupendously slow. I don't know if this is because of the way my ...
This is an apples to oranges comparison. See <http://redis.io/topics/benchmarks> Redis is an efficient **remote** data store. Each time a command is executed on Redis, a message is sent to the Redis server, and if the client is synchronous, it blocks waiting for the reply. So beyond the cost of the command itself, you...
Looping through python regex matches
12,870,178
26
2012-10-13T05:12:51Z
12,870,218
41
2012-10-13T05:20:19Z
[ "python", "regex", "nested-loops" ]
This has to be easier than what I am running into. My problem is turning a string that looks like this: ``` ABC12DEF3G56HIJ7 ``` into ``` 12 * ABC 3 * DEF 56 * G 7 * HIJ ``` And I can't, for the life of me, design a correct set of loops using REGEX matching. The crux of the issue is that the code has to be comple...
Python's `re.findall` should work for you. [Live demo](http://codepad.org/70EHhuI1) ``` import re s = "ABC12DEF3G56HIJ7" pattern = re.compile(r'([A-Z]+)([0-9]+)') for (letters, numbers) in re.findall(pattern, s): print numbers, '*', letters ```
get object from redis without eval?
12,870,772
10
2012-10-13T06:56:12Z
12,871,168
23
2012-10-13T07:57:08Z
[ "python", "redis" ]
To get a key from memcache (using pylibmc), you do this: ``` client.set(key, {'object': 'dictionary'}, time=expire) client.get(key) ``` The same in redis is this: ``` redis.setex(key, expire, {'object': 'dictionary'}) eval(redis.get(key) or 'None') ``` That last line doesn't look right to me. redis only seems to re...
The difference is that while both memcached and redis only support string values, `pylibmc` serializes the values you send it using [`pickle`](http://docs.python.org/library/pickle.html), `redis-py` just converts them to string. If you want to do the same with redis, you can have your own functions to do the pickling ...
get object from redis without eval?
12,870,772
10
2012-10-13T06:56:12Z
20,295,984
7
2013-11-30T02:57:04Z
[ "python", "redis" ]
To get a key from memcache (using pylibmc), you do this: ``` client.set(key, {'object': 'dictionary'}, time=expire) client.get(key) ``` The same in redis is this: ``` redis.setex(key, expire, {'object': 'dictionary'}) eval(redis.get(key) or 'None') ``` That last line doesn't look right to me. redis only seems to re...
Or you can even **subclass Redis**: ``` import pickle from redis import StrictRedis class PickledRedis(StrictRedis): def get(self, name): pickled_value = super(PickledRedis, self).get(name) if pickled_value is None: return None return pickle.loads(pickled_value) def set(s...
What exactly is a "raw string regex" and how can you use it?
12,871,066
18
2012-10-13T07:42:51Z
13,836,171
32
2012-12-12T09:01:23Z
[ "python", "regex", "python-module" ]
From the python documentation on [regex](https://docs.python.org/library/re.html), regarding the `'\'` character: > The solution is to use Python’s raw string notation for regular > expression patterns; backslashes are not handled in any special way in > a string literal prefixed with `'r'`. So `r"\n"` is a two-char...
Zarkonnen's response does answer your question, but not directly. Let me try to be more direct, and see if I can grab the bounty from Zarkonnen. You will perhaps find this easier to understand if you stop using the terms "raw string regex" and "raw string patterns". These terms conflate two separate concepts: the repr...
Managing parameters of URL (Python Flask)
12,871,153
11
2012-10-13T07:55:14Z
12,871,250
27
2012-10-13T08:08:50Z
[ "python", "flask" ]
I want some search feature in my website. In the output page, I am getting all the results in single page. However, I want to distribute it to many pages (i.e. 100 searches/page). For that, I am passing a number of default searches in "urlfor" but it isn't working. I know I am making a small error but I am not catching...
Function parameters are mapped only to the route variables. That means in your case, the `show_results` function should have only one parameter and that's `labelname`. You don't even have to default it to `None`, because it always has to be set (otherwise the route won't match). In order to get the query parameters, u...
Python - Compress Ascii String
12,871,775
13
2012-10-13T09:26:07Z
12,872,743
20
2012-10-13T11:39:09Z
[ "python", "algorithm", "compression" ]
I'm looking for a way to compress an ascii-based string, any help? I also need to decompress it. I tried zlib but with no help. What can I do to compress the string into lesser length? code: ``` def compress(request): if request.POST: data = request.POST.get('input') if is_ascii(data): ...
Using compression will not always reduce the length of a string! Consider the following code; ``` import zlib import bz2 def comptest(s): print 'original length:', len(s) print 'zlib compressed length:', len(zlib.compress(s)) print 'bz2 compressed length:', len(bz2.compress(s)) ``` Let's try this on an ...
Parallel optimizations in SciPy
12,874,756
6
2012-10-13T15:55:28Z
12,905,481
7
2012-10-15T23:33:14Z
[ "python", "optimization", "scipy" ]
I have a simple function ``` def square(x, a=1): return [x**2 + a, 2*x] ``` I want to minimize it over `x`, for several parameters `a`. I currently have loops that, in spirit, do something like this: ``` In [89]: from scipy import optimize In [90]: res = optimize.minimize(square, 25, method='BFGS', jac=True) I...
Here's another try, based on [my original answer](http://stackoverflow.com/a/12874964/1015178) and the discussion that followed. As far as I know, the [scipy.optimize](http://docs.scipy.org/doc/scipy/reference/optimize.html) module is for functions with scalar or vector inputs and a scalar output, or "cost". Since yo...
Why do tuples with only one element get converted to strings?
12,876,177
20
2012-10-13T19:21:19Z
12,876,193
13
2012-10-13T19:23:50Z
[ "python" ]
In the below example I would expect all the elements to be tuples, why is a tuple converted to a string when it only contains a single string? ``` >>> a = [('a'), ('b'), ('c', 'd')] >>> a ['a', 'b', ('c', 'd')] >>> >>> for elem in a: ... print type(elem) ... <type 'str'> <type 'str'> <type 'tuple'> ```
Your first two examples are not tuples, they are strings. Single-item tuples require a trailing comma, as in: ``` >>> a = [('a',), ('b',), ('c', 'd')] >>> a [('a',), ('b',), ('c', 'd')] ```
Why do tuples with only one element get converted to strings?
12,876,177
20
2012-10-13T19:21:19Z
12,876,194
21
2012-10-13T19:24:00Z
[ "python" ]
In the below example I would expect all the elements to be tuples, why is a tuple converted to a string when it only contains a single string? ``` >>> a = [('a'), ('b'), ('c', 'd')] >>> a ['a', 'b', ('c', 'd')] >>> >>> for elem in a: ... print type(elem) ... <type 'str'> <type 'str'> <type 'tuple'> ```
Because those first two elements aren't tuples; they're just strings. The parenthesis don't automatically make them tuples. You have to add a comma after the string to indicate to python that it should be a tuple. ``` >>> type( ('a') ) <type 'str'> >>> type( ('a',) ) <type 'tuple'> ``` To fix your example code, add ...
Nested string to tuple python
12,876,974
3
2012-10-13T21:03:14Z
12,876,986
7
2012-10-13T21:05:55Z
[ "python" ]
my String looks like: ``` "('f', ('d', ('a', 'b')), 'g')" ``` I want to convert that to tuple. How can do that... I will use that in drawing a dendogram Edit: additional explanation: my code and output's (print's): ``` print type(myString) # <type 'str'> print myString ...
You can do this with [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval) - for example: ``` >>> import ast >>> s = "('f', ('d', ('a', 'b')), 'g')" >>> ast.literal_eval(s) ('f', ('d', ('a', 'b')), 'g') ``` The [documentation](http://docs.python.org/library/ast.html#ast.literal_eval) for that...
How to target a different host inside a Fabric command
12,877,168
4
2012-10-13T21:29:45Z
12,877,595
7
2012-10-13T22:27:58Z
[ "python", "fabric" ]
How do you specify a different target to run a command on other than the one that's currently set for the running Fabric command? I have a command download\_backup() that downloads a database backup file to the localhost from a remote host. Since it has to run locally, the host\_string is localhost. However, I need to...
you could use the settings context manager to change the host that a specific command runs on, independent of the host setting for the enclosing task. ``` from fabric.context_managers import settings with settings(host_string='remote_server'): run('ls -lart') ```
float64 with pandas to_csv
12,877,189
10
2012-10-13T21:31:34Z
12,882,439
28
2012-10-14T12:58:04Z
[ "python", "numpy", "pandas" ]
I'm reading a CSV with float numbers like this: ``` Bob,0.085 Alice,0.005 ``` And import into a dataframe, and write this dataframe to a new place ``` df = pd.read_csv(orig) df.to_csv(pandasfile) ``` Now this `pandasfile` has: ``` Bob,0.085000000000000006 Alice,0.0050000000000000001 ``` What happen? maybe I have ...
As mentioned in the comments, it is a general floating point problem. However you can use the `float_format` key word of `to_csv` to hide it: ``` df.to_csv('pandasfile.csv', float_format='%.3f') ``` or, if you don't want 0.0001 to be rounded to zero: ``` df.to_csv('pandasfile.csv', float_format='%g') ``` will give...
__repr__ vs repr
12,877,619
2
2012-10-13T22:32:06Z
12,877,751
9
2012-10-13T22:53:55Z
[ "python", "repr" ]
Is there a difference between the two methods? For example, ``` from datetime import date today = date(2012, 10, 13) repr(today) 'datetime.date(2012, 10, 13); today.__repr__() 'datetime.date(2012, 10, 13)' ``` They seem to do the same thing, but why would someone want to use the latter over the regular repr?
[`__repr__` method](http://docs.python.org/reference/datamodel.html#object.__repr__) is used to *implement* custom result for `repr()`. It is used by `repr()`, `str()` (if `__str__` is not defined). You shouldn't call `__repr__` explicitly. The difference is that repr() enforces the string as the returned type and rep...
Handle multiple socket connections
12,877,643
5
2012-10-13T22:36:21Z
12,877,966
14
2012-10-13T23:32:46Z
[ "python", "sockets", "client-server" ]
I'm writing a client-server app with Python. The idea is to have a main server and thousands of clients that will connect with it. The server will send randomly small files to the clients to be processed and clients must do the work and update its status to the server every minute. My problem with this is that for the ...
## Setting yourself up for success: access patterns matter What are some of design decisions that could affect how you implement a networking solution? You immediately begin to list down a few: * programmability * available memory * available processors * available bandwidth This looks like a great list. We want som...
Python: Pip command is not recognized
12,878,615
15
2012-10-14T01:44:12Z
12,882,318
12
2012-10-14T12:42:48Z
[ "python", "python-2.7", "pip" ]
Here is a screenshot I took. ![enter image description here](http://i.stack.imgur.com/t0jrI.png) When I try to use `pip` in command prompt I get the following error message: `pip` is not recognized as an internal or external command, operable program or batch file. I already checked this thread: [How to install pip ...
There is a space before the last path entry, right after the previous semicolon, that is causing the problem.
Need help understanding this error text in python:
12,879,117
3
2012-10-14T03:44:35Z
12,879,258
7
2012-10-14T04:17:20Z
[ "python", "tkinter", "traceback" ]
Ok so basically I wrote a not very pretty GUI that gives random simple math questions. It works just like I want it to. However the idle Shell spits out red at me every time I click enter. Despite that, like I said, it continues to function as I want it to. So I'm having trouble understanding why this specific part of ...
The error message says that Tkinter thinks it's getting the wrong number of args. Looking further back in the traceback we see this line caused the error: ``` File "C:\Python32\Python shit\csc242hw4\csc242hw4.py", line 55, in evaluate self.entry1.insert(END, self.new_problem()) ``` But that seems like the right ...
PyGame: Applying transparency to an image with alpha?
12,879,225
5
2012-10-14T04:10:44Z
16,177,852
12
2013-04-23T19:43:43Z
[ "python", "pygame", "alpha", "geometry-surface", "blit" ]
I want to display [an image with alpha](http://8bitboobs.com/stuff/alpha.png) with a specified transparency, but can't figure out how to do it. To elaborate on how I'm struggling with this, the blurb below is a slightly modified hunk of code from [this SO answer](http://stackoverflow.com/questions/12255558/how-to-use-...
Make a copy of the image you want to show (to not change the original) and use following: ``` self.image = self.original_image.copy() # this works on images with per pixel alpha too alpha = 128 self.image.fill((255, 255, 255, alpha), None, pygame.BLEND_RGBA_MULT) ``` Sorry, to not provide a full example.
Comparison of Python and R vocabularies
12,879,412
8
2012-10-14T04:52:43Z
12,879,462
13
2012-10-14T05:03:35Z
[ "python", "syntax", "programming-languages" ]
I was searching for language comparisons of R and Python and come across a comparison of vocabularies for R and JuliaLang. This is similar to what I was looking except for a different language. [Comparing R and JuliaLang vocabularies](http://www.johnmyleswhite.com/notebook/2012/04/09/comparing-julia-and-rs-vocabularie...
Check this sheet comparing Python, R and Matlab for numeric tools: <http://mathesaurus.sourceforge.net/matlab-python-xref.pdf> it assumes you have installed numpy, scipy and matplotlib and imported then with ``` from pylab import * ```
pymongo- How can I have distinct values for a field along with other query parameters
12,879,781
14
2012-10-14T06:15:51Z
12,883,331
27
2012-10-14T14:51:49Z
[ "python", "mongodb", "pymongo" ]
I am using pymongo and want to have distinct values for a field such that I can also pass other query parameters. For example, I have entries like: ``` { id = "my_id1" tags: [tag1, tag2, tag3], category: "movie", } { id = "my_id2" tags: [tag3, tag6, tag9], category: "tv", } { id = "my_id3" tags...
You have to make the `distinct` call [on the cursor](http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.distinct) returned from a `find` instead of on the collection: ``` tags = db.mycoll.find({"category": "movie"}).distinct("tags") ```
Selenium WebDriver (2.25) Timeout Not Working
12,880,024
9
2012-10-14T06:58:17Z
13,626,788
8
2012-11-29T13:21:46Z
[ "python", "selenium", "selenium-webdriver", "qa" ]
I think I've read all the Selenium timeout questions on Stack Overflow, yet neither implicit nor explicit timeout works in my Selenium webdriver 2.25 (Python 2.7 binding) and both "no\_timeout\_here =" lines would hang forever -- ``` browser = webdriver.Firefox() browser.implicitly_wait(6) browser.set_p...
If you are using Firefox 17 and Selenium 2.26.0 then you are hitting defect #4814: <http://code.google.com/p/selenium/issues/detail?id=4814>
Is there anything similar to Python function decorators in F# programming language?
12,880,529
5
2012-10-14T08:28:53Z
12,880,824
9
2012-10-14T09:16:40Z
[ "python", "f#", "decorator" ]
I am learning F# and have some experience with Python. I really like Python function decorators; I was just wondering if we have anything similar to it in F#?
There is no syntactic sugar for function decorators in F#. For types, you can use `StructuredFormatDisplay` attribute to customize printf contents. Here is an example from [F# 3.0 Sample Pack](http://fsharp3sample.codeplex.com/wikipage?title=Format): ``` [<StructuredFormatDisplayAttribute("MyType is {Contents}")>] ty...
Draw polygons more efficiently with matplotlib
12,881,848
16
2012-10-14T11:37:37Z
12,883,685
25
2012-10-14T15:32:29Z
[ "python", "numpy", "matplotlib", "scipy", "matplotlib-basemap" ]
I have a dateset of around 60000 shapes (with lat/lon coordinates of each corner) which I want to draw on a map using matplotlib and basemap. This is the way I am doing it at the moment: ``` for ii in range(len(data)): lons = np.array([data['lon1'][ii],data['lon3'][ii],data['lon4'][ii],data['lon2'][ii]],'f2') ...
You could consider creating Collections of polygons instead of individual polygons. The relevant docs can be found here: <http://matplotlib.org/api/collections_api.html> With a example worth picking appart here: <http://matplotlib.org/examples/api/collections_demo.html> As an example: ``` import numpy as np import m...
Python: pass statement in lambda form
12,883,088
14
2012-10-14T14:20:45Z
12,883,120
17
2012-10-14T14:24:23Z
[ "python", "lambda", "anonymous-function" ]
A Python newbie question, why is this syntax invalid: `lambda: pass`, while this: `def f(): pass` is correct? Thanks for your insight.
That is an error because after the colon you have to put the return value, so: ``` lambda: pass ``` is equal to: ``` def f(): return pass ``` that indeed makes no sense and produces a `SyntaxError` as well.
Python: pass statement in lambda form
12,883,088
14
2012-10-14T14:20:45Z
12,883,121
21
2012-10-14T14:24:29Z
[ "python", "lambda", "anonymous-function" ]
A Python newbie question, why is this syntax invalid: `lambda: pass`, while this: `def f(): pass` is correct? Thanks for your insight.
lambdas can only contain *expressions* - basically, something that can appear on the right-hand side of an assignment statement. `pass` is not an expression - it doesn't evaluate to a value, and `a = pass` is never legal. Another way of thinking about it is, because lambdas implicitly return the result of their body, ...
Python GTK3 Treeview Move Selection up or down
12,883,268
3
2012-10-14T14:43:09Z
12,887,704
7
2012-10-14T23:55:15Z
[ "python", "gtk", "gtk3", "gtktreeview" ]
How do I move a selection up or down in a Treeview? The idea is that I can have an up and down buttons to move the selection up a row or down a row. My Treeview is using a ListStore. Not sure if that matters.
First off, I will be using C code as that's what I'm familiar with. Should you have problems translating it to Python, then say so, and I will do my best to help. The class you want to use for this is `GtkTreeSelection`. Basically, what you do is: 1. Get the selection object of the view (`gtk_tree_view_get_selection`...
Remove the first word in a Python string?
12,883,376
12
2012-10-14T14:57:04Z
12,883,390
31
2012-10-14T14:59:41Z
[ "python", "string" ]
What's the quickest/cleanest way to remove the first word of a string? I know I can use `split` and then iterate on the array to get my string. But I'm pretty sure it's not the nicest way to do it. Ps: I'm quite new to python and I don't know every trick. Thanks in advance for your help.
I think the best way is to split, but limit it to only one split by providing [`maxsplit`](http://docs.python.org/library/stdtypes.html#str.split) parameter: ``` >>> s = 'word1 word2 word3' >>> s.split(' ', 1) ['word1', 'word2 word3'] >>> s.split(' ', 1)[1] 'word2 word3' ```
Remove the first word in a Python string?
12,883,376
12
2012-10-14T14:57:04Z
12,883,445
8
2012-10-14T15:08:07Z
[ "python", "string" ]
What's the quickest/cleanest way to remove the first word of a string? I know I can use `split` and then iterate on the array to get my string. But I'm pretty sure it's not the nicest way to do it. Ps: I'm quite new to python and I don't know every trick. Thanks in advance for your help.
A naive solution would be: ``` text = "funny cheese shop" print text.partition(' ')[2] # cheese shop ``` However, that won't work in the following (admittedly contrived) example: ``` text = "Hi,nice people" print text.partition(' ')[2] # people ``` To handle this, you're going to need regular expressions: ``` impo...
How to parse restructuredtext in python?
12,883,428
10
2012-10-14T15:05:40Z
12,883,499
13
2012-10-14T15:14:31Z
[ "python", "parsing", "dom", "restructuredtext" ]
Is there any module that can parse restructuredtext into a tree model? Can docutils or sphinx do this?
[Docutils](https://pypi.python.org/pypi/docutils) does indeed contain the tools to do this. What you probably want is the parser at `docutils.parsers.rst` See [this page](http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document) for details on what is involved. There are also some examples at [`docu...
BeautifulSoup can't parse a webpage?
12,886,619
3
2012-10-14T21:18:02Z
12,886,809
7
2012-10-14T21:41:32Z
[ "python", "parsing", "beautifulsoup" ]
I am using beautiful soup for parsing webpage now, I've heard it's very famous and good, but it doesn't seems works properly. Here's what I did ``` import urllib2 from bs4 import BeautifulSoup page = urllib2.urlopen("http://www.cnn.com/2012/10/14/us/skydiver-record-attempt/index.html?hpt=hp_t1") soup = BeautifulSoup...
You cannot use BeautifulSoup nor any HTML parser to read web pages. You are never guaranteed that web page is a well formed document. Let me explain what is happening in this given case. On that page there is this INLINE javascript: ``` var str="<script src='http://widgets.outbrain.com/outbrainWidget.js'; type='text/...
BeautifulSoup can't parse a webpage?
12,886,619
3
2012-10-14T21:18:02Z
12,886,926
10
2012-10-14T21:54:34Z
[ "python", "parsing", "beautifulsoup" ]
I am using beautiful soup for parsing webpage now, I've heard it's very famous and good, but it doesn't seems works properly. Here's what I did ``` import urllib2 from bs4 import BeautifulSoup page = urllib2.urlopen("http://www.cnn.com/2012/10/14/us/skydiver-record-attempt/index.html?hpt=hp_t1") soup = BeautifulSoup...
From [the docs](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser): > If you can, I recommend you install and use lxml for speed. If you’re > using a version of Python 2 earlier than 2.7.3, or a version of Python > 3 earlier than 3.2.2, it’s essential that you install lxml or > html5lib–P...
How to unzip file in Python on all OSes?
12,886,768
25
2012-10-14T21:37:35Z
12,886,818
40
2012-10-14T21:42:58Z
[ "python", "zip" ]
Is there a simple Python function that would allow unzipping a .zip file like so?: ``` unzip(ZipSource, DestinationDirectory) ``` I need the solution to act the same on Windows, Mac and Linux: always produce a file if the zip is a file, directory if the zip is a directory, and directory if the zip is multiple files; ...
Use the [`zipfile`](http://docs.python.org/library/zipfile.html) module in the standard library: ``` import zipfile,os.path def unzip(source_filename, dest_dir): with zipfile.ZipFile(source_filename) as zf: for member in zf.infolist(): # Path traversal defense copied from # http://h...
Opening spreadsheet returns InMemoryUploadedFile
12,886,842
5
2012-10-14T21:45:59Z
12,886,981
10
2012-10-14T22:01:40Z
[ "python", "django" ]
I have a user uploading a file to a website and I need to parse the spreadsheet. Here is my code: ``` input_file = request.FILES.get('file-upload') wb = xlrd.open_workbook(input_file) ``` The error I keep getting is: ``` TypeError at /upload_spreadsheet/ coercing to Unicode: need string or buffer, InMemoryUploadedFi...
You can dump the InMemoryUploadedFile to a temp file before opening with xlrd. ``` try: fd, tmp = tempfile.mkstemp() with os.fdopen(fd, 'w') as out: out.write(input_file.read()) wb = xlrd.open_workbook(tmp) ... # do what you have to do finally: os.unlink(tmp) # delete the temp file no mat...
Python 3: Getting TypeError: Slices must be integers... But they are I believe
12,888,320
4
2012-10-15T01:50:26Z
12,888,348
11
2012-10-15T01:56:11Z
[ "python", "python-3.x", "integer", "slice" ]
I am trying to write a function called "middle" that takes the middle 3 digits of odd numbers, or the middle 4 digits of even numbers. If the number is less than 5 digits, it just returns the whole number. Here is my work: ``` def middle(x): mystring=str(x) length=len(mystring) if len(mystring)<=5: ...
You're using Python 3, I bet. [And you are -- I just noticed the tag this second.] `length/2` will be a float: ``` return (mystring[((length/2)-1):((length/2)+3)]) ``` use `length//2` throughout instead. Note this will happen even if `length` is even: ``` >>> s = 'abcd' >>> len(s) 4 >>> len(s)/2 2.0 >>> s[len(s...
MySQL LOAD DATA LOCAL INFILE Python
12,890,098
18
2012-10-15T06:02:49Z
13,154,531
54
2012-10-31T09:13:07Z
[ "python", "mysql" ]
I am running Ubuntu 12.04 and MySQL 5.5 Alright so here is the problem: Using the MySQLDB module for Python, the SQL command: ``` cursor.execute("LOAD DATA LOCAL INFILE 'example.csv' INTO TABLE 'example_mysql_table' TERMINATED BY ',';") ``` Doesn't work. I get `ERROR 1148: The used command is not allowed with this M...
After spending hours on trying all kinds of settings in the config files and restarting mysql dozens of times I came up with this which seems to solve the problem (could not find this in any documentation anywhere) ``` MySQLdb.connect(server, username, password, database, local_infile = 1) ```
Tornado - '_xsrf' argument missing from POST
12,890,105
9
2012-10-15T06:03:21Z
12,917,054
15
2012-10-16T14:31:35Z
[ "python", "python-3.x", "tornado" ]
As can be seen in the following code, I have a `GET` for registration, that delegates its work to `POST`. ``` class RegistrationHandler(tornado.web.RequestHandler): def get(self): s = """ <h1>Register</h1> <form method="post" action="/register"> <div> ...
I imagine you have Cross-site request forgery cookies enabled in your settings (by default it is on). [Tornado's XSRF is here](http://tornado.readthedocs.org/en/latest/guide/security.html#cross-site-request-forgery-protection) To fix this turn it off in your settings: ``` settings = { "xsrf_cookies": False, } ``...
Interactive selection of series in a matplotlib plot
12,891,860
7
2012-10-15T08:31:34Z
13,370,994
7
2012-11-14T00:00:16Z
[ "python", "matplotlib" ]
I have been looking for a way to be able to select which series are visible on a plot, after a plot is created. I need this as i often have plots with many series. they are too many to plot at the same time, and i need to quickly and interactively select which series are visible. Ideally there will be a window with a ...
It all depends on how much effort you are willing to do and what the exact requirements are, but you can bet it has already been implemented somewhere :-) If the aim is mainly to not clutter the image, it may be sufficient to use the built-in capabilities; you can find relevant code in the matplotlib examples library:...
Adding spaces to items in list (Python)
12,892,698
2
2012-10-15T09:24:45Z
12,892,719
7
2012-10-15T09:25:49Z
[ "python", "string", "list", "space" ]
I'm a Python noob and I need some help for a simple problem. What I need to do is create a list with 3 items and add spaces before and after every item. For example:`l1 = ['a', 'bb', 'c']` should be transformed into: `[' a ',' bb ',' c ']` I was trying to write something like this: ``` lst = ['a', 'bb', 'c'] for a...
As always, use a [list comprehension](http://docs.python.org/reference/expressions.html#list-displays): ``` lst = [' {0} '.format(elem) for elem in lst] ``` This applies a [string formatting operation](http://docs.python.org/library/string.html#formatstrings) to each element, adding the spaces. If you use python 2.7 ...
Get all tags from taggit
12,894,154
8
2012-10-15T10:56:56Z
12,894,243
13
2012-10-15T11:03:02Z
[ "python", "django", "django-models", "django-taggit" ]
How to get all the (unique) tags from django-taggit? I would like to display all the tags in a side bar. Currently I am able to get all the tags for a particular post, but now I need to get all the unique tags in the entire blog. code in models.py: ``` from django.db import models from taggit.managers import Taggable...
You can use [`all()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.all) to get all the tags in your database: ``` from taggit.models import Tag tags = Tag.objects.all() ``` If you need a complete solution, have a look at [`django-taggit-templatetags`](https://github.com/...
django test database is not created with utf8
12,894,658
7
2012-10-15T11:27:03Z
16,701,052
7
2013-05-22T20:30:03Z
[ "python", "mysql", "django", "utf-8" ]
I am using `utf-8` general case insensitive for for mysql database, but `django` creates a test db with `latin collation` I have set this: ``` TEST_CHARSET="utf8_general_ci" TEST_COLLATION="utf8_general_ci" ``` In the settings file, but to no avail. What else should i do?
in settings add: ``` DATABASES = { 'default': { ... 'TEST_CHARSET': "utf8", 'TEST_COLLATION': "utf8_general_ci", } } ```
django test database is not created with utf8
12,894,658
7
2012-10-15T11:27:03Z
31,903,613
9
2015-08-09T11:14:39Z
[ "python", "mysql", "django", "utf-8" ]
I am using `utf-8` general case insensitive for for mysql database, but `django` creates a test db with `latin collation` I have set this: ``` TEST_CHARSET="utf8_general_ci" TEST_COLLATION="utf8_general_ci" ``` In the settings file, but to no avail. What else should i do?
`TEST_CHARSET` and `TEST_COLLATION` are renamed to `CHARSET` and `COLLATION` and moved to `TEST` dictionary in Django 1.8: ``` DATABASES = { ... 'TEST': { 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } } ```
Get parent directory of a specific file
12,894,815
5
2012-10-15T11:36:49Z
12,894,871
8
2012-10-15T11:41:10Z
[ "python" ]
There is a file `a.py`. The location is `/home/user/projects/project1/xxx/a.py`. If I call `os.getcwd()`, it gives me `/home/user/projects/project1/xxx/`. But I want to reach `/home/user/projects/project1`. How can i do this in Python? **Edit :** I think i must be more clear. i want this for my Django project. i us...
``` >>> import os >>> os.getcwd() '/tmp/test' >>> os.chdir('..') >>> os.getcwd() '/tmp' >>> ``` The dot dot (`..`) represents the parent directory. Because relative path names specify a path starting in the current directory. See the documentation of [`os.chdir`](http://docs.python.org/library/os.html?highlight=os.ch...
Get parent directory of a specific file
12,894,815
5
2012-10-15T11:36:49Z
12,894,892
12
2012-10-15T11:42:09Z
[ "python" ]
There is a file `a.py`. The location is `/home/user/projects/project1/xxx/a.py`. If I call `os.getcwd()`, it gives me `/home/user/projects/project1/xxx/`. But I want to reach `/home/user/projects/project1`. How can i do this in Python? **Edit :** I think i must be more clear. i want this for my Django project. i us...
``` from os.path import dirname print(dirname(dirname(__file__))) ``` Each time you call `dirname` it gives you parent directory. Call as many times as necessary. Alternatively you can do following: ``` normpath(join(path1, '..', '..')) ```
Python: print list of list in a specified format
12,895,694
3
2012-10-15T12:28:43Z
12,895,740
7
2012-10-15T12:31:07Z
[ "python", "list", "python-2.7" ]
I have a list of list `l = [['a','b', 'c'], 'd','e', ['f', 'g']]`. It is not always necessary that list elements are going to be alphabets. Now, I used the below code: ``` >>> index =1 >>> for i in l: ... if isinstance(i, list): ... for j in i : ... print index, j ... ...
You can do this very easily with [`itertools.chain.from_iterable()`](http://docs.python.org/py3k/library/itertools.html#itertools.chain.from_iterable) and [`enumerate()`](http://docs.python.org/py3k/library/functions.html#enumerate): ``` >>> import itertools >>> l = [['a','b', 'c'], 'd','e', ['f', 'g']] >>> for index,...
Deploy pure python to heroku
12,895,896
2
2012-10-15T12:41:42Z
12,908,393
11
2012-10-16T05:57:37Z
[ "python", "heroku" ]
I "finished" a little python project and I want to deploy it on heroku [GitHub page](https://github.com/ttouch/panager). I want to execute: python2 main.py -i json-rpc in order to have the json-rpc server listening for connections but I get the following error when pushing to heroku: > $ git push heroku master Countin...
What you might want to try doing is creating a Procfile. The full filename is `Procfile`, no extension, and it goes in the main directory of your project folder. The content of that file would be: ``` web: python main.py -i json-rpc ``` Give that a shot and see if it works. Alternatively, you may have forgotten to ...
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
12,897,419
22
2012-10-15T14:07:47Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
what type is your output variable? Python [sets](https://docs.python.org/2/library/sets.html) are what you just need. Declare output like this: ``` output = set([]) # initialize an empty set ``` and you're ready to go adding elements with output.add(elem) and be sure they're unique. Warning: sets DO NOT preserve th...
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
12,897,477
339
2012-10-15T14:11:06Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
First declare your list properly, separated by commas You can get the unique values by converting the list to a set ``` mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] myset = set(mylist) print myset ``` If you use it further as a list, you should convert it back to list by d...
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
12,897,491
41
2012-10-15T14:11:38Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
The exemple you provide do not correspond to lists in Python. This ressemble nested dict, which is probably not what you intended. A python list: ``` a = ['a', 'b', 'c', 'd', 'b'] ``` To get unique items, just transform it into a set (which you can transform back again into a list if required): ``` b = set(a) print...
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
27,305,828
79
2014-12-04T23:02:17Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
To be consistent with the type I would use: ``` mylist = list(set(mylist)) ```
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
28,365,630
15
2015-02-06T12:16:09Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
set - unordered collection of unique elements. List of elements can be passed to set's constructor. So, pass list with duplicate elements, we get set with unique elements and transform it back to list then get list with unique elements. I can say nothing about performance and memory overhead, but I hope, it's not so im...
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
29,980,767
9
2015-05-01T02:20:15Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
Same order unique list using only a list compression. ``` > my_list = [1, 2, 1, 3, 2, 4, 3, 5, 4, 3, 2, 3, 1] > unique_list = [ > e > for i, e in enumerate(my_list) > if my_list.index(e) == i > ] > unique_list [1, 2, 3, 4, 5] ``` `enumerates` gives the index `i` and element `e` as a `tuple`. `my_list.index`...
Get unique values from a list in python
12,897,374
201
2012-10-15T14:05:37Z
37,163,210
8
2016-05-11T12:49:52Z
[ "python" ]
I want to get the unique values from the following list: ``` [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] ``` The output which I require is: ``` [u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow'] ``` I tried the following code: ``` output = [] for x in trends: if x no...
If we need to keep the elements order, how about this: ``` used = [] mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow'] unique = [x for x in mylist if x not in used and (used.append(x) or True)] ``` And one more solution using `reduce` and without the temporary `used` var. ``` ...
Replacing a sublist with another sublist in python
12,898,023
5
2012-10-15T14:41:19Z
12,898,180
8
2012-10-15T14:49:39Z
[ "python", "list" ]
I want to replace a sub-list from list `a`, with another sub-list. Something like this: ``` a=[1,3,5,10,13] ``` Lets say I want to take a sublist like: ``` a_sub=[3,5,10] ``` and replace it with ``` b_sub=[9,7] ``` so the final result will be ``` print(a) >>> [1,9,7,13] ``` Any suggestions?
You can do this nicely with list slicing: ``` >>> a=[1, 3, 5, 10, 13] >>> a[1:4] = [9, 7] >>> a [1, 9, 7, 13] ``` So how do we get the indices here? ``` def find_sublists(seq, sublist): length = len(sublist) for index, value in enumerate(seq): if value == sublist[0] and seq[index:index+length] == sub...
Python MySQLdb converters isn't working
12,898,516
5
2012-10-15T15:07:15Z
12,898,650
8
2012-10-15T15:14:45Z
[ "python", "sql", "converter", "long-integer", "mysql-python" ]
I'm trying to run an ETL script using python and MySQLdb but I'm stuck with the results from my initial extract query. The types returned are all Long and Decimal when I want Int and Float. I've searched around for a few hours trying to get an answer to this without any success. ``` database = MySQLdb.connect(host='db...
Your conversions dictionary needs to use MySQL types for the keys, not Python types: ``` import _mysql from MySQLdb.constants import FIELD_TYPE my_conv = { FIELD_TYPE.LONG: int } db=_mysql.connect(conv=my_con) ``` From <http://mysql-python.sourceforge.net/MySQLdb.html> It appears you need to use `_mysql.connect()`...
Partial matching GAE search API
12,899,083
11
2012-10-15T15:38:08Z
13,171,181
22
2012-11-01T04:57:18Z
[ "python", "google-app-engine", "search", "autocomplete", "webapp2" ]
Using the [GAE search API](https://developers.google.com/appengine/docs/python/search/) is it possible to search for a partial match? I'm trying to create autocomplete functionality where the term would be a partial word. eg. > > b > > bui > > build would all return "building". How is this possible with GAE?
Though LIKE statement (partial match) is not supported in Full Text Search, but you could hack around it. First, tokenize the data string for all possible substrings (hello = h, he, hel, lo, etc.) ``` def tokenize_autocomplete(phrase): a = [] for word in phrase.split(): j = 1 while True: ...
How can I run a celery periodic task from the shell manually?
12,900,023
36
2012-10-15T16:34:53Z
12,900,126
41
2012-10-15T16:40:28Z
[ "python", "django", "celery", "django-celery", "celery-task" ]
I'm using celery and django-celery. I have defined a periodic task that I'd like to test. Is it possible to run the periodic task from the shell manually so that I view the console output?
Have you tried just running the task from the Django shell? You can use the `.apply` method of a task to ensure that it is run eagerly and locally. Assuming the task is called `my_task` in Django app `myapp` in a `tasks` submodule: ``` $ python manage.py shell >>> from myapp.tasks import my_task >>> eager_result = my...
Python PIL incorrectly decoding TIFF colors (using incorrect colorspace)?
12,900,656
12
2012-10-15T17:13:00Z
12,947,573
8
2012-10-18T05:15:59Z
[ "python", "python-imaging-library", "tiff" ]
When I use `PIL==1.1.7` to load TIFF images, it seems to get the colorspace wrong: ![bad colorspace conversion](http://i.stack.imgur.com/GDaMq.png) What's going on? * The `.tiff` was created using `convert test.jpg test.tiff` (but seems to happen with other tiff files too) * It can be found at: <http://hul.wolever.n...
This is most likely due to the fact that your TIFF images contain compressed JPEG data generated by Adobe Photoshop, that uses a special marker to indicate the correct colorspace. I guess PIL doesn't know this marker (at least, in a TIFF-embedded JPEG), so it assumes that the image is in YCbCr colorspace (which we can ...
Python "setup.py develop": is it possible to create ".egg-info" folder not in source code folder?
12,901,776
12
2012-10-15T18:29:36Z
13,538,687
15
2012-11-24T05:51:06Z
[ "python", "setuptools", "distutils" ]
Python has ability to "pseudoinstall" a package by running it's `setup.py` script with `develop` instead of `install`. This modifies python environment so package can be imported from it's current location (it's not copied into `site-package` directory). This allows to develop packages that are used by other packages: ...
`setup.py develop` creates a python egg, in-place; it does **not** *[modify the] python environment so package can be imported from it's current location*. You still have to either add it's location to the python search path or use the directory it is placed in as the current directory. It is the job of the `develop` ...
Data structure to perform fast GPS lookups?
12,902,264
4
2012-10-15T19:02:28Z
12,902,327
7
2012-10-15T19:06:26Z
[ "java", "python", "data-structures", "gps", "gis" ]
I have a text file (UTF-8, ~50K lines) with city names and GPS coordinates. Example lines: ``` San Pedro locality -3367 -5968 Argentina Buenos Aires San Pedro Talagante locality -3366 -7093 Chile Metropolitana Talagante Peñaflor locality -3362 -7092 Chile Metropolitana Tal...
What you are looking for is a [KD tree](http://en.wikipedia.org/wiki/K-d_tree). I found a link to a [python implementation](http://code.google.com/p/python-kdtree/) for it here, but I am not python developer, never tried it. The KD tree will support for square root complexity of finding the nearest point in a plane, wh...
Read from a gzip file in python
12,902,540
14
2012-10-15T19:21:25Z
13,083,308
20
2012-10-26T08:22:11Z
[ "python", "python-2.7", "gzip" ]
I've just make excises of gzip on python. ``` import gzip f=gzip.open('Onlyfinnaly.log.gz','rb') file_content=f.read() print file_content ``` And I get no output on the screen. As a beginner of python, I'm wondering what should I do if I want to read the content of the file in the gzip file. Thank you.
Try gzipping some data through the gzip libary like this... ``` import gzip content = "Lots of content here" f = gzip.open('Onlyfinnaly.log.gz', 'wb') f.write(content) f.close() ``` ... then run your code as posted ... ``` import gzip f=gzip.open('Onlyfinnaly.log.gz','rb') file_content=f.read() print file_content ``...
getting the row and column numbers from coordinate value in openpyxl
12,902,621
11
2012-10-15T19:26:23Z
12,902,801
12
2012-10-15T19:39:30Z
[ "python", "openpyxl" ]
I'm trying to covert a coordinate value in excel to a row number and column number in openpyxl. For example if my cell coordinate is D4 I want to find the corresponding row and column numbers to use for future operations, in the case row = 3, column = 3. I can get the row number easily using `ws.cell('D4').row` which ...
What you want is openpyxl.cell.coordinate\_from\_string() and openpyxl.cell.column\_index\_from\_string() ``` from openpyxl.cell import coordinate_from_string, column_index_from_string xy = coordinate_from_string('A4') # returns ('A',4) col = column_index_from_string(xy[0]) # returns 1 row = xy[1] ```
Where is BeautifulSoup4 hiding?
12,902,783
8
2012-10-15T19:38:33Z
12,902,800
20
2012-10-15T19:39:25Z
[ "python", "beautifulsoup", "pip" ]
I did `sudo pip install BeautifulSoup4` and got an awfully optimistic response: ``` Downloading/unpacking beautifulsoup4 Running setup.py egg_info for package beautifulsoup4 Installing collected packages: beautifulsoup4 Running setup.py install for beautifulsoup4 Successfully installed beautifulsoup4 Cleaning up.....
Try `import bs4`. It's unfortunate there's no correspondence between PyPI package name and import name. After that the class names are the same as before eg. `soup = bs4.BeautifulSoup(doc)` will work. If that still doesn't work, try `pip install` again and note the path to the package install. Then in your python cons...
Python mySQL - escaping quotes
12,902,862
7
2012-10-15T19:43:51Z
12,902,951
30
2012-10-15T19:50:16Z
[ "python", "mysql" ]
I have seen this question asked in various ways on this website, but none of them exactly addressed my issue. I have an sql statement with single quotes inside it, and am trying to use recommended practices before making database queries with it. So the statement is like ``` val2="abc 'dostuff'" sql="INSERT INTO TAB...
Use parameters instead of string interpolation to ensure that your values are properly escaped by the database connector: ``` sql = "INSERT INTO TABLE_A(COL_A,COL_B) VALUES(%s, %s)" a_cursor.execute(sql, (val1, val2)) ``` The mysqldb sql parameter style uses the same syntax as used by the python string formatting ope...
Allow Python list append method to return the new list
12,902,980
14
2012-10-15T19:52:17Z
12,903,015
36
2012-10-15T19:54:17Z
[ "python", "list", "append" ]
I want to do something like this: ``` myList = [10,20,30] yourList = myList.append (40) ``` Unfortunately, list append does not return the modified list. **So, how can I allow `append` to return the new list?**
Don't use append but concatenation instead: ``` yourList = myList + [40] ``` This returns a *new* list; `myList` will not be affected. If you need to have `myList` affected *as well* either use `.append()` anyway, then assign `yourList` separately from (a copy of) `myList`.
puzzling python index error
12,903,320
2
2012-10-15T20:17:51Z
12,903,334
9
2012-10-15T20:18:49Z
[ "python", "python-2.7" ]
Here is a piece of python code ("result" is a nested list created before) ``` for i in range(len(result)-1): try: result[i][3]=0 result[i+i][0]=0 except IndexError: print "fail", result[i][3], result[i+1][0], i, len(result) return result ``` which, to my astonishment, quite often print...
You are accessing the index `i + i`, *not* `i + 1`: ``` result[i+i][0]=0 ``` This means that by the time you reach `i // 2 + 1` you have an index error, whatever the size of your list.
Python - User-defined classes have __cmp__() and __hash__() methods by default? Or?
12,903,620
13
2012-10-15T20:38:27Z
12,903,694
9
2012-10-15T20:44:27Z
[ "python", "methods", "comparison", "default" ]
In the python [docs](http://docs.python.org/reference/datamodel.html#object.__hash__) ([yeah, I have this thing with the docs](http://stackoverflow.com/questions/10674428/python-supports-a-limited-form-of-multiple-inheritance-in-what-way-limited)) it says that: > User-defined classes have `__cmp__()` and `__hash__()` ...
The documentation is a bit misleading. To get the full story, you have to read up on [`__cmp__`](http://docs.python.org/reference/datamodel.html#object.__cmp__), namely this part: > If no `__cmp__()`, `__eq__()` or `__ne__()` operation is defined, class instances are compared by object identity (“address”). So, b...
Python IMAP: =?utf-8?Q? in subject string
12,903,893
8
2012-10-15T20:59:37Z
12,904,228
17
2012-10-15T21:22:32Z
[ "python", "email", "character-encoding", "imap", "mime" ]
I am displaying new email with `IMAP`, and everything looks fine, except for one message subject shows as: `=?utf-8?Q?Subject?=` How can I fix it?
In MIME terminology, those encoded chunks are called encoded-words. You can decode them like this: ``` import email.Header text, encoding = email.Header.decode_header('=?utf-8?Q?Subject?=')[0] ``` Check out the docs for [`email.Header`](http://docs.python.org/library/email.header.html) for more details.
how to set "camera position" for 3d plots using python/matplotlib?
12,904,912
59
2012-10-15T22:25:18Z
12,905,458
76
2012-10-15T23:31:00Z
[ "python", "matplotlib", "mplot3d" ]
I'm learning how to use mplot3d to produce nice plots of 3d data and I'm pretty happy so far. What I am trying to do at the moment is a little animation of a rotating surface. For that purpose, I need to set a camera position for the 3D projection. I guess this must be possible since a surface can be rotated using the ...
By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. I've used the below script to first create the plot, then I determined a good elevation, or `elev`, from which to view my plot. I then adjusted the azimuth angle, or `azim`, to vary the full 360...
Python Difference between x = x+1 and x += 1
12,905,338
8
2012-10-15T23:17:29Z
12,905,374
10
2012-10-15T23:21:53Z
[ "python" ]
In Python, is there any difference (semantics, efficiency, etc.) between writing `x = x+1` and `x += 1`?
Yes. Depending on how the class of `x` is coded, the short form has the option to modify x in-place, instead of creating a new object representing the sum and rebinding it back to the same name. This has an implication if you have multiple variables all referring to the same object - eg, with lists: ``` >>> a = b = []...