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
Check if an open file has been deleted after open in python
12,690,281
13
2012-10-02T12:30:08Z
12,690,767
12
2012-10-02T13:01:50Z
[ "python", "filesystems" ]
Is it possible to check if a file has been deleted or recreated in python? For example, if you did a `open("file")` in the script, and then while that file is still open, you do `rm file; touch file;`, then the script will still hold a reference to the old file even though it's already been deleted.
You should `fstat` the file descriptor for the opened file. ``` >>> import os >>> f = open("testdv.py") >>> os.fstat(f.fileno()) posix.stat_result(st_mode=33188, st_ino=1508053, st_dev=65027L, st_nlink=1, st_uid=1000, st_gid=1000, st_size=1107, st_atime=1349180541, st_mtime=1349180540, st_ctime=1349180540) >>> os.fsta...
Mercurial / hg - abort: outstanding uncommitted merges
12,690,557
25
2012-10-02T12:47:45Z
12,690,559
47
2012-10-02T12:47:45Z
[ "python", "mercurial" ]
I have a master repo on host1 and made an update to a repo on host2. I `hg push`ed the changes from host2 to host1 with ``` [mpenning@host2 login]$ hg push ssh://host1//opt/python/login ``` However, when I try to update or merge, I get ``` [mpenning@host1 login]$ hg update abort: outstanding uncommitted merges [mpe...
`hg update --clean -r tip` resolved the problem... ``` [mpenning@host1 login]$ hg update --clean -r tip resolving manifests getting Protocol.py getting Session.py getting mp_getconf.py getting mp_runcmd.py 4 files updated, 0 files merged, 0 files removed, 0 files unresolved [mpenning@host1 login]$ hg up resolving mani...
Mercurial / hg - abort: outstanding uncommitted merges
12,690,557
25
2012-10-02T12:47:45Z
12,731,329
7
2012-10-04T16:07:28Z
[ "python", "mercurial" ]
I have a master repo on host1 and made an update to a repo on host2. I `hg push`ed the changes from host2 to host1 with ``` [mpenning@host2 login]$ hg push ssh://host1//opt/python/login ``` However, when I try to update or merge, I get ``` [mpenning@host1 login]$ hg update abort: outstanding uncommitted merges [mpe...
At some point you did: ``` $ hg pull (or maybe someone pushed to you) $ hg merge ``` ...and then carried on. This left the merge uncommitted. That's what 'abort: outstanding uncommitted merges' means. You can't do 'x' because there's you haven't finished working on the merge you started. What you should have done is...
Defining a global function in a Python script
12,691,949
7
2012-10-02T14:11:18Z
12,692,068
10
2012-10-02T14:17:28Z
[ "python", "function", "python-2.7", "global" ]
I'm new to Python. I am writing a script that will numerically integrate a set of ordinary differential equations using a Runge-Kutta method. Since the Runge-Kutta method is a useful mathematical algorithm, I've put it in its own .py file, rk4.py. ``` def rk4(x,dt): k1=diff(x)*dt k2=diff(x+k1/2)*dt k3=diff...
Accept the function as an argument: ``` def rk4(diff, # accept an argument of the function to call x, dt) k1=diff(x)*dt k2=diff(x+k1/2)*dt k3=diff(x+k2/2)*dt k4=diff(x+k3)*dt return x+(k1+2*k2+2*k3+k4)/6 ``` Then, when you call `rk4`, simply pass in the function to be executed: ``` from ...
Error: Cursor' object has no attribute '_last_executed
12,692,043
9
2012-10-02T14:16:20Z
14,474,133
7
2013-01-23T07:01:46Z
[ "python", "django", "string", "cursor", "rawsql" ]
I have this cursor ``` cursor.execute("SELECT price FROM Items WHERE itemID = ( SELECT item_id FROM Purchases WHERE purchaseID = %d AND customer_id = %d)", [self.purchaseID, self.customer]) ``` I get this error ``` 'Cursor' object has no attribute '_last_execu...
I encountered this problem too. I changed the %d to %s, and it is solved. Wish this is useful for you.
Create dictionary from lists of keys and multiple values
12,692,135
4
2012-10-02T14:21:32Z
12,692,201
7
2012-10-02T14:24:29Z
[ "python" ]
I have two lists: ``` header = ["Name", "Age"] detail = ["Joe", 22, "Dave", 43, "Herb", 32] ``` And would like to create a list of dictonaries like this: ``` [{"Name": "Joe", "Age": 22}, {"Name": "Dave", "Age": 32}, {"Name": "Herb", "Age": 32}] ``` This method [zip](http://docs.python.org/library/functions.html#zip...
``` >>> detail = ["Joe", 22, "Dave", 43, "Herb", 32] >>> d = dict(zip(detail[::2], detail[1::2])) >>> d {'Herb': 32, 'Dave': 43, 'Joe': 22} ``` For your new/edited question: ``` >>> d = [dict(zip(header, items)) for items in zip(detail[::2],detail[1::2])] >>> d [{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}...
python regular expression. Extract text between patterns
12,692,667
4
2012-10-02T14:49:48Z
12,692,765
8
2012-10-02T14:54:55Z
[ "python", "regex" ]
How to get all the values in between 'uniprotkb:' and '(gene name)' in the 'str' below: ``` str = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:...
Using re.findall(), you can get all parts of a string that match a regular expression: ``` >>> import re >>> sstr = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gen...
why does right-clicking create an orange dot in the center of the circle?
12,692,851
12
2012-10-02T14:59:19Z
12,699,681
11
2012-10-02T23:02:27Z
[ "python", "kivy" ]
Why does [the first widget example](http://kivy.org/docs/guide/firstwidget.html) in kivy lead to an orange circle in the middle of the yellow one when you right click on the canvas and a pure yellow one when you left click? ``` from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics ...
It's multitouch emulation, you can see how to disable it here <http://kivy.org/docs/api-kivy.input.providers.mouse.html>
Reason for globals() in Python?
12,693,606
35
2012-10-02T15:39:46Z
12,694,065
50
2012-10-02T16:07:15Z
[ "python", "global-variables", "global" ]
What is the reason of having globals() function in Python? It only returns dictionary of global variables, which are already global, so they can be used anywhere... I'm asking only out of curiosity, trying to learn python. ``` def F(): global x x = 1 def G(): print(globals()["x"]) #will return value of gl...
Python gives the programmer a large number of tools for introspecting the running environment. `globals()` is just one of those, and it can be very useful in a debugging session to see what objects the global scope actually contains. The rationale behind it, I'm sure, is the same as that of using `locals()` to see the...
Reason for globals() in Python?
12,693,606
35
2012-10-02T15:39:46Z
18,965,612
21
2013-09-23T17:46:34Z
[ "python", "global-variables", "global" ]
What is the reason of having globals() function in Python? It only returns dictionary of global variables, which are already global, so they can be used anywhere... I'm asking only out of curiosity, trying to learn python. ``` def F(): global x x = 1 def G(): print(globals()["x"]) #will return value of gl...
It's also useful when you need to call a function using function's string name. For example: ``` def foo(): pass function_name_as_string = 'foo' globals()[function_name_as_string]() # foo(). ```
time.sleep hangs multithread function in python
12,693,690
2
2012-10-02T15:45:01Z
12,693,773
8
2012-10-02T15:49:34Z
[ "python", "python-3.x", "multiprocessing" ]
I am having trouble with a sleep statement hanging my multithreading function. I want my function to go about it's buisness while the rest of the program runs. Here is a toy that recreates my problem: ``` import multiprocessing, sys, time def f(icount, _sleepTime = 1): for i in range(icount): time.sleep(_...
Use `start` and `join` instead of `run`: ``` import multiprocessing, sys, time def f(icount, _sleepTime = 1): for i in range(icount): time.sleep(_sleepTime) print(_sleepTime) def main(args): m = multiprocessing.Process(target = f, args=(4, )) m.start() # f should be sleeping for 1 sec...
Python lxml - How to remove empty repeated tags
12,694,091
5
2012-10-02T16:09:15Z
12,694,730
10
2012-10-02T16:52:15Z
[ "python", "xml", "lxml" ]
I have some XML that is generated by a script that may or may not have empty elements. I was told that now we cannot have empty elements in the XML. Here is an example: ``` <customer> <govId> <id>@</id> <idType>SSN</idType> <issueDate/> <expireDate/> <dob/> ...
First of all, the problem with your code is that you are iterating over `customers`, but not over `govIds`. On the third line you take the *first* `govId` for every customer, and iterate over its children. So, you'd need a another `for` loop for the code to work like you intended it to. This small sentence at the end ...
how to cleanly remove ndb properties
12,694,569
10
2012-10-02T16:40:50Z
12,701,172
28
2012-10-03T02:32:46Z
[ "python", "google-app-engine", "app-engine-ndb", "polymodel" ]
in my app i need to remove a few of my models properties. i checked out [this link](https://developers.google.com/appengine/articles/update_schema) but the first issue is that the properties are on a `polymodel` and there is no way im going to switch to an `expando` for the time to remove the properties, im not even ...
If you want to update all your entities the recommended approach is a map/reduce job that reads and rewrites all entities; however it may not be worth it, depending on how much data you have -- the map/reduce isn't free either. Also be sure you test the map/reduce job on a small subset of the data. It is remarkably su...
Error on running transaction with multiple entity groups through nosetests
12,695,592
9
2012-10-02T17:53:48Z
12,696,287
15
2012-10-02T18:43:41Z
[ "python", "google-app-engine", "nose" ]
I am building an application with Python 2.7 using the Google App Engine framework. To test my application I have a several tests that are run through nosetests making use of the nosegae plugin. I run them with the following command: ``` nosetests --with-gae --gae-lib-root=/usr/local/google_appengine/ -w . -w */test/ ...
I would highly suggest you to switch from **db** to **ndb**, where you can use [cross group transactions](https://cloud.google.com/appengine/docs/python/ndb/transactions). To simulate the HRD, you can add this part to the `setUp` function of your tests, from [Writing High Replication Datastore tests](https://cloud.goo...
How to modify the navigation toolbar easily in a matplotlib figure window?
12,695,678
8
2012-10-02T18:00:19Z
15,549,675
12
2013-03-21T14:01:34Z
[ "python", "matplotlib" ]
Is it possible to do something like the following to modify the navigation toolbar in matplotlib? 1. Generate a figure window, with: `fig = figure()` 2. Get a reference of the navigation tool-bar, with: `tbar = fig.get_navigation_toolbar()`, or better yet, just by: `tbar = fig.navtbar` 3. Modify the tool-bar throug...
The way I found to remove unwanted toolbar items is making a subclass, which is instantiated and used in a GTK application. As I manually create Figure, FigureCanvas and NavigationToolbar objects anyway, this was the easiest way. ``` class NavigationToolbar(NavigationToolbar2GTKAgg): # only display the buttons we ...
failed to set __main__.__loader__ in Python
12,696,151
12
2012-10-02T18:34:13Z
12,942,390
9
2012-10-17T20:01:36Z
[ "python" ]
When running any Python script (by double clicking a .py file on Windows 7) I'm getting a `Python: failed to set __main__.__loader__` error message. What to do? **More details:** * The scripts work on other machines. * The only version of Python installed on the machine on which the scripts don't work is 3.2. * I get...
I had the same problem. Turns out it was because the file was stored in a directory with a name not in English (Hebrew in my case). Make sure the path to the file contains only English letters. <http://bugs.python.org/issue16218>
Tornado: Can I run code after calling self.finish() in an asynchronous RequestHandler?
12,696,291
6
2012-10-02T18:44:11Z
19,519,508
9
2013-10-22T13:37:40Z
[ "python", "tornado" ]
I'm using Tornado. I have a bunch of asynchronous request handlers. Most of them do their work asynchronously, and then report the result of that work back to the user. But I have one handler whose job it is to simply tell the user that their request is going to be processed at some point in the future. I finish the HT...
**Yes, you can.** You have to define `on_finish` method of your `RequestHandler`. This is a function run after the request finished and has sent the response to client. > [`RequestHandler.on_finish()`](http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.on_finish) > > Called after the end of a req...
Python if Statement Invalid Syntax!? Why?
12,696,427
5
2012-10-02T18:52:58Z
12,696,702
7
2012-10-02T19:11:43Z
[ "python", "if-statement" ]
``` while x < len(Hand): while y < len(Hand): if Hand[x][0] == Hand[y][0] and y != x: sameRank += 1 y += 1 x += 1 ``` It highlights a space right before the "if" and says syntax error...Makes no sense.
I don't see any errors here, but it's possible that you're indenting the block below your if statement too much. Notice that the rest of your program uses 4 spaces to indent? Try reducing the indentation to just 4 spaces and see if it runs. **Your code does have a logic error, however**. You won't loop through y for e...
Why is Python's eval() rejecting this multiline string, and how can I fix it?
12,698,028
4
2012-10-02T20:44:45Z
12,698,067
13
2012-10-02T20:47:20Z
[ "python", "python-3.x", "metaprogramming", "eval" ]
I am attempting to eval the following tab-indented string: ``` '''for index in range(10): os.system("echo " + str(index) + "") ''' ``` I get, "There was an error: invalid syntax , line 1" What is it complaining about? Do I need to indent to match the eval() statement, or write it to a string file or temp fil...
`eval` evaluates stuff like `5+3` `exec` executes stuff like `for ...` ``` >>> eval("for x in range(3):print x") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 for x in range(3):print x ^ SyntaxError: invalid syntax >>> exec("for x in range(3):print x") 0 ...
Why is Python's eval() rejecting this multiline string, and how can I fix it?
12,698,028
4
2012-10-02T20:44:45Z
12,698,145
7
2012-10-02T20:52:10Z
[ "python", "python-3.x", "metaprogramming", "eval" ]
I am attempting to eval the following tab-indented string: ``` '''for index in range(10): os.system("echo " + str(index) + "") ''' ``` I get, "There was an error: invalid syntax , line 1" What is it complaining about? Do I need to indent to match the eval() statement, or write it to a string file or temp fil...
To use such statements with `eval` you should convert them to code object first, using `compile()`: ``` In [149]: import os In [150]: cc=compile ('''for index in range(10): os.system("echo " + str(index) + "")''','abc','single') In [154]: eval cc --------> eval(cc) 0 Out[154]: 0 1 Out[154]: 0 2 Out[154]: 0 3 Out...
How to debug Celery/Django tasks running localy in Eclipse
12,698,212
14
2012-10-02T20:57:24Z
12,705,610
21
2012-10-03T09:31:41Z
[ "python", "eclipse", "celery" ]
I need to debug Celery task from the Eclipse debugger. I'm using Eclipse, PyDev and Django. First, I open my project in Eclipse and put a breakpoint at the beginning of the task function. Then, I'm starting the Celery workers from Eclipse by Right Clicking on manage.py from the PyDev Package Explorer and choosing "De...
You should consider the option to run the celery task in the same thread as the main process (normally it runs on a separate process), this will make the debug much easier. You can tell celery to run the task in sync by adding this setting to your settings.py module: ``` CELERY_ALWAYS_EAGER = True ``` Note: this is ...
How do I pass options to the Selenium Chrome driver using Python?
12,698,843
24
2012-10-02T21:45:15Z
12,698,844
43
2012-10-02T21:45:15Z
[ "python", "google-chrome", "selenium", "selenium-chromedriver" ]
The [Selenium documentation](http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.webdriver.html#module-selenium.webdriver.chrome.webdriver) mentions that the Chrome webdriver can take an instance of `ChromeOptions`, but I can't figure out how to create `ChromeOptions`. I'm h...
Found the [chrome Options class in the Selenium source code](https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/chrome/options.py). Usage to create a Chrome driver instance: ``` from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome...
How to setup enviroment variable R_user to use rpy2 in python
12,698,877
5
2012-10-02T21:48:12Z
25,479,841
10
2014-08-25T06:03:41Z
[ "python", "error-handling", "installation" ]
I 'm unable to run rpy2 in python. with this code ``` import rpy2.robjects as robjects ``` Here's the full exceptions : --- RuntimeError: R\_USER not defined. File "d:\py\r\r.python.py", line 1, in ``` import rpy2.robjects as robjects File "c:\Python27\Lib\site-packages\rpy2\robjects\__init__.py", line 17, i...
Here is the way I fixed my **R** package version **3.0.2** python version **2.7** platform ipython notebook. Change Path for R computer-> property -> advanced and system setting -> environment variables in the user variable field add `C:\Program Files\R\R-3.0.2\bin\x64` (my system is windows 64bit) to path In the sy...
Python: block character will not print
12,699,827
3
2012-10-02T23:19:03Z
12,699,884
7
2012-10-02T23:24:40Z
[ "python", "character-encoding", "ascii", "block", "non-ascii-characters" ]
In IDLE, `print(chr(219))` (219's the block character) outputs "Û". Is there any way to get it to output the block character instead? This might actually be some sort of computer-wide problem, as I cannot seem to get the block character to print from anywhere, copying it out of charmap and into **any** textbox just ...
Use the correct character set. ``` 3>> print(bytes((219,)).decode('cp437')) █ 3>> ord(bytes((219,)).decode('cp437')) 9608 3>> hex(9608) '0x2588' 3>> print('\u2588') █ ``` [Unicode Character 'FULL BLOCK' (U+2588)](http://www.fileformat.info/info/unicode/char/2588/index.htm)
How to check if a string is a valid python identifier? including keyword check?
12,700,893
10
2012-10-03T01:47:58Z
12,700,971
13
2012-10-03T01:59:40Z
[ "python", "keyword", "identifier", "reserved" ]
Does anyone know if there is any builtin python method that will check if something is a valid python variable name, INCLUDING a check against reserved keywords? (so, ie, something like 'in' or 'for' would fail...) Failing that, does anyone know of where I can get a list of reserved keywords (ie, dyanamically, from wi...
The `keyword` module contains the list of all reserved keywords: ``` >>> import keyword >>> keyword.iskeyword("in") True >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'no...
How to check if a string is a valid python identifier? including keyword check?
12,700,893
10
2012-10-03T01:47:58Z
15,570,599
11
2013-03-22T12:41:08Z
[ "python", "keyword", "identifier", "reserved" ]
Does anyone know if there is any builtin python method that will check if something is a valid python variable name, INCLUDING a check against reserved keywords? (so, ie, something like 'in' or 'for' would fail...) Failing that, does anyone know of where I can get a list of reserved keywords (ie, dyanamically, from wi...
John: as a slight improvement, I added a $ in the re, otherwise, the test does not detect spaces: ``` import keyword import re my_var = "$testBadVar" print re.match("[_A-Za-z][_a-zA-Z0-9]*$",my_var) and not keyword.iskeyword(my_var) ```
How to check if a string is a valid python identifier? including keyword check?
12,700,893
10
2012-10-03T01:47:58Z
29,586,366
16
2015-04-12T05:41:18Z
[ "python", "keyword", "identifier", "reserved" ]
Does anyone know if there is any builtin python method that will check if something is a valid python variable name, INCLUDING a check against reserved keywords? (so, ie, something like 'in' or 'for' would fail...) Failing that, does anyone know of where I can get a list of reserved keywords (ie, dyanamically, from wi...
Python 3 now has `'foo'.isidentifier()`, so that seems to be the best solution for recent Python versions. Thanks fellow *runciter@freenode* for suggestion. For Python 2, easiest possible way to check if given string is valid Python identifier is to let Python parse it itself. There are two possible approaches. First...
How to extend Python class init
12,701,206
14
2012-10-03T02:39:04Z
12,701,228
20
2012-10-03T02:44:00Z
[ "python", "class", "inheritance", "initialization" ]
I have created a base class: ``` class Thing(): def __init__(self, name): self.name = name ``` I want to extend the class and add to the **init** method so the that `SubThing` has both a `name` and a `time` property. How do I do it? ``` class SubThing(Thing): # something here to extend the init and a...
You can just define `__init__` in the subclass and call `super` to call the parents' `__init__` methods appropriately: ``` class SubThing(Thing): def __init__(self, *args, **kwargs): super(SubThing, self).__init__(*args, **kwargs) self.time = datetime.now() ``` Make sure to have your base class su...
Finding range of a numpy array elements
12,701,659
5
2012-10-03T03:54:11Z
12,701,677
12
2012-10-03T03:56:35Z
[ "python", "arrays", "numpy" ]
This is a very simple question: I have a numpy array of 94 x 155: ``` a = [1 2 20 68 210 290.. 2 33 34 55 230 340.. .. .. ... .. ... .....] ``` I want to calculate the range of each row..so that I get 94 ranges in a result. I tried looking for numpy.range function, which I don't think exists. If t...
I think `np.ptp` might do what you want: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.ptp.html> ``` r = np.ptp(a,axis=1) ``` where `r` is your range array.
mysql for python 2. 7 says Python v2.7 not found
12,702,146
9
2012-10-03T04:57:43Z
12,757,375
7
2012-10-06T06:33:23Z
[ "python", "mysql", "python-2.7", "mysql-connector-python" ]
I have downloaded mysql-connector-python-1.0.7-py2.7.msi from MySQL site and try to install but it gives error that **Python v2.7 not found. We only support Microsoft Windows Installer(MSI) from python.org.** I am using Official Python v 2.7.3 on windows XP SP3 with MySQL esssential5.1.66 Need Help ???
The Solution I get for this problem is I have found Adding Python to Registry, the script as follows applicable for python v 2.0 and above: Register a Python Interpreter ``` # # script to register Python 2.0 or later for use with win32all # and other extensions that require Python registry settings # # written by Jo...
mysql for python 2. 7 says Python v2.7 not found
12,702,146
9
2012-10-03T04:57:43Z
13,899,478
10
2012-12-16T07:41:06Z
[ "python", "mysql", "python-2.7", "mysql-connector-python" ]
I have downloaded mysql-connector-python-1.0.7-py2.7.msi from MySQL site and try to install but it gives error that **Python v2.7 not found. We only support Microsoft Windows Installer(MSI) from python.org.** I am using Official Python v 2.7.3 on windows XP SP3 with MySQL esssential5.1.66 Need Help ???
I met the similar problem under Windows 7 when installing `mysql-connector-python-1.0.7-py2.7.msi` and `mysql-connector-python-1.0.7-py3.2.msi`. After changing from `"Install only for yourself"` to `"Install for all users"` when installing Python for windows, the `"python 3.2 not found"` problem disappear and `mysql-c...
return column names from pyodbc execute() statement
12,704,305
10
2012-10-03T08:05:48Z
12,707,465
26
2012-10-03T11:23:18Z
[ "python", "pandas", "pyodbc" ]
``` from pandas import DataFrame import pyodbc cnxn = pyodbc.connect(databasez) cursor.execute("""SELECT ID, NAME AS Nickname, ADDRESS AS Residence FROM tablez""") DF = DataFrame(cursor.fetchall()) ``` This is fine to populate my pandas DataFrame. But how do I get ``` DF.columns = ['ID', 'Nickname', 'Residence'] ```...
You can get the columns from the cursor description: `columns = [column[0] for column in cursor.description]`
return column names from pyodbc execute() statement
12,704,305
10
2012-10-03T08:05:48Z
17,491,690
9
2013-07-05T14:52:48Z
[ "python", "pandas", "pyodbc" ]
``` from pandas import DataFrame import pyodbc cnxn = pyodbc.connect(databasez) cursor.execute("""SELECT ID, NAME AS Nickname, ADDRESS AS Residence FROM tablez""") DF = DataFrame(cursor.fetchall()) ``` This is fine to populate my pandas DataFrame. But how do I get ``` DF.columns = ['ID', 'Nickname', 'Residence'] ```...
Recent pandas have a higher level [`read_sql`](http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries) functions that can do this for you ``` import pyodbc import pandas as pd cnxn = pyodbc.connect(databasez) DF = pd.read_sql_query("SELECT ID, NAME AS Nickname, ADDRESS AS Residence FROM tablez", cnxn) ```
Regex to split words in Python
12,705,293
10
2012-10-03T09:12:17Z
12,705,513
13
2012-10-03T09:25:37Z
[ "python", "regex", "split" ]
I was designing a regex to **split** all the **actual words** from a given **text**: *Input Example:* ``` "John's mom went there, but he wasn't there. So she said: 'Where are you'" ``` *Expected Output:* ``` ["John's", "mom", "went", "there", "but", "he", "wasn't", "there", "So", "she", "said", "Where", "are", "you...
Instead of regex, you can use string-functions: ``` to_be_removed = ".,:!" # all characters to be removed s = "John's mom went there, but he wasn't there. So she said: 'Where are you!!'" for c in to_be_removed: s = s.replace(c, '') s.split() ``` **BUT**, in your example you do not want to remove apostrophe in `J...
Python lambda with if but without else
12,709,062
13
2012-10-03T13:00:18Z
12,709,152
23
2012-10-03T13:05:54Z
[ "python", "lambda", "inline-if" ]
I was writing some lambda functions and couldn't figure this out. Is there a way to have something like `lambda x: x if (x<3)` in python? As `lambda a,b: a if (a > b) else b` works ok. So far `lambda x: x < 3 and x or None` seems to be the closest i have found.
A lambda, like any function, must have a return value. `lambda x: x if (x<3)` does not work because it does not specify what to return if not `x<3`. By default functions return `None`, so you could do ``` lambda x: x if (x<3) else None ``` --- But perhaps what you are looking for is a list comprehension with an `if...
how to turn on minor ticks only on y axis matplotlib
12,711,202
19
2012-10-03T14:58:29Z
12,711,768
14
2012-10-03T15:29:04Z
[ "python", "matplotlib" ]
How can I turn the minor ticks only on y axis on a linear vs linear plot? When I use the function to turn minor ticks on, they appear on both x and y axis.
nevermind, I figured it out. ``` ax.tick_params(axis='x',which='minor',bottom='off') ```
how to turn on minor ticks only on y axis matplotlib
12,711,202
19
2012-10-03T14:58:29Z
12,711,964
12
2012-10-03T15:40:08Z
[ "python", "matplotlib" ]
How can I turn the minor ticks only on y axis on a linear vs linear plot? When I use the function to turn minor ticks on, they appear on both x and y axis.
Here's another way I found in the [matplotlib documentation](http://matplotlib.org/examples/pylab_examples/major_minor_demo1.html): ``` import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import MultipleLocator a = np.arange(100) ml = MultipleLocator(5) plt.plot(a) plt.axes().yaxis.set_mino...
QtSingleApplication for PySide or PyQt
12,712,360
4
2012-10-03T16:02:03Z
12,712,362
13
2012-10-03T16:02:03Z
[ "python", "qt", "pyqt", "pyside" ]
Is there a Python version of the C++ class [`QtSingleApplication`](http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html) from [Qt Solutions](http://qt.digia.com/Product/Qt-Add-Ons/Qt-Solutions-Archive/)? [`QtSingleApplication`](http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingl...
Here is my own implementation. It has been tested with Python 2.7 and PySide 1.1. It has essentially the same interface as the [C++ version of `QtSingleApplication`](http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html). The main difference is that you must supply an application unique id t...
ReadProcessMemory with ctypes
12,712,585
7
2012-10-03T16:15:48Z
12,720,188
8
2012-10-04T04:14:41Z
[ "python", "winapi", "ctypes", "readprocessmemory" ]
im working on a little solitär trainer. I don't know why the function ReadProcessMemory doesn't work. Normally it returns a False or True but in that case nothing. The GetlastError() gives me the Errorcode 6. ``` #-*- coding: cp1252 -*- import ctypes, win32ui, win32process ,win32api PROCESS_ALL_ACCESS = 0x1F0FFF HW...
Check the community comment to the MSDN [ReadProcessMemory](http://msdn.microsoft.com/en-us/library/windows/desktop/ms680553%28v=vs.85%29.aspx) page, quote(sic): > ### W7 wont run read process memory > > You may need to check your access permissions for "SE\_DEBUG\_NAME" for the current processes token. If not enabled...
Inverted glyph: bitmap > SVG via autotrace > glyph via fontforge
12,713,444
6
2012-10-03T17:10:41Z
12,768,301
13
2012-10-07T11:12:40Z
[ "python", "fonts", "svg", "invert", "fontforge" ]
I am trying to create a font/glyph by: * taking a bitmap image * creating an SVG with autotrace (on Linux) * importing the outline as a glyph with python-fontforge (glyph.importOutlines(svgfile) ) This works fine **except that the resulting glyph in inverted** (see images). Any idea how this can be prevented, how the...
solved this simply by using [potrace](http://potrace.sourceforge.net/) instead of autotrace. for reference, these are the steps: convert bitmap to svg (linux command line): ``` potrace -s sourceimg.bmp ``` use svg as glyph (python): ``` import fontforge font = fontforge.open('blank.sfd') glyph = font.createMappedC...
Take string argument from Python command line
12,714,461
2
2012-10-03T18:18:53Z
12,714,516
7
2012-10-03T18:22:40Z
[ "python", "arguments" ]
I need to take an optional argument when running my Python script: ``` python3 myprogram.py afile.json ``` or ``` python3 myprogram.py ``` This is what I've been trying: ``` filename = 0 parser = argparse.ArgumentParser(description='Create Configuration') parser.add_argument('filename', type=str, ...
Please read the tutorial carefully. <http://docs.python.org/howto/argparse.html> i believe you need to actually parse the arguments: ``` parser = argparse.ArgumentParser() args = parser.parse_args() ``` then filename will be come available `args.filename`
Python, WSGI, multiprocessing and shared data
12,715,139
14
2012-10-03T19:06:06Z
12,782,760
12
2012-10-08T13:28:03Z
[ "python", "multiprocessing", "mod-wsgi", "wsgi" ]
I am a bit confused about multiproessing feature of mod\_wsgi and about a general design of WSGI applications that would be executed on WSGI servers with multiprocessing ability. Consider the following directive: ``` WSGIDaemonProcess example processes=5 threads=1 ``` If I understand correctly, mod\_wsgi will spawn ...
There are several aspects to consider in your question. First, the interaction between apache MPM's and mod\_wsgi applications. If you run the mod\_wsgi application in embedded mode (no `WSGIDaemonProcess` needed, `WSGIProcessGroup %{GLOBAL}`) you inherit multiprocessing/multithreading from the apache MPM's. This shou...
Python : AttributeError: 'NoneType' object has no attribute 'append'
12,715,198
7
2012-10-03T19:09:57Z
12,715,226
16
2012-10-03T19:11:43Z
[ "python" ]
My program looks like ``` # global item_to_bucket_list_map = {} def fill_item_bucket_map(items, buckets): global item_to_bucket_list_map for i in range(1, items + 1): j = 1 while i * j <= buckets: if j == 1: item_to_bucket_list_map[i] = [j] else: ...
Actually you stored `None` here: `append()` changes the list in place and returns `None` ``` item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j) ``` example: ``` In [42]: lis = [1,2,3] In [43]: print lis.append(4) None In [44]: lis Out[44]: [1, 2, 3, 4] ```
How to save an excel file with DataNitro and python
12,715,267
2
2012-10-03T19:15:07Z
12,755,240
7
2012-10-05T23:18:32Z
[ "python", "excel", "datanitro" ]
I've got an python script to that generates an excel worksheet from a database query with the DataNitro excel plugin (the free one), now i want so save the file and then send it via email, but the DataNitro docs only includes working with cells and worksheets, is there a method call in the DataNitro API or any other wo...
DataNitro founder here - I've just added the functions to save workbooks to the DataNitro API for you. Thanks for point this out! You need to download the latest version of DataNitro from <https://www.datanitro.com> Here's the Python 2 code to save a workbook & send it via email: <https://github.com/datanitro/blog/blo...
Trying to identify the newest and second newest file in a directory
12,715,309
2
2012-10-03T19:17:38Z
12,715,320
7
2012-10-03T19:18:41Z
[ "python" ]
I am trying to identify the newest and second newest files in a directory. This is the code I intended to use: ``` CONFIGS = "/Users/root/dev/config-files/" allConfigs = sorted(os.listdir(CONFIGS), key=os.path.getctime) t1 = "%s/%s" % (CONFIGS, allConfigs[-1]) t2 = "%s/%s" % (CONFIGS, allConfigs[-2]) ``` I am encount...
`os.listdir` returns *relative* names, so you'll have to use `os.path.join` to make them absolute: ``` allConfigs = sorted(os.listdir(CONFIGS), key=lambda p: os.path.getctime(os.path.join(CONFIGS, p)) ```
Python sum() returns negative value because the sum is too large for 32bit integer
12,715,750
3
2012-10-03T19:48:10Z
12,715,801
14
2012-10-03T19:51:56Z
[ "python", "integer", "long-integer" ]
``` x = [1, 2, 3, ... ] y = sum(x) ``` The sum of `x` is 2165496761, which is larger than the limit of 32bit integer So `sum(x)` returns -2129470535. How can I get the correct value by converting it to long integer? Here is my import list: ``` import math, csv, sys, re, time, datetime, pickle, os, gzip from numpy i...
Twenty quatloos says you're using `numpy`'s sum function: ``` >>> sum(xrange(10**7)) 49999995000000L >>> from numpy import sum >>> sum(xrange(10**7)) -2014260032 ``` So I'd bet you did `from numpy import *` or are using some interface which does the equivalent. To verify this, try ``` print type(sum(x)) ``` On the...
In Flask, why does this hello world app work?
12,715,834
6
2012-10-03T19:54:10Z
12,715,896
11
2012-10-03T19:58:23Z
[ "python", "flask" ]
Looking at the default "Hello world" script on Flask's website: ``` from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() ``` I'm very new to programming, so I don't understand how this script can work - the `hello()` function i...
This line: `@app.route("/")` will register the function as the handler for the '/' route. When the browser queries '/' (the root), the application responds "Hello World!". The `@` syntax is called Decorators. [Understanding Python decorators](http://stackoverflow.com/questions/739654/understanding-python-decorators)
Send form data from views to template
12,717,054
3
2012-10-03T21:16:59Z
12,816,533
9
2012-10-10T09:53:33Z
[ "python", "django", "django-forms", "django-templates", "django-views" ]
**Edit:** I want the 'success\_url' (ie, result.html) to display the 'data' from 'form.process()'. The following code obviously doesn't work. Can anyone please tell me what's wrong with it or suggest another way to basically view the context 'data' in a template (either in the form of list or dict), ie a better way t...
As far as I understood your question, you want to show the contents of the user submitted form in the result view. Is that correct? In this case the method get\_context\_data won't help you at all, because it will only store data in the current context which is in MainView. The form\_valid method of FormView will mak...
Split one file into multiple files based on pattern (cut can occur within lines)
12,717,294
2
2012-10-03T21:38:50Z
12,717,497
7
2012-10-03T21:59:32Z
[ "python", "perl", "awk", "split", "gnu" ]
A lot of solutions exist, but the specificity here is I need to be able to split within a line, the cut should occur just before the pattern. Ex: Infile: ``` <?xml 1><blabla1> <blabla><blabla2><blabla> <blabla><blabla> <blabla><blabla3><blabla><blabla> <blabla><blabla><blabla><?xml 4> <blabla> <blabla><blabla><blabla...
This performs the split without reading everything into RAM: ``` def files(): n = 0 while True: n += 1 yield open('/output/dir/%d.part' % n, 'w') pat = '<?xml' fs = files() outfile = next(fs) with open(filename) as infile: for line in infile: if pat not in line: outf...
Calling class staticmethod within the class body?
12,718,187
46
2012-10-03T23:12:08Z
12,718,272
60
2012-10-03T23:24:28Z
[ "python", "decorator", "static-methods" ]
When I attempt to use a static method from within the body of the class, and define the static method using the built-in `staticmethod` function as a decorator, like this: ``` class Klass(object): @staticmethod # use as decorator def _stat_func(): return 42 _ANS = _stat_func() # call the static...
`staticmethod` objects apparently have a `__func__` attribute storing the original raw function (makes sense that they had to). So this will work: ``` class Klass(object): @staticmethod # use as decorator def stat_func(): return 42 _ANS = stat_func.__func__() # call the staticmethod def me...
Count vowels from raw input
12,719,600
2
2012-10-04T02:40:10Z
12,719,624
9
2012-10-04T02:44:06Z
[ "python", "string", "count" ]
I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a problem: ``` def vowels(): vowels = ["a","e","i","o","u"] count = 0 string = raw_input ("Enter a string: ") for i in range(0, len(str...
## `in` operator You probably want to use the `in` operator instead of the `==` operator - the `in` operator lets you check to see if a particular item is in a sequence/set. ``` 1 in [1,2,3] # True 1 in [2,3,4] # False 'a' in ['a','e','i','o','u'] # True 'a' in 'aeiou' # Also True ``` --- Some other comments: ## S...
Simple way to group items into buckets
12,720,151
8
2012-10-04T04:09:44Z
12,720,386
15
2012-10-04T04:44:07Z
[ "python" ]
I often want to bucket an unordered collection in python. [`itertools.groubpy`](http://docs.python.org/library/itertools.html#itertools.groupby) does the right sort of thing but almost always requires massaging to sort the items first and catch the iterators before they're consumed. Is there any quick way to get this ...
This has come up several times before -- [(1)](http://stackoverflow.com/questions/8793772/how-to-split-a-sequence-according-to-a-predicate), [(2)](http://stackoverflow.com/questions/949098/python-split-a-list-based-on-a-condition), [(3)](http://stackoverflow.com/questions/4578590/python-equivalent-of-filter-getting-two...
Unpacking arguments: only named arguments may follow *expression
12,720,450
25
2012-10-04T04:52:37Z
12,720,567
9
2012-10-04T05:07:03Z
[ "python", "arrays", "arguments" ]
The following works beautifully in Python: ``` def f(x,y,z): return [x,y,z] a=[1,2] f(3,*a) ``` The elements of `a` get unpacked as if you had called it like `f(3,1,2)` and it returns `[3,1,2]`. Wonderful! But I can't unpack the elements of `a` into the *first* two arguments: ``` f(*a,3) ``` Instead of calling t...
It doesn't *have to* be that way. It was just rule that Guido found to be sensible. In Python 3, the rules for unpacking have been liberalized somewhat: ``` >>> a, *b, c = range(10) >>> a 0 >>> b [1, 2, 3, 4, 5, 6, 7, 8] >>> c 9 ``` Depending on whether Guido feels it would improve the language, that liberalization ...
Unpacking arguments: only named arguments may follow *expression
12,720,450
25
2012-10-04T04:52:37Z
12,830,036
19
2012-10-10T23:31:45Z
[ "python", "arrays", "arguments" ]
The following works beautifully in Python: ``` def f(x,y,z): return [x,y,z] a=[1,2] f(3,*a) ``` The elements of `a` get unpacked as if you had called it like `f(3,1,2)` and it returns `[3,1,2]`. Wonderful! But I can't unpack the elements of `a` into the *first* two arguments: ``` f(*a,3) ``` Instead of calling t...
As Raymond Hettinger's answer points out, this may change in Python 3 and [here is a related proposal](http://www.python.org/dev/peps/pep-3132/), which has been accepted. Especially related to the current question, here's one of the possible changes to that proposal that was discussed: > Only allow a starred expressio...
Combining feature extraction classes in scikit-learn
12,721,486
13
2012-10-04T06:27:33Z
12,724,375
16
2012-10-04T09:36:26Z
[ "python", "machine-learning", "scikit-learn", "feature-extraction" ]
I'm using `sklearn.pipeline.Pipeline` to chain feature extractors and a classifier. Is there a way to combine multiple feature selection classes (for example the ones from `sklearn.feature_selection.text`) in parallel and join their output? My code right now looks as follows: ``` pipeline = Pipeline([ ('vect', Co...
This has been implemented recently in the master branch of scikit-learn under the name `FeatureUnion`: <http://scikit-learn.org/dev/modules/pipeline.html#feature-union>
Python Bool and int comparison and indexing on list with boolean values
12,721,676
13
2012-10-04T06:42:54Z
12,721,712
20
2012-10-04T06:46:27Z
[ "python", "list", "indexing", "boolean" ]
Indexing on list with boolean values works fine. Though the index should be an integer. Following is what I tried in console: ``` >>> l = [1,2,3,4,5,6] >>> >>> l[False] 1 >>> l[True] 2 >>> l[False + True] 2 >>> l[False + 2*True] 3 >>> >>> l['0'] Traceback (most recent call last): File "<stdin>", line 1, in <module>...
What's going on is that booleans actually *are* integers. True is 1 and False is 0. Bool is a subtype of int. ``` >>> isinstance(True, int) True >>> issubclass(bool, int) True ``` So it's not converting them to integers, it's just using them as integers. (Bools are ints for historical reasons. Before a bool type exi...
Replacing letter in string by index
12,723,751
17
2012-10-04T08:59:40Z
12,723,785
21
2012-10-04T09:01:49Z
[ "python", "string" ]
This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work: ``` for i in range(0,len(line)): if (line[i]==";" and i in rightindexarray): line[i]=":" ``` It gives the error ``` line[i]=":" TypeError: 'str' object does not support item assignment ``` How c...
Strings in python are immutable, so you cannot treat them as a list and assign to indices. Use [`.replace()`](http://docs.python.org/library/stdtypes.html#str.replace) instead: ``` line = line.replace(';', ':') ``` If you need to replace only *certain* semicolons, you'll need to be more specific. You could use slici...
Replacing letter in string by index
12,723,751
17
2012-10-04T08:59:40Z
12,723,941
16
2012-10-04T09:10:13Z
[ "python", "string" ]
This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work: ``` for i in range(0,len(line)): if (line[i]==";" and i in rightindexarray): line[i]=":" ``` It gives the error ``` line[i]=":" TypeError: 'str' object does not support item assignment ``` How c...
Turn the string into a list; then you can change the characters individually. Then you can put it back together with `.join`: ``` s = 'a;b;c;d' slist = list(s) for i, c in enumerate(slist): if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text slist[i] = ':' s = ''.jo...
Replacing letter in string by index
12,723,751
17
2012-10-04T08:59:40Z
32,346,864
24
2015-09-02T07:20:15Z
[ "python", "string" ]
This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work: ``` for i in range(0,len(line)): if (line[i]==";" and i in rightindexarray): line[i]=":" ``` It gives the error ``` line[i]=":" TypeError: 'str' object does not support item assignment ``` How c...
You can do the below, to replace any char with a respective char at a given index, if you wish not to use `.replace()` ``` word = 'python' index = 4 char = 'i' word = word[:index] + char + word[index + 1:] print word o/p: pythin ```
Print to standard printer from Python?
12,723,818
15
2012-10-04T09:03:27Z
12,725,233
13
2012-10-04T10:25:38Z
[ "python", "printing", "cpython" ]
Is there a reasonably standard and cross platform way to print text (or even PS/PDF) to the system defined printer? Assuming [CPython](http://www.python.org/) here, not something clever like using Jython and the [Java printing API](http://docs.oracle.com/javase/tutorial/2d/printing/printable.html).
Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print. You need to [detect the OS](http://stackoverflow.com/questions/1854/python-what-os-am-i-running-on) your program is running on, then: For Linux - ``` import subprocess lpr = su...
Print to standard printer from Python?
12,723,818
15
2012-10-04T09:03:27Z
22,550,163
11
2014-03-21T04:26:40Z
[ "python", "printing", "cpython" ]
Is there a reasonably standard and cross platform way to print text (or even PS/PDF) to the system defined printer? Assuming [CPython](http://www.python.org/) here, not something clever like using Jython and the [Java printing API](http://docs.oracle.com/javase/tutorial/2d/printing/printable.html).
This has only been tested on Windows: You can do the following: ``` import os os.startfile("C:/Users/TestFile.txt", "print") ``` This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the `os` module which comes with the standard library
global name 're' is not defined
12,725,024
8
2012-10-04T10:12:12Z
12,756,257
11
2012-10-06T02:46:49Z
[ "python", "regex", "mincemeat" ]
I am new to python and working on a map reduce problem with mincemeat. I am getting the following error while running the mincemeat script. ``` $python mincemeat.py -p changeme localhost error: uncaptured python exception, closing channel <__main__.Client connected at 0x923fdcc> (<type 'exceptions.NameError'>:global ...
You need to have the import statement in `mapfn` itself. `mapfn` gets executed in a different python process, so it doesn't have access to the original context (including imports) in which it was declared.
Drop non-numeric columns from a pandas DataFrame
12,725,417
15
2012-10-04T10:36:50Z
12,726,468
23
2012-10-04T11:41:00Z
[ "python", "pandas" ]
In my application I load text files that are structured as follows: * First non numeric column (ID) * A number of non-numeric columns (strings) * A number of numeric columns (floats) The number of the non-numeric columns is variable. Currently I load the data into a DataFrame like this: ``` source = pandas.read_tabl...
It`s a private method, but it will do the trick: source.\_get\_numeric\_data() ``` In [2]: import pandas as pd In [3]: source = pd.DataFrame({'A': ['foo', 'bar'], 'B': [1, 2], 'C': [(1,2), (3,4)]}) In [4]: source Out[4]: A B C 0 foo 1 (1, 2) 1 bar 2 (3, 4) In [5]: source._get_numeric_data() Out[5]...
Name of files opened by a process in window?
12,726,218
9
2012-10-04T11:25:28Z
12,726,417
19
2012-10-04T11:37:40Z
[ "python", "c", "windows", "filesystems", "windows-api-code-pack" ]
How to print name of file open by some process (PID) in window? Or All Processes (PID) currently open a file. **Process Explorer** is a utility works for same. **But how does it work not mentioned?** Any */proc filesystem* kind of thing present in windows? ``` Can we read any Window's Registry? I wants to write a ...
Here is the platform independent solution in python. ``` import psutil p = psutil.Process(os.getpid()) # or PID of process p.open_files() ``` So i refer you [psutil](http://code.google.com/p/psutil/) package it has too good functions for getting information on running processes
split strings and save comma int python
12,726,373
6
2012-10-04T11:34:23Z
12,726,416
22
2012-10-04T11:37:32Z
[ "python", "string", "split" ]
I have the following string ``` c='a,b,c,"d,e",f,g' ``` and I want to get ``` b=['a','b','c','d,e','f','g'] ``` so ``` b[3]=='d,e' ``` any ideas? the problem with `c.split(',')` is that it splits also `'d,e'` [I have see an answer here for C++, that of course didn't help me] Many Thanks
You could use the CSV module if `c` should indeed be the below... ``` import csv c = 'a,b,c,"d,e",f,g' print next(csv.reader([c])) # ['a', 'b', 'c', 'd,e', 'f', 'g'] ```
django templates loops
12,726,799
2
2012-10-04T11:59:41Z
12,726,865
8
2012-10-04T12:03:09Z
[ "python", "django" ]
Can I loop through two arrays/lists in django templates simultaneously? Something like this: ``` # views.py a = [{'a':'apple','b':'banana','c':'clementine'}, {'a':'aunt','b':'brother','c':'cousin'}, {'a':'ant','b':'bat','c':'cat'}] b = [{'d':'dave','f':'fred'}, {'d':'dason','f':'ford'}, {'d':'dan...
You can [`zip`](http://docs.python.org/library/functions.html#zip) the two lists in your view, then iterate through the resulting list in your template. ``` # views.py ab = zip(a,b) # template {% for x,y in ab %} {{ x.a }},{{ x.c }}<br> {{ y.f }} {% endfor %} ```
String parsing in Python with various unique cases
12,727,873
2
2012-10-04T13:01:17Z
12,727,952
7
2012-10-04T13:06:25Z
[ "python", "string", "parsing" ]
My goal is to convert a string into a dictionary. Here's how it looks like: ``` [exploit] => 1 [hits] => 1 [completed] => 1 [is_malware] => 1 [summary] => 26.0@13965: suspicious.warning: object contains JavaScript 76.0@14467: suspicious.obfuscation using eval 76.0@14467: suspicious.obfuscation using String.fromCharCod...
You can use `re.findall` to parse the text: ``` >>> import re >>> re.findall('\[([^]]+)\] => (.*?)(?=\n\[|$)', s, re.S) [('exploit', '1'), ('hits', '1'), ('completed', '1'), ('is_malware', '1'), ('summary', '26.0@13965: suspicious.warning: object contains JavaScript\n76.0@14467: suspicious.obfuscation using eval\n76.0...
Error: No module named psycopg2.extensions
12,728,004
38
2012-10-04T13:08:49Z
14,308,925
97
2013-01-13T22:28:38Z
[ "python", "django", "postgresql", "psycopg2" ]
I am trying to set up a PostgreSQL database for my django project, which I believe I have done now thanks to the replies to my last question [Problems setting up a postgreSQL database for a django project](http://stackoverflow.com/questions/12710715/problems-setting-up-a-postgresql-database-for-a-django-project/1271373...
The first thing to do is to install the dependencies. ``` sudo apt-get build-dep python-psycopg2 ``` After that go inside your virtualenv and use ``` pip install psycopg2 ``` These two commands should solve the problem.
Subtract Unless Negative Then Return 0
12,728,099
9
2012-10-04T13:14:17Z
12,728,167
10
2012-10-04T13:17:41Z
[ "python", "math" ]
I'll preface with, this is solely to satisfy my curiosity rather than needing help on a coding project. But I was wanting to know if anyone knows of a function (particularly in python, but I'll accept a valid mathematical concept) kind of like absolute value, that given a number will return 0 if negative or return that...
This should do it: ``` max(x-y, 0) ```
Subtract Unless Negative Then Return 0
12,728,099
9
2012-10-04T13:14:17Z
12,728,174
25
2012-10-04T13:17:50Z
[ "python", "math" ]
I'll preface with, this is solely to satisfy my curiosity rather than needing help on a coding project. But I was wanting to know if anyone knows of a function (particularly in python, but I'll accept a valid mathematical concept) kind of like absolute value, that given a number will return 0 if negative or return that...
One way... ``` >>> max(0, x) ```
Simple, efficient bilinear interpolation of images in numpy and python
12,729,228
2
2012-10-04T14:12:15Z
12,729,229
11
2012-10-04T14:12:15Z
[ "python", "numpy", "interpolation" ]
How do I implement bilinear interpolation for image data represented as a numpy array in python?
I found many questions on this topic and many answers, though none were efficient for the common case that the data consists of samples on a grid (i.e. a rectangular image) and represented as a numpy array. This function can take lists as both x and y coordinates and will perform the lookups and summations without need...
How does telnet differ from a raw tcp connection
12,730,293
7
2012-10-04T15:06:34Z
12,730,703
14
2012-10-04T15:31:37Z
[ "python", "sockets", "network-programming", "telnet" ]
I am trying to send commands to a server via a python script. I can see the socket connection being established on the server. But the commands I am sending across , do not seem to make it through(server does a read on the socket). The server currently supports a telnet command interpreter. ie: you telnet to the comman...
Telnet is a way of passing control information about the communication channel. It defines line-buffering, character echo, etc, and is done through a series of will/wont/do/dont messages when the connection starts (and, on rare occasions, during the session). That's probably not what your server documentation means. I...
Removing duplicates using custom comparisons
12,730,961
12
2012-10-04T15:46:19Z
12,731,057
18
2012-10-04T15:51:35Z
[ "python", "python-3.x" ]
The most convenient, "Pythonic" way to remove duplicates from a list is basically: ``` mylist = list(set(mylist)) ``` But suppose your criteria for counting a duplicate depends on a particular member field of the objects contained in `mylist`. Well, one solution is to just define `__eq__` and `__hash__` for the obje...
You can use a dict instead of a set, where the dict's keys will be the unique values: ``` d = {x.firstname: x for x in mylist} mylist = list(d.values()) ```
How can I debug POST requests with python's BaseHTTPServer / SimpleHTTPServer?
12,731,207
13
2012-10-03T20:10:09Z
12,731,208
22
2012-10-04T04:42:37Z
[ "python", "http", "command-line" ]
I found a script on [this site](http://wiki.python.org/moin/BaseHttpServer) for running a simple server via the command line with python. I added some `print` lines in because I'd like to print out the GET and POST parameters via the command line for requests, but I can't seem to get them to show up anywhere. If I ju...
It's not tremendously obvious, but the handler is using sockets behind the scenes. So you need to read the raw data from the socket, and then interpret it. Use the [`urlparse`](http://docs.python.org/library/urlparse.html) module. * In Python 2, you want `urlparse.parse_qs`. * In Python 3, the library is renamed: you...
Syntax error on the colon in an if statement
12,732,743
8
2012-10-04T17:41:29Z
12,732,902
8
2012-10-04T17:52:01Z
[ "python", "python-3.x" ]
I am new to python, and am making a sort-of game as one of my first projects that guesses a number between 1 and 10, then the user guesses it. They have three guesses, and the program tells the user if they need to go higher or lower on their next guess. The part of the code with the error in isn't crucial, as it only ...
It's not actually the colon. It's the unclosed bracket on the previous line. When you get a weird `SyntaxError`, check for bracket balance before it.
Determine if a list is in descending order
12,734,178
7
2012-10-04T19:09:22Z
12,734,211
9
2012-10-04T19:11:19Z
[ "python" ]
I am trying to write a function that will test whether or not a list is in decending order. This is what I have so far, but it doesn't seem to be working for all lists. I used the list `[9,8,5,1,4,3,2]` and it returned `'true'`. I can't seem to figure out where my mistake is. ``` def ordertest(A): n = len(A) ...
You should rather do the reverse check (As soon as you get `A[i] < A[i+1]`, return false, else keep on iterating.. ): ``` def ordertest(A): for i in xrange(len(A) - 1): if A[i]<A[i+1]: return False return True ```
Determine if a list is in descending order
12,734,178
7
2012-10-04T19:09:22Z
12,734,228
23
2012-10-04T19:12:16Z
[ "python" ]
I am trying to write a function that will test whether or not a list is in decending order. This is what I have so far, but it doesn't seem to be working for all lists. I used the list `[9,8,5,1,4,3,2]` and it returned `'true'`. I can't seem to figure out where my mistake is. ``` def ordertest(A): n = len(A) ...
You can do this easily with [a generator expression](http://www.youtube.com/watch?v=t85uBptTDYY&list=UUAuqj5Bs5mTTl1mIVDmuAlw&index=1&feature=plcp) and [the `all()` builtin](http://docs.python.org/release/3.1.5/library/functions.html#all): ``` all(earlier >= later for earlier, later in zip(seq, seq[1:])) ``` For exam...
Python class static methods
12,735,392
35
2012-10-04T20:30:59Z
12,735,459
8
2012-10-04T20:34:39Z
[ "python", "static" ]
I want to create a kind of utility class which contains only static methods which are callable by the name class prefix. Looks like I'm doing something wrong :) Here is my small class: ``` class FileUtility(): @staticmethod def GetFileSize(self, fullName): fileSize = os.path.getsize(fullName) ...
You really shouldn't be creating static methods in Python. What you should be doing is putting them at the global function level, and then accessing the module they're in when you call them. foo.py: ``` def bar(): return 42 ``` baz.py: ``` import foo print foo.bar() ```
Python class static methods
12,735,392
35
2012-10-04T20:30:59Z
12,735,474
61
2012-10-04T20:35:13Z
[ "python", "static" ]
I want to create a kind of utility class which contains only static methods which are callable by the name class prefix. Looks like I'm doing something wrong :) Here is my small class: ``` class FileUtility(): @staticmethod def GetFileSize(self, fullName): fileSize = os.path.getsize(fullName) ...
You're getting the error because you're taking a `self` argument in each of those functions. They're static, you don't need it. However, the 'pythonic' way of doing this is not to have a class full of static methods, but to just make them free functions in a module. ``` #fileutility.py: def get_file_size(fullName): ...
regex matching between two strings in Python
12,736,074
10
2012-10-04T21:16:18Z
12,736,203
22
2012-10-04T21:24:10Z
[ "python", "regex", "python-3.x", "regex-negation" ]
I can't seem to find a way to extract all comments like in following example. ``` >>> import re >>> string = ''' ... <!-- one ... --> ... <!-- two -- -- --> ... <!-- three --> ... ''' >>> m = re.findall ( '<!--([^\(-->)]+)-->', string, re.MULTILINE) >>> m [' one \n', ' three '] ``` block with `two -- --` is not matc...
this should do the trick ``` m = re.findall ( '<!--(.*?)-->', string, re.DOTALL) ```
Python : How to add month to December 2012 and get January 2013?
12,736,229
4
2012-10-04T21:25:39Z
12,736,330
7
2012-10-04T21:32:02Z
[ "python", "date", "calendar" ]
``` >>> start_date = date(1983, 11, 23) >>> start_date.replace(month=start_date.month+1) datetime.date(1983, 12, 23) ``` This works until the month is `<=11`, as soon as I do ``` >>> start_date = date(1983, 12, 23) >>> start_date.replace(month=start_date.month+1) Traceback (most recent call last): File "<stdin>", l...
The [dateutil](http://labix.org/python-dateutil) library is useful for calculations like that: ``` >>> start_date + relativedelta(months=2) datetime.date(1984, 1, 23) ```
Why don't my Scrapy CrawlSpider rules work?
12,736,257
8
2012-10-04T21:27:33Z
12,736,369
17
2012-10-04T21:35:03Z
[ "python", "scrapy" ]
I've managed to code a very simple crawler with Scrapy, with these given constraints: * Store all link info (e.g.: anchor text, page title), hence the 2 callbacks * Use CrawlSpider to take advantage of rules, hence no BaseSpider It runs well, except it doesn't implement rules if I add a callback to the first request!...
Here's a scraper that works perfectly: ``` from scrapy.contrib.spiders import CrawlSpider,Rule from scrapy.selector import HtmlXPathSelector from scrapy.http import Request from scrapySpider.items import SPage from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor class TestSpider4(CrawlSpider): name = ...
Google App Engine - Getting Sessions working with Python 2.7
12,737,008
6
2012-10-04T22:32:14Z
12,737,074
15
2012-10-04T22:40:45Z
[ "python", "google-app-engine", "python-2.7", "session-variables" ]
First of all, I'm brand new to GAE, so its possible I'm doing this the wrong way - but I've used PHP before and session was how I kept persistent data. I'm using Python 2.7 because that is what I use for all my other Python development - although I'm beginning to wonder if downgrading to 2.5 might be a valid solution, ...
Have you seen webapp2 sessions? It's all built in and you can get started right away. <http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html> > This module provides a lightweight but flexible session support for webapp2. > It has three built-in backends: secure cookies, memcache and datastore. New backe...
Launch android app from SL4A script?
12,737,150
4
2012-10-04T22:50:56Z
12,807,197
8
2012-10-09T19:37:03Z
[ "android", "python", "sl4a" ]
I have the following in /sdcard/sl4a/scripts/twitter.py ``` import android droid = android.Android() droid.launch('com.twitter.android') ``` And if I run it in the console or the background, it immediately exits with code 1, and the log file is empty. If there are other ways to launch applications from some sort of ...
you can use **`startActivity`** for that: ``` import android droid = android.Android() droid.startActivity('android.intent.action.MAIN', None, None, None, False, 'com.twitter.android', 'com.twitter.android.StartActivity' ) ``` see the s...
set and zip questions with Python
12,737,286
5
2012-10-04T23:06:30Z
12,737,319
8
2012-10-04T23:10:31Z
[ "python", "python-3.x" ]
Not sure why this one works when using set and zip: ``` >>> a = ([1]) >>> b = ([2]) >>> set(zip(a,b)) {(1, 2)} ``` but this one doesn't ?. ``` >>> a = ([1],[2]) >>> b = ([3],[4]) >>> set(zip(a,b)) Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> set(zip(a,b)) TypeError: unhashable ty...
It makes more sense if we look at the `zip` output: ``` >>> a = ([1]) # equivalent to [1], not a tuple >>> b = ([2]) # equivalent to [2], not a tuple >>> list(zip(a,b)) [(1, 2)] >>> a = ([1],[2]) >>> b = ([3],[4]) >>> list(zip(a,b)) [([1], [3]), ([2], [4])] ``` In the first case, the list contains a tuple of ints; i...
Python Requests and persistent sessions
12,737,740
32
2012-10-05T00:06:36Z
12,737,874
70
2012-10-05T00:24:06Z
[ "python", "python-requests" ]
I am using the [requests](http://docs.python-requests.org/en/latest/) module (version 0.10.0 with Python 2.5). I have figured out how to submit data to a login form on a website and retrieve the session key, but I can't see an obvious way to use this session key in subsequent requests. Can someone fill in the ellipsis ...
You can easily create a persistent session using: ``` s = requests.session() ``` After that, continue with your requests as you would: ``` s.post('https://localhost/login.py', login_data) #logged in! cookies saved for future requests. r2 = s.get('https://localhost/profile_data.json', ...) #cookies sent automatically...
SQLalchemy specify which index to use
12,738,499
5
2012-10-05T01:58:25Z
12,738,680
8
2012-10-05T02:26:11Z
[ "python", "sql", "indexing", "sqlalchemy" ]
Is there a way in SQLalchemy to tell the query which index to use? The reason I need this is that the SQL queries it generates use the "wrong" index - there exists an index for exactly the two fields that I have and it doesn't use it. Thanks!
I think you can use [with\_hint()](http://docs.sqlalchemy.org/en/rel_0_7/orm/query.html#sqlalchemy.orm.query.Query.with_hint) for this. e.g. ``` session.query(Model).with_hint(Model, 'USE INDEX col1_index') ``` Honestly, I didn't really know about this; I discovered it by finding 'USE INDEX' in their [ORM tests](htt...
How can I call scikit-learn classifiers from Java?
12,738,827
9
2012-10-05T02:50:26Z
12,743,013
16
2012-10-05T09:05:29Z
[ "java", "python", "jython", "scikit-learn" ]
I have a classifier that I trained using Python's scikit-learn. How can I use the classifier from a Java program? Can I use Jython? Is there some way to save the classifier in Python and load it in Java? Is there some other way to use it?
You cannot use jython as scikit-learn heavily relies on numpy and scipy that have many compiled C and Fortran extensions hence cannot work in jython. The easiest ways to use scikit-learn in a java environment would be to: * expose the classifier as a HTTP / Json service, for instance using a microframework such as [f...
When or why to use relative imports in Python
12,738,889
13
2012-10-05T02:59:32Z
12,738,912
13
2012-10-05T03:03:28Z
[ "python", "import", "module", "package" ]
Is there any rules or guidelines concerning when to use relative imports in Python? I see them in use all the time like in the Flask web framework. When searching for this topic, I only see articles on how to use relative imports, but not *why*. So is there some special benefit to using: ``` from . import x ``` rath...
Check out [PEP 328's section on relative imports](http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports) The rationale seems to be as written: > Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-package...
How to split a string within a list to create key-value pairs in Python
12,739,911
10
2012-10-05T05:15:28Z
12,739,929
22
2012-10-05T05:18:29Z
[ "python", "string" ]
I have a list that looks like this: ``` [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'] ``` And I want to split this list by '=' so that everything on the left side will become keys and on the right, values. ``` { 'abc':'lalalla', 'appa':'kdkdkdkd', 'kkakaka':'oeoeo' } ```
``` a = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'] d = dict(s.split('=') for s in a) print d Output: {'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'} ``` <http://codepad.org/bZ8lGuHE>
Pandas DataFrame: apply function to all columns
12,741,092
21
2012-10-05T06:55:44Z
12,741,168
29
2012-10-05T07:01:18Z
[ "python", "dataframe", "pandas" ]
I can use `.map(func)` on any column in a df, like: ``` df=DataFrame({'a':[1,2,3,4,5,6],'b':[2,3,4,5,6,7]}) df['a']=df['a'].map(lambda x: x > 1) ``` I could also: ``` df['a'],df['b']=df['a'].map(lambda x: x > 1),df['b'].map(lambda x: x > 1) ``` Is there a more pythonic way to apply a function to all columns or the...
If I understand you right, you're looking for the `applymap` method. ``` >>> print df A B C 0 -1 0 0 1 -4 3 -1 2 -1 0 2 3 0 3 2 4 1 -1 0 >>> print df.applymap(lambda x: x>1) A B C 0 False False False 1 False True False 2 False False True 3 False True True 4 False False...
Creating empty spreadsheets in Google Drive using Drive API (in Python)
12,741,303
12
2012-10-05T07:09:05Z
14,163,492
24
2013-01-04T19:21:02Z
[ "python", "google-drive-sdk", "google-spreadsheet-api", "google-api-python-client", "google-sheets-api" ]
I want to create an empty Google Sheet (created only with metadata) in Google Drive. When I referred to the Google [SpreadSheet API](https://developers.google.com/google-apps/spreadsheets/#creating_a_spreadsheet) documentation, it says to use the DocumentsList API, but it's deprecated and instead asks me to use the Goo...
You can do this using the [Drive API](https://developers.google.com/drive/v2/reference/files/insert) by setting the [MIME type](http://en.wikipedia.org/wiki/MIME) to `application/vnd.google-apps.spreadsheet`: To do this in Python: ``` from apiclient.discovery import build service = build('drive', 'v2') import httpli...
How to load image files to gtk.gdk.Pixbuf from stream?
12,741,880
3
2012-10-05T07:51:17Z
12,741,973
7
2012-10-05T07:57:00Z
[ "python", "pygtk" ]
I have a file picture.jpg, i'm reading it to memory ``` f = open('picture.jpg', 'rb') pic = f.read() f.close() ``` How can I convert pic to gtk.gdk.Pixbuf? I know that there is gdk\_pixbuf\_new\_from\_stream() but it appears to be missing from pyGTK :/
You can use a `Pixbuf` loader: ``` loader = gtk.gdk.PixbufLoader('jpeg') loader.write(pic) loader.close() pixbuf = loader.get_pixbuf() ```
Printing a list of numbers in python v.3
12,742,806
4
2012-10-05T08:54:10Z
12,742,851
7
2012-10-05T08:56:24Z
[ "python", "python-3.x" ]
I am using Python version 3.2.3. I am trying to print a list of numbers in a row, the print command seems to always printing the numbers one at row. Example ``` numbers = [1, 2, 3, 4, 5]; for num in numbers: print("\t ", num) ``` output is: ``` 1 2 ... ``` the required output is 1 2 3 4 5 I would appreciate ...
Use the `end` argument to suppress (or replace) the automatic EOL output: ``` print("\t ", num, end='') ``` Or, you should probably just use: ``` print('\t'.join(map(str, [1, 2, 3, 4, 5]))) ```
What is the equivalent of "zip()" in Python's numpy?
12,744,778
33
2012-10-05T10:57:21Z
12,744,865
49
2012-10-05T11:02:58Z
[ "python", "arrays", "numpy" ]
I am trying to do the following but with numpy arrays: ``` x = [(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)] normal_result = zip(*x) ``` This should give a result of: ``` normal_result = [(0.1, 0.1, 0.1, 0.1, 0.1), (1., 2., 3., 4., 5.)] ``` But if the input vector is a numpy array: ``` y = np.array(x) nu...
You can just transpose it... ``` >>> a = np.array([(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)]) >>> a array([[ 0.1, 1. ], [ 0.1, 2. ], [ 0.1, 3. ], [ 0.1, 4. ], [ 0.1, 5. ]]) >>> a.T array([[ 0.1, 0.1, 0.1, 0.1, 0.1], [ 1. , 2. , 3. , 4. , 5. ]]) ```
What is the equivalent of "zip()" in Python's numpy?
12,744,778
33
2012-10-05T10:57:21Z
12,744,905
19
2012-10-05T11:05:08Z
[ "python", "arrays", "numpy" ]
I am trying to do the following but with numpy arrays: ``` x = [(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)] normal_result = zip(*x) ``` This should give a result of: ``` normal_result = [(0.1, 0.1, 0.1, 0.1, 0.1), (1., 2., 3., 4., 5.)] ``` But if the input vector is a numpy array: ``` y = np.array(x) nu...
Try using [dstack](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html): ``` >>> from numpy import * >>> a = array([[1,2],[3,4]]) # shapes of a and b can only differ in the 3rd dimension (if present) >>> b = array([[5,6],[7,8]]) >>> dstack((a,b)) # stack arrays along a third axis (depth wise) array([...
Only able to read one byte via serial
12,747,528
4
2012-10-05T13:40:14Z
12,747,620
7
2012-10-05T13:45:12Z
[ "python", "c", "windows", "linux", "serial-port" ]
I've got a C/Python setup on my machine, I'm doing some testing with serial communications and for some reason I'm never reading more than 1 byte back. My set up: I have a windows 7 machine, running OpenSUSE in a virtual box. I have 2 USB-RS232 converters and an adaptor between them (so it's a loop from one usb port t...
From the [read(2) manual](http://linux.die.net/man/2/read); > On success, the number of bytes read is returned (zero indicates end > of file), and the file position is advanced by this number. **It is not > an error if this number is smaller than the number of bytes requested; > this may happen for example because few...
SQLAlchemy: Check if object is already present in table
12,748,926
6
2012-10-05T15:00:03Z
12,750,328
10
2012-10-05T16:24:49Z
[ "python", "python-3.x", "sqlalchemy" ]
I have a class `Item` whose `id` is a primary key and auto-generated. Now I read data from some other external source, create an `Item` object, and need to check if this object is already present in my `items` table. How do I do it?
You could query for items that have the same attributes and check if the count is greater than zero. ``` if session.query(Item.id).filter(Item.email==newItem.email, Item.type==newItem.type).count() > 0: // item exists ```
How to prove that parameter evaluation is "left to right" in python
12,749,246
8
2012-10-05T15:18:11Z
12,749,400
12
2012-10-05T15:27:00Z
[ "python", "function", "python-3.x", "parameter-passing", "evaluation" ]
Ok i know its kinda weird question but... For example in javascript we could write a program like this: ``` var a = 1; testFunction(++a, ++a, a); function testFunction(x, y, z){ document.writeln("<br />x = " + x); document.writeln("<br />y = " + y); document.writeln("<br />z = " + z); } ``` and we w...
``` >>> def f(x, y): pass ... >>> f(print(1), print(2)) 1 2 ```
Using a comparator function to sort
12,749,398
9
2012-10-05T15:26:51Z
12,749,495
15
2012-10-05T15:31:42Z
[ "python" ]
So I'm working with a few pre-existing comparators that compare certain values in two tuples and return true if the first is greater than the second, false if otherwise. Here's the code for one of them: ``` def cmpValue(subInfo1, subInfo2): """ Returns True if value in (value, work) tuple subInfo1 is GREATER t...
You're passing the comparator as the `key` function. You should be passing it as the `cmp`, wrapped in some kind of function that turns it into a proper comparator. ``` def make_comparator(less_than): def compare(x, y): if less_than(x, y): return -1 elif less_than(y, x): ret...