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
Django Sites Framework initial setup
19,012,044
4
2013-09-25T18:02:39Z
19,013,555
9
2013-09-25T19:28:00Z
[ "python", "django", "frameworks", "sites" ]
I'm comfortable with fairly one-dimensional Django implementations, but now trying to understand the multi-sites-with-shared-stuff process. I've read through the Django Sites Framework and many posts on the topic, but I'm not getting the basics of how to start a second site that uses the same database, but presents it...
> Q1: Does the Sites Framework assume each site is a separate project or > a separate app? A Django website usually consists of multiple apps, so the "single app" approach wouldn't really work. But it's not helpful to think in terms of a separate project for every site either. The *only* thing that have to be separate...
Discovering Poetic Form with NLTK and CMU Dict
19,015,590
15
2013-09-25T21:35:25Z
19,040,560
7
2013-09-26T23:51:06Z
[ "python", "nltk" ]
**Edit: This code has been worked on and released as a basic module: <https://github.com/hyperreality/Poetry-Tools>** I'm a linguist who has recently picked up python and I'm working on a project which hopes to automatically analyze poems, including detecting the form of the poem. I.e. if it found a 10 syllable line w...
Welcome to stack overflow. I'm not that familiar with Python, but I see you have not received many answers yet so I'll try to help you with your queries. First some advice: You'll find that if you focus your questions your chances of getting answers are greatly improved. Your post is too long and contains several diff...
python tuple is immutable - so why can I add elements to it
19,015,698
4
2013-09-25T21:44:36Z
19,015,721
20
2013-09-25T21:46:16Z
[ "python", "tuples", "immutability" ]
I've been using Python for some time already and today while reading the following code snippet: ``` >>> a = (1,2) >>> a += (3,4) >>> a (1, 2, 3, 4) ``` I asked myself a question: how come python tuples are immutable and I can use an `+=` operator on them (or, more generally, why can I modify a tuple)? And I couldn't...
`5` is immutable, too. When you have an immutable data structure, `a += b` is equivalent to `a = a + b`, so a new number, tuple or whatever is created. When doing this with mutable structures, the structure is *changed*. Example: ``` >>> tup = (1, 2, 3) >>> id(tup) 140153476307856 >>> tup += (4, 5) >>> id(tup) 14015...
python command line arguments in main, skip script name
19,016,702
3
2013-09-25T23:10:50Z
19,016,716
8
2013-09-25T23:12:05Z
[ "python", "for-loop", "command-line-arguments", "argv", "sys" ]
This is my script ``` def main(argv): if len(sys.argv)>1: for x in sys.argv: build(x) if __name__ == "__main__": main(sys.argv) ``` so from the command line I write `python myscript.py commandlineargument` I want it to skip `myscript.py` and simply run `commandlineargument` through `commandlineargum...
Since [sys.argv](http://docs.python.org/2/library/sys.html#sys.argv) is a list, you can use slicing `sys.argv[1:]`: ``` def main(argv): for x in argv[1:]: build(x) if __name__ == "__main__": main(sys.argv) ``` But, if you can only have one script parameter, just get it by index: `sys.argv[1]`. But, y...
python: How to remove values from 2 lists based on what's in 1 list
19,017,638
4
2013-09-26T01:00:45Z
19,017,668
10
2013-09-26T01:05:16Z
[ "python" ]
I have 2 lists of numbers, one called `xVar` and the other called `yVar`. I will use these 2 elements to plot X and Y values on a graph. They both have the same number of elements. Normally, I would just plot ``` ax.scatter(xVar,yVar,s=2,color='tomato'); ``` I want to remove data from `yVar` that are over a certain ...
Whenever you want to do something to the corresponding values of two (or more) lists, that's what [`zip`](http://docs.python.org/3/library/functions.html#zip) is for. It gives you one list, of the corresponding values for each index. So, in this case, `zip` the two lists together, then filtered the zipped list, then u...
ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there
19,019,720
61
2013-09-26T04:59:00Z
19,042,026
54
2013-09-27T03:00:49Z
[ "python", "opencv", "dll", "path" ]
I have a situation very much like the one at [ImportError: DLL load failed: %1 is not a valid Win32 application](http://stackoverflow.com/questions/14629818/importerror-dll-load-failed-1-is-not-a-valid-win32-application), but the answer there isn't working for me. My Python code says: ``` import cv2 ``` But that lin...
[Unofficial Windows Binaries for Python Extension Packages](http://www.lfd.uci.edu/~gohlke/pythonlibs/) you can find any python libs from here
ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there
19,019,720
61
2013-09-26T04:59:00Z
25,398,326
16
2014-08-20T06:45:11Z
[ "python", "opencv", "dll", "path" ]
I have a situation very much like the one at [ImportError: DLL load failed: %1 is not a valid Win32 application](http://stackoverflow.com/questions/14629818/importerror-dll-load-failed-1-is-not-a-valid-win32-application), but the answer there isn't working for me. My Python code says: ``` import cv2 ``` But that lin...
Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the OPENCV library.
Scrapy, scrapping data inside a javascript
19,021,541
15
2013-09-26T07:04:58Z
19,051,261
16
2013-09-27T12:51:59Z
[ "python", "screen-scraping", "scrapy" ]
I am using scrapy (python) to screen scrape data from a website. However, the data i wanted wasn't inside the html itself, instead, it is from a javascript. So, my question is, How to get the values ( text values ) of such cases? This, is the site i'm trying to screen scrape: <https://www.mcdonalds.com.sg/locate-us/>...
*(I posted this to `scrapy-users` mailing list but by Paul's suggestion I'm posting it here as it complements the answer with the `shell` command interaction.)* Generally, websites that use a third party service to render some data visualization (map, table, etc) have to send the data somehow, and in most cases this d...
redis-py : What's the difference between StrictRedis() and Redis()?
19,021,765
31
2013-09-26T07:17:52Z
19,024,045
54
2013-09-26T09:14:32Z
[ "python", "redis" ]
I want using redis-py for caching some data. I can't find a suitable explain about difference between redis.StrictRedis() and redis.Redis() ! Is the Redis() equivalent to StrictRedis() ? In addition, i can't find any clear documentation about redis.StrictRedis() arguments in [Redis Python Docs](http://redis-py.readthe...
[This seems pretty clear](https://github.com/andymccurdy/redis-py): ``` redis-py exposes two client classes that implement these commands The StrictRedis class attempts to adhere to the official command syntax. ``` and ``` In addition to the changes above, the Redis class, a subclass of StrictRedis, overrides seve...
How to make dictionary read-only in python
19,022,868
11
2013-09-26T08:18:20Z
28,452,633
13
2015-02-11T10:58:59Z
[ "python", "dictionary" ]
I have a class like: ``` class A: def __init__(self): self.data = {} ``` and at some moment I want to prohibit `self.data` fields modification. I've read in [PEP-416 rejection notice](http://www.python.org/dev/peps/pep-0416/#rejection-notice) that there are a lot of ways to do it. So I'd like to find wha...
Use [`collections.Mapping`](https://docs.python.org/2/library/collections.html#collections.Mapping) e.g. ``` import collections class DictWrapper(collections.Mapping): def __init__(self, data): self._data = data def __getitem__(self, key): return self._data[key] def __len__(self): ...
How to make dictionary read-only in python
19,022,868
11
2013-09-26T08:18:20Z
31,049,908
11
2015-06-25T12:05:28Z
[ "python", "dictionary" ]
I have a class like: ``` class A: def __init__(self): self.data = {} ``` and at some moment I want to prohibit `self.data` fields modification. I've read in [PEP-416 rejection notice](http://www.python.org/dev/peps/pep-0416/#rejection-notice) that there are a lot of ways to do it. So I'd like to find wha...
This is full implementation of read-only dict: ``` class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise RuntimeError("Cannot modify ReadOnlyDict") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ clear = __readonly__ ...
error with reading float from two column text file into an array in Python
19,023,512
4
2013-09-26T08:49:19Z
19,023,597
7
2013-09-26T08:53:35Z
[ "python", "numpy", "matplotlib" ]
I have a text file which contains 2 columns separated by a tab, containing some data that I would like to read into arrays and perform some simple operations for instance plot the data. The data in the second column is in scientific notation and can takes extremely small values such varying from order of magnitude 10e-...
Don't reinvent the wheel!, it would be much more easy to use [`numpy.loadtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html): ``` >>> import numpy as np >>> import matplotlib.pyplot as plt >>> data = np.loadtxt('data.dat') >>> x1 = data[:,0] >>> y1 = data[:,1] >>> plt.plot(x1, y1) >>> plt.sho...
Convert float Series into an integer Series in pandas
19,026,684
8
2013-09-26T11:14:14Z
19,027,455
12
2013-09-26T11:49:58Z
[ "python", "pandas", "time-series" ]
I have the following data frame: ``` In [31]: rise_p Out[31]: time magnitude 0 1379945444 156.627598 1 1379945447 1474.648726 2 1379945448 1477.448999 3 1379945449 1474.886202 4 1379945699 1371.454224 ``` Now, I want to group rows which are within a minute. So I divide the time series with 100...
Try converting with astype: ``` new_re_df = [s.iloc[np.where(ts.astype(int) == int(i))] for i in ts] ``` **Edit** On suggestion by @Rutger Kassies a nicer way would be to cast series and then groupby: ``` rise_p['ts'] = (rise_p.time / 100).astype('int') ts_grouped = rise_p.groupby('ts') ... ```
pip fails to install numpy error code 1
19,027,324
2
2013-09-26T11:44:09Z
19,029,835
7
2013-09-26T13:35:09Z
[ "python", "python-2.7", "numpy", "pip" ]
I'm trying to install numpy using pip. When I type `pip install numpy` in the command prompt it goes to work but won't install the file and returns an error code `1`. I am using windows 8 64-Bit and python 2.7.This is the final bit of the error message ``` Cleaning up... Removing temporary dir c:\users\pim\appdata\lo...
Installing extension modules can be an issue with pip. This is why conda exists. conda is an open-source BSD-licensed cross-platform package manager. It can easily install NumPy. Two options: * Install Anaconda (<http://www.continuum.io/downloads>) * Install Miniconda (<http://repo.continuum.io/miniconda/index.html>)...
How to check that the anaconda package was properly installed
19,029,333
15
2013-09-26T13:14:21Z
19,030,049
12
2013-09-26T13:45:27Z
[ "python", "osx", "numpy", "installation", "anaconda" ]
I'm completely new to Python and want to use it for data analysis. I just installed Python 2.7 on my mac running OSX 10.8. I need the NumPy, SciPy, matplotlib and csv packages. I read that I could simply install the Anaconda package and get all in one. So I went ahead and downloaded/installed Anaconda 1.7. However, wh...
You can determine which version of python you are running when you get the error by looking at the results of `which python` from the commandline. It is likely that you are running the system version (although recent versions Mac OS X include numpy in its system python), rather than Anaconda's python distribution. If t...
How to auto assign public ip to EC2 instance with boto
19,029,588
16
2013-09-26T13:24:44Z
19,050,770
32
2013-09-27T12:27:25Z
[ "python", "amazon-web-services", "amazon-ec2", "boto" ]
I have to start a new machine with `ec2.run_instances` in a given subnet but also to have a public ip auto assigned (not fixed elastic ip). When one starts a new machine from the Amazon's web EC2 Manager via the Request Instance (Instance details) there is a check-box called **Assign Public IP** to Auto-assign Public ...
~~Interestingly enough, seems that not many people had this problem.~~ For me was very important to be able to do this right. Without this functionality one is not able to reach out to the internet from instances that are launched into a `nondefault subnet`. The boto documentation provided no help, there was a related...
Programmatically importing module via importlib - __path__ not set?
19,030,115
7
2013-09-26T13:48:38Z
23,797,282
11
2014-05-22T03:18:39Z
[ "python", "python-3.x", "python-import" ]
I'm trying to import a sub-module programmatically. My file tree looks like this: ``` oopsd/__init__.py oopsd/oopsd.py oopsd/driver/__init__.py oopsd/driver/optiups.py ``` The optiups.py simply prints "Hello World". The oopsd.py looks like this: ``` import importlib importlib.import_module('oopsd.driver.optiups') `...
This is an old question, but since it was bumped, the other answer is totally wrong, and this is a common problem: You're probably doing this. ``` python oopsd/oopsd.py ``` Don't do this. :) Specifically, **NEVER** try to directly run a file that's part of a parent package. When you run `python FILENAME`, Python ad...
How to access the first and the last elements in a dictionary python?
19,030,179
3
2013-09-26T13:51:01Z
19,030,374
9
2013-09-26T13:59:46Z
[ "python" ]
Before posting, I have already gone through [Python access to first element in dictionary](http://stackoverflow.com/questions/3097866/python-access-to-first-element-in-dictionary), butI'm uncertain about this. I have a long dictionary and I've to get the values of its first and last keys. I can use `dict[dict.keys()[0...
Use an [`OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict), because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how: ``` # import the right class from collections import OrderedDict # create and fill the dictionary d = Orde...
pep8 warning on regex string in Python, Eclipse
19,030,952
13
2013-09-26T14:25:47Z
19,030,982
22
2013-09-26T14:27:02Z
[ "python", "string", "eclipse", "pydev", "pep8" ]
Why is pep8 complaining on the next string in the code? ``` import re re.compile("\d{3}") ``` The warning I receive: ``` ID:W1401 Anomalous backslash in string: '\d'. String constant might be missing an r prefix. ``` Can you explain what is the meaning of the message? What do I need to change in the code so that t...
`"\d"` is same as `"\\d"` because there's no escape sequence for `d`. But it is not clear for the reader of the code. But, consider `\t`. `"\t"` represent tab chracter, while `r"\t"` represent literal `\` and `t` character. So use raw string when you mean literal `\` and `d`: ``` re.compile(r"\d{3}") ``` or escape ...
Get background model from BackgroundSubtractorMOG2 in python
19,031,836
3
2013-09-26T15:03:11Z
19,252,068
7
2013-10-08T15:32:31Z
[ "python", "opencv", "mog" ]
I need to get the background model of a Mixture of Gaussian with opencv. I know that there is a method called getBackgroundImage in C++ I searched if it is possible to get it in python interface but I haven't get good result. I Tried opencv 3.0.0-dev because it has BackgroundSubtractorMOG2 implementation, but help() fu...
**Zaw Lin**'s solution in Ubuntu 12.04: The main difference is that the result (`fg` / `bg`) images are created/allocated in python and then passed down to the c++ lib. Zaw Lin's solution was giving me errors (errno 139 - SIG\_SEGV), because of the app was accessing invalid memory zones. Hope it saves someone a couple...
Skip unittest test without decorator syntax
19,031,953
14
2013-09-26T15:08:58Z
19,032,932
7
2013-09-26T15:50:53Z
[ "python", "unit-testing" ]
I have a suite of tests that I have loaded using TestLoader's (from the unittest module) loadTestsFromModule() method, i.e., ``` suite = loader.loadTestsFromModule(module) ``` This gives me a perfectly ample list of tests that works fine. My problem is that the test harness I'm working with sometimes needs to skip ce...
Using [`unittest.TestCase.skipTest`](http://docs.python.org/2/library/unittest.html#unittest.TestCase.skipTest): ``` import unittest class TestFoo(unittest.TestCase): def setUp(self): print('setup') def tearDown(self): print('teardown') def test_spam(self): pass def test_egg(self): pass def test_h...
How to call a function on a running Python thread
19,033,818
8
2013-09-26T16:36:14Z
19,034,408
28
2013-09-26T17:10:20Z
[ "python", "python-2.7" ]
Say I have this class that spawns a thread: ``` import threading class SomeClass(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: pass def doSomething(self): pass def doSomethingElse(self): pass ``` I want ...
You can't directly do what you want. The background thread is running its `run` function, which just loops forever, so it can't possibly do anything else. You can, of course, call the class's methods on your own thread, but that presumably isn't what you want here. --- The reason frameworks like Qt, .NET, or Cocoa c...
Python Multiprocessing: pool.map vs using queues
19,034,842
10
2013-09-26T17:32:13Z
19,035,025
9
2013-09-26T17:42:53Z
[ "python", "multithreading", "queue" ]
I am trying to use the `multiprocessing` package for `Python`. In looking at tutorials, the clearest and most straightforward technique seems to be using `pool.map`, which allows the user to easily name the number of processes and pass `pool.map` a function and a list of values for that function to distribute across th...
The `pool.map` technique is a "subset" of the technique with queues. That is, without having `pool.map` you can easily implement it using `Pool` and `Queue`. That said, using queues gives you much more flexibility in controlling your pool processes, i.e. you can make it so that particular types of messages are read onl...
Installing python modules on Ubuntu
19,034,959
12
2013-09-26T17:38:51Z
19,035,050
19
2013-09-26T17:44:55Z
[ "python", "linux", "ubuntu", "python-3.x", "package" ]
I need to install some modules for python on Ubuntu Linux 12.04. I want pygame and livewires but I'm not sure how to install them. I have the py file for livewires, which has been specially edited (from a book I'm reading) and I want to install it but I'm not sure how to, I also want to install pygame.
There are two nice ways to install Python packages on Ubuntu (and similar Linux systems): ``` sudo apt-get install python-pygame ``` to use the Debian/Ubuntu package manager APT. This only works for packages that are shipped by Ubuntu, unless you change the APT configuration, and in particular there seems to be no Py...
How to select element with Selenium Python xpath
19,035,186
6
2013-09-26T17:51:20Z
19,035,495
14
2013-09-26T18:06:28Z
[ "python", "xpath", "selenium" ]
consider following HTML: ``` <div id='a'> <div> <a class='click'>abc</a> </div> </div> ``` I want to click abc, but the wrapper div could change, so ``` driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']") ``` is not what I want i tried: ``` driver.get_element_by_xpath("//div[@id='a']").ge...
**HTML** ``` <div id='a'> <div> <a class='click'>abc</a> </div> </div> ``` You could use the **XPATH** as : ``` //div[@id='a']//a[@class='click'] ``` **output** ``` <a class="click">abc</a> ``` That said your Python code should be as : ``` driver.find_element_by_xpath("//div[@id='a']//a[@class='click']...
Why isn't my user defined exception being handled properly?
19,035,244
2
2013-09-26T17:54:13Z
19,035,284
9
2013-09-26T17:56:07Z
[ "python" ]
I'm wondering a user defined exception I've raised in my python program from within a class isn't being handled by the correct exception handler within my `main()`. Say I have a class: ``` class Pdbalog: # Constructor def __init__(self, logtype): if logtype == 1 or logtype == 2: # These are...
`Exception("Invalid Logtype")` is still just an `Exception`, just now with an error message. `"Invalid Logtype"` isn't an error, just a `str`, so you can't catch it. Try: ``` class InvalidLogtype(Exception): pass try: raise InvalidLogType except InvalidLogType: pass ``` Note that you can catch based on erro...
Why does scipy.ndimage.io.imread return PngImageFile, not an array of values
19,036,283
6
2013-09-26T18:49:24Z
19,774,150
7
2013-11-04T18:05:22Z
[ "python", "scipy" ]
I have two different machines with scipy 0.12 and PIL installed. On one machine, when I try to read a .png file, it returns an array of integers with size (w x h x 3): ``` In[2]: from scipy.ndimage.io import imread In[3]: out = imread(png_file) In[4]: out.shape Out[4]: (750, 1000, 4) ``` On the other machine, usin...
It's likely that you have an incomplete Python Imaging Library (PIL) install, which SciPy relies on to read the image. PIL relies on `libjpeg` to load JPEG images and `libz` to load PNG images, but can be installed without either (in which case it is unable to load whatever images the libraries are missing for). I had...
pelican: How to embed html and javascript in markdown
19,036,718
12
2013-09-26T19:14:20Z
19,036,909
15
2013-09-26T19:24:26Z
[ "python", "html", "markdown", "pelican" ]
I want to embed a few html elements and javascript in a blog post. This is my markdown file. ``` Title: Foo Tags: Bar Some Content here <div id="foo"> </div> <script type="text/javascript" src="static/js/bar.js"> </script> ``` But pelican is wrapping the html tags in a `pre`. So the code i...
Probably the reason its not working is that you've indented your code, which means that it gets inserted as a `<code>` block in the HTML, according to the Markdown spec: [daringfireball.net/projects/markdown/syntax#precode](http://daringfireball.net/projects/markdown/syntax#precode)
Forwarding an incoming call to multiple numbers using call screening without round robin
19,038,251
4
2013-09-26T20:37:49Z
19,116,643
9
2013-10-01T12:49:51Z
[ "python", "twilio", "twiml" ]
**Background** I'm attempting to implement call screening for my twilio app - i.e. a person presses a key to accept a call. I have seen a couple of examples of this in action (e.g. [How to use twilio to guarantee a live answer or voicemail?](http://stackoverflow.com/questions/17690425/how-to-use-twilio-to-guarantee-a-...
Twilio Evangelist here, When you receive your initial call (let's call it the customer) ask the them for some information using `<Gather>`, or play them some holding music, whatever you think works best: ``` <Response> <Play loop="0">/my_music.mp3</Play> </Response> ``` Then, use the REST API to initiate 3 outboun...
elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7
19,039,080
6
2013-09-26T21:31:13Z
19,039,167
8
2013-09-26T21:38:09Z
[ "python", "arrays", "loops", "datetime", "numpy" ]
I have a numpy array called `dt`. Each element is of type `datetime.timedelta`. For example: ``` >>>dt[0] datetime.timedelta(0, 1, 36000) ``` how can I convert `dt` into the array `dt_sec` which contains only seconds without looping? my current solution (which works, but I don't like it) is: ``` dt_sec = zeros((len(...
``` import numpy as np helper = np.vectorize(lambda x: x.total_seconds()) dt_sec = helper(dt) ```
elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7
19,039,080
6
2013-09-26T21:31:13Z
19,039,219
8
2013-09-26T21:41:48Z
[ "python", "arrays", "loops", "datetime", "numpy" ]
I have a numpy array called `dt`. Each element is of type `datetime.timedelta`. For example: ``` >>>dt[0] datetime.timedelta(0, 1, 36000) ``` how can I convert `dt` into the array `dt_sec` which contains only seconds without looping? my current solution (which works, but I don't like it) is: ``` dt_sec = zeros((len(...
`numpy` has its own `datetime` and `timedelta` formats. Just use them ;). Set-up for example: ``` import datetime import numpy times = numpy.array([datetime.timedelta(0, 1, 36000)]) ``` Code: ``` times.astype("timedelta64[ms]").astype(int) / 1000 #>>> array([ 1.036]) ``` Since people don't seem to realise that th...
Load high-dimensional R dataset into Pandas DataFrame
19,039,356
7
2013-09-26T21:51:48Z
19,039,585
7
2013-09-26T22:10:15Z
[ "python", "pandas", "rpy2" ]
Some [R datasets](http://stat.ethz.ch/R-manual/R-devel/library/datasets/html/00Index.html) can be [loaded into a Pandas DataFrame or Panel](http://pandas.pydata.org/pandas-docs/dev/r_interface.html#transferring-r-data-sets-into-python) quite easily: ``` import pandas.rpy.common as com infert = com.load_data('infert') ...
Using @joran's very helpful suggestion, after installing the `reshape` package with ``` % sudo R R> install.packages('reshape') ``` I managed to load the `Titanic` dataset into a Pandas DataFrame with: ``` import pandas as pd import pandas.rpy.common as com import rpy2.robjects as ro r = ro.r r('library(reshape)') ...
Scraping Data from Facebook with Python
19,041,827
3
2013-09-27T02:37:18Z
19,041,974
11
2013-09-27T02:54:47Z
[ "python", "facebook", "web-scraping", "beautifulsoup", "mechanize" ]
I've been trying for several day now (unsuccessfully) to scrape cities from about 500 Facebook URLs. However, Facebook handles its data in a very strange way and I can't figure out what's going on under the hood to understand what I need to do. Essentially the problem is that Facebook displays very different amounts o...
The **right** way to do this is to use the facebook API. For various business, security, and privacy reasons they go out of their way to make scraping data tricky. If you insist on scraping I would try to log in first using mechanize to submit the form. I've never tried to do this with facebook, but alot of websites h...
Scraping Data from Facebook with Python
19,041,827
3
2013-09-27T02:37:18Z
19,041,985
11
2013-09-27T02:56:43Z
[ "python", "facebook", "web-scraping", "beautifulsoup", "mechanize" ]
I've been trying for several day now (unsuccessfully) to scrape cities from about 500 Facebook URLs. However, Facebook handles its data in a very strange way and I can't figure out what's going on under the hood to understand what I need to do. Essentially the problem is that Facebook displays very different amounts o...
You should look into using [facepy](https://github.com/jgorset/facepy) by [Johannes Gorset](https://twitter.com/jgorset). He has done a brilliant job. I used it when I worked on a small Facebook app for a personal project.
Change the values in a tuple in a list
19,042,028
3
2013-09-27T03:01:18Z
19,042,048
10
2013-09-27T03:04:45Z
[ "python", "list", "tuples" ]
I have a two-dimensional list containing three-element tuple. ``` image = [[(15, 103, 255), (0, 3, 19)],[(22, 200, 1), (8, 8, 8)],[(0, 0, 0), (5, 123, 19)]] ``` I want to add one to each element. ``` def get_elements(image): for i in range(len(image)-1) : m = image[i] for j in range(len(m)-1) : ...
Tuples are immutable. You can't modify them directly, so the best bet is to generate a new list with new tuples. ``` >>> image [[(15, 103, 255), (0, 3, 19)], [(22, 200, 1), (8, 8, 8)], [(0, 0, 0), (5, 123, 19)]] >>> [[(r+1,g+1,b+1) for r,g,b in row] for row in image] [[(16, 104, 256), (1, 4, 20)], [(23, 201, 2), (9, 9...
Python 3.3 - Connect with Oracle database
19,042,353
4
2013-09-27T03:45:38Z
19,042,569
7
2013-09-27T04:10:55Z
[ "python", "oracle", "python-3.3" ]
Is there a module for python 3.3 to connect with Oracle Databases? Which is the easiest to use? Something like the mysql module, only works with Oracle. Preferably version 10g, but 11g will do just fine.
**There is:** `cx_Oracle` ``` # Install --> You should have oracle installed otherwise exception will be raised pip install cx_Oracle import cx_Oracle con = cx_Oracle.connect('pythonhol/[email protected]/orcl') print con.version con.close() ``` <http://www.orafaq.com/wiki/Python> <http://www.oracle.com/technetwo...
Conda: Installing / upgrading directly from github
19,042,389
26
2013-09-27T03:50:44Z
19,071,214
17
2013-09-28T20:13:10Z
[ "python", "github", "pip", "package-managers", "conda" ]
Can I install/upgrade packages from GitHub using [conda](http://www.continuum.io/blog/conda)? For example, with `pip` I can do: ``` pip install git+git://github.com/scrappy/scrappy@master ``` to install `scrappy` directly from the `master` branch in GitHub. Can I do something equivalent with conda? If this is not p...
`conda` doesn't support this directly because it installs from binaries, whereas git install would be from source. `conda build` does support recipes that are built from git. On the other hand, if all you want to do is keep up-to-date with the latest and greatest of a package, using pip inside of Anaconda is just fine,...
Conda: Installing / upgrading directly from github
19,042,389
26
2013-09-27T03:50:44Z
32,799,944
12
2015-09-26T17:29:26Z
[ "python", "github", "pip", "package-managers", "conda" ]
Can I install/upgrade packages from GitHub using [conda](http://www.continuum.io/blog/conda)? For example, with `pip` I can do: ``` pip install git+git://github.com/scrappy/scrappy@master ``` to install `scrappy` directly from the `master` branch in GitHub. Can I do something equivalent with conda? If this is not p...
There's better support for this now through `conda-env`. You can, for example, now do: ``` name: sample_env channels: dependencies: - requests - bokeh>=0.10.0 - pip: - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master" `...
python setup.py build_ext --include-dirs=/usr/include/gdal/ not work
19,045,596
3
2013-09-27T07:54:39Z
19,046,818
7
2013-09-27T09:03:17Z
[ "python", "gdal", "virtualenvwrapper" ]
I'm trying to install GDAL ina virstualenvwrapper, following several guides and StackOverflow answers. I'm on ubuntu 13.04 I istalled `ligbdal1` and `libgdal1-dev` Inside my virtualenv I tried that: ``` pip install --no-install GDAL ``` ...and after: ``` python setup.py build_ext --include-dirs=/usr/include/gdal/ ...
It appears the `libgdal1` package on Ubuntu 13.04 is already out of date. The Python cheeseshop (PyPi, which is what pip uses) provides a 1.10.0 wrapper, while [the 13.04 package list](http://packages.ubuntu.com/raring/libgdal-dev) shows that libgdal version 1.9.0 is provided. Apparently, in 1.10, a number of new funct...
Python how to know if a record inserted successfully or not
19,046,202
7
2013-09-27T08:29:08Z
19,046,257
12
2013-09-27T08:32:29Z
[ "python", "mysql", "mysql-connector" ]
I'm using Python MySQL Connector, I inserted a record into database, and it was successful. But in Python code, how can I know if it is inserted or not? My Table does not have a primary key. ``` def insert(params) : db_connection = Model.get_db_connection() cursor = db_connection.cursor() try : cur...
You can use [`.rowcount`](http://www.python.org/dev/peps/pep-0249/#rowcount) attribute: ``` cursor.execute("""INSERT INTO `User`(`UID`, `IP`) VALUES(%s,%s);""", params) print("affected rows = {}".format(cursor.rowcount)) ``` > **.rowcount** This read-only attribute specifies the number of rows that > the last .execut...
How to read the last MB of a very large text file
19,046,369
11
2013-09-27T08:39:12Z
19,046,457
20
2013-09-27T08:43:31Z
[ "python", "file", "text", "jython" ]
I am trying to find a string near the end of a text file. The problem is that the text file can vary greatly in size. From 3MB to 4GB. But everytime I try to run a script to find this string in a text file that is around 3GB, my computer runs out of memory. SO I was wondering if there was anyway for python to find the ...
Use [file.seek()](https://docs.python.org/2/library/stdtypes.html#file.seek): ``` import os find_str = "ERROR" error = False # Open file with 'b' to specify binary mode with open(file_directory, 'rb') as file: file.seek(-1024 * 1024, os.SEEK_END) # Note minus sign if find_str in file.read(): error = T...
Python setup.py develop vs install
19,048,732
135
2013-09-27T10:39:13Z
19,048,754
169
2013-09-27T10:40:46Z
[ "python", "setuptools" ]
Two options in setup.py `develop` and `install` are confusing me. According to this [site](http://www.siafoo.net/article/77#id10), using `develop` creates a special link to site-packages directory. People have suggested that I use `python setup.py install` for a fresh installation and `python setup.py develop` after a...
`python setup.py install` is used to install (typically third party) packages that you're not going to be developing/editing/debugging yourself. For your own stuff, you want to get your package installed and then be able to frequently edit your code and **not** have to re-install your package—this is exactly what `p...
Python setup.py develop vs install
19,048,732
135
2013-09-27T10:39:13Z
26,588,871
47
2014-10-27T13:40:06Z
[ "python", "setuptools" ]
Two options in setup.py `develop` and `install` are confusing me. According to this [site](http://www.siafoo.net/article/77#id10), using `develop` creates a special link to site-packages directory. People have suggested that I use `python setup.py install` for a fresh installation and `python setup.py develop` after a...
From the [documentation](http://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode). The `develop` will not install the package but it will create a `.egg-link` in the deployment directory back to the project source code directory. So it's like installing but instead of copying to the `site-packages`...
Setting global font size in kivy
19,052,905
4
2013-09-27T14:10:51Z
19,066,530
7
2013-09-28T11:39:36Z
[ "python", "properties", "kivy", "font-size" ]
What is the preferred way, whether through python or the kivy language, to set the global font size (i.e. for Buttons and Labels) in kivy? What is a good way to dynamically change the global font size setting in proportion to the size of the window?
``` <Label>: font_size: dp(20) font_name: 'path/to/funcy/font.ttf' ``` Will set the font name and the font size globally for any widget that uses Label as it's base(TextInput and a few other widgets don't).
Python if statement checking for a £ pound sign in a string?
19,053,323
3
2013-09-27T14:29:55Z
19,053,347
7
2013-09-27T14:31:08Z
[ "python", "python-2.7", "if-statement", "unicode" ]
I have the following line which is causing me problems: `if "Total £" in studentfees:` returns: `UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 4: ordinal not in range(128)` How can I get around this? Thanks in advance - Hyflex
You can add the following to the file: ``` # -*- coding: utf-8 -*- ``` Also: ``` if u"Total £" in studentfees: ```
Converting Snake Case to Lower Camel Case (lowerCamelCase)
19,053,707
17
2013-09-27T14:48:06Z
19,053,800
30
2013-09-27T14:52:41Z
[ "python", "python-2.7" ]
What would be a good way to convert from snake case (`my_string`) to lower camel case (myString) in Python 2.7? The obvious solution is to split by underscore, capitalize each word except the first one and join back together. However, I'm curious as to other, more idiomatic solutions or a way to use `RegExp` to achie...
``` def to_camel_case(snake_str): components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + "".join(x.title() for x in components[1:]) ``` Example: ``` In [11]: to_camel_case('snake...
Can I asynchronously delete a file in Python?
19,056,837
3
2013-09-27T17:37:53Z
19,057,043
8
2013-09-27T17:48:56Z
[ "python", "multithreading" ]
I have a long running python script which creates and deletes temporary files. I notice there is a non-trivial amount of time spent on file deletion, but the only purpose of deleting those files is to ensure that the program doesn't eventually fill up all the disk space during a long run. Is there a cross platform mech...
You can try delegating deleting the files to another thread or process. Using a newly spawned thread: ``` thread.start_new_thread(os.remove, filename) ``` Or, using a process: ``` # create the process pool once process_pool = multiprocessing.Pool(1) results = [] # later on removing a file in async fashion # note: ...
Specifying the line width of the legend frame, in matplotlib
19,058,485
5
2013-09-27T19:18:45Z
28,295,797
7
2015-02-03T09:47:58Z
[ "python", "matplotlib" ]
In matplotlib, how do I specify the line width and color of a legend frame?
For the width: `legend.get_frame().set_linewidth(w)` For the color: `legend.get_frame().set_edgecolor("red")`
OpenCV wont' capture from MacBook Pro iSight
19,059,459
3
2013-09-27T20:23:03Z
19,084,592
7
2013-09-29T23:43:29Z
[ "python", "osx", "opencv", "isight" ]
Since a couple of days I can't open my iSight camera from inside a opencv application any more. cap = cv2.VideoCapture(0) returns, and cap.isOpened() returns true. However, cap.grab() just returns false. Any ideas? Example Code: ``` import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) rval = True while r...
I am having the exact same problem using the same code however I'm on OSX 10.6. Any help would be greatly appreciated. **Edit:** This is how I got the camera working for your code: ``` import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) rval, frame = vc.read() while True: if frame is not None: ...
Json print output in python different from write output because of escaped characters
19,059,627
5
2013-09-27T20:34:34Z
19,059,672
9
2013-09-27T20:37:13Z
[ "python", "json", "csv" ]
I have a pipe delimited file I am trying to convert to json using python (2.7). The code reads the text file, converts it based on the delimiter and then converts it to json. When I run the code, the output in my terminal window is correct. However, when I write to a file the escape slashes \ are being added to the ou...
You are encoding your data to JSON *twice*. `out` is *already* JSON encoded, but you encode it again by dumping the JSON string to `outfile`. Just write it out without encoding again: ``` with open('data.json', 'w') as outfile: outfile.write(out) ``` Do remove the `ensure_ascii=False` option, as `json.dumps()` w...
More efficient matplotlib stacked bar chart - how to calculate bottom values
19,060,144
10
2013-09-27T21:12:47Z
19,060,351
10
2013-09-27T21:29:11Z
[ "python", "numpy", "matplotlib", "stackedbarseries" ]
I need some help making a set of stacked bar charts in python with matlibplot. My basic code is below but my problems is how to generate the value for **bottom** for any element beyond the 2nd one **efficiently**. I can get the example graph to stack correctly (always a,b,c,d from bottom to top) ``` import numpy as np...
Converting your values to numpy arrays will make your life easier: ``` data = np.array([a, b, c, d]) bottom = np.cumsum(data, axis=0) colors = ('#ff3333', '#33ff33', '#3333ff', '#33ffff') plt.bar(ind, data[0], color=colors[0]) for j in xrange(1, data.shape[0]): plt.bar(ind, data[1], color=colors[j], bottom=bottom...
More efficient matplotlib stacked bar chart - how to calculate bottom values
19,060,144
10
2013-09-27T21:12:47Z
20,983,033
24
2014-01-07T22:12:14Z
[ "python", "numpy", "matplotlib", "stackedbarseries" ]
I need some help making a set of stacked bar charts in python with matlibplot. My basic code is below but my problems is how to generate the value for **bottom** for any element beyond the 2nd one **efficiently**. I can get the example graph to stack correctly (always a,b,c,d from bottom to top) ``` import numpy as np...
I have just recently faced the same problem. Afterwards I decided to wrap it all up in a nice class. For anyone interested you get an implementation of a stacked bar graph class here: <https://github.com/minillinim/stackedBarGraph> It allows scaled stacked graphs as well as setting bar widths and set heights (with sc...
Very poor weakref performance in Python/SQL Alchemy
19,061,330
5
2013-09-27T22:55:55Z
19,128,021
7
2013-10-02T00:08:25Z
[ "python", "memory-leaks", "sqlalchemy" ]
I've spent the day trying to debug a memory problem in my Python script. I'm using SQL Alchemy as my ORM. There are several confounding issues here, and I'm hoping that if I list them all out, somebody will be able to point me in the right direction. In order to achieve the performance I'm looking for, I read in all t...
800K ORM objects is very large. These are Python objects, each of which has a `__dict__` as well as an `_sa_instance_state` attribute which is itself an object, which then has weakrefs and other things inside of it, then the `Session` has more than one weakref to your object - an ORM object is identity tracked, a featu...
Python - Crypto.Cipher/Pycrypto on Mac?
19,062,968
2
2013-09-28T03:39:05Z
19,102,883
7
2013-09-30T20:09:21Z
[ "python", "osx", "pycrypto" ]
After a bit of googling around, I see this issue is pretty common but has no direct answers. Trying to use Pycrypto on my Mac 10.8.5. Installed it through Pip, Easy\_install, and manually with setup.py yet when I try to import it, it says it can't find the module. Anyone else have an issue like this?
For those having this issue on Mac, for something reason Pip, easy\_install, and even doing it manually installs Crypto with a lowercase 'c' in to site-packages. By browsing in to site-packages and renaming 'crypto' to 'Crypto', it solves the issues with other libaries.
How to create a dictionary of dictionaries of dictionaries in Python
19,063,086
6
2013-09-28T03:59:30Z
19,063,131
11
2013-09-28T04:08:30Z
[ "python", "dictionary" ]
So I am taking a natural language processing class and I need to create a trigram language model to generate random text that looks "realistic" to a certain degree based off of some sample data. Essencially need to create a "trigram" to hold the various 3 letter grammar word combinations. My professor hints that this ...
I've tried nested `defaultdict`'s before and the solution seems to be a `lambda` call: ``` trigram = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) trigram['a']['b']['c'] += 1 ``` It's not pretty, but I suspect the nested dictionary suggestion is for efficient lookup.
In what situation do we need to use `multiprocessing.Pool.imap_unordered`?
19,063,238
6
2013-09-28T04:24:12Z
19,063,758
14
2013-09-28T05:47:09Z
[ "python" ]
The ordering of results from the returned iterator of `imap_unordered` is arbitrary, and it doesn't seem to run faster than `imap`(which I check with the following code), so why would one use this method? ``` from multiprocessing import Pool import time def square(i): time.sleep(0.01) return i ** 2 p = Pool(...
Using `pool.imap_unordered` instead of `pool.imap` will not have a large effect on the total running time of your code. It might be a little faster, but not by too much. What it may do, however, is make the interval between values being available in your iteration more even. That is, if you have operations that can ta...
Python windows path slash
19,065,115
3
2013-09-28T08:49:28Z
19,065,182
7
2013-09-28T08:57:46Z
[ "python" ]
I am facing a very basic problem using directory path in python script. When I do copy path from the windows explorer, it uses backward slash as path seperator which is causing problem. ``` >>> x 'D:\testfolder' >>> print x D: estfolder >>> print os.path.normpath(x) D: estfolder >>> print os.path.abspath(x) ...
Python interprets a `\t` in a string as a tab character; hence, `"D:\testfolder"` will print out with a tab between the `:` and the `e`, as you noticed. If you want an actual backslash, you need to *escape* the backslash by entering it as `\\`: ``` >>> x = "D:\\testfolder" >>> print x D:\testfolder ``` However, for c...
why multiple assignments and single assignments behave differently in python
19,067,252
4
2013-09-28T13:02:17Z
19,067,302
13
2013-09-28T13:06:51Z
[ "python" ]
I was working with queue in python when I had a error in code even while the code looked very perfect to me but latter when I changed assignment style all of sudden the code started working. The code looked some what like this before. ``` x=y=Queue() x.put("a") x.put("b") print y.get() ``` later i cha...
Variables in Python are references, or names, not like variables in C etc. This code: ``` x=y=Queue() ``` means "allow the name `y` to reference an object in memory made by calling `Queue()`, and allow the name `x` to reference the object that `y` is pointing to." This means both variables refer to the same object -...
Access Django models with scrapy: defining path to Django project
19,068,308
24
2013-09-28T15:02:34Z
19,073,347
46
2013-09-29T00:54:40Z
[ "python", "django", "django-models", "scrapy" ]
I'm very new to Python and Django. I'm currently exploring using Scrapy to scrape sites and save data to the Django database. My goal is to run a spider based on domain given by a user. I've written a spider that extracts the data I need and store it correctly in a json file when calling ``` scrapy crawl spider -o it...
I think the main misconception is the package path vs the settings module path. In order to use django's models from an external script you need to set the `DJANGO_SETTINGS_MODULE`. Then, this module has to be *importable* (i.e. if the settings path is `myproject.settings`, then the statement `from myproject import set...
Does a slicing operation give me a deep or shallow copy?
19,068,707
5
2013-09-28T15:47:46Z
19,068,714
10
2013-09-28T15:48:51Z
[ "python", "list", "copy", "deep-copy" ]
The [official Python docs](http://docs.python.org/2/library/copy.html) say that using the slicing operator and assigning in Python makes a shallow copy of the sliced list. But when I write code for example: ``` o = [1, 2, 4, 5] p = o[:] ``` And when I write: ``` id(o) id(p) ``` I get different id's and also append...
You are creating a *shallow* copy, because nested values are not copied, merely referenced. A *deep* copy would create copies of the values referenced by the list too. Demo: ``` >>> lst = [{}] >>> lst_copy = lst[:] >>> lst_copy[0]['foo'] = 'bar' >>> lst_copy.append(42) >>> lst [{'foo': 'bar'}] >>> id(lst) == id(lst_c...
How to overplot a line on a scatter plot in python?
19,068,862
15
2013-09-28T16:05:10Z
19,069,001
33
2013-09-28T16:20:36Z
[ "python", "numpy", "matplotlib" ]
I have two vectors of data and I've put them into `matplotlib.scatter()`. Now I'd like to over plot a linear fit to these data. How would I do this? I've tried using `scikitlearn` and `np.scatter`.
``` import numpy as np import matplotlib.pyplot as plt # sample data x = np.arange(10) y = 5*x + 10 # fit with np.polyfit m, b = np.polyfit(x, y, 1) plt.plot(x, y, '.') plt.plot(x, m*x + b, '-') ``` ![enter image description here](http://i.stack.imgur.com/rnWmJ.png)
How to overplot a line on a scatter plot in python?
19,068,862
15
2013-09-28T16:05:10Z
19,069,028
9
2013-09-28T16:22:44Z
[ "python", "numpy", "matplotlib" ]
I have two vectors of data and I've put them into `matplotlib.scatter()`. Now I'd like to over plot a linear fit to these data. How would I do this? I've tried using `scikitlearn` and `np.scatter`.
I'm partial to [scikits.statsmodels](http://statsmodels.sourceforge.net/stable/). Here an example: ``` import statsmodels.api as sm import numpy as np import matplotlib.pyplot as plt X = np.random.rand(100) Y = X + np.random.rand(100)*0.1 results = sm.OLS(Y,sm.add_constant(X)).fit() print results.summary() plt.sca...
Python requests library how to pass Authorization header with single token
19,069,701
15
2013-09-28T17:25:29Z
19,072,991
24
2013-09-29T00:01:02Z
[ "python", "get", "authorization", "token", "python-requests" ]
I have a request URI and a token. If I use: ``` curl -s "<MY_URI>" -H "Authorization: TOK:<MY_TOKEN>" ``` etc., I get a 200 and view the corresponding JSON data. So, I installed requests and when I attempt to access this resource I get a 403 probably because I do not know the correct syntax to pass that token. Can an...
In python: ``` ('<MY_TOKEN>') ``` is equivalent to ``` '<MY_TOKEN>' ``` And requests interprets ``` ('TOK', '<MY_TOKEN>') ``` As you wanting requests to use Basic Authentication and craft an authorization header like so: ``` 'VE9LOjxNWV9UT0tFTj4K' ``` Which is the base64 representation of `'TOK:<MY_TOKEN>'` To...
python - os.getenv and os.environ don't see environment variables of my bash shell
19,070,615
19
2013-09-28T19:02:30Z
19,070,674
45
2013-09-28T19:08:44Z
[ "python", "bash", "environment-variables", "pythonpath" ]
I am on ubuntu 13.04, bash, python2.7.4 **The interpreter doesn't see variables I set.** Here is an example: ``` $ echo $A 5 $ python -c 'import os; print os.getenv( "A" )' None $ python -c 'import os; print os.environ[ "A" ]' Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib...
Aha! the solution is simple! I was setting variables with plain `$ A=5` command; when you use `$ export B="kkk"` everything is fine. That is [beca](http://stackoverflow.com/questions/1158091/bash-defining-a-variable-with-or-without-export)[use](https://www.gnu.org/software/bash/manual/html_node/Environment.html#Envir...
numpy/scipy analog of matlab's fminsearch
19,070,943
8
2013-09-28T19:40:16Z
19,071,217
9
2013-09-28T20:13:28Z
[ "python", "matlab", "numpy", "scipy" ]
I am converting some Matlab code into python using [numpy](http://www.numpy.org/). Everything worked pretty smoothly but recently I encountered [fminsearch](http://www.mathworks.com/help/matlab/ref/fminsearch.html) function. So, to cut it short: is there an easy way to make in python something like this: ``` banana =...
It's just a straight-forward conversion from Matlab syntax to python syntax: ``` import scipy.optimize banana = lambda x: 100*(x[1]-x[0]**2)**2+(1-x[0])**2 xopt = scipy.optimize.fmin(func=banana, x0=[-1.2,1]) ``` with output: ``` Optimization terminated successfully. Current function value: 0.000000 ...
Pandas dataframe: drop columns whose name contains a specific string
19,071,199
7
2013-09-28T20:10:42Z
19,071,572
7
2013-09-28T20:55:09Z
[ "python", "pandas", "dataframe" ]
I have a pandas dataframe with the following column names: Result1, Test1, Result2, Test2, Result3, Test3, etc... I want to drop all the columns whose name contains the word "Test". The numbers of such columns is not static but depends on a previous function. How can I do that?
``` import pandas as pd import numpy as np array=np.random.random((2,4)) df=pd.DataFrame(array, columns=('Test1', 'toto', 'test2', 'riri')) print df Test1 toto test2 riri 0 0.923249 0.572528 0.845464 0.144891 1 0.020438 0.332540 0.144455 0.741412 cols = [c for c in df.columns if c.lowe...
How to generalize a function by adding arguments?
19,071,496
2
2013-09-28T20:45:52Z
19,071,503
9
2013-09-28T20:47:20Z
[ "python" ]
I am completing a beginner's Python book. I think I understand what the question is asking. **Encapsulate into a function, and generalize it so that it accepts the string and the letter as arguments.** ``` fruit = "banana" count = 0 for char in fruit: if char == 'a': count += 1 print count ``` **My answe...
`a` and `banana` are variable names. Since you never defined either of them (e.g. `a = 'x'`), the interpreter cannot use them. You need to wrap them in quotes and turn them into strings: ``` count_letters('a', 'banana') ``` Or assign them beforehand and pass the variables: ``` l = 'a' s = 'banana' count_letters(l,...
socket.error: [Errno 48] Address already in use
19,071,512
61
2013-09-28T20:48:08Z
19,071,568
131
2013-09-28T20:54:37Z
[ "python", "simplehttpserver" ]
I'm trying to set up a server with python from mac terminal. I navigate to folder location an use: ``` python -m SimpleHTTPServer ``` But this gives me error: ``` socket.error: [Errno 48] Address already in use ``` I had previously open a connection using the same command for a different website in a different loc...
You already have a process bound to the default port (8000). If you already ran the same module before, it is most likely that process still bound to the port. Try and locate the other process first: ``` $ ps -fA | grep python 501 81651 12648 0 9:53PM ttys000 0:00.16 python -m SimpleHTTPServer ``` The command...
pip install customized include path
19,071,708
9
2013-09-28T21:10:52Z
28,981,343
8
2015-03-11T08:06:49Z
[ "python", "installation", "install", "pip" ]
I'm trying to install a library `pyleargist`. It requires another lib `libfftw3` to be manually installed which I've installed. Since I don't have the root privilege, I have to install `libfftw3` under my home directory: `~/usr/include` and `~/usr/lib`. Then I follow this post: <http://superuser.com/questions/242190/ho...
`pip` has a `--global-option` flag You can use it to pass additional flags to `build_ext`. For instance, to add a `-I` flag: ``` pip install --global-option=build_ext --global-option="-I/home/users/abc/include/" pyOpenSSL ```
How to design a Windows Forms App with Iron Python
19,073,415
4
2013-09-29T01:08:15Z
19,087,892
7
2013-09-30T06:41:34Z
[ "python", "ironpython", "visual-studio-2013", "ptvs" ]
I just got Visual Studio 2013 RC with PTVS ([Python Tools for Visual Studio](http://pytools.codeplex.com/)). How would I use the Windows Forms Designer that Visual Studio has built in with Python? VS has an Iron Python template for WF, but there's no way to use the actual GUI designer. Is there any way to get the GUI d...
Python Tools for Visual Studio does not have a Windows Forms designer. You could take a look at [SharpDevelop which does have a Windows Forms designer for IronPython](http://community.sharpdevelop.net/blogs/mattward/archive/2009/05/12/IronPython2FormsDesigner.aspx). The other alternative would be to design your form in...
Matplotlib overlapping annotations / text
19,073,683
6
2013-09-29T02:04:43Z
34,762,716
9
2016-01-13T09:22:27Z
[ "python", "matplotlib", "annotate" ]
I'm trying to stop annotation text overlapping in my graphs. The method suggested in the accepted answer to [Matplotlib overlapping annotations](http://stackoverflow.com/questions/8850142/matplotlib-overlapping-annotations) looks extremely promising, however is for bar graphs. I'm having trouble converting the "axis" m...
I just wanted to post here another solution, a small library I wrote to implement this kind of things: <https://github.com/Phlya/adjustText> An example of the process can be seen here: [![enter image description here](http://i.stack.imgur.com/rpyZp.gif)](http://i.stack.imgur.com/rpyZp.gif) Usage is super simple: ``` ...
Python - docstrings descriptions vs comments
19,074,745
8
2013-09-29T05:27:03Z
19,076,001
11
2013-09-29T08:34:47Z
[ "python", "comments", "docstring" ]
I'm a bit confused over the difference between docstrings and comments in python. In my class my teacher introduced something known as a 'design recipe', a set of steps that will supposedly help us students plot and organize our coding better in Python. From what I understand, the below is an example of the steps we f...
It appears your teacher is a fan of How to Design Programs ;) I'd tackle this as writing for two different audiences who won't always overlap. First there are the docstrings; these are for people who are going to be using your code without needing or wanting to know how it works. Docstrings can be turned into actual ...
How to validate integer range in Flask routing (Werkzeug)?
19,076,226
3
2013-09-29T09:03:28Z
19,076,418
8
2013-09-29T09:29:24Z
[ "python", "routing", "flask", "werkzeug" ]
I have the below routing in my flask app ``` from foo import get_foo @app.route("/foo/<int:id>") def foo_id(id): return render_template('foo.html', foo = get_foo(id)) ``` Foo can have ID between 1-300. Where can I have this validation? I can have the validation inside get\_foo. But, I am not sure if it's best p...
Flask uses the Werkzeug routing system, after I checked the [Werkzeug URL Routing docs](http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.IntegerConverter), I find it's possible to do range control in route rules. > **From Werkzeug docs** > > class werkzeug.routing.IntegerConverter(map, fixed\_digits=0, min=Non...
what happens when i import module twice in python
19,077,381
5
2013-09-29T11:12:43Z
19,077,396
11
2013-09-29T11:14:49Z
[ "python", "module" ]
I have a doubt that I would like to get cleared. Consider the following module named `ex_1.py`: ``` print("Hello, I'm ex_1") def greet(name): print("Hello, "+name+" nice to meet you! ") ``` Now consider another file called `1_client_ex_1.py` that will import `ex_1.py` module. ``` import ex_1.py ``` Now when I exe...
Nothing, if a module has already been imported, it's not loaded again. You will simply get a reference to the module that has already been imported (it will come from `sys.modules`). To get a list of the modules that have already been imported, you can look up `sys.modules.keys()` (note that `urllib`here imports a *l...
Python: How would you save a simple settings/config file?
19,078,170
20
2013-09-29T12:44:22Z
19,078,712
43
2013-09-29T13:42:09Z
[ "python", "json", "settings", "config", "ini" ]
I don't care if it's JSON, pickle, YAML, or whatever. All other implementations I have seen are not forwards compatible, so if I have a config file, add a new key in the code, then load that config file, it'll just crash. Are there any simple way to do this?
# Configuration files in python There are several ways to do this depending on the file format required. ## ConfigParser [.ini format] I would use the standard [configparser](http://docs.python.org/2/library/configparser.html) approach unless there were compelling reasons to use a different format. Write a file lik...
Naming returned columns in Pandas aggregate function?
19,078,325
11
2013-09-29T13:00:05Z
19,078,773
17
2013-09-29T13:47:39Z
[ "python", "group-by", "pandas", "aggregate-functions" ]
I'm having trouble with Pandas' groupby functionality. I've read [the documentation](http://pandas.pydata.org/pandas-docs/dev/groupby.html), but I can't see to figure out how to apply aggregate functions to multiple columns *and* have custom names for those columns. This comes very close, but the data structure return...
This will drop the outermost level from the hierarchical column index: ``` df = data.groupby(...).agg(...) df.columns = df.columns.droplevel(0) ``` --- For example: ``` import pandas as pd import pandas.rpy.common as com import numpy as np data = com.load_data('Loblolly') print(data.head()) # height age Seed ...
How to plot time series in python
19,079,143
16
2013-09-29T14:24:39Z
19,079,248
42
2013-09-29T14:35:37Z
[ "python", "matplotlib", "plot" ]
I have been trying to plot a time series graph from a CSV file. I have managed to read the file and converted the data from string to date using `strptime` and stored in a list. When I tried plotting a test plot in matplotlib with the list containing the date information it plotted the date as a series of dots; that is...
Convert your x-axis data from text to [`datetime.datetime`](http://docs.python.org/2/library/datetime.html#datetime-objects), use [`datetime.strptime`](http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime): ``` >>> from datetime import datetime >>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d ...
How to get pip to work behind a proxy server
19,080,352
18
2013-09-29T16:23:23Z
20,818,379
23
2013-12-28T19:18:12Z
[ "python", "proxy", "pip" ]
I am trying to use python package manager pip to install a package and it's dependencies from the internet. However I am behind a proxy in my college and have already set the `http_proxy` environment variable. But when I try to install a package like this: ``` pip install TwitterApi ``` I get this error in the log fi...
The pip's proxy parameter is, according to `pip --help`, in the form `[user:passwd@]proxy.server:port` You should use the following, without specifying `http://` ``` pip install --proxy user:password@proxyserver:port TwitterApi ```
How to get pip to work behind a proxy server
19,080,352
18
2013-09-29T16:23:23Z
23,103,309
15
2014-04-16T07:56:07Z
[ "python", "proxy", "pip" ]
I am trying to use python package manager pip to install a package and it's dependencies from the internet. However I am behind a proxy in my college and have already set the `http_proxy` environment variable. But when I try to install a package like this: ``` pip install TwitterApi ``` I get this error in the log fi...
At least for pip 1.3.1, it honors the http\_proxy and https\_proxy environment variables. Make sure you define both, as it will access the PYPI index using https. ``` export https_proxy="http://<proxy.server>:<port>" pip install TwitterApi ```
Transparent background in a Tkinter window
19,080,499
4
2013-09-29T16:37:39Z
22,106,858
8
2014-02-28T22:14:10Z
[ "python", "tkinter", "transparency" ]
Is there a way to create a "Loading Screen" in Python 3.x using Tkinter? I mean like the loading screen for Adobe Photoshop, with transparency and so on. I managed to get rid of the frame border already using: ``` root.overrideredirect(1) ``` But if I do this: ``` root.image = PhotoImage(file=pyloc+'\startup.gif') l...
It is possible, but it's OS-dependent. This will work in Windows: ``` import Tkinter as tk # Python 2 import tkinter as tk # Python 3 root = tk.Tk() # The image must be stored to Tk or it will be garbage collected. root.image = tk.PhotoImage(file='startup.gif') label = tk.Label(root, image=root.image, bg='white') root...
Run separate processes in parallel - Python
19,080,792
3
2013-09-29T17:04:07Z
19,081,455
9
2013-09-29T18:06:53Z
[ "python", "python-3.x", "parallel-processing", "multiprocessing" ]
I use python 'multiprocessing' module to run single process on multiple cores but I want to run a couple of independent process in parallel. For ex - Process one parses large file, Process two find pattern in different file and process three does some calculation; can all three different processed that have different s...
From [16.6.1.5. Using a pool of workers](http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers): ``` from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': pool = Pool(processes=4) # start 4 worker processes result = pool.apply_async(f, [10])...
List comprehension and function returning multiple values
19,082,084
3
2013-09-29T19:05:27Z
19,082,105
7
2013-09-29T19:08:32Z
[ "python", "list-comprehension" ]
I wanted to use list comprehension to avoid writing a for loop appending to some lists. But can it work with a function that returns multiple values? I expected this (simplified example) code to work... ``` def calc(i): a = i * 2 b = i ** 2 return a, b steps = [1,2,3,4,5] ay, be = [calc(s) for s in steps...
Use `zip` with `*`: ``` >>> ay, by = zip(*(calc(x) for x in steps)) >>> ay (2, 4, 6, 8, 10) >>> by (1, 4, 9, 16, 25) ```
Can literals in Python be overridden?
19,083,160
9
2013-09-29T20:53:02Z
19,083,442
15
2013-09-29T21:24:07Z
[ "python", "macropy" ]
Couldn't find a way to phrase the title better, feel free to correct. I'm pretty new to Python, currently experimenting with the language.. I've noticed that all built-ins types cannot be extended with other members.. I'd like for example to add an `each` method to the `list` type, but that would be impossible. I real...
This is a conscientious choice from Python. Firstly, with regards to patching inbuilt type, this is primarily a design *decision* and only secondarily an optimization. I have learnt from much lurking on the Python Mailing List that monkey patching on builtin types, although enjoyable for small scripts, serves no good ...
How does Flask-login with multiple servers work
19,083,705
6
2013-09-29T21:51:02Z
19,084,316
10
2013-09-29T23:07:01Z
[ "python", "flask", "flask-login" ]
I have been using [Flask login module](http://flask-login.readthedocs.org/en/latest/), which creates and maintains session on the server. Since server maintains the session, I think it is not completely stateless. How does it work when application has more than one server. Should requests be sticky (i.e. given session...
This statement you've made is not completely correct: > ... which creates and maintains session on the server. Flask-Login uses the session facilities provided by Flask, so the data it stores in the session will be written by Flask using the configured session storage mechanism. By default Flask writes user sessions...
How to make matrices in Python?
19,084,476
6
2013-09-29T23:27:59Z
19,084,485
8
2013-09-29T23:29:30Z
[ "python", "matrix" ]
I've googled it and searched StackOverflow and YouTube.. I just can't get matrices in Python to click in my head. Can someone please help me? I'm just trying to create a basic 5x5 box that displays: ``` A A A A A B B B B B C C C C C D D D D D E E E E E ``` I got ``` a b c d e a b c d e a b c d e a b c d e a b c d e ...
Looping helps: ``` for row in matrix: print ' '.join(row) ``` or use nested `str.join()` calls: ``` print '\n'.join([' '.join(row) for row in matrix]) ``` Demo: ``` >>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'...
How to make matrices in Python?
19,084,476
6
2013-09-29T23:27:59Z
19,087,033
8
2013-09-30T05:30:47Z
[ "python", "matrix" ]
I've googled it and searched StackOverflow and YouTube.. I just can't get matrices in Python to click in my head. Can someone please help me? I'm just trying to create a basic 5x5 box that displays: ``` A A A A A B B B B B C C C C C D D D D D E E E E E ``` I got ``` a b c d e a b c d e a b c d e a b c d e a b c d e ...
The answer to your question depends on what your learning goals are. If you are trying to get matrices to "click" so you can use them later, I would suggest looking at a Numpy `array` instead of a list of lists. This will let you slice out rows and columns and subsets easily. Just try to get a column from a list of lis...
Numpy memory error creating huge matrix
19,085,012
2
2013-09-30T00:53:20Z
19,085,026
11
2013-09-30T00:56:32Z
[ "python", "memory", "numpy" ]
I am using numpy and trying to create a huge matrix. While doing this, I receive a memory error Because the matrix is not important, I will just show the way how to easily reproduce the error. ``` a = 10000000000 data = np.array([float('nan')] * a) ``` not surprisingly, this throws me `MemoryError` There are two th...
Assuming each floating point number is 4 bytes each, you'd have ``` (10000000000 * 4) /(2**30.0) = 37.25290298461914 ``` Or 37.5 gigabytes you need to store in memory. So I don't think 24gb of RAM is enough.
Is Python list.extend() Order Presserving?
19,085,713
5
2013-09-30T02:45:01Z
19,085,720
7
2013-09-30T02:45:45Z
[ "python", "list" ]
I'm wondering whether the extend function preserves the order in the two list. ``` >> list = [1, 2, 3] >> list.extend([4, 5]) >> list [1, 2, 3, 4, 5] ``` Is extend always working like that way?
Yes. `list.extend()` just *extends* the arguments given to the end of the list. According to the [docs](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists): > Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L. So: ``` >>> a = [1, 2, 3] >>> a[len(a):] = [4, ...
Can pip (or setuptools, distribute etc...) list the license used by each installed package?
19,086,030
12
2013-09-30T03:27:06Z
19,086,260
12
2013-09-30T03:57:46Z
[ "python", "licensing", "virtualenv", "pip", "easy-install" ]
I'm trying to audit a Python project with a large number of dependencies and while I can manually look up each project's homepage/license terms, it seems like most OSS packages should already contain the license name and version in their metadata. Unfortunately I can't find any options in pip or easy\_install to list ...
You can use `pkg_resources`: ``` import pkg_resources def get_pkg_license(pkgname): """ Given a package reference (as from requirements.txt), return license listed in package metadata. NOTE: This function does no error checking and is for demonstration purposes only. """ pkgs = pkg_resourc...
How to utilize all cores with python multiprocessing
19,086,106
9
2013-09-30T03:36:31Z
19,098,791
22
2013-09-30T16:05:28Z
[ "python", "multiprocessing" ]
have been fiddling with Python's `multicore` function for upwards of an hour now, trying to parallelize a rather complex graph traversal function using `Process` and `Manager`: ``` import networkx as nx import csv import time from operator import itemgetter import os import multiprocessing as mp cutoff = 1 exclusio...
Too much piling up here to address in comments, so, where `mp` is `multiprocessing`: `mp.cpu_count()` should return the number of processors. But test it. Some platforms are funky, and this info isn't always easy to get. Python does the best it can. If you start 24 processes, they'll do exactly what you tell them to ...
Python unittest.TestCase object has no attribute 'runTest'
19,087,189
12
2013-09-30T05:45:29Z
19,087,974
7
2013-09-30T06:46:12Z
[ "python", "unit-testing", "python-3.x", "pyunit" ]
For the following code: ``` import unittest class Test(unittest.TestCase): def test1(self): assert(True == True) if __name__ == "__main__": suite = unittest.TestSuite() suite.addTest(Test()) unittest.TextTestRunner().run(suite) ``` Use python3 to execute it, the following error is raised: `...
You need to invoke a test loader: ``` if __name__ == "__main__": suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test) unittest.TextTestRunner().run(suite) ```
Subclassing Tkinter to create a custom Widget
19,087,515
3
2013-09-30T06:14:01Z
19,099,802
9
2013-09-30T17:02:21Z
[ "python", "class", "widget", "tkinter", "inheritance" ]
please see the following code: (I am basically trying to create a text widget with a vertical scrollbar while retaining all the methods / functions from Tkinter.Text in my class) ``` class ScrollableTextWidget(Tkinter.Text): def __init__(self, parent): self.parent = parent self.Frame = ttk.Frame(se...
It's very normal to subclass a widget to create a custom one. However, if this custom widget is made up of more than one widget, you would normally subclass `Frame`. For example, to create a widget that is a text widget with a scrollbar I would do something like this: ``` import Tkinter as tk class ScrolledText(tk.Fr...
What does [^.]* mean in regular expression?
19,089,800
5
2013-09-30T08:36:34Z
19,089,855
18
2013-09-30T08:39:28Z
[ "python", "regex" ]
I'm trying to get 482.75 from the following text: `<span id="yfs_l84_aapl">482.75</span>` The regex I used is: `regex = '<span id="yfs_l84_[^.]*">(.+?)</span>'` and it worked. But the thing that I do not understand is why [^.]\* can match aapl here? My understanding is that . means any character except a newline; and...
Within the `[]` the `.` means just a dot. And the leading `^` means "anything but ...". So `[^.]*` matches zero or more non-dots.
pylab histogram get rid of nan
19,090,070
7
2013-09-30T08:51:25Z
19,090,183
16
2013-09-30T08:58:00Z
[ "python", "numpy", "matplotlib", "histogram", null ]
I have a problem with making a histogram when some of my data contains "not a number" values. I can get rid of the error by using `nan_to_num` from numpy, but than i get a lot of zero values which mess up the histogram as well. ``` pylab.figure() pylab.hist(numpy.nan_to_num(A)) pylab.show() ``` So the idea would be t...
Remove `np.nan` values from your array using `A[~np.isnan(A)]`, this will select all entries in `A` which values are not `nan`, so they will be excluded when calculating histogram. Here is an example of how to use it: ``` >>> import numpy as np >>> import pylab >>> A = np.array([1,np.nan, 3,5,1,2,5,2,4,1,2,np.nan,2,1...
TypeError: '_csv.reader' object has no attribute '__getitem__'?
19,090,589
3
2013-09-30T09:20:31Z
19,090,623
12
2013-09-30T09:22:15Z
[ "python", "csv" ]
Here is my code so far: ``` import csv reader = csv.reader(open('new_file.txt','r'),delimiter=' ') row1 = reader[0] row2 = reader[1] row3 = reader[2] ``` Here is my `new_file.txt`: ``` this is row one this is row two this is row three ``` When I run It i have the following error: ``` Traceback (most recent call la...
A `csv.reader()` object is *not* a sequence. You cannot access rows by index. You'd have to 'slurp' the whole iterable into a list for that: ``` rows = list(reader) row1 = rows[0] row2 = rows[1] row3 = rows[2] ``` This is generally not a good idea. You can instead ask for the next value from the iterator with the [`...
Editing .html files using Python?
19,092,475
3
2013-09-30T10:56:46Z
19,092,522
7
2013-09-30T10:59:07Z
[ "python" ]
I want to delete everything from my html file and add `<!DOCTYPE html><html><body>`. Here is my code so far: ``` with open('table.html', 'w'): pass table_file = open('table.html', 'w') table_file.write('<!DOCTYPE html><html><body>') ``` After i run my code, `table.html` is now empty. Why? How can I fix that?
It looks like you're not closing the file and the first line is doing nothing, so you could do 2 things. Either skip the first line and close the file in the end: ``` table_file = open('table.html', 'w') table_file.write('<!DOCTYPE html><html><body>') table_file.close() ``` or if you want to use the `with` statement...
Measure (max) memory usage with IPython—like timeit but memit
19,092,812
11
2013-09-30T11:14:47Z
19,105,973
15
2013-10-01T00:16:20Z
[ "python", "memory", "benchmarking", "ipython" ]
I have a simple task: in addition to measuring the time it takes to execute a chunk of code in Python, I need to measure the amount of memory a given chunk of code needs. IPython has a nice utility called `timeit` which works like this: ``` In [10]: timeit 3 + 3 10000000 loops, best of 3: 24 ns per loop ``` What I'm...
In fact, it already exists, as part of the prosaically named `memory_profiler` package: ``` In [2]: %memit np.zeros(1e7) maximum of 3: 76.402344 MB per loop ``` More info at <https://github.com/fabianp/memory_profiler#ipython-integration> Edit: To use this, you first need to load it as an IPython extension: ``` %lo...
Sum over squared array
19,094,441
9
2013-09-30T12:35:23Z
19,094,808
11
2013-09-30T12:53:33Z
[ "python", "numpy", "linear-algebra" ]
As part of a batch Euclidean distance computation, I'm computing ``` (X * X).sum(axis=1) ``` where `X` is a rather large 2-d array. This works fine, but it constructs a temporary array of the same size as `X`. Is there any way to get rid of this temporary, but retain the efficiency of a vectorized operation? The obv...
The `einsum` equivalent is: ``` np.einsum('ij,ij->i', X, X) ``` Though I am not sure how this works internally so it may or may not not solve your problem.
Using Twython to send a tweet, twitter api error
19,095,257
10
2013-09-30T13:16:13Z
19,196,583
24
2013-10-05T10:15:43Z
[ "python", "python-2.7", "twitter", "twython" ]
I'm trying to make python send a tweet for me using [Twython](https://github.com/ryanmcgrath/twython/) but for some reason everything I'm trying isn't working. I've followed the [Twython README](https://github.com/ryanmcgrath/twython/blob/master/README.rst) but still unable to acheive what I want. Below is my latest ...
There is a far simpler way to update your post as opposed to the way `Twython` *actually* shows you. It will take more work on your API console space though, so let me begin. 1. Firstly, you will need to go to your [apps page](https://dev.twitter.com/apps). After you've selected the application that you are using righ...
How to print backslash with Python?
19,095,796
25
2013-09-30T13:42:01Z
19,095,831
33
2013-09-30T13:43:57Z
[ "python", "python-2.7" ]
When I write: `print '\'` or `print "\"` or `print "'\'"` Python doesn't print me the backslash `\` symbol. **What should I do to get the expected result?**
You need to escape your backslash by preceding it with, yes, another backslash: ``` print "\\" ``` The `\` character is called an escape character, which interprets the character following it differently. For example, `n` by itself is simply a letter, but when you precede it with a backslash, it becomes `\n`, which i...