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
Python DistributionNotFound Error after installing EB CLI 3.0
29,051,968
7
2015-03-14T17:28:55Z
29,948,666
19
2015-04-29T15:48:53Z
[ "python", "python-2.7", "amazon-web-services", "command-line-interface", "elastic-beanstalk" ]
Have tried many things, but keep getting this error after multiple attempts to update python, pip, etc. I am on OS X running 10.9.5. ``` CMD% eb Traceback (most recent call last): File "/usr/local/bin/eb", line 5, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python....
I was experiencing a similar error when trying to run eb, though not for dateutil... ``` Traceback (most recent call last): File "/usr/local/bin/eb", line 5, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resourc...
Show partitions on a pyspark RDD
29,056,079
2
2015-03-15T00:58:12Z
29,056,482
7
2015-03-15T02:06:10Z
[ "python", "apache-spark", "pyspark" ]
The pyspark RDD documentation > <http://spark.apache.org/docs/1.2.1/api/python/pyspark.html#pyspark.RDD> does not show any method(s) to display partition information for an RDD. Is there any way to get that information without executing an additional step e.g.: ``` myrdd.mapPartitions(lambda x: iter[1]).sum() ``` ...
I missed it: very simple: ``` rdd.getNumPartitions() ``` Not used to the java-ish **get**FooMethod() anymore ;)
How do I make this long if statement less cumbersome?
29,056,312
2
2015-03-15T01:36:40Z
29,056,324
9
2015-03-15T01:38:22Z
[ "python", "if-statement", "comparison-operators" ]
Here is an `if` statement from a method I was making (never mind what it's for): `if str.lower(char) == "a" or str.lower(char) == "e" or str.lower(char) == "i" or str.lower(char) == "o" or str.lower(char) == "u":` There must be a shorter way to write this `if` statement, right? Maybe something like: `if str.lower(ch...
The `in` keyword is designed for this sort of thing: ``` if str.lower(char) in "aeiou": ... ```
pyGTK image type error (save pixmap)
29,058,763
10
2015-03-15T08:38:05Z
30,006,595
10
2015-05-02T19:33:05Z
[ "python", "gtk", "pixmap" ]
How can I save a pixmap as a .png file? I do this: ``` image = gtk.Image() image.set_from_pixmap(disp.pixmap, disp.mask) pixbf=image.get_pixbuf() pixbf.save('path.png') ``` I get this error: ``` pixbf=image.get_pixbuf() ValueError: image should be a GdkPixbuf or empty ```
From the [documentation](http://www.pygtk.org/pygtk2reference/class-gtkimage.html#method-gtkimage--get-pixbuf), > The `get_pixbuf()` method gets the `gtk.gdk.Pixbuf` being displayed by the `gtk.Image`. > The `return` value may be `None` if no image data is set. If the storage type of the image is not either > `gtk.IMA...
String matching performance: gcc versus CPython
29,058,914
9
2015-03-15T08:58:51Z
29,059,906
12
2015-03-15T11:07:26Z
[ "python", "c++", "performance", "gcc", "cpython" ]
Whilst researching performance trade-offs between Python and C++, I've devised a small example, which mostly focusses on a dumb substring matching. Here is the relevant C++: ``` using std::string; std::vector<string> matches; std::copy_if(patterns.cbegin(), patterns.cend(), back_inserter(matches), [&fileContents] ...
The python 3.4 code `b'abc' in b'abcabc'` (or `b'abcabc'.__contains__(b'abc')` as in your example) executes the [`bytes_contains`](https://hg.python.org/cpython/file/3.4/Objects/bytesobject.c#l763) method, which in turn calls the inlined function [`stringlib_find`](https://hg.python.org/cpython/file/8ddda7d1f8e3/Object...
does the extra comma at the end of a dict, list or set has any special meaning?
29,063,868
2
2015-03-15T17:30:32Z
29,063,884
9
2015-03-15T17:32:23Z
[ "python", "data-structures", "syntax" ]
I noticed by chance that adding an extra separator comma at the end of a list, dict or set is syntactically correct and does not seem to add anything to the data structure: ``` In [1]: d1 = {'a': 1, 'b': 2} In [2]: d2 = {'c': 10, 'd': 20,} In [3]: d1 Out[3]: {'a': 1, 'b': 2} In [4]: d2 Out[4]: {'c': 10, 'd': 20} ``...
It has no special meaning in a list or dictionary, but can be useful when using source code change management tools, see below. Non-empty tuples are defined by using a comma between elements, the parentheses are optional and only required in contexts where the comma could have a different meaning. Because the comma d...
Representing Coordinates in GeoAlchemy2
29,074,414
3
2015-03-16T10:22:51Z
29,074,669
8
2015-03-16T10:35:39Z
[ "python", "geoalchemy2" ]
To extend my restfull api with GPS locations I decided to try geoalchemy. I already have a database going and I think it saves the points to my database already. However, everytime I try to print a point that I saved (for instance to return to the the user) I get a memory adress or something like this: ``` <WKBEle...
That would be in the **W**ell-**K**nown **B**inary format; you can use the [`geoalchemy2.functions.ST_AsText`](http://geoalchemy-2.readthedocs.org/en/latest/spatial_functions.html#geoalchemy2.functions.ST_AsText) to convert them to the WKT text format. This would work in the database itself, thus you'd apply this to y...
Pythonic Variable Assignment
29,075,091
2
2015-03-16T10:55:30Z
29,075,196
7
2015-03-16T11:01:29Z
[ "python", "coding-style" ]
At the moment I have a large section of code that looks like this: ``` daily_stats.Turnover = int(row[2]) daily_stats.Cars = int(row[0]) daily_stats.Cash = int(row[29]) daily_stats.Card = int(row[33]) daily_stats.Other = int(row[31]) + int(row[35]) + int(row[37]) daily_stats.Exit = int(row[43]) daily_stats.Manual = in...
You could save your data in a dictionary and then iterate over it while using `setattr` to set the attributes in `daily_stats`. In your dict the values could take either integers or lists (depending on whether they're a single value from `row` or multiple summed values). As such you can use a `try:... except:...` bloc...
Absolute value for column in Python
29,077,188
5
2015-03-16T12:46:39Z
29,077,254
8
2015-03-16T12:50:18Z
[ "python", "pandas", "calculated-columns" ]
How could I convert the values of column 'count' to absolute value? A summary of my dataframe this: ``` datetime count 0 2011-01-20 00:00:00 14.565996 1 2011-01-20 01:00:00 10.204177 2 2011-01-20 02:00:00 -1.261569 3 2011-01-20 03:00:00 1.938322 4 2011-01-20 04:00:00 1.938322 5 2011-01-20 0...
Use [`pandas.DataFrame.abs()`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.abs.html). ``` import pandas as pd df = pd.DataFrame(data={'count':[1, -1, 2, -2, 3, -3]}) df['count'] = df['count'].abs() print(df) count #0 1 #1 1 #2 2 #3 2 #4 3 #5 3 ```
Scrapy: 'str' object has no attribute 'iter'
29,081,330
6
2015-03-16T15:57:11Z
29,081,475
8
2015-03-16T16:03:42Z
[ "python", "scrapy", "scrapy-spider" ]
I added `restrict_xpaths` rules to my scrapy spider and now it immediately fails with: ``` 2015-03-16 15:46:53+0000 [tsr] ERROR: Spider error processing <GET http://www.thestudentroom.co.uk/forumdisplay.php?f=143> Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2...
The problem is that `restrict_xpaths` should **point to elements** - either the links directly or containers containing links, not attributes: ``` rules = [ Rule(LinkExtractor(allow='forumdisplay\.php\?f=143\&page=\d', restrict_xpaths="//li[@class='pager-page_numbers']/a")), Rule(LinkEx...
Python time.sleep() vs event.wait()
29,082,268
22
2015-03-16T16:40:06Z
29,082,411
24
2015-03-16T16:47:14Z
[ "python", "multithreading", "sleep" ]
I want to perform an action at a regular interval in my multi-threaded Python application. I have seen two different ways of doing it ``` exit = False def thread_func(): while not exit: action() time.sleep(DELAY) ``` or ``` exit_flag = threading.Event() def thread_func(): while not exit_flag....
Using `exit_flag.wait(timeout=DELAY)` will be more responsive, because you'll break out of the while loop instantly when `exit_flag` is set. With `time.sleep`, even after the event is set, you're going to wait around in the `time.sleep` call until you've slept for `DELAY` seconds. In terms of implementation, Python 2....
Heroku Sporadic High Response Time
29,088,113
11
2015-03-16T22:28:17Z
32,465,651
8
2015-09-08T19:23:13Z
[ "python", "django", "heroku", "gunicorn", "newrelic" ]
This is very specific, but I will try to be brief: We are running a **Django** app on **Heroku**. Three servers: 1. test (1 web, 1 celery dyno) 2. training (1 web, 1 celery dyno) 3. prod (2 web, 1 celery dyno). We are using **Gunicorn** with **gevents** and **4 workers on each dyno**. We are **experiencing sporadic...
I have been in contact with the Heroku support team over the past 6 months. It has been a long period of narrowing down through trial/error, but we have identified the problem. I eventually noticed these high response times corresponded with a sudden memory swap, and even though I was paying for a Standard Dyno (which...
Biased coin flipping?
29,090,525
2
2015-03-17T02:52:53Z
29,090,539
8
2015-03-17T02:54:55Z
[ "python" ]
What is the simplest (does not have to be fastest) way to do a biased random choice between True and False in Python? By "biased", I mean where either True or False is more probable based on a probability I set.
It's pretty easy **and** fast: ``` import random def biased_flip(prob_true=0.5): return random.random() < prob_true ``` Of course if you just call `biased_flip()` you'll get `True` and `False` with 50% probability each, but e.g `biased_flip(0.8)` will give you about eight `True`s for each `False` in the long run...
how to get data from 'ImmutableMultiDict' in flask
29,091,070
3
2015-03-17T03:59:05Z
29,091,380
8
2015-03-17T04:39:25Z
[ "jquery", "python", "ajax", "flask" ]
I am learning how to use ajax and Flask ,so what I do is I send a ajax request and I receive the data as `post` request in my python file `My html file contains this code` ``` var data = {"name":"John Doe","age":"21"}; $.ajax({ url:'/post/data', datatype : "json", contentType: "application/json; charset=utf-8",...
You don't actually need to get data from an `ImmutableMultiDict`. There are a couple of errors in what you have that are preventing you from just pulling the response as json data. First off, you have to slightly tweak the parameters of your ajax call. You should add in the call type as a `POST`. Furthermore, `datatype...
ImportError: cannot import name 'webdriver'
29,092,970
5
2015-03-17T06:52:03Z
32,824,053
8
2015-09-28T13:18:37Z
[ "python" ]
I am newbie for selenium python. I have installed pyhton, pip etc.. I am trying to run the below code but it is showing error ImportError: cannot import name 'webdriver' ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") ...
if your file name is **selenium** change it to something else and delete .pyc files too.
SSL InsecurePlatform error when using Requests package
29,099,404
170
2015-03-17T12:43:34Z
29,099,439
271
2015-03-17T12:45:11Z
[ "python", "ssl", "python-requests" ]
Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy. I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with `Requests` I get an `InsecurePlatform` exception. The error ment...
Use the somewhat hidden **security** feature: `pip install 'requests[security]'` or `pip install pyOpenSSL ndg-httpsclient pyasn1` Both commands install following extra packages: * pyOpenSSL * ndg-httpsclient * pyasn1 Please note that this is not required for [python-2.7.9+](http://docs.python-requests.org/en/maste...
SSL InsecurePlatform error when using Requests package
29,099,404
170
2015-03-17T12:43:34Z
29,154,960
8
2015-03-19T21:02:12Z
[ "python", "ssl", "python-requests" ]
Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy. I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with `Requests` I get an `InsecurePlatform` exception. The error ment...
If you are **not able to upgrade** your Python version to 2.7.9, and want to suppress warnings, you can **downgrade your 'requests'** version to 2.5.3: ``` sudo pip install requests==2.5.3 ``` About version: <http://fossies.org/diffs/requests/2.5.3_vs_2.6.0/requests/packages/urllib3/util/ssl_.py-diff.html>
SSL InsecurePlatform error when using Requests package
29,099,404
170
2015-03-17T12:43:34Z
29,501,899
51
2015-04-07T21:44:18Z
[ "python", "ssl", "python-requests" ]
Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy. I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with `Requests` I get an `InsecurePlatform` exception. The error ment...
Requests 2.6 introduced this warning for users of python prior to 2.7.9 with only stock SSL modules available. Assuming you can't upgrade to a newer version of python, this will install more up-to-date python SSL libraries: ``` pip install --upgrade ndg-httpsclient ``` HOWEVER, this may fail on some systems without ...
SSL InsecurePlatform error when using Requests package
29,099,404
170
2015-03-17T12:43:34Z
31,946,125
12
2015-08-11T15:36:36Z
[ "python", "ssl", "python-requests" ]
Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy. I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with `Requests` I get an `InsecurePlatform` exception. The error ment...
I don't use this in production, just some test runners. And to reiterate the [urllib3 documentation](https://urllib3.readthedocs.org/en/latest/security.html#insecurerequestwarning) > If you know what you are doing and would like to disable this and > other warnings ``` import requests.packages.urllib3 requests.packag...
Equivalent im2double function in OpenCV Python
29,100,722
4
2015-03-17T13:46:26Z
29,104,511
12
2015-03-17T16:26:52Z
[ "python", "image", "matlab", "opencv", "image-processing" ]
In MATLAB, the following code reads in an image and normalizes the values between `[0.0,1.0]`: ``` img=im2double(imread('image.jpg')) ``` I would like to perform this in OpenCV Python. Is there an equivalent function to do this? I have tried the following code, but its asking for source `IplImage`. Also, what would ...
I would avoid using the old `cv` module and use `cv2` instead as these use `numpy` arrays. `numpy` arrays operate very similar to arrays and matrices in MATLAB. In any case, [`im2double`](http://www.mathworks.com/help/matlab/ref/im2double.html) in MATLAB normalizes an image such that the minimum intensity is 0 and the...
Updating a dataframe column in spark
29,109,916
24
2015-03-17T21:19:04Z
29,110,394
10
2015-03-17T21:51:45Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Looking at the new spark dataframe api, it is unclear whether it is possible to modify dataframe columns. How would I go about changing a value in row `x` column `y` of a dataframe? In `pandas` this would be `df.ix[x,y] = new_value`
`DataFrames` are based on RDDs. RDDs are immutable structures and do not allow updating elements on-site. To change values, you will need to create a new DataFrame by transforming the original one either using the SQL-like DSL or RDD operations like `map`. A highly recommended slide deck: [Introducing DataFrames in Sp...
Updating a dataframe column in spark
29,109,916
24
2015-03-17T21:19:04Z
29,257,220
29
2015-03-25T13:35:02Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Looking at the new spark dataframe api, it is unclear whether it is possible to modify dataframe columns. How would I go about changing a value in row `x` column `y` of a dataframe? In `pandas` this would be `df.ix[x,y] = new_value`
While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a `UserDefinedFunction` implementing the operation to apply and then selectively apply that function to the targeted column only. In Python: ``` from pyspark.sql.function...
Updating a dataframe column in spark
29,109,916
24
2015-03-17T21:19:04Z
33,599,150
10
2015-11-08T21:19:36Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Looking at the new spark dataframe api, it is unclear whether it is possible to modify dataframe columns. How would I go about changing a value in row `x` column `y` of a dataframe? In `pandas` this would be `df.ix[x,y] = new_value`
Just as [maasg](http://stackoverflow.com/users/764040/maasg) says you can create a new DataFrame from the result of a map applied to the old DataFrame. An example for a given DataFrame `df` with two rows: ``` val newDf = sqlContext.createDataFrame(df.map(row => Row(row.getInt(0) + SOMETHING, applySomeDef(row.getAs[...
Python returns length of 2 for single Unicode character string
29,109,944
3
2015-03-17T21:21:01Z
29,109,996
8
2015-03-17T21:24:24Z
[ "python", "python-2.7", "unicode", "python-unicode" ]
In Python 2.7: ``` In [2]: utf8_str = '\xf0\x9f\x91\x8d' In [3]: print(utf8_str) 👍 In [4]: unicode_str = utf8_str.decode('utf-8') In [5]: print(unicode_str) 👍 In [6]: unicode_str Out[6]: u'\U0001f44d' In [7]: len(unicode_str) Out[7]: 2 ``` Since `unicode_str` only contains a single unicode code point (0x00...
Your Python binary was compiled with UCS-2 support (a *narrow* build) and internally anything outside of the BMP (Basic Multilingual Plane) is represented using a [surrogate pair](https://en.wikipedia.org/wiki/UTF-16#U.2B10000_to_U.2B10FFFF). That means such codepoints show up as 2 characters when asking for the lengt...
How to install multiple ipython 3.0 kernels (python 2.7, python 3.4, etc...) with anaconda under linux?
29,118,729
7
2015-03-18T09:47:46Z
29,130,363
7
2015-03-18T18:50:56Z
[ "python", "ipython", "ipython-notebook", "anaconda", "jupyter" ]
Ipython 3.0 (Jupyter) allows to choose which kernel (python 2.7, python 3.4, etc...) to use when creating a new ipython notebook. How can I install multiple ipython notebook kernels under Continuum Anaconda?
You'll want to make separate conda environments for Python 2 and 3 (see info elsewhere on how to do this), with IPython installed in both of them. Then, in each environment, run: ``` ipython kernelspec install-self ``` This registers that kernel so IPython can see it from outside the environment. If you want more ke...
Removing NaNs in numpy arrays
29,120,626
3
2015-03-18T11:17:46Z
29,120,699
7
2015-03-18T11:21:40Z
[ "python", "arrays", "numpy", null ]
I have two numpy arrays that contains NaNs: ``` A = np.array([np.nan, 2, np.nan, 3, 4]) B = np.array([ 1 , 2, 3 , 4, np.nan]) ``` are there any smart way using numpy to remove the NaNs in both arrays, and also remove whats on the corresponding index in the other list? Making it look like this: ...
What you could do is add the 2 arrays together this will overwrite with NaN values where they are none, then use this to generate a boolean mask index and then use the index to index into your original numpy arrays: ``` In [193]: A = np.array([np.nan, 2, np.nan, 3, 4]) B = np.array([ 1 , 2, 3 , 4...
Removing NaNs in numpy arrays
29,120,626
3
2015-03-18T11:17:46Z
29,120,720
7
2015-03-18T11:22:23Z
[ "python", "arrays", "numpy", null ]
I have two numpy arrays that contains NaNs: ``` A = np.array([np.nan, 2, np.nan, 3, 4]) B = np.array([ 1 , 2, 3 , 4, np.nan]) ``` are there any smart way using numpy to remove the NaNs in both arrays, and also remove whats on the corresponding index in the other list? Making it look like this: ...
`A[~(np.isnan(A) | np.isnan(B))]` `B[~(np.isnan(A) | np.isnan(B))]`
Calling a coroutine from asyncio.Protocol.data_received
29,126,340
5
2015-03-18T15:39:08Z
29,126,866
7
2015-03-18T16:00:13Z
[ "python", "python-asyncio" ]
This is similar to [Calling coroutines in asyncio.Protocol.data\_received](http://stackoverflow.com/questions/20746619/calling-coroutines-in-asyncio-protocol-data-received) but I think it warrants a new question. I have a simple server set up like this ``` loop.create_unix_server(lambda: protocol, path=serverSocket) ...
You need to add your coroutine to the event loop, and then use [`Future.add_done_callback`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Future.add_done_callback) to handle the result when the coroutine completes: ``` @asyncio.coroutine def go(self): return(yield from asyncio.sleep(3, result = b'dat...
Most efficient way to loop finding items not in a list in python
29,126,387
4
2015-03-18T15:40:45Z
29,126,502
13
2015-03-18T15:46:04Z
[ "python", "list", "for-loop" ]
I'm trying to improve the efficiency of a script that takes lists and counts how many items aren't in another 'master' list (`list_of_all_items`). It feels like there might be a more efficient way of doing this, perhaps through combining the querying somehow? ``` purple_count, brown_count, blue_count = 0, 0, 0 for i...
Use *sets* so you don't have to keep looping: ``` set_of_all_items = set(list_of_all_items) purple_count = len(set(list_of_purple_items).difference(list_of_all_items)) brown_count = len(set(list_of_brown_items).difference(list_of_all_items)) blue_count = len(set(list_of_blue_items).difference(list_of_all_items)) ``` ...
Trying to write a cPickle object but get a 'write' attribute type error
29,127,593
6
2015-03-18T16:33:01Z
29,127,668
8
2015-03-18T16:36:14Z
[ "python", "pickle" ]
When trying to apply some code I found on the internet in iPython, it's coming up with an error: ``` TypeError Traceback (most recent call last) <ipython-input-4-36ec95de9a5d> in <module>() 13 all[i] = r.json() 14 ---> 15 cPickle.dump(all, outfile) TypeError: argumen...
The second argument to `cPickle.dump()` must be a *file object*. You passed in a string containing a filename instead. You need to use the `open()` function to open a file object for that filename, then pass the file object to `cPickle`: ``` with open(outfile, 'wb') as pickle_file: cPickle.dump(all, pickle_file) ...
Django Rest Framework 3.1 breaks pagination.PaginationSerializer
29,128,225
16
2015-03-18T17:00:57Z
29,135,818
9
2015-03-19T01:38:53Z
[ "python", "django", "pagination", "django-rest-framework", "django-pagination" ]
I just updated to Django Rest Framework 3.1 and it seems that all hell broke loose. in my `serializers.py` I was having the following code: ``` class TaskSerializer(serializers.ModelSerializer): class Meta: model = task exclude = ('key', ...) class PaginatedTaskSerializer(pagination.PaginationSerializer)...
I am not sure if this is the completely correct way to do it, but it works for my needs. It uses the Django Paginator and a custom serializer. Here is my View Class that retrieves the objects for serialization ``` class CourseListView(AuthView): def get(self, request, format=None): """ Returns a J...
Django Rest Framework 3.1 breaks pagination.PaginationSerializer
29,128,225
16
2015-03-18T17:00:57Z
29,144,786
16
2015-03-19T12:36:53Z
[ "python", "django", "pagination", "django-rest-framework", "django-pagination" ]
I just updated to Django Rest Framework 3.1 and it seems that all hell broke loose. in my `serializers.py` I was having the following code: ``` class TaskSerializer(serializers.ModelSerializer): class Meta: model = task exclude = ('key', ...) class PaginatedTaskSerializer(pagination.PaginationSerializer)...
I think I figured it out (for the most part at least): What we should have used from the very beginning is this: Just use the built-in paginator and change your `views.py` to this: ``` from rest_framework.pagination import PageNumberPagination class CourseListView(AuthView): def get(self, request, format=None):...
Django form EmailField doesn't accept the css attribute
29,131,908
2
2015-03-18T20:20:24Z
29,136,743
8
2015-03-19T03:30:11Z
[ "python", "django", "django-forms", "django-templates" ]
I have a from containing some fields, but my `css` class applies to all the fileds except the `EmailField`. I've also tried `sender.widget.attrs.update({'class':"contatct-form"})` and it still doesn't work (just change the size of field). Does anybody knows what the problem is? as all of my searches were unsuccessful. ...
The problem you have probably is because you have not assigned any **widget** to your **EmailField()**, change to this (like @Todor said) should work: ``` ... sender = forms.EmailField( widget=forms.EmailInput(attrs={'class': 'contatct-form'}) ) ``` If this doesn't work for whatever reason (probably wrong css sty...
Python-OpenCV dilate and erode functions don't modify anything
29,132,164
5
2015-03-18T20:37:28Z
29,134,219
7
2015-03-18T22:54:40Z
[ "python", "opencv" ]
Given the code below, the cv2.dilate and cv2.erode functions in python return the same image I send to it. What am I doing wrong? I am using OpenCV3.0.0. and numpy1.9.0 on iPython 2.7 ``` im = np.zeros((100,100), dtype=np.uint8) im[50:,50:] = 255 dilated = cv2.dilate(im, (11,11)) print np.array_equal(im, dilated) ``` ...
The function requires a kernel, not a kernel size. So a correct function call would be below. ``` dilated = cv2.dilate(im, np.ones((11, 11))) ```
create ordered dict from list comprehension?
29,136,222
6
2015-03-19T02:31:31Z
29,136,283
7
2015-03-19T02:37:44Z
[ "python", "python-2.7", "dictionary" ]
[Here is a list comprehension](http://stackoverflow.com/a/29135851/156458): ``` L = [{k: d[k](v) for (k, v) in l.iteritems()} for l in L] ``` where * `L` is a list of ordered dictionaries (i.e. objects of collections.OrderedDict), where the dictionaries have the same set of keys. * `d` is another ordered dictionary,...
`collections.OrderedDict` is nothing but a dict, which remembers the order in which the elements are included in it. So you can create one with its constructor like this ``` [OrderedDict((k, d[k](v)) for (k, v) in l.iteritems()) for l in L] ```
Installing pygame module in anaconda mac
29,137,369
5
2015-03-19T04:44:59Z
32,027,798
10
2015-08-15T18:13:33Z
[ "python", "pygame", "anaconda" ]
I have [Anaconda](http://www.continuum.io/) installed on my mac. And it has messed with my pygame module. I tried following this [tutorial](http://programarcadegames.com/index.php?chapter=foreword&lang=en#section_0_1_2) and replacing `pip3 install pygame` with `conda install pygame`. I have tried `conda install pip` a...
After 2 days of messing around with macports and homebrew with no joy, the instructions [here](http://www.srmathias.com/?p=886) worked for me using Anaconda Python 2.7.10 on a mac. Echoing them here in case the linked site ever disappears! First open up terminal and enter these two lines: ``` ruby -e "$(curl -fsSL ht...
Calculating the number of specific consecutive equal values in a vectorized way in pandas
29,142,487
6
2015-03-19T10:46:15Z
29,143,354
7
2015-03-19T11:26:13Z
[ "python", "pandas", "vectorization" ]
Let's say we have the following pandas DataFrame: ``` In [1]: import pandas as pd import numpy as np df = pd.DataFrame([0, 1, 0, 0, 1, 1, 0, 1, 1, 1], columns=['in']) df Out[1]: in 0 0 1 1 2 0 3 0 4 1 5 1 6 0 7 1 8 1 9 1 ``` How to count the number of consecutive ones **in a vectorized way** ...
You can do something like this(credit goes to: [how to emulate itertools.groupby with a series/dataframe?](https://groups.google.com/d/msg/pydata/V3p37GRxgNY/Ca3mmXikYUwJ)): ``` >>> df['in'].groupby((df['in'] != df['in'].shift()).cumsum()).cumsum() 0 0 1 1 2 0 3 0 4 1 5 2 6 0 7 1 8 2 9 3 ...
How to fix pylint logging-not-lazy?
29,147,442
16
2015-03-19T14:37:26Z
29,371,584
15
2015-03-31T14:50:12Z
[ "python", "pylint" ]
I am using prospector and there are many errors: > Line: 31 > pylint: logging-not-lazy / Specify string format arguments as logging function parameters (col 16) Line: 42 > pylint: logging-not-lazy / Specify string format arguments as logging function parameters (col 12) My code is: ``` logging.debug("detect mimetype...
This mean, that you should rewrite your code as: ``` logging.debug("detect mimetypes faild because %s", e) ``` Acording to <https://docs.python.org/2/library/logging.html> **Logger.debug(msg, \*args, \*\*kwargs)** ... Logs a message with level DEBUG on this logger. *The `msg` is the message format string, and the `...
What is the difference between mock.patch.object(... and mock.patch(
29,152,170
10
2015-03-19T18:18:55Z
29,152,283
14
2015-03-19T18:26:23Z
[ "python", "unit-testing", "mocking" ]
I am trying to understand the difference between these two approaches of mocking a method. Could someone please help distinguish them? For this example, I use the passlib library. ``` from passlib.context import CryptContext from unittest import mock with mock.patch.object(CryptContext, 'verify', return_value=True) a...
You already discovered the difference; `mock.patch()` takes a string which will be resolved to an object *when applying the patch*, `mock.patch.object()` takes a direct reference. This means that `mock.patch()` doesn't require that you import the object before patching, while `mock.patch.object()` does require that yo...
Tkinter understanding mainloop
29,158,220
8
2015-03-20T02:09:18Z
29,158,947
12
2015-03-20T03:31:34Z
[ "python", "tkinter" ]
Till now, I used to end my Tkiter programs with: `tk.mainloop()`, or nothing would show up! See example: ``` from Tkinter import * import random import time tk = Tk() tk.title = "Game" tk.resizable(0,0) tk.wm_attributes("-topmost", 1) canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) canvas.pack...
`tk.mainloop()` *blocks*. What that means is that execution of your *python* program halts there. You can see that by writing: ``` while 1: ball.draw() tk.mainloop() print "hello" #NEW CODE time.sleep(0.01) ``` You will never see the output from the print statement. Because there is no loop, the bal...
What's the difference between "update" and "update_idletasks"?
29,158,811
5
2015-03-20T03:18:16Z
29,159,152
8
2015-03-20T03:56:22Z
[ "python", "python-3.x", "tkinter" ]
From the `effbot.org` documentation, we have the following about the [`update`](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.update-method) function: > Processes all pending events, calls event callbacks, completes any > pending geometry management, redraws widgets as necessary, and calls > all pending idle...
> The only difference I see is that update processes all pending events > and calls event callbacks. That's why we should not call update from > within an even callback, I suppose. You are correct on both accounts. What are pending events? Events scheduled with `after`, mostly. And, as you also mentioned in your ques...
Python: Iterate over each item in nested-list-of-lists and replace specific items
29,159,657
9
2015-03-20T04:52:54Z
29,159,830
7
2015-03-20T05:11:17Z
[ "python", "python-2.7", "nested-lists" ]
I am a beginner in python. I want to know if there is any in-built function or other way so I can achieve below in python 2.7: Find all **-letter** in list and sublist and replace it with **['not',letter]** Eg: Find all items in below list starting with - and replace them with ['not',letter] ``` Input : ['and', ['or...
Try a bit of recursion: ``` def change(lol): for index,item in enumerate(lol): if isinstance(item, list): change(item) elif item.startswith('-'): lol[index] = ['not',item.split('-')[1]] return lol ``` In action: ``` In [24]: change(['and', ['or', '-S', 'Q'], ['or', '-S...
Error in python-igraph 'module' object has no attribute 'Graph'
29,159,881
6
2015-03-20T05:16:08Z
29,160,832
8
2015-03-20T06:39:52Z
[ "python", "import", "pycharm", "igraph" ]
I have installed igraph on Pycharm for Windows. ``` import igraph ``` yields no errors. ``` import igraph print igraph.__version__ ``` yields: 0.1.5. ``` import igraph dir(igraph) ``` yields nothing... ``` import igraph g = igraph.Graph(1) ``` yields: > Traceback (most recent call last): > File "C:/Users/Mar...
There are two `igraph` libraries on PyPI, [`igraph`](https://pypi.python.org/pypi/igraph) and [`python-igraph`](https://pypi.python.org/pypi/python-igraph). You have `igraph` installed, which is the wrong one. Uninstall it using: ``` pip uninstall igraph ``` As you are on Windows you probably need a pre-compiled dis...
What is the difference between .one() and .first()
29,161,730
3
2015-03-20T07:45:39Z
29,161,740
7
2015-03-20T07:46:32Z
[ "python", "sqlalchemy" ]
What is the difference between .one() and .first() in SQLAlchemy
`Query.one()` requires that there is only *one* result in the result set; it is an error if the database returns 0 or 2 or more results and an exception will be raised. `Query.first()` returns the first of a potentially larger result set, or `None` if there were no results. No exception will be raised. From the docum...
How do you add error bars to Bokeh plots in python?
29,166,353
7
2015-03-20T12:19:39Z
30,538,908
9
2015-05-29T20:55:51Z
[ "python", "plot", "bokeh" ]
I have successfully plotted several data sets and fitted functions using Bokeh however I really need to add error bars to the graphs, how might I go about doing this?
Maybe its a little late but I wanted to do this today too. It's a shame that bokeh does not offer this function by itself. ``` import numpy as np from bokeh.plotting import figure, show, output_file # some pseudo data xs = np.linspace(0, 2*np.pi, 25) yerrs = np.random.uniform(0.1, 0.3, xs.shape) ys = np.sin(xs) + np...
Super init vs. parent.__init__
29,173,299
11
2015-03-20T18:20:09Z
29,173,605
13
2015-03-20T18:38:27Z
[ "python", "python-2.7", "inheritance" ]
We're following a Python class in a book I'm involved with that does not use super for initialization from a inherited class. I'm having trouble giving a clear, straightforward description of the differences between these two cases: ``` class Parent(object): def __init__(self): .... class Child(Parent)...
The purpose of super is to handle inheritance diamonds. If the class inheritance structure uses only single-inheritance, then using super() will result in the same calls as explicit calls to the "parent" class. Consider this inheritance diamond: ``` class A(object): def __init__(self): print('Running A.__...
How do you kill Futures once they have started?
29,177,490
11
2015-03-20T23:42:06Z
29,237,343
10
2015-03-24T15:58:33Z
[ "python", "multithreading", "concurrent.futures" ]
I am using the new [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html) module (which also has a Python 2 backport) to do some simple multithreaded I/O. I am having trouble understanding how to cleanly kill tasks started using this module. Check out the following Python 2/3 script, which r...
It's kind of painful. Essentially, your worker threads have to be finished before your main thread can exit. You cannot exit unless they do. The typical workaround is to have some global state, that each thread can check to determine if they should do more work or not. Here's the [quote](https://hg.python.org/cpython/...
How can I add nothing to the list in list comprehension?
29,179,881
2
2015-03-21T06:22:15Z
29,179,888
7
2015-03-21T06:23:49Z
[ "python", "list", "list-comprehension" ]
I am writing a list comprehension in Python: ``` [2 * x if x > 2 else add_nothing_to_list for x in some_list] ``` I need the "add\_nothing\_to\_list" part (the else part of the logic) to literally be nothing. Does Python have a way to do this? In particular, is there a way to say `a.append(nothing)` which would leav...
Just move the condition to the last ``` [2 * x for x in some_list if x > 2] ``` Quoting the [List Comprehension documentation](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions), > **A list comprehension consists of brackets containing an expression followed by a `for` clause, then zero or m...
Python: Check second variable if first variable is True?
29,180,754
4
2015-03-21T08:33:29Z
29,180,768
12
2015-03-21T08:36:12Z
[ "python", "if-statement", "python-3.x" ]
I have a script that checks bools through if statements and then executes code. What I am trying to do is make it so that: ``` if variable a is True, check if b is True and execute code if variable a is False, execute the same code mentioned before ``` A simplified version of what I currently have is this: ``` if a:...
``` if not a or (a and b): print('foo') ``` Let's talk this step by step: When is `print('foo')` executed? 1. When `a` and `b` are both `True`. 2. When `else` is executed, what is `else`? The opposite of the previous `if` so `not a`. Finally you wish to display `'foo'` in one case or the other. **EDIT:** Altern...
Why does appending a list to itself show [...] when printed?
29,182,841
3
2015-03-21T12:42:43Z
29,182,864
9
2015-03-21T12:44:53Z
[ "python", "list", "python-2.7", "python-3.x" ]
When I appended the list in itself using the following code. ``` a = [1, 2, 3, 4] print a a.append(a) print a ``` I was expecting the output to be... ``` [1, 2, 3, 4] [1, 2, 3, 4, [1, 2, 3, 4]] ``` But it was something like this... ``` [1, 2, 3, 4] [1, 2, 3, 4, [...]] ``` **WHY?**
You are adding `a` to `a` itself. The second element of `a` is `a` only. So, if it tries to print `a`, as you wanted * it would print the first element `[1, 2, 3, 4]` * it would print the second element, which is actually `a` + it would print the first element `[1, 2, 3, 4]` + it would print the second element, w...
Why is this Haskell program so much slower than an equivalent Python one?
29,186,541
46
2015-03-21T18:38:37Z
29,186,861
26
2015-03-21T19:08:13Z
[ "python", "performance", "haskell", "io" ]
As part of a programming challenge, I need to read, from stdin, a sequence of space-separated integers (*on a single line*), and print the sum of those integers to stdout. The sequence in question can contain as many as 10,000,000 integers. I have two solutions for this: one written in Haskell (`foo.hs`), and another,...
**Read is slow** Fast read, [from this answer](http://stackoverflow.com/questions/10357663/python-faster-than-compiled-haskell/10358198#10358198), will bring you down to 5.5 seconds. ``` import Numeric fastRead :: String -> Int fastRead s = case readDec s of [(n, "")] -> n ``` **Strings are Linked Lists** In Haskel...
Why is this Haskell program so much slower than an equivalent Python one?
29,186,541
46
2015-03-21T18:38:37Z
29,186,898
62
2015-03-21T19:12:48Z
[ "python", "performance", "haskell", "io" ]
As part of a programming challenge, I need to read, from stdin, a sequence of space-separated integers (*on a single line*), and print the sum of those integers to stdout. The sequence in question can contain as many as 10,000,000 integers. I have two solutions for this: one written in Haskell (`foo.hs`), and another,...
`read` is slow. For bulk parsing, use `bytestring` or `text` primitives, or `attoparsec`. I did some benchmarking. Your original version ran in **23,9** secs on my computer. The version below ran in **0.35** secs: ``` import qualified Data.ByteString.Char8 as B import Control.Applicative import Data.Maybe import Data...
Attribute Error trying to run Gmail API quickstart in Python
29,190,604
14
2015-03-22T03:24:30Z
29,237,551
24
2015-03-24T16:08:21Z
[ "python", "oauth-2.0", "gmail-api" ]
It looks like there might be a version mismatch problem here. How should I go about fixing it? I've trying updating six with pip, but that doesn't do anything. Here's the error I see: ``` Traceback (most recent call last): File "./quickstart.py", line 27, in <module> credentials = run(flow, STORAGE, http=http)...
I ran into a very similar problem, albeit using a completely different API (compute engine). I ended up rolling back the google api client to the previous version - 1.3.2 - as opposed to the latest - 1.4.0. To do this, I ran: ``` sudo pip install -I google-api-python-client==1.3.2 ``` And was then able to run my code...
Attribute Error trying to run Gmail API quickstart in Python
29,190,604
14
2015-03-22T03:24:30Z
29,529,618
11
2015-04-09T04:11:55Z
[ "python", "oauth-2.0", "gmail-api" ]
It looks like there might be a version mismatch problem here. How should I go about fixing it? I've trying updating six with pip, but that doesn't do anything. Here's the error I see: ``` Traceback (most recent call last): File "./quickstart.py", line 27, in <module> credentials = run(flow, STORAGE, http=http)...
Figured out the source of the problem -- the pre-installed OSX version of six (1.4.1) is the one loaded because its location comes first on your python path. The version required by gmail (1.6.1) is therefore shielded and therefore never imported. A quick fix is just to prepend the 1.6.1 installation directory to you...
Why does this python re only capture one digit?
29,190,982
2
2015-03-22T04:24:28Z
29,191,040
7
2015-03-22T04:35:58Z
[ "python", "regex" ]
I'm trying to use python RE module to capture specific digits of strings like `'03'` in `' video [720P] [DHR] _sp03.mp4 '`. And what confused me is : when I use `'.*\D+(\d+).*mp4'`, it succeed to capture both the two digits `03` , but when I use `'.*\D*(\d+).*mp4'`, it only captured the rear digit `3`. I know python...
What makes the difference is not the `\D+` but the first `.*` Now in regex `.*` is greedy and tries to match as much as characters as possible as it can So when you write ``` .*\D*(\d+).*mp4 ``` The `.*` will match as much as it can. That is if we try to break it down, it would look like ``` video [720P] [DHR] _sp...
Django 1.8 RC1: ProgrammingError when creating database tables
29,194,575
12
2015-03-22T12:49:39Z
29,398,908
15
2015-04-01T19:11:38Z
[ "python", "django", "database", "migrate" ]
I'm using AbstractBaseUser for my user models in various projects. Updating to Django 1.8 RC1 works smoothly and I can run the migrate management command. However, when trying to create a fresh database table layout from scratch, I get the following error: ``` python manage.py migrate >>> ... >>> ... >>> django.db.uti...
To copy the answer I got from the Django ticket mentioned above: Before calling "python manage.py migrate" to create the database layout, one needs to create a migration for the app that contains the custom user class: ``` python manage.py makemigrations appname ``` This creates a migration file within the app direct...
pylint duplicate code false positive
29,206,482
8
2015-03-23T09:09:27Z
30,007,053
8
2015-05-02T20:21:24Z
[ "python", "pylint" ]
I have this code in (many) of my Python files for a project. ``` from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from pprint import pformat ``` Pylint complains that: ``` ==ook:2 ==eek:2 from __future__ import absolu...
# Pylint Similarities Config Try changing the `ignore-imports` in the [similarities](http://docs.pylint.org/features.html#similarities-checker) section of your [`pylintrc` config file](https://docs.pylint.org/tutorial.html#the-next-step). Default pylintrc: ``` [SIMILARITIES] # Minimum lines number of a similarity. ...
Difference between data type 'datetime64[ns]' and '<M8[ns]'?
29,206,612
7
2015-03-23T09:17:10Z
29,218,694
7
2015-03-23T19:25:43Z
[ "python", "numpy", "pandas", "datetime64" ]
I have created a TimeSeries in pandas: ``` In [346]: from datetime import datetime In [347]: dates = [datetime(2011, 1, 2), datetime(2011, 1, 5), datetime(2011, 1, 7), .....: datetime(2011, 1, 8), datetime(2011, 1, 10), datetime(2011, 1, 12)] In [348]: ts = Series(np.random.randn(6), index=dates) In [349]: ts Ou...
`datetime64[ns]` is a general dtype, while `<M8[ns]` is a specific dtype. General dtypes map to specific dtypes, but may be different from one installation of NumPy to the next. On a machine whose byte order is little endian, there is no difference between `np.dtype('datetime64[ns]')` and `np.dtype('<M8[ns]')`: ``` I...
TypeError: Cannot create a consistent method resolution order (MRO)
29,214,888
6
2015-03-23T16:04:28Z
29,214,925
18
2015-03-23T16:06:00Z
[ "python", "inheritance", "typeerror", "method-resolution-order" ]
This is the code which I plan to use for my game. But it complains for an MRO error. I don't know why. Can someone explains for me? Many thanks. ``` class Player: pass class Enemy(Player): pass class GameObject(Player, Enemy): pass g = GameObject() ```
Your `GameObject` is inheriting from `Player` **and** `Enemy`. Because `Enemy` *already* inherits from `Player` Python now cannot determine what class to look methods up on first; either `Player`, or on `Enemy`, which would override things defined in `Player`. You don't need to name all base classes of `Enemy` here; j...
How does Python 2.7 compare items inside a list
29,215,418
7
2015-03-23T16:29:53Z
29,215,682
13
2015-03-23T16:42:53Z
[ "python", "python-2.7" ]
I came across this interesting example today ``` class TestableEq(object): def __init__(self): self.eq_run = False def __eq__(self, other): self.eq_run = True if isinstance(other, TestableEq): other.eq_run = True return self is other ``` --- ``` >>> eq = TestableEq...
CPython's underlying implementation will skip the equality check (`==`) for items in a list if items are identical (`is`). CPython uses this as an optimization assuming identity implies equality. This is documented in [PyObject\_RichCompareBool](https://docs.python.org/2.7/c-api/object.html#c.PyObject_RichCompareBool...
How does Python 2.7 compare items inside a list
29,215,418
7
2015-03-23T16:29:53Z
29,216,101
10
2015-03-23T17:06:14Z
[ "python", "python-2.7" ]
I came across this interesting example today ``` class TestableEq(object): def __init__(self): self.eq_run = False def __eq__(self, other): self.eq_run = True if isinstance(other, TestableEq): other.eq_run = True return self is other ``` --- ``` >>> eq = TestableEq...
Python's testing of equality for sequences goes as follows: ``` Lists identical? / \ Y N / \ Equal Same length? / \ Y N ...
Socket error: Address already in use
29,217,502
2
2015-03-23T18:16:49Z
29,217,540
8
2015-03-23T18:19:04Z
[ "python", "sockets", "cherrypy" ]
I have a CherryPy script that I frequently run to start a server. Today I was having to start and stop it a few times to fix some bugs in a config file, and I guess the socket didn't close all the way because when I tried to start it up again I got this issue: ``` [23/Mar/2015:14:08:00] ENGINE Listening for SIGHUP. [2...
You can try the following ``` from socket import * sock=socket() sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # then bind ``` From the docs: > The SO\_REUSEADDR flag tells the kernel to reuse a local socket in TIME\_WAIT state, without waiting for its natural timeout to expire. Here's the complete explanation: > ...
Why does this solve the 'no $DISPLAY environment' issue with matplotlib?
29,217,543
5
2015-03-23T18:19:17Z
29,218,294
8
2015-03-23T19:02:05Z
[ "python", "matplotlib", "x11" ]
When running a code that uses the `matplotlib` library in my desktop PC, I have no issues using the line: ``` import matplotlib.pyplot as plt ``` far down the code, which is where I actually use the plotting functions. If I run the code in a server though it will only work if I import `matplotlib` *before*, and forc...
X11 follows a client/server model, where the X server accepts requests for graphical output from client applications (e.g. interactive matplotlib sessions), and sends back user input from the keyboard, mouse etc. In order for this model to work, client applications need to know which X server to send their requests to....
What is the best way to remove a dictionary item by value in python?
29,218,750
4
2015-03-23T19:28:57Z
29,218,792
7
2015-03-23T19:31:32Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
I wonder if there is *simple* way to remove *one* or *more* dictionary element(s) from a python dictionary *by value*. We have a dictionary called `myDict`: ``` myDict = {1:"egg", "Answer":42, 8:14, "foo":42} ``` and want to *remove* all items which *values* are equal to `42`. Implementation suggestion: 1. Get a l...
You can use a simple `dict` comprehension: ``` myDict = {key:val for key, val in myDict.items() if val != 42} ``` As such: ``` >>> {key:val for key, val in myDict.items() if val != 42} {8: 14, 1: 'egg'} ```
Updating Anaconda's root Python to newer minor version on Windows does nothing
29,220,236
10
2015-03-23T20:57:32Z
29,238,416
11
2015-03-24T16:49:13Z
[ "python", "windows", "upgrade", "anaconda" ]
I have an Anaconda (not miniconda) Python 2.7 install on Windows. I would like to update the version of Python installed to the latest minor version (2.7.9), which I see is available in the channels that `conda` is configured to use. However, typing `conda update python` basically says: ``` # All requested packages al...
You are right that Windows won't let conda update Python in the root environment. The only option is to create a new environment with `conda create`. Otherwise, for now, you will have to reinstall Anaconda to update the root environment Python. We are working on a way to update Python in the root environment, but it is...
Can sphinx napoleon document function returning multiple arguments?
29,221,551
5
2015-03-23T22:21:35Z
29,343,326
8
2015-03-30T10:01:57Z
[ "python", "python-sphinx", "documentation-generation" ]
I am trying to use the Google code style to document a function that I then use sphinx with the napoleon extension to create documentation for. The function is unusual in that is returns two arguments. I don't think napoleon handles this. If so, could someone tell me how they handle it? ``` def foo(a): '''one line sum...
Python only returns a single object. If you call ``` serv,msg = foo(myinput) ``` Then you are explicitly expanding the expression\_list tuple which is generated when the function returns with this code ``` return servers,msg ``` You docstring should read some thing like this (with the Napoleon Google Style) ``` ""...
Is there a way to have a conditional requirements.txt file for my Python application based on platform?
29,222,269
5
2015-03-23T23:22:02Z
35,614,580
14
2016-02-24T22:33:48Z
[ "python", "pip" ]
I have a python application that I wrote to be compatible with both, Linux and Windows platforms. However there is one problem... One of the python packages I need for Windows is not compatible with Linux. Fortunately there is another package that provides the same functionality on Linux. All other dependencies are com...
You can add certain conditional requirements after a semi-colon particularly useful for sys\_platform and python\_version. Examples: ``` atomac==1.1.0; sys_platform == 'darwin' futures>=3.0.5; python_version < '3.0' futures>=3.0.5; python_version == '2.6' or python_version=='2.7' ``` Apparently you can also exclude ...
What is the Spark DataFrame method `toPandas` actually doing?
29,226,210
11
2015-03-24T06:22:11Z
29,233,999
16
2015-03-24T13:31:58Z
[ "python", "pandas", "apache-spark", "pyspark" ]
I'm a beginner of Spark-DataFrame API. I use this code to load csv tab-separated into Spark Dataframe ``` lines = sc.textFile('tail5.csv') parts = lines.map(lambda l : l.strip().split('\t')) fnames = *some name list* schemaData = StructType([StructField(fname, StringType(), True) for fname in fnames]) ddf = sqlContex...
Using spark to read in a CSV file to `pandas` is quite a roundabout method for achieving the end goal of reading a CSV file into memory. It seems like you might be misunderstanding the use cases of the technologies in play here. Spark is for distributed computing (though it can be used locally). It's generally far to...
cycle through multiple list using itertools.cycle()
29,226,375
13
2015-03-24T06:37:29Z
29,226,427
9
2015-03-24T06:41:31Z
[ "python", "itertools" ]
I have a list of servers. Every server has a list of name on it. example: ``` server1 = ['a','b','c'] server2 = ['d','e','f'] server3 = ['g','h','i'] ``` I want to iterate per server name not per server. For example after picking `'a'` in `server1`, move to `'d'` (not `'b'`) and so on. If I'm going to use `itertools....
You can do it the with [`zip`](https://docs.python.org/2/library/functions.html#zip) and [`reduce`](https://docs.python.org/2/library/functions.html#reduce) built-in functions (and in python3 `functools.reduce`): ``` >>> list_of_servers=[server1,server2,server3] >>> s=reduce(lambda x,y:x+y,zip(*list_of_servers)) >>> s...
cycle through multiple list using itertools.cycle()
29,226,375
13
2015-03-24T06:37:29Z
29,226,436
7
2015-03-24T06:42:11Z
[ "python", "itertools" ]
I have a list of servers. Every server has a list of name on it. example: ``` server1 = ['a','b','c'] server2 = ['d','e','f'] server3 = ['g','h','i'] ``` I want to iterate per server name not per server. For example after picking `'a'` in `server1`, move to `'d'` (not `'b'`) and so on. If I'm going to use `itertools....
This one works alright: ``` >>> from itertools import chain, islice, izip, cycle >>> list(islice(cycle(chain.from_iterable(izip(server1, server2, server3))), 0, 18)) ['a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i', 'a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i'] ``` Note, the `list` and `islice` are just for demonstration ...
cycle through multiple list using itertools.cycle()
29,226,375
13
2015-03-24T06:37:29Z
29,226,470
11
2015-03-24T06:45:16Z
[ "python", "itertools" ]
I have a list of servers. Every server has a list of name on it. example: ``` server1 = ['a','b','c'] server2 = ['d','e','f'] server3 = ['g','h','i'] ``` I want to iterate per server name not per server. For example after picking `'a'` in `server1`, move to `'d'` (not `'b'`) and so on. If I'm going to use `itertools....
We can also use [`itertools.chain.from_iterable()`](https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable) which is faster in comparison. ``` import itertools server1 = ['a','b','c'] server2 = ['d','e','f'] server3 = ['g','h','i'] print list(itertools.chain.from_iterable(zip(server1,server2,...
An array field in scrapy.Item
29,227,119
6
2015-03-24T07:33:11Z
29,227,311
13
2015-03-24T07:45:41Z
[ "python", "web-scraping", "scrapy" ]
I want to add a field to scrapy.Item so that it's an array: ``` class MyItem(scrapy.Item): field1 = scrapy.Field() field2 = scrapy.Field() field3_array = ??? ``` How can I do that?
You just create a filed ``` field3_array = scrapy.Field() ``` But while parsing the scraped items do like this ``` items['field3_array'] = [] items['field3_array'][0] ='one' items['field3_array'][1] ='two' ``` in this way you can achieve this. Have a [look](http://stackoverflow.com/questions/15507651/scrapy-with-...
Counting number of zeros per row by Pandas DataFrame?
29,229,600
3
2015-03-24T10:00:47Z
29,229,653
9
2015-03-24T10:04:01Z
[ "python", "pandas" ]
Given a DataFrame I would like to compute number of zeros per each row. How can I compute it with Pandas? This is presently what I ve done, this returns indices of zeros ``` def is_blank(x): return x == 0 indexer = train_df.applymap(is_blank) ```
Use a boolean comparison which will produce a boolean df, we can then cast this to int, True becomes 1, False becomes 0 and then call `count` and pass param `axis=1` to count row-wise: ``` In [56]: df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,0,1,0,1], 'c':[0,0,0,0,0]}) df Out[56]: a b c 0 1 0 0 1 0 0 0 2 0...
Plotting multiple lines with pandas dataframe
29,233,283
5
2015-03-24T12:57:58Z
29,233,885
9
2015-03-24T13:26:55Z
[ "python", "pandas", "plot" ]
I have a dataframe that looks like the following ``` color x y 0 red 0 0 1 red 1 1 2 red 2 2 3 red 3 3 4 red 4 4 5 red 5 5 6 red 6 6 7 red 7 7 8 red 8 8 9 red 9 9 10 blue 0 0 11 blue 1 1 12 blue 2 4 13 blue 3 9 14 blue 4 16 15 blue ...
You could use `groupby` to split the DataFrame into subgroups according to the color: ``` for key, grp in df.groupby(['color']): ``` --- ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_table('data', sep='\s+') fig, ax = plt.subplots() labels = [] for key, grp in df.groupby(['...
Edit distance such as Levenshtein taking into account proximity on keyboard
29,233,888
11
2015-03-24T13:27:04Z
29,590,495
9
2015-04-12T14:26:55Z
[ "python", "levenshtein-distance" ]
Is there an edit distance such as Levenshtein which takes into account distance for substitutions? For example, if we would consider if words are equal, `typo` and `tylo` are really close (`p` and `l` are physically close on the keyboard), while `typo` and `tyqo` are far apart. I'd like to allocate a smaller distance ...
the kind of distance you ask is not included in levenshtein - but you should use a helper like euclidean or manhattan distance, to get the result.my simple assumption is, **q** (in english qwerty layout) is cartesian (y=0; x=0) so, **w** will be (y=0; x=1) and so on. [whole list here](http://repl.it/iUB) ``` keyboard_...
What is the Python <> operator
29,238,871
2
2015-03-24T17:12:20Z
29,238,897
8
2015-03-24T17:13:49Z
[ "python", "operator-keyword" ]
What exactly is the `<>` operator in Python, and why is it undocumented (as far as I can tell)? Is it the same as `!=` or `is not`?
In [Python 2.x](https://docs.python.org/2/reference/lexical_analysis.html#operators), `<>` is the same as `!=` (i.e. *"not equal to"*, rather than `is not` which is *"not identical to"*), but the latter is preferred: > The comparison operators `<>` and `!=` are alternate spellings of the same operator. `!=` is the pre...
Why can't I call hash() on an apparently hashable method of an unhashable instance?
29,239,128
24
2015-03-24T17:26:22Z
29,239,150
32
2015-03-24T17:27:43Z
[ "python", "dictionary", "methods", "instance", "hashable" ]
Let's say I have a dictionary: ``` >>> d = {} ``` It has a method `clear()`: ``` >>> d.clear <built-in method clear of dict object at 0x7f209051c988> ``` ... which has a `__hash__` attribute: ``` >>> d.clear.__hash__ <method-wrapper '__hash__' of builtin_function_or_method object at 0x7f2090456288> ``` ... which ...
It is a bound method, and bound methods have a reference to `self`, e.g. the dictionary. This makes the method un-hashable. You *can* hash the unbound `dict.clear` method: ``` >>> d = {} >>> d.clear.__self__ {} >>> d.clear.__self__ is d True >>> hash(d.clear) Traceback (most recent call last): File "<stdin>", line ...
Why can't I call hash() on an apparently hashable method of an unhashable instance?
29,239,128
24
2015-03-24T17:26:22Z
29,242,105
10
2015-03-24T20:19:32Z
[ "python", "dictionary", "methods", "instance", "hashable" ]
Let's say I have a dictionary: ``` >>> d = {} ``` It has a method `clear()`: ``` >>> d.clear <built-in method clear of dict object at 0x7f209051c988> ``` ... which has a `__hash__` attribute: ``` >>> d.clear.__hash__ <method-wrapper '__hash__' of builtin_function_or_method object at 0x7f2090456288> ``` ... which ...
Martijn is right as he very often is. If you have a `dict` subclass that does implement the `__hash__` method, even the bound methods become hashable ``` class MyHashableDict(dict): def __hash__(self): return 42 x = MyHashableDict() print(x, hash(x), hash(x.clear)) y = {} print(y, hash(y.clear)) ``` Out...
Python collections.Counter: most_common complexity
29,240,807
11
2015-03-24T19:03:24Z
29,240,949
13
2015-03-24T19:11:16Z
[ "python", "python-2.7", "counter", "python-collections" ]
I'm wondering what is the complexity of the function `most_common` provided by the `collections.Counter` object in python 2.7. More specifically, is the `Counter` keeping some kind of sorted list while it is being updated, allowing to perform the `most_common` operation faster than `O(n)` when `n` is the number of (un...
From the source code of [collections.py](https://hg.python.org/cpython/file/2.7/Lib/collections.py#l472), we see that if we don't specify a number of returned elements, `most_common` returns a sorted list of the counts. This is an `O(n log n)` algorithm. If we use `most_common` to return `k > 1` elements, then we use ...
How to slice one MultiIndex DataFrame with the MultiIndex of another
29,266,600
5
2015-03-25T21:11:12Z
29,267,229
7
2015-03-25T21:51:16Z
[ "python", "pandas" ]
I have a pandas dataframe with 3 levels of a MultiIndex. I am trying to pull out rows of this dataframe according to a list of values that correspond to two of the levels. I have something like this: ``` ix = pd.MultiIndex.from_product([[1, 2, 3], ['foo', 'bar'], ['baz', 'can']], names=['a', 'b', 'c']) data = np.aran...
Here is a way to get this slice: ``` df.sort_index(inplace=True) idx = pd.IndexSlice df.loc[idx[:, ('foo','bar'), 'can'], :] ``` yielding ``` hi a b c 1 bar can 3 foo can 1 2 bar can 7 foo can 5 3 bar can 11 foo can 9 ``` Note that you might need to sort MultiIndex before you can...
Comparing the values of two dictionaries to receive their numerical difference Python
29,266,679
3
2015-03-25T21:15:43Z
29,266,750
9
2015-03-25T21:19:41Z
[ "python", "dictionary", "subtract", "valuestack" ]
I am new to Python. I have two dictionaries which share the same keys but different values for the keys. I would like to compare the two dictionaries so that I would get the numerical difference of the values for each key. For example: `dict1 = {'hi' : 45, 'thanks' : 34, 'please' : 60}` `dict2 = {'hi' : 40, 'thanks' ...
First, the format of your dictionaries is not correct (`:` and not `=`): ``` dict1 = {'hi':45, 'thanks':34, 'please':60} dict2 = {'hi':40, 'thanks':46, 'please':50} ``` You can use a dictionary comprehension. You basically loop through one dictionary, check that the key is also in the second dictionary and insert the...
How to enable proxy servers with anaconda python?
29,267,646
10
2015-03-25T22:20:01Z
29,267,796
8
2015-03-25T22:32:45Z
[ "python", "proxy", "firewall", "anaconda" ]
We are trying to get the conda install (on windows 8) to work behind a firewall via a proxy server. Currently, we are able to use pip to install packages while on our company network by using this at the command prompt: ``` pip install pandas --proxy=http://abc.def.xyz.com:1234 ``` No passwords need to be specified, ...
Well, this is embarrassing, but good news. I solved my problem with one more attempt at a change in the condarc file. ``` https: https://abc.def.xyz.com:1234 ``` I guess pip worked ok with regular http, while conda's addresses are all https sites: ``` https://repo.continuum.io/pkgs/free/win-64/ ``` I should have ca...
How to properly create and run concurrent tasks using python's asyncio module?
29,269,370
26
2015-03-26T01:08:21Z
29,280,606
33
2015-03-26T14:07:41Z
[ "python", "concurrency", "task", "python-3.4", "python-asyncio" ]
I am trying to properly understand and implement two concurrently running [`Task`](https://docs.python.org/3/library/asyncio-task.html#task) objects using Python 3's relatively new [`asyncio`](https://docs.python.org/3/library/asyncio.html) module. In a nutshell, asyncio seems designed to handle asynchronous processes...
Yes, any coroutine that's running inside your event loop will block other coroutines and tasks from running, unless it 1. Calls another coroutine using `yield from` or `await` (if using Python 3.5+). 2. Returns. This is because `asyncio` is single-threaded; the only way for the event loop to run is for no other corou...
How to properly create and run concurrent tasks using python's asyncio module?
29,269,370
26
2015-03-26T01:08:21Z
32,067,269
9
2015-08-18T08:25:17Z
[ "python", "concurrency", "task", "python-3.4", "python-asyncio" ]
I am trying to properly understand and implement two concurrently running [`Task`](https://docs.python.org/3/library/asyncio-task.html#task) objects using Python 3's relatively new [`asyncio`](https://docs.python.org/3/library/asyncio.html) module. In a nutshell, asyncio seems designed to handle asynchronous processes...
You don't necessarily need a `yield from x` to give control over to the event loop. In your example, I think the *proper* way would be to do a `yield None` or equivalently a simple `yield`, rather than a `yield from asyncio.sleep(0.001)`: ``` import asyncio @asyncio.coroutine def say_boo(): i = 0 while True: ...
Why is a Python I/O bound task not blocked by the GIL?
29,270,818
11
2015-03-26T03:52:01Z
29,270,846
16
2015-03-26T03:55:14Z
[ "python", "multithreading" ]
The [python threading](https://docs.python.org/2/library/threading.html) documentation states that "...threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously", apparently because I/O-bound processes can avoid the GIL that prevents threads from concurrent execution in CPU-boun...
All of Python's blocking I/O primitives release the GIL while waiting for the I/O block to resolve -- it's as simple as that! They will of course need to acquire the GIL again before going on to execute further Python code, but for the long-in-terms-of-machine-cycles intervals in which they're just waiting for some I/O...
Why is a Python I/O bound task not blocked by the GIL?
29,270,818
11
2015-03-26T03:52:01Z
29,270,976
8
2015-03-26T04:12:15Z
[ "python", "multithreading" ]
The [python threading](https://docs.python.org/2/library/threading.html) documentation states that "...threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously", apparently because I/O-bound processes can avoid the GIL that prevents threads from concurrent execution in CPU-boun...
The [GIL in CPython1](https://wiki.python.org/moin/GlobalInterpreterLock) is *only* concerned with Python code being executed. A thread-safe C extension that uses a lot of CPU might release the GIL as long as it doesn't need to interact with the Python runtime. As soon as the C code needs to 'talk' to Python (read: ca...
Pack function arguments into a dictionary - opposite to **kwargs
29,273,536
4
2015-03-26T08:03:08Z
29,273,620
7
2015-03-26T08:09:03Z
[ "python", "arguments", "argument-passing" ]
I'm trying to do something opposite to what \*\*kwargs do and I'm not sure if it is even possible. But knowing Python it probably is :-) I want to have all attributes clearly designed in my method (for auto completion, and easy of use) and I want to grab them all as, lets say a dictionary, and pass on further. ``` cla...
You can the the dict with variables using [locals()](https://docs.python.org/2/library/functions.html#locals). For example: ``` class Foo(object): def __init__(self, a=1, b=2): inputs = locals() del inputs['self'] # remove self variable print(inputs) f = Foo() ``` Results in print ou...
How does this App Engine Ndb syntax work?
29,279,776
3
2015-03-26T13:31:28Z
29,280,524
8
2015-03-26T14:04:22Z
[ "python", "google-app-engine", "app-engine-ndb", "google-app-engine-python" ]
Guido van Rossum's `Ndb` library for Google App Engine has a [syntax for queries](https://cloud.google.com/appengine/docs/python/ndb/queries#filter_by_prop "Ndb query syntax") that I find curious. Suppose you wanted to find all happy users, you would write this query: ``` User.query(User.happy == True) ``` I read tha...
You're missing python magic methods. ``` __eq__(self, other) ``` > Defines behavior for the equality operator, ==. Good guide about this could be found [here](http://www.rafekettler.com/magicmethods.html#comparisons).
Numpy individual element access slower than for lists
29,281,680
12
2015-03-26T14:54:37Z
29,311,751
10
2015-03-27T23:23:29Z
[ "python", "numpy" ]
I just started using Numpy and noticed that iterating through each element in a Numpy array is ~4x slower than doing the same but with a list of lists. I know now that this defeats the purpose of Numpy and I should vectorize the function if possible. My question is though why is it 4x slower. That seems like quite a la...
To recap, the NumPy operations you have listed do the following: 1. `b[100][100]` returns row 100 of `b`, and then gets the value at index 100 of this row. 2. `b[100,100]` returns the value at row 100 and column 100 *directly* (no row is returned first). 3. `b.item(100,100)` does the same as above `b[100,100]` except ...
What exactly does the T and Z mean in timestamp?
29,281,935
8
2015-03-26T15:06:12Z
29,282,022
12
2015-03-26T15:09:13Z
[ "python", "datetime", "timestamp", "strftime", "rfc3339" ]
I have this timestamp value being return by a webservice `"2014-09-12T19:34:29Z"` I know that it means timezone, but what exactly does it mean? And I am trying to mock this webservice, so is there a way to generate this timestamp using strftime in python? Sorry if this is painfully obvious, but google was not very h...
The `T` doesn't really stand for anything. It is just the *separator* that the [ISO 8601 combined date-time format](http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations) requires. You can read it as an abbreviation for *Time*. The `Z` stands for the *Zero* timezone, as it is offset by 0 from th...
Pandas read in table without headers
29,287,224
6
2015-03-26T19:27:49Z
29,287,549
9
2015-03-26T19:48:50Z
[ "python", "pandas" ]
How can I read in a .csv file (with no headers) and when I only want a subset of the columns (say 4th and 7th out of a total of 20 columns), using pandas? I cannot seem to be able to do `usecols`
In order to read a csv in that doesn't have a header and for only certain columns you need to pass params `header=None` and `usecols=[3,6]` for the 4th and 7th columns: ``` df = pd.read_csv(file_path, header=None, usecols=[3,6]) ``` See the [docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv....
pandas groupby for multiple data frames/files at once
29,287,943
3
2015-03-26T20:12:40Z
29,291,306
8
2015-03-27T00:29:39Z
[ "python", "csv", "pandas", "group-by", "multiple-files" ]
I have multiple huge tsv files that I'm trying to process using pandas. I want to group by 'col3' and 'col5'. I've tried this: ``` import pandas as pd df = pd.read_csv('filename.txt', sep = "\t") g2 = df.drop_duplicates(['col3', 'col5']) g3 = g2.groupby(['col3', 'col5']).size().sum(level=0) print g3 ``` It works fine...
This is a nice use case for [`blaze`](http://blaze.pydata.org). Here's an example using a couple of reduced files from the [nyctaxi dataset](http://www.andresmh.com/nyctaxitrips/). I've purposely split a single large file into two files of 1,000,000 lines each: ``` In [16]: from blaze import Data, compute, by In [17...
Quickly and efficiently calculating an eigenvector for known eigenvalue
29,290,232
9
2015-03-26T22:44:21Z
29,290,958
7
2015-03-26T23:52:27Z
[ "python", "matlab", "linear-algebra", "numeric", "eigenvector" ]
**Short version of my question**: What would be the optimal way of calculating an eigenvector for a matrix `A`, if we already know the eigenvalue belonging to the eigenvector? **Longer explanation**: I have a large stochastic matrix `A` which, because it is stochastic, has a non-negative left eigenvector `x` (such t...
Here's one approach: 1. Let **x** denote the (row) left†eigenvector associated to eigenvalue 1. It satisfies the system of linear equations (or matrix equation) **xA** = **x**, or **x**(**A**−**I**)=**0**. 2. To avoid the all-zeros solution to that system of equations, remove the first equation and arbitrarily set...
Existence of mutable named tuple in Python?
29,290,359
36
2015-03-26T22:56:46Z
29,290,496
14
2015-03-26T23:09:06Z
[ "python" ]
Can anyone amend [namedtuple](http://code.activestate.com/recipes/500261/) or provide an alternative class so that it works for mutable objects? Primarily for readability, I would like something similar to namedtuple that does this: ``` from Camelot import namedgroup Point = namedgroup('Point', ['x', 'y']) p = Point...
It seems like the answer to this question is no. Below is pretty close, but it's not technically mutable. This is creating a new `namedtuple()` instance with an updated x value: ``` Point = namedtuple('Point', ['x', 'y']) p = Point(0, 0) p = p._replace(x=10) ``` On the other hand, you can create a simple class using...
Existence of mutable named tuple in Python?
29,290,359
36
2015-03-26T22:56:46Z
29,419,745
36
2015-04-02T18:16:47Z
[ "python" ]
Can anyone amend [namedtuple](http://code.activestate.com/recipes/500261/) or provide an alternative class so that it works for mutable objects? Primarily for readability, I would like something similar to namedtuple that does this: ``` from Camelot import namedgroup Point = namedgroup('Point', ['x', 'y']) p = Point...
There is a mutable alternative to `collections.namedtuple` - [recordclass](https://pypi.python.org/pypi/recordclass). It has same API and memory footprint as `namedtuple` (actually it also faster). It also support assignments. For example: ``` from recordclass import recordclass Point = recordclass('Point', 'x y') ...
How to count down in for loop in python?
29,292,133
4
2015-03-27T02:06:58Z
29,292,161
8
2015-03-27T02:11:15Z
[ "python" ]
In Java, I have the following for loop and I am learning Python: ``` for (int index = last-1; index >= posn; index--) ``` My question is simple and probably obvious for most of people who are familiar with Python. I would like to code that 'for' loop in Python. How can I do this? I tried to do the following: ``` fo...
The range function in python has the syntax: `range(start, end, step)` It has the same syntax as python lists where the start is inclusive but the end is exclusive. So if you want to count from 5 to 1, you would use `range(5,0,-1)` and if you wanted to count from `last` to `posn` you would use `range(last, posn - 1,...
Format date without dash?
29,295,402
4
2015-03-27T07:28:44Z
29,295,462
9
2015-03-27T07:33:04Z
[ "python", "date" ]
In Python, we can convert a date to a string by: ``` >>> import datetime >>> datetime.date(2002, 12,4).isoformat() '2002-12-04' ``` How can we format the output to be '20021204', i.e. without dashes? There are two functions, but I don't know how to specify the format: > `date.strftime(format)` > Return a string r...
You are using the wrong tool for your job, use [strftime](https://docs.python.org/2/library/datetime.html#datetime.date.strftime) ``` >>> datetime.date(2002, 12,4).strftime("%Y%m%d") '20021204' ``` For details on using [strftime](https://docs.python.org/2/library/datetime.html#datetime.date.strftime) and [strptime](h...
python asyncio, how to create and cancel tasks from another thread
29,296,064
9
2015-03-27T08:17:34Z
29,302,684
7
2015-03-27T14:10:25Z
[ "python", "multithreading", "python-multithreading", "python-asyncio" ]
I have a python multi-threaded application. I want to run an asyncio loop in a thread and post calbacks and coroutines to it from another thread. Should be easy but I cannot get my head around the [asyncio](https://docs.python.org/3.4/library/asyncio.html) stuff. I came up to the following solution which does half of ...
I think you may need to make your `add_task` method aware of whether or not its being called from a thread other than the event loop's. That way, if it's being called from the same thread, you can just call `asyncio.async` directly, otherwise, it can do some extra work to pass the task from the loop's thread to the cal...
s3cmd ImportError: No module named S3.Exceptions
29,303,657
4
2015-03-27T14:55:33Z
29,303,658
13
2015-03-27T14:55:33Z
[ "python", "linux", "amazon-ec2", "s3cmd" ]
Received an error after installing and trying to run [s3cmd](http://s3tools.org/s3cmd) 1.0.0 ``` s3cmd -h Problem: ImportError: No module named S3.Exceptions S3cmd: unknown version. Module import problem? Traceback (most recent call last): File "/usr/bin/s3cmd", line 1995, in <module> from S3.Exceptions impo...
Looks like the error happened because python2.7 is now the default python version in the Amazon Linux 2015.03.0+ If you change python back to 2.6 and run s3cmd it should work without a problem ``` update-alternatives --set python /usr/bin/python2.6 s3cmd -h ``` After the s3cmd command is ran you can put python back t...
How to stop celery worker process
29,306,337
11
2015-03-27T17:10:32Z
29,307,816
19
2015-03-27T18:33:23Z
[ "python", "django", "amazon-ec2", "celery" ]
I have a Django project on an Ubuntu EC2 node, which I have been using to set up an asynchronous using `Celery`. I am following [this](http://michal.karzynski.pl/blog/2014/05/18/setting-up-an-asynchronous-task-queue-for-django-using-celery-redis/) along with the docs. I've been able to get a basic task working at the...
Try this in terminal ``` ps aux|grep 'celery worker' ``` You will see like this ``` username 29042 0.0 0.6 23216 14356 pts/1 S+ 00:18 0:01 /bin/celery worker ... ``` Then kill process id by ``` sudo kill -9 process_id # here 29042 ``` If you have multiple processes, then you have to kill all process id...