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
Image.open() cannot identify image file - Python?
19,230,991
12
2013-10-07T17:24:53Z
22,350,586
13
2014-03-12T11:49:08Z
[ "python", "python-imaging-library" ]
I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run: ``` import numpy as np import scipy as sp import math as mt import matplotlib.pyplot as plt import Image import random # (0, 1) is N SCALE = 2.2666 # the scale is chosen to be 1 m = 2.266666666 pixels MIN_LENG...
So after struggling with this issue for quite some time, this is what could help you: ``` from PIL import Image ``` instead of ``` import Image ``` Also, if your Image file is not loading and you're getting an error "No file or directory" then you should do this: ``` path=r'C:\ABC\Users\Pictures\image.jpg' ``` an...
'module' object has no attribute 'now' will trying to create a CSV
19,231,458
5
2013-10-07T17:56:05Z
19,231,474
31
2013-10-07T17:57:13Z
[ "python", "django", "csv", "django-views" ]
Hello I'm having problems importing to csv, I get that error, the problem is that I have the same code running in other machine and it runs perfectly. What am I missing do I need to install an other library for this?. ``` def exportar_a_csv_grl(request): #Fecha actual hoy = datetime.now().date() #Creado el...
You probably have ``` import datetime ``` change that to ``` from datetime import datetime ``` Demo: ``` >>> import datetime >>> datetime.now() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'now' >>> from datetime import datetime >>> datet...
Convert unix time to readable date in pandas DataFrame
19,231,871
24
2013-10-07T18:21:02Z
19,231,939
42
2013-10-07T18:25:59Z
[ "python", "pandas", "unix-timestamp", "dataframe" ]
I have a data frame with unix times and prices in it. I want to convert the index column so that it shows in human readable dates. So for instance i have "date" as 1349633705 in the index column but I'd want it to show as 10/07/2012 (or at least 10/07/2012 18:15). For some context, here is the code I'm working with and...
These appear to be seconds since epoch. ``` In [20]: df = DataFrame(data['values']) In [21]: df.columns = ["date","price"] In [22]: df Out[22]: <class 'pandas.core.frame.DataFrame'> Int64Index: 358 entries, 0 to 357 Data columns (total 2 columns): date 358 non-null values price 358 non-null values dtypes: ...
Anaconda: Unable to import pylab
19,231,944
7
2013-10-07T18:26:27Z
19,987,452
10
2013-11-14T20:14:11Z
[ "python", "matplotlib", "pip", "sip", "anaconda" ]
I am unable to `import pylab` using the latest version of [Anaconda](https://store.continuum.io/cshop/anaconda/) (Linux 64 bit). Other packages seem to work fine. (Note: I don't have `sudo` access) ``` In [1]: import pylab as pl --------------------------------------------------------------------------- ImportError ...
Just had this problem and it was related to which qt backend matplotlib was trying to use, try: ``` import PyQt4 ``` If you don't have PyQt4 you probably have PySide ``` import PySide ``` If this is the case you need to set the `matplotlib.rcParams['backend.qt4'] == 'PySide'` not `'PyQt4'`. You can also do this in ...
'ascii' codec can't encode character u'\u2013' in position 9: ordinal not in range(128)
19,232,385
5
2013-10-07T18:53:24Z
19,232,746
9
2013-10-07T19:15:15Z
[ "python", "django", "csv", "export" ]
I'm trying to import to cvs, but I get this error ``` UnicodeEncodeError at /brokers/csv/'ascii' codec can't encode character u'\u2013' in position 9: ordinal not in range(128) ``` Unicode error hint The string that could not be encoded/decoded was: ) 758–9800 I have tried .encode, unicode(), etc and nothing work...
I'm guessing your using python 2.x? if so try using .encode('utf-8') on your string when writing.
Emulate uint32_t in Python?
19,233,055
7
2013-10-07T19:33:00Z
19,233,149
7
2013-10-07T19:38:02Z
[ "python" ]
I was trying to port a function from C to Python and to make it easy to debug, I'd prefer it performed the same CPU word-size limited operations so I could compare the intermediate results. In other words, I'd like something like: ``` a = UnsignedBoundedInt(32, 399999) b = UnsignedBoundedInt(32, 399999) print(a*b) # p...
You can try using `ctypes.uint_32` to bound the results for you: ``` >>> import ctypes >>> print ctypes.c_uint32(399999 * 399999).value 1085410049 ``` Alternatively you can use [numpy](http://www.numpy.org/)'s data types: ``` >>> import numpy as np >>> a = np.uint32(399999) >>> b = np.uint32(399999) >>> a * b __main...
How to tell uWSGI to prefer processes to threads for load balancing
19,233,132
9
2013-10-07T19:37:25Z
19,238,645
8
2013-10-08T03:36:18Z
[ "python", "multithreading", "process", "load-balancing", "uwsgi" ]
I've installed Nginx + uWSGI + Django on a VDS with 3 CPU cores. uWSGI is configured for 6 processes and 5 threads per process. Now I want to **tell uWSGI to use processes for load balancing until all processes are busy, and then to use threads if needed.** It seems uWSGI prefer threads, and I have not found any config...
Every process is effectively a thread, as threads are execution contexts of the same process. For such a reason there is nothing like "a process executes it instead of a thread". Even without threads your process has 1 execution context (a thread). What i would investigate is why you get (perceived) poor performances ...
How to tell uWSGI to prefer processes to threads for load balancing
19,233,132
9
2013-10-07T19:37:25Z
19,326,373
9
2013-10-11T20:05:35Z
[ "python", "multithreading", "process", "load-balancing", "uwsgi" ]
I've installed Nginx + uWSGI + Django on a VDS with 3 CPU cores. uWSGI is configured for 6 processes and 5 threads per process. Now I want to **tell uWSGI to use processes for load balancing until all processes are busy, and then to use threads if needed.** It seems uWSGI prefer threads, and I have not found any config...
So, the solution is: 1. Upgrade uWSGI to recent stable version (as roberto suggested). 2. Use --thunder-lock option. Now I'm running with 50 threads per process and all requests are distrebuted between processes equally.
Custom list_editable field in django admin change list, which doesn't correspond directly to a model field
19,233,551
6
2013-10-07T19:58:19Z
19,309,815
17
2013-10-11T03:29:53Z
[ "python", "django", "django-admin" ]
Assuming my model looks like this (this is a simplified example): ``` class Person(Model): first_name = CharField(...) last_name = CharField(...) def name(): return first_name + ' ' + last_name ``` Displaying the name as a single column in the admin change list is easy enough. However, I need a single, edi...
You should be able to do this in pure Python with a bit of work. Basically, you need to use the [`get_changelist_form`](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_changelist_form) method on the admin class to tell it to use a custom form rather than a default `ModelForm...
sklearn plot confusion matrix with labels
19,233,771
11
2013-10-07T20:08:53Z
19,252,430
16
2013-10-08T15:49:43Z
[ "python", "matplotlib", "scikit-learn" ]
I want to plot a confusion matrix to visualize the classifer's performance, but it shows only the numbers of the labels, not the labels themselves: ``` from sklearn.metrics import confusion_matrix import pylab as pl y_test=['business', 'business', 'business', 'business', 'business', 'business', 'business', 'business',...
As hinted in [this question](http://stackoverflow.com/questions/3529666/matplotlib-matshow-labels), you have to "open" the [lower-level artist API](http://matplotlib.org/users/artists.html#artist-tutorial), by storing the figure and axis objects passed by the matplotlib functions you call (the `fig`, `ax` and `cax` var...
sklearn plot confusion matrix with labels
19,233,771
11
2013-10-07T20:08:53Z
31,720,054
7
2015-07-30T09:31:52Z
[ "python", "matplotlib", "scikit-learn" ]
I want to plot a confusion matrix to visualize the classifer's performance, but it shows only the numbers of the labels, not the labels themselves: ``` from sklearn.metrics import confusion_matrix import pylab as pl y_test=['business', 'business', 'business', 'business', 'business', 'business', 'business', 'business',...
You might be interested by <https://github.com/pandas-ml/pandas-ml/> which implements a Python Pandas implementation of Confusion Matrix. Some features: * plot confusion matrix * plot normalized confusion matrix * class statistics * overall statistics Here is an example: ``` In [1]: from pandas_ml import Confusion...
Finding out an exception context
19,234,134
15
2013-10-07T20:28:35Z
19,285,852
10
2013-10-10T02:04:22Z
[ "python", "exception", "python-2.7" ]
tlndr: how to tell in a function if it's called from an `except` block (directly/indirectly). python2.7/cpython. I use python 2.7 and try to provide something similar to py3's `__context__` for my custom exception class: ``` class MyErr(Exception): def __init__(self, *args): Exception.__init__(self, *args...
This is tested with CPython 2.7.3: ``` $ python myerr.py MyErr('bang!',) from ZeroDivisionError('integer division or modulo by zero',) MyErr('nobang!',) ``` It works as long as the magic exception is directly created within the scope of an except clause. A little additional code can lift that restriction, though. `...
Nested validation with the flask-restful RequestParser
19,234,737
15
2013-10-07T21:03:09Z
27,091,966
15
2014-11-23T17:26:56Z
[ "python", "rest", "flask", "flask-restful" ]
Using the [flask-restful](http://flask-restful.readthedocs.org/) micro-framework, I am having trouble constructing a `RequestParser` that will validate nested resources. Assuming an expected JSON resource format of the form: ``` { 'a_list': [ { 'obj1': 1, 'obj2': 2, 'obj...
I have had success by creating `RequestParser` instances for the nested objects. Parse the root object first as you normally would, then use the results to feed into the parsers for the nested objects. The trick is the `location` argument of the `add_argument` method and the `req` argument of the `parse_args` method. ...
Psycopg2 Insert Into Table with Placeholders
19,235,686
4
2013-10-07T22:11:41Z
19,235,869
8
2013-10-07T22:27:08Z
[ "python", "postgresql", "postgis", "psycopg2", "psycopg" ]
This might be a rather silly question but what am I doing wrong here? It creates the table but the INSERT INTO doesn't work, I guess I'm doing something wrong with the placeholders? ``` conn = psycopg2.connect("dbname=postgres user=postgres") cur = conn.cursor() escaped_name = "TOUR_2" cur.execute('CREATE TABLE %s(id ...
You are using Python string formatting and this is a Very Bad Idea (TM). Think SQL-injection. The right way to do it is to use bound variables: ``` cur.execute('INSERT INTO %s (day, elapsed_time, net_time, length, average_speed, geometry) VALUES (%s, %s, %s, %s, %s, %s)', (escaped_name, day, time_length, time_length_n...
pycharm pytestrunner PluginManager unexpected keyword argument
19,236,745
8
2013-10-07T23:49:33Z
19,247,931
11
2013-10-08T12:38:46Z
[ "python", "pycharm", "py.test" ]
I have a very simple test script just to learn pytest, tmp.py: ``` def square(x): return x*x def test_square(): assert square(4) == 16 ``` Using Pycharm to run this script, I've configured my project setting such that pytest is used as my default test runner. When I run the above code I get the following erro...
It appears to be an incompatibility between PyCharm and py.test 2.4.x. If you install py.test 2.3.5 (for example, `pip install pytest==2.3.5`) it works fine. I suggest submitting a bug report to JetBrains.
Add numbers without carrying
19,237,609
3
2013-10-08T01:30:59Z
19,237,917
7
2013-10-08T02:09:28Z
[ "python", "math" ]
Lets say I have two numbers, Number 1: ``` 1646 ``` Number 2: ``` 2089 ``` You see adding them left to right without the carry on adds up to 3625 how would I do this in python? I'm not sure but I need it to add 9+6 which is 15 but not to carry on the 1 when it adds 8+4 is there any way to add like this in python? ...
This will work with varying N of integers of varying lengths: ``` from itertools import izip_longest nums = [1646, 2089, 345] revs = [str(n)[-1::-1] for n in nums] # nums as reversed strings izl = izip_longest(*revs, fillvalue = '0') # zip the digits together xsum = lambda ds: str(sum(map(i...
Call Django celery task by name
19,239,154
6
2013-10-08T04:35:06Z
19,538,597
10
2013-10-23T10:01:04Z
[ "python", "django", "celery" ]
I need to call a celery task (in tasks.py) from models.py, the only problem is, tasks.py imports models.py, so I can't import tasks.py from models.py. Is there some way to call a celery task simply using its name, without having to import it? A similar thing is implemented for ForeignKey fields for the same reason (pr...
Yes, there is. You can use: ``` from celery.execute import send_task send_task('my_task', [], kwargs) ``` Be sure that you task function has a name: ``` from celery import task @task(name='my_task') def my_task(): ... ``` Hope it helps!
Python SQL Alchemy cascade delete
19,243,964
3
2013-10-08T09:30:04Z
19,245,058
13
2013-10-08T10:21:32Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
Here are my two models classes in Flask-SQLAlchemy: ``` class JSONSERIALIZER(object): def to_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} class User(db.Model,JSONSERIALIZER): __tablename__ = 'user' __public__ = ('my_id', 'name') my_id = db.Column(db.Intege...
You have the following... ``` db.session.query(User).filter(User.my_id==1).delete() ``` Note that after "filter", you are still returned a Query object. Therefore, when you call `delete()`, you are calling `delete()` on the Query object (not the User object). This means you are doing a bulk delete (albeit probably wi...
Obtaining PIL instead of Pillow for Python 2.7 64-bit on Windows
19,244,057
7
2013-10-08T09:34:04Z
22,743,465
16
2014-03-30T11:33:09Z
[ "python", "windows", "64bit", "python-imaging-library", "pillow" ]
Pillow for Python seems to be completely broken. Every image produces an `IOError: cannot identify image file`. Using Python 2.6 (where I had PIL installed) works great. Does anyone know where to get hold of `PIL-1.1.7.win-amd64-py2.7.exe` now that <http://www.lfd.uci.edu/~gohlke/pythonlibs/> has moved on to only offer...
Here you can find [PIL-1.1.7.win-amd64-py2.7.exe](https://github.com/lightkeeper/lswindows-lib/blob/master/amd64/python/PIL-1.1.7.win-amd64-py2.7.exe?raw=true)
Scipy.optimize: how to restrict argument values
19,244,527
5
2013-10-08T09:54:20Z
19,245,243
8
2013-10-08T10:29:12Z
[ "python", "scipy" ]
I'm trying to use `scipy.optimize` functions to find a global minimum of a complicated function with several arguments. `scipy.optimize.minimize` seems to do the job best of all, namely, the 'Nelder-Mead' method. However, it tends to go to the areas out of arguments' domain (to assign negative values to arguments that ...
The `minimize` function has a [`bounds` parameter](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize) which can be used to restrict the bounds for each variable when using the L-BFGS-B, TNC, COBYLA or SLSQP methods. For example, ``` import scipy.optimize as optim...
Scipy.optimize: how to restrict argument values
19,244,527
5
2013-10-08T09:54:20Z
19,245,263
8
2013-10-08T10:30:16Z
[ "python", "scipy" ]
I'm trying to use `scipy.optimize` functions to find a global minimum of a complicated function with several arguments. `scipy.optimize.minimize` seems to do the job best of all, namely, the 'Nelder-Mead' method. However, it tends to go to the areas out of arguments' domain (to assign negative values to arguments that ...
The Nelder-Mead solver doesn't support constrained optimization, but there are several others that do. TNC and L-BFGS-B both support only bound constraints (e.g. `x[0] >= 0`), which should be fine for your case. COBYLA and SLSQP are more flexible, supporting any combination of bounds, equality and inequality-based con...
How to download big file in python via ftp (with monitoring & reconnect)?
19,245,769
3
2013-10-08T10:53:33Z
19,457,349
7
2013-10-18T19:11:23Z
[ "python", "ftplib" ]
**UPDATE #1** The code in the question **works pretty good for stable connection** (like local network or intranet). **UPDATE #2** I implemented the FTPClient class with ftplib which can: 1. monitor a download progress 2. reconnect in case of timeout or disconnect 3. makes several attempts to download file 4. shows...
Because I couldn't find any good suggestions or code samples, I implemented my own solution. Thank you so much to the Stackoverflow community for some ideas which I used in my code. I put the code to GitHub ([pyFTPclient](https://github.com/keepitsimple/pyFTPclient)) due to the size of the code(~ 120 lines). I tested ...
Python in Emacs shell-mode turns on stty echo and breaks C-d
19,246,065
10
2013-10-08T11:06:08Z
19,251,659
10
2013-10-08T15:15:18Z
[ "python", "osx", "shell", "emacs", "tty" ]
When I run an interactive Python inside an Emacs shell buffer (M-x shell), it does two surprising things to the TTY. First, it turns on input echo, which persists after Python exits, until I do stty -echo. Secondly, it doesn't accept C-d (or C-q C-d, i.e. ^D) as EOF: I have to type quit() to leave the Python. How can I...
### 1. Reproduction I can reproduce this (GNU Emacs 23.4.1; OS X 10.8.5; Python 3.3.2). Here's a session in a fresh `emacs -Q` showing the problem: ``` $ stty -a > stty-before $ python3.3 Python 3.3.2 (default, May 21 2013, 11:50:47) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Typ...
socket.error:[errno 99] cannot assign requested address and namespace in python
19,246,103
6
2013-10-08T11:07:45Z
19,267,994
15
2013-10-09T09:25:51Z
[ "python", "sockets", "namespaces", "ip" ]
My server software says `errno99: cannot assign requested address` while using an ip address other than `127.0.0.1` for binding. But if the IP address is `127.0.0.1` it works. Is it related to namespaces? I am executing my server and client codes in another python program by calling `execfile()`. I am actually editin...
Stripping things down to basics this is what you would want to test with: ``` import socket server = socket.socket() server.bind(("10.0.0.1", 6677)) server.listen(4) client_socket, client_address = server.accept() print(client_address, "has connected") while 1==1: recvieved_data = s.recv(1024) print(recviev...
How do I force Django to connect to Oracle using Service Name
19,246,643
9
2013-10-08T11:34:09Z
20,486,810
7
2013-12-10T05:24:28Z
[ "python", "sql", "django", "oracle" ]
Q : How do specify that Django needs to connect to Oracle DB using the service name and not SID ? Hi, I am currently telling my Django configuration to connect to Oracle using my SID. However, I'll need to connect using the service name and not the SID. ``` APP_DATABASES={ 'default': { 'ENGINE': 'dj...
Thanks guys, There's a "documented" solution to this: ``` 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'host.db.com:1699/oracle_service.db.com', 'USER': 'user', 'PASSWORD': 'pass', } ``` Note: The HOST and PORT keys need to...
Are C++11 containers supported by Cython?
19,246,783
7
2013-10-08T11:40:36Z
30,367,448
8
2015-05-21T07:39:12Z
[ "python", "c++", "c++11", "cython", "c++-standard-library" ]
Cython gives us an easy way to import C++ standard library data structures, e.g.: ``` from libcpp.vector cimport vector from libcpp.utility cimport pair ``` But what about newer containers introduced with C++11: `std::unordered_map`, `std::unordered_set` etc. Are they supported in the same way? I could not find...
Current cython versions allow them. Make sure your `setup.py` contains something like: ``` ext_module = Extension( "foo", ["foo.pyx"], language="c++", extra_compile_args=["-std=c++11"], extra_link_args=["-std=c++11"] ) ``` You can then use ``` from libcpp.unordered_map cimport unordered_map ``` ...
python - merge two lists but keep same number of occurrences
19,246,854
3
2013-10-08T11:44:59Z
19,247,109
9
2013-10-08T11:59:18Z
[ "python", "list", "merge" ]
I have a problem that I could not find a good answer for: I want to merge two lists but keep the same number of occurrences from each object EX: ``` list1 = [2,3,7] list2 = [2,2,5] ``` After merging thees two lists the result should look like this: ``` res = [2,2,3,5,7] #it does not need to be sorted ``` Observe th...
As I understand your question, you want each number to appear in the result with the maximum frequency it appears in any of the input lists. You can use a `collections.Counter` to get the frequencies for each individual list, and use the `|` operator on them to merge them: ``` >>> c = collections.Counter([2, 2, 5]) >>...
Why does pressing Ctrl-backslash result in core dump?
19,248,556
4
2013-10-08T13:07:58Z
19,248,775
16
2013-10-08T13:17:11Z
[ "python", "coredump", "backslash", "ctrl" ]
When I'm in a python application (the python shell, for instance), pressing `Ctrl\` results in ``` >>> Quit (core dumped) ``` Why is this, and how can I avoid this? It is very inconvenient if application bails out whenever I press `Ctrl\` by accident.
`CTRL`-`\` is the Linux key that generates the QUIT signal. Generally, that signal causes a program to terminate and dump core. This is a feature of UNIX and Linux, wholly unrelated to Python. (For example, try `sleep 30` followed by `CTRL`-`\`.) If you want to disable that feature, use the [stty](http://linux.die.net...
How to create a number of empty nested lists in python
19,249,201
4
2013-10-08T13:35:07Z
19,249,250
8
2013-10-08T13:37:06Z
[ "python", "list", "nested-lists" ]
I want to have a variable that is a nested list of a number of empty lists that I can fill in later. Something that looks like: ``` my_variable=[[], [], [], []] ``` However, I do not know beforehand how many lists I will need, only at the creation step, therefore I need a variable `a` to determine it. I thought about...
Try a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` lst = [[] for _ in xrange(a)] ``` See below: ``` >>> a = 3 >>> lst = [[] for _ in xrange(a)] >>> lst [[], [], []] >>> a = 10 >>> lst = [[] for _ in xrange(a)] >>> lst [[], [], [], [], [], [], [], [], [], []] >>...
Way to check that string contains two of the same characters?
19,250,470
2
2013-10-08T14:27:34Z
19,250,490
7
2013-10-08T14:28:25Z
[ "python", "string" ]
Lets say I have: ``` str = "Hello! My name is Barney!" ``` Is there a one or two line method to check if this string contains two `!`?
Yes, you can get the solution in one line easily with the `count` method of a string: ``` >>> # I named it 'mystr' because it is a bad practice to name a variable 'str' >>> # Doing so overrides the built-in >>> mystr = "Hello! My name is Barney!" >>> mystr.count("!") 2 >>> if mystr.count("!") == 2: ... print True ...
A strange list behavior
19,251,101
2
2013-10-08T14:52:44Z
19,251,152
8
2013-10-08T14:54:21Z
[ "python", "list", "pop" ]
I have the following code: ``` d = [1,2,3,4] dpop = d.pop d = ["A","B","C"] dpop() # return 4 d.pop() #return C ``` So, why my first list still exists ? where ?
The first list exists because a reference to it is kept by the method object to which `dpop` is pointing. Essentially, what you've done is this: ``` dpop = [1,2,3,4].pop ``` The instance of the `pop` method which you've stored in `dpop` is associated with the instance of the list that you initially had (and you can ...
python - read whole file at once
19,251,736
6
2013-10-08T15:18:10Z
19,251,893
16
2013-10-08T15:24:47Z
[ "python", "file-io" ]
I need to read whole source data from file something.zip (not uncompress it) I tried ``` f = open('file.zip') s = f.read() f.close() return s ``` but it returns only few bytes and not whole source data. Any idea how to achieve it? Thanks
Use binary mode(`b`) when you're dealing with binary file. ``` def read_zipfile(path): with open(path, 'rb') as f: return f.read() ``` BTW, use [`with` statement](http://docs.python.org/2/whatsnew/2.5.html#pep-343-the-with-statement) instead of manual `close`.
creating a new list with subset of list using index in python
19,252,301
3
2013-10-08T15:44:00Z
19,252,378
8
2013-10-08T15:47:37Z
[ "python", "list", "indexing", "subset" ]
A list: ``` a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] ``` I want a list using a subset of a using `a[0:2],a[4], a[6:]`, that is I want a list `['a', 'b', 4, 6, 7, 8]`
Try `new_list = a[0:2] + [a[4]] + a[6:]`. Or more generally, something like this: ``` from itertools import chain new_list = list(chain(a[0:2], [a[4]], a[6:])) ``` This works with other sequences as well, and is likely to be faster. Or you could do this: ``` def chain_elements_or_slices(*elements_or_slices): n...
creating a new list with subset of list using index in python
19,252,301
3
2013-10-08T15:44:00Z
33,356,141
7
2015-10-26T21:41:25Z
[ "python", "list", "indexing", "subset" ]
A list: ``` a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] ``` I want a list using a subset of a using `a[0:2],a[4], a[6:]`, that is I want a list `['a', 'b', 4, 6, 7, 8]`
Suppose ``` a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] ``` and the list of indexes is stored in ``` b= [0, 1, 2, 4, 6, 7, 8] ``` then a simple one-line solution will be ``` c = [a[i] for i in b] ```
Issue with Sublime Text 3's build system - can't get input from running program
19,254,765
5
2013-10-08T17:50:12Z
19,297,613
15
2013-10-10T13:50:02Z
[ "python", "windows-7", "cmd", "sublimetext3" ]
I'm trying to get Sublime Text 3 (build 3049, if that matters) to run a Python script. A simple two liner ``` var = raw_input("Enter something: ") print "You entered ", var ``` which asks for input, waits for it, then prints it out in windows console prompt. This is, seeing the number of similar questions on the sid...
First off, since you're using a dev build, you must be a registered user (good!) and I'd recommend [upgrading](http://sublimetext.com/3dev) to 3053, the latest version, as newer is often better in terms of known issues being fixed. Second, just FYI, there's a fairly complete set of (unofficial) docs at [docs.sublimetex...
Can't set attribute for subclasses of namedtuple
19,257,497
4
2013-10-08T20:17:39Z
19,257,700
14
2013-10-08T20:27:51Z
[ "python", "class", "python-3.x", "namedtuple" ]
It looks like [this](http://stackoverflow.com/questions/1529002/cant-set-attributes-of-object-class) or [this](http://stackoverflow.com/questions/4183432/cant-set-attribute-with-new-style-properties-in-python) are somewhat related threads, but still haven't figured things out :) I'm trying to create a subclass of `nam...
Named tuples are immutable, so you cannot manipulate them in the `__init__` initializer. Your only option is to override the `__new__` method: ``` class C(namedtuple('C', 'x, y')): __slots__ = () def __new__(cls, obj): return super(C, cls).__new__(cls, obj.x, obj.y) ``` Note that because `__new__` is ...
Python "all" function with conditional generator expression returning True. Why?
19,257,821
4
2013-10-08T20:34:37Z
19,257,843
7
2013-10-08T20:35:55Z
[ "python", "python-3.x", "generator" ]
Can anyone help me understand why the following Python script returns `True`? ``` x = '' y = all(i == ' ' for i in x) print(y) ``` I imagine it's something to do with `x` being a zero-length entity, but cannot fully comprehend.
`all()` always returns `True` *unless* there is an element in the sequence that is `False`. Your loop produces 0 items, so `True` is returned. This is [documented](http://docs.python.org/3/library/functions.html#all): > Return `True` if all elements of the *iterable* are true (**or if the iterable is empty**). Emph...
SQLAlchemy ORM __init__ method vs
19,258,471
3
2013-10-08T21:09:21Z
19,258,715
9
2013-10-08T21:23:33Z
[ "python", "sqlalchemy" ]
In the [SQLAlchemy ORM tutorial](http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html) the following code is given as an example of a class which will be mapped to a table: ``` >>> from sqlalchemy import Column, Integer, String >>> class User(Base): ... __tablename__ = 'users' ... ... id = Column(Integer, p...
first, you should understand that ``` class Foo(object): bar = ['baz'] ``` and ``` class Foo(object): def __init__(self): self.bar = ['baz'] ``` Mean very different things, in the first case, `bar` is a class attribute, it is the same for all instances of `Foo`, and the class `Foo` itself (which ...
How to get synonyms from nltk WordNet Python
19,258,652
10
2013-10-08T21:20:26Z
19,258,889
9
2013-10-08T21:35:09Z
[ "python", "nltk", "wordnet" ]
WordNet is great, but I'm having a hard time getting synonyms in nltk. If you search similar to for the word 'small' like [here](http://wordnetweb.princeton.edu/perl/webwn?o2=&o0=1&o8=1&o1=1&o7=&o5=&o9=&o6=&o3=&o4=&s=small&i=3&h=00100000000000000#c), it shows all of the synonyms. Basically I just need to know the foll...
You've already got the synonyms. That's what a `Synset` is. ``` >>> wn.synsets('small') [Synset('small.n.01'), Synset('small.n.02'), Synset('small.a.01'), Synset('minor.s.10'), Synset('little.s.03'), Synset('small.s.04'), Synset('humble.s.01'), Synset('little.s.07'), Synset('little.s.05'), Synset('small.s.08'...
How to get synonyms from nltk WordNet Python
19,258,652
10
2013-10-08T21:20:26Z
32,718,824
11
2015-09-22T13:55:02Z
[ "python", "nltk", "wordnet" ]
WordNet is great, but I'm having a hard time getting synonyms in nltk. If you search similar to for the word 'small' like [here](http://wordnetweb.princeton.edu/perl/webwn?o2=&o0=1&o8=1&o1=1&o7=&o5=&o9=&o6=&o3=&o4=&s=small&i=3&h=00100000000000000#c), it shows all of the synonyms. Basically I just need to know the foll...
If you want the synonyms in the synset (i.e. the lemmas that make up the set), you can get them with `lemma_names()`: ``` >>> for ss in wn.synsets('small'): print(ss.name(), ss.lemma_names())small.n.01 ['small'] small.n.02 ['small'] small.a.01 ['small', 'little'] minor.s.10 ['minor', 'modest', 'small', 'small-...
Get list of column names from a Firebird database table
19,258,749
4
2013-10-08T21:25:36Z
19,258,750
8
2013-10-08T21:25:36Z
[ "python", "sql", "firebird", "firebird2.5", "fdb" ]
How do you get a list of the column names in an specific table? ie. Firebird table: ``` | name | id | phone_number | ``` get list like this: `columnList = ['name', 'id', 'phone_number']`
if you want to get a list of column names in an specific table, this is the sql query you need: ``` select rdb$field_name from rdb$relation_fields where rdb$relation_name='YOUR-TABLE_NAME'; ``` I tried this in firebird 2.5 and it works. the single quotes around YOUR-TABLE-NAME are necessary btw
Peewee syntax for selecting on null field
19,259,964
9
2013-10-08T22:54:19Z
19,306,746
11
2013-10-10T21:42:13Z
[ "python", "mysql", null, "isnull", "peewee" ]
I have researched this everywhere and can't seem to find an answer. I hope I haven't duplicated this (as it's my first question on SO). I am trying to write a select query with Peewee that would normally go ... WHERE foo = NULL; in SQL world. MySQL looks like this: ``` +-----------+-------------+------+-----+-------...
First off you must use the bitwise operands for "and" and "or". Then for is null, use `>>`: ``` Peers.select().where((Peers.user == 'foo') & (Peers.deleted >> None)) ``` For not null you would negate it: ``` Peers.select().where(~(Peers.deleted >> None)) ``` It is documented: <http://peewee.readthedocs.org/en/lates...
No module named scipy.stats - Why despite scipy being installed
19,261,077
2
2013-10-09T00:44:23Z
19,275,642
9
2013-10-09T15:00:42Z
[ "python", "scipy" ]
How to use python and scipy to get a poissio random variable? Wow..I installed scipy and per the docs I get No module named scipy.stats? I am on ubuntu 12.04. So......go figure <http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html> ``` ubuntu@ubuntu:~/Downloads$ sudo apt-get install python-sci...
I think scipy is the way to go. Probably you have a simple namespace visibility problem. since stats is itself a module you first need to import it, then you can use functions from scipy.stats ``` import scipy import scipy.stats #now you can use scipy.stats.poisson #if you want it more accessible you could do what you...
sum of N lists element-wise python
19,261,747
3
2013-10-09T01:58:20Z
19,261,766
16
2013-10-09T02:00:16Z
[ "python", "list", "sum" ]
Is there an easy way to compute the element-wise sum of N lists in python? I know if we have n lists *defined* (call the ith list `c_i`), we can do: ``` z = [sum(x) for x in zip(c_1, c_2, ...)] ``` For example: ``` c1 = [1,2] c2 = [3,4] c3 = [5,6] z = [sum(x) for x in zip(c1,c2,c3)] ``` Here `z = [9, 12]` But wha...
Just do this: ``` [sum(x) for x in zip(*C)] ``` In the above, `C` is the list of `c_1...c_n`. As explained in the [link](http://stackoverflow.com/questions/5239856/foggy-on-asterisk-in-python) in the comments (thanks, @kevinsa5!): > `*` is the "splat" operator: It takes a list as input, and expands it into actual po...
What is an 'endpoint' in Flask?
19,261,833
49
2013-10-09T02:07:46Z
19,262,022
12
2013-10-09T02:29:40Z
[ "python", "flask" ]
The [Flask documentation shows](http://flask.pocoo.org/docs/api/#flask.Flask.add_url_rule): ``` add_url_rule(*args, **kwargs) Connects a URL rule. Works exactly like the route() decorator. If a view_func is provided it will be registered with the endpoint. endpoint – the endpoint for the registered...
Endpoint is the name used to reverse-lookup the url rules with `url_for` and it defaults to the name of the view function. Small example: ``` from flask import Flask, url_for app = Flask(__name__) # We can use url_for('foo_view') for reverse-lookups in templates or view functions @app.route('/foo') def foo_view(): ...
What is an 'endpoint' in Flask?
19,261,833
49
2013-10-09T02:07:46Z
19,262,349
100
2013-10-09T03:04:15Z
[ "python", "flask" ]
The [Flask documentation shows](http://flask.pocoo.org/docs/api/#flask.Flask.add_url_rule): ``` add_url_rule(*args, **kwargs) Connects a URL rule. Works exactly like the route() decorator. If a view_func is provided it will be registered with the endpoint. endpoint – the endpoint for the registered...
## How Flask Routing Works The entire idea of Flask (and the underlying Werkzeug library) is to map URL paths to some logic that you will run (typically, the "view function"). Your basic view is defined like this: ``` @app.route('/greeting/<name>') def give_greeting(name): return 'Hello, {0}!'.format(name) ``` N...
Is it possible to toggle a certain step in sklearn pipeline?
19,262,621
6
2013-10-09T03:34:18Z
19,265,260
10
2013-10-09T07:04:38Z
[ "python", "machine-learning", "scikit-learn", "pipeline" ]
I wonder if we can set up an "optional" step in `sklearn.pipeline`. For example, for a classification problem, I may want to try an `ExtraTreesClassifier` with AND without a `PCA` transformation ahead of it. In practice, it might be a pipeline with an extra parameter specifying the toggle of the `PCA` step, so that I c...
* `Pipeline` steps cannot currently be made optional in a grid search but you could wrap the `PCA` class into your own `OptionalPCA` component with a boolean parameter to turn off PCA when requested as a quick workaround. You might want to have a look at [hyperopt](https://github.com/jaberg/hyperopt) to setup more comp...
Python Django Gmail SMTP setup
19,264,907
16
2013-10-09T06:42:43Z
19,281,735
22
2013-10-09T20:15:50Z
[ "python", "django", "ubuntu", "amazon-ec2", "gmail" ]
I am trying to send email from Django by setting up gmail smtp. But everytime it is returning me 0 status. I have searched different relevant answers in stackoverflow and i am setting up the smtp server the same way but still it is not sending any email.. Below is my setting file ``` EMAIL_USE_TLS = True EMAIL_HOST = ...
Your `gmail.smtp` setup is correct. It looks like you are not calling the `send_email` function correctly, and that's why it's not sending. In the python shell, try the following: ``` import django from django.conf import settings from django.core.mail import send_mail send_mail('Subject here', 'Here is the message.'...
Python range( ) is not giving me a list
19,268,352
2
2013-10-09T09:39:54Z
19,268,393
9
2013-10-09T09:41:06Z
[ "python", "range" ]
Having a beginner issue with Python range. I am trying to generate a list, but when I enter: ``` def RangeTest(n): # list = range(n) return list print(RangeTest(4)) ``` what is printing is `range(0,4)` rather than `[0,1,2,3]` What am I missing? Thanks in advance!
You're using Python 3, where [`range()`](http://docs.python.org/3.3/library/functions.html#func-range) returns an "immutable sequence type" instead of a list object (Python 2). You'll want to do: ``` def RangeTest(n): return list(range(n)) ``` If you're used to Python 2, then `range()` is equivalent to `xrange()...
python ignore certicate validation urllib2
19,268,548
18
2013-10-09T09:47:27Z
28,048,260
55
2015-01-20T14:49:15Z
[ "python", "python-2.7", "urllib2", "python-requests" ]
I want to ignore the `certification validation` during my request to the server with an internal corporate link. With python `requests` library I would do this: ``` r = requests.get(link, allow_redirects=False,verify=False) ``` How do I do the same with urllib2 library?
In the meantime urllib2 seems to verify server certificates by default. The [warning, that was shown in the past](http://stackoverflow.com/a/18063008/1381638) [disappeared](http://docs.python.org/2/library/urllib2.html) for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate...
python ignore certicate validation urllib2
19,268,548
18
2013-10-09T09:47:27Z
35,799,458
8
2016-03-04T15:13:55Z
[ "python", "python-2.7", "urllib2", "python-requests" ]
I want to ignore the `certification validation` during my request to the server with an internal corporate link. With python `requests` library I would do this: ``` r = requests.get(link, allow_redirects=False,verify=False) ``` How do I do the same with urllib2 library?
For those who uses an opener, you can achieve the same thing based on Enno Gröper's great answer: ``` import urllib2, ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx), your_first_handler, your_second_han...
Matplotlib: Save figure as file from iPython notebook
19,271,309
12
2013-10-09T11:54:26Z
19,272,338
9
2013-10-09T12:41:49Z
[ "python", "matplotlib", "ipython-notebook" ]
I am trying to save a Matplotlib figure as a file from an iPython notebook. ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([1,1,1,1]) ax.plot([1,2]) fig.savefig('test.png') ``` --- The inline view in the iPython notebook looks good: ![Inline view of figure in iPython notebook](http://i.s...
Problem solved: add `'bbox_inches='tight'` argument to savefig. ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([1,1,1,1]) plt.plot([1,2]) savefig('test.png', bbox_inches='tight') ``` I don't understand what's happening here, but the file looks like the iPython notebook inline file now. Yay...
elasticsearch bulk indexing using python
19,271,943
8
2013-10-09T12:24:34Z
19,300,714
11
2013-10-10T15:58:34Z
[ "python", "linux", "elasticsearch" ]
i am trying to index a csv file with 6M records to elasticsearch using python pyes module,the code reads a record line by line and pushes it to elasticsearch...any idea how i can send this as bulk? ``` import csv from pyes import * import sys header = ['col1','col2','col3','col3', 'col4', 'col5', 'col6'] conn = ES('...
[pyelasticsearch](http://pyelasticsearch.readthedocs.org/en/latest/api/) supports bulk indexing: ``` bulk_index(index, doc_type, docs, id_field='id', parent_field='_parent'[, other kwargs listed below]) ``` For example, ``` cities = [] for line in f: fields = line.rstrip().split("\t") city = { "id" : fields[...
How to speed up list comprehension
19,273,256
2
2013-10-09T13:19:30Z
19,273,508
8
2013-10-09T13:29:26Z
[ "python", "list", "python-2.7", "list-comprehension" ]
Below is my list: ``` col = [['red', 'yellow', 'blue', 'red', 'green', 'yellow'], ['pink', 'orange', 'brown', 'pink', 'brown'] ] ``` My goal is to eliminate items that appear once in each list. Here is my code: ``` eliminate = [[w for w in c if c.count(w)>1]for c in col] Output: [['red', 'red', 'yello...
I'd have a go at trying an `OrderedCounter` to avoid the repeated `.count()` calls: ``` from collections import OrderedDict, Counter col=[['red', 'yellow', 'blue', 'red', 'green', 'yellow'],['pink', 'orange', 'brown', 'pink', 'brown']] class OrderedCounter(Counter, OrderedDict): pass new = [[k for k, v in Order...
How to speed up list comprehension
19,273,256
2
2013-10-09T13:19:30Z
19,273,573
7
2013-10-09T13:31:49Z
[ "python", "list", "python-2.7", "list-comprehension" ]
Below is my list: ``` col = [['red', 'yellow', 'blue', 'red', 'green', 'yellow'], ['pink', 'orange', 'brown', 'pink', 'brown'] ] ``` My goal is to eliminate items that appear once in each list. Here is my code: ``` eliminate = [[w for w in c if c.count(w)>1]for c in col] Output: [['red', 'red', 'yello...
Don't use `.count()` as it scans through your list *for each element*. Moreover, it'll add items to the output multiple times if they appear 3 or more times in the input. You'd be better off using a generator function here that only yields items it has seen before, but only once: ``` def unique_plurals(lst): seen...
How to have unique emails with python social auth
19,273,904
6
2013-10-09T13:46:25Z
19,275,086
16
2013-10-09T14:37:43Z
[ "python", "django", "authentication", "social", "django-socialauth" ]
I'm using Python Social Auth (django) with Google and Facebook and it creates different users with the same email. How do I fix that? If I log first with google, logout and then with facebook, it must just associate the accounts and not create. Thanks,
After some code reading I found this in the pipeline: ``` 'social.pipeline.social_auth.associate_by_email', ``` So, I just added it before ``` 'social.pipeline.user.get_username', ``` And it worked.
How to track the current user in flask-login?
19,274,226
7
2013-10-09T13:59:43Z
19,275,188
9
2013-10-09T14:41:34Z
[ "python", "python-2.7", "flask", "flask-login", "flask-extensions" ]
I m trying to use the current user in my view from flask-login. So i tried to `g object` I m assigning `flask.ext.login.current_user` to g object ``` @pot.before_request def load_users(): g.user = current_user.username ``` It works if the user is correct. But when i do **sign-up** or login as with wrong credenti...
Thanks for your answer @Joe and @pjnola, as you all suggested i referred [flask-login docs](http://flask-login.readthedocs.org/en/latest/#anonymous-users) I found that we can customize the anonymous user class, so i customized for my requirement, `Anonymous class` ``` #!/usr/bin/python #flask-login anonymous user cl...
What do (s)witch, (i)gnore, (w)ipe, (b)ackup options mean when installing a package from repository using pip?
19,276,818
15
2013-10-09T15:53:00Z
23,296,211
19
2014-04-25T14:40:37Z
[ "python", "git", "pip" ]
When installing a package using pip, I get the following message: ``` Obtaining some-package from git+git://github.com/some-user/some-package.git@commit-hash#egg=some_package-dev (from -r requirements.txt (line 3)) git clone in /Users/me/Development/some-env/src/some-package exists with URL https://github.com/some...
A patch explaining this option was merged into the PIP documentation, but it was not released until Pip 6.0 (2014-12-22). (<https://github.com/pypa/pip/commit/b5e54fc61c06268c131f1fad3bb4471e8c37bb25>). Here is what that patch says: > # --exists-action option > > This option specifies default behavior when path alread...
Preserving global state in a flask application
19,277,280
20
2013-10-09T16:13:07Z
19,278,304
7
2013-10-09T17:02:18Z
[ "python", "flask", "global", "state" ]
I am trying to save a cache dictionary in my `flask` application. As far as I understand it, the [Application Context](http://flask.pocoo.org/docs/appcontext/), in particualr the [flask.g object](http://flask.pocoo.org/docs/api/#application-globals) should be used for this. Setup: ``` import flask as f app = f.Flas...
This line ``` with app.app_context(): f.g.foo = "bar" ``` Since you are using the "with" keyword, once this loop is executed, it calls the `__exit__` method of the AppContext class. See [this](https://github.com/mitsuhiko/flask/blob/master/flask/ctx.py#L185). So the 'foo' is popped out once done. Thats why you do...
Preserving global state in a flask application
19,277,280
20
2013-10-09T16:13:07Z
23,417,696
23
2014-05-01T22:25:21Z
[ "python", "flask", "global", "state" ]
I am trying to save a cache dictionary in my `flask` application. As far as I understand it, the [Application Context](http://flask.pocoo.org/docs/appcontext/), in particualr the [flask.g object](http://flask.pocoo.org/docs/api/#application-globals) should be used for this. Setup: ``` import flask as f app = f.Flas...
Based on your question, I think you're confused about the definition of "global". In a stock Flask setup, you have a Flask server with multiple threads and potentially multiple processes handling requests. Suppose you had a stock global variable like "itemlist = []", and you wanted to keep adding to it in every reques...
matplotlib: Aligning y-axis labels in stacked scatter plots
19,277,324
11
2013-10-09T16:14:43Z
19,277,494
13
2013-10-09T16:23:23Z
[ "python", "matplotlib", "plot", "alignment", "axis-labels" ]
In the plot bellow i have two scatter plots which have different number scale, so their Y-axis labels are not aligned. Is there any way I can force the horizontal alignment in the y-axis labels? ``` import matplotlib.pylab as plt import random import matplotlib.gridspec as gridspec random.seed(20) data1 = [random.ran...
You can use the set\_label\_coords method. ``` import matplotlib.pylab as plt import random import matplotlib.gridspec as gridspec random.seed(20) data1 = [random.random() for i in range(10)] data2 = [random.random()*1000 for i in range(10)] gs = gridspec.GridSpec(2,1) fig = plt.figure() ax = fig.add_subplot(gs[0])...
Why does object.__new__ work differently in these three cases
19,277,399
7
2013-10-09T16:18:05Z
19,277,824
14
2013-10-09T16:39:03Z
[ "python", "object", "types", "constructor" ]
from question [Why does or rather how does object.\_\_new\_\_ work differently in these two cases](http://stackoverflow.com/questions/18680901/why-does-or-rather-how-does-object-new-work-differently-in-these-two-cases) the author wasn't interested in the why, but rather in the how. I would very much want to understan...
You are using an older Python version; the error message has since been updated: ``` >>> object.__new__(testclass1, 56) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object() takes no parameters ``` Python will only complain about `__init__` not supporting arguments if neither `_...
zip function giving incorrect output in Python
19,278,084
5
2013-10-09T16:51:44Z
19,278,108
11
2013-10-09T16:53:06Z
[ "python", "python-3.x" ]
I am writing some cryptographic algorithm using Python, but I have never worked with Python before. First of all, look at this code then I'd explain the issue, ``` x = bytearray(salt[16:]) y = bytearray(sha_512[32:48]) c = [ i ^ j for i, j in zip( x, y ) ] ``` The value of x and y are , ``` bytearray(b'AB\xc8s\x0...
In Python 3 [`zip`](http://docs.python.org/3.2/library/functions.html#zip) returns an [iterator](http://docs.python.org/2/glossary.html#term-iterator), use `list` to see its content: ``` >>> list(zip((1,2,3),(10,20,30),(100,200,300))) [(1, 10, 100), (2, 20, 200), (3, 30, 300)] ``` `c = [ i ^ j for i, j in zip( x, y )...
pandas - pivot_table with non-numeric values? (DataError: No numeric types to aggregate)
19,279,229
7
2013-10-09T17:53:53Z
26,476,883
22
2014-10-21T00:02:46Z
[ "python", "pandas", "pivot-table", "dataframe" ]
I'm trying to do a pivot of a table containing strings as results. ``` import pandas as pd df1 = pd.DataFrame({'index' : range(8), 'variable1' : ["A","A","B","B","A","B","B","A"], 'variable2' : ["a","b","a","b","a","b","a","b"], 'variable3' : ["x","x","x","y","y","y","x","y"], 'result': ["on","off","off","on","on","o...
My original reply was based on Pandas 0.14.1, and since then, many things changed in the pivot\_table function (rows --> index, cols --> columns... ) Additionally, it appears that the original lambda trick I posted no longer works on Pandas 0.18. You have to provide a reducing function (even if it is min, max or mean)...
Python: Can you use an evaluated expression in an object reference?
19,279,283
3
2013-10-09T17:57:31Z
19,279,300
7
2013-10-09T17:58:06Z
[ "python" ]
I'm not sure the best way to ask this, so I'm going to try by example. Is there an easy way in Python to accomplish the following? instead of referencing an object like this: ``` >> print myobject.someattrib 5 ``` ...use an expression which will be evaluated first, and then dereferenced?: ``` >> obj_name = "someatt...
You can do: ``` print getattr(myobject, obj_name) ```
py2exe - No system module 'pywintypes'
19,280,894
9
2013-10-09T19:28:26Z
20,017,920
19
2013-11-16T11:33:49Z
[ "python", "windows", "py2exe", "pywin32", "anaconda" ]
I'm trying to convert a simple Python script into a Windows executable. My setup.py script is: ``` from distutils.core import setup import py2exe setup( name = "Simple Script", options = { "py2exe": { "dll_excludes" : ["libmmd.dll","libifcoremd.dll","libiomp5md.dll","libzmq.dll"] }...
I recently installed Anaconda, partly because I need the win32com package, and don't want to exclude dll files. However, same problem for me. > **Solution** was to copy the DLL files: > pywintypes27.dll > pythoncom27.dll > sitting in: > C:\Anaconda\Lib\site-packages\win32 > to > C:\Anaconda\Lib\site-packag...
MemoryError while converting sparse matrix to dense matrix? (numpy, scikit)
19,281,271
2
2013-10-09T19:52:09Z
19,281,347
8
2013-10-09T19:56:36Z
[ "python", "numpy", "scikit-learn" ]
``` lr = lm.LogisticRegression(penalty='l2', dual=True, tol=0.0001, C=1, fit_intercept=True, intercept_scaling=1.0, class_weight=None, random_state=None) rd = AdaBoostClassifier( base_estimator=lr, learning_rate=1, ...
`MemoryError` means that there isn't enough RAM available on your system to allocate the matrix. Why? Well, a `7395 x 412605` matrix has 3,051,213,975 elements. If they're in the default `float64` (usually `double` in C) datatype, that's 22.7GB. If you convert to lower-precision `float32`s (usually `float` in C), it'd ...
Redis: Return all values stored in a database
19,282,580
5
2013-10-09T20:57:45Z
19,312,607
14
2013-10-11T07:30:49Z
[ "python", "redis" ]
We're using Redis to store various application configurations in a DB 0. Is it possible to query Redis for every key/valuie pair within the database, without having to perform two separate queries and joining the key/value pairs yourself? I would expect functionality similar to the following: ``` kv = redis_conn.get...
There are differences between different types in Redis, so you have to look at the data type to determine how to get the values from the key. So: ``` keys = redis.keys('*') for key in keys: type = redis.type(key) if type == KV: val = redis.get(key) if type == HASH: vals = redis.hgetall(key)...
django template if or statement
19,284,270
17
2013-10-09T23:01:29Z
19,284,388
18
2013-10-09T23:10:29Z
[ "python", "django", "if-statement", "django-templates", "xor" ]
Basically to make this quick and simple, I'm looking to run an XOR conditional in django template. Before you ask why don't I just do it in the code, this isn't an option. Basically I need to check if a user is in one of two many-to-many objects. ``` req.accepted.all ``` and ``` req.declined.all ``` Now they can o...
`and` has higher precedence than `or`, so you can just write the decomposed version: ``` {% if user.username in req.accepted.all and user.username not in req.declined.all or user.username not in req.accepted.all and user.username in req.declined.all %} ``` For efficiency, using `with` to skip reevaluating the q...
Instance attribute attribute_name defined outside __init__
19,284,857
39
2013-10-10T00:04:50Z
19,285,003
9
2013-10-10T00:21:51Z
[ "python", "constructor", "pylint" ]
I split up my class constructor by letting it call multiple functions, like this: ``` class Wizard: def __init__(self, argv): self.parse_arguments(argv) self.wave_wand() # declaration omitted def parse_arguments(self, argv): if self.has_correct_argument_count(argv): self.na...
Just return a tuple from `parse_arguments()` and unpack into attributes inside `__init__` as needed. Also, I would recommend that you use Exceptions in lieu of using `exit(1)`. You get tracebacks, your code is reusable, etc. ``` class Wizard: def __init__(self, argv): self.name,self.magic_ability = self.p...
Instance attribute attribute_name defined outside __init__
19,284,857
39
2013-10-10T00:04:50Z
19,292,653
28
2013-10-10T09:57:25Z
[ "python", "constructor", "pylint" ]
I split up my class constructor by letting it call multiple functions, like this: ``` class Wizard: def __init__(self, argv): self.parse_arguments(argv) self.wave_wand() # declaration omitted def parse_arguments(self, argv): if self.has_correct_argument_count(argv): self.na...
The idea behind this message is for the sake of readability. We expect to find all the attributes an instance may have by reading its `__init__` method. You may still want to split initialization into other methods though. In such case, you can simply assign attributes to `None` (with a bit of documentation) in the `_...
Project Euler #8 in Python
19,285,079
3
2013-10-10T00:30:12Z
19,285,245
8
2013-10-10T00:47:39Z
[ "python" ]
``` ''' Find the greatest product of five consecutive digits in the 1000-digit number ''' import time num = '\ 73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\...
There were several issues. 1. You were printing `product` not `biggest`. Make sure to print the right variable! 2. You were iterating through the length of the entire string when you should really just iterate in the range `[0..len(num) - 4)` so that you don't get an IndexError when you do your product calculation. 3....
Python - OpenCV - imread - Displaying Image
19,285,562
10
2013-10-10T01:23:18Z
19,416,871
9
2013-10-17T01:39:18Z
[ "python", "image", "opencv", "imshow" ]
I am currently working on reading an image and displaying it to a window. I have successfully done this, but upon displaying the image, the window only allows me to see a portion of the full image. I tried saving the image after loading it, and it saved the entire image. So I am fairly certain that it is reading the en...
Looks like the image is too big and the window simply doesn't fit the screen. Create window with the `cv2.WINDOW_NORMAL` flag, it will make it scalable. Then you can resize it to fit your screen like this: ``` from __future__ import division import cv2 img = cv2.imread('1.jpg') screen_res = 1280, 720 scale_width = ...
Python - Convert Very Large (6.4GB) XML files to JSON
19,286,118
6
2013-10-10T02:37:01Z
19,286,509
8
2013-10-10T03:20:59Z
[ "python", "xml", "json" ]
Essentially, I have a 6.4GB XML file that I'd like to convert to JSON then save it to disk. I'm currently running OSX 10.8.4 with an i7 2700k and 16GBs of ram, and running Python 64bit (double checked). I'm getting an error that I don't have enough memory to allocate. How do I go about fixing this? ``` print 'Opening'...
Many Python XML libraries support parsing XML sub elements incrementally, e.g. `xml.etree.ElementTree.iterparse` and `xml.sax.parse` in the standard library. These functions are usually called "XML Stream Parser". The xmltodict library you used also has a streaming mode. I think it may solve your problem <https://git...
Index all *except* one item in python
19,286,657
15
2013-10-10T03:39:18Z
19,286,676
22
2013-10-10T03:41:47Z
[ "python", "list", "numpy", "indexing" ]
Is there a simple way to index all elements of a list (or array, or whatever) **except** for a particular index? E.g., * `mylist[3]` will return the item in position 3 * `milist[~3]` will return the whole list except for 3
``` >>> l = range(1,10) >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> l[:2] [1, 2] >>> l[3:] [4, 5, 6, 7, 8, 9] >>> l[:2] + l[3:] [1, 2, 4, 5, 6, 7, 8, 9] >>> ``` See also [Python's slice notation](http://stackoverflow.com/questions/509211/pythons-slice-notation)
Index all *except* one item in python
19,286,657
15
2013-10-10T03:39:18Z
19,286,740
14
2013-10-10T03:49:05Z
[ "python", "list", "numpy", "indexing" ]
Is there a simple way to index all elements of a list (or array, or whatever) **except** for a particular index? E.g., * `mylist[3]` will return the item in position 3 * `milist[~3]` will return the whole list except for 3
If you are using numpy, the closest, I can think of is using a mask ``` >>> import numpy as np >>> arr = np.arange(1,10) >>> mask = np.ones(arr.shape,dtype=bool) >>> mask[5]=0 >>> arr[mask] array([1, 2, 3, 4, 5, 7, 8, 9]) ``` Something similar can be achieved using `itertools` without `numpy` ``` >>> from itertools ...
Index all *except* one item in python
19,286,657
15
2013-10-10T03:39:18Z
19,286,855
12
2013-10-10T04:02:50Z
[ "python", "list", "numpy", "indexing" ]
Is there a simple way to index all elements of a list (or array, or whatever) **except** for a particular index? E.g., * `mylist[3]` will return the item in position 3 * `milist[~3]` will return the whole list except for 3
For a **list**, you could use a list comp. For example, to make `b` a copy of `a` without the 3rd element: ``` a = range(10)[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] b = [x for i,x in enumerate(a) if i!=3] # [9, 8, 7, 5, 4, 3, 2, 1, 0] ``` This is very general, and can be used with all iterables...
Index all *except* one item in python
19,286,657
15
2013-10-10T03:39:18Z
21,935,005
7
2014-02-21T12:52:03Z
[ "python", "list", "numpy", "indexing" ]
Is there a simple way to index all elements of a list (or array, or whatever) **except** for a particular index? E.g., * `mylist[3]` will return the item in position 3 * `milist[~3]` will return the whole list except for 3
The simplest way I found was: ``` mylist[:x]+mylist[x+1:] ``` that will produce your `mylist` without the element at index `x`.
ImportError: No module named redis
19,288,900
7
2013-10-10T06:48:45Z
19,288,952
16
2013-10-10T06:51:50Z
[ "python", "ubuntu", "redis", "install", "package" ]
I have installed redis using `sudo apt-get install redis-server` command but I am receiving this error when I run my Python program: `ImportError: No module named redis` Any idea what's going wrong or if I should install any other package as well? I am using Ubuntu 13.04 and I have Python 2.7.
To install redis-py, simply: ``` $ sudo pip install redis ``` or alternatively (you really should be using pip though): ``` $ sudo easy_install redis ``` or from source: ``` $ sudo python setup.py install ``` Getting Started ``` >>> import redis >>> r = redis.StrictRedis(host='localhost', port=6379, db=0) >>> r....
Importing a variable from one python script to another
19,289,171
6
2013-10-10T07:05:09Z
19,289,230
13
2013-10-10T07:08:14Z
[ "python", "python-2.7" ]
I have `script1.py` which calls `script2.py (subprocess.call([sys.executable, "script2.py"])`. But `script2.py` needs variable `x` that is known in `script1.py`. I tried a very simple `import x from script1`, but it seems not to work. Is that the right approach to use? For example: ``` #script1.py import subprocess, ...
The correct syntax is: ``` from script1 import x ``` So, literally, "from script1.py import the "x" object."
Can't modify list elements in a loop Python
19,290,762
11
2013-10-10T08:29:51Z
19,290,848
12
2013-10-10T08:34:04Z
[ "python", "list", "loops" ]
While looping over a list in Python, I was unable to modify the elements without a list comprehension. For reference: ``` li = ["spam", "eggs"] for i in li: i = "foo" li ["spam", "eggs"] li = ["foo" for i in li] li ["foo", "foo"] ``` So, why can't I modify elements through a loop in Python? There's definitely ...
Because the way `for i in li` works is something like this: ``` for idx in range(len(li)): i = li[idx] i = 'foo' ``` So if you assign anything to `i`, it won't affect `li[idx]`. The solution is either what you have proposed, or looping through the indices: ``` for idx in range(len(li)): li[idx] = 'foo' ...
How can I troubleshoot Python "Could not find platform independent libraries <prefix>"
19,292,957
12
2013-10-10T10:10:17Z
24,044,339
7
2014-06-04T17:57:05Z
[ "python", "path", "importerror" ]
I'm trying to use Fontcustom to create an icon font using svg files and fontforge. I'm on OSX.7. However, whenever I run the program I get the error ``` Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefi...
Try `export PYTHONHOME=/usr/local`. Python should be installed in `/usr/local` on OS X.
How to elegantly interleave two lists of uneven length in python?
19,293,481
8
2013-10-10T10:37:58Z
19,293,833
9
2013-10-10T10:54:29Z
[ "python", "list", "python-3.x" ]
I want to merge two lists in python, with the lists being of different lengths, so that the elements of the shorter list are as equally spaced within the final list as possible. i.e. I want to take `[1, 2, 3, 4]` and `['a','b']` and merge them to get a list similar to `[1, 'a', 2, 3, 'b', 4]`. It needs to be able to fu...
This is basically the same as [Bresenham's line algorithm](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm). You can calculate "pixel" positions and use them as the indices into the lists. Where your task differs is that you only want each element to show up once. You'd need to either modify the algorithm or...
Numpy: Indexing of arrays
19,294,766
3
2013-10-10T11:37:41Z
19,294,889
7
2013-10-10T11:44:32Z
[ "python", "numpy" ]
Given the following example ``` d = array([[1, 2, 3], [1, 2, 3], [1, 3, 3], [4, 4, 4], [5, 5, 5] ]) ``` To get the sub-array containing `1` in the first column: ``` d[ d[:,0] == 1 ] array([[1, 2, 3], [1, 2, 3], [1, 3, 3]]) ``` How to get (without ...
Method #1: use bitwise or `|` to combine the conditions: ``` >>> d array([[1, 2, 3], [1, 2, 3], [1, 3, 3], [4, 4, 4], [5, 5, 5]]) >>> (d[:,0] == 1) | (d[:,0] == 5) array([ True, True, True, False, True], dtype=bool) >>> d[(d[:,0] == 1) | (d[:,0] == 5)] array([[1, 2, 3], [1, 2, 3],...
indentation error with python 3.3 when python2.7 works well
19,295,519
4
2013-10-10T12:16:58Z
19,295,607
8
2013-10-10T12:20:51Z
[ "python", "python-2.7", "python-3.3" ]
I wrote this script below which converts number to it's spelling. ``` no = raw_input("Enter a number: ") strcheck = str(no) try: val = int(no) except ValueError: print("sayi degil") raise SystemExit lencheck = str(no) if len(lencheck) > 6: print("Bu sayi cok buyuk !") raise SystemExit n = in...
You are mixing tabs and spaces. Python 3 explicitly disallows this. Use spaces *only* for indentation. Quoting from the [Python Style Guide](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) (PEP 8): > Spaces are the preferred indentation method. > > Tabs should be used solely to remain consistent with code t...
tempfile.TemporaryDirectory context manager in Python 2.7
19,296,146
12
2013-10-10T12:46:32Z
19,299,884
22
2013-10-10T15:22:25Z
[ "python", "python-2.7", "with-statement", "temp" ]
Is there a way to create a temporary directory in a context manager with Python 2.7? ``` with tempfile.TemporaryDirectory() as temp_dir: # modify files in this dir # here the temporary diretory does not exist any more. ```
[`tempfile.TemporaryDirectory()`](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory) was added to the tempfile standard library in Python 3.2 It's a simple wrapper for `tempfile.mkdtemp`. It is coded in pure Python and can be easily ported to Python 2.7. For example: ``` from __future__ imp...
Why child class doesn't overwerite the fields from based class in python and how deal with that
19,299,168
2
2013-10-10T14:52:11Z
19,299,295
7
2013-10-10T14:57:20Z
[ "python" ]
I create based abstract class in python which is based class for all child classes and implement some functions which will be redundant to write each time in every child class. ``` class Element: ###SITE### __sitedefs = [None] def getSitedefs(self): return self.__sitedefs class SRL16(Element): ...
Your problem's is due to name mangling. See eg: [The meaning of a single- and a double-underscore before an object name in Python](http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python). If you change all the `__sitedefs` by `_sitedefs` then everythi...
list.reverse() is not working
19,299,563
6
2013-10-10T15:09:05Z
19,299,587
9
2013-10-10T15:10:01Z
[ "python", "list", "reverse" ]
I honestly just don't understand why this is returning `None` rather than a reversed list: ``` >>> l = range(10) >>> print l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print l.reverse() None ``` Why is this happening? According to [the docs](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists), I am doing not...
`reverse` modifies the list in place and returns `None`. If you do ``` l.reverse() print l ``` you will see your list has been modified.
Python match a string with regex
19,300,020
7
2013-10-10T15:28:10Z
19,300,066
11
2013-10-10T15:30:07Z
[ "python", "regex" ]
I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially. So for example, ``` line = 'This,is,a,sample,string' ``` I want to search based on "sample", this would return true. I am crappy with reg ex, so when I looked at the python docs, I saw someth...
The `r` makes the string a [raw string](http://docs.python.org/2/reference/lexical_analysis.html#string-literals), which doesn't process escape characters (however, since there are none in the string, it is actually not needed here). Also, `re.match` matches from the beginning of the string. In other words, it looks f...
Python match a string with regex
19,300,020
7
2013-10-10T15:28:10Z
19,300,157
16
2013-10-10T15:32:58Z
[ "python", "regex" ]
I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially. So for example, ``` line = 'This,is,a,sample,string' ``` I want to search based on "sample", this would return true. I am crappy with reg ex, so when I looked at the python docs, I saw someth...
Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do: ``` >>> line = 'This,is,a,sample,string' >>> "sample" in line True ```
Python: Assign each element of a List to a separate Variable
19,300,174
3
2013-10-10T15:33:29Z
19,300,250
8
2013-10-10T15:37:01Z
[ "python", "list", "variables" ]
if I have a list, say: ``` ll = ['xx','yy','zz'] ``` and I want to assign each element of this list to a separate variable: ``` var1 = xx var2 = yy var3 = zz ``` without knowing how long the list is, how would I do this? I have tried: ``` max = len(ll) count = 0 for ii in ll: varcount = ii count += 1 i...
You should go back and rethink why you "need" dynamic variables. Chances are, you can create the same functionality with looping through the list, or slicing it into chunks.
Computing the smallest positive integer not covered by any of a set of intervals
19,300,735
11
2013-10-10T15:59:20Z
19,302,313
8
2013-10-10T17:25:27Z
[ "python", "algorithm", "big-o", "time-complexity", "intervals" ]
Someone posted this question here a few weeks ago, but it looked awfully like homework without prior research, and the OP promptly removed it after getting a few downvotes. The question itself was rather interesting though, and I've been thinking about it for a week without finding a satisfying solution. Hopefully som...
Elaborating on @mrip's comment: you can do this in O(n) time by using the exact algorithm you've described but changing how the sorting algorithm works. Typically, radix sort uses base 2: the elements are divvied into two different buckets based on whether their bits are 0 or 1. Each round of radix sort takes time O(n...
python generator "send" function purpose?
19,302,530
45
2013-10-10T17:38:19Z
19,302,671
8
2013-10-10T17:45:11Z
[ "python" ]
Can someone give me an example of why the "send" function associated with Python generator function exists? I fully understand the yield function. However, the send function is confusing to me. The documentation on this method is convoluted: ``` generator.send(value) ``` > Resumes the execution and “sends” a valu...
The `send` method implements [coroutines](http://en.wikipedia.org/wiki/Coroutine). If you haven't encountered Coroutines they are tricky to wrap your head around because they change the way a program flows. You can read a [good tutorial](http://dabeaz.com/coroutines/) for more details.
python generator "send" function purpose?
19,302,530
45
2013-10-10T17:38:19Z
19,302,694
43
2013-10-10T17:47:01Z
[ "python" ]
Can someone give me an example of why the "send" function associated with Python generator function exists? I fully understand the yield function. However, the send function is confusing to me. The documentation on this method is convoluted: ``` generator.send(value) ``` > Resumes the execution and “sends” a valu...
It's used to send values into a generator that just yielded. Here is an artificial (non-useful) explanatory example: ``` >>> def double_inputs(): ... while True: ... x = yield ... yield x * 2 ... >>> gen = double_inputs() >>> gen.next() #run up to the first yield >>> gen.send(10) #goes into 'x' var...
python generator "send" function purpose?
19,302,530
45
2013-10-10T17:38:19Z
19,302,700
35
2013-10-10T17:47:32Z
[ "python" ]
Can someone give me an example of why the "send" function associated with Python generator function exists? I fully understand the yield function. However, the send function is confusing to me. The documentation on this method is convoluted: ``` generator.send(value) ``` > Resumes the execution and “sends” a valu...
This function is to write coroutines ``` def coroutine(): for i in range(1, 10): print("From generator {}".format((yield i))) c = coroutine() c.send(None) try: while True: print("From user {}".format(c.send(1))) except StopIteration: pass ``` prints ``` From generator 1 From user 2 From gener...
How to write data from two lists into columns in a csv?
19,302,612
4
2013-10-10T17:42:02Z
19,302,732
7
2013-10-10T17:49:11Z
[ "python", "csv", "file-io" ]
I want to write data that I have to create a histogram into a csv file. I have my 'bins' list and I have my 'frequencies' list. Can someone give me some help to write them into a csv in their respective columns? ie bins in the first column and frequency in the second column
This example uses [`izip`](http://docs.python.org/2/library/itertools.html#itertools.izip) (instead of `zip`) to avoid creating a new list and having to keep it in the memory. It also makes use of [Python's built in csv module](http://docs.python.org/2/library/csv.html), which ensures proper escaping. As an added bonus...
Getting header row from numpy.genfromtxt
19,302,859
6
2013-10-10T17:56:37Z
19,302,906
9
2013-10-10T17:59:38Z
[ "python", "numpy" ]
I did this call: ``` data = numpy.genfromtxt('grades.txt', dtype=None, delimiter='\t', names=True) ``` How do you get a list of the column names?
The column names can be found in ``` data.dtype.names ``` --- For example, ``` In [39]: data Out[39]: array([('2010-1-1', 1.2, 2.3, 3.4), ('2010-2-1', 4.5, 5.6, 6.7)], dtype=[('f0', '|S10'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8')]) In [40]: data.dtype Out[40]: dtype([('f0', '|S10'), ('f1', '<f8'), ('f...
Why is the quality of JPEG images produced by PIL so poor?
19,303,621
5
2013-10-10T18:38:02Z
19,303,889
10
2013-10-10T18:50:25Z
[ "python", "python-imaging-library" ]
The JPEG images created with PIL (1.1.7) have very poor quality. Here is an example: Input: <http://s23.postimg.org/8bks3x5p7/cover_1.jpg> Output: <http://s23.postimg.org/68ey9zva3/cover_2.jpg> The output image was created with the following code: ``` from PIL import Image im = Image.open('/path/to/cover_1.jpg') im...
There are two parts to JPEG quality. The first is the `quality` setting which you have already set to the highest possible value. JPEG also uses [chroma subsampling](http://en.wikipedia.org/wiki/Chroma_subsampling), assuming that color hue changes are less important than lightness changes and some information can be s...
determine matplotlib axis size in pixels
19,306,510
11
2013-10-10T21:25:38Z
19,306,776
22
2013-10-10T21:44:39Z
[ "python", "matplotlib" ]
Given a set of [axes](http://matplotlib.org/api/axes_api.html) in matplotlib, is there a way to determine its size in pixels? I need to scale things according to adjust for larger or smaller figures. (In particular I want to change the linewidth so it is proportionate for the axes size.)
This gives the width and height in inches. ``` bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = bbox.width, bbox.height ``` That probably suffices for your purpose, but to get pixels, you can multiply by `fig.dpi`: ``` width *= fig.dpi height *= fig.dpi ``` --- For example,...
Fast way to place bits for puzzle
19,306,692
11
2013-10-10T21:38:05Z
19,309,344
12
2013-10-11T02:33:07Z
[ "python", "performance", "algorithm", "math", "time-complexity" ]
There is a puzzle which I am writing code to solve that goes as follows. Consider a binary vector of length n that is initially all zeros. You choose a bit of the vector and set it to 1. Now a process starts that sets the bit that is the greatest distance from any 1 bit to $1$ (or an arbitrary choice of furthest bit i...
# Latest answer (O(log n) complexity) If we believe the conjecture by templatetypedef and Aleksi Torhamo (**update**: proof at the end of this post), there is a closed form solution `count(n)` calculable in `O(log n)` (or `O(1)` if we assume logarithm and bit shifting is `O(1)`): Python: ``` from math import log de...