title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I execute inserts and updates in an Alembic upgrade script?
24,612,395
25
2014-07-07T13:59:44Z
24,623,979
34
2014-07-08T04:54:29Z
[ "python", "sqlalchemy", "alembic" ]
I need to alter data during an Alembic upgrade. I currently have a 'players' table in a first revision: ``` def upgrade(): op.create_table('player', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Unicode(length=200), nullable=False), sa.Column('position', sa.Unicode(le...
What you are asking for is a *data migration*, as opposed to the *schema migration* that is most prevalent in the Alembic docs. This answer assumes you are using declarative (as opposed to class-Mapper-Table or core) to define your models. It should be relatively straightforward to adapt this to the other forms. Note...
B-spline interpolation with Python
24,612,626
10
2014-07-07T14:10:45Z
24,693,358
11
2014-07-11T08:31:41Z
[ "python", "bspline" ]
I am trying to reproduce a Mathematica example for a B-spline with Python. The code of the mathematica example reads ``` pts = {{0, 0}, {0, 2}, {2, 3}, {4, 0}, {6, 3}, {8, 2}, {8, 0}}; Graphics[{BSplineCurve[pts, SplineKnots -> {0, 0, 0, 0, 2, 3, 4, 6, 6, 6, 6}], Green, Line[pts], Red, Point[pts]}] ``` and produces ...
I was able to recreate the Mathematica example I asked about in the previous post using Python/scipy. Here's the result: ## B-Spline, Aperiodic ![Spline through a 2D curve.](http://i.stack.imgur.com/4IpVe.png) The trick was to either intercept the coefficients, i.e. element 1 of the tuple returned by `scipy.interpol...
How to install NumPy for python 3.3.5 on Mac OSX 10.9
24,615,005
3
2014-07-07T16:07:15Z
24,616,464
10
2014-07-07T17:34:21Z
[ "python", "osx", "numpy", "matplotlib" ]
So I'm currently trying to use python so that it will receive an email and open an attachment, and one of the imports I found required was matplotlib.pyplot as plt. This in turn required Numpy and matplotlib, of which matplotlib was easy to import but I can't for the life of me get NumPy to work. I tried going through ...
Welcome to both Python and Stack Overflow! Your question is not at all uncommon. I've seen PhD graduates struggle with the exact same issues! While Python is a beautiful programming language with a very friendly community, getting started with the scientific Python stack can be quite a hassle. There are two nice opti...
UnicodeDecodeError in Python when reading a file, how to ignore the error and jump to the next line?
24,616,678
4
2014-07-07T17:49:25Z
24,617,071
7
2014-07-07T18:14:11Z
[ "python", "python-3.x", "utf-8" ]
I have to read a text file into Python. The file encoding is: ``` file -bi test.csv text/plain; charset=us-ascii ``` This is a third-party file, and I get a new one every day, so I would rather not change it. The file has non ascii characters, such as Ö, for example. I need to read the lines using python, and I can...
Your file doesn't appear to use the UTF-8 encoding. It is important to use the correct codec when opening a file. You *can* tell [`open()`](https://docs.python.org/3/library/functions.html#open) how to treat decoding errors, with the `errors` keyword: > *errors* is an optional string that specifies how encoding and d...
Sklearn SGDClassifier partial fit
24,617,356
18
2014-07-07T18:31:48Z
24,755,029
24
2014-07-15T09:51:27Z
[ "python", "machine-learning", "scikit-learn", "gradient-descent" ]
I'm trying to use SGD to classify a large dataset. As the data is too large to fit into memory, I'd like to use the *partial\_fit* method to train the classifier. I have selected a sample of the dataset (100,000 rows) that fits into memory to test *fit* vs. *partial\_fit*: ``` from sklearn.linear_model import SGDClass...
I have finally found the answer. You need to **shuffle the training data between each iteration**, as setting *shuffle=True* when instantiating the model will NOT shuffle the data when using *partial\_fit* (it only applies to *fit*). Note: it would have been helpful to find this information on the [sklearn.linear\_mode...
How to print to console in Py Test?
24,617,397
28
2014-07-07T18:33:34Z
24,617,813
38
2014-07-07T18:55:13Z
[ "python", "unit-testing", "python-2.7", "py.test" ]
I'm trying to use Test-Driven Development with the `pytest` module. pytest will not `print` to the console when I write `print`. I use `py.test my_tests.py` to run it... The `documentation` seems to say that it should work by default: <http://pytest.org/latest/capture.html> But: ``` import myapplication as tum cla...
By default, `py.test` captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text. However, if a test fails, it will include a section in the resulting report that shows what was printed to sta...
how to change the order of factor plot in seaborn
24,618,862
5
2014-07-07T20:03:36Z
24,620,595
9
2014-07-07T21:58:29Z
[ "python", "pandas", "bar-chart", "seaborn" ]
my data looks like ``` m=pd.DataFrame({'model':['1','1','2','2','13','13'],'rate':randn(6)},index=['0', '0','1','1','2','2']) ``` I want to have the x axis of factor plot ordered in [1,2,13] but the default is [1,13,2] Does anyone know how to change it? Thank you so much! Update: I think I have figured it out in t...
Your update to the post shows the correct way to do it, i.e. you should pass a list of `x`, values to `x_order` in the order you want them plotted. The default is just to plot in sorted order, so if you have numeric values it's best to keep them as integers or floats instead of strings, so they will be in "natural" ord...
O(n) + O(n) = O(n)?
24,620,993
7
2014-07-07T22:34:03Z
24,621,031
10
2014-07-07T22:37:35Z
[ "python", "algorithm", "big-o" ]
According to Alex Martelli in O'Reilly's Python in a Nutshell, the complexity class `O(n) + O(n) = O(n)`. So I believe it. But am confused. He explains it by saying that, "the sum of two linear functions of N is also a linear function of N." According to [wikipedia](http://en.wikipedia.org/wiki/Linear_function), in fu...
Correct, O(n) + O(n) = O(n). More specifically, O(n) + O(n) = 2 \* O(n), but since Big O only cares about functions as they tend toward infinity, anything linear is denoted as O(n).
O(n) + O(n) = O(n)?
24,620,993
7
2014-07-07T22:34:03Z
24,621,033
8
2014-07-07T22:37:53Z
[ "python", "algorithm", "big-o" ]
According to Alex Martelli in O'Reilly's Python in a Nutshell, the complexity class `O(n) + O(n) = O(n)`. So I believe it. But am confused. He explains it by saying that, "the sum of two linear functions of N is also a linear function of N." According to [wikipedia](http://en.wikipedia.org/wiki/Linear_function), in fu...
> So even though in the following two functions, the "complex" function takes three times as long to process as the "simple" one, they each function in big-O notation as O(n), because the arc of the processing time would be represented by a straight, diagonal line on a plot/graph, even though the angle of the more comp...
O(n) + O(n) = O(n)?
24,620,993
7
2014-07-07T22:34:03Z
24,621,209
10
2014-07-07T22:54:59Z
[ "python", "algorithm", "big-o" ]
According to Alex Martelli in O'Reilly's Python in a Nutshell, the complexity class `O(n) + O(n) = O(n)`. So I believe it. But am confused. He explains it by saying that, "the sum of two linear functions of N is also a linear function of N." According to [wikipedia](http://en.wikipedia.org/wiki/Linear_function), in fu...
The statement is correct, because the addition of two linear functions is also a linear function. Take for example these two: ``` y = 6*x + 10 y = 20*x + 2 ``` Add them together and you get: ``` y = 26*x + 12 ``` Which is also a linear function! This holds for any two linear functions. ``` y = A*x + B y = C*x + D ...
Django - Inline form for OneToOne field in admin site
24,623,457
5
2014-07-08T03:58:37Z
24,891,823
8
2014-07-22T15:40:46Z
[ "python", "django" ]
Hi This question has been asked many times but unfortunately I could not find an answer for it that would actually work. Below are my models: ``` class Person(models.Model): name = models.CharField(max_length=100) ... class Address(models.Model): person = models.OneToOneField(Person) ... ``` Then in ...
I have not tried it, but this gist appears to be based on the code in django-reverse-admin but updated to work on Django 1.6: <https://gist.github.com/mzbyszewska/8b6afc312b024832aa85> Note that this part of the example code is wrong: ``` class AddressForm(models.Form): pass ``` ...you need to `from django impo...
Sort list of strings and place numbers after letters in python
24,624,644
3
2014-07-08T05:58:38Z
24,624,700
7
2014-07-08T06:02:10Z
[ "python", "string", "sorting" ]
I have a list of strings that I want to sort. By default, letters have a larger value than numbers (or string numbers), which places them last in a sorted list. ``` >>> 'a' > '1' True >>> 'a' > 1 True ``` I want to be able to place all the strings that begins with a number at the bottom of the list. Example: Unsor...
``` >>> a = ['big', 'apple', '42nd street', '25th of May', 'subway'] >>> sorted(a, key=lambda x: (x[0].isdigit(), x)) ['apple', 'big', 'subway', '25th of May', '42nd street'] ``` Python's sort functions take an optional `key` parameter, allowing you to specify a function that gets applied before sorting. Tuples are so...
Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""
24,627,525
73
2014-07-08T08:51:55Z
24,627,797
37
2014-07-08T09:05:01Z
[ "python", "pip" ]
Searching the net this seems to be a problem caused by spaces in the Python installation path. How do I get `pip` to work without having to reinstall everything in a path without spaces ?
On Windows at least, `pip` stores the execution path in the executable `pip.exe` when it is installed. Edit this file using a hex editor or WordPad (you have to save it as plain text then to retain binary data), change the path to Python with quotes and spaces like this: ``` #!"C:\Program Files (x86)\Python33\python....
Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""
24,627,525
73
2014-07-08T08:51:55Z
26,428,562
146
2014-10-17T15:37:09Z
[ "python", "pip" ]
Searching the net this seems to be a problem caused by spaces in the Python installation path. How do I get `pip` to work without having to reinstall everything in a path without spaces ?
it seems that ``` python -m pip install XXX ``` will work anyway (worked for me) (see link by user474491)
Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""
24,627,525
73
2014-07-08T08:51:55Z
26,694,976
17
2014-11-02T01:04:52Z
[ "python", "pip" ]
Searching the net this seems to be a problem caused by spaces in the Python installation path. How do I get `pip` to work without having to reinstall everything in a path without spaces ?
having the same trouble I read in <https://pip.pypa.io/en/latest/installing.html#install-pip> that to update pip it's: `python -m pip install -U pip` So I made (for example) `python -m pip install virtualenv` And it worked! So you can do the same being 'virtualenv' another package you want.
Django using get_user_model vs settings.AUTH_USER_MODEL
24,629,705
10
2014-07-08T10:40:48Z
24,630,589
13
2014-07-08T11:25:36Z
[ "python", "django" ]
Reading the Django Documentation: **get\_user\_model()** > Instead of referring to User directly, you should reference the user > model using django.contrib.auth.get\_user\_model(). This method will > return the currently active User model – the custom User model if one > is specified, or User otherwise. > > When y...
Using `settings.AUTH_USER_MODEL` will delay the retrieval of the actual model class until all apps are loaded. `get_user_model` will attempt to retrieve the model class at the moment your app is imported the first time. `get_user_model` cannot guarantee that the `User` model is already loaded into the app cache. It mi...
Python try/except: trying multiple options
24,630,757
8
2014-07-08T11:33:33Z
24,630,828
7
2014-07-08T11:37:29Z
[ "python", "exception-handling" ]
I'm trying to scrape some information from webpages that are inconsistent about where the info is located. I've got code to handle each of several possibilities; what I want is to try them in sequence, then if none of them work I'd like to fail gracefully and move on. That is, in psuedo-code: ``` try: info = look...
If each lookup is a separate function, you can store all the functions in a list and then iterate over them one by one. ``` lookups = [ look_in_first_place, look_in_second_place, look_in_third_place ] info = None for lookup in lookups: try: info = lookup() # exit the loop on success ...
UnicodeDecodeError: 'utf-8' codec can't decode byte error
24,632,298
6
2014-07-08T12:48:08Z
24,632,340
11
2014-07-08T12:50:21Z
[ "python", "encoding", "utf-8", "urllib" ]
I'm trying to get a response from `urllib` and decode it to a readable format. The text is in Hebrew and also contains characters like `{` and `/` top page coding is: ``` # -*- coding: utf-8 -*- ``` raw string is: ``` b'\xff\xfe{\x00 \x00\r\x00\n\x00"\x00i\x00d\x00"\x00 \x00:\x00 \x00"\x001\x004\x000\x004\x008\x003...
Your problem is that that is not UTF-8. You have **UTF-16** encoded data, decode it as such: ``` >>> data = b'\xff\xfe{\x00 \x00\r\x00\n\x00"\x00i\x00d\x00"\x00 \x00:\x00 \x00"\x001\x004\x000\x004\x008\x003\x000\x000\x006\x004\x006\x009\x006\x00"\x00,\x00\r\x00\n\x00"\x00t\x00i\x00t\x00l\x00e\x00"\x00 \x00:\x00 \x00"\...
Why is type(bytes()) <'str'>
24,633,024
6
2014-07-08T13:23:12Z
24,633,056
8
2014-07-08T13:25:02Z
[ "python", "python-2.7" ]
I'm fairly new to python and I appreciate it's a dynamic language. Some 30 minutes into my first python code, I've discovered that the `bytes` type behaves a little strange (to say the least): ``` a = bytes() print type(a) // prints: <type 'str'> ``` Try it here: <http://ideone.com/NqbcHk> Now, the [docs](https://do...
You're looking at the Python 3 docs. In Python 2, `bytes` is an alias for `str`, added to make it easier to write forward-compatible code (Python 2's `str` is a byte string, while in Python 3 `str` is what was called `unicode` in Python 2). For more details, see [What’s New In Python 3.0](https://docs.python.org/3.0...
Why is type(bytes()) <'str'>
24,633,024
6
2014-07-08T13:23:12Z
24,633,058
10
2014-07-08T13:25:12Z
[ "python", "python-2.7" ]
I'm fairly new to python and I appreciate it's a dynamic language. Some 30 minutes into my first python code, I've discovered that the `bytes` type behaves a little strange (to say the least): ``` a = bytes() print type(a) // prints: <type 'str'> ``` Try it here: <http://ideone.com/NqbcHk> Now, the [docs](https://do...
The `bytes` type is new in Python 3.x. In Python 2.x, as a compatibility shim, `bytes` is a simple alias to `str`. Read more about this here: <https://docs.python.org/2/whatsnew/2.6.html#pep-3112-byte-literals> > Python 3.0 adopts Unicode as the language’s fundamental string type > and denotes 8-bit literals differ...
Django change password issue, super(type, obj): obj must be an instance or subtype of type
24,633,601
7
2014-07-08T13:50:25Z
24,633,645
12
2014-07-08T13:52:30Z
[ "python", "django", "passwords" ]
i'm having some trouble with my changepassword form, it continues to give me the same error: super(type, obj): obj must be an instance or subtype of type this is my form: ``` class PasswordChangeForm(forms.Form): current_password = forms.CharField(label=u'Current Password', widget=forms.PasswordInput(render_value...
Your issue is in this line: ``` super(UserProfileEditForm, self).__init__(data=data, *args, **kwargs) ``` It should be ``` super(PasswordChangeForm, self).__init__(data=data, *args, **kwargs) ``` It is probably a copy-paste issue, when you were copying from the other form. Some more [context here](https://docs.pyt...
Boto S3 API does not return full list of keys
24,634,232
3
2014-07-08T14:19:52Z
24,637,193
7
2014-07-08T16:37:58Z
[ "python", "amazon-web-services", "amazon-s3", "boto" ]
I use boto S3 API in my python script which slowly copies data from S3 to my local filesystem. The script worked well for a couple of days, but now there is a problem. I use the following API function to obtain the list of keys in "directory": ``` keys = bucket.get_all_keys(prefix=dirname) ``` And this function (`ge...
There is an easier way. The `Bucket` object itself can act as an iterator and it knows how to handle paginated responses. So, if there are more results available, it will automatically fetch them behind the scenes. So, something like this should allow you to iterate over all of the objects in your bucket: ``` for key ...
storing the python-dictionary with 10000 lines in mysql - instead of printing
24,635,811
3
2014-07-08T15:27:36Z
24,636,400
7
2014-07-08T15:55:14Z
[ "php", "python", "mysql", "sql", "database" ]
see below **update 2** i did as you adviced me: **update:** see the important updates: want to store the data to the mysql-db ``` {'url': 'http://dom1', 'name': 'miller', 'name2': 'phil man', 'email-adress': 'waddehadde@hotmail.com'} {'url': 'http://dom2', 'name': 'jonboy', 'name2': 'Josef dude', 'email-adress': 'wa...
Assuming you want to use python and peewee, I would do something like the following: ``` from peewee import * import json db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy') class User(Model): name = TextField() name2 = TextField() email_address = TextField() url = TextField() class Me...
Using RabbitMQ with Plone - Celery or not?
24,636,315
3
2014-07-08T15:51:31Z
24,650,440
7
2014-07-09T09:50:43Z
[ "python", "rabbitmq", "plone", "celery" ]
I hope I am posting this in the right place. I am researching RabbitMQ for potential use in our Plone sites. We currently us Async on a dedicated worker client in the Plone server, but we are thinking about building a dedicated RabbitMQ server that will handle all Plone messaging and other activity. My specific quest...
At first, ask yourself, if you need the features of RabbitMQ or just want to do some asynchronous tasks in Python with Plone. If you don't really need RabbitMQ, you could look into David Glick's gists for how to integrate Celery with Plone (and still use RabbitMQ with Celery): * <https://gist.github.com/davisagli/582...
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
24,639,907
13
2014-07-08T19:11:57Z
25,537,015
10
2014-08-27T21:12:29Z
[ "python", "gunicorn" ]
I've installed gunicorn inside my virtualenv. From this directory: ``` manage.py /onbytes/wsgi.py ``` I run the following: ``` gunicorn onbytes.wsgi:application ``` And I get the following error: ``` Traceback (most recent call last): File "/home/ymorin007/.virtualenvs/onbytes.com/bin/gunicorn", line 9, in <mod...
I had a similar problem and it was because i was running the command in the wrong directory. In a standard django installation, try running gunicorn in the same directory that 'manage.py'
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
24,639,907
13
2014-07-08T19:11:57Z
25,689,349
25
2014-09-05T15:32:06Z
[ "python", "gunicorn" ]
I've installed gunicorn inside my virtualenv. From this directory: ``` manage.py /onbytes/wsgi.py ``` I run the following: ``` gunicorn onbytes.wsgi:application ``` And I get the following error: ``` Traceback (most recent call last): File "/home/ymorin007/.virtualenvs/onbytes.com/bin/gunicorn", line 9, in <mod...
Probably there is an issue in your application, not in gunicorn. Try: ``` gunicorn --log-file=- onbytes.wsgi:application ``` Since the version R19, Gunicorn doesn’t log by default in the console and the --debug option was deprecated.
how to unstack (or pivot?) in pandas
24,640,399
4
2014-07-08T19:40:12Z
24,640,886
10
2014-07-08T20:09:52Z
[ "python", "pandas", "stack", "pivot" ]
I have a dataframe that looks like the following: ``` import pandas as pd datelisttemp = pd.date_range('1/1/2014', periods=3, freq='D') s = list(datelisttemp)*3 s.sort() df = pd.DataFrame({'BORDER':['GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY' ], 'HOUR1':[2 ,2 ,2 ,4 ,4 ,4 ,6 ,6, 6],...
We want values (e.g. `'GERMANY'`) to become column names, and column names (e.g. `'HOUR1'`) to become values -- a swap of sorts. The `stack` method turns column names into index values, and the `unstack` method turns index values into column names. So by shifting the values into the index, we can use `stack` and `uns...
protocol error setting up virtualenvironment through vagrant on ubuntu
24,640,819
9
2014-07-08T20:04:45Z
26,193,922
9
2014-10-04T14:47:58Z
[ "python", "ubuntu", "virtualenv", "vagrant" ]
I'm trying to set up a virtualenv on Ubuntu 12.04 with Python 2.7 using vagrant but having same issues. it seems like this issues is seen only when "vagrant up" is issued from windows. what is the solution? any pointers? ``` New python executable in .vagrant-env/bin/python Traceback (most recent call last): File "...
This error can be fixed if you create the virtual env outside the /vagrant/ shared folder... If go to the home folder of your vagrant user, you can create the virtualenv in there without this problem! Just the venv must be out of this /vagrant/ directory... after that you can go work as usually activating this venv a...
protocol error setting up virtualenvironment through vagrant on ubuntu
24,640,819
9
2014-07-08T20:04:45Z
26,637,493
22
2014-10-29T17:58:13Z
[ "python", "ubuntu", "virtualenv", "vagrant" ]
I'm trying to set up a virtualenv on Ubuntu 12.04 with Python 2.7 using vagrant but having same issues. it seems like this issues is seen only when "vagrant up" is issued from windows. what is the solution? any pointers? ``` New python executable in .vagrant-env/bin/python Traceback (most recent call last): File "...
The solution is to use `--always-copy`. See [here](https://github.com/gratipay/gratipay.com/issues/2327) for the gory details.
protocol error setting up virtualenvironment through vagrant on ubuntu
24,640,819
9
2014-07-08T20:04:45Z
27,311,356
7
2014-12-05T07:59:41Z
[ "python", "ubuntu", "virtualenv", "vagrant" ]
I'm trying to set up a virtualenv on Ubuntu 12.04 with Python 2.7 using vagrant but having same issues. it seems like this issues is seen only when "vagrant up" is issued from windows. what is the solution? any pointers? ``` New python executable in .vagrant-env/bin/python Traceback (most recent call last): File "...
I found the issue and fixed it. Just start your git bash/cmd prompt console as an administrator. Then, vagrant up > setup your virtual env. It should be a cake walk. Thanks Venkat
Using Python Requests to send file and JSON in single request
24,642,040
4
2014-07-08T21:41:39Z
24,748,562
7
2014-07-15T01:23:13Z
[ "python", "rest", "python-requests" ]
I'm trying to POST to an API (Build using SlimPHP) which accepts an image along with additional image meta data in the form of JSON. I've verified the API works correctly using a REST client tool and can successfully POST to the service. All data is stored correctly. I'm now trying to POST using Python - however my J...
Your problem is that you are using the image metadata as the source of key/value pairs to be posted. Instead of sending it as the value of one of those key/value pairs. The following code will send a request much like the curl statement you provided: ``` url = 'my-url.com/api/endpoint' headers = {'Authorization': 'my...
Python Quickest way to round every float in nested list of tuples
24,642,669
2
2014-07-08T22:43:50Z
24,642,866
7
2014-07-08T23:01:26Z
[ "python" ]
I have a list of coordinates like this: ``` [[(-88.99716274669669, 45.13003508233472), (-88.46889143213836, 45.12912220841379), (-88.47075415770517, 44.84090409706577), (-88.75033424251002, 44.84231949526811), (-88.75283245650954, 44.897062864942406), (-88.76794136151051, 44.898020801741716), (-88.77994787408718, 44.9...
I don't know about "quickest" (quickest to write? read? runtime?), but this is how I'd write it recursively: ``` def re_round(li, _prec=5): try: return round(li, _prec) except TypeError: return type(li)(re_round(x, _prec) for x in li) ``` demo: ``` x = [[(-88.99716274669669, 45.1300350823...
how to print dataframe without index
24,644,656
14
2014-07-09T02:50:29Z
32,662,331
15
2015-09-18T23:09:38Z
[ "python", "datetime", "pandas", "dataframe" ]
I want to print the whole dataframe, but I don't want to print the index Besides, one column is datetime type, I just want to print time, not date. The dataframe looks like: ``` User ID Enter Time Activity Number 0 123 2014-07-08 00:09:00 1411 1 123 2014-07-08 00:18:00 ...
``` print df.to_string(index=False) ```
pandas dataframe columns scaling with sklearn
24,645,153
13
2014-07-09T03:57:55Z
28,479,181
12
2015-02-12T13:51:03Z
[ "python", "pandas", "scikit-learn", "dataframe" ]
I have a pandas dataframe with mixed type columns, and I'd like to apply sklearn's min\_max\_scaler to some of the columns. Ideally, I'd like to do these transformations in place, but haven't figured out a way to do that yet. I've written the following code that works: ``` import pandas as pd import numpy as np from s...
Like this? ``` dfTest = pd.DataFrame({ 'A':[14.00,90.20,90.95,96.27,91.21], 'B':[103.02,107.26,110.35,114.23,114.68], 'C':['big','small','big','small','small'] }) dfTest[['A','B']] = dfTest[['A','B']].apply( lambda x: MinMaxScaler().fit_transform(x)...
pandas dataframe columns scaling with sklearn
24,645,153
13
2014-07-09T03:57:55Z
36,475,297
7
2016-04-07T11:48:04Z
[ "python", "pandas", "scikit-learn", "dataframe" ]
I have a pandas dataframe with mixed type columns, and I'd like to apply sklearn's min\_max\_scaler to some of the columns. Ideally, I'd like to do these transformations in place, but haven't figured out a way to do that yet. I've written the following code that works: ``` import pandas as pd import numpy as np from s...
I am not sure if previous versions of `pandas` prevented this but now the following snippet works perfectly for me and produces exactly what you want without having to use `apply` ``` >>> import pandas as pd >>> from sklearn.preprocessing import MinMaxScaler >>> scaler = MinMaxScaler() >>> dfTest = pd.DataFrame({'A...
Django NameError: name 'views' is not defined
24,650,261
2
2014-07-09T09:41:36Z
24,650,361
8
2014-07-09T09:46:34Z
[ "python", "django" ]
I am working through [this tutorial](http://code.tutsplus.com/tutorials/rapid-website-deployment-with-django-heroku-new-relic--cms-21543) on rapid site development with `Django.` I have followed it exactly (as far as I can see), but get the following error when I try to view the index page: ``` NameError at /name 'vi...
The error line is ``` url(r'^$', views.index, name='index'), #----------^ ``` Here `views` is not defined, hence the error. You need to import it from your app. in urls.py add line ``` from <your_app> import views # replace <your_app> with your application name. ```
Python - Send HTML-formatted email via Outlook 2007/2010 and win32com
24,650,518
7
2014-07-09T09:54:30Z
24,650,720
9
2014-07-09T10:03:56Z
[ "python", "html", "email", "outlook" ]
Is there a way to send HTML-formatted email using Python's win32com.client (which utilizes Outlook 2007/2010). The format I'm using now looks like this: ``` import win32com.client olMailItem = 0x0 obj = win32com.client.Dispatch("Outlook.Application") newMail = obj.CreateItem(olMailItem) newMail.Subject = "the subject"...
This is the way to make the body in html format ``` newMail.HTMLBody = htmltext ```
ImportError: No module named request
24,652,074
16
2014-07-09T11:08:37Z
24,652,184
15
2014-07-09T11:13:08Z
[ "python", "speech-recognition" ]
I am trying to install python `SpeechRecognition` on my machine.When i am trying to install the package as `pip install SpeechRecognition`. I am getting the following error. ``` import json, urllib.request ImportError: No module named request ``` And then i referred and installed requests as `pip install requests` i...
The `SpeechRecognition` library [requires Python 3.3 or up](https://pypi.python.org/pypi/SpeechRecognition): > ### Requirements > > [...] > > The first software requirement is Python 3.3 or better. This is required to use the library. and from the Trove classifiers: > Programming Language :: Python > Programming L...
Elegant way to iterate over heads of lists in Python
24,653,628
2
2014-07-09T12:23:16Z
24,653,658
8
2014-07-09T12:24:51Z
[ "python", "list", "iteration", "generator" ]
Imagine I have a list of `["a", "b", "c", "d"]` I am looking for a Pythonic idiom for doing roughly this: ``` for first_elements in head(mylist): # would first yield ["a"], then ["a", "b], then ["a", "b", "c"] # until the whole list gets generated as a result, after which the generator # terminates. ``` My ...
You mean this? ``` def head(it): val = [] for elem in it: val.append(elem) yield val ``` This takes any iterable, not just lists. Demo: ``` >>> for first_elements in head('abcd'): ... print first_elements ... ['a'] ['a', 'b'] ['a', 'b', 'c'] ['a', 'b', 'c', 'd'] ```
How to use Python sets and add strings to it in as a dictionary value
24,654,183
7
2014-07-09T12:50:20Z
24,654,261
12
2014-07-09T12:53:32Z
[ "python", "dictionary", "set" ]
I am trying to create a dictionary that has values as a Set object. I would like a collection of unique names associated with a unique reference). My aim is to try and create something like: **AIM:** ``` Dictionary[key_1] = set('name') Dictionary[key_2] = set('name_2', 'name_3') ``` **Adding to SET:** ``` Dicti...
`('name')` is not a tuple. It's just the expression `'name'`, parenthesized. A one-element tuple is written `('name',)`; a one-element list `['name']` is prettier and works too. In Python 2.7, 3.x you can also write `{'name'}` to construct a set.
Regex for existence of some words whose order doesn't matter
24,656,131
9
2014-07-09T14:15:15Z
24,656,216
22
2014-07-09T14:19:04Z
[ "python", "regex", "string", "string-matching", "regex-lookarounds" ]
I would like to write a regex for searching for the existence of some words, but their order of appearance doesn't matter. For example, search for "Tim" and "stupid". My regex is `Tim.*stupid|stupid.*Tim`. But is it possible to write a simpler regex (e.g. so that the two words appear just once in the regex itself)?
See this regex: ``` /^(?=.*Tim)(?=.*stupid).+/ ``` **Regex explanation:** * `^` Asserts position at start of string. * `(?=.*Tim)` Asserts that "Tim" is present in the string. * `(?=.*stupid)` Asserts that "stupid" is present in the string. * `.+`Now that our phrases are present, this string is valid. Go ahead and u...
find peaks location in a spectrum numpy
24,656,367
4
2014-07-09T14:25:00Z
24,693,260
8
2014-07-11T08:26:22Z
[ "python", "numpy" ]
I have a TOF spectrum and I would like to implement an algorithm using python (numpy) that finds all the maxima of the spectrum and returns the corresponding x values. I have looked up online and I found the algorithm reported below. The assumption here is that near the maximum the difference between the value befor...
This, I think could work as a starting point. I'm not a signal-processing expert, but I tried this on a generated signal `Y` that looks quite like yours and one with much more noise: ``` from scipy.signal import convolve import numpy as np from matplotlib import pyplot as plt #Obtaining derivative kernel = [1, 0, -1] ...
Bamboo failing test can't parse junit
24,657,958
3
2014-07-09T15:36:18Z
25,442,699
7
2014-08-22T08:28:18Z
[ "python", "testing", "junit", "bamboo" ]
I'm using bamboo as CI server for my django project and for a good start, I've made a simple script to know how bamboo shows the successful and the failing tests. I use py.test like this : ``` py.test test.py --junitxml=junitresults/results.xml ``` my test.py file contains something like this : ``` def test_that_fai...
Just for sharing what I've found. The thing I was ignoring is that Bamboo stops the tasks chain if one fails. So if `python manage.py test` fails due to an error in a testcase, bamboo stops and won't parse the junit results. The solution was to place the junit parser as a task in the end, under the section 'Final Task...
cython issue: 'bool' is not a type identifier
24,659,723
7
2014-07-09T17:04:02Z
24,659,818
9
2014-07-09T17:09:26Z
[ "python", "c++", "cython" ]
I'm desperately trying to expose a `std::vector<bool>` class member to a Python class. Here is my C++ class: ``` class Test { public: std::vector<bool> test_fail; std::vector<double> test_ok; }; ``` While the access and conversion of `test_ok` of type `double` (or int, float, ..) works, it does not for `bo...
There's some extra C++ support you need to do. At the top of your .pyx file, add ``` from libcpp cimport bool ``` I'd take a look inside that to find the other things you might need, like std::string and STL containers
Necessity of explicit cursor.close()
24,661,754
13
2014-07-09T19:00:06Z
24,662,568
9
2014-07-09T19:48:09Z
[ "python", "django", "database", "cursor", "database-connection" ]
From time to time, I'm executing raw queries using [`connection.cursor()`](https://docs.djangoproject.com/en/dev/topics/db/sql/#connections-and-cursors) instead of using ORM (since it is definitely not a silver bullet). I've noticed that in several places I don't call explicit `cursor.close()` after I'm done with data...
Django's `cursor` class is just a wrapper around the underlying DB's `cursor`, so the effect of leaving the `cursor` open is basically tied to the underlying DB driver. According to psycopg2's (psycopg2 is DB driver Django uses for PostgreSQL DB's) [FAQ](http://initd.org/psycopg/docs/faq.html#best-practices), their cu...
Add one hour forward to current time in Python
24,662,472
3
2014-07-09T19:43:13Z
24,662,582
7
2014-07-09T19:48:46Z
[ "python", "python-2.7", "datetime", "time" ]
I'm working on my Python script to get the hours time. When my current time is 8:30PM, I want to know how I can add the hour forward in the labels which it will be 9:00PM, 9:30PM? Here is for example: ``` if (0 <= datetime.datetime.now().minute <= 29): self.getControl(4203).setLabel(time.strftime("%I").lstrip('0'...
For time offsets you can use [`datetime.timedelta`](https://docs.python.org/2/library/datetime.html#datetime.timedelta): ``` >>> import datetime >>> datetime.datetime.now() datetime.datetime(2014, 7, 9, 21, 47, 6, 178534) >>> datetime.datetime.now() + datetime.timedelta(hours=1) datetime.datetime(2014, 7, 9, 22, 47,...
Python import csv to list
24,662,571
52
2014-07-09T19:48:13Z
24,662,707
97
2014-07-09T19:55:32Z
[ "python", "csv" ]
I have a CSV file with about 2000 records. Each record has a string, and a category to it. ``` This is the first line, Line1 This is the second line, Line2 This is the third line, Line3 ``` I need to read this file into a list that looks like this; ``` List = [('This is the first line', 'Line1'), ('This is ...
Use the [`csv`](https://docs.python.org/2/library/csv.html) module: ``` import csv with open('file.csv', 'rb') as f: reader = csv.reader(f) your_list = list(reader) print your_list # [['This is the first line', 'Line1'], # ['This is the second line', 'Line2'], # ['This is the third line', 'Line3']] ``` If ...
Python import csv to list
24,662,571
52
2014-07-09T19:48:13Z
35,340,988
12
2016-02-11T13:43:09Z
[ "python", "csv" ]
I have a CSV file with about 2000 records. Each record has a string, and a category to it. ``` This is the first line, Line1 This is the second line, Line2 This is the third line, Line3 ``` I need to read this file into a list that looks like this; ``` List = [('This is the first line', 'Line1'), ('This is ...
Update for **Python3**: ``` import csv with open('file.csv', 'r') as f: reader = csv.reader(f) your_list = list(reader) print(your_list) # [['This is the first line', 'Line1'], # ['This is the second line', 'Line2'], # ['This is the third line', 'Line3']] ```
Upload an image from Django shell
24,665,259
4
2014-07-09T23:26:42Z
24,666,519
9
2014-07-10T02:21:22Z
[ "python", "django", "file", "shell" ]
I need to import a bunch of images into a Django app. I am testing in the shell but cannot get past this error when attempting to save the image: ``` File "/lib/python3.3/codecs.py", line 301, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode b...
I'd been bit by this before, so I feel you -- but as per my comment: replace the `'r'` with `'rb'` in the File() call, and it should work fine. I should also add, for those who come upon this answer later, that this is an issue specific to Python3. Take a look at the SO link in Steve's comment for a fuller explanation...
How to test coverage properly with Django + Nose
24,668,174
9
2014-07-10T03:50:14Z
29,650,256
9
2015-04-15T12:29:51Z
[ "python", "django", "code-coverage", "django-nose" ]
Currently have a project configured to run coverage via Django's manage command like so: ``` ./manage.py test --with-coverage --cover-package=notify --cover-branches --cover-inclusive --cover-erase ``` This results in a report like the following: ``` Name Stmts Miss Branch BrMiss Cover Mi...
At the moment it's not possible to accurately run coverage alongside with django-nose (because of the way Django 1.7 loads models). So to get the coverage stats, you need to use coverage.py directly from command line, e.g: ``` $ coverage run --branch --source=app1,app2 ./manage.py test $ coverage report $ coverage htm...
Python Bottle and Cache-Control
24,672,996
9
2014-07-10T09:31:43Z
24,748,094
12
2014-07-15T00:20:52Z
[ "python", "caching", "bottle" ]
I have an application with Python Bottle and I want to add Cache-Control in static files. I am new on this so forgive me if I have done something wrong. Here is the function and how I serve static files: ``` @bottle.get('/static/js/<filename:re:.*\.js>') def javascripts(filename): return bottle.static_file(filenam...
I had a look at the [source code](https://github.com/defnull/bottle/blob/master/bottle.py#L2325) for `static_file()` and found the solution. You need to assign the result of `static_file(...)` to a variable and call `set_header()` on the resulting `HTTPResponse` object. ``` #!/usr/bin/env python import bottle @bot...
ca-certificates Mac OS X
24,675,167
10
2014-07-10T11:18:19Z
28,274,272
14
2015-02-02T09:12:56Z
[ "python", "osx", "ssl" ]
I need to install offlineimap and mu4e on emacs. Problem is configuration. When I run offlineimap I get : ``` OfflineIMAP 6.5.5 Licensed under the GNU GPL v2+ (v2 or any later version) Thread 'Account sync Gmail' terminated with exception: Traceback (most recent call last): File "/usr/local/Cellar/offline-imap/6.5.6/l...
I had a similar problem (on MacOS 10.10.2, openssl 1.0.2 and offlineimap 6.5.5 both from homebrew) and couldn't get the dummy certificate solution to work. However, I found a certfile that makes offlineimap stop complaining in `/usr/local/etc/openssl/cert.pem` (which is put there during the installation of openssl thro...
Python-peewee get last saved row
24,675,271
2
2014-07-10T11:23:38Z
24,680,185
7
2014-07-10T15:12:56Z
[ "python", "orm", "peewee" ]
is there a way how to obtain last saved row in database while using peewee with all its attributes? Let's say I do this: ``` user = User.create( email = request.json['email'], nickname = request.json['nickname'], password = request.json['password'], salt = "salt" ) ``` But `user.id` is `None` and the ...
``` User.select().order_by(User.id.desc()).get() ``` This will get the last-created user assuming the IDs is an auto-incrementing integer (the default). If you want to get the last *saved* user, you need to add a timestamp to indicate when the user is saved. --- Update: Peewee also now supports `RETURNING` clause ...
numpy python 3.4.1 installation: Python 3.4 not found in registry
24,676,609
5
2014-07-10T12:29:28Z
27,412,399
7
2014-12-10T22:55:34Z
[ "python", "python-3.x", "numpy" ]
I have two python versions on my computer 2.7 and 3.4.1 . I have tried to install numpy by pip3.4 which resulted with *vcvarsall.bat* not found which i am pretty sure it is included in system path. Then i gave up downloaded numpy binary [numpy-1.8.1-win32-superpack-python3.4.exe](http://sourceforge.net/projects/numpy/f...
*This steps work for me with windows 8.1 64bits* The problem is that some module installers look in the wrong place for Python version information. For example, in the case of this one module, the installer was looking for `HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.4` in the registry. I found that my Python 3.4...
Should I use 'in' or 'or' in an if statement in Python 3.x to check a variable against multiple values?
24,678,118
2
2014-07-10T13:41:41Z
24,678,205
9
2014-07-10T13:45:10Z
[ "python", "performance" ]
Suppose I have the following, which is the better, faster, more Pythonic method and why? ``` if x == 2 or x == 3 or x == 4: do following... ``` or : ``` if x in (2, 3, 4): do following... ```
In Python 3 (3.2 and up), you should use a *set*: ``` if x in {2, 3, 4}: ``` as set membership is a O(1) test, versus a worst-case performance of O(N) for testing with separate `or` equality tests or using membership in a tuple. In Python 3, the set literal will be optimised to use a `frozenset` constant: ``` >>> i...
Django error: "'ChoiceField' object has no attribute 'is_hidden'"
24,679,181
4
2014-07-10T14:26:45Z
24,679,263
8
2014-07-10T14:30:37Z
[ "python", "django", "forms", "django-forms" ]
Django template throws 'AttributeError' when rendering..What I want to achive is that in the template the resolted forn will contain a select box with the values from the list below. Here's the `Forms.py` file: ``` class CallForm (forms.ModelForm): class Meta(): model = Call widgets = { 'employee_id...
[`ChoiceField`](https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield) is not a widget - it is a [form field](https://docs.djangoproject.com/en/dev/ref/forms/fields): ``` class CallForm (forms.ModelForm): employee_id = forms.ChoiceField(choices=FormsTools.EmployeesToTuples(Employee.objects.all())) ...
django: User Registration with error: no such table: auth_user
24,682,155
8
2014-07-10T16:49:40Z
24,682,252
7
2014-07-10T16:55:22Z
[ "python", "django", "authentication", "authorization" ]
I try to use Django's default Auth to handle register and login. And I think the procedure is pretty standard, but mine is with sth wrong. my setting.py: ``` INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib....
This seems very elementary, but have you initialized the tables with the command ``` manage.py syncdb ``` This allows you to nominate a "super user" as well as initializing any tables.
django: User Registration with error: no such table: auth_user
24,682,155
8
2014-07-10T16:49:40Z
24,682,472
9
2014-07-10T17:09:02Z
[ "python", "django", "authentication", "authorization" ]
I try to use Django's default Auth to handle register and login. And I think the procedure is pretty standard, but mine is with sth wrong. my setting.py: ``` INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib....
### Update You are probably getting this error because you are using `UserCreationForm` modelform, in which in `META` it contains `User`(django.contrib.auth.models > User) as model. ``` class Meta: model = User fields = ("username",) ``` And here you are using your own custom auth model, so tables related to...
django: User Registration with error: no such table: auth_user
24,682,155
8
2014-07-10T16:49:40Z
32,737,460
9
2015-09-23T10:43:23Z
[ "python", "django", "authentication", "authorization" ]
I try to use Django's default Auth to handle register and login. And I think the procedure is pretty standard, but mine is with sth wrong. my setting.py: ``` INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib....
``` ./manage.py migrate ``` If you've just enabled all the middlewares etc this will run each migration and add the missing tables.
Add reply to address to django EmailMultiAlternatives
24,685,529
2
2014-07-10T20:18:34Z
24,685,754
7
2014-07-10T20:31:54Z
[ "python", "django" ]
I am trying to add a "reply to" email while using django's EmailMultiAlternatives format. The documentation demonstrates who to do it with EmailMessage class but doesn't show how to do it when using EmailMultiAlternatives. <https://docs.djangoproject.com/en/dev/topics/email/?from=olddocs#sending-alternative-content-ty...
To add `Reply-To` in `EmailMultiAlternatives` you have to do it in the same way you do so with `EmailMessage`. As you can see in django's source code [EmailMultiAlternatives](https://github.com/django/django/blob/master/django/core/mail/message.py#L377) inherits from [EmailMessage](https://github.com/django/django/blo...
shipping python modules in pyspark to other nodes?
24,686,474
10
2014-07-10T21:18:36Z
24,686,708
18
2014-07-10T21:35:20Z
[ "python", "apache-spark" ]
How can I ship C compiled modules (for example, python-Levenshtein) to each node in a spark cluster? I know that I can ship python files in spark using a standalone python script (example code below): ``` from pyspark import SparkContext sc = SparkContext("local", "App Name", pyFiles=['MyFile.py', 'MyOtherFile.py']) ...
If you can package your module into a `.egg` or `.zip` file, you should be able to list it in `pyFiles` when constructing your SparkContext (or you can add it later through [sc.addPyFile](https://spark.apache.org/docs/latest/api/python/pyspark.context.SparkContext-class.html#addPyFile)). For Python libraries that use ...
How can I identify requests made via AJAX in Python's Flask?
24,687,736
7
2014-07-10T23:06:57Z
24,687,968
12
2014-07-10T23:34:09Z
[ "python", "ajax", "angularjs", "flask" ]
I'd like to detect if the browser made a request via AJAX (AngularJS) so that I can return a JSON array, or if I have to render the template. How can I do this?
Flask comes with a `is_xhr` attribute in the `request` object. ``` from flask import request @app.route('/', methods=['GET', 'POST']) def home_page(): if request.is_xhr: context = controllers.get_default_context() return render_template('home.html', **context) ```
Async like pattern in pyqt? Or cleaner background call pattern?
24,689,800
9
2014-07-11T03:47:41Z
24,739,145
8
2014-07-14T14:42:24Z
[ "python", "qt", "pyqt", "nonblocking" ]
I'm trying to write a short(one file pyqt) program which is responsive(so dependencies outside python/lxml/qt, especially ones I can't just stick in the file have some downsides for this use case but I might still be willing to try them). I'm trying to perform possibly lengthy(and cancelable) operations on a worker thr...
The short answer to your question ("is there a way to use an `asyncio`-like pattern in PyQt?") is yes, but it's pretty complicated and arguably not worth it for a small program. Here's some prototype code that allows you to use an asynchronous pattern like you described: ``` import types import weakref from functools ...
Why can I use the same name for iterator and sequence in a Python for loop?
24,689,967
73
2014-07-11T04:08:24Z
24,690,060
66
2014-07-11T04:20:57Z
[ "python", "for-loop", "variable-assignment", "python-internals" ]
This is more of a conceptual question. I recently saw a piece of code in Python (it worked in 2.7, and it might also have been run in 2.5 as well) in which a `for` loop used the same name for both the list that was being iterated over and the item in the list, which strikes me as both bad practice and something that sh...
What does `dis` tell us: ``` Python 3.4.1 (default, May 19 2014, 13:10:29) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from dis import dis >>> dis("""x = [1,2,3,4,5] ... for x in x: ... print(x) ... print(x)""") 1 ...
Why can I use the same name for iterator and sequence in a Python for loop?
24,689,967
73
2014-07-11T04:08:24Z
24,690,950
42
2014-07-11T05:59:16Z
[ "python", "for-loop", "variable-assignment", "python-internals" ]
This is more of a conceptual question. I recently saw a piece of code in Python (it worked in 2.7, and it might also have been run in 2.5 as well) in which a `for` loop used the same name for both the list that was being iterated over and the item in the list, which strikes me as both bad practice and something that sh...
Using your example code as the core reference ``` x = [1,2,3,4,5] for x in x: print x print x ``` I would like you to refer the section [7.3. The for statement](https://docs.python.org/2/reference/compound_stmts.html#the-for-statement) in the manual **Excerpt 1** > The expression list is evaluated once; it shou...
Is it good practice to yield from within a context manager?
24,691,234
11
2014-07-11T06:18:38Z
24,692,431
7
2014-07-11T07:37:53Z
[ "python", "generator", "contextmanager" ]
I recently wrote a method which returned a sequence of open files; in other words, something like this: ``` # this is very much simplified, of course # the actual code returns file-like objects, not necessarily files def _iterdir(self, *path): dr = os.path.join(*path) paths = imap(lambda fn: os.path.join(dr, f...
There are two problems I see. One is that if you try to use more than one file at a time, things break: ``` list(iterdir('/', 'usr')) # Doesn't work; they're all closed. ``` The second is unlikely to happen in CPython, but if you have a reference cycle, or if your code is ever run on a different Python implementation...
Is there an equivalent to the "for ... else" Python loop in C++?
24,693,694
35
2014-07-11T08:50:37Z
24,693,825
7
2014-07-11T08:57:49Z
[ "python", "c++", "loops", "for-loop", "break" ]
Python has an interesting `for` statement which lets you specify an `else` clause. In a construct like this one: ``` for i in foo: if bar(i): break else: baz() ``` the `else` clause is executed after the `for`, but only if the `for` terminates normally (not by a `break`). I wondered if there was an equivale...
This is my rough implementation in C++: ``` bool other = true; for (int i = 0; i > foo; i++) { if (bar[i] == 7) { other = false; break; } } if(other) baz(); ```
Is there an equivalent to the "for ... else" Python loop in C++?
24,693,694
35
2014-07-11T08:50:37Z
24,693,843
10
2014-07-11T08:58:28Z
[ "python", "c++", "loops", "for-loop", "break" ]
Python has an interesting `for` statement which lets you specify an `else` clause. In a construct like this one: ``` for i in foo: if bar(i): break else: baz() ``` the `else` clause is executed after the `for`, but only if the `for` terminates normally (not by a `break`). I wondered if there was an equivale...
Yes you can achieve the same effect by: ``` auto it = std::begin(foo); for (; it != std::end(foo); ++it) if(bar(*it)) break; if(it == std::end(foo)) baz(); ```
Is there an equivalent to the "for ... else" Python loop in C++?
24,693,694
35
2014-07-11T08:50:37Z
24,694,114
8
2014-07-11T09:12:34Z
[ "python", "c++", "loops", "for-loop", "break" ]
Python has an interesting `for` statement which lets you specify an `else` clause. In a construct like this one: ``` for i in foo: if bar(i): break else: baz() ``` the `else` clause is executed after the `for`, but only if the `for` terminates normally (not by a `break`). I wondered if there was an equivale...
If doesn't mind using `goto` also can be done in following way. This one saves from extra `if` check and higher scope variable declaration. ``` for(int i = 0; i < foo; i++) if(bar(i)) goto m_label; baz(); m_label: ... ```
Is there an equivalent to the "for ... else" Python loop in C++?
24,693,694
35
2014-07-11T08:50:37Z
24,694,668
26
2014-07-11T09:38:14Z
[ "python", "c++", "loops", "for-loop", "break" ]
Python has an interesting `for` statement which lets you specify an `else` clause. In a construct like this one: ``` for i in foo: if bar(i): break else: baz() ``` the `else` clause is executed after the `for`, but only if the `for` terminates normally (not by a `break`). I wondered if there was an equivale...
A simpler way to express your actual logic is with [`std::none_of`](http://en.cppreference.com/w/cpp/algorithm/all_any_none_of): ``` if (std::none_of(std::begin(foo), std::end(foo), bar)) baz(); ``` If the range proposal for C++17 gets accepted, hopefully this will simplify to `if (std::none_of(foo, bar)) baz();`...
Python lambda as constant functor
24,694,364
5
2014-07-11T09:24:26Z
24,694,557
10
2014-07-11T09:33:02Z
[ "python", "lambda" ]
I have code with labdas, I have checked each time the function object is created it is different (not reference to same object), but it doesn't work as I would expect it. Is there any way how to or I should use a functor to do it even if I have constant data which I insert into lambda`s body? ``` pairs = [('abc', 'xyz...
This is a well-known gotcha - since you don't bind the current value of `p` when defining the `lambda`, when called it uses the current value of `p`. The solution is to use a named arg with default value to bind the "current" (definition time) value of `p`: ``` pairs = [('abc', 'xyz'), ('123', '987'), ('abc', '987')] ...
Reduced if/else block
24,697,849
2
2014-07-11T12:33:45Z
24,697,872
14
2014-07-11T12:34:50Z
[ "python" ]
I'm trying to assign a value to a variable according to some input. This is what I currently do: ``` if a == 1: var = 'some_value' elif a == 2: var = 'another_one' elif a == 3: var = 'text_string' elif a == 4: var = 'one_more' elif a == 5: var = 'final_str' ``` So basically it maps a given value t...
You can use a dictionary: ``` var_map = {1: 'foo', 2: 'bar', 10: 'spam'} var = var_map[a] ``` If `a` is a sequential integer, you can use a list too: ``` var_map = [None, 'some_value', 'another_one', 'text_string', 'one_more', 'final_str'] var = var_map[a] ``` Here `var_map[0]` is set to `None` to keep the sequence...
OpenCV for Python - AttributeError: 'module' object has no attribute 'connectedComponents'
24,699,766
7
2014-07-11T14:10:06Z
25,181,460
11
2014-08-07T11:33:19Z
[ "python", "opencv" ]
I'm trying the watershed algorithm using the following tutorial for OpenCV: <https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_watershed/py_watershed.html#watershed> I already fixed an error, now the code looks like this: ``` import numpy as np import cv2 from matplotlib import pyplo...
For anyone searching for this, the answer is that I had OpenCV 2.9 from Sourceforge, but I needed the 3.0 version from their repo on git for this function to work.
Setting up Memcached for Django session caching on App Engine
24,699,935
3
2014-07-11T14:19:07Z
24,785,322
12
2014-07-16T15:55:15Z
[ "python", "django", "google-app-engine", "caching", "memcached" ]
when setting up Django to use Memcached for caching (in my case, I want to to use session caching), in `settings.py` we set ``` CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } ``` I will be running the project in App ...
As it happens, I have been porting a Django (1.6.5) application to GAE over the last few days (GAE Development SDK 1.9.6). I don't have a big need for caching right now but it's good to know it's available if I need it. So I just tried using `django.core.cache.backends.memcached.MemcachedCache` as my cache backend (se...
Misunderstanding of python os.path.abspath
24,705,679
8
2014-07-11T20:05:59Z
24,705,780
15
2014-07-11T20:12:53Z
[ "python", "path", "os.path" ]
I have following code: ``` directory = r'D:\images' for file in os.listdir(directory): print(os.path.abspath(file)) ``` and I want next output: * D:\images\img1.jpg * D:\images\img2.jpg and so on But I get different result: * D:\code\img1.jpg * D:\code\img2.jpg where D:\code is my current working directory an...
The problem is with your understanding of `os.listdir()` not `os.path.abspath()`. `os.listdir()` returns the names of each of the files in the directory. This will give you: ``` img1.jpg img2.jpg ... ``` When you pass these to `os.path.abspath()`, they are seen as relative paths. This means it is relative to the dire...
Setting a fixed size for points in legend
24,706,125
3
2014-07-11T20:35:44Z
24,707,567
7
2014-07-11T22:29:13Z
[ "python", "legend", "scatter-plot" ]
I'm making some scatter plots and I want to set the size of the points in the legend to a fixed, equal value. Right now I have this: ``` import matplotlib.pyplot as plt import numpy as np def rand_data(): return np.random.uniform(low=0., high=1., size=(100,)) # Generate data. x1, y1 = [rand_data() for i in rang...
I had a look into the source code of `matplotlib`. Bad news is that there does not seem to be any simple way of setting equal sizes of points in the legend. It is especially difficult with scatter plots (**wrong: see the update below**). There are essentially two alternatives: 1. Change the `maplotlib` code 2. Add a t...
How to convert all Decimals in a Python data structure to string?
24,706,951
5
2014-07-11T21:36:44Z
24,707,102
9
2014-07-11T21:49:02Z
[ "python", "json", "dictionary", "flask", "decimal" ]
I'm building a website using [Flask](http://flask.pocoo.org/) from which I use the jsonify method a lot to convert mostly dictionaries to Json. The problem is now that I also use Decimals a lot, and unfortunately jsonify cannot handle Decimals: ``` jsonify({'a': Decimal('1')}) ``` leads to: ``` === (a long stacktra...
You can override the application's JSON encoder by setting the [`json_encoder`](http://flask.pocoo.org/docs/api/#flask.Flask.json_encoder) attribute on your application instance: ``` import flask app = flask.Flask(...) app.json_encoder = MyJSONEncoder ``` Then you can sub-class Flask's [`JSONEncoder`](http://flask.p...
Python and JSON - TypeError list indices must be integers not str
24,708,634
9
2014-07-12T01:08:00Z
24,708,681
11
2014-07-12T01:17:15Z
[ "python", "json" ]
I am learning to use Python and APIs (specifically, this World Cup API, <http://www.kimonolabs.com/worldcup/explorer>) The JSON data looks like this: ``` [ { "firstName": "Nicolas Alexis Julio", "lastName": "N'Koulou N'Doubena", "nickname": "N. N'Koulou", "assists": 0, "clubId": "5AF524A1-830C-4...
First of all, you should be using `json.loads`, not `json.dumps`. `loads` converts JSON source text to a Python value, while `dumps` goes the other way. After you fix that, based on the JSON snippet at the top of your question, `readable_json` will be a list, and so `readable_json['firstName']` is meaningless. The cor...
Python Convert time to UTC format
24,710,233
2
2014-07-12T06:18:00Z
24,710,877
9
2014-07-12T07:50:36Z
[ "python", "django", "datetime", "timezone" ]
``` from django.utils import timezone time_zone = timezone.get_current_timezone_name() # Gives 'Asia/Kolkata' date_time = datetime.time(12,30,tzinfo=pytz.timezone(str(time_zone))) ``` Now I need to convert this time to UTC format and save it in Django model. I am not able to use `date_time.astimezone(pytz.timezone('UT...
These things are always easier using complete `datetime` objects, e.g.: ``` import datetime import pytz time_zone = pytz.timezone('Asia/Kolkata') # get naive date date = datetime.datetime.now().date() # get naive time time = datetime.time(12, 30) # combite to datetime date_time = datetime.datetime.combine(date, time...
random forest with categorical features in sklearn
24,715,230
15
2014-07-12T16:54:00Z
24,715,300
11
2014-07-12T17:01:13Z
[ "python", "scikit-learn", "random-forest", "one-hot" ]
Say I have a categorical feature, color, which takes the values ['red', 'blue', 'green', 'orange'], and I want to use it to predict something in a random forest. If I one-hot encode it (i.e. I change it to four dummy variables), how do I tell sklearn that the four dummy variables are really one variable? Specifically...
No, there isn't. Somebody's [working on this](https://github.com/scikit-learn/scikit-learn/pull/3346) and the patch might be merged into mainline some day, but right now there's no support for categorical variables in scikit-learn except dummy (one-hot) encoding.
Reading in a text file in a set line range
24,716,001
4
2014-07-12T18:24:39Z
24,716,047
12
2014-07-12T18:30:39Z
[ "python" ]
Is it possible to read in from a text file a set line range for example from line 20 to 52? I am opening the file and reading the file like this: ``` text_file = open(file_to_save, "r") line = text_file.readline() ``` but only want to save the data in a set range or if it possible to read in from a after a line cont...
You can use [`itertools.islice()`](https://docs.python.org/2/library/itertools.html#itertools.islice) on the file object and use iteration to read only specific lines: ``` import itertools with open(file_to_save, "r") as text_file: for line in itertools.islice(text_file, 19, 52): # do something with line...
Context managers and multiprocessing pools
24,717,468
5
2014-07-12T21:25:25Z
24,724,452
9
2014-07-13T15:48:30Z
[ "python", "multiprocessing", "contextmanager" ]
Suppose you are using a `multiprocessing.Pool` object, and you are using the `initializer` setting of the constructor to pass an initializer function that then creates a resource in the global namespace. Assume resource has a context manager. How would you handle the life-cycle of the context managed resource provided ...
First, this is a really great question! After digging around a bit in the `multiprocessing` code, I think I've found a way to do this: When you start a `multiprocessing.Pool`, internally the `Pool` object creates a `multiprocessing.Process` object for each member of the pool. When those sub-processes are starting up, ...
PySpark Drop Rows
24,718,697
8
2014-07-13T01:08:33Z
24,734,612
10
2014-07-14T10:35:43Z
[ "python", "mapreduce", "apache-spark" ]
how do you drop rows from an RDD in PySpark? Particularly the first row, since that tends to contain column names in my datasets. From perusing the API, I can't seem to find an easy way to do this. Of course I could do this via Bash / HDFS, but I just want to know if this can be done from within PySpark.
AFAIK there's no 'easy' way to do this. This should do the trick, though: ``` val header = data.first val rows = data.filter(line => line != header) ```
SyntaxError: non-default argument follows default argument
24,719,368
5
2014-07-13T03:50:31Z
24,719,380
7
2014-07-13T03:52:41Z
[ "python" ]
``` from os import system def a(len1,hgt=len1,til,col=0): system('mode con cols='+len1,'lines='+hgt) system('title',til) system('color',col) a(64,25,"hi","0b") input() ``` When I run this, it rejects "def a(..." and highlights "(" in red. I have no clue why.
As the error message says, non-default argument `til` should not follow default argument `hgt`. Changing order of parameters (function call also be adjusted accordingly) or making `hgt` non-default parameter will solve your problem. ``` def a(len1, hgt=len1, til, col=0): ``` -> ``` def a(len1, hgt, til, col=0): ```...
Regex - matching numbers between hyphens
24,719,769
3
2014-07-13T05:15:37Z
24,719,786
7
2014-07-13T05:19:16Z
[ "python", "regex" ]
I'm trying to piece together a regex to match a number between hyphens. general ``` a-b-c-d-e, where a,b,c,d,e can each be either one, two or three digit numbers. ``` example ``` 9-b-90-2-2 19-b-390-2-2 ``` How can I select the number b from each expression?
You can do it without regex ``` num = "9-b-90-2-2" print num.split('-')[1] # b ```
Python cant find module in the same folder
24,722,212
7
2014-07-13T11:33:35Z
24,722,419
11
2014-07-13T11:55:21Z
[ "python", "module" ]
My python somehow cant find any modules in the same directory. What am I doing wrong? (python2.7) So I have one directory '2014\_07\_13\_test', with two files in it: 1. test.py 2. hello.py where hello.py: ``` # !/usr/local/bin/python # -*- coding: utf-8 -*- def hello1(): print 'HelloWorld!' ``` and test.py: ...
Your code is fine, I suspect your problem is how you are launching it. You need to launch python from your '2014\_07\_13\_test' directory. Open up a command prompt and 'cd' into your '2014\_07\_13\_test' directory. For instance: ``` $ cd /path/to/2014_07_13_test $ python test.py ``` If you cannot 'cd' into the dir...
scikit-learn MinMaxScaler produces slightly different results than a NumPy implemantation
24,724,717
4
2014-07-13T16:17:51Z
24,724,945
7
2014-07-13T16:41:33Z
[ "python", "numpy", "normalization", "scikit-learn", "scaling" ]
I compared the scikit-learn Min-Max scaler from its `preprocessing` module with a "manual" approach using NumPy. However, I noticed that the result is slightly different. Does anyone have a explanation for this? Using the following equation for Min-Max scaling: ![enter image description here](http://i.stack.imgur.com...
`scikit-learn` processes each feature individually. So, you need to specify `axis=0` when taking `min`, otherwise `numpy.min` would be the min on *all* the elements of the array, not each column separately: ``` >>> xs array([[1, 2], [3, 4]]) >>> xs.min() 1 >>> xs.min(axis=0) array([1, 2]) ``` same thing for `n...
I don't understand python MANIFEST.in
24,727,709
24
2014-07-13T23:06:24Z
24,727,824
27
2014-07-13T23:28:30Z
[ "python", "setuptools" ]
Reading this: [Python Distribute](http://guide.python-distribute.org/creation.html) it tells me to include `doc/txt` files and `.py` files are excluded in `MANIFEST.in` file Reading [this](https://docs.python.org/2/distutils/sourcedist.html#manifest-template) It tells me only sdist uses `MANIFEST.in` and only includ...
# Re: "Do I need a MANIFEST.in? No, you do not have to use `MANIFEST.in`. Both, `distutils` and `setuptools` are including in source distribution package all the files mentioned in `setup.py` - modules, package python files, `README.txt` and `test/test*.py`. If this is all you want to have in distribution package, you...
Why does this implementation of multiprocessing.pool not work?
24,728,084
4
2014-07-14T00:15:49Z
24,728,161
7
2014-07-14T00:33:54Z
[ "python", "multithreading", "numpy", "multiprocessing", "sympy" ]
Here is the code I am using: ``` def initFunction(arg1, arg2): def funct(value): return arg1 * arg2 * value return funct os.system("taskset -p 0xff %d" % os.getpid()) pool = Pool(processes=4) t = np.linspace(0,1,10e3) a,b,c,d,e,f,g,h = sy.symbols('a,b,c,d,e,f,g,h',commutative=False) arg1 = sy.Matri...
Objects that you pass between processes when using `multiprocessing` must be importable from the `__main__` module, [so that they can be unpickled](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled) in the child. Nested functions, like `funct`, are not importable from `__main__`, so you ge...
python parse http response (string)
24,728,088
6
2014-07-14T00:17:23Z
24,729,316
15
2014-07-14T03:56:50Z
[ "python", "http" ]
I'm using python 2.7 and I want to parse string HTTP response fields which I already extracted from a text file. What would be the easiest way? I can parse requests by using the BaseHTTPServer but couldn't manage to find something for the responses. The responses I have are pretty standard and in the following format ...
You might find this useful, keep in mind that [HTTPResponse](https://docs.python.org/2/library/httplib.html#httplib.HTTPResponse) wasn't designed to be "instantiated directly by user." Also note that the content-length header in your response string may not be valid any more (it depends on how you've aquired these res...
Segmenting License Plate Characters
24,731,810
10
2014-07-14T07:47:04Z
24,732,434
20
2014-07-14T08:32:03Z
[ "python", "matlab", "opencv", "image-processing", "computer-vision" ]
I am facing problem in segmenting characters from license plate image. I have applied following method to extract license plate characters, ``` -adaptive threshold the license plate image. -select contours which having particular aspect ratio. ``` If there is any shade in the license plate image as in attached fi...
Before I start, I know you are seeking an implementation of this algorithm in OpenCV C++, but my algorithm requires the FFT and the `numpy / scipy` packages are awesome for that. As such, I will give you an implementation of the algorithm in OpenCV *using Python* instead. The code is actually quite similar to the C++ A...
Print on same line at the first in python 2 and 3
24,732,163
3
2014-07-14T08:13:51Z
24,732,197
11
2014-07-14T08:16:50Z
[ "python", "python-3.x" ]
There are several solutions for printing on same line and at the first of it, like below. In python 2, ``` print "\r Running... xxx", ``` And in Python 3, ``` print("\r Running... xxx", end="") ``` I can't find a single print solution to cover python 2 and 3 at the same time. Do I have to use `sys.stdout.write`?
Use `from __future__ import print_function` and use the `print()` function in both Python 2 and Python 3: ``` from __future__ import print_function print("\r Running... xxx", end="") # works across both major versions ``` See the [`print()` function documentation in Python 2](https://docs.python.org/2/library/funct...
Volume of convex hull with QHull from SciPy
24,733,185
9
2014-07-14T09:17:07Z
24,734,583
12
2014-07-14T10:34:07Z
[ "python", "scipy", "convex-hull", "qhull" ]
I'm trying to get the **volume of the convex hull** of a set of points using the [SciPy wrapper for QHull](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.ConvexHull.html). According to the [documentation of QHull](http://www.qhull.org/html/qhull.htm), I should be passing the `"FA"` option to get...
There does not seem to be any obvious way of directly getting the results you are after, regardless of what parameters you pass in. It shouldn't be too hard to compute yourself if, instead of `ConvexHull`, you use [`Delaunay`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html) (which also ...
Python: What does the slash mean in the output of help(range)?
24,735,311
23
2014-07-14T11:15:32Z
24,735,582
28
2014-07-14T11:32:30Z
[ "python", "python-3.x", "documentation", "introspection" ]
What does the `/` mean in Python 3.4's `help` output for `range` before the closing parenthesis? ``` >>> help(range) Help on class range in module builtins: class range(object) | range(stop) -> range object | range(start, stop[, step]) -> range object | | Return a virtual sequence of numbers from start to st...
It signifies the end of the [*positional only* parameters](http://www.python.org/dev/peps/pep-0436/#functions-with-positional-only-parameters), parameters you *cannot* use as keyword parameters. Such parameters can only be specified in the C API. It means the `key` argument to `__contains__` can only be passed in by p...
Updated Bokeh to 0.5.0, now plots all previous versions of graph in one window
24,739,390
7
2014-07-14T14:52:07Z
24,967,653
8
2014-07-26T04:51:26Z
[ "python", "plot", "bokeh" ]
Before I updated, I would run my script and output the html file. There would be my one plot in the window. I would make changes to my script, run it, output the html file, look at the new plot. Then I installed the library again to update it using conda. I made some changes to my script, ran it again, and the output f...
as of 0.5.1 there is now `bokeh.plotting.reset_output` that will clear all output\_modes and state. This is especially useful in situations where a new interpreter is not started in between executions (e.g., Spyder and the notebook)
matplotlib imshow plots different if using colormap or RGB array
24,739,769
3
2014-07-14T15:10:43Z
24,741,429
9
2014-07-14T16:36:42Z
[ "python", "numpy", "matplotlib" ]
I am having the following problem: I am saving 16-bit tiff images with a microscope and I need to analyze them. I want to do that with numpy and matplotlib, but when I want to do something as simple as plotting the image in green (I will later need to superpose other images), it fails. Here is an example when I try to...
I find the right plot much more artistic... `matplotlib` is rather complicated when it comes to interpreting images. It goes roughly as follows: * if the image is a NxM array of any type, it is interpreted through the colormap (autoscale, if not indicated otherwise). (In principle, if the array is a `float` array sca...
python using __init__ vs just defining variables in class - any difference?
24,739,850
5
2014-07-14T15:15:19Z
24,739,890
7
2014-07-14T15:17:08Z
[ "python", "oop" ]
I'm new to Python - and just trying to better understand the logic behind certain things. Why would I write this way (default variables are in `__init__`): ``` class Dawg: def __init__(self): self.previousWord = "" self.root = DawgNode() self.uncheckedNodes = [] self.minimizedNod...
When you create variables in the Class, then they are Class variables (They are common to all the objects of the class), when you initialize the variables in `__init__` with `self.variable_name = value` then they are created per instance and called instance variables. For example, ``` class TestClass(object): var...
PyCharm - Have author appear before imports?
24,741,141
7
2014-07-14T16:21:39Z
24,859,703
7
2014-07-21T07:28:55Z
[ "python", "import", "pycharm", "jetbrains", "author" ]
When you create new python files and add new imports, PyCharm will automatically add the imports and \_\_author\_\_ tag whenever it can by itself. However, by default the \_\_author\_\_ tag will always appear below any imports. It seems to me that the \_\_author\_\_ tag should be up at the top of the file where I would...
1. is according to the "Imports" section of [PEP-8](http://legacy.python.org/dev/peps/pep-0008/#imports): > Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants `__author__` is a global "variable" and should therefore appear below ...
multi-threading in python: is it really performance effiicient most of the time?
24,744,739
2
2014-07-14T19:51:57Z
24,744,911
8
2014-07-14T20:00:52Z
[ "python", "multithreading", "multiprocessing", "gil" ]
In my little understanding, it is the performance factor that drives programming for `multi-threading` in most cases but not all. (irrespective of Java or Python). I was reading this [enlightening article](http://stackoverflow.com/questions/265687/why-the-global-interpreter-lock) on `GIL` in SO. The article summarizes...
You're right about the GIL, there is no point to use multithreading to do CPU-bound computation, as the CPU will only be used by one thread. But that previous statement may have enlighted you: If your computation is not CPU bound, you may take advantage of multithreading. A typical example is when your application ta...
Installing h5py on an Ubuntu server
24,744,969
33
2014-07-14T20:03:45Z
24,745,489
63
2014-07-14T20:33:30Z
[ "python", "python-2.7", "installation", "installer", "h5py" ]
I was installing h5py on an Ubuntu server. However it seems to return an error that `h5py.h` is not found. It gives the same error message when I install it using `pip` or the `setup.py` file. What am I missing here? I have Numpy version 1.8.1, which higher than the required version of 1.6 or above. The complete outp...
You need to install [`libhdf5-dev`](http://packages.ubuntu.com/trusty/libhdf5-dev) to get the required header files. Just run ``` sudo apt-get install libhdf5-dev ``` and it should install it and its dependencies automatically. Don't worry about the NumPy warning, it just means that the package developers are using ...