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
Flask route using path with leading slash
24,000,729
4
2014-06-02T18:11:11Z
24,001,029
8
2014-06-02T18:31:00Z
[ "python", "flask", "routes" ]
I am trying to get Flask using a simple route with a path converter: ``` @api.route('/records/<hostname>/<metric>/<path:context>') ``` It works unless the "path" part of the URL uses a leading slash. In this case I get a 404. I understand the error but what I don't get is that there is no workaround in the documentat...
The [`PathConverter` URL converter](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.PathConverter) explicitly doesn't include the leading slash; this is deliberate because most paths should *not* include such a slash. See the [`PathConverter` source code](https://github.com/mitsuhiko/werkzeug/blob/5eed9385b86...
python bind socket.error: [Errno 13] Permission denied
24,001,147
6
2014-06-02T18:40:54Z
24,001,186
11
2014-06-02T18:43:13Z
[ "python", "tunnel" ]
I have a python script which gets packets from a remote machine and writes them (os.write(self.tun\_fd.fileno(), ''.join(packet))) to a tun interface gr3: ``` Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 inet addr:10.0.0.6 P-t-P:10.0.0.8 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOAR...
You can't bind to port numbers lower than 1024 as a unprivileged user. So you should either: * Use a port number larger than 1024 (recommended) * Or run the script as a privileged user Harder, but more secure solution if it's really necessary to accept from 111: * Run the as unprivileged on a higher port, and forwa...
Function definition in Python takes a lot of time
24,004,642
11
2014-06-02T23:02:12Z
24,004,848
8
2014-06-02T23:23:07Z
[ "python", "function", "python-2.7" ]
Why is python trying to calculate the value of `p` during definition? It takes ages to define this function. ``` def f(): raise Exception('Some error') p = 2322111239**42322222334923492304923 print 'Defined!' ``` Also if the value of `p` is being calculated during definition, why is it possible to define thi...
It is the peephole optimizer: <http://hg.python.org/cpython/file/eabff2a97b5b/Python/peephole.c#l88> See in particular lines 104-106 ``` case BINARY_POWER: newconst = PyNumber_Power(v, w, Py_None); break; ``` The intention is to speed up runtime execution of the function at the cost of slower definiton (rea...
Function definition in Python takes a lot of time
24,004,642
11
2014-06-02T23:02:12Z
24,004,962
7
2014-06-02T23:38:16Z
[ "python", "function", "python-2.7" ]
Why is python trying to calculate the value of `p` during definition? It takes ages to define this function. ``` def f(): raise Exception('Some error') p = 2322111239**42322222334923492304923 print 'Defined!' ``` Also if the value of `p` is being calculated during definition, why is it possible to define thi...
This feature of the interpreter is called `constant folding` (see [here](http://cfbolz.de/draft/trace-time-computation.html) for some nice inforamtion). There exist several Issues addressing even too agressive constant foldings. Similar issues can arries for memory as well, where a lot of memory is allocated and direct...
How to install Numpy on Windows 8, in pyvenv?
24,005,777
4
2014-06-03T01:29:22Z
25,908,690
7
2014-09-18T09:14:59Z
[ "python", "python-3.x", "numpy", "windows-8", "pip" ]
I have a virtual environment set up (Pyvenv, Python 3.4), but after executing activate.bat and the command `pip install numpy`, i get an error stating "Unable to find vcvarsall.bat". I added `C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC` to the PATH variable, which contains the vcvarsall.bat file, yet the er...
You do not need to compile numpy on Windows, you can just download the binaries. The numpy team does not upload Windows binaries to pypi (an open github issue on the subject can be found [here](https://github.com/numpy/numpy/issues/5479)), and you will need to download them manually from an alternative site. This is qu...
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment varia
24,011,428
16
2014-06-03T09:20:18Z
27,455,703
12
2014-12-13T04:57:25Z
[ "python", "django", "python-3.x", "pycharm" ]
I've tried everything that I could find to fix this issue, and I'm starting to tear my hair out a little. I'm getting this error: ``` django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call se...
Use this ``` import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' ``` instead of ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.settings") ```
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment varia
24,011,428
16
2014-06-03T09:20:18Z
30,332,846
7
2015-05-19T17:58:38Z
[ "python", "django", "python-3.x", "pycharm" ]
I've tried everything that I could find to fix this issue, and I'm starting to tear my hair out a little. I'm getting this error: ``` django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call se...
In your python script, you are trying to access Django models before setting the environment try it in this order : ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.`settings`") from <appname>.models import Class1, Class2,... ```
How to test if one string is a subsequence of another?
24,017,363
5
2014-06-03T14:08:26Z
24,017,747
13
2014-06-03T14:24:44Z
[ "python", "string", "algorithm" ]
How to test if one string is a subsequence of another? This is a weaker condition than being a substring. For example 'iran' is not a substring of 'ireland', but it is a subsequence `IRelANd`. The difference is a subsequence doesn't have to be contiguous. More examples: * 'indonesia' contains 'india'. `INDonesIA` * ...
``` def is_subseq(x, y): it = iter(y) return all(any(c == ch for c in it) for ch in x) assert is_subseq('india', 'indonesia') assert is_subseq('oman', 'romania') assert is_subseq('mali', 'malawi') assert not is_subseq('mali', 'banana') assert not is_subseq('ais', 'indonesia') assert not is_subseq('ca', 'abc') ...
How should I fork an existing python environment into a new environment using virtualenv?
24,017,564
3
2014-06-03T14:17:19Z
24,017,690
7
2014-06-03T14:22:11Z
[ "python", "copy", "fork", "virtualenv" ]
I have installed virtualenv for python. After I have installed some packages such as "nose" etc., I decided to have a try at installing some other packages without affect the former environment. I type the command, virtualenv --system-site-packages --always-copy some\_new\_env And it responded, New python executable...
Ideally, you should not copy virtualenvs - instead, you should track the packages you need and install them in the new virtualenv. This is made much easier if you use `pip`: ``` $ env1/bin/pip freeze > requirements.txt $ env2/bin/pip install -r requirements.txt ``` As a bonus, you can check `requirements.txt` into s...
Celery workers not consuming enough tasks
24,020,693
3
2014-06-03T16:50:09Z
24,026,148
11
2014-06-03T22:39:49Z
[ "python", "rabbitmq", "celery" ]
I have a strange issue with Celery. I am using RabbitMQ as message broker and result backend. Tasks are serialized via pickle, but they only get an id for a file in a database. They fetch it, do some work on it and write the result back to the database. I'm just storing the id in the result backend. I use a group to...
Finally figured it out: It's just an option I had to put then starting the worker. Starting the worker with the -Ofair option did it! See: <http://docs.celeryproject.org/en/latest/userguide/optimizing.html#prefork-pool-prefetch-settings> Thanks for your help :)
Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT
24,022,558
10
2014-06-03T18:39:52Z
24,022,604
17
2014-06-03T18:42:26Z
[ "python", "django", "django-staticfiles", "django-static" ]
What are the differences of these three static url? I am not sure if I am right, I am using the `MEDIA_ROOT` to store my uploaded photos (via `models.ImageField()`) However, I created a JS script to my admin and in `admin.py`. I defined the media as below: ``` .... class Media: js = ('/admin/custom.js', ) ``` ...
You can find a definition for each of these settings [in the documentation](https://docs.djangoproject.com/en/dev/ref/settings/). Here is a quick definition (of my own) and a quotation of the doc, for each: * `MEDIA_ROOT` is the folder where every files uploaded with an `FileField` will go. > Absolute filesystem pa...
Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT
24,022,558
10
2014-06-03T18:39:52Z
24,022,621
9
2014-06-03T18:43:50Z
[ "python", "django", "django-staticfiles", "django-static" ]
What are the differences of these three static url? I am not sure if I am right, I am using the `MEDIA_ROOT` to store my uploaded photos (via `models.ImageField()`) However, I created a JS script to my admin and in `admin.py`. I defined the media as below: ``` .... class Media: js = ('/admin/custom.js', ) ``` ...
Difference between `STATICFILES_DIRS` and `STATIC_ROOT` The `STATICFILES_DIRS` can contain other directories (not necessarily app directories) with static files and these static files will be collected into your STATIC\_ROOT when you run `collectstatic`. These static files will then be served by your web server and th...
Is it good practice to use `import __main__`?
24,023,601
13
2014-06-03T19:42:10Z
24,023,850
16
2014-06-03T19:57:20Z
[ "python", "python-2.7" ]
I'm working on a relatively large Python application, and there are several resources that I would like to keep as global variables accessible throughout several different modules. These values are things like the version number, version date, the global configuration, and some static paths to resources. I've also incl...
I think there are two main (ha ha) reasons one might prescribe an avoidance of this pattern. * It obfuscates the origin of the variables you're importing. * It breaks (or at least it's tough to maintain) if your program has multiple entry points. Imagine if someone, very possibly you, wanted to extract some subset of ...
Subtract seconds from datetime in python
24,025,552
5
2014-06-03T21:51:21Z
24,025,606
10
2014-06-03T21:54:40Z
[ "python", "datetime", "python-3.x" ]
I have an int variable that are actually seconds (lets call that amount of seconds X). I need to get as result current date and time (in datetime format) minus X seconds. For example, if X is 65 and current date is 2014-06-03 15:45:00, and I need to get as result 2014-06-03 15:43:45. I'm doing this on Python 3.3.3 and...
Using the `datetime` module indeed: ``` import datetime X = 65 result = datetime.datetime.now() - datetime.timedelta(seconds=X) ``` You should read the [documentation](https://docs.python.org/3.3/library/datetime.html) of this package to learn how to use it!
How to convert raw javascript object to python dictionary?
24,027,589
2
2014-06-04T01:27:25Z
26,900,181
7
2014-11-13T02:08:09Z
[ "javascript", "python", "json", "web-scraping" ]
When screen-scraping some website, I extract data from `<script>` tags. The data I get is not in standard `JSON` format. I cannot use `json.loads()`. ``` # from js_obj = '{x:1, y:2, z:3}' # to py_obj = {'x':1, 'y':2, 'z':3} ``` Currently, I use `regex` to transform the raw data to `JSON` format. But I feel prett...
## [`demjson.decode()`](http://deron.meranda.us/python/demjson/demjson-2.2.3/docs/demjson.html#-decode) ``` import demjson # from js_obj = '{x:1, y:2, z:3}' # to py_obj = demjson.decode(js_obj) ``` ## [`jsonnet.evaluate_snippet()`](http://google.github.io/jsonnet/doc/bindings.html) ``` import json, _jsonnet # fro...
Python AttributeError: 'module' object has no attribute 'DIST_L2'
24,029,401
6
2014-06-04T05:04:12Z
24,135,899
10
2014-06-10T08:06:59Z
[ "python", "opencv", "image-processing", "image-segmentation" ]
I am trying to use **cv2.distanceTransform()** method in Python. And I am getting an error when running the following line of code: **dist\_transform = cv2.distanceTransform(opening,cv2.DIST\_L2,5)** I get the following error when running this code: *AttributeError: 'module' object has no attribute 'DIST\_L2'* Simil...
Instead of `cv2.DIST_L2`, use: ``` cv2.cv.CV_DIST_L2 ``` I was having the same problem, but after some research, the [documentation](http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#distancetransform) mention an example file on the source code (opencv\_source/samples/python2/distrans.py) ...
Python AttributeError: 'module' object has no attribute 'DIST_L2'
24,029,401
6
2014-06-04T05:04:12Z
24,553,504
18
2014-07-03T12:17:40Z
[ "python", "opencv", "image-processing", "image-segmentation" ]
I am trying to use **cv2.distanceTransform()** method in Python. And I am getting an error when running the following line of code: **dist\_transform = cv2.distanceTransform(opening,cv2.DIST\_L2,5)** I get the following error when running this code: *AttributeError: 'module' object has no attribute 'DIST\_L2'* Simil...
Should be rewritten as below: ``` (dist_transform, labels) = cv2.distanceTransform(opening,cv2.cv.CV_DIST_L2,5) ```
Python Pandas replicate rows in dataframe
24,029,659
6
2014-06-04T05:26:20Z
24,029,921
9
2014-06-04T05:47:21Z
[ "python", "pandas", "dataframe" ]
If the data look like: ``` Store,Dept,Date,Weekly_Sales,IsHoliday 1,1,2010-02-05,24924.5,FALSE 1,1,2010-02-12,46039.49,TRUE 1,1,2010-02-19,41595.55,FALSE 1,1,2010-02-26,19403.54,FALSE 1,1,2010-03-05,21827.9,FALSE 1,1,2010-03-12,21043.39,FALSE 1,1,2010-03-19,22136.64,FALSE 1,1,2010-03-26,26229.21,FALSE 1,1,2010-04-02,5...
You can put `df_try` inside a list and then do what you have in mind: ``` >>> df.append([df_try]*5,ignore_index=True) Store Dept Date Weekly_Sales IsHoliday 0 1 1 2010-02-05 24924.50 False 1 1 1 2010-02-12 46039.49 True 2 1 1 2010-02-19 41595.55 Fa...
Is it possible to get values from query string with same name?
24,030,565
2
2014-06-04T06:33:27Z
24,030,705
7
2014-06-04T06:42:30Z
[ "python", "query-string", "tornado" ]
I want to know if it's possible to get values from this query string? ``` '?agencyID=1&agencyID=2&agencyID=3' ``` Why I have to use a query string like this? I have a form with 10 check boxes. my user should send me ID of news agencies which he/she is interested in. so to query string contains of multiple values wi...
Reading [the tornado docs](http://www.tornadoweb.org/en/branch2.1/web.html), this seems to do what you want > **RequestHandler.get\_arguments(name, strip=True)** > > Returns a list > of the arguments with the given name. > If the argument is not present, returns an empty list. > The returned values are always unicode....
Performance issues with App Engine memcache / ndb.get_multi
24,030,855
8
2014-06-04T06:50:53Z
24,051,351
10
2014-06-05T03:53:08Z
[ "python", "performance", "google-app-engine", "memcached" ]
I'm seeing very poor performance when fetching multiple keys from Memcache using `ndb.get_multi()` in App Engine (Python). I am fetching ~500 small objects, all of which are in memcache. If I do this using `ndb.get_multi(keys)`, it takes 1500ms or more. Here is typical output from App Stats: ![App Stats](http://i.sta...
I investigated this in a bit of detail, and the problem is ndb and Python, not memcache. The reason things are so incredibly slow is partly deserialization (explains about 30% of the time), and the rest seems to be overhead in ndb's task queue implementation. This means that, if you really want to, you can avoid ndb a...
Difference in values of tf-idf matrix using scikit-learn and hand calculation
24,032,485
6
2014-06-04T08:27:18Z
24,042,772
8
2014-06-04T16:28:18Z
[ "python", "matrix", "machine-learning", "tf-idf" ]
I am playing with `scikit-learn` to find the `tf-idf` values. I have a set of `documents` like: ``` D1 = "The sky is blue." D2 = "The sun is bright." D3 = "The sun in the sky is bright." ``` I want to create a matrix like this: ``` Docs blue bright sky sun D1 tf-idf 0.0000000 tf-idf 0.0000...
There are two reasons: 1. You are neglecting **smoothing** which often occurs in such cases 2. You are assuming logarithm of base 10 According to [source](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py) sklearn does not use such assumptions. First, it smooths document cou...
How to read from QTextedit in python?
24,035,660
2
2014-06-04T11:01:12Z
24,036,888
11
2014-06-04T12:01:37Z
[ "python", "pyqt4" ]
I created the GUI using QTDesigner and save the file as .ui extension. Then convert the file to .py file using the following code ``` pyuic4 -x test.ui -o test.py ``` Now I want to integrate my project code to this test.py file. Since I am new to pyqt4, I dont know how to read text from text edit and save to file and...
If all you need is the displayed text in your QTextEdit widget, you can access that by using the [`toPlainText()`](http://pyqt.sourceforge.net/Docs/PyQt4/qtextedit.html#toPlainText) method on the widget you need the text from. Example: ``` mytext = self.textEdit.toPlainText() ``` At this point, you can do whatever y...
Tag inside tag in django template
24,035,972
5
2014-06-04T11:16:13Z
24,036,255
8
2014-06-04T11:31:49Z
[ "python", "django", "django-templates" ]
I am trying to do something like the following: ``` {% include "default_form.html" with action="{% url 'settings' var1 var2 %}" %} ``` But it doesn't seem to be supported, as I get the following error: ``` Could not parse the remainder: '"{%' from '"{%' ``` Is there any way to achieve this within the template or do...
The simplest solution would be: ``` {% url 'settings' var1 var2 as action_url %} {% include "default_form.html" with action=action_url %} ```
how to limit the ouput of get_all_images in amazon boto?
24,036,068
2
2014-06-04T11:22:02Z
24,036,750
7
2014-06-04T11:55:44Z
[ "python", "amazon-ec2", "boto" ]
I tried to load list of AWS images using Python boto library. My code looks like this: ``` con = boto.connect_ec2(user, pasw) images_list = con.get_all_images() ``` How do I get only the first 10 results from the function `get_all_images()`? I'm looking for something like `con.get_all_images(maxresult=10)`.
As you can find out from [the boto documentation](http://boto.readthedocs.org/en/latest/ref/ec2.html#boto.ec2.connection.EC2Connection.get_all_images) **you cannot directly limit the amount of images returned by that function**. It's lacking the API support (see the link below), it's not exactly a boto's issue. ## Fil...
How protobuf-net serialize DateTime?
24,036,291
8
2014-06-04T11:33:32Z
24,038,019
9
2014-06-04T12:52:55Z
[ "c#", "python", "protocol-buffers", "protobuf-net" ]
I'm working on a project consisting on Client/Server. Client is written in Python (will run on linux) and server in C#. I'm communicating through standard sockets and I'm using protobuf-net for protocol definition. However, I'm wondering how would protobuf-net handle DateTime serialization. Unix datetime differs from ....
DateTime is spoofed via a multi-field message that is not trivial, but not impossible to understand. In hindsight, I wish I had done it a different way, but it is what it is. The definition is available in bcl.proto in the protobuf-net project. However! If you are targering multiple platforms, I strongly recommend you...
How to update values in a specific row in a Python Pandas DataFrame?
24,036,911
10
2014-06-04T12:02:26Z
24,043,138
17
2014-06-04T16:48:48Z
[ "python", "pandas" ]
With the nice indexing methods in Pandas I have no problems extracting data in various ways. On the other hand I am still confused about how to change data in an existing DataFrame. In the following code I have two DataFrames and my goal is to update values in a specific row in the first df from values of the second d...
So first of all, **pandas updates using the index**. When an update command does not update anything, check both left-hand side and right-hand side. If for some reason you are too lazy to update the indices to follow your identification logic, you can do something along the lines of ``` >>> df.loc[df.filename == 'test...
Converting string objects to int/float using pandas
24,037,507
6
2014-06-04T12:31:34Z
24,037,972
14
2014-06-04T12:51:12Z
[ "python", "csv", "pandas" ]
``` import pandas as pd path1 = "/home/supertramp/Desktop/100&life_180_data.csv" mydf = pd.read_csv(path1) numcigar = {"Never":0 ,"1-5 Cigarettes/day" :1,"10-20 Cigarettes/day":4} print mydf['Cigarettes'] mydf['CigarNum'] = mydf['Cigarettes'].apply(numcigar.get).astype(float) print mydf['CigarNum'] mydf.to_csv(...
OK, first problem is you have embedded spaces causing the function to incorrectly apply: fix this using vectorised `str`: ``` mydf['Cigarettes'] = mydf['Cigarettes'].str.replace(' ', '') ``` now create your new column should just work: ``` mydf['CigarNum'] = mydf['Cigarettes'].apply(numcigar.get).astype(float) ``` ...
Numpy "sort like" function
24,038,347
3
2014-06-04T13:08:10Z
24,038,413
7
2014-06-04T13:11:20Z
[ "python", "sorting", "numpy" ]
Say I have two arrays, `v` and `w`: ``` v=np.arange(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) w=np.random.random(10,) array([ 0.20224634, 0.19145386, 0.44607429, 0.53601637, 0.29148741, 0.62670435, 0.95371219, 0.63634805, 0.48733178, 0.17155278]) ``` I can sort `w` like this: ``` np.sort(w) array([ 0...
You can get the order using `np.argsort`: ``` order = np.argsort(w) ``` And then just sort both arrays: ``` w = w[order] v = v[order] ```
CPython string addition optimisation failure case
24,040,198
7
2014-06-04T14:28:25Z
24,040,766
8
2014-06-04T14:52:22Z
[ "python", "string", "optimization", "cpython" ]
# The Question Why, in CPython, does ``` def add_string(n): s = '' for _ in range(n): s += ' ' ``` take linear time, but ``` def add_string_in_list(n): l = [''] for _ in range(n): l[0] += ' ' ``` take quadratic time? --- Proof: ``` Timer(partial(add_string, 1000000)).timeit(1) #>...
In the list based approach, string from index 0 of the list is taken and modified before being put back to the list at index 0. For this short moment interpreter still has the old version of string in the list and can't perform in place modification. If you take a look at [Python's source](https://github.com/python...
set multi index of an existing data frame in pandas
24,041,436
11
2014-06-04T15:22:44Z
24,041,761
12
2014-06-04T15:37:57Z
[ "python", "pandas" ]
I have a dataframe that looks like this ``` Emp1 Empl2 date Company 0 0 0 2012-05-01 apple 1 0 1 2012-05-29 apple 2 0 1 2013-05-02 apple 3 0 1 2013-11-22 apple 18 1 0 2011-09-09 google 19 1...
When you pass inplace in makes the changes on the original variable and returns None, and the function **does not** return the modified dataframe, it returns None. ``` is_none = df.set_index(['Company', 'date'], inplace=True) df # the dataframe you want is_none # has the value None ``` so when you have a line like: ...
Specifying limit and offset in Django QuerySet wont work
24,041,448
3
2014-06-04T15:23:13Z
24,041,646
9
2014-06-04T15:32:14Z
[ "python", "django", "django-models", "django-orm" ]
I'm using Django 1.6.5 and have MySQL's general-query-log on, so I can see the sql hitting MySQL. And I noticed that Specifying a bigger limit in Django's QuerySet would not work: ``` >>> from blog.models import Author >>> len(Author.objects.filter(pk__gt=0)[0:999]) >>> len(Author.objects.all()[0:999]) ``` And My...
It happens when you make queries from the shell - the `LIMIT` clause is added to stop your terminal filling up with thousands of records when debugging: > You were printing (or, at least, trying to print) the repr() of the > queryset. To avoid people accidentally trying to retrieve and print a > million results, we (w...
Conditionally join a list of strings in Jinja
24,041,885
7
2014-06-04T15:44:07Z
24,042,287
10
2014-06-04T16:02:55Z
[ "python", "jinja2", "jinja" ]
I have a list like ``` users = ['tom', 'dick', 'harry'] ``` In a `Jinja` template I'd like to print a list of all users except `tom` joined. I cannot modify the variable before it's passed to the template. I tried a list comprehension, and using Jinja's `reject` filter but I haven't been able to get these to work, e...
Use [`reject`](http://jinja.pocoo.org/docs/templates/#reject) filter with [`sameas`](http://jinja.pocoo.org/docs/templates/#sameas) test: ``` >>> import jinja2 >>> template = jinja2.Template("{{ users|reject('sameas', 'tom')|join(',') }}") >>> template.render(users=['tom', 'dick', 'harry']) u'dick,harry' ```
Splitting a Python String by math expressions
24,042,517
2
2014-06-04T16:14:08Z
24,042,690
7
2014-06-04T16:23:05Z
[ "python", "regex", "string", "split" ]
I have a lot of python strings such as `"A7*4"`, `"Z3+8"`, `"B6 / 11"`, and I want to split these strings so that they would be in a list, in the format `["A7", "*", "4"]`, `["B6", "/", "11"]`, etc. I have used a lot of different split methods but I think I need to just perform the split where there is a math symbol, s...
You should split on the [character set](https://docs.python.org/2/library/re.html#regular-expression-syntax) `[+-/*]` after removing the whitespace from the string: ``` >>> import re >>> def mysplit(mystr): ... return re.split("([+-/*])", mystr.replace(" ", "")) ... >>> mysplit("A7*4") ['A7', '*', '4'] >>> mysplit...
how connect to vertica using pyodbc
24,049,173
6
2014-06-04T23:18:14Z
24,049,512
8
2014-06-04T23:56:33Z
[ "python", "pyodbc", "unixodbc", "vertica" ]
I've read the [iODBC documentation](http://www.iodbc.org/dataspace/iodbc/wiki/iODBC/FAQ) regarding the `odbc.ini`, and the [Vertica documentation](https://my.vertica.com/docs/7.0.x/HTML/index.htm#Authoring/ProgrammersGuide/InstallingDrivers/CreatingAnODBCDSNForLinuxSolarisAIXAndHP-UX.htm). I also saw a question [with t...
Try connecting using `DSN`: ``` conn = pyodbc.connect("DSN=VerticaDB1;UID=dbadmin;PWD=mypassword") ``` Alternatively, you can connect using `DRIVER`, but you need to supply more information, like which database, host, and port: ``` conn = pyodbc.connect("DRIVER=HPVertica;SERVER=10.0.0.67;DATABASE=db1;PORT=5433;UID=d...
why \* escapes even when it is a raw string?
24,051,248
3
2014-06-05T03:40:07Z
24,051,270
12
2014-06-05T03:43:12Z
[ "python", "regex" ]
I have read that when 'r' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. But when I create a regex object: `p=re.compile(r'\*(.*?)\*')`, it matches `'*text*'`. I don't understand why it happens. Under my impression it should mat...
Regular expressions treat the backslash specially. The backslash disables the "magic" behavior of special characters like `*`. To actually match a backslash, you need to put two in your raw string: `r'\\foo'` I think what confused you is that backslashes are special in strings and also special for regular expressions...
webdriver wait for ajax request in python
24,053,671
7
2014-06-05T07:01:44Z
24,053,891
8
2014-06-05T07:13:25Z
[ "python", "ajax", "selenium", "webdriver" ]
Currently I am writing webdriver test for search which uses ajax for suggestions. Test works well if I add explicit wait after typing the search content and before pressing enter. ``` wd.find_element_by_xpath("//div[@class='searchbox']/input").send_keys("obama") time.sleep(2) wd.find_element_by_xpath("//div[@class='se...
You indeed can add an explicit wait for the presence of an element like ``` from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as EC # available since 2.26....
L suffix in long integer in Python 3.x
24,059,842
2
2014-06-05T12:08:42Z
24,059,884
8
2014-06-05T12:10:38Z
[ "python", "python-3.x" ]
In Python 2.x there was a `L` suffix after long integer. As Python 3 treats all integers as long integer this has been removed. From [What's New In Python 3.0](https://docs.python.org/3.0/whatsnew/3.0.html#integers): > The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally ...
You misunderstood the documentation. The remark is aimed at people trying to strip the `L` from `repr()` **in Python 2**. Those people could use `str()` instead and get the same number without having to strip the `L` each time. In other words, `str()`, when used on a long integer in Python 2, is the better method to ...
GDAL error: command 'cc' failed with exit status 1
24,063,612
3
2014-06-05T14:59:46Z
24,149,064
8
2014-06-10T19:09:55Z
[ "python", "xcode", "pip", "gdal" ]
I am getting increasingly frustrated with this issue, but I have been trying to reinstall GDAL in order to install the new version of QGIS. When I try to install it using `pip install GDAL` I get the following: ``` Installing collected packages: GDAL Running setup.py install for GDAL building 'osgeo._gdal' exten...
I've just run into this (hence finding your question). I solved it by making sure that the version of (Python's) `GDAL` I was trying to install matched that of the `libgdal` on the system. In my case pip was pulling in `GDAL==1.11.0`, whereas the version of `libgdal` I had was `1.10.1+dfsg-5ubuntu1`. Running `pip inst...
python3: singledispatch in class, how to dispatch self type
24,063,788
6
2014-06-05T15:06:55Z
24,064,102
7
2014-06-05T15:21:20Z
[ "python", "class", "types", "python-3.4", "dispatch" ]
Using python3.4. Here I want use singledispatch to dispatch different type in `__mul__` method . The code like this : ``` class Vector(object): ## some code not paste @functools.singledispatch def __mul__(self, other): raise NotImplementedError("can't mul these type") @__mul__.register(int)...
You cannot use `functools.singledispatch` on methods **at all**. It doesn't matter that `Vector` isn't defined here yet; the first argument to any method is always going to be `self`, while you'd use single dispatch for the *second argument* here. If it did work, you'd register your 'methods' as functions instead, *o...
Python: Numpy standard deviation error
24,067,996
13
2014-06-05T18:51:24Z
24,068,053
14
2014-06-05T18:54:34Z
[ "python", "numpy" ]
This is a simple test ``` import numpy as np data = np.array([-1,0,1]) print data.std() >> 0.816496580928 ``` I don't understand how this result been generated? Obviously: ``` ( (1^0.5 + 1^0.5 + 0^0.5)/(3-1) )^0.5 = 1 ``` and in matlab it gives me `std([-1,0,1]) = 1`. Could you help me get understand how `numpy.st...
First, you need to divide by `N` (3), not `N-1`. As Iarsmans pointed out, python will use the population variance, not the sample variance. Second you need to take the square root, not the square. (Variance is the square of the standard deviation, not the other way around.) So the real answer is `sqrt(2/3)` which is e...
How to receive json data using HTTP POST request in Django 1.6?
24,068,576
18
2014-06-05T19:25:31Z
24,119,878
39
2014-06-09T12:02:08Z
[ "python", "django", "django-views", "http-post", "python-requests" ]
I am learning [Django](https://www.djangoproject.com/) 1.6. I want to post some [JSON](http://en.wikipedia.org/wiki/JSON) using HTTP POST request and I am using Django for this task for learning. I tried to use `request.POST['data']`, `request.raw_post_data`, `request.body` but none are working for me. my views.p...
You're confusing form-encoded and JSON data here. `request.POST['foo']` is for form-encoded data. You are posting raw JSON, so you should use `request.body`. ``` received_json_data=json.loads(request.body) ```
How to receive json data using HTTP POST request in Django 1.6?
24,068,576
18
2014-06-05T19:25:31Z
35,087,348
10
2016-01-29T14:51:32Z
[ "python", "django", "django-views", "http-post", "python-requests" ]
I am learning [Django](https://www.djangoproject.com/) 1.6. I want to post some [JSON](http://en.wikipedia.org/wiki/JSON) using HTTP POST request and I am using Django for this task for learning. I tried to use `request.POST['data']`, `request.raw_post_data`, `request.body` but none are working for me. my views.p...
For python3 you have to decode body first: ``` received_json_data = json.loads(request.body.decode("utf-8")) ```
How can I make a Python Wheel from an existing native library?
24,071,491
8
2014-06-05T22:51:41Z
24,793,171
11
2014-07-17T00:45:32Z
[ "python", "python-wheel" ]
Suppose I have a native shared library (.dll or .so), built independently of any Python mechanism, and a Python module using ctypes to interface to the library. Is there a way that I can build those into a .whl package? If so, how? Assuming this is possible, I think I'd need the wheel package installed and to use `pyt...
Here is a way. For an example, this uses libeay32.dll to expose an md5 package. The project structure is: ``` MD5 │ setup.py │ └───md5 __init__.py libeay32.dll ``` The setup.py is: ``` from setuptools import setup, Distribution class BinaryDistribution(Distribution): def is_pure(self)...
Is os.path.join necessary?
24,072,713
8
2014-06-06T01:16:54Z
24,072,843
13
2014-06-06T01:34:33Z
[ "python", "filepath" ]
Currently I use `os.path.join` almost always in my django project for cross OS support; the only places where I don't currently use it are for template names and for URLs. So in situations where I want the path `'/path/to/some/file.ext'` I use `os.path.join('path', 'to', 'some', 'file.ext')`. However I just tested my ...
The Microsoft Windows API doesn't care whether you use `/` or `\`, so it's normally fine to use either as a separator on Windows. However, command line ("DOS box" - `command.com` or `cmd.exe`) commands generally require `\` in paths (`/` is used to flag command options in these native Windows shells). So, for example, ...
How to truncate a string using str.format in Python?
24,076,297
16
2014-06-06T07:16:19Z
24,076,314
29
2014-06-06T07:17:40Z
[ "python", "string", "string-formatting" ]
How to truncate a string using [`str.format`](https://docs.python.org/2/library/stdtypes.html#str.format) in Python? Is it even possible? There is a width parameter mentioned in the [Format Specification Mini-Language](https://docs.python.org/2/library/string.html#format-specification-mini-language): ``` format_spec ...
Use `.precision` instead: ``` >>> '{:.5}'.format('aaabbbccc') 'aaabb' ``` According to the documentation [`Format Specification Mini-Language`](https://docs.python.org/2/library/string.html#format-specification-mini-language): > The **precision** is a decimal number indicating how many digits should be > displayed a...
Custom cross validation split sklearn
24,078,301
2
2014-06-06T09:19:22Z
24,083,951
10
2014-06-06T14:15:15Z
[ "python", "validation", "machine-learning", "scikit-learn", "cross-validation" ]
I am trying to split a dataset for cross validation and GridSearch in sklearn. I want to define my own split but GridSearch only takes the built in cross-validation methods. However, I can't use the built in cross validation method because I need certain groups of examples to be in the same fold. So, if I have example...
This type of thing can usually be done with `sklearn.cross_validation.LeaveOneLabelOut`. You just need to construct a label vector that encodes your groups. I.e., all samples in `K1` would take label `1`, all samples in `K2` would take label 2, and so on. Here is a fully runnable example with fake data. The important ...
numpy genfromtxt/pandas read_csv; ignore commas within quote marks
24,079,304
3
2014-06-06T10:09:16Z
24,079,561
8
2014-06-06T10:24:20Z
[ "python", "file-io", "numpy", "pandas", "genfromtxt" ]
Consider a file, `a.dat`, with contents: ``` address 1, address 2, address 3, num1, num2, num3 address 1, address 2, address 3, 1.0, 2.0, 3 address 1, address 2, "address 3, address4", 1.0, 2.0, 3 ``` I am trying to import with [`numpy.genfromtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt....
Just managed to find [this](http://stackoverflow.com/a/17942117/1461850): The key parameter that I was missing is `skipinitialspace=True` - this "deals with the spaces after the comma-delimiter" ``` a=pd.read_csv('a.dat',quotechar='"',skipinitialspace=True) address 1 address 2 address 3 num1 num2 n...
How to hide *pyc files in atom editor
24,079,976
26
2014-06-06T10:47:35Z
24,080,070
12
2014-06-06T10:52:42Z
[ "python", "atom-editor" ]
As In topic. I am using [`https://atom.io/`](https://atom.io/) fro Python/Django development and would like to hide all the `*.pyc` files from sidebar. How to configure it?
I found [this](http://discuss.atom.io/t/way-to-make-pyc-files-disappear-from-tree-view/938) where it is said that you can toggle that in `Preferences`->`Tree View`->`Hide Ignored Names` and `Hide Vcs Ignored Files`. **Edit:** The files to hide you have to specify first in `Preferences`->`Settings`->`Core Settings`->`I...
How to hide *pyc files in atom editor
24,079,976
26
2014-06-06T10:47:35Z
24,728,871
75
2014-07-14T02:41:39Z
[ "python", "atom-editor" ]
As In topic. I am using [`https://atom.io/`](https://atom.io/) fro Python/Django development and would like to hide all the `*.pyc` files from sidebar. How to configure it?
The method for hiding files that you do not want showing up in the Tree View (which is what most people mean when they ask this question) depends on whether or not you've added the files to your `.gitignore`. If you have, then all you have to do is: 1. Open Settings 2. Scroll down the list on the left to find the `Tre...
Plotting multiple line graph using pandas and matplotlib
24,080,275
7
2014-06-06T11:02:21Z
24,098,903
25
2014-06-07T15:47:06Z
[ "python", "matplotlib", "plot", "pandas" ]
I have the following data in a pandas dataframe ``` date template score 0 20140605 0 0.138786 1 20140605 1 0.846441 2 20140605 2 0.766636 3 20140605 3 0.259632 4 20140605 4 0.497366 5 20140606 0 0.138139 6 20140606 1 0.845320 7 20140606...
You can use the groupby method: ``` data.groupby("template").plot(x="date", y="score") ```
pandas dataframe groupby datetime month
24,082,784
13
2014-06-06T13:15:41Z
24,083,253
24
2014-06-06T13:38:42Z
[ "python", "datetime", "pandas" ]
Consider a csv file: ``` string,date,number a string,2/5/11 9:16am,1.0 a string,3/5/11 10:44pm,2.0 a string,4/22/11 12:07pm,3.0 a string,4/22/11 12:10pm,4.0 a string,4/29/11 11:59am,1.0 a string,5/2/11 1:41pm,2.0 a string,5/2/11 2:02pm,3.0 a string,5/2/11 2:56pm,4.0 a string,5/2/11 3:00pm,5.0 a string,5/2/14 3:02pm,6....
Managed to do it: ``` pd.groupby(b,by=[b.index.month,b.index.year]) ```
Segmentation fault and crashing when trying to import opencv
24,084,391
13
2014-06-06T14:34:44Z
24,269,779
8
2014-06-17T17:19:36Z
[ "python", "osx", "opencv" ]
I have mac os x 10.9. I downloaded opencv-python using homebrew and I have both the python 2.7 and python 3.4 versions off of the main python site, downloaded the usual way with macs. I need to use opencv, but they do not have a download package for macs so I used homebrew: ``` brew tap homebrew/science brew install o...
Chris Muktar pointed in [this thread](http://code.opencv.org/issues/3632) that the problem is caused by the conflict between the system Python and brewed Python. Following that idea, I resolved this issue by removing the system python and re-installing opencv: ``` $ cd /usr/bin $ sudo mv python python.bak $ brew unins...
How do I connect to SQL Server via sqlalchemy using Windows Authentication?
24,085,352
4
2014-06-06T15:19:17Z
24,085,353
8
2014-06-06T15:19:17Z
[ "python", "sql-server", "sqlalchemy" ]
sqlalchemy, a db connection module for Python, uses SQL Authentication (database-defined user accounts) by default. If you want to use your Windows (domain or local) credentials to authenticate to the SQL Server, the connection string must be changed. By default, as defined by sqlalchemy, the connection string to conn...
In order to use Windows Authentication with sqlalchemy and mssql, the following connection string is required: **OBDC Driver:** ``` engine = sqlalchemy.create_engine('mssql://*server_name*/*database_name*?trusted_connection=yes') ``` **SQL Express Instance:** ``` engine = sqlalchemy.create_engine('mssql://*server_n...
Why do backslashes appear twice?
24,085,680
17
2014-06-06T15:36:28Z
24,085,681
27
2014-06-06T15:36:28Z
[ "python", "string", "escaping", "backslash", "repr" ]
When I create a string containing backslashes, they get duplicated: ``` >>> my_string = "why\does\it\happen?" >>> my_string 'why\\does\\it\\happen?' ``` Why?
What you are seeing is the *representation* of the `my_string` created by its [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__) method. If you print it, you can see that you've actually got single backslashes, just as you intended: ``` >>> print(my_string) why\does\it\happen? ``` You ...
Python reference to an new instance alternating
24,086,367
6
2014-06-06T16:14:19Z
24,086,389
9
2014-06-06T16:15:33Z
[ "python", "python-2.7" ]
I have been playing with Python these days, and I realize some interesting way how Python assign id(address) to new instance (int and list). For example, if I keep call id function with a number (or two different number), it return the same result. e.g. ``` >>> id(12345) 4298287048 >>> id(12345) 4298287048 >>> id(123...
You are creating a new object **without any other references** and Python re-uses the memory location when the object is destroyed again after `id()` is done with it. In CPython, the result of `id()` *happens* to be the memory location of the object. From the [`id()` function documentation](https://docs.python.org/2/li...
Can a Java GUI control a Python backend?
24,089,806
6
2014-06-06T20:03:26Z
24,089,943
8
2014-06-06T20:13:31Z
[ "java", "python" ]
Okay so what I have so far is a gui(In Java) and a program(In Python). I want the button in the gui when pressed to send the outputs to the python program and to run it. I then want the gui program to display the python print commands in the text box on the right side. So, my question is, is this possible and how woul...
You can spawn a python process: ``` Process p = Runtime.getRuntime().exec("python "+yourpythonprog+" "+yourargs); ``` Then use the `Process` object to read the output of your python program.
Skip over a value in the range function in python
24,089,924
9
2014-06-06T20:11:43Z
24,090,006
19
2014-06-06T20:18:33Z
[ "python", "loops", "for-loop", "range" ]
What is the pythonic way of looping through a range of numbers and skipping over one value? For example, the range is from 0 to 100 and I would like to skip 50. Edit: Here's the code that I'm using ``` for i in range(0, len(list)): x= listRow(list, i) for j in range (#0 to len(list) not including x#) ...
You can use any of these: ``` # Create a range that does not contain 50 for i in [x for x in xrange(100) if x != 50]: print i # Create 2 ranges [0,49] and [51, 100] for i in range(50) + range(51, 100): print i # Create a iterator and skip 50 xr = iter(xrange(100)) for i in xr: print i if i == 49: ...
Best way to run Julia code in an IPython notebook (or Python code in an IJulia notebook)
24,091,373
19
2014-06-06T22:11:01Z
24,106,944
23
2014-06-08T14:06:56Z
[ "python", "ipython", "julia-lang" ]
My goal is to run only a few lines of Julia in an IPython notebook where the majority of the code will be Python for some experiments ... I found a nice example notebook here: <http://nbviewer.ipython.org/github/JuliaLang/IJulia.jl/blob/master/python/doc/JuliaMagic.ipynb> And now I am wondering how I would install t...
# Run Julia inside an IPython notebook ## Hack In order to run Julia snippets (or *other* language) inside an IPython notebook, I just append the string `'julia'` to the **`default`** list in the `_script_magics_default` method from the `ScriptMagics` class in: * `/usr/lib/python3.4/site-packages/IPython/core/magics...
Best way to run Julia code in an IPython notebook (or Python code in an IJulia notebook)
24,091,373
19
2014-06-06T22:11:01Z
24,682,197
8
2014-07-10T16:52:02Z
[ "python", "ipython", "julia-lang" ]
My goal is to run only a few lines of Julia in an IPython notebook where the majority of the code will be Python for some experiments ... I found a nice example notebook here: <http://nbviewer.ipython.org/github/JuliaLang/IJulia.jl/blob/master/python/doc/JuliaMagic.ipynb> And now I am wondering how I would install t...
Another option is to use [Beaker](http://beakernotebook.com). They have a [tutorial notebook](http://sharing.beakernotebook.com/gist/anonymous/11152408) available that mixes R and Python; using Julia is just as easy.
Pascal's Triangle for Python
24,093,387
7
2014-06-07T03:35:53Z
24,093,559
8
2014-06-07T04:08:47Z
[ "python", "pascals-triangle" ]
As a learning experience for Python, I am trying to code my own version of Pascal's triangle. It took me a few hours (as I am just starting), but I came out with this code: ``` pascals_triangle = [] def blank_list_gen(x): while len(pascals_triangle) < x: pascals_triangle.append([0]) def pascals_tri_gen(r...
I know you want to implement yourself, but the best way for me to explain is to walk through an implementation. Here's how I would do it, and this implementation relies on my fairly complete knowledge of how Python's functions work, so you probably won't want to use this code yourself, but it may get you pointed in the...
"The C extension could not be compiled' error. - while installing Flask
24,097,129
18
2014-06-07T12:22:09Z
24,097,144
31
2014-06-07T12:23:27Z
[ "python", "flask" ]
I get the error below when installing flask in virtualenv on debian 7. apt-get-install tells me I already have GCC. I tried `apt-get install libpcre3-dev` but then reinstalled flask with `pip install Flask-scss --force-reinstall -I` but still got the same error. How do I fix this so that the speedups are used? The Err...
You need to install the [`python-dev` package](http://packages.ubuntu.com/search?keywords=python-dev) too; it depends on the right package that [contains `Python.h`](http://packages.ubuntu.com/utopic/i386/libpython2.7-dev/filelist): ``` apt-get install python-dev ```
"The C extension could not be compiled' error. - while installing Flask
24,097,129
18
2014-06-07T12:22:09Z
24,097,149
7
2014-06-07T12:23:40Z
[ "python", "flask" ]
I get the error below when installing flask in virtualenv on debian 7. apt-get-install tells me I already have GCC. I tried `apt-get install libpcre3-dev` but then reinstalled flask with `pip install Flask-scss --force-reinstall -I` but still got the same error. How do I fix this so that the speedups are used? The Err...
``` sudo apt-get install python-dev ``` Or ``` sudo apt-get install python3-dev for python3 ```
Flask: Background thread sees a non-empty queue as empty
24,098,318
8
2014-06-07T14:39:44Z
24,101,692
12
2014-06-07T23:47:43Z
[ "python", "multithreading", "flask", "uwsgi" ]
When I run a Flask app in uwsgi, the background thread and the app functions see different values when querying size of the same Queue. ### Components * A Flask application with a [thread-safe queue](https://docs.python.org/2/library/queue.html). * A `GET` call returns the queue size. * A `POST` call adds an element ...
From the [Things to Know documenation page](http://uwsgi-docs.readthedocs.org/en/latest/ThingsToKnow.html): > uWSGI tries to (ab)use the Copy On Write semantics of the `fork()` call whenever possible. By default it will fork after having loaded your applications to share as much of their memory as possible. If this be...
tweepy how to get a username from id
24,100,377
7
2014-06-07T18:32:20Z
24,100,492
8
2014-06-07T18:47:57Z
[ "python", "tweepy" ]
how do I derrive a plaintext username from a user Id number with tweepy? Here is the CORRECTED code that I am using: ``` ids = [] userid = "someOne" for page in tweepy.Cursor(api.followers_ids, screen_name=userid).pages(): ids.extend(page) time.sleep(60) print len(ids), "following have been gathered from",...
You are iterating `ids` and `i` already contains element of `ids`. Try to pass `i` to `lookup_users`: ``` for i in ids: print screen_name(api.lookup_users(i)) # print screen_name(api.lookup_users(ids[i])) ``` **update**, try this way: ``` users = api.lookup_users(user_ids=ids) for u in users: print u.scr...
Multiprocessing Pause-Restart functionality using `event`
24,100,401
5
2014-06-07T18:35:56Z
24,100,700
8
2014-06-07T19:12:26Z
[ "python", "multiprocessing" ]
I am using a code posted below to enable **pause-restart** functionality for `multiprocessing` Pool. I would appreciate if you explain me why `event` variable has to be sent as an argument to `setup()` function. Why then a global variable `unpaused` is declared inside of the scope of `setup()` function and then it is ...
You're misunderstanding how `Event` works. But first, I'll cover what `setup` is doing. The `setup` function is executed in each child process inside the pool as soon as it is started. So, you're setting a global variable called `event` inside each process to be the the same `multiprocessing.Event` object you created ...
Developing Python applications in Qt Creator
24,100,602
18
2014-06-07T19:00:14Z
24,121,860
20
2014-06-09T13:58:14Z
[ "python", "qt" ]
I've developed a few Qt projects in C++ using Qt Creator in the past, but now I want to experiment with the Python implementation of Qt. I discovered that Qt Creator 2.8 and higher [support Python](http://blog.qt.digia.com/blog/2013/07/11/qt-creator-2-8-0-released/), but I haven't been able to figure out how to create ...
Currently, `Qt Creator` allows you to create Python files (not projects) and run them. It also has syntax highlighting, but it lacks more complex features such as autocomplete. Running scripts requires some configuration (I used [this](http://ceg.developpez.com/tutoriels/python/configurer-qtcreator-pour-python/) tutor...
Finding median of list in Python
24,101,524
43
2014-06-07T21:04:05Z
24,101,534
25
2014-06-07T22:09:12Z
[ "python", "list", "sorting", "median" ]
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order. If the list contains an even number of elements, the function should return the average of the middle two. Here are some examples (sorted for display purposes): ``` median([1]...
The sorted() function is very helpful for this. Use the sorted function to order the list, then simply return the middle value (or average the two middle values if the list contains an even amount of elements). ``` def median(lst): sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if...
Finding median of list in Python
24,101,524
43
2014-06-07T21:04:05Z
24,101,655
50
2014-06-07T23:33:03Z
[ "python", "list", "sorting", "median" ]
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order. If the list contains an even number of elements, the function should return the average of the middle two. Here are some examples (sorted for display purposes): ``` median([1]...
Use [`numpy.median()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.median.html) to make a one-line function: ``` import numpy def median(lst): return numpy.median(numpy.array(lst)) ``` This runs as: ``` >>> median([7,12,3,1,6,9]) 6.5 >>> median([[6, 8, 2, 3], [1, 5, 6, 2]]) 4.0 >>> ``` Or, to [**w...
Finding median of list in Python
24,101,524
43
2014-06-07T21:04:05Z
24,101,797
64
2014-06-08T00:08:43Z
[ "python", "list", "sorting", "median" ]
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order. If the list contains an even number of elements, the function should return the average of the middle two. Here are some examples (sorted for display purposes): ``` median([1]...
Python 3.4 has [`statistics.median`](https://docs.python.org/3/library/statistics.html#statistics.median): > Return the median (middle value) of numeric data. > > When the number of data points is odd, return the middle data point. > When the number of data points is even, the median is interpolated by taking the aver...
How to link msvcr100.dll to cx_freeze program
24,103,105
6
2014-06-08T04:50:04Z
24,124,313
8
2014-06-09T16:13:01Z
[ "python", "python-3.x", "dll", "windows-7-x64", "cx-freeze" ]
I have a Console type Python3 program [.py] which when executed [exe file after compiling] gives missing `msvcr100.dll` error in some machines [friends or relatives etc.] to which I need to download that dll file [google search and download it] and copy it to `system32` folder myself. Hence, after googling I found tha...
Thanks for all the help everyone but I figured it out myself. The `include_msvcr` option is to be added in the setup.py file as follows: ``` import sys from cx_Freeze import setup, Executable build_exe_options = { "include_msvcr": True #skip error msvcr100.dll missing } base=None if sys.platform=='win32': base="...
Google App Engine: Won't serve static assets with below error:
24,106,776
5
2014-06-08T13:45:36Z
24,107,830
10
2014-06-08T15:40:50Z
[ "python", "css", "google-app-engine" ]
Google is useless in this case, it seems I am the first to encounter this error :/ Works fine on my Mac, but using the same files on a Windows 8 rig gives the following error in the logs when trying to request static assets like CSS files and images. Here is a snippet of the error: ``` INFO 2014-06-08 14:42:28,431...
Weird. Another person had a static files 500 error on Windows yesterday. This may be a GAE bug, where the mimetype guess is sent as a python unicode string in the header. Try adding `mime_type: "text/css"` to your `- url: /css`, as follows: ``` - url: /css static_dir: css mime_type: "text/css" ``` in app.yaml. I ...
Simple way of creating a 2D array with random numbers (Python)
24,108,417
5
2014-06-08T16:46:38Z
24,108,444
11
2014-06-08T16:49:49Z
[ "python", "arrays", "random" ]
I know that an easy way to create a NxN array full of zeroes in Python is with: ``` [[0]*N for x in range(N)] ``` However, let's suppose I want to create the array by filling it with random numbers: ``` [[random.random()]*N for x in range(N)] ``` This doesn't work because each random number that is created is then ...
You could use a nested list comprehension: ``` >>> N = 5 >>> import random >>> [[random.random() for i in range(N)] for j in range(N)] [[0.9520388778975947, 0.29456222450756675, 0.33025941906885714, 0.6154639550493386, 0.11409250305307261], [0.6149070141685593, 0.3579148659939374, 0.031188652624532298, 0.4607597656919...
Beautiful Soup: 'ResultSet' object has no attribute 'find_all'?
24,108,507
13
2014-06-08T16:56:11Z
24,108,588
7
2014-06-08T17:04:29Z
[ "python", "beautifulsoup" ]
I am trying to scrape a simple table using Beautiful Soup. Here is my code: ``` import requests from bs4 import BeautifulSoup url = 'https://gist.githubusercontent.com/anonymous/c8eedd8bf41098a8940b/raw/c7e01a76d753f6e8700b54821e26ee5dde3199ab/gistfile1.txt' r = requests.get(url) soup = BeautifulSoup(r.text) table =...
> ``` > table = soup.find_all(class_='dataframe') > ``` This gives you a result set – i.e. *all* the elements that match the class. You can either iterate over them or, if you know you only have one `dataFrame`, you can use `find` instead. From your code it seems the latter is what you need, to deal with the immedia...
Beautiful Soup: 'ResultSet' object has no attribute 'find_all'?
24,108,507
13
2014-06-08T16:56:11Z
24,108,608
11
2014-06-08T17:06:39Z
[ "python", "beautifulsoup" ]
I am trying to scrape a simple table using Beautiful Soup. Here is my code: ``` import requests from bs4 import BeautifulSoup url = 'https://gist.githubusercontent.com/anonymous/c8eedd8bf41098a8940b/raw/c7e01a76d753f6e8700b54821e26ee5dde3199ab/gistfile1.txt' r = requests.get(url) soup = BeautifulSoup(r.text) table =...
The `table` variable contains an array. You would need to call `find_all` on its members (even though you know it's an array with only one member), not on the entire thing. ``` >>> type(table) <class 'bs4.element.ResultSet'> >>> type(table[0]) <class 'bs4.element.Tag'> >>> len(table[0].find_all('tr')) 6 >>> ```
Finding k closest numbers to a given number
24,112,259
25
2014-06-09T00:29:14Z
24,112,356
41
2014-06-09T00:45:41Z
[ "python", "closest" ]
Say I have a list `[1,2,3,4,5,6,7]`. I want to find the 3 closest numbers to, say, 6.5. Then the returned value would be `[5,6,7]`. Finding one closest number is not that tricky in python, which can be done using ``` min(myList, key=lambda x:abs(x-myNumber)) ``` But I am trying not to put a loop around this to find ...
The [*heapq.nsmallest()*](https://docs.python.org/2.7/library/heapq.html#heapq.nsmallest) function will do this neatly and efficiently: ``` >>> from heapq import nsmallest >>> s = [1,2,3,4,5,6,7] >>> nsmallest(3, s, key=lambda x: abs(x-6.5)) [6, 7, 5] ``` Essentially this says, "Give me the three input values that ha...
Cannot import urllib.request and urllib.parse
24,115,006
3
2014-06-09T06:46:37Z
24,115,098
7
2014-06-09T06:53:22Z
[ "python", "import", "import-libraries" ]
I will be grateful for any help. I use Python 3.4.1 and I try to import urllib.request and urllib.parse. Without success. I always receive: > ``` > Traceback (most recent call last): > File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked > AttributeError: 'module' object has no attribute '__pa...
Without the actual code, I am guessing based on my past experience with such an error. I presume you are trying to import `urllib.parse` in a file called `importowanie.py` in `C:/Users/x/Documents/PROGRAMING and MODELING/Phyton/find cure words`. When Python tries to import a module by the name `urllib`, it first check...
How to plot a density map in python?
24,119,920
9
2014-06-09T12:04:27Z
24,121,745
7
2014-06-09T13:52:29Z
[ "python", "matplotlib", "histogram" ]
I have a .txt file containing the x,y values of regularly spaced points in a 2D map, the 3rd coordinate being the density at that point. ``` 4.882812500000000E-004 4.882812500000000E-004 0.9072267 1.464843750000000E-003 4.882812500000000E-004 1.405174 2.441406250000000E-003 4.882812500000000E-004 24.32851 3.41...
The comment from @HYRY is good, but a complete minimal working answer (with a picture!) is better. Using [`plt.pcolormesh`](http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.pcolormesh) ``` import pylab as plt import numpy as np # Sample data side = np.linspace(-2,2,15) X,Y = np.meshgrid(side,side) Z ...
How to plot a density map in python?
24,119,920
9
2014-06-09T12:04:27Z
24,122,985
10
2014-06-09T14:57:06Z
[ "python", "matplotlib", "histogram" ]
I have a .txt file containing the x,y values of regularly spaced points in a 2D map, the 3rd coordinate being the density at that point. ``` 4.882812500000000E-004 4.882812500000000E-004 0.9072267 1.464843750000000E-003 4.882812500000000E-004 1.405174 2.441406250000000E-003 4.882812500000000E-004 24.32851 3.41...
Here is my aim at a more complete answer including choosing the color map and a logarithmic normalization of the color axis. ``` import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm import numpy as np x, y, z = np.loadtxt('data.txt', unpack=True) N = int(len(z)**.5) z = z.re...
Strange error with matplotlib axes labels
24,120,023
5
2014-06-09T12:10:13Z
33,925,268
12
2015-11-25T19:51:01Z
[ "python", "matplotlib", "axes" ]
I'm very new to Python and programming in general, so apologies in advance if I'm missing something obvious. I'm trying to plot a graph and label the axes, but every time I try to label the y axis an exception is raised. I wrote the code below in a new script to make sure the problem wasn't coming from somewhere else i...
I had this same issue when working in iPython notebook. I think it can be re-created as follows: ``` from matplotlib.pyplot as plt plt.ylabel = 'somestring' # oh wait this isn't the right syntax. ... plt.ylabel('somestring') # now this breaks because the function has been turned into a string ``` Re-starting the ke...
In Python, why is list(None) an error but [None] is not?
24,120,448
6
2014-06-09T12:36:19Z
24,120,496
20
2014-06-09T12:38:55Z
[ "python", "list" ]
Passing `None` to Python's `list` constructor is a `TypeError`: ``` >>> l = list(None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable ``` But using brackets to instantiate a `list` is fine; using `None` with the built-in functions is also fine: `...
They are *not* equivalent. `list()` attempts to iterate over its argument, making each object a separate list item, whereas a list literal `[]` just takes exactly what it's given. Compare: ``` >>> list("foo") ['f', 'o', 'o'] >>> ["foo"] ['foo'] ``` You can't iterate over `None`, hence the error. You will get the same...
Sklearn, gridsearch: how to print out progress during the execution?
24,121,018
7
2014-06-09T13:08:38Z
24,144,654
9
2014-06-10T15:15:00Z
[ "python", "logging", "scikit-learn" ]
I am using `GridSearch` from `sklearn` to optimize parameters of the classifier. There is a lot of data, so the whole process of optimization takes a while: more than a day. I would like to watch the performance of the already-tried combinations of parameters during the execution. Is it possible?
Set the `verbose` parameter in `GridSearchCV` to a positive number (the greater the number the more detail you will get). For instance: ``` GridSearchCV(clf, param_grid, cv=cv, scoring='accuracy', verbose=10) ```
python keyword arguments with hyphen
24,121,279
2
2014-06-09T13:23:46Z
24,121,330
7
2014-06-09T13:26:49Z
[ "python", "arguments", "keyword", "hyphen" ]
I have a keyword argument function: ``` def f1(**kw): for key,val in kw.iteritems(): print "key=%s val=%s" % (key,val) f1(Attr1 = "Val1", Attr2 = "Val2") # works fine. f1(Attr1-SubAttr = "Val1", Attr2 = "Val2") # complains about keyword being an expression. f1("Attr1-SubAttr" = "Val1", Attr2 = "Val2")...
Keyword arguments *must* be [valid Python identifiers](https://docs.python.org/2/reference/lexical_analysis.html#identifiers); these don't allow for `-` as that's reserved for subtraction. You can pass in arbitrary strings using the [`**kwargs` variable keyword argument syntax](https://docs.python.org/2/tutorial/contr...
pandas ValueError: numpy.dtype has the wrong size, try recompiling
24,122,850
13
2014-06-09T14:50:19Z
24,242,333
22
2014-06-16T11:09:21Z
[ "python", "numpy", "pandas" ]
I took a new clean install of OSX 10.9.3 and installed pip, and then did ``` pip install pandas pip install numpy ``` Both installs seemed to be perfectly happy, and ran without any errors (though there were a zillion warnings). When I tried to run a python script with import pandas, I got the following error: ``` ...
You can install previous version of pandas. ``` pip uninstall numpy pip uninstall pandas pip install pandas==0.13.1 ``` In my situation it solved problem...
pandas ValueError: numpy.dtype has the wrong size, try recompiling
24,122,850
13
2014-06-09T14:50:19Z
25,442,201
17
2014-08-22T07:57:20Z
[ "python", "numpy", "pandas" ]
I took a new clean install of OSX 10.9.3 and installed pip, and then did ``` pip install pandas pip install numpy ``` Both installs seemed to be perfectly happy, and ran without any errors (though there were a zillion warnings). When I tried to run a python script with import pandas, I got the following error: ``` ...
``` sudo pip install pandas sudo easy_install --upgrade numpy ``` should also realign everything.
pyvenv-3.4 returned non-zero exit status 1
24,123,150
12
2014-06-09T15:06:51Z
24,123,372
9
2014-06-09T15:18:46Z
[ "python", "unix", "python-3.x", "virtualenv" ]
I'm in Kubuntu 14.04 , I want to create a virtualenv with python3.4. I did with python2.7 before in other folder. But when I try: ``` pyvenv-3.4 venv ``` I've got: `Error: Command '['/home/fmr/projects/ave/venv/bin/python3.4', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1`
I got a solution installing python-virtualenv ``` sudo apt-get install python-virtualenv ``` and using ``` virtualenv --python=/usr/bin/python3.4 venv ```
Recursive feature elimination on Random Forest using scikit-learn
24,123,498
12
2014-06-09T15:26:35Z
25,454,051
16
2014-08-22T19:14:15Z
[ "python", "pandas", "scikit-learn", "random-forest", "feature-selection" ]
I'm trying to preform recursive feature elimination using `scikit-learn` and a random forest classifier, with OOB ROC as the method of scoring each subset created during the recursive process. However, when I try to use the `RFECV` method, I get an error saying `AttributeError: 'RandomForestClassifier' object has no a...
Here's what I've done to adapt RandomForestClassifier to work with RFECV: ``` class RandomForestClassifierWithCoef(RandomForestClassifier): def fit(self, *args, **kwargs): super(RandomForestClassifierWithCoef, self).fit(*args, **kwargs) self.coef_ = self.feature_importances_ ``` Just using this cl...
Parse XML from URL into python object
24,124,643
16
2014-06-09T16:31:01Z
24,124,770
20
2014-06-09T16:38:30Z
[ "python", "xml", "django", "xml-parsing", "urllib2" ]
The goodreads website has this API for accessing a user's 'shelves:' <https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread> It returns XML. I'm trying to create a django project that shows books on a shelf from this API. I'm looking to find out how (or if there is a better way...
I'd use [`xmltodict`](https://github.com/martinblech/xmltodict) to make a python dictionary out of the `XML` data structure and pass this dictionary to the template inside the context: ``` import urllib2 import xmltodict def homepage(request): file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068...
Are sets internally sorted, or is the __str__ method displaying a sorted list?
24,126,240
2
2014-06-09T18:11:30Z
24,126,255
8
2014-06-09T18:12:23Z
[ "python", "python-2.7", "set" ]
I have a `set`, I add items (ints) to it, and when I print it, the items apparently are sorted: ``` a = set() a.add(3) a.add(2) a.add(4) a.add(1) a.add(5) print a # set([1, 2, 3, 4, 5]) ``` I have tried with various values, apparently it needs to be only ints. I run Python 2.7.5 under MacOSX. It is also reproduced ...
This is a coincidence. The data is neither sorted nor does `__str__` sort. The hash values for integers equal their value (except for `-1` and long integers outside the `sys.maxint` range), which *increases the chance* that integers are slotted in order, but that's not a given. `set` uses a hash table to track items ...
Why in Python, += and -= are considered as delimiters?
24,126,468
3
2014-06-09T18:24:18Z
24,126,650
7
2014-06-09T18:35:51Z
[ "python", "operators", "delimiter" ]
I am reading a [tutorial](http://zetcode.com/lang/python/lexicalstructure/) about python, it's lexical structure to be more precise. And I just want to know why in Python, the: ``` += , -= , *= , /= , //= , %=, <= , |= , ^= , >>= , <<= , **= ``` are considered as delimiters and not operators? After all, the "+...
The syntax you refer to are used in [augmented assignment statements](https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements). Like regular [assignment](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), these are not expressions, so they are *not operators eith...
uWSGI request timeout in Python
24,127,601
12
2014-06-09T19:35:15Z
25,573,359
18
2014-08-29T17:32:36Z
[ "python", "rest", "timeout", "request", "uwsgi" ]
Trying to set the timeout for requests in uWSGI, I'm not sure of the correct setting. There seem to be multiple timeout options (socket, interface, etc.) and it's not readily evident which setting to configure or where to set it. The behavior I'm looking for is to extend the time a request to the resource layer of a R...
You're propably looking for the **harakiri** parameter - if request takes longer than specified harakiri time (in seconds), the request will be dropped and the corresponding worker recycled. For standalone uwsgi (ini config): ``` [uwsgi] http = 0.0.0.0:80 harakiri = 30 ... ``` If you have nginx proxy before uwsgi yo...
How to include a local table of contents into Sphinx doc?
24,129,481
13
2014-06-09T21:36:21Z
24,160,594
14
2014-06-11T10:28:18Z
[ "python", "documentation", "python-sphinx" ]
How to include a local table of contents into Sphinx doc? I tried ``` .. toc:: ``` But that doesn't seem to have any effect: nothing is inserted in the document. Basically I need links to the sections in the current page to be placed at a certain location of each page. Is this possible? Thanks!
I'm not 100% sure this is what you're looking for, but the `.. contents::` directive may help. By default, it'll give you the headings for the whole page, wherever you put the directive. With `:local:` specified, it will generate a local TOC for the headings below where you put the directive (handy for sub-section tocs...
TypeError:__init__() got an unexpected keyword argument 'delay'
24,130,398
3
2014-06-09T23:03:56Z
25,298,989
10
2014-08-14T02:10:26Z
[ "python" ]
I am getting a TypeError in the following python program where the constructor is being called. If I remove the delay argument, I get the same error with "bw". I cannot figure out the mistake. Please help. I am trying to create a network topology using python. ``` #!/usr/bin/python from mininet.topo import Topo from...
Remember to set the link type as tc. Specify it on your script just like this: ``` net = Mininet(topo=topo, link=TCLink) ``` Remember to import the TCLink as well on your python script ``` from mininet.link import TCLink ``` Instead, if you want to call mininet from the command prompt, set the --link parameter as ...
Convert generator object to list for debugging
24,130,745
35
2014-06-09T23:41:38Z
24,130,771
63
2014-06-09T23:44:25Z
[ "python", "python-2.7", "generator", "ipdb" ]
When I'm debugging in Python using IPython, I sometimes hit a break-point and I want to examine a variable that is currently a generator. The simplest way I can think of doing this is converting it to a list, but I'm not clear on what's an easy way of doing this in one line in `ipdb`, since I'm so new to Python.
Simply call `list` on the generator. ``` lst = list(gen) lst ``` Be aware that this affects the generator which will not return any further items. You also cannot directly call `list` in IPython, as it conflicts with a command for listing lines of code. Tested on this file: ``` def gen(): yield 1 yield 2 ...
X and Y axis labels for Bokeh figure
24,131,501
16
2014-06-10T01:29:38Z
24,131,542
9
2014-06-10T01:36:57Z
[ "python", "bokeh" ]
Does anyone know how to add x and y axis title/labels for a Bokeh figure? E.g. X-axis: time, Y-axis: stock price. Thanks a lot!
Check out this example: [periodic table](http://bokeh.pydata.org/docs/gallery/elements.html) You can also now give general plot related options (`plot_width`, `title`, etc.) to a call to `figure(...)` instead of the renderer function (`circle`, in that example)
X and Y axis labels for Bokeh figure
24,131,501
16
2014-06-10T01:29:38Z
24,782,534
11
2014-07-16T13:47:41Z
[ "python", "bokeh" ]
Does anyone know how to add x and y axis title/labels for a Bokeh figure? E.g. X-axis: time, Y-axis: stock price. Thanks a lot!
### Bokeh 0.11.1 As @bigreddot kindly points out, the [user's guide section on axes](http://bokeh.pydata.org/en/latest/docs/user_guide/styling.html#axes) now shows how to edit properties of existing axes. The way to do it is the same as before: ``` p = figure(width=300, height=300, x_axis_label='Initial xlabel') p.xa...
Scikit-learn cross validation scoring for regression
24,132,237
5
2014-06-10T03:08:50Z
24,226,041
9
2014-06-15T02:27:51Z
[ "python", "scikit-learn", "regression" ]
How can one use `cross_val_score` for regression? The default scoring seems to be accuracy, which is not very meaningful for regression. Supposedly I would like to use mean squared error, is it possible to specify that in `cross_val_score`? Tried the following two but doesn't work: `scores = cross_validation.cross_val...
I dont have the reputation to comment but I want to provide this link for you and/or a passersby where the negative output of the MSE in scikit learn is discussed - <https://github.com/scikit-learn/scikit-learn/issues/2439> In addition (to make this a real answer) your first option is correct in that not only is MSE t...
Python get most recent file in a directory with certain extension
24,134,495
6
2014-06-10T06:41:23Z
24,134,783
10
2014-06-10T07:01:22Z
[ "python", "file", "file-io" ]
I'm trying to use the newest file in the 'upload' directory with '.log' extension to be processed by Python. I use a `Ubuntu` web server and file upload is done by a html script. The uploaded file is processed by a Python script and results are written to a `MySQL` database. I used [this](http://stackoverflow.com/quest...
The problem is that the logical inverse of `max` is `min`: ``` newest = max(glob.iglob('upload/*.log'), key=os.path.getctime) ``` For your purposes should be: ``` newest = min(glob.iglob('upload/*.log'), key=os.path.getctime) ```
Ubuntu: pip not working with python3.4
24,137,291
7
2014-06-10T09:19:57Z
24,139,871
11
2014-06-10T11:30:37Z
[ "python", "ubuntu", "python-3.x", "pip" ]
Trying to get pip working on my Ubuntu pc. pip seems to be working for python2.7, but not for others. Here's the problem: ``` $ pip Traceback (most recent call last): File "/usr/local/bin/pip", line 9, in <module> load_entry_point('pip==1.4.1', 'console_scripts', 'pip')() File "/usr/local/lib/python3.4/dist-packages/...
You have pip installed for python 2, but not python 3. Ubuntu distributes `python-pip`, `python3-pip`, `python-setuptools` and `python3-setuptools` packages, which you can install (`apt-get install` etc) as necessary. Thereafter, note that `pip` installs for python 2, and `pip3` installs for python 3 (similar to `pyth...
FieldError at /admin/ - Unknown field(s) (added_on) specified for UserProfile
24,137,457
15
2014-06-10T09:27:50Z
24,137,698
34
2014-06-10T09:39:29Z
[ "python", "django", "django-models", "django-admin", "django-users" ]
I'm using a custom user model in Django. The model works fine and is able to create a user. But when I try to access the admin page it throws me the error ``` FieldError at /admin/ Unknown field(s) (added_on) specified for UserProfile ``` The `UserProfile` has a `added_on` attribute. I can't think of any reason why t...
Your problem is the `auto_now_add=True` on that field. See the notes on the [documentation for DateField](https://docs.djangoproject.com/en/1.6/ref/models/fields/#datefield): > Note that the current date is *always* used; it’s not just a default value that you can override. and > As currently implemented, setting ...
How do I create test and train samples from one dataframe with pandas?
24,147,278
49
2014-06-10T17:24:57Z
24,147,363
52
2014-06-10T17:29:25Z
[ "python", "python-2.7", "pandas", "dataframe" ]
I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing. Thanks!
I would just use numpy's `randn`: ``` In [11]: df = pd.DataFrame(np.random.randn(100, 2)) In [12]: msk = np.random.rand(len(df)) < 0.8 In [13]: train = df[msk] In [14]: test = df[~msk] ``` And just to see this has worked: ``` In [15]: len(test) Out[15]: 21 In [16]: len(train) Out[16]: 79 ```