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
pandas: Frequency table for a single variable
12,207,326
42
2012-08-31T00:10:12Z
12,207,352
71
2012-08-31T00:14:46Z
[ "python", "statistics", "pandas", "frequency" ]
One last newbie pandas question for the day: How do I generate a table for a single Series? For example: ``` my_series = pandas.Series([1,2,2,3,3,3]) pandas.magical_frequency_function( my_series ) >> { 1 : 1, 2 : 2, 3 : 3 } ``` Lots of googling has led me to Series.describe() and pandas.crosstabs...
Maybe `.value_counts()`? ``` >>> import pandas >>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8]) >>> my_series 0 1 1 2 2 2 3 3 4 3 5 3 6 fred 7 1.8 8 1.8 >>> counts = my_series.value_counts() >>> counts 3 3 2 2 1.8 2 fred 1 1 1 >>> le...
Fitting only one paramter of a function with many parameters in python
12,208,634
14
2012-08-31T03:46:28Z
12,208,940
23
2012-08-31T04:30:57Z
[ "python", "scipy", "curve-fitting" ]
In python I have a function which has many parameters. I want to fit this function to a data set, but using only one parameter, the rest of the parameters I want to supply on on my own. Here is an example: ``` def func(x,a,b): return a*x*x + b for b in xrange(10): popt,pcov = curve_fit(func,x1,x2) ``` In this ...
You can wrap `func` in a lambda, as follows: ``` def func(x,a,b): return a*x*x + b for b in xrange(10): popt,pcov = curve_fit(lambda x, a: func(x, a, b), x1, x2) ``` A lambda is an anonymous function, which in Python can only be used for simple one line functions. Basically, it's normally used to reduce the am...
In Python, how do I inspect and then re-raise an exception while maintaining the original call stack?
12,209,450
8
2012-08-31T05:36:22Z
12,209,501
7
2012-08-31T05:41:11Z
[ "python", "exception-handling", "callstack" ]
I've got a situation where I'm catching a specific exception type, inspecting the exception's message to check if it's actually an exception I want to catch, and then re-raising the exception if not: ``` try: # do something exception-prone except FooException as e: if e.message == 'Something I want to handle':...
Just do: ``` raise ``` instead of `raise e`. See the tutorial section on [raising exceptions](http://docs.python.org/tutorial/errors.html#raising-exceptions), and also the [language reference on `raise` statements](http://docs.python.org/reference/simple_stmts.html#raise): > If no expressions are present, raise re-r...
Multi Celery projects with same RabbitMQ broker backend process
12,209,652
8
2012-08-31T05:57:44Z
12,214,248
12
2012-08-31T11:18:11Z
[ "python", "rabbitmq", "celery" ]
How can I use **two different celery project** which consumes messages from **single RabbitMQ installation**. Generally, these scripts work fine if I use different rabbitmq for them. But on production machine, I need to share the same RabbitMQ backend for them. Note: Due to some constraint, I cannot merge new project...
RabbitMQ has the ability to create virtual message brokers called virtual hosts or vhosts. Each one is essentially a mini-RabbitMQ server with its own queues. This lets you safely use one RabbitMQ server for multiple applications. `rabbitmqctl add_vhost` command creates a vhost. By default Celery uses the **/** defau...
How to add PyPi dependencies to DEB package
12,210,389
6
2012-08-31T07:03:18Z
13,938,848
8
2012-12-18T18:04:28Z
[ "python", "installation", "distutils", "deb", "autobahn" ]
I created some `python` app using `autobahn` and packaged it using `baazar builddeb`. In python setup.py file I added `requires` tag with all the required dependencies. Is it possible to tell debian package installer to install these packages? I added some of deps to `debian/control>Depends` but: 1. `dpkg -i my_packa...
Create debian packages from pypi using the python-stdeb package, then depend on them like any other package. See <http://pypi.python.org/pypi/stdeb>
Monkey patch a function in a module for unit testing
12,210,910
2
2012-08-31T07:41:51Z
12,211,179
8
2012-08-31T08:01:05Z
[ "python", "unit-testing", "monkeypatching" ]
I have the following method in a module that calls another method imported from another module: ``` def imported_function(): do_unnecessary_things_for_unittest() ``` The actual method that needs to be tested, imports and uses the above function: ``` from somewhere import imported_function def function_to_be_tes...
Say you have the following files: **somewhere.py** ``` def imported_function(): return False ``` **testme.py** ``` from somewhere import imported_function def function_to_be_tested(): return imported_function() ``` A call to `testme.function_to_be_tested()` would return `False`. --- Now, the trick is to...
Monkey patch a function in a module for unit testing
12,210,910
2
2012-08-31T07:41:51Z
12,211,657
11
2012-08-31T08:34:23Z
[ "python", "unit-testing", "monkeypatching" ]
I have the following method in a module that calls another method imported from another module: ``` def imported_function(): do_unnecessary_things_for_unittest() ``` The actual method that needs to be tested, imports and uses the above function: ``` from somewhere import imported_function def function_to_be_tes...
I think better to use [Mock Library](http://pypi.python.org/pypi/mock/) So you can do something like: ``` from somewhere import imported_function @patch(imported_function) def test_function_to_be_tested(self, imported_function): imported_function.return_value = True #Your test ``` I think for unit tests it'...
How to Maximize window in chrome using webDriver (python)
12,211,781
9
2012-08-31T08:41:03Z
12,213,723
14
2012-08-31T10:42:00Z
[ "python", "selenium", "selenium-chromedriver" ]
Is there a way to maximize the chrome browser window using python selenium WebDriver? Note: I am using Chrome Driver 23.0 Any solution on this would be greatly appreciated!
You could use ChromeOptions and set suitable argument: ``` options = ChromeOptions() options.add_argument("--start-maximized") driver = ChromeDriver(options) ```
Python PyQt: How can I move my widgets on the window with mouse?
12,213,391
2
2012-08-31T10:20:33Z
12,219,643
7
2012-08-31T17:00:40Z
[ "python", "pyqt4" ]
I am new to Python. I have drawn polygon and circle with fixed coordinates. Now I want to move this polygon and circle using mouse to some other place on window. Please guide me how can I do it? ``` import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class MyFrame(QWidget): def __init__(self, parent=N...
You should look into the QGraphicsView instead of what you are doing, it has this all built in already. <http://doc.qt.nokia.com/4.7-snapshot/qgraphicsview.html> <http://doc.qt.nokia.com/4.7-snapshot/qgraphicsscene.html> ``` from PyQt4 import QtGui, QtCore class MyFrame(QtGui.QGraphicsView): def __init__( self,...
What does "variable or 0" mean in python?
12,213,430
18
2012-08-31T10:23:28Z
12,213,455
22
2012-08-31T10:25:20Z
[ "python", "variables" ]
What is the meaning of the following statement in python: ``` x = variable_1 or 0 ``` `variable_1` is an object. What value does `x` have above? And what is the type of `x`?
`x` will be `0` if `variable_1` evaluates as false, otherwise it will be `variable_1` ``` >>> 'abc' or 0 'abc' >>> '' or 0 0 >>> ['a', 'b', 'c'] or 0 ['a', 'b', 'c'] >>> [] or 0 0 ```
What does "variable or 0" mean in python?
12,213,430
18
2012-08-31T10:23:28Z
12,213,466
17
2012-08-31T10:25:36Z
[ "python", "variables" ]
What is the meaning of the following statement in python: ``` x = variable_1 or 0 ``` `variable_1` is an object. What value does `x` have above? And what is the type of `x`?
If `variable_1` evaluates to `False` , x is set to `0`, otherwise to `variable_1` Think of it as ``` if variable_1: x = variable_1 else: x = 0 ```
Celery. Decrease number of processes
12,213,665
10
2012-08-31T10:38:32Z
12,214,343
7
2012-08-31T11:25:42Z
[ "python", "django", "celery" ]
Is there any way around to limit number of workers in [celery](http://celery.readthedocs.org/en/latest/index.html)? I have small server and celery always creates 10 processes on 1 core processor. I want to limit this number to 3 processes.
celery worker **--concurrency** option allows to specify the number of child processes processing the queue.
Celery. Decrease number of processes
12,213,665
10
2012-08-31T10:38:32Z
12,217,897
20
2012-08-31T14:56:03Z
[ "python", "django", "celery" ]
Is there any way around to limit number of workers in [celery](http://celery.readthedocs.org/en/latest/index.html)? I have small server and celery always creates 10 processes on 1 core processor. I want to limit this number to 3 processes.
I tried setting concurrency to 1 and max\_tasks\_per\_child to 1 in my settings.py file and ran 3 tasks at the same time. It just spawns 1 process as a User and the other 2 as celery. It should should just run 1 process and then wait for it to finish before running the other one. I am using django celery. **EDIT** { ...
Print a string as hex bytes?
12,214,801
84
2012-08-31T11:51:45Z
12,214,880
132
2012-08-31T11:55:52Z
[ "python", "string", "hex", "ordinal-indicator" ]
I have this string: `Hello world !!` and I want to print it using Python as `48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21`. `hex()` works only for integers. How can it be done?
Your can transform your string to a int generator, apply hex formatting for each element and intercalate with separator: ``` >>> s = "Hello world !!" >>> ":".join("{:02x}".format(ord(c)) for c in s) '48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21 ```
Print a string as hex bytes?
12,214,801
84
2012-08-31T11:51:45Z
12,214,957
119
2012-08-31T12:00:43Z
[ "python", "string", "hex", "ordinal-indicator" ]
I have this string: `Hello world !!` and I want to print it using Python as `48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21`. `hex()` works only for integers. How can it be done?
``` ':'.join(x.encode('hex') for x in 'Hello World!') ```
Print a string as hex bytes?
12,214,801
84
2012-08-31T11:51:45Z
13,892,068
38
2012-12-15T12:14:58Z
[ "python", "string", "hex", "ordinal-indicator" ]
I have this string: `Hello world !!` and I want to print it using Python as `48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21`. `hex()` works only for integers. How can it be done?
For Python 2.x: ``` ':'.join(x.encode('hex') for x in 'Hello World!') ``` The code above will **not work with Python 3.x**, for 3.x, the code below will work: ``` ':'.join(hex(ord(x))[2:] for x in 'Hello World!') ```
Print a string as hex bytes?
12,214,801
84
2012-08-31T11:51:45Z
16,882,092
16
2013-06-02T10:57:41Z
[ "python", "string", "hex", "ordinal-indicator" ]
I have this string: `Hello world !!` and I want to print it using Python as `48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21`. `hex()` works only for integers. How can it be done?
Some complements to Fedor Gogolev answer: First, if the string contains characters whose 'ASCII code' is below 10, they will not be displayed as required. In that case, the correct format should be `{:02x}`: ``` >>> s = "Hello unicode \u0005 !!" >>> ":".join("{0:x}".format(ord(c)) for c in s) '48:65:6c:6c:6f:20:75:6e...
Print a string as hex bytes?
12,214,801
84
2012-08-31T11:51:45Z
20,726,001
11
2013-12-22T03:38:12Z
[ "python", "string", "hex", "ordinal-indicator" ]
I have this string: `Hello world !!` and I want to print it using Python as `48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21`. `hex()` works only for integers. How can it be done?
Another answer in two lines that some might find easier to read, and helps with debugging line breaks or other odd characters in a string: ``` for character in string: print character, character.encode('hex') ```
Why do some list methods in Python work only with defined variables?
12,217,203
3
2012-08-31T14:15:50Z
12,217,224
9
2012-08-31T14:16:52Z
[ "python", "list", "python-2.7" ]
``` >>> a = [1, 2, 3] >>> a.append(4) >>> a [1, 2, 3, 4] ``` But: ``` >>> [1, 2, 3].append(4) >>> ``` Why do [`list`](http://docs.python.org/tutorial/datastructures.html) methods in Python (such as `insert` and `append`) only work with defined variables?
In the second sample nothing is printed, because `append`, that was called on a list (**note that append was actually performed**), returns `None`. Alternatively you should mention that `a.append(4)` also gave you a blank line (as your first sample shows), and final output of a first code sample was a representation o...
Can I force debugging python on AssertionError?
12,217,537
7
2012-08-31T14:35:24Z
12,217,717
8
2012-08-31T14:45:00Z
[ "python", "python-3.x", "assert", "pdb" ]
Suppose I have a python program where assert has been used to define how things should be, and I would like to capture anomalies with the read-eval-loop rather than having `AssertionError` be thrown. Granted, I could have ``` if (reality!=expectation): print("assertion failed"); import pdb; pdb.set_trace(); `...
Mainly taken from [this great snippet](http://code.activestate.com/recipes/65287-automatically-start-the-debugger-on-an-exception/): ``` import sys def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty() or type != AssertionError: # we are in interactive mode or we don't have a tty-like ...
Sum the second value of each tuple in a list
12,218,112
6
2012-08-31T15:10:27Z
12,218,119
11
2012-08-31T15:11:06Z
[ "python" ]
I have structure like this: ``` structure = [('a', 1), ('b', 3), ('c', 2)] ``` I would like to sum the integers (`1+3+2`) using `sum()` builtin method (in one line). Any ideas?
``` sum(n for _, n in structure) ``` would work.
Sum the second value of each tuple in a list
12,218,112
6
2012-08-31T15:10:27Z
12,218,122
10
2012-08-31T15:11:10Z
[ "python" ]
I have structure like this: ``` structure = [('a', 1), ('b', 3), ('c', 2)] ``` I would like to sum the integers (`1+3+2`) using `sum()` builtin method (in one line). Any ideas?
``` sum(x[1] for x in structure) ``` should work
Python slice first and last element in list
12,218,796
29
2012-08-31T15:54:40Z
12,218,829
41
2012-08-31T15:57:07Z
[ "python", "list", "slice", "subscript" ]
Is there a way to slice only the first and last item in a list? For example; If this is my list: ``` >>> some_list ['1', 'B', '3', 'D', '5', 'F'] ``` I *want* to do this (obviously `[0,-1]` is not valid syntax): ``` >>> first_item, last_item = some_list[0,-1] >>> print first_item '1' >>> print last_item 'F' ``` So...
One way: ``` some_list[::len(some_list)-1] ``` A better way (Doesn't use slicing, but is easier to read): ``` [some_list[0], some_list[-1]] ```
Python slice first and last element in list
12,218,796
29
2012-08-31T15:54:40Z
12,218,871
9
2012-08-31T15:59:49Z
[ "python", "list", "slice", "subscript" ]
Is there a way to slice only the first and last item in a list? For example; If this is my list: ``` >>> some_list ['1', 'B', '3', 'D', '5', 'F'] ``` I *want* to do this (obviously `[0,-1]` is not valid syntax): ``` >>> first_item, last_item = some_list[0,-1] >>> print first_item '1' >>> print last_item 'F' ``` So...
Just thought I'd show how to do this with numpy's fancy indexing: ``` >>> import numpy >>> some_list = ['1', 'B', '3', 'D', '5', 'F'] >>> numpy.array(some_list)[[0,-1]] array(['1', 'F'], dtype='|S1') ``` Note that it also supports arbitrary index locations, which the `[::len(some_list)-1]` method would not wor...
Using magic commands outside of Interactive Shell in IPython
12,219,387
6
2012-08-31T16:39:27Z
12,219,596
10
2012-08-31T16:56:47Z
[ "python", "ipython", "ipython-magic" ]
Is there a way to use "magic commands" from IPython from an outside file? For example if I have a file, "rcode.py" with the code: ``` %load_ext rmagic %R a=c(1,2,3);b=c(2,3,4);print(summary(lm(a~b))) ``` This gives me a `SyntaxError` for the first line when I run it using `ipython rcode.py` in the command line. Howev...
If you name your file with a `.ipy` extension, ipython will parse it properly. You can simply make a symlink if you want: ``` $ ln -s rcode.py rcode.ipy $ ipython rcode.ipy ```
Is there a Python equivalent of the Haskell 'let'
12,219,465
14
2012-08-31T16:46:20Z
12,219,526
10
2012-08-31T16:51:05Z
[ "python", "haskell", "functional-programming" ]
Is there a Python equivalent of the Haskell 'let' expression that would allow me to write something like: ``` list2 = [let (name,size)=lookup(productId) in (barcode(productId),metric(size)) for productId in list] ``` If not, what would be the **most readable** alternative? Added for clarification of the...
There is no such thing. You *could* emulate it the same way `let` is desugared to lambda calculus (`let x = foo in bar` <=> `(\x -> bar) (foo)`). The most readable alternative depends on the circumstances. For your specific example, I'd choose something like `[barcode(productId), metric(size) for productId, (_, size) ...
Is there a Python equivalent of the Haskell 'let'
12,219,465
14
2012-08-31T16:46:20Z
12,219,552
12
2012-08-31T16:52:46Z
[ "python", "haskell", "functional-programming" ]
Is there a Python equivalent of the Haskell 'let' expression that would allow me to write something like: ``` list2 = [let (name,size)=lookup(productId) in (barcode(productId),metric(size)) for productId in list] ``` If not, what would be the **most readable** alternative? Added for clarification of the...
You could use a temporary list comprehension ``` [(barcode(productId), metric(size)) for name, size in [lookup(productId)]][0] ``` or, equivalently, a generator expression ``` next((barcode(productId), metric(size)) for name, size in [lookup(productId)]) ``` but both of those are pretty horrible. Another (horrible...
Upgrade version of scikit-learn included in Enthought Canopy distribution
12,219,657
7
2012-08-31T17:01:55Z
12,219,996
12
2012-08-31T17:28:20Z
[ "python", "scikit-learn", "enthought", "canopy", "pythonpath" ]
I have EPD 7.3.1 installed (nowadays called Enthought Canopy), which comes with scikit-learn v 0.11. I am running Ubuntu 12.04. I need to install v 0.12 of scikit-learn. The scikit-learn [doc says](http://scikit-learn.org/dev/developers/index.html#git-repo) clone the repository, add the scikit-learn directory to your ...
The actions described on the scikit-learn website work irrespective of the scikit-learn version in EPD. Python will automatically use the scikit-learn version set in the `PYTHONPATH` [environment variable](http://en.wikipedia.org/wiki/Environment_variable), which you should set to the directory path of the Git version ...
Dragging/Moving a QPushButton in PyQt
12,219,727
5
2012-08-31T17:07:05Z
12,221,360
8
2012-08-31T19:19:18Z
[ "python", "pyqt", "pyqt4" ]
I am really struggling to figure out a way to do this. Say I implement a button very simply in a widget window: ``` self.button = QPushButton("Drag Me", self) ``` I can move its initialization point around the parent widget's area using `self.button.move(x,y)`, and I can get mouse events from `mousePressEvent(self, e...
Here is an example of a moveable button that still supports the normal click signal properly: ``` from PyQt4 import QtCore, QtGui class DragButton(QtGui.QPushButton): def mousePressEvent(self, event): self.__mousePressPos = None self.__mouseMovePos = None if event.button() == QtCore.Qt.L...
How to mock a base class with python mock library
12,219,967
10
2012-08-31T17:26:09Z
12,220,965
16
2012-08-31T18:45:36Z
[ "python", "mocking" ]
I try to use `mock` to write some unit-tests in python. For example I have the following class: ``` class TCPHandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() ``` And I only want to test the `handle` method. Without having to assume anything about `so...
You can do this by patching the derived class's `__bases__`: ``` def test_derived(): patcher = mock.patch.object(Derived, '__bases__', (mock.Mock,)) with patcher: patcher.is_local = True d = Derived() print d.foo() ``` The `is_local` hack is necessary to stop `mock.patch` from trying t...
webkit: is it possible to store cookies to file and reuse it again?
12,220,373
3
2012-08-31T17:57:22Z
15,800,193
7
2013-04-03T23:45:52Z
[ "python", "webkit", "gtk" ]
is it possible to store cookies to file when you use webkit and reuse it again next time when I run my application?
I know its old question and have been looking for the answer all over the place. Finally came up on my own after some trial and error. Hope this helps others. ``` from gi.repository import Soup cookiejar = Soup.CookieJarText.new("<Your cookie path>", False) cookiejar.set_accept_policy(Soup.CookieJarAcceptPolicy.ALWAYS...
Get NDB query length - using Python on Google App Engine
12,220,653
5
2012-08-31T18:18:56Z
12,220,742
11
2012-08-31T18:26:27Z
[ "python", "google-app-engine", "app-engine-ndb" ]
**What is a good way to get the number of query result when using NDB on google app engine?** Attempted this: ``` query = NDB_Model.query(NDB_Model.some_property == some_value) if len(query) > 0: # <-- this throws and exception entity = query[0] ``` I apologize that this is probably a very simple question, bu...
It seems like you just want to get the first entity from your query. That's what [`query.get()`](https://developers.google.com/appengine/docs/python/ndb/queryclass#Query_get) is for. ``` query = NDB_Model.query(NDB_Model.some_property == some_value) entity = query.get() if entity is not None: # Do stuff ``` From...
How can I make Python use a raw_input value as a fixed point number?
12,220,850
3
2012-08-31T18:35:41Z
12,220,877
7
2012-08-31T18:37:41Z
[ "python", "python-2.7" ]
I'm making a unit converter just to practice. Currently, I've defined a function to figure out what type of conversion to make (distance, time, mass, etc.). It then calls the correct converter for the type, asks what you're converting from, what you're converting to, and what the value for conversion is. ``` def mass...
The problem here is that you're using the `%d` format modifier in your string formatting which casts your answer to an integer. Use `%f` instead (or even `%s`).
Iterate over (item, others) in a list
12,222,013
10
2012-08-31T20:22:21Z
12,222,029
13
2012-08-31T20:23:51Z
[ "python", "sequence", "itertools", "complement" ]
Suppose I have a list: ``` l = [0, 1, 2, 3] ``` How can I iterate over the list, taking each item along with its complement from the list? That is, ``` for item, others in ... print(item, others) ``` would print ``` 0 [1, 2, 3] 1 [0, 2, 3] 2 [0, 1, 3] 3 [0, 1, 2] ``` Ideally I'm looking for a concise expressi...
This is quite easy and understandable: ``` for index, item in enumerate(l): others = l[:index] + l[index+1:] ``` You *could* make an iterator out of this if you insist: ``` def iter_with_others(l): for index, item in enumerate(l): yield item, l[:index] + l[index+1:] ``` Giving it's usage: ``` for i...
How can I get the user's facebook id with django-allauth?
12,222,021
11
2012-08-31T20:23:08Z
12,226,639
24
2012-09-01T09:38:13Z
[ "python", "django", "django-allauth" ]
I want to display a picture of the current\_user in my template. How can I access the user's facebook id when I'm using django-allauth?
For each user that is signed up via a social account a `SocialAccount` instance is available. This model has a foreign key to `User`. Note that a user can connect multiple social networking accounts to his local account, so in practice there may be more than one `SocialAccount` instances available. How you want to dea...
Django: [email protected] in admin
12,222,196
13
2012-08-31T20:40:01Z
12,222,451
17
2012-08-31T21:04:31Z
[ "python", "django" ]
I'm having a seemingly simple problem, but I haven't found a way to debug it. In the admin on our production website, when editing an object that has a ForeignKey to User, all the users show up as **[email protected]**. That makes the admin unusable in these areas! I tried googling the problem, but because the term "...
I don't really know the answer but whenever i see **[email protected]** showing up on google, if i navigate to the link then the email shows up and if i inspect the element it has near it this piece of javascript : ``` /* <![CDATA[ */ (function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__");a=l.classN...
Adding Header to Numpy array
12,223,167
2
2012-08-31T22:23:02Z
12,225,821
9
2012-09-01T07:27:39Z
[ "python", "numpy", "python-3.x" ]
I have an array I would like to add a header for. This is what i have now: ``` 0.0,1.630000e+01,1.990000e+01,1.840000e+01 1.0,1.630000e+01,1.990000e+01,1.840000e+01 2.0,1.630000e+01,1.990000e+01,1.840000e+01 ``` This is what i want: ``` SP,1,2,3 0.0,1.630000e+01,1.990000e+01,1.840000e+01 1.0,1.630000e+01,1.990000e+...
Since `numpy.savetxt` can also write to file objects, you can open the file youself and write your header before the data: ``` import numpy a = numpy.array([[0.0,1.630000e+01,1.990000e+01,1.840000e+01], [1.0,1.630000e+01,1.990000e+01,1.840000e+01], [2.0,1.630000e+01,1.990000e+01,1.840...
Adding Header to Numpy array
12,223,167
2
2012-08-31T22:23:02Z
16,520,086
15
2013-05-13T10:40:01Z
[ "python", "numpy", "python-3.x" ]
I have an array I would like to add a header for. This is what i have now: ``` 0.0,1.630000e+01,1.990000e+01,1.840000e+01 1.0,1.630000e+01,1.990000e+01,1.840000e+01 2.0,1.630000e+01,1.990000e+01,1.840000e+01 ``` This is what i want: ``` SP,1,2,3 0.0,1.630000e+01,1.990000e+01,1.840000e+01 1.0,1.630000e+01,1.990000e+...
Ever since Numpy 1.7.0, three parameters have been added to [numpy.savetxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) for exactly this purpose: header, footer and comments. So the code to do as you wanted can easily be written as: ``` import numpy a = numpy.array([[0.0,1.630000e+01,1.9900...
SQLAlchemy: Creating vs. Reusing a Session
12,223,335
35
2012-08-31T22:46:25Z
12,223,711
106
2012-08-31T23:45:40Z
[ "python", "sqlalchemy" ]
Just a quick question: SQLAlchemy [talks about](http://docs.sqlalchemy.org/en/rel_0_7/orm/session.html#session-frequently-asked-questions) calling `sessionmaker()` once but calling the resulting `Session()` class each time you need to talk to your DB. For me that means the second I would do my first `session.add(x)` or...
`sessionmaker()` is a factory, it's there to encourage placing configuration options for creating new `Session` objects in just one place. It is optional, in that you could just as easily call `Session(bind=engine, expire_on_commit=False)` anytime you needed a new `Session`, except that its verbose and redundant, and I...
How to filter by sub-level index in Pandas
12,224,778
3
2012-09-01T03:57:04Z
12,228,299
10
2012-09-01T13:47:53Z
[ "python", "pandas" ]
I have a 'df' which have a multilevel index (STK\_ID,RPT\_Date) ``` sales cogs net_pft STK_ID RPT_Date 000876 20060331 NaN NaN NaN 20060630 857483000 729541000 67157200 20060930 1063590000 925...
To use the "str.\*" methods on a column, you could reset the index, filter rows with a column "str.\*" method call, and re-create the index. ``` In [72]: x = df.reset_index(); x[x.RPT_Date.str.endswith("0630")].set_index(['STK_ID', 'RPT_Date']) Out[72]: sales cogs net_pft STK_ID RPT_Da...
supervisor.conf default location
12,226,113
11
2012-09-01T08:15:26Z
12,226,293
15
2012-09-01T08:44:19Z
[ "python", "deployment", "configuration", "supervisord" ]
Im trying to make automatic deployment including supervisord and confused by default settings path. Every deployment scheme i found use `/etc/supervisor/supervisor.conf` and `/etc/supervisor/conf.d/` without any presettings and links, also, after installing supervisor package via apt-get this path is really filled by ...
*Normally* the default file is indeed `/etc/supervisor.conf`, but the [Debian distribution patches this](http://ftp.de.debian.org/debian/pool/main/s/supervisor/supervisor_3.0a8-1.1.diff.gz) (link to the gzipped patch as provided by Debian) to look for `/etc/supervisor/supervisor.conf` first: ``` --- supervisor-3.0a8.o...
Count letter differences of two strings
12,226,846
8
2012-09-01T10:11:23Z
12,226,874
7
2012-09-01T10:15:38Z
[ "python" ]
This is the behaviour I want: ``` a: IGADKYFHARGNYDAA c: KGADKYFHARGNYEAA 2 difference(s). ```
``` def diff_letters(a,b): return sum ( a[i] != b[i] for i in range(len(a)) ) ```
Writing a distributed queue in Amazon's DynamoDB
12,228,056
8
2012-09-01T13:13:52Z
12,228,553
9
2012-09-01T14:25:24Z
[ "python", "amazon-web-services", "amazon-dynamodb" ]
I'm looking to convert a large directory of high resolution images (several million) into thumbnails using Python. I have a DynamoDB table that stores the location of each image in S3. Instead of processing all these images on one EC2 instance (would take weeks) I'd like to write a distributed application using a bunc...
One approach you could take would be to use [Amazon's Simple Queue Service(SQS)](http://aws.amazon.com/sqs/) in conjunction with DynamoDB. So what you could do is write messages to the queue that contain something like the hash key of the image entry in DynamoDB. Each instance would periodically check the queue and gra...
How to install beautiful soup 4 with python 2.7 on windows
12,228,102
28
2012-09-01T13:20:58Z
12,228,268
21
2012-09-01T13:42:53Z
[ "python", "html", "parsing", "beautifulsoup" ]
I have windows vista with Python 2.7. I would like to install BeautifulSoup 4 but apparently I can't install Beautiful Soup just by copying the file into the site-packages directory. I have to install pip and then run some commands from the command prompt. Could you guide me through that step by step. I am really a noo...
``` easy_install BeautifulSoup4 ``` or ``` easy_install BeautifulSoup ``` to install easy\_install ``` http://pypi.python.org/pypi/setuptools#files ```
How to install beautiful soup 4 with python 2.7 on windows
12,228,102
28
2012-09-01T13:20:58Z
12,228,336
32
2012-09-01T13:52:21Z
[ "python", "html", "parsing", "beautifulsoup" ]
I have windows vista with Python 2.7. I would like to install BeautifulSoup 4 but apparently I can't install Beautiful Soup just by copying the file into the site-packages directory. I have to install pip and then run some commands from the command prompt. Could you guide me through that step by step. I am really a noo...
You don't **need** `pip` for installing Beautiful Soup - you *can* just download it and run `python setup.py install` from the directory that you have unzipped BeautifulSoup in (assuming that you have added Python to your system `PATH` - if you haven't and you don't want to you can run `C:\Path\To\Python27\python "C:\P...
How to install beautiful soup 4 with python 2.7 on windows
12,228,102
28
2012-09-01T13:20:58Z
24,484,632
17
2014-06-30T07:08:38Z
[ "python", "html", "parsing", "beautifulsoup" ]
I have windows vista with Python 2.7. I would like to install BeautifulSoup 4 but apparently I can't install Beautiful Soup just by copying the file into the site-packages directory. I have to install pip and then run some commands from the command prompt. Could you guide me through that step by step. I am really a noo...
**Install pip** Download [get-pip](https://raw.github.com/pypa/pip/master/contrib/get-pip.py). Remember to save it as "get-pip.py" Now go to the download folder. Right click on **get-pip.py** then open with **python.exe**. **You can add system variable by** **(by doing this you can use pip and easy\_install without...
Python csv.writer - is it possible to write to a variable?
12,228,699
3
2012-09-01T14:46:34Z
12,228,737
8
2012-09-01T14:50:34Z
[ "python" ]
Is it possible to use csv.writer to write data to a variable rather than a file? I was hoping I could do something like this: ``` data = '' csv.writer(data) # ...... (I have removed the csv processing code for brevity) message = EmailMessage('Invoice for 2012', 'h', 'noreply@test.co.uk', ['test@test.co.uk']) message....
The `csv.writer` class needs a file-like object, something with a `.write()` method. A [`StringIO` class](http://docs.python.org/library/stringio.html) would be best here: ``` from cStringIO import StringIO data = StringIO() csv.writer(data) # write your stuff message = EmailMessage('Invoice for 2012', 'h', 'noreply@...
Mapping over values in a python dictionary
12,229,064
94
2012-09-01T15:31:37Z
12,229,070
137
2012-09-01T15:33:08Z
[ "python", "dictionary", "map-function" ]
Given a dictionary `{ k1: v1, k2: v2 ... }` I want to get `{ k1: f(v1), k2: f(v2) ... }` provided I pass a function `f`. Is there any such built in function? Or do I have to do ``` dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()]) ``` Ideally I would just write ``` my_dictionary.map_values(f) ``` or ``` m...
There is no such function; the easiest way to do this is to use a dict comprehension: ``` my_dictionary = {k: f(v) for k, v in my_dictionary.items()} ``` In python 2.7, use the `.iteritems()` method instead of `.items()` to save memory. The dict comprehension syntax wasn't introduced until python 2.7. Note that ther...
Mapping over values in a python dictionary
12,229,064
94
2012-09-01T15:31:37Z
23,687,802
7
2014-05-15T20:16:39Z
[ "python", "dictionary", "map-function" ]
Given a dictionary `{ k1: v1, k2: v2 ... }` I want to get `{ k1: f(v1), k2: f(v2) ... }` provided I pass a function `f`. Is there any such built in function? Or do I have to do ``` dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()]) ``` Ideally I would just write ``` my_dictionary.map_values(f) ``` or ``` m...
These toolz are great for this kind of simple yet repetitive logic. <http://toolz.readthedocs.org/en/latest/api.html#toolz.dicttoolz.valmap> Get's you right where you want to be. ``` import toolz def f(x): return x+1 toolz.valmap(f, my_list) ```
Mapping over values in a python dictionary
12,229,064
94
2012-09-01T15:31:37Z
25,469,948
8
2014-08-24T08:36:20Z
[ "python", "dictionary", "map-function" ]
Given a dictionary `{ k1: v1, k2: v2 ... }` I want to get `{ k1: f(v1), k2: f(v2) ... }` provided I pass a function `f`. Is there any such built in function? Or do I have to do ``` dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()]) ``` Ideally I would just write ``` my_dictionary.map_values(f) ``` or ``` m...
You can do this in-place, rather than create a new dict, which may be preferable for large dictionaries (if you do not need a copy). ``` def mutate_dict(f,d): for k, v in d.iteritems(): d[k] = f(v) my_dictionary = {'a':1, 'b':2} mutate_dict(lambda x: x+1, my_dictionary) ``` results in `my_dictionary` con...
Python: importing a sub‑package or sub‑module
12,229,580
24
2012-09-01T16:45:51Z
12,229,742
22
2012-09-01T17:09:37Z
[ "python", "import", "module", "package" ]
Having already use flat packages, I was not expecting the issue I encountered with nested packages. Here is… # Directory layout ``` dir | +-- test.py | +-- package | +-- __init__.py | +-- subpackage | +-- __init__.py | +-- module.py ``` # Cont...
You seem to be misunderstanding how `import` searches for modules. When you use an import statement it *always* searches the actual module path (and/or `sys.modules`); it doesn't make use of module *objects* in the local namespace that exist because of previous imports. When you do: ``` import package.subpackage.modul...
Sum a list which contains 'None' using Python
12,229,902
13
2012-09-01T17:33:00Z
12,229,907
15
2012-09-01T17:34:40Z
[ "python", "sum" ]
Basically my question is say you have an list containing 'None' how would you try retrieving the sum of the list. Below is an example I tried which doesn't work and I get the error: `TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'`. Thanks ``` def sumImport(self): my_list = [[1,2,3,None],[1,2,3]...
You can use `filter` function ``` >>> sum(filter(None, [1,2,3,None])) 6 ``` **Updated from comments** Typically `filter` usage is `filter(func, iterable)`, but passing `None` as first argument is a special case, described in [Python docs](http://docs.python.org/library/functions.html#filter). Quoting: > If function...
Sum a list which contains 'None' using Python
12,229,902
13
2012-09-01T17:33:00Z
12,229,910
8
2012-09-01T17:35:05Z
[ "python", "sum" ]
Basically my question is say you have an list containing 'None' how would you try retrieving the sum of the list. Below is an example I tried which doesn't work and I get the error: `TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'`. Thanks ``` def sumImport(self): my_list = [[1,2,3,None],[1,2,3]...
Remove `None` (and zero) elements before summing by using `filter`: ``` >>> k = sum(filter(None, chain.from_iterable(my_list))) >>> k 20 ``` To see why this works, see the [documentation for `filter`](http://docs.python.org/library/functions.html#filter): > `filter(function, iterable)` > > Construct a list from thos...
"AttributeError: 'module' object has no attribute 'argv'" when using Python.h
12,230,210
6
2012-09-01T18:16:29Z
12,230,270
11
2012-09-01T18:26:00Z
[ "c++", "python" ]
When messing around with Python.h I got this error: ``` AttributeError: 'module' object has no attribute 'argv' ``` C++ code: ``` #include "stdafx.h" #include "C:/Python27/include/Python.h" #include <iostream> using namespace std; int main() { Py_Initialize(); PyRun_SimpleString("import sys\npri...
Conceptually, `sys.argv` should contain the arguments that Python was called with (and what it was called under). What should it have if it were called like this, though? You can load the calling program's `argv` into `sys`, if you want: ``` int main(int argc, char **argv) { Py_Initialize(); PySys_SetArgv(arg...
How to make sense of this result?
12,231,136
5
2012-09-01T20:30:08Z
12,231,162
7
2012-09-01T20:33:08Z
[ "python", "tuples" ]
I am new to Python. Here is a question I have about lists: It is said that lists are mutable and tuples are immutable. But when I write the following: ``` L1 = [1, 2, 3] L2 = (L1, L1) L1[1] = 5 print L2 ``` the result is ``` ([1, 5, 3], [1, 5, 3]) ``` instead of ``` ([1, 2, 3], [1, 2, 3]) ``` But `L2` is a tuple ...
From the Python documentation (http://docs.python.org/reference/datamodel.html), note: > The value of an immutable container object that contains a reference to a mutable > object can change when the latter’s value is changed; however the container is > still considered immutable, because the collection of objects i...
Python split string by start and end characters
12,231,193
3
2012-09-01T20:36:51Z
12,231,364
8
2012-09-01T20:59:50Z
[ "python", "string", "list" ]
Say you have a string like this: `"(hello) (yes) (yo diddly)"`. You want a list like this: `["hello", "yes", "yo diddly"]` How would you do this with Python?
``` import re pattern = re.compile(r'\(([^)]*)\)') ``` The pattern matches the parentheses in your string (`\(...\)`) and these need to be escaped. Then it defines a subgroup (`(...)`) - these parentheses are part of the regex-syntax. The subgroup matches all characters except a right parenthesis (`[^)]*`) ``` s ...
How to implement server push in Flask framework?
12,232,304
30
2012-09-01T23:42:35Z
12,236,019
64
2012-09-02T12:40:08Z
[ "python", "redis", "flask", "juggernaut" ]
I am trying to build a small site with the server push functionality on Flask micro-web framework, but I did not know if there is a framework to work with directly. I used Juggernaut (http://flask.pocoo.org/snippets/80/), but it seems to be not working with redis (https://github.com/andymccurdy/redis-py) in current ve...
Have a look at [Server-Sent Events](http://dev.w3.org/html5/eventsource/). Server-Sent Events is a browser API that lets you keep open a socket to your server, subscribing to a stream of updates. For more Information read Alex MacCaw (Author of Juggernaut) post on [why he kills juggernaut](http://blog.alexmaccaw.com/ki...
Pyramid.security questions: Double cookies? Insecure cookies? Expiration?
12,232,364
7
2012-09-01T23:57:59Z
12,234,593
9
2012-09-02T08:52:14Z
[ "python", "cookies", "security", "pylons", "pyramid" ]
I'm taking my first foray into the Pyramid security module. I'm using this login code to set the auth\_tkt: ``` @view_config(route_name='LoginForm', request_method='POST', renderer='string') class LoginForm(SimpleObject): def __call__(self): emailAddress = self.request.params.get('emailAddress') p...
1. Actually, 3 cookies are generated; one without a `Domain` key, one with, and a 3rd with the wildcard version of your domain (the leading dot). Your browser usually either merges the two or ignores one of those (which one differs by browser, which is why 2 are set). That last cookie is generated when the `wild_do...
how to multiply all the numbers in a sequence (python)
12,232,584
4
2012-09-02T00:49:13Z
12,232,599
7
2012-09-02T00:53:40Z
[ "python", "numbers", "sequence" ]
Like if i told the program `n=10`, how would I make it return `10*9*8*7*6*5....1`? I thought a while loop but I feel I messed up somewhere because it doesn't sum up all of the numbers in the sequence. My current code looks like this ``` def product(n): i=n a=n-1 while a>0: return i * a b=i * a a=a-...
Since you are trying to learn to code, I won't give you a total solution, but I'll give you a few hints instead: * Have a `for` loop that runs up from 1 to n (using `range(1, n+1)`) instead of your `while`-loop. This will generate the values that you want to multiply and iterate the right number of times (which can be...
sqlalchemy cursor error during yield_per
12,233,115
8
2012-09-02T03:02:38Z
12,233,167
10
2012-09-02T03:20:02Z
[ "python", "sqlalchemy" ]
I am getting the following error: ``` Traceback (most recent call last): main() for item in session.query(Item).yield_per(10): fetch = cursor.fetchmany(self._yield_per) self.cursor, self.context) l = self.process_rows(self._fetchmany_impl(size)) row = self._fetchone_impl() self.__buffer_row...
If you haven't fetched all rows from a DBAPI cursor, then it's usually a bad idea to call commit() on that cursor's connection. In this case psycopg2 (which I'm guessing that's the DBAPI you're on) is not able to maintain the state of a named cursor (which is what it uses when you want server-buffered rows) over the tr...
Python: Find the absolute path of an imported module
12,233,836
6
2012-09-02T06:11:42Z
12,233,889
20
2012-09-02T06:23:55Z
[ "python", "python-module" ]
How to get the absolute path of module which may be imported elsewhere?
As the other answers have said, you can use `__file__`. However, note that this won't give the full path if the other module is in the same directory as the program. So to be safe, do something like this: ``` >>> import os >>> import math >>> os.path.abspath(math.__file__) '/Library/Frameworks/Python.framework/Version...
Passing extra metadata to a RequestHandler using python's SocketServer and Children
12,233,940
2
2012-09-02T06:36:17Z
19,870,162
8
2013-11-08T23:10:33Z
[ "python", "sockets" ]
I'm implementing a python application which is using `ThreadingTCPServer` and a custom subclass of `BaseRequestHandler`. The problem with this is that the `ThreadingTCPServer` seems to automatically spawn threads and create instances of the handler, calling their `handle()` function. However this leaves me with no way ...
I stumbled upon the very same thing. My solution was the following: ``` class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): def handle(self): print(self.server.mycustomdata) class ThreadedTCPServer(SocketServer.ThreadingTCPServer): pass server = ThreadedTCPServer((args.host, args.port...
Use eval to set unknown property
12,234,788
4
2012-09-02T09:23:04Z
12,234,807
11
2012-09-02T09:27:09Z
[ "python", "eval" ]
I have an User class, that has multiple properties inside it, and I also have addPoint method for User class, which allows user to input points into any of it's properties. However, there can be up to like 500 properties, everyone can have different ones, etc. So it would be a pain in the ass to code every property wit...
Don't use `eval()`, use [`setattr()`](http://docs.python.org/library/functions.html#setattr) and [`getattr()`](http://docs.python.org/library/functions.html#getattr) instead: ``` setattr(self, property, getattr(self, property) + amount) ```
R function rep() in Python (replicates elements of a list/vector)
12,235,552
11
2012-09-02T11:23:05Z
12,235,637
14
2012-09-02T11:34:44Z
[ "python" ]
The R function rep() replicates each element of a vector: ``` > rep(c("A","B"), times=2) [1] "A" "B" "A" "B" ``` This is like the list multiplication in Python: ``` >>> ["A","B"]*2 ['A', 'B', 'A', 'B'] ``` But with the rep() R function it is also possible to specifiy the number of repeats for each element of the ve...
Use `numpy` arrays and the [numpy.repeat](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html) function: ``` import numpy as np x = np.array(["A", "B"]) print np.repeat(x, [2, 3], axis=0) ['A' 'A' 'B' 'B' 'B'] ```
Use of python's logical operators when slicing a numpy array
12,236,455
4
2012-09-02T13:48:15Z
12,236,619
7
2012-09-02T14:08:52Z
[ "python", "arrays", "slice" ]
I would like to perform a slicing on a two dimensional numpy array: ``` type1_c = type1_c[ (type1_c[:,10]==2) or (type1_c[:,10]==3) or (type1_c[:,10]==4) or (type1_c[:,10]==5) or (type1_c[:,10]==6) ] ``` The syntax looks right; however I got the following error message: 'The truth value of an arra...
`or` is unambiguous when it's between two scalars, but what's the right vector generalization? if `x == array([0, 0])` and `y == array([0,1])`, should `x or y` be (1) False, because not all pairwise terms `or`-ed together are True, (2) True, because at least one pairwise `or` result is true, (3) `array([0, 1])`, becaus...
Setting different color for each series in scatter plot on matplotlib
12,236,566
55
2012-09-02T14:02:12Z
12,236,808
90
2012-09-02T14:39:07Z
[ "python", "matplotlib", "scatter-plot" ]
Suppose I have three data sets: ``` X = [1,2,3,4] Y1 = [4,8,12,16] Y2 = [1,4,9,16] ``` I can scatter plot this: ``` from matplotlib import pyplot as plt plt.scatter(X,Y1,color='red') plt.scatter(X,Y2,color='blue') plt.show() ``` How can I do this with 10 sets? I searched for this and could find any reference to wh...
I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm x = np.arange(10) ys = [i+x+(i*x)**2 for i in range(10)] colors = cm.rainbow(np.linspace(0, 1, len(ys))) for y, c in zip(ys, co...
Setting different color for each series in scatter plot on matplotlib
12,236,566
55
2012-09-02T14:02:12Z
32,649,740
10
2015-09-18T10:27:53Z
[ "python", "matplotlib", "scatter-plot" ]
Suppose I have three data sets: ``` X = [1,2,3,4] Y1 = [4,8,12,16] Y2 = [1,4,9,16] ``` I can scatter plot this: ``` from matplotlib import pyplot as plt plt.scatter(X,Y1,color='red') plt.scatter(X,Y2,color='blue') plt.show() ``` How can I do this with 10 sets? I searched for this and could find any reference to wh...
The normal way to plot plots with points in different colors in maptplotlib is to pass a list of colors as a parameter. Eg: ``` import matplotlib.pyplot matplotlib.pyplot.scatter([1,2,3],[4,5,6],color=['red','green','blue']) ``` [![3 colors](http://i.stack.imgur.com/Jew5I.png)](http://i.stack.imgur.com/Jew5I.png) W...
How to iterate in a cartesian product of lists
12,237,283
3
2012-09-02T15:38:10Z
12,237,296
7
2012-09-02T15:39:43Z
[ "python", "list", "for-loop", "loops" ]
I would like to iterate in a for loop using 3 (or any number of) lists with any number of elements, for example: ``` from itertools import izip for x in izip(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]): print x ``` but it gives me: ``` ('AAA', 'M', '00:00') ('BBB', 'Q'...
You want to use the [product](http://docs.python.org/library/itertools.html#itertools.product) of the lists: ``` from itertools import product for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]): ``` Demo: ``` >>> from itertools import product >...
Multiplying elements in a sparse array with rows in matrix
12,237,954
5
2012-09-02T16:57:55Z
12,238,133
8
2012-09-02T17:22:24Z
[ "python", "matrix", "numpy", "scipy", "sparse-matrix" ]
If you have a sparse matrix X: ``` >> X = csr_matrix([[0,2,0,2],[0,2,0,1]]) >> print type(X) >> print X.todense() <class 'scipy.sparse.csr.csr_matrix'> [[0 2 0 2] [0 2 0 1]] ``` And a matrix Y: ``` >> print type(Y) >> print text_scores <class 'numpy.matrixlib.defmatrix.matrix'> [[8] [5]] ``` ...How can yo...
Unfortunatly the `.multiply` method of the CSR matrix seems to densify the matrix if the other one is dense. So this would be one way avoiding that: ``` # Assuming that Y is 1D, might need to do Y = Y.A.ravel() or such... # just to make the point that this works only with CSR: if not isinstance(X, scipy.sparse.csr_ma...
Python: shuffling list, but keeping some elements frozen
12,238,005
15
2012-09-02T17:04:48Z
12,238,093
11
2012-09-02T17:16:04Z
[ "python", "python-2.7" ]
I've such a problem: There is a list of elements of class `CAnswer` (no need to describe the class), and I need to shuffle it, but with one constraint - some elements of the list have `CAnswer.freeze` set to `True`, and those elements must not be shuffled, but remain on their original positions. So, let's say, for a g...
One solution: ``` def fixed_shuffle(lst): unfrozen_indices, unfrozen_subset = zip(*[(i, e) for i, e in enumerate(lst) if not e.freeze]) unfrozen_indices = list(unfrozen_indices) random.shuffle(unfrozen_indices) for i, e in zip(unfrozen_indices, unfrozen_subse...
Python: shuffling list, but keeping some elements frozen
12,238,005
15
2012-09-02T17:04:48Z
12,238,111
14
2012-09-02T17:18:48Z
[ "python", "python-2.7" ]
I've such a problem: There is a list of elements of class `CAnswer` (no need to describe the class), and I need to shuffle it, but with one constraint - some elements of the list have `CAnswer.freeze` set to `True`, and those elements must not be shuffled, but remain on their original positions. So, let's say, for a g...
Another solution: ``` # memorize position of fixed elements fixed = [(pos, item) for (pos,item) in enumerate(items) if item.freeze] # shuffle list random.shuffle(items) # swap fixed elements back to their original position for pos, item in fixed: index = items.index(item) items[pos], items[index] = items[index...
Python: shuffling list, but keeping some elements frozen
12,238,005
15
2012-09-02T17:04:48Z
12,238,498
9
2012-09-02T18:13:45Z
[ "python", "python-2.7" ]
I've such a problem: There is a list of elements of class `CAnswer` (no need to describe the class), and I need to shuffle it, but with one constraint - some elements of the list have `CAnswer.freeze` set to `True`, and those elements must not be shuffled, but remain on their original positions. So, let's say, for a g...
In linear time, constant space using [`random.shuffle() source`](http://hg.python.org/cpython/file/2.7/Lib/random.py#l276): ``` from random import random def shuffle_with_freeze(x): for i in reversed(xrange(1, len(x))): if x[i].freeze: continue # fixed # pick an element in x[:i+1] with which to ex...
How to accelerate matrix multiplications in Python?
12,239,002
7
2012-09-02T19:20:27Z
12,239,239
7
2012-09-02T19:52:15Z
[ "python", "optimization", "numpy", "parallel-processing", "blas" ]
I am developing a small neural network whose parameters need a lot of optimization, so a lot of processing time. I have profiled my script with `cProfile` and what takes 80% of the processor time is the NumPy `dot` function, the rest is matrix inversion with the function `numpy.linalg.solve`. My current version of nump...
If you're not already, you could try linking numpy to a very optimized BLAS library like [Intel MKL](http://software.intel.com/en-us/intel-mkl) (which is [free-as-in-beer for non-commercial use](http://software.intel.com/en-us/non-commercial-software-development) or [discounted for academic use](http://software.intel.c...
Getting started with speech recognition and python
12,239,080
15
2012-09-02T19:31:59Z
16,551,389
7
2013-05-14T19:33:45Z
[ "python", "speech-to-text" ]
I would like to know where one could get started with speech recognition. Not with a library or anything that is fairly "Black Box'ed" But instead, I want to know where I can Actually make a simple speech recognition script. I have done some searching and found, not much, but what I have seen is that there are dictiona...
## UPDATE: this is not working anymore because google closed her platform -- you can use <https://pypi.python.org/pypi/pygsr> ``` $> pip install pygsr ``` example usage: ``` from pygsr import Pygsr speech = Pygsr() # duration in seconds speech.record(3) # select the language phrase, complete_response = speech.spe...
Umlauts in regexp matching (via locale?)
12,240,260
7
2012-09-02T22:27:35Z
12,240,286
14
2012-09-02T22:30:09Z
[ "python", "regex", "locale" ]
I'm surprised that I'm not able to match a German umlaut in a regexp. I tried several approaches, most involving setting locales, but up to now to no avail. ``` locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8') re.findall(r'\w+', 'abc def g\xfci jkl', re.L) re.findall(r'\w+', 'abc def g\xc3\xbci jkl', re.L) re.findall(r'...
Have you tried to use the `re.UNICODE` flag, as described in the [doc](http://docs.python.org/library/re.html)? ``` >>> re.findall(r'\w+', 'abc def güi jkl', re.UNICODE) ['abc', 'def', 'g\xc3\xbci', 'jkl'] ``` A quick search points to this [thread](http://www.gossamer-threads.com/lists/python/python/850772) that giv...
How to share data between requests in Tornado Web
12,240,285
7
2012-09-02T22:30:08Z
12,247,021
14
2012-09-03T11:32:58Z
[ "python", "tornado" ]
I have the following use case for my Tornado web server: Upon POST requests entries can be made to the server, entries which will not be persisted to a file or database. Upon GET requests a process can be started or terminated. Hence I need to share data between different requests in my `RequestHandler` implementatio...
I suggest the following: Instead of a database access object pass an object which stores your data, for instance: ``` data = DataStore() application = web.Application([ (r'.*', MainHandler, dict(data = data), ]) ``` with the following `RequestHandler` initialization method. ``` def initialize(self, ...
Write list of comma separate strings to csv file in Python
12,240,662
2
2012-09-02T23:49:32Z
12,240,667
7
2012-09-02T23:50:57Z
[ "python", "list", "csv" ]
If I have a list of strings as follows: ``` data = ['a,x', 'b,y', 'c,z'] f = open('data.csv', 'wb') w = csv.writer(f, delimiter = ',') w.writerow(data) f.close() ``` The problem is that they are saved in 3 cells on a single line like this: (" " is one Excel cell) "a,x" "b,y" "c,z" What I really want is the followin...
You can create a list of lists(row) and write them all using [writerows](http://docs.python.org/library/csv.html#csv.csvwriter.writerows). or write them all individually. The important part is that a row is a python list, not a string with comma seperated values. ``` data = ['a,x', 'b,y', 'c,z'] f = open('data.csv', '...
Python get image matrix PIL
12,243,803
5
2012-09-03T07:42:44Z
12,243,875
8
2012-09-03T07:50:16Z
[ "python", "numpy", "python-imaging-library" ]
i am trying to get to load an image, convert it and print the matrix. I have the following code ; ``` im = Image.open("1.jpg") im = im.convert("L") print im ``` when i print 'im' i get this `<PIL.Image.Image image mode=L size=92x112 at 0x2F905F8>` . How can i get to see the image matrix?
You can use `numpy.asarray()`: ``` >>> import Image, numpy >>> numpy.asarray(Image.open('1.jpg').convert('L')) ```
Python source code for built-in "in" operator
12,244,074
9
2012-09-03T08:05:44Z
12,244,378
25
2012-09-03T08:28:32Z
[ "python", "c", "string", "cpython", "python-internals" ]
I am trying to find the implementation of the built-in `in` operator in the (C) Python source code. I have searched in the built-in functions source code, [bltinmodule.c](http://svn.python.org/projects/python/trunk/Python/bltinmodule.c), but cannot find the implementation of this operator. Where can I find this impleme...
To find the implementation of *any* python operator, first find out what bytecode Python generates for it, using the [`dis.dis` function](http://docs.python.org/library/dis.html#dis.dis): ``` >>> def inop(): ... '0' in [] ... >>> dis.dis(inop) 2 0 LOAD_CONST 1 ('0') 3 LOAD_...
Python YAML: Controlling output format
12,246,605
8
2012-09-03T11:05:50Z
12,248,040
13
2012-09-03T12:37:25Z
[ "python", "yaml" ]
My file reads user input (like userid, password..). And sets the data to x.yml file. The content of x.yml file is ``` {user: id} ``` But instead I want the content to be as ``` user: id ``` How can I achieve this?
As mentioned in the comments, the python YAML library is the right tool for the job. To get the output you want, you need to pass the keyword argument `default_flow_style=False` to `yaml.dump`: ``` >>> x = { "user" : 123 } >>> output_stream = open("output_file.yml","w") >>> yaml.dump(x,output_stream,default_flow_style...
joining two numpy matrices
12,246,680
6
2012-09-03T11:11:14Z
12,246,720
12
2012-09-03T11:14:02Z
[ "python", "multidimensional-array", "matrix", "numpy", "scipy" ]
If you have two numpy matrices, how can you join them together into one? They should be joined horizontally, so that ``` [[0] [1] [[0][1] [1] + [0] = [1][0] [4] [1] [4][1] [0]] [1]] [0][1]] ``` For example, with these matrices: `...
Judging from the traceback, it seems like you've done `from scipy.sparse import *` or something similar, so that `numpy.hstack` is shadowed by `scipy.sparse.hstack`. `numpy.hstack` works fine: ``` >>> X = np.matrix([[0, 1, 4, 0]]).T >>> Y = np.matrix([[1, 0, 1, 1]]).T >>> np.hstack([X, Y]) matrix([[0, 1], [1, ...
How to change tcp keepalive timer using python script?
12,248,132
15
2012-09-03T12:42:43Z
14,855,726
29
2013-02-13T14:25:22Z
[ "python", "tcp", "keep-alive" ]
In my python script, I have activate TCP Keepalive using this command: ``` x = s.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ``` My goal is for socket connection to get closed, if there is no transmission(\*) for 5 minutes. I am working on Windows and my python script is only receiving and not transmitting...
You can set the TCP keepalive timers on an already-open socket using setsockopt(). ``` import socket def set_keepalive_linux(sock, after_idle_sec=1, interval_sec=3, max_fails=5): """Set TCP keepalive on an open socket. It activates after 1 second (after_idle_sec) of idleness, then sends a keepalive ping ...
How to use numpy with OpenBLAS instead of Atlas in Ubuntu?
12,249,089
12
2012-09-03T13:44:17Z
12,251,204
13
2012-09-03T16:12:00Z
[ "python", "ubuntu", "numpy", "installation", "blas" ]
I have looked for an easy way to install/compile Numpy with OpenBLAS but didn't find an easy answer. All the documentation I have seen takes too much knowledge as granted for someone like me who is not used to compile software. There are two packages in Ubuntu related to OpenBLAS : `libopenblas-base` and `libopenblas-d...
Run `sudo update-alternatives --all` and set `liblapack.so.3gf` to `/usr/lib/lapack/liblapack.so.3gf`
How to use numpy with OpenBLAS instead of Atlas in Ubuntu?
12,249,089
12
2012-09-03T13:44:17Z
32,422,482
8
2015-09-06T10:22:12Z
[ "python", "ubuntu", "numpy", "installation", "blas" ]
I have looked for an easy way to install/compile Numpy with OpenBLAS but didn't find an easy answer. All the documentation I have seen takes too much knowledge as granted for someone like me who is not used to compile software. There are two packages in Ubuntu related to OpenBLAS : `libopenblas-base` and `libopenblas-d...
To add to the accepted answer (of using `update-alternatives`), the reason for this is because OpenBlas is not compatible with the Atlas version of Lapack. For each of the Blas and Lapack versions: 1. Default Blas + Default Lapack => OK 2. OpenBlas + Default Lapack => OK 3. Atlas-Blas + Default Lapack => OK 4. Atlas-B...
How to log memory usage of an Django app per request
12,249,150
12
2012-09-03T13:48:34Z
12,254,394
12
2012-09-03T21:48:57Z
[ "python", "django", "apache", "memory-leaks" ]
Do you know about an efficient way to log memory usage of a django app per request ? I have an apache/mod\_wsgi/django stack, which runs usually well, but sometimes one process ends up eating a huge lot of memory. The servers ends up being short on mem, swapping a lot, and services are dramatically slowed down. This ...
A Django middleware for tracking memory usage and generating a usable result immediately, needs to hook both process request and process response. In other words, look at difference between start and finish of request and log a warning if exceeds some threshold. A complete middleware example is: ``` import os import ...
How to obtain sheet names from XLS files without loading the whole file?
12,250,024
15
2012-09-03T14:44:51Z
12,250,416
18
2012-09-03T15:12:35Z
[ "python", "excel", "pandas", "xlrd" ]
I'm currently using pandas to read an Excel file and present its sheet names to the user, so he can select which sheet he would like to use. The problem is that the files are really big (70 columns x 65k rows), taking up to 14s to load on a notebook (the same data in a CSV file is taking 3s). My code in panda goes lik...
you can use the [xlrd](http://pypi.python.org/pypi/xlrd) library and open the workbook with the "on\_demand=True" flag, so that the sheets won't be loaded automaticaly. Than you can retrieve the sheet names in a similar way to pandas: ``` import xlrd xls = xlrd.open_workbook(r'<path_to_your_excel_file>', on_demand=Tr...
Python, pinax, django, windows AttributeError: 'module' object has no attribute 'call_subprocess'
12,250,317
2
2012-09-03T15:04:58Z
12,521,077
12
2012-09-20T21:19:03Z
[ "python", "django", "windows", "virtualenv", "pinax" ]
I installed pinax on windows after trying to create a project I got this error: ``` (mysite) C:\virtualenvs\mysite>pinax-admin setup_project mypinax Created project mypinax Installing project requirements... Traceback (most recent call last): File "c:\virtualenvs\mysite\Scripts\pinax-admin-script.py", line 8, in <m...
You have new version of **pip**, the function `pip.call_subprocess` has been moved to `pip.util.call_subprocess`. See: <https://github.com/pypa/pip/pull/464> Just replace the string in `C:\virtualenvs\mysite\lib\site-packages\pinax\core\management\commands\setup_project.py` Before executing the pinax-admin
Parse birth and death dates from Wikipedia?
12,250,580
8
2012-09-03T15:24:54Z
12,250,675
7
2012-09-03T15:31:47Z
[ "python", "mediawiki", "wikipedia", "wikipedia-api", "mediawiki-api" ]
I'm trying to write a python program that can search wikipedia for the birth and death dates for people. For example, Albert Einstein was born: 14 March 1879; died: 18 April 1955. I started with [Fetch a Wikipedia article with Python](http://stackoverflow.com/questions/120061/fetch-a-wikipedia-article-with-python) `...
You can consider using a library such as [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) or [lxml](http://lxml.de) to parse the response html/xml. You may also want to take a look at [`Requests`](http://docs.python-requests.org/en/latest/index.html), which has a much cleaner API for making reque...
What's the pythonic way to wrap several functions in the same with statements
12,251,620
6
2012-09-03T16:51:11Z
12,251,659
11
2012-09-03T16:54:54Z
[ "python", "eval", "fabric", "with-statement", "contextmanager" ]
I am using the Python library, [Fabric](http://docs.fabfile.org/en/1.4.3/index.html), to do some remote server maintenance. Fabric automatically outputs all of the responses to remote and local commands unless you wrap the command in a couple with statements. Like so, on a local machine, ``` with settings(warn_only='t...
The better solution would be for you to build your own context manager; by far the easiest way would be to use the [`contextlib.contextmanager` decorator](http://docs.python.org/library/contextlib.html#contextlib.contextmanager): ``` from contextlib import contextmanager @contextmanager def _mute(): with settings...
KVM api to start virtual machine
12,251,881
4
2012-09-03T17:17:10Z
12,259,532
7
2012-09-04T08:26:30Z
[ "python", "kvm" ]
I was wondering if there is a KVM API which allows you to start a KVM virtual machine using a simple command, from a python script. My Python script performs a series of checks to see whether or not we need to start a specific VM, and I would like to start a VM if I need to. All I need now is to find the API calls, b...
You can use the create() function from the python API bindings of libvirt: ``` import libvirt #connect to hypervisor running on localhost conn = libvirt.open('qemu:///system') dom0 = conn.lookupByName('my-vm-1') dom0.create() ``` basically the python API is the C API, called by libvirt.C\_API\_CALL minus the virCon...
Colorize image while preserving transparency with PIL?
12,251,896
4
2012-09-03T17:19:10Z
12,310,820
8
2012-09-07T02:10:22Z
[ "python", "image", "transparency", "python-imaging-library", "colorize" ]
Okay, here's the situation: I want to use the Python Image Library to "theme" an image like this: Theme color: ![swatch showing tint color](http://i.stack.imgur.com/b7ZlA.png) `"#33B5E5"` IN: ![http://mupload.nl/img/olpiyj9is.png](http://i.stack.imgur.com/9dLMw.png) OUT: ![http://mupload.nl/img/fiaoq6gk5.png](http:/...
**Update 4.0.1**: There's a Python 3/pillow fork of PIL version of this answer [here](http://stackoverflow.com/a/29379704/355230). **Update 4**: Guess the previous update to my answer wasn't the last one after all. Although converting it to use`PIL`exclusively was a major improvement, there were a couple of things tha...
Error "No such file or directory" when running Django ./manage.py
12,252,198
4
2012-09-03T17:50:11Z
16,741,864
7
2013-05-24T18:58:05Z
[ "python", "django", "bash", "virtualenv" ]
In my `django` project, the command `./manage.py [command]` results in this error message: ``` : No such file or directory ``` The command `python manage.py [command]` works well. I tried with `syncdb` and `runserver`. I tried `chmod a+x manage.py`, but the problem persists. My manage.py: ``` #!/usr/bin/env python ...
Likely, the reason is because your line endings in the manage.py file are \n instead of \r\n. As a result the #! hash-bang is misinterpreted. This happens to me when I use a Windows based text-editor for my linux connection.
Return statement using ternary operator
12,252,564
5
2012-09-03T18:26:20Z
12,252,575
25
2012-09-03T18:27:26Z
[ "python", "ternary-operator" ]
In `c` I can do something like: ``` int minn(int n, int m){ return (n<m)? n:m } ``` But in python I am not able to achieve the same: ``` def minn(n,m): return n if n<m else return m ``` this gives `Syntax Error` I know I can do something like : ``` def minn(n,m): return min(n,m) ``` My question is that,...
Your C code doesn't contain two `return` statements. Neither should your python code... The translation of your ternary expression is `n if n<m else m`, so just use that expression when you return the value: ``` def minn(n,m): return n if n<m else m ```
Return statement using ternary operator
12,252,564
5
2012-09-03T18:26:20Z
12,252,598
7
2012-09-03T18:30:08Z
[ "python", "ternary-operator" ]
In `c` I can do something like: ``` int minn(int n, int m){ return (n<m)? n:m } ``` But in python I am not able to achieve the same: ``` def minn(n,m): return n if n<m else return m ``` this gives `Syntax Error` I know I can do something like : ``` def minn(n,m): return min(n,m) ``` My question is that,...
``` def minn(n,m): return n if n<m else m ``` The `expr1 if expr2 else expr3` expression is an expression, not a statement. `return` is a statement (See [this](http://stackoverflow.com/questions/4728073/python-what-is-the-difference-between-an-expression-and-a-statement) question) Because expressions cannot conta...
Why does Popen fail on Windows if the "env" parameter contains a unicode object?
12,253,014
7
2012-09-03T19:18:28Z
12,253,097
10
2012-09-03T19:27:24Z
[ "python", "windows" ]
Consider this example: ``` >>> import subprocess as sp >>> sp.Popen("notepad2.exe",env={"PATH":"C:\\users\\guillermo\\smallapps\\bin"}) <subprocess.Popen object at 0x030DF430> >>> sp.Popen("notepad2.exe",env={"PATH":u"C:\\users\\guillermo\\smallapps\\bin"}) Traceback (most recent call last): File "<stdin>", line 1, ...
As the error message says, the environment must only contain strings. Your first `Popen` call satisfies this condition, but the second one doesn't because you are mapping `PATH` to a Unicode object created with the `u"..."` syntax. Use only byte strings when providing environment dicts to `Popen` and you will not get t...
Distinguishing overfitting vs good prediction
12,253,151
23
2012-09-03T19:32:23Z
12,254,521
25
2012-09-03T22:06:01Z
[ "python", "numpy", "machine-learning", "regression", "scikit-learn" ]
These are questions on how to calculate & reduce overfitting in machine learning. I think many new to machine learning will have the same questions, so I tried to be clear with my examples and questions in hope that answers here can help others. I have a very small sample of texts and I'm trying to predict values asso...
> how would you normally tell that the model is over-fitting? [One useful rule of thumb](http://digitheadslabnotebook.blogspot.nl/2011/12/practical-advice-for-applying-machine.html) is that you may be overfitting when your model's performance on its own training set is much better than on its held-out validation set o...
How is Lisp's read-eval-print loop different than Python's?
12,253,200
51
2012-09-03T19:38:45Z
12,253,272
52
2012-09-03T19:45:57Z
[ "python", "functional-programming", "lisp", "read-eval-print-loop" ]
I've encounter a following [statement by Richard Stallman](http://stallman.org/stallman-computing.html): > 'When you start a Lisp system, it enters a read-eval-print loop. Most other languages have nothing comparable to read, nothing comparable to eval, and nothing comparable to print. What gaping deficiencies! ' Now...
In support of Stallman's position, Python does not do the same thing as typical Lisp systems in the following areas: * The `read` function in Lisp reads an S-expression, which represents an arbitrary data structure that can either be treated as data, or evaluated as code. The closest thing in Python reads a single str...
How is Lisp's read-eval-print loop different than Python's?
12,253,200
51
2012-09-03T19:38:45Z
12,253,402
23
2012-09-03T20:01:04Z
[ "python", "functional-programming", "lisp", "read-eval-print-loop" ]
I've encounter a following [statement by Richard Stallman](http://stallman.org/stallman-computing.html): > 'When you start a Lisp system, it enters a read-eval-print loop. Most other languages have nothing comparable to read, nothing comparable to eval, and nothing comparable to print. What gaping deficiencies! ' Now...
Stallman's point is that not implementing an explicit "reader" makes Python's REPL appear crippled compared to Lisps because it removes a crucial step from the REPL process. Reader is the component that transforms a textual input stream into the memory — think of something like an XML parser built into the language a...
How is Lisp's read-eval-print loop different than Python's?
12,253,200
51
2012-09-03T19:38:45Z
12,253,421
17
2012-09-03T20:03:07Z
[ "python", "functional-programming", "lisp", "read-eval-print-loop" ]
I've encounter a following [statement by Richard Stallman](http://stallman.org/stallman-computing.html): > 'When you start a Lisp system, it enters a read-eval-print loop. Most other languages have nothing comparable to read, nothing comparable to eval, and nothing comparable to print. What gaping deficiencies! ' Now...
In a Lisp-based system one typically develops the program while it is running from the REPL (read eval print loop). So it integrates a bunch of tools: completion, editor, command-line-interpreter, debugger, ... The default is to have that. Type an expression with an error - you are in another REPL level with some debug...
Python list intersection with non unique items
12,253,361
6
2012-09-03T19:56:45Z
12,253,376
10
2012-09-03T19:58:29Z
[ "python", "intersection", "multiset" ]
I have two strings and I would like to have the intersection on them *including* duplicate items: ``` str_a = "aabbcc" str_b = "aabd" list(set(str_a) & set(str_b)) >> "ab" ``` I would like to have it return: ``` >> "aab" ``` Any ideas?
Multisets are implemented in python 2.7 or later as (mutable) `Counter` objects. You can perform many of the same operations as you can for sets, such as union, intersection, difference (though counts can become negative), etc.: ``` from collections import Counter as mset ``` Solution: ``` (mset("aabbcc") & mset("aa...