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
Combine a list of pandas dataframes to one pandas dataframe
32,444,138
6
2015-09-07T18:13:42Z
32,444,187
10
2015-09-07T18:17:24Z
[ "python", "pandas" ]
I have a list of Pandas dataframes that I would like to combine into one Pandas dataframe. I am using Python 2.7.10 and Pandas 0.16.2 I created the list of dataframes from: ``` import pandas as pd dfs = [] sqlall = "select * from mytable" for chunk in pd.read_sql_query(sqlall , cnxn, chunksize=10000): dfs.append...
Given that all the dataframes have the same columns, you can simply `concat` them: ``` import pandas as pd df = pd.concat(list_of_dataframes) ```
Django app works fine, but getting a TEMPLATE_* warning message
32,445,953
19
2015-09-07T20:57:45Z
32,446,043
41
2015-09-07T21:07:07Z
[ "python", "django", "django-1.8" ]
When I use runserver, it gives this warning message: > (1\_8.W001) The standalone TEMPLATE\_\* settings were deprecated in > Django 1.8 and the TEMPLATES dictionary takes precedence. You must put > the values of the following settings into your default TEMPLATES dict: > TEMPLATE\_DEBUG. Quoth the Django Documentation...
Set `debug` in `OPTIONS` dictionary of your templates settings. ``` DEBUG = True TEMPLATES = [ { ... 'OPTIONS': { 'debug': DEBUG, }, }, ] ``` Then remove this line from your settings to stop the warnings ``` TEMPLATE_DEBUG = DEBUG ```
Django app works fine, but getting a TEMPLATE_* warning message
32,445,953
19
2015-09-07T20:57:45Z
34,643,824
8
2016-01-06T22:12:48Z
[ "python", "django", "django-1.8" ]
When I use runserver, it gives this warning message: > (1\_8.W001) The standalone TEMPLATE\_\* settings were deprecated in > Django 1.8 and the TEMPLATES dictionary takes precedence. You must put > the values of the following settings into your default TEMPLATES dict: > TEMPLATE\_DEBUG. Quoth the Django Documentation...
remove APP\_DIRS and add the loaders inside the templates. example: ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'OPTIONS': { 'context_processors': [ 'django.template.con...
Why is while loop much faster than range in this case?
32,448,958
2
2015-09-08T03:45:32Z
32,449,045
7
2015-09-08T03:56:17Z
[ "python", "loops" ]
According to this [post](http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop), range loop should be faster than while loop in python, but please have a look at the following code. It is simply used to test if a number is prime and return the divisor if n is not a...
Since you are using Python 2+ ( your code needs to use integer division to work in Python 3+ ) you are running into the fact that Python 2+ `range` generates a list of all elements and then iterates over them. This would explain the differences in time that it takes for the `while` and `range` functions to run. Inced...
What is the purpose of this if statement from "Learning Python the Hard Way"?
32,449,229
3
2015-09-08T04:21:46Z
32,449,241
8
2015-09-08T04:23:50Z
[ "python" ]
I am currently reading *Learning Python the Hard Way* and I have a question regarding one line of the following code. ``` cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return t...
An empty string is considered a falsey value. Therefore, `if not state:` means that the content of that block will be evaluated when `state` is an empty string (or any other falsey value). The `break` ends the loop early. What this does is exit the loop immediately when the user simply presses `Enter` without entering...
Is this a valid use of a conditional expression?
32,454,225
10
2015-09-08T09:35:45Z
32,454,339
16
2015-09-08T09:40:59Z
[ "python", "python-3.x" ]
I'm trying to figure out what the best way of doing this is: ``` resource['contents'][media_type] = [] resource['contents'][media_type].append(row[0].toPython()) if row[0] is not None else None resource['contents'][media_type].append(row[2].toPython()) if row[2] is not None else None ``` I think the code is quite sim...
Using a "ternary" [conditional expression](https://docs.python.org/2/reference/expressions.html#conditional-expressions) (`x if C else y`) for side effects is not at all Pythonic. Here's how I would do it: ``` resource['contents'][media_type] = [] for index in (0, 2): item = row[i] if item is not None: ...
Is this a valid use of a conditional expression?
32,454,225
10
2015-09-08T09:35:45Z
32,454,341
10
2015-09-08T09:41:08Z
[ "python", "python-3.x" ]
I'm trying to figure out what the best way of doing this is: ``` resource['contents'][media_type] = [] resource['contents'][media_type].append(row[0].toPython()) if row[0] is not None else None resource['contents'][media_type].append(row[2].toPython()) if row[2] is not None else None ``` I think the code is quite sim...
No, that's not a valid use of a conditional expression. It confuses anyone trying to read your code. Use an `if` statement; you can save some space by creating another reference to the list: ``` lst = resource['contents'][media_type] = [] if row[0] is not None: lst.append(row[0].toPython()) if row[2] is not None: ls...
Git 2.5.1's bash console doesn't open python interpreter
32,454,589
10
2015-09-08T09:51:34Z
33,696,825
12
2015-11-13T15:59:04Z
[ "python", "git", "bash" ]
If I do it in CMD, it works without issues, but if I try it in Git Bash it doesn't work. I like to use Git Bash as my only console, but I can't do that if it doesn't work with Python 3.4. Example is in the picture below. This can be easily reproduced. Uninstall Python and Git if they are installed, install Python 3.4,...
The MinTTY terminal that is the new default terminal for Git simply doesn't support Windows console programs. I don't know why the decision was made to change the default terminal, but I know two ways to work around this: 1. Launch python in interactive mode explicitly, or use winpty: **Interactive mode:** ``` pytho...
Python: understanding iterators and `join()` better
32,462,194
10
2015-09-08T15:52:22Z
32,462,254
10
2015-09-08T15:55:33Z
[ "python", "python-internals" ]
The `join()` function accepts an iterable as parameter. However, I was wondering why having: ``` text = 'asdfqwer' ``` This: ``` ''.join([c for c in text]) ``` Is significantly faster than: ``` ''.join(c for c in text) ``` The same occurs with long strings (i.e. `text * 10000000`). Watching the memory footprint ...
The `join` method reads its input twice; once to determine how much memory to allocate for the resulting string object, then again to perform the actual join. Passing a list is faster than passing a generator object that it needs to make a copy of so that it can iterate over it twice. A list comprehension is not simpl...
Add colorbar to existing axis
32,462,881
8
2015-09-08T16:32:40Z
32,463,689
9
2015-09-08T17:21:13Z
[ "python", "matplotlib" ]
I'm making some interactive plots and I would like to add a colorbar legend. I don't want the colorbar to be in its own axes, so I want to add it to the existing axes. I'm having difficulties doing this, as most of the example code I have found creates a new axes for the colorbar. I have tried the following code using...
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the `cax` kwarg to tell `fig.colorbar` to use the new axes. For example: ``` import numpy as np import matplotlib.pyplot as plt data = np.arange(100, 0, -1).reshape(10, 10) fig, ax = plt.subplots() c...
Spark performance for Scala vs Python
32,464,122
58
2015-09-08T17:46:02Z
32,471,016
104
2015-09-09T04:39:57Z
[ "python", "performance", "scala", "apache-spark", "pyspark" ]
I prefer Python over Scala. But, as Spark is natively written in Scala, I was expecting my code to run faster in the Scala than the Python version for obvious reasons. With that assumption, I thought to learn & write the Scala version of some very common preprocessing code for some 1 GB of data. Data is picked from th...
--- The original answer discussing the code can be found below. --- First of all you have to distinguish between different types of API, each with its own performance consideration. ### RDD API *(pure Python structures with JVM based orchestration)* This is the component which will be most affected by a performan...
For line in : not returning all lines
32,464,521
4
2015-09-08T18:11:30Z
32,464,538
7
2015-09-08T18:12:56Z
[ "python", "dictionary", "readlines" ]
I am trying to traverse a text file and take each line and put it into a dictionary. Ex: If the txt file is a b c I am trying to create a dictionary like word\_dict = {'a':1, 'b:2', 'c':3} When I use this code: ``` def word_dict(): fin = open('words2.txt','r') dict_words = dict() i = 1 for line in fin: txt = fi...
You're trying to read the lines twice. Just do this: ``` def word_dict(file_path): with open(file_path, 'r') as input_file: words = {line.strip(): i for i, line in enumerate(input_file, 1)} return words print(word_dict('words2.txt')) ``` This fixes a couple things. 1. Functions should not have hard...
What exactly is the "resolution" parameter of numpy float
32,465,481
4
2015-09-08T19:11:42Z
32,466,516
7
2015-09-08T20:16:17Z
[ "python", "numpy", "floating-point", "precision", "floating-accuracy" ]
I am seeking some more understanding about the "resolution" parameter of a numpy float (I guess any computer defined float for that matter). Consider the following script: ``` import numpy as np a = np.finfo(10.1) print a ``` I get an output which among other things prints out: ``` precision=15 resolution= 1.0000...
The short answer is "*dont' confuse [`numpy.finfo`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html) with [`numpy.spacing`](http://nullege.com/codes/search/numpy.spacing?fulldoc=1)*". `finfo` operates on the `dtype`, while `spacing` operates on the value. ## Background Information First, though,...
How to explode a list inside a Dataframe cell into separate rows
32,468,402
10
2015-09-08T22:43:05Z
32,470,490
10
2015-09-09T03:36:02Z
[ "python", "pandas", "dataframe" ]
I'm looking to turn a pandas cell containing a list into rows for each of those values. So, take this: [![enter image description here](http://i.stack.imgur.com/j7lFk.png)](http://i.stack.imgur.com/j7lFk.png) If I'd like to unpack and stack the values in the 'nearest\_neighbors" column so that each value would be a ...
In the code below, I first reset the index to make the row iteration easier. I create a list of lists where each element of the outer list is a row of the target DataFrame and each element of the inner list is one of the columns. This nested list will ultimately be concatenated to create the desired DataFrame. I use ...
Splitting a string into consecutive counts?
32,469,124
3
2015-09-09T00:22:44Z
32,469,143
8
2015-09-09T00:26:15Z
[ "python", "string", "list-comprehension" ]
For example given string ``` "aaabbbbccdaeeee" ``` I want to say something like ``` 3 a, 4 b, 2 c, 1 d, 1 a, 4 e ``` It is easy enough to do in Python with a brute force loop but I am wondering if there is a more Pythonic / cleaner one-liner type of approach. My brute force: ``` while source!="": lead...
Use a [Counter](https://docs.python.org/2/library/collections.html#collections.Counter) for a count of each distinct letter in the string regardless of position: ``` >>> s="aaabbbbccdaeeee" >>> from collections import Counter >>> Counter(s) Counter({'a': 4, 'b': 4, 'e': 4, 'c': 2, 'd': 1}) ``` You can use [groupby](h...
why does python logging level in basicConfig have no effect?
32,471,999
6
2015-09-09T06:05:59Z
32,535,301
7
2015-09-12T04:55:11Z
[ "python", "logging" ]
``` import logging # root logger root = logging.getLogger() # root ch = logging.StreamHandler() ch.setLevel(logging.WARN) formatter = logging.Formatter('[root] %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) # logging as child c = logging.getLogger('mod') c.setLevel(logging.DEBUG) ch...
You are seeing those `[root]` info and debug messages because your call to `logging.basicConfig` creates a root **Handler** with a level of `NOTSET`. A handler with a level of `NOTSET` will output any message it receives (see [Handler.setLevel](https://docs.python.org/3.5/library/logging.html#logging.Handler.setLevel))...
How to check if a range is a part of another range in Python 3.x
32,480,423
2
2015-09-09T13:07:19Z
32,481,015
7
2015-09-09T13:33:25Z
[ "python", "python-3.x", "range" ]
How can I simply check if a range is a subrange of another ? `range1 in range2` will not work as expected.
You can do it in `O(1)`, as follows: ``` def range_subset(range1, range2): """Whether range1 is a subset of range2.""" if not range1: return True # empty range is subset of anything if not range2: return False # non-empty range can't be subset of empty range if len(range1) > 1 and ran...
how to skip the index in python for loop
32,480,808
4
2015-09-09T13:23:58Z
32,480,880
8
2015-09-09T13:26:30Z
[ "python", "for-loop" ]
I have a list like this: ``` array=['for','loop','in','python'] for arr in array: print arr ``` This will give me the output ``` for lop in python ``` I want to print ``` in python ``` How can I skip the first 2 indices in python?
Use [slicing](https://docs.python.org/2/tutorial/introduction.html#lists). ``` array = ['for','loop','in','python'] for arr in array[2:]: print arr ``` When you do this, the starting index in the `for` loop becomes `2`. Thus the output would be: ``` in python ``` For more info on `slicing` read this: [Explain ...
Why do these tests fail for this custom Flask session interface?
32,483,063
8
2015-09-09T15:00:25Z
32,597,959
7
2015-09-16T00:47:03Z
[ "python", "session", "flask", "customization" ]
I am writing a hybrid single page web/PhoneGap application in Flask. Since cookies in a PhoneGap application are basically unavailable, I have implemented a custom [session interface](http://flask.pocoo.org/docs/0.10/api/#session-interface) that completely avoids cookies. It stores session data in the application datab...
Your problems *mostly* come down to providing the session token in your test requests. If you don't provide the token the session is blank. I assume your actual application is correctly sending the session token and thus appears to work. It doesn't take much to fix up the test cases to pass correctly. ## Every reque...
How to use viridis in matplotlib 1.4
32,484,453
12
2015-09-09T16:08:21Z
32,484,859
11
2015-09-09T16:29:38Z
[ "python", "matplotlib", "colormap" ]
I want to use the colormap "viridis" (<http://bids.github.io/colormap/>), and I won't be updating to the development version 1.5 quite yet. Thus, I have downloaded `colormaps.py` from <https://github.com/BIDS/colormap>. Unfortunately, I'm not able to make it work. This is what I do: ``` import matplotlib.pyplot as plt...
Rather than using `set_cmap`, which requires a `matplotlib.colors.Colormap` instance, you can set the `cmap` directly in the `pcolormesh` call (`cmaps.viridis` is a `matplotlib.colors.ListedColormap`) ``` import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import colormaps as cmaps i...
How to use viridis in matplotlib 1.4
32,484,453
12
2015-09-09T16:08:21Z
32,484,915
9
2015-09-09T16:32:01Z
[ "python", "matplotlib", "colormap" ]
I want to use the colormap "viridis" (<http://bids.github.io/colormap/>), and I won't be updating to the development version 1.5 quite yet. Thus, I have downloaded `colormaps.py` from <https://github.com/BIDS/colormap>. Unfortunately, I'm not able to make it work. This is what I do: ``` import matplotlib.pyplot as plt...
To set `viridis` as your colormap using `set_cmap`, you must register it first: ``` import colormaps as cmaps plt.register_cmap(name='viridis', cmap=cmaps.viridis) plt.set_cmap(cmaps.viridis) img=mpimg.imread('stinkbug.png') lum_img = np.flipud(img[:,:,0]) imgplot = plt.pcolormesh(lum_img) ```
Matplotlib and Numpy - Create a calendar heatmap
32,485,907
2
2015-09-09T17:32:25Z
32,492,179
8
2015-09-10T02:34:22Z
[ "python", "python-2.7", "numpy", "matplotlib" ]
Is it possible to create a calendar heatmap without using pandas? If so, can someone post a simple example? I have dates like Aug-16 and a count value like 16 and I thought this would be a quick and easy way to show intensity of counts between days for a long period of time. Thank you
It's certainly possible, but you'll need to jump through a few hoops. First off, I'm going to assume you mean a calendar display that looks like a calendar, as opposed to a more linear format (a linear formatted "heatmap" is much easier than this). The key is reshaping your arbitrary-length 1D series into an Nx7 2D a...
Performance - searching a string in a text file - Python
32,487,979
2
2015-09-09T19:47:12Z
32,488,150
7
2015-09-09T19:59:35Z
[ "python", "performance", "list" ]
I have a set of dates: ``` dates1 = {'21/5/2015', '4/4/2015', '15/6/2015', '30/1/2015', '19/3/2015', '25/2/2015', '25/5/2015', '8/2/2015', '6/6/2015', '15/3/2015', '15/1/2015', '30/5/2015'} ``` the same dates appear in a text ('data' from now on). It´s a pretty long text. I want to loop over the text and get the num...
Loop over the lines once, extracting any date, check if the date is in the set, if so increment the count using a [Counter](https://docs.python.org/2/library/collections.html#collections.Counter) dict for the counts, at the end call Counter.most\_common to get the 5 most common dates: ``` dates1 = {'21/5/2015', '4/4/2...
Convert a 64 bit integer into 8 separate 1 byte integers in python
32,490,081
12
2015-09-09T22:23:34Z
32,490,254
8
2015-09-09T22:38:22Z
[ "python", "bitmask" ]
In python, I have been given a 64 bit integer. This Integer was created by taking several different 8 bit integers and mashing them together into one giant 64 bit integer. It is my job to separate them again. For example: ``` Source number: 2592701575664680400 Binary (64 bits): 001000111111101100100000010110001010101...
# Solution Solution without converting the number to a string: ``` x = 0b0010001111111011001000000101100010101010000101101011111000000000 numbers = list((x >> i) & 0xFF for i in range(0,64,8)) print(numbers) # [0, 190, 22, 170, 88, 32, 251, 35] print(list(reversed(numbers))) # [35, 251, 32, 88,...
Getting today's date in YYYY-MM-DD in Python?
32,490,629
6
2015-09-09T23:20:25Z
32,490,661
19
2015-09-09T23:23:57Z
[ "python", "python-2.7", "datetime", "python-datetime" ]
I'm using: ``` str(datetime.datetime.today()).split()[0] ``` to return today's date in the form *YYYY-MM-DD*. Is there a less crude way to achieve this?
You can use [strftime](http://strftime.org/): ``` datetime.datetime.today().strftime('%Y-%m-%d') ```
Selenium Python Headless Webdriver (PhantomJS) Not Working
32,491,274
6
2015-09-10T00:42:44Z
33,037,330
10
2015-10-09T11:38:19Z
[ "python", "linux", "selenium", "phantomjs", "splinter" ]
So I'm having trouble getting selenium to work with a headless driver, specifically PhantomJS. I'm trying to get it to work on an Ubuntu webserver (Ubuntu 14.04.2 LTS). Running the following commands from a python interpreter (Python 2.7.6) gives: ``` from selenium import webdriver driver = webdriver.PhantomJS() Tra...
I had the same problem as you with the same errors. I have tried to install it on openSuse Server. I ended up installing PhantomJS form source -unfortunately without any success. The way that worked for me was installing Phantomjs via npm ``` sudo npm install -g phantomjs ```
Parse an XML string in Python
32,494,318
4
2015-09-10T06:06:50Z
32,494,514
11
2015-09-10T06:19:13Z
[ "python", "xml" ]
I have this XML string result and i need to get the values in between the tags. But the data type of the XML is string. ``` final = " <Table><Claimable>false</Claimable><MinorRev>80601</MinorRev><Operation>530600 ION MILL</Operation><HTNum>162</HTNum><WaferEC>80318</WaferEC><HolderType>HACARR</HolderType><Job>16718...
Your XML is malformed. It has to have exactly one top level element. [From Wikipedia](https://en.wikipedia.org/wiki/Root_element): > Each XML document has exactly one single root element. It encloses all > the other elements and is therefore the sole parent element to all the > other elements. ROOT elements are also c...
Python string converts magically to tuple. Why?
32,499,871
3
2015-09-10T10:51:15Z
32,499,912
14
2015-09-10T10:53:10Z
[ "python", "string", "casting", "tuples" ]
I've got a dict in which I load some info, among others a name which is a plain string. But somehow, when I assign it to a key in the dict it gets converted to a tuple, and I have no idea why. Here's some of my code: ``` sentTo = str(sentTo) print type(sentTo), sentTo ticketJson['sentTo'] = sentTo, print type(ticketJ...
You told Python to create a tuple containing a string: ``` ticketJson['sentTo'] = sentTo, # ^ ``` It is the comma that defines a tuple. Parentheses are only needed to disambiguate a tuple from other uses of a comma, such as in a function call. From the [*Parenthesized forms* section](https...
Boto3/S3: Renaming an object using copy_object
32,501,995
15
2015-09-10T12:31:12Z
32,502,197
10
2015-09-10T12:40:53Z
[ "python", "amazon-web-services", "amazon-s3", "boto3" ]
I'm trying to rename a file in my s3 bucket using python boto3, I couldn't clearly understand the arguments. can someone help me here? What I'm planing is to copy object to a new object, and then delete the actual object. I found similar questions here, but I need a solution using boto3.
You cannot rename objects in S3, so as you indicated, you need to copy it to a new name and then deleted the old one: ``` client.copy_object(Bucket="BucketName", CopySource="BucketName/OriginalName", Key="NewName") client.delete_object(Bucket="BucketName", Key="OriginalName") ```
Boto3/S3: Renaming an object using copy_object
32,501,995
15
2015-09-10T12:31:12Z
32,504,096
18
2015-09-10T14:05:44Z
[ "python", "amazon-web-services", "amazon-s3", "boto3" ]
I'm trying to rename a file in my s3 bucket using python boto3, I couldn't clearly understand the arguments. can someone help me here? What I'm planing is to copy object to a new object, and then delete the actual object. I found similar questions here, but I need a solution using boto3.
I found another solution ``` s3 = boto3.resource('s3') s3.Object('my_bucket','my_file_new').copy_from(CopySource='my_bucket/my_file_old') s3.Object('my_bucket','my_file_old').delete() ```
hashing different tuples in python give identical result
32,504,977
6
2015-09-10T14:41:35Z
32,505,139
8
2015-09-10T14:49:21Z
[ "python", "hash", "tuples" ]
I'm working with sets of integer matrices, and I thought representing them as tuples made sense, as they are hashable. However the hash() function gave me strange results for tuples: ``` hash(((1, -1, 0), (1, 0, 0), (1, 0, -1))) Out[147]: -697649482279922733 hash(((1, 0, -1), (1, 0, 0), (1, -1, 0))) Out[148]: -6976...
The hash of a tuple is based on the hashes of the content using the following formula (from the [`tuplehash()` function](https://hg.python.org/cpython/file/v2.7.10/Objects/tupleobject.c#l341)): ``` long mult = 1000003L; x = 0x345678L; p = v->ob_item; while (--len >= 0) { y = PyObject_Hash(*p++); if (y == -1) ...
Python regex '\s' does not match unicode BOM (U+FEFF)
32,506,708
8
2015-09-10T16:03:28Z
32,507,020
12
2015-09-10T16:19:52Z
[ "python", "regex", "unicode" ]
The Python `re` module's [documentation](https://docs.python.org/2/library/re.html) says that when the `re.UNICODE` flag is set, `'\s'` will match: > whatever is classified as space in the Unicode character properties database. As far I can tell, the BOM (U+FEFF) is [classified as a space](https://en.wikipedia.org/wi...
U+FEFF is not a whitespace character according to the unicode database. Wikipedia only lists it as it is a "related character". These are similar to whitespace characters but don't have the `WSpace` property in the database. None of those characters are matched by `\s`.
Standard solution for supporting Python 2 and Python 3
32,507,715
6
2015-09-10T16:58:41Z
32,507,890
8
2015-09-10T17:08:49Z
[ "python", "python-3.x", "import", "module", "compatibility" ]
I'm trying to write a forward compatible program and I was wondering what the "best" way to handle the case where you need different imports. In my specific case, I am using `ConfigParser.SafeConfigParser()` from Python2 which becomes `configparser.ConfigParser()` in Python3. So far I have made it work either by usin...
Use [six](https://pypi.python.org/pypi/six)! It's a python compatibility module that irons out the differences between python3 and python2. The documentation [available here](http://pythonhosted.org/six/#module-six.moves) will help you with this problem as well as any other issues you're having.. Specifically for your...
Iterate over the lines of two files simultaneously
32,509,173
3
2015-09-10T18:25:58Z
32,509,411
10
2015-09-10T18:40:57Z
[ "python", "python-2.x" ]
I am trying to concatenate pieces specific lines together between two files. Such that I want to add something from line 2 in file2 onto line 2 of file1. Then from line 6 from file2 onto line 6 of file 1 and so on. Is there a way to simultaneously iterate through these two files to do this? (It might be helpful to know...
**Python3**: ``` with open('bigfile_1') as bf1: with open('bigfile_2') as bf2: for line1, line2 in zip(bf1, bf2): process(line1, line2) ``` Importantly, bf1 and bf2 will not read the entire file in at once. They are iterators which know how to produce one line at a time. [`zip()`](https://doc...
Sum all values of a counter in Python
32,511,444
5
2015-09-10T20:55:57Z
32,511,472
9
2015-09-10T20:58:06Z
[ "python", "python-2.7", "counter" ]
I have a counter from the `collections` module. What is the best way of summing all of the counts? For example, I have: ``` my_counter = Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}) ``` and would like to get the value `7` returned. As far as I can tell, the function `sum` is for adding multiple counters together.
Something like this will do ``` sum(my_counter.itervalues()) ``` This way you don't create any intermediate data structures, just get the sum lazily evaluated.
Generator as function argument
32,521,140
67
2015-09-11T10:21:14Z
32,521,643
57
2015-09-11T10:47:18Z
[ "python", "python-2.7", "syntax", "generator-expression" ]
Can anyone explain why passing a generator as the only positional argument to a function seems to have special rules? If we have: ``` >>> def f(*args): >>> print "Success!" >>> print args ``` 1. This works, as expected. ``` >>> f(1, *[2]) Success! (1, 2) ``` 2. This does not work, as expected. ...
**Both 3. and 4. *should* be syntax errors on all Python versions.** However you've found a bug that affects Python versions 2.5 - 3.4, and which was subsequently [posted to the Python issue tracker](https://bugs.python.org/issue25070). Because of the bug, an unparenthesized generator expression was accepted as an argu...
Python, distinguishing custom exceptions
32,523,086
6
2015-09-11T12:02:53Z
32,523,156
11
2015-09-11T12:06:53Z
[ "python", "exception-handling" ]
fairly new to Python here. Have this code: ``` def someFunction( num ): if num < 0: raise Exception("Negative Number!") elif num > 1000: raise Exception("Big Number!") else: print "Tests passed" try: someFunction(10000) except Exception: print "This was a negative number b...
you need to create your own exception classes if you want to be able to distinguish the kind of exception that happened. example (i inherited from `ValueError` as i think this is the closest to what you want - it also allows you to just catch `ValueError` should the distinction not matter): ``` class NegativeError(Val...
How to set React to production mode when using Gulp
32,526,281
18
2015-09-11T14:49:03Z
32,999,184
17
2015-10-07T17:53:10Z
[ "javascript", "python", "flask", "reactjs", "tornado" ]
I need to run React in production mode, which presumably entails defining the following somewhere in the enviornment: ``` process.env.NODE_ENV = 'production'; ``` The issue is that I'm running this behind Tornado (a python web-server), not Node.js. I also use Supervisord to manage the tornado instances, so it's not a...
***Step I:*** Add the following to your gulpfile.js somewhere ``` gulp.task('apply-prod-environment', function() { process.env.NODE_ENV = 'production'; }); ``` ***Step II:*** Add it to your default task (or whichever task you use to serve/build your app) ``` // before: // gulp.task('default',['browsersync','wat...
Straightforward way to save the contents of an S3 key to a string in boto3?
32,526,356
6
2015-09-11T14:53:16Z
32,526,756
9
2015-09-11T15:14:04Z
[ "python", "amazon-s3", "boto3" ]
So when I issue a get() what I have is a dict and the 'Body' member of the dict is a "StreamingBody' type and per [How to save S3 object to a file using boto3](https://stackoverflow.com/questions/29378763/how-to-save-s3-object-to-a-file-using-boto3), I see how I could read from this stream in chunks, but I'm wondering ...
Update: I have done `response = s3_client.get_object(Bucket=bn,Key=obj['Key']) contents = response['Body'].read()` which seems to work.
pip doesn't work after upgrade
32,531,563
12
2015-09-11T20:23:05Z
36,548,685
12
2016-04-11T12:26:45Z
[ "python", "pip", "pypi" ]
Today I upgraded from pip 7.1.0 to 7.1.2, and now it doesn't work. ``` $ pip search docker-compose Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/s...
I wasn't able to reproduce this with pip 7.1.2 and either Python 2.7.8 or 3.5.1 on Linux. The [xmlrpclib docs](https://docs.python.org/3/library/xmlrpc.client.html) have this to say on 'faults': > Method calls may also raise a special Fault instance, used to signal > XML-RPC server errors This implies that pip is re...
Log log plot linear regression
32,536,226
8
2015-09-12T07:11:40Z
32,577,245
13
2015-09-15T03:32:35Z
[ "python", "numpy", "matplotlib" ]
``` fig = plt.figure(); ax=plt.gca() ax.scatter(x,y,c="blue",alpha=0.95,edgecolors='none') ax.set_yscale('log') ax.set_xscale('log') (Pdb) print x,y [29, 36, 8, 32, 11, 60, 16, 242, 36, 115, 5, 102, 3, 16, 71, 0, 0, 21, 347, 19, 12, 162, 11, 224, 20, 1, 14, 6, 3, 346, 73, 51, 42, 37, 251, 21, 100, 11, 53, 118, 82...
[The only mathematical form that is a straight line on a log-log-plot is an exponential function.](https://en.wikipedia.org/wiki/Log%E2%80%93log_plot) Since you have data with x=0 in it you can't just fit a line to `log(y) = k*log(x) + a` because [`log(0)`](https://en.wikipedia.org/wiki/Logarithm) is undefined. So we'...
Pycharm IPython tab completion not working (within python console)
32,542,289
8
2015-09-12T18:31:23Z
34,091,233
9
2015-12-04T15:02:21Z
[ "python", "ipython", "pycharm", "tab-completion" ]
So I have searched high and low for an answer regarding this and I am starting to come to the conclusion that it simply isn't a feature for Pycharm. I am using IPython in Pycharm and I cannot get tab completion to work at all. If I start IPython in the terminal within Pycharm, there is no issue and tab completion work...
I emailed PyCharm support and asked the same question. Their response is that tab completion isn't currently supported, but you can vote [here](https://youtrack.jetbrains.com/issue/PY-9345) to move it up their priority list. After years of tab completion in my muscle memory, Ctrl + space is not an ideal alternative.
Control tick labels in Python seaborn package
32,542,957
2
2015-09-12T19:42:39Z
32,543,266
10
2015-09-12T20:13:08Z
[ "python", "pandas", "ipython", "seaborn" ]
I have a scatter plot matrix generated using the `seaborn` package and I'd like to remove all the tick mark labels as these are just messying up the graph (either that or just remove those on the x-axis), but I'm not sure how to do it and have had no success doing Google searches. Any suggestions? ``` import seaborn a...
``` import seaborn as sns iris = sns.load_dataset("iris") g = sns.pairplot(iris) g.set(xticklabels=[]) ``` [![enter image description here](http://i.stack.imgur.com/GFNVF.png)](http://i.stack.imgur.com/GFNVF.png)
How to print from Flask @app.route to python console
32,550,487
11
2015-09-13T14:07:28Z
33,383,239
21
2015-10-28T05:02:09Z
[ "python", "flask" ]
I would like to simply print a "hello world" to the python console after /button is called by the user. This is my naive approach: ``` @app.route('/button/') def button_clicked(): print 'Hello world!' return redirect('/') ``` Background: I would like to execute other python commands from flask (not shell). "...
It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this: ``` from __future__ import print_function # In python 2.7 import sys @app.route('/button/') def button_clicked(): print('Hello world!', file=sys.stderr) ret...
Flask validates decorator multiple fields simultaneously
32,555,829
17
2015-09-14T00:23:26Z
33,025,472
7
2015-10-08T20:33:59Z
[ "python", "validation", "flask", "sqlalchemy", "flask-sqlalchemy" ]
I have been using the @validates decorator in sqlalchemy.orm from flask to validate fields, and all has gone well as long as all of the fields are independent of one another such as: ``` @validates('field_one') def validates_field_one(self, key, value): #field one validation @validates('field_two') def validates_f...
Order the fields in the order they were defined on the model. Then check if the last field is the one being validated. Otherwise just return the value unchecked. If the validator is validating one of the earlier fields, some of them will not be set yet. ``` @validates('field_one', 'field_two') def validates_fields(sel...
Create labeledPoints from Spark DataFrame in Python
32,556,178
4
2015-09-14T01:29:26Z
32,557,330
7
2015-09-14T04:29:33Z
[ "python", "pandas", "apache-spark", "apache-spark-mllib" ]
What .map() function in python do I use to create a set of labeledPoints from a spark dataframe? What is the notation if The label/outcome is not the first column but I can refer to its column name, 'status'? I create the python dataframe with this .map() function: ``` def parsePoint(line): listmp = list(line.spl...
If you already have numerical features and which require no additional transformations you can use `VectorAssembler` to combine columns containing independent variables: ``` from pyspark.ml.feature import VectorAssembler assembler = VectorAssembler( inputCols=["your", "independent", "variables"], outputCol="f...
What are Type hints in Python 3.5
32,557,920
58
2015-09-14T05:37:33Z
32,558,710
82
2015-09-14T06:49:50Z
[ "python", "python-3.x", "type-hinting" ]
One of the talked about features in `Python 3.5` is said to be `type hints`. An example of `type hints` is mentioned in this [article](http://lwn.net/Articles/650904/) and [this](http://lwn.net/Articles/640359/) while also mentioning to use type hints responsibly. Can someone explain more about it and when it should b...
I would suggest reading [PEP 483](https://www.python.org/dev/peps/pep-0483/) and [PEP 484](https://www.python.org/dev/peps/pep-0484/) and watching [this](https://www.youtube.com/watch?v=2wDvzy6Hgxg) presentation by Guido on Type Hinting. In addition, more examples on Type Hints can be found at their [documentation topi...
What are Type hints in Python 3.5
32,557,920
58
2015-09-14T05:37:33Z
34,352,299
13
2015-12-18T09:28:02Z
[ "python", "python-3.x", "type-hinting" ]
One of the talked about features in `Python 3.5` is said to be `type hints`. An example of `type hints` is mentioned in this [article](http://lwn.net/Articles/650904/) and [this](http://lwn.net/Articles/640359/) while also mentioning to use type hints responsibly. Can someone explain more about it and when it should b...
The newly released PyCharm 5 supports type hinting. In their blog post about it (see [Python 3.5 type hinting in PyCharm 5](http://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/)) they offer a great explanation of **what type hints are and aren't** along with several examples and illustrations...
What are Type hints in Python 3.5
32,557,920
58
2015-09-14T05:37:33Z
38,045,620
7
2016-06-27T03:46:37Z
[ "python", "python-3.x", "type-hinting" ]
One of the talked about features in `Python 3.5` is said to be `type hints`. An example of `type hints` is mentioned in this [article](http://lwn.net/Articles/650904/) and [this](http://lwn.net/Articles/640359/) while also mentioning to use type hints responsibly. Can someone explain more about it and when it should b...
Adding to Jim's elaborate answer: Check the [`typing` module](https://docs.python.org/3/library/typing.html) -- this module supports type hints as specified by PEP 484. For example, the function below takes and returns values of type `str` and is annotated as follows: ``` def greeting(name: str) -> str: return '...
How can I understand a .pyc file content
32,562,163
3
2015-09-14T10:08:27Z
32,562,303
8
2015-09-14T10:15:38Z
[ "python", "python-2.7", "disassembling", "pyc" ]
I have a `.pyc` file. I need to understand the content of that file to know how the disassembler works of python, i.e. how can I generate a output like `dis.dis(function)` from `.pyc` file content. for e.g. ``` >>> def sqr(x): ... return x*x ... >>> import dis >>> dis.dis(sqr) 2 0 LOAD_FAST ...
`.pyc` files contain some metadata and a [`marshal`ed](https://docs.python.org/2/library/marshal.html) `code` object; to load the `code` object and disassemble that use: ``` import dis, marshal with open(pycfile, "rb") as f: magic_and_timestamp = f.read(8) # first 8 bytes are metadata code = marshal.load(f) ...
Simple way to measure cell execution time in ipython notebook
32,565,829
14
2015-09-14T13:15:57Z
36,690,084
9
2016-04-18T09:27:25Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
I would like to get the time spent on the cell execution in addition to the original output from cell. To this end, I tried `%%timeit -r1 -n1` but it doesn't expose the variable defined within cell. `%%time` works for cell which only contains 1 statement. ``` In[1]: %%time 1 CPU times: user 4 µs, sys: 0 ns, ...
Use cell magic and this project on github by Phillip Cloud: Load it by putting this at the top of your notebook or put it in your config file if you always want to load it by default: ``` %install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py %load_ext autotime ``` If loaded, every output of...
What did I wrong here [Write to file in new line]?
32,568,234
3
2015-09-14T15:11:51Z
32,568,264
9
2015-09-14T15:13:29Z
[ "python" ]
I want to make a simple function that writes two words to a file each on a new line. But if I run this code it only writes "tist - tost" to the file. Code: ``` def write_words(word1, word2): w = open("output.txt", "w") w.write(word1 + " - " + word2 + '\n') w.close() write_words("test", "tast") write_word...
You need to open your file in append mode, also as a more pythonic way for opening a file you can use [*`with` statement*](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) which close the file at the end of block : ``` def write_words(word1, word2): with open("output.txt", "a") as f : ...
Does spark predicate pushdown work with JDBC?
32,573,991
11
2015-09-14T21:09:33Z
32,585,936
8
2015-09-15T12:20:01Z
[ "python", "jdbc", "apache-spark", "apache-spark-sql", "pyspark" ]
According to [this](https://databricks.com/blog/2015/02/17/introducing-dataframes-in-spark-for-large-scale-data-science.html) > Catalyst applies logical optimizations such as predicate pushdown. The > optimizer can push filter predicates down into the data source, > enabling the physical execution to skip irrelevant d...
Spark DataFrames support predicate push-down with JDBC sources but term *predicate* is used in a strict SQL meaning. It means it covers only `WHERE` clause. Moreover it looks like it is limited to the logical conjunction (no `IN` and `OR` I am afraid) and simple predicates. Everything else, like limits, counts, orderi...
Convert dictionary to tuple with additional element inside tuple
32,582,458
3
2015-09-15T09:27:53Z
32,582,520
8
2015-09-15T09:30:50Z
[ "python", "dictionary", "tuples" ]
Let's say I have this dictionary: ``` d = {'a': 1, 'b': 2, 'c': 3} ``` So doing `d.items()`, it would convert it to: ``` [('a', 1), ('c', 3), ('b', 2)] ``` But I need it to be like this: ``` [('a', '=', 1), ('c', '=', 3), ('b', '=', 2)] ``` What would be most pythonic/efficient way of doing it? Are there better a...
You have to iterate over the dictionary and construct each tuple. Using a list comprehension, this is fairly straightforward to do: ``` >>> [(k, '=', v) for k, v in d.items()] [('a', '=', 1), ('c', '=', 3), ('b', '=', 2)] ```
Django REST Framework: difference between views and viewsets?
32,589,087
5
2015-09-15T14:47:55Z
32,589,879
10
2015-09-15T15:24:24Z
[ "python", "django", "rest", "django-views", "django-rest-framework" ]
May be [relevant](http://stackoverflow.com/questions/32430689/what-does-django-rest-framework-mean-trade-offs-between-view-vs-viewsets). What is the difference between **views** and **viewsets**? And what about **router** and **urlpatterns**?
`ViewSets` and `Routers` are simple tools to speed-up implementing of your API, if you're aiming to standard behaviour and standard URLs. Using `ViewSet` you don't have to create separate views for getting list of objects and detail of one object. ViewSet will handle for you in consistent way both list and detail. Us...
Python pandas: how to specify data types when reading an Excel file?
32,591,466
2
2015-09-15T16:48:09Z
32,591,786
11
2015-09-15T17:06:27Z
[ "python", "pandas", "dataframe" ]
I am importing an excel file into a pandas dataframe with the `pandas.read_excel()` function. One of the columns is the primary key of the table: it's all numbers, but it's stored as text (the little green triangle in the top left of the Excel cells confirms this). However, when I import the file into a pandas datafr...
You just specify converters. I created an excel spreadsheet of the following structure: ``` names ages bob 05 tom 4 suzy 3 ``` Where the "ages" column is formatted as strings. To load: import pandas as pd ``` df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str...
Static method syntax confusion
32,593,763
2
2015-09-15T19:08:26Z
32,593,849
8
2015-09-15T19:13:58Z
[ "python", "python-2.7", "methods", "static-methods" ]
This is how we make static functions in Python: ``` class A: @staticmethod def fun(): print 'hello' A.fun() ``` This works as expected and prints `hello`. If it is a member function instead of a static one, we use `self`: ``` class A: def fun(self): print 'hello' A().fun() ``` which also wor...
Python doesn't give you a syntax error, because the binding of a method (which takes care of passing in `self`) is a *runtime* action. Only when you look up a method on a class or instance, is a method being bound (because functions are [descriptors](https://docs.python.org/2/howto/descriptor.html) they produce a meth...
How do I generate non-repeating random numbers in a while loop? (Python 3)
32,596,805
4
2015-09-15T22:34:44Z
32,596,849
8
2015-09-15T22:39:42Z
[ "python", "python-3.x", "random", "while-loop" ]
So far what I have is ``` import random def go(): rounds = 0 while rounds < 5: number = random.randint(1, 5) if number == 1: print('a') elif number == 2: print('b') elif number == 3: print('c') elif number == 4: print('d') ...
The [random.sample(population, k)](https://docs.python.org/2/library/random.html#random.sample) method returns a sample of unique values from the specified population of length k. ``` r = random.sample("abcde", 5) for element in r: print(element) ```
Python not working in the command line of git bash
32,597,209
22
2015-09-15T23:18:07Z
32,599,341
22
2015-09-16T03:38:17Z
[ "python", "windows", "git", "command-line", "git-bash" ]
Python will not run in git bash (Windows). When I type python in the command line, it takes me to a blank line without saying that it has entered python 2.7.10 like its does in Powershell. It doesn't give me an error message, but python just doesn't run. I have already made sure the environmental variables in PATH inc...
[This is a known bug in MSys2, which provides the terminal used by Git Bash.](http://sourceforge.net/p/msys2/tickets/32/) You can work around it by running a Python build without ncurses support, or by using [WinPTY](https://github.com/rprichard/winpty/), used as follows: > To run a Windows console program in mintty o...
Python not working in the command line of git bash
32,597,209
22
2015-09-15T23:18:07Z
36,530,750
18
2016-04-10T14:05:16Z
[ "python", "windows", "git", "command-line", "git-bash" ]
Python will not run in git bash (Windows). When I type python in the command line, it takes me to a blank line without saying that it has entered python 2.7.10 like its does in Powershell. It doesn't give me an error message, but python just doesn't run. I have already made sure the environmental variables in PATH inc...
Just enter this in your git shell on windows - > `alias python='winpty python.exe'`, that is all and you are going to have alias to the python executable. Enjoy P.S. For permanent alias addition see below, ``` cd ~ touch .bashrc ``` then open .bashrc, add your command from above and save the file. You need to create...
Fast Iteration of numpy arrays
32,597,294
7
2015-09-15T23:27:33Z
32,600,805
7
2015-09-16T05:58:30Z
[ "python", "arrays", "numpy", "filtering", "signal-processing" ]
I'm new to python and I'm trying to do some basic signal-processing stuff and I'm having a serious performance problem. Is there a python trick for doing this in a vectorized manner? Basically I'm trying to implement a 1st order filter, but where the filter characteristics may change from one sample to the next. If it ...
You could consider using one of the python-to-native- code converter, among [cython](http://cython.org), [numba](http://numba.pydata.org) or [pythran](https://github.com/serge-sans-paille/pythran). For instance, running your original code with timeit gives me: ``` $ python -m timeit -s 'from co import co; import nump...
Asyncio RuntimeError: Event Loop is Closed
32,598,231
5
2015-09-16T01:22:12Z
32,615,276
11
2015-09-16T17:43:03Z
[ "python", "python-3.x", "python-asyncio", "aiohttp" ]
I'm trying to make a bunch of requests (~1000) using Asyncio and the aiohttp library, but I am running into a problem that I can't find much info on. When I run this code with 10 urls, it runs just fine. When I run it with 100+ urls, it breaks and gives me `RuntimeError: Event loop is closed` error. ``` import asynci...
The bug is filed as <https://github.com/python/asyncio/issues/258> Stay tuned. As quick workaround I suggest using custom executor, e.g. ``` loop = asyncio.get_event_loop() executor = concurrent.futures.ThreadPoolExecutor(5) loop.set_default_executor(executor) ``` Before finishing your program please do ``` executo...
How to make this simple string function "pythonic"
32,600,848
5
2015-09-16T06:01:15Z
32,600,945
26
2015-09-16T06:08:49Z
[ "python", "string" ]
Coming from the C/C++ world and being a Python newb, I wrote this simple string function that takes an input string (guaranteed to be ASCII) and returns the last four characters. If there’s less than four characters, I want to fill the leading positions with the letter ‘A'. (this was not an exercise, but a valuable...
I would use simple slicing and then [`str.rjust()`](https://docs.python.org/2/library/stdtypes.html#str.rjust) to right justify the result using `A` as `fillchar` . Example - ``` def copy_four(s): return s[-4:].rjust(4,'A') ``` Demo - ``` >>> copy_four('21') 'AA21' >>> copy_four('1233423') '3423' ```
Converting this list into Dictionary using Python
32,602,353
4
2015-09-16T07:32:10Z
32,602,472
11
2015-09-16T07:38:34Z
[ "python", "list" ]
``` list = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n'] ``` I want this list in a dictionary with keys as `Name`, `country`, `game` and values as `Sachin`, `India`, `cricket` as corresponding values. I got this list using `readlines()` from a text file.
``` >>> lst = ['Name=Sachin\n', 'country=India\n', 'game=cricket\n'] >>> result = dict(e.strip().split('=') for e in lst) >>> print(result) {'Name': 'Sachin', 'country': 'India', 'game': 'cricket'} ```
Error when loading rpy2 with anaconda
32,602,578
5
2015-09-16T07:43:33Z
32,617,616
7
2015-09-16T19:59:45Z
[ "python", "anaconda", "rpy2" ]
I am trying to load `rpy2` inside a project where I am working with `anaconda` and I am getting a surprising error for which I cannot find a solution. My python version is `3.4`, my anaconda version is `3.17.0` - I am using a Mac (OSX Yosemite version 10.10.4) `R version 3.2.2 (2015-08-14) -- "Fire Safety"` `Platform...
I just built an updated rpy2 2.7.0 against R 3.2.2. Can you run ``` conda install -c r rpy2 ``` and see if that fixes it?
Create feature vector programmatically in Spark ML / pyspark
32,606,294
4
2015-09-16T10:39:53Z
32,607,349
10
2015-09-16T11:29:29Z
[ "python", "apache-spark", "pyspark", "apache-spark-ml" ]
I'm wondering if there is a concise way to run ML (e.g KMeans) on a DataFrame in pyspark if I have the features in multiple numeric columns. I.e. as in the `Iris` dataset: ``` (a1=5.1, a2=3.5, a3=1.4, a4=0.2, id=u'id_1', label=u'Iris-setosa', binomial_label=1) ``` I'd like to use KMeans without recreating the DataSe...
You can use [`VectorAssembler`](http://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.feature.VectorAssembler): ``` from pyspark.ml.feature import VectorAssembler ignore = ['id', 'label', 'binomial_label'] assembler = VectorAssembler( inputCols=[x for x in df.columns if x not in ignore], o...
splitting lines with " from an infile in python
32,608,338
5
2015-09-16T12:14:58Z
32,608,386
8
2015-09-16T12:17:49Z
[ "python", "split" ]
I have a series of input files such as: ``` chr1 hg19_refFlat exon 44160380 44160565 0.000000 + . gene_id "KDM4A"; transcript_id "KDM4A"; chr1 hg19_refFlat exon 19563636 19563732 0.000000 - . gene_id "EMC1"; transcript_id "EMC1"; chr1 hg19_refFlat exon 52870219 5...
It is because your file object is exhausted when you loop over it once here `start = set([line.strip().split()[3] for line in r])` again you are trying to loop here `genes = set([line.split('"')[1] for line in r])` over the exhausted file object **Solution:** You could seek to the start of the file (this is one of th...
Replace keys in a dictionary
32,623,405
10
2015-09-17T05:54:17Z
32,623,459
15
2015-09-17T05:59:22Z
[ "python", "string", "python-2.7", "dictionary" ]
I have a dictionary ``` event_types={"as":0,"ah":0,"es":0,"eh":0,"os":0,"oh":0,"cs":0,"ch":0} ``` How can I replace `a` by `append`, `s` by `see`, `h` by `horse`, `e` by `exp` with a space in between. Output something like: ``` {"append see":0,"append horse":0,"exp horse":0....} ```
Have another dictionary with your replacements, like this ``` keys = {"a": "append", "h": "horse", "e": "exp", "s": "see"} ``` Now, if your events look like this ``` event_types = {"as": 0, "ah": 0, "es": 0, "eh": 0} ``` Simply reconstruct it with dictionary comprehension, like this ``` >>> {" ".join([keys[char] f...
How to serialize custom user model in DRF
32,638,268
2
2015-09-17T19:13:00Z
32,638,296
7
2015-09-17T19:15:44Z
[ "python", "django", "serialization", "django-rest-framework", "django-serializer" ]
I have made a custom user model,by referring the [tutorial](http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/) , this is how I serialize the new user model: **Serializers.py** ``` from django.conf import settings User = settings.AUTH_USER_MODEL class UserSerializer(serializers.ModelSeri...
Instead of ``` User = settings.AUTH_USER_MODEL ``` use ``` from from django.contrib.auth import get_user_model User = get_user_model() ``` Remember that `settings.AUTH_USER_MODEL` is just a `string` that indicates which user model you will use not the model itself. If you want to get the model, use `get_user_model`
Is it possible to "transfer" a session between selenium.webdriver and requests.session
32,639,014
6
2015-09-17T20:03:40Z
32,639,151
8
2015-09-17T20:11:35Z
[ "python", "session", "selenium", "browser", "python-requests" ]
In theory, if I copy all of the cookies from selenium's `webdriver` object to `requests.Session` object, would requests be able to continue on as if the session was not interrupted? Specifically, I am interested in writing automation where I get to specific location on the webpage via selenium, then pass on a certain ...
Yes it will definitely work. Following code snippet should help as well - ``` headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" } s = requests.session() s.headers.update(headers) for cookie in driver.get_cookies(): c = {co...
Python Flask: keeping track of user sessions? How to get Session Cookie ID?
32,640,090
4
2015-09-17T21:14:44Z
32,643,135
9
2015-09-18T03:00:47Z
[ "python", "session", "web-applications", "flask", "flask-login" ]
I want to build a simple webapp as part of my learning activity. Webapp is supposed to ask for user to input their email\_id if it encounters a first time visitor else it remembers the user through cookie and automatically logs him/her in to carry out the functions. This is my first time with creating a user based web...
You can access request cookies through the [`request.cookies` dictionary](http://flask.pocoo.org/docs/0.10/api/#flask.Request.cookies) and set cookies by using either `make_response` or just storing the result of calling `render_template` in a variable and then calling [`set_cookie` on the response object](http://flask...
Combine (join) networkx Graphs
32,652,149
5
2015-09-18T12:33:33Z
32,697,415
7
2015-09-21T14:11:23Z
[ "python", "graph-theory", "networkx" ]
Say I have two networkx graphs, `G` and `H`: ``` G=nx.Graph() fromnodes=[0,1,1,1,1,1,2] tonodes=[1,2,3,4,5,6,7] for x,y in zip(fromnodes,tonodes): G.add_edge(x,y) H=nx.Graph() fromnodes=range(2,8) tonodes=range(8,14) for x,y in zip(fromnodes,tonodes): H.add_edge(x,y) ``` **What is the best way to join the tw...
The function you're looking for is [compose](https://networkx.readthedocs.org/en/stable/reference/generated/networkx.algorithms.operators.binary.compose.html). ``` import networkx as nx G=nx.Graph() G.add_edge(1,2) H=nx.Graph() H.add_edge(1,3) F = nx.compose(G,H) F.edges() > [(1, 2), (1, 3)] ``` There are also other ...
Python Function Return Loop
32,653,496
10
2015-09-18T13:38:47Z
32,653,596
18
2015-09-18T13:43:18Z
[ "python", "recursion" ]
Ok, so this piece of code is from a practice question at my school. We are to mentally parse the code and check the answer. When I first parsed it, I got 4. I copied the code and ran it through IDLE and got 8. I ran the debugger and saw that the else: return is looping the if else statement until `x == 0` and then it ...
You will make following calls to foo: ``` foo(3) -> foo(2) -> foo(1) -> foo(0) ``` those will return ``` foo(0) -> 1 foo(1) -> 2 * foo(0) -> 2 * 1 -> 2 foo(2) -> 2 * foo(1) -> 2 * 2 -> 4 foo(3) -> 2 * foo(2) -> 2 * 4 -> 8 ``` Is it clear now?
Python Function Return Loop
32,653,496
10
2015-09-18T13:38:47Z
32,653,604
11
2015-09-18T13:43:44Z
[ "python", "recursion" ]
Ok, so this piece of code is from a practice question at my school. We are to mentally parse the code and check the answer. When I first parsed it, I got 4. I copied the code and ran it through IDLE and got 8. I ran the debugger and saw that the else: return is looping the if else statement until `x == 0` and then it ...
I think you’re having the right idea (otherwise you wouldn’t have gotten the answer 4), you’re simply aborting too early in your mental exercise. You can keep track of the variables by tabulating them while going through the code: * `foo(3)` + calls `foo(3 - 1)` → `foo(2)` - calls `foo(2 - 1)` → `foo(...
How to create simple 3-layer neural network and teach it using supervised learning?
32,655,573
6
2015-09-18T15:19:25Z
32,683,367
8
2015-09-20T19:26:45Z
[ "python", "python-2.7", "pybrain" ]
Based on [PyBrain's tutorials](http://pybrain.org/docs/index.html#tutorials) I managed to knock together the following code: ``` #!/usr/bin/env python2 # coding: utf-8 from pybrain.structure import FeedForwardNetwork, LinearLayer, SigmoidLayer, FullConnection from pybrain.datasets import SupervisedDataSet from pybrai...
There are four problems with your approach, all easy to identify after reading [Neural Network FAQ](ftp://ftp.sas.com/pub/neural/FAQ.html): * [Why use a bias/threshold?](ftp://ftp.sas.com/pub/neural/FAQ2.html#A_bias): you should add a bias node. Lack of bias makes the learning very limited: the separating hyperplane r...
Histogram matching of two images in Python 2.x?
32,655,686
4
2015-09-18T15:24:38Z
33,047,048
9
2015-10-09T20:56:26Z
[ "python", "numpy", "image-processing", "histogram" ]
I'm trying to match the histograms of two images (in MATLAB this could be done using [`imhistmatch`](http://www.mathworks.com/help/images/ref/imhistmatch.html)). Is there an equivalent function available from a standard Python library? I've looked at OpenCV, scipy, and numpy but don't see any similar functionality.
I previously wrote an answer [here](http://stackoverflow.com/a/31493356/1461210) explaining how to do piecewise linear interpolation on an image histogram in order to enforce particular ratios of highlights/midtones/shadows. The same basic principles underlie [histogram matching](https://en.wikipedia.org/wiki/Histogra...
How to run a python 3.4 script as an executable?
32,656,758
2
2015-09-18T16:22:45Z
32,656,911
9
2015-09-18T16:32:00Z
[ "python", "bash" ]
Say, I have a python script named `hello.py`, which I run on mac as: ``` $ python hello.py ``` What do I need to do to run it as: ``` $ hello ```
Add a "shebang" to the top of the file to tell it how to run your script. ``` #!/usr/bin/env python ``` Then you need to mark the script as "executable": ``` chmod +x hello.py ``` Then you can just run it as `./hello.py` instead of `python hello.py`. To run it as just `hello`, you can rename the file from `hello.p...
parallelized algorithm for evaluating a 1-d array of functions on a same-length 1d numpy array
32,669,916
5
2015-09-19T15:22:46Z
32,671,603
7
2015-09-19T18:06:36Z
[ "python", "performance", "numpy", "parallel-processing", "scientific-computing" ]
The upshot of the below is that I have an embarrassingly parallel for loop that I am trying to thread. There's a bit of rigamarole to explain the problem, but despite all the verbosity, I **think** this should be a rather trivial problem that the multiprocessing module is designed to solve easily. I have a large lengt...
## Warning/Caveat: You may not want to apply `multiprocessing` to this problem. You'll find that relatively simple operations on large arrays, the problems will be memory bound with `numpy`. The bottleneck is moving data from RAM to the CPU caches. The CPU is starved for data, so throwing more CPUs at the problem does...
How can I read keyboard input in Python
32,671,306
2
2015-09-19T17:37:55Z
32,671,356
8
2015-09-19T17:42:08Z
[ "python", "python-2.7", "user-input" ]
I have problem with keyboard input in Python. I tried raw\_input and it is called only once. But I want to read keyboard input every time user press any key. How can I do it? Thanks for answers.
So for instance you have a Python code like this: ### file1.py ``` #!/bin/python ... do some stuff... ``` And at a certain point of the document you want to always check for input: ``` while True: input = raw_input(">>>") ... do something with the input... ``` That will always wait for input. You can threa...
Failing to change bool var state in loop
32,672,769
2
2015-09-19T20:14:53Z
32,672,786
7
2015-09-19T20:17:21Z
[ "python", "if-statement", "for-loop", "range" ]
I'm trying to write a prime number checker according to : [Prime equations](http://www.wikihow.com/Check-if-a-Number-Is-Prime) My code so far looks like this: ``` def primer(x): prime = False x = math.sqrt(x) if type(x) == float: x = math.ceil(x) for i in range(3,x + 1): if (i % 2) =...
You are not actually assigning: ``` prime == True ``` Should be: ``` prime = True ``` `==` is a comparison operator, `=` is for assignment. You can use the `any` function to create your prime number checker, also we only need to loop to the sqrt of x and check odd numbers. I also added an implementation of [fermat...
Is checking if key is in dictionary and getting it's value in the same "if" safe?
32,679,180
5
2015-09-20T12:03:29Z
32,679,210
13
2015-09-20T12:06:03Z
[ "python", "python-3.x", "dictionary" ]
I think this is safe: ``` if key in test_dict: if test_dict[key] == 'spam': print('Spam detected!') ``` but is this safe? ``` if key in test_dict and test_dict[key] == 'spam': print('Spam detected!') ``` It should do the same thing because condition checking is lazy in python. It won't try to get th...
Yes, it is safe, Python would short circuit if first expression result in False, that is it would not evaluate the second expression in the `if` condition. But a better way to do your condition would be to use `.get()` , which returns `None` if key is not present in dictionary . Example - ``` if test_dict.get(key) ==...
How do I get the user to input a number in Python 3?
32,679,575
3
2015-09-20T12:46:29Z
32,679,606
7
2015-09-20T12:51:03Z
[ "python", "python-3.x" ]
I'm trying to make a quiz using Python 3. The quiz randomly generates two separate numbers and operator. But when I try to get the user to input their answer, this shows up in the shell: ``` <class 'int'> ``` I'm not sure what I need to do. Even if I type in the correct answer, it always returns as incorrect. ``` im...
This line is incorrect: ``` if input(int)==(num1,op,num2): ``` You must convert the input to `int` and apply `op` to `num1` and `num2`: ``` if int(input()) == op(num1, num2): ```
How to get the format of image with PIL?
32,679,589
6
2015-09-20T12:49:11Z
32,679,637
12
2015-09-20T12:54:55Z
[ "python", "python-imaging-library", "image-formats" ]
After loading an image file with PIL.Image, how can I determine whether the image file is a PNG/JPG/BMP/GIF? I understand very little about these file formats, can PIL get the `format` metadata from the file header? Or does it need to 'analyze' the data within the file? If PIL doesn't provide such an API, is there any...
Try: ``` img = Image.open(filename) print(img.format) # 'JPEG' ``` More info * <http://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.format> * <http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html>
ImportError after successful pip installation
32,680,081
2
2015-09-20T13:45:10Z
32,680,082
8
2015-09-20T13:45:10Z
[ "python", "pip" ]
I have successfully installed a library with `pip install <library-name>`. But when I try to import it, python raises `ImportError: No module named <library-name>`. Why do I get this error and how can I use the installed library?
**TL;DR**: There are often multiple versions of python interpreters and pip versions present. Using `python -m pip install <library-name>` instead of `pip install <library-name>` will ensure that the library gets installed into the default python interpreter. **Please also note:** From my personal experience I would a...
Converting all non-numeric to 0 (zero) in Python
32,680,639
9
2015-09-20T14:46:12Z
32,680,821
10
2015-09-20T15:05:00Z
[ "python" ]
I'm looking for the easiest way to convert all non-numeric data (including blanks) in Python to zeros. Taking the following for example: ``` someData = [[1.0,4,'7',-50],['8 bananas','text','',12.5644]] ``` I would like the output to be as follows: ``` desiredData = [[1.0,4,7,-50],[0,0,0,12.5644]] ``` So '7' should ...
``` import numbers def mapped(x): if isinstance(x,numbers.Number): return x for tpe in (int, float): try: return tpe(x) except ValueError: continue return 0 for sub in someData: sub[:] = map(mapped,sub) print(someData) [[1.0, 4, 7, -50], [0, 0, 0, 12.564...
How to get string before hyphen
32,682,199
2
2015-09-20T17:24:24Z
32,682,209
9
2015-09-20T17:25:09Z
[ "python" ]
I have below filename: ``` pagecounts-20150802-000000 ``` I want to extract the date out of above `20150802` I am using the below code but its not working: ``` print os.path.splitext("pagecounts-20150802-000000")[0] ```
The methods in `os.path` are mainly used for path string manipulation. You want to use string splitting: ``` print 'pagecounts-20150802-000000'.split('-')[1] ```
How do I ensure parameter is correct type in Python?
32,684,720
3
2015-09-20T21:56:28Z
32,684,829
7
2015-09-20T22:09:33Z
[ "python" ]
I'm new to Python, and am trying to figure out if there is a way to specify the variable type in a parameter definition. For example: ``` def function(int(integer)) ``` as opposed to: ``` def function(integer) int(integer) ``` I know it's not a major difference, but I'm trying to use good programming practices ...
Python uses [Duck typing](http://stackoverflow.com/questions/4205130/what-is-duck-typing) which means you should not discriminate objects based on what type they are, but based on what attributes and functions they have. This has many advantages which are outside of the scope of this answer. What you should do instead...
Recursive generation of pattern
32,696,640
2
2015-09-21T13:33:48Z
32,696,717
7
2015-09-21T13:37:08Z
[ "python", "recursion", "permutation" ]
I'm trying to generate all permutations in a list. I know there's built-in functions for this but I would like to do it myself with a recursive function. I'm trying to understand why my attempt doesn't work: ``` chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def recurse(n, value): if n >...
``` for c in chars: value += c recurse(n-1, value) ``` This loop runs 62 times per recursion level, so `value` will grow and grow to have a maximum size of 124. To avoid this cumulative effect, try: ``` for c in chars: recurse(n-1, value+c) ```
Limit a python file to only be run by a bash script
32,698,320
3
2015-09-21T14:51:55Z
32,698,394
8
2015-09-21T14:55:24Z
[ "python", "bash" ]
I am looking for a way to limit how a python file to be called. Basically I only want it to be executable when I call it from a bash script but if ran directly either from a terminal or any other way I do not want it to be able to run. I am not sure if there is a way to do this or not but I figured I would give it a sh...
There is no meaningful way to do this. UNIX process architecture does not work this way. You cannot control the execution of a script by its parent process. Instead we should discuss *why* you want to do something like this, you are probably thinking doing it in a wrong way and what good options there is to address t...
python: replace elements in list with conditional
32,699,654
2
2015-09-21T15:59:06Z
32,699,693
7
2015-09-21T16:00:57Z
[ "python", "list" ]
I am trying to do the following with python and am having a strange behavior. Say I have the following list: ``` x = [5, 4, 3, 2, 1] ``` Now, I am doing something like: ``` x[x >= 3] = 3 ``` This gives: ``` x = [5, 3, 3, 2, 1] ``` Why does only the second element get changed? I was expecting: ``` [3, 3, 3, 2, 1]...
Because python will evaluated the `x>=3` as `True` and since `True` is equal to 1 so the second element of `x` will be convert to 3. For such aim you need to use a list comprehension : ``` >>> [3 if i >=3 else i for i in x] [3, 3, 3, 2, 1] ``` And if you want to know that why `x >= 3` returns True, based on followin...
Python map each integer within input to int
32,708,415
5
2015-09-22T04:30:48Z
32,708,428
8
2015-09-22T04:31:46Z
[ "python" ]
If I am given an input of 1 2 3 4 5, what is the standard method of splitting such input and maybe add 1 to each integer? I'm thinking something along the lines of splitting the input list and map each to an integer.
You may use list comprehension. ``` s = "1 2 3 4 5" print [int(i)+1 for i in s.split()] ```
Docker image error: "/bin/sh: 1: [python,: not found"
32,709,075
3
2015-09-22T05:32:36Z
32,709,181
7
2015-09-22T05:42:27Z
[ "python", "django", "ubuntu", "docker", "dockerfile" ]
I'm building a new Docker image based on the standard Ubuntu 14.04 image. Here's my *Dockerfile*: ``` FROM ubuntu:14.04 RUN apt-get update -y RUN apt-get install -y nginx git python-setuptools python-dev RUN easy_install pip ADD . /code WORKDIR /code RUN pip install -r requirements.txt # only 'django' for now ENV pro...
Use `"` instead of `'` in CMD. [(Documentation)](https://docs.docker.com/engine/reference/builder/#/cmd)
Python Inherit from one class but override method calling another class?
32,715,484
5
2015-09-22T11:18:50Z
32,716,126
7
2015-09-22T11:50:57Z
[ "python", "oop", "inheritance", "super" ]
Let say I have 3 classes: A, B and C. A is a base class for B and B is for C. Hierarchy is kept normally here, but for one method it should be different. For C class it should act like it was inherited from A. For example like this: ``` class A(object): def m(self): print 'a' class B(A): def m(self):...
There are in fact two ways to solve this: you can shortcut the call to `super()` and totally bypass the mro as in Mathias Ettinger's answer, or you can just issue the *correct* call to `super()`: ``` class C(B): def m(self): super(B, self).m() print 'c' ``` Remember that `super()` expects as first...
IPython 4 shell does not work with Sublime REPL
32,719,352
6
2015-09-22T14:16:40Z
32,770,759
11
2015-09-24T20:56:37Z
[ "python", "ipython", "sublimetext3", "jupyter", "sublimerepl" ]
I am having problems with running the IPython shell from the Sublime REPL package. Here is what I get: ``` C:\Anaconda\lib\site-packages\IPython\config.py:13: ShimWarning: The`IPython.config` package has been deprecated. You should import from traitlets.config instead. "You should import from traitlets.config inste...
With the release of IPython 4.0, the structure has completely changed, and is now implemented as a kernel for the [Jupyter](http://jupyter.org) core, which is capable of running IPython-like sessions using [many different languages](https://github.com/ipython/ipython/wiki/IPython-kernels-for-other-languages) other than...
Operation on 2d array columns
32,719,578
8
2015-09-22T14:27:11Z
32,719,624
7
2015-09-22T14:29:12Z
[ "python", "arrays", "2d" ]
I'd like to know if it's possible to apply a function (or juste an operation, such as replacing values) to column in a python 2d array, without using for loops. I'm sorry if the question has already been asked, but I couldn't find anything specific about my problem. I'd like to do something like : ``` array[:][2] = ...
You can do this easily with [`numpy`](http://www.numpy.org/) arrays. Example - ``` In [2]: import numpy as np In [3]: na = np.array([[1,2,3],[3,4,5]]) In [4]: na Out[4]: array([[1, 2, 3], [3, 4, 5]]) In [5]: na[:,2] = 10 In [6]: na Out[6]: array([[ 1, 2, 10], [ 3, 4, 10]]) In [7]: na[:,2] Out[7]: ...
Operation on 2d array columns
32,719,578
8
2015-09-22T14:27:11Z
32,719,862
7
2015-09-22T14:39:40Z
[ "python", "arrays", "2d" ]
I'd like to know if it's possible to apply a function (or juste an operation, such as replacing values) to column in a python 2d array, without using for loops. I'm sorry if the question has already been asked, but I couldn't find anything specific about my problem. I'd like to do something like : ``` array[:][2] = ...
Without numpy it can be done like this: ``` map(lambda x: x[:2] + [1] + x[3:], array) map(lambda x: x[:2] + my_func(x[2]) + x[3:], array) ```
Why is a class __dict__ a mappingproxy?
32,720,492
29
2015-09-22T15:08:59Z
32,720,603
31
2015-09-22T15:13:12Z
[ "python", "class", "python-3.x", "python-internals" ]
I wonder why a class `__dict__` is a `mappingproxy`, but an instance `__dict__` is just a plain `dict` ``` >>> class A: pass >>> a = A() >>> type(a.__dict__) <class 'dict'> >>> type(A.__dict__) <class 'mappingproxy'> ```
This helps the interpreter assure that the keys for class-level attributes and methods can only be strings. Elsewhere, Python is a "consenting adults language", meaning that dicts for objects are exposed and mutable by the user. However, in the case of class-level attributes and methods for classes, if we can guarante...
Flask application traceback doesn't show up in server log
32,722,143
6
2015-09-22T16:32:34Z
32,722,523
9
2015-09-22T16:53:14Z
[ "python", "nginx", "flask", "uwsgi" ]
I'm running my Flask application with uWSGI and nginx. There's a 500 error, but the traceback doesn't appear in the browser or the logs. How do I log the traceback from Flask? ``` uwsgi --http-socket 127.0.0.1:9000 --wsgi-file /var/webapps/magicws/service.py --module service:app --uid www-data --gid www-data --logto /...
Run in debug mode by adding this line before `app.run` gets called ``` app.debug = true ``` or by running with ``` app.run(debug=True) ``` Now a stack trace should appear in the terminal and the browser instead of a generic 500 error page. When using the new `flask` command to run the server, set the environment v...
How do I add a title to Seaborn Heatmap?
32,723,798
3
2015-09-22T18:03:15Z
32,724,156
7
2015-09-22T18:23:13Z
[ "python", "pandas", "ipython-notebook", "seaborn" ]
I want to add a title to a seaborn heatmap. Using Pandas and iPython Notebook code is below, ``` a1_p = a1.pivot_table( index='Postcode', columns='Property Type', values='Count', aggfunc=np.mean, fill_value=0) sns.heatmap(a1_p, cmap="YlGnBu") ``` the data is pretty straight forward: ``` In [179]: a1_p Out [179]: ...
`heatmap` is an `axes`-level function, so you should be able to use just `plt.title` or `ax.set_title`: ``` %matplotlib inline import numpy as np import os import seaborn as sns import matplotlib.pyplot as plt data = np.random.randn(10,12) ax = plt.axes() sns.heatmap(data, ax = ax) ax.set_title('lalala') plt.show()...
Building a RESTful Flask API for Scrapy
32,724,537
4
2015-09-22T18:43:30Z
32,784,312
8
2015-09-25T14:21:04Z
[ "python", "heroku", "flask", "scrapy", "twisted" ]
The API should allow arbitrary HTTP get requests containing URLs the user wants scraped, and then Flask should return the results of the scrape. The following code works for the first http request, but after twisted reactor stops, it won't restart. I may not even be going about this the right way, but I just want to p...
I think there is no a good way to create Flask-based API for Scrapy. Flask is not a right tool for that because it is not based on event loop. To make things worse, Twisted reactor (which Scrapy uses) [can't](http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#WhycanttheTwistedsreactorberestarted) be started/st...