title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python: Find in list
9,542,738
210
2012-03-03T02:03:34Z
10,302,859
81
2012-04-24T17:22:44Z
[ "python", "find" ]
I have come across this delightful: ``` item = someSortOfSelection() if item in myList: doMySpecialFunction(item) ``` but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string). is it the most 'pythonic' way of finding an item in a list: `if x in l:`?
If you want to find one element or `None` use default in `next`, it won't raise `StopIteration` if the item was not found in the list: ``` first_or_default = next((x for x in lst if ...), None) ```
scrapy allow all domains
9,543,292
5
2012-03-03T03:55:22Z
9,543,452
11
2012-03-03T04:29:11Z
[ "python", "scrapy" ]
I saw [this](http://stackoverflow.com/questions/6320167/python-scrapy-allowed-domains-adding-new-domains-from-database) post to make scrapy crawl any site without allowed domains restriction. Is there any better way of doing it, such as using a regular expression in allowed domains variable, like- ``` allowed_domains...
Don't set allowed\_domains at all. Look at the get\_host\_regex() function in this scrapy file: <https://github.com/scrapy/scrapy/blob/master/scrapy/contrib/spidermiddleware/offsite.py>
Python arguments and keyword-arguments best practices
9,543,469
7
2012-03-03T04:32:54Z
9,543,817
12
2012-03-03T05:41:24Z
[ "python", "django" ]
I'm writing a Django App, where I am expecting to use many management.py commands. I like the idea of python functions having parameters with default values, where you define the param as: ``` def function(param1=value1) ``` So I'm writing my management commands such that you input as follows: ``` python manage.py c...
**Updated:** Per @rix, later versions of Django now use [argparse](http://docs.python.org/library/argparse.html), which should be preferred. **Original Answer:** I believe the standard approach here is to use [optparse](http://docs.python.org/library/optparse.html), which can hook into the existing option parsing Dja...
Sort list of tuples considering locale (swedish ordering)
9,546,822
7
2012-03-03T14:23:27Z
9,551,325
8
2012-03-04T00:53:13Z
[ "python", "django", "postgresql", "locale" ]
Apparently PostgreSQL 8.4 and Ubuntu 10.04 cannot handle the updated way to sort W and V for Swedish alphabet. That is, it's still ordering them as the same letter like this (old definition for Swedish ordering): * Wa * Vb * Wc * Vd it should be (new definition for Swedish ordering): * Vb * Vd * Wa * Wc I need to o...
When running `LC_ALL=sv_SE.UTF-8 sort` on your example on Ubuntu-10.04, it comes out with Wa before Vb (the "old way"), so Ubuntu does not seem to agree with the "new way". Since PostgreSQL relies on the operating system for this, it will behave just the same as the OS given the same lc\_collate. There is actually a p...
GeoDjango distance filter with distance value stored within model - query
9,547,069
11
2012-03-03T14:58:06Z
9,649,987
8
2012-03-10T20:37:58Z
[ "python", "django", "geodjango" ]
I have an `Order` model, that has an `origin` PointField and a `range` IntegerField. Furthermore, there is an `UserProfile` model, which has a `geo_location` PointField. Now, I have an `User` instance, `user`. I want to select all `Orders`, whose distance between `Order.origin` and `user.userprofile.geo_location` is le...
I think you're going to have to drop some SQL in to do what you want, as the GeoDjango helpers don't have a way of you making a suitable `Distance` object that is simultaneously a Django `F` object (ie field lookup). You don't say which database you're using, but here's how you do it with PostGIS: ``` Order.objects.al...
Python datastructures into js datastructures using Django templates (lists and dicts)
9,547,185
4
2012-03-03T15:14:24Z
9,547,301
7
2012-03-03T15:32:55Z
[ "javascript", "python", "django", "django-templates" ]
I have a Django view that returns a list of dicts like so ``` data = [{'year': 2006, 'books': 54}, {'year': 2007, 'books': 43}, {'year': 2008, 'books': 41}, {'year': 2009, 'books': 44}, {'year': 2010, 'books': 35}] c = { 'data': data, } return render(request, 'template.html', c...
This is part of django's design to stop user generated data from getting into output unescaped. (XSS prevention and such) To get around this, you will want to use a combination of `json.dumps()` (simplejson is deprecated in py>=2.6) to make sure that the output is JS Safe, and`var data = "{{ data|safe }}"` to explicit...
Adding data to related table with SQLAlchemy
9,547,298
4
2012-03-03T15:32:44Z
9,547,667
8
2012-03-03T16:25:44Z
[ "python", "sqlalchemy" ]
I have this to SQLAlchemy(using the Flask SqlAlchemy) objects defined: ``` class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True) password = db.Column(db.String(30)) email = db.Column(db.String(45), unique=True) friends = db.relationship(...
Figured this one out my self.. What I needed to do was: ``` MyUser.friends.append(Friend(MyUser.id, MyFriend.id)) ``` and then commit the update. **Update:** Ok I found the proper way of doing what I wanted. First I don't need the Friend table/class at all. Full code: ``` association_table = db.Table('association...
How to determine the type of class instance
9,548,936
6
2012-03-03T18:58:30Z
9,549,021
7
2012-03-03T19:09:28Z
[ "python", "python-3.x" ]
To determine the class, I can do so: ``` class A: pass a = A type(A) is type #True ``` or: ``` import inspect inspect.isclass(A) ``` But how to determine the type of class instance, not knowing the class name? Something like this: ``` isinstance(a, a.__class__.__name__) #TypeError: isinstance() arg 2 must be...
`type(a)` is the type of the instance, i.e., its class. `a.__class__` is also a reference to the instance's class, but you should use `type(a)`. `types.InstanceType` is only for old-style classes in versions of Python pre-3.0, where all instances had the same type. You should be using new-style classes (derived from `...
How to determine the type of class instance
9,548,936
6
2012-03-03T18:58:30Z
9,557,597
7
2012-03-04T18:22:14Z
[ "python", "python-3.x" ]
To determine the class, I can do so: ``` class A: pass a = A type(A) is type #True ``` or: ``` import inspect inspect.isclass(A) ``` But how to determine the type of class instance, not knowing the class name? Something like this: ``` isinstance(a, a.__class__.__name__) #TypeError: isinstance() arg 2 must be...
Your question is a bit unclear. You want to determine the "type of class instance". This can mean two things. Either you want to determine is an instance is an instance of a specific class. You can do that like so: ``` >>> isinstance(a, A) True ``` You can also get the class with the `type()` call, but that is genera...
Using Python's Format Specification Mini-Language to align floats
9,549,084
15
2012-03-03T19:20:33Z
9,549,204
9
2012-03-03T19:37:10Z
[ "python", "string" ]
I read that I can use Python's [Format Specification Mini-Language](http://docs.python.org/library/string.html#formatspec) to have more control over how strings are displayed. However, I am having a hard time figuring out how to use it to display floats aligned on the decimal point. For example, say I have thre follow...
This is what you want: ``` for i in range(len(job_IDs)): print "Job {item:15} {value[0]:>6}.{value[1]:<6} {units:3}".format(item=job_IDs[i]+':', value=memory_used[i].split('.') if '.' in memory_used[i] else (memory_used[i], '0'), units=memory_units[i]) ``` Here is how it works: This is the main part: `value=memo...
Using Python's Format Specification Mini-Language to align floats
9,549,084
15
2012-03-03T19:20:33Z
9,549,302
9
2012-03-03T19:50:36Z
[ "python", "string" ]
I read that I can use Python's [Format Specification Mini-Language](http://docs.python.org/library/string.html#formatspec) to have more control over how strings are displayed. However, I am having a hard time figuring out how to use it to display floats aligned on the decimal point. For example, say I have thre follow...
Here's another implementation based on `.split('.')` idea. It might be more readable. Split on `'.'`, right-align the left part, left-align the right part: ``` width = max(map(len, job_IDs)) # width of "job id" field for jid, mem, unit in zip(job_IDs, memory_used, memory_units): print("Job {jid:{width}}: {part[0]:>...
django - how to unit test a post request using request.FILES
9,549,397
9
2012-03-03T20:01:49Z
9,549,589
13
2012-03-03T20:28:31Z
[ "python", "django", "unit-testing" ]
I have the following logic in my view: ``` def view_function(request): if request.method == 'POST': uploadform = UploadFileForm(request.POST, request.FILES) if uploadform.is_valid(): #do stuff ``` Where UploadFileForm equals to: ``` class UploadFileForm(forms.Form): file = forms.F...
In the docs, the file field is called `attachment`, but in yours, it's called `file`. You don't need `name` in your post data either -- that refers to another field called `name`, not the name of the file that you are uploading. Try the following: ``` def test_stuff(self): myfile = open('....\file.csv','r') ...
django - how to unit test a post request using request.FILES
9,549,397
9
2012-03-03T20:01:49Z
15,660,249
17
2013-03-27T13:38:01Z
[ "python", "django", "unit-testing" ]
I have the following logic in my view: ``` def view_function(request): if request.method == 'POST': uploadform = UploadFileForm(request.POST, request.FILES) if uploadform.is_valid(): #do stuff ``` Where UploadFileForm equals to: ``` class UploadFileForm(forms.Form): file = forms.F...
The way django's testsuite does it is: ``` from django.core.files.uploadedfile import SimpleUploadedFile f = SimpleUploadedFile("file.txt", b"file_content") ``` This way you don't need to create a temp file and write to it, and you don't need to mock a file (not as easy as it sounds).
How to save generated PDF with Reportlab to Datastore in App Engine Python
9,550,716
7
2012-03-03T23:16:34Z
9,554,660
8
2012-03-04T11:57:45Z
[ "python", "google-app-engine", "pdf", "gae-datastore", "reportlab" ]
I have a method that generates a PDF file using Reportlab library: ``` def obtenerPDFNuevoPedido(self, handler,rsUsuarioPedido, rsPedido): handler.response.headers['Content-Type'] = 'application/pdf' handler.response.headers['Content-Disposition'] = 'attachment; filename=output.pdf' story = [] story.ap...
1) You can specify only desired file name (not destination) 2) Try this (not tested) ``` #define your database structure from google.appengine.ext import db class PdfStorage(db.Model): timeAdded = db.DateTimeProperty(auto_now_add=True) pdfContent = db.BlobProperty() ``` --- Replace your ``` doc = SimpleDoc...
Tkinter changing the select background color on an unfocused Text widget
9,552,121
6
2012-03-04T03:42:53Z
9,558,768
9
2012-03-04T21:00:01Z
[ "python", "colors", "tkinter", "tk", "ttk" ]
I am trying to change the default background color for selected text in a Tkinter Text widget on Mac OS X *when the widget does not have focus*. The default unfocused select color is gray. After many hours of searching, I was unable to find an out-of-the-box solution to do this. Here is what I have tried: * Changing t...
Digging through the Tk source code lead me to the answer! The `inactiveselectbackground` option sets the color. ``` import Tkinter as tk root = tk.Tk() # Create a Text widget with a red selected text background # And green selected text background when not focused text = tk.Text(root, selectbackground="red", inactiv...
What is the best way to get Python auto-completions/intellisense in Vim dynamically?
9,552,171
9
2012-03-04T03:57:45Z
9,683,931
12
2012-03-13T12:32:05Z
[ "python", "vim", "autocomplete" ]
I have looked at `pydiction`, `pysmell` and `vim-ipython`. Both `pydiction` and `pysmell` require generating the index before we can use it, and `vim-ipython` requires loading back and forth before the autocompletion works. However, none of them give the on-the-fly auto-completion working in different `virtualenv`, lik...
Try this: <https://github.com/klen/python-mode> Dynamic omnicompletion from Rope and many other features.
Python - find the index of an item in a list of lists
9,553,638
2
2012-03-04T09:01:28Z
9,553,668
7
2012-03-04T09:06:25Z
[ "python", "list", "indexing" ]
I have a list of lists: ``` colours=[["#660000","#863030","#ba4a4a","#de7e7e","#ffaaaa"],["#a34b00","#d46200","#ff7a04","#ff9b42","#fec28d"],["#dfd248","#fff224","#eefd5d","#f5ff92","#f9ffbf"],["#006600","#308630","#4aba4a","#7ede7e","#aaffaa"]] ``` whats the cleanest way of search the list, and returning the positio...
I'd do something like this: ``` [(i, colour.index(c)) for i, colour in enumerate(colours) if c in colour] ``` This will return a list of tuples where the first index is the position in the first list and second index the position in the second list (note: `c` is the colour you're looking for, that is, `"#660000"`)....
Python - find the index of an item in a list of lists
9,553,638
2
2012-03-04T09:01:28Z
9,553,691
7
2012-03-04T09:10:06Z
[ "python", "list", "indexing" ]
I have a list of lists: ``` colours=[["#660000","#863030","#ba4a4a","#de7e7e","#ffaaaa"],["#a34b00","#d46200","#ff7a04","#ff9b42","#fec28d"],["#dfd248","#fff224","#eefd5d","#f5ff92","#f9ffbf"],["#006600","#308630","#4aba4a","#7ede7e","#aaffaa"]] ``` whats the cleanest way of search the list, and returning the positio...
Using [`enumerate()`](http://docs.python.org/py3k/library/functions.html#enumerate) you could write a function like this one: ``` def find(target): for i,lst in enumerate(colours): for j,color in enumerate(lst): if color == "#660000": return (i, j) return (None, None) ```
setting an environment variable in virtualenv
9,554,087
95
2012-03-04T10:22:27Z
9,554,331
22
2012-03-04T10:58:45Z
[ "python", "heroku", "environment-variables", "virtualenv" ]
I have a Heroku project that uses environment variables to get its configuration, but I use virtualenv to test my app locally first. Is there a way to set the environment variables defined on the remote machine inside virtualenv?
You could try: ``` export ENVVAR=value ``` in virtualenv\_root/bin/activate. Basically the activate script is what is executed when you start using the virtualenv so you can put all your customization in there.
setting an environment variable in virtualenv
9,554,087
95
2012-03-04T10:22:27Z
9,572,842
13
2012-03-05T19:40:48Z
[ "python", "heroku", "environment-variables", "virtualenv" ]
I have a Heroku project that uses environment variables to get its configuration, but I use virtualenv to test my app locally first. Is there a way to set the environment variables defined on the remote machine inside virtualenv?
Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within you...
setting an environment variable in virtualenv
9,554,087
95
2012-03-04T10:22:27Z
9,578,590
76
2012-03-06T05:53:45Z
[ "python", "heroku", "environment-variables", "virtualenv" ]
I have a Heroku project that uses environment variables to get its configuration, but I use virtualenv to test my app locally first. Is there a way to set the environment variables defined on the remote machine inside virtualenv?
I wrote autoenv to do exactly this: <https://github.com/kennethreitz/autoenv>
setting an environment variable in virtualenv
9,554,087
95
2012-03-04T10:22:27Z
11,134,336
202
2012-06-21T08:30:34Z
[ "python", "heroku", "environment-variables", "virtualenv" ]
I have a Heroku project that uses environment variables to get its configuration, but I use virtualenv to test my app locally first. Is there a way to set the environment variables defined on the remote machine inside virtualenv?
In case you're using [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/) (I highly recommend doing so), you can define different hooks (preactivate, postactivate, predeactivate, postdeactivate) using the scripts with the same names in `$VIRTUAL_ENV/bin/`. You need the postactivate hook. ``` $ ...
setting an environment variable in virtualenv
9,554,087
95
2012-03-04T10:22:27Z
20,918,496
12
2014-01-04T07:58:25Z
[ "python", "heroku", "environment-variables", "virtualenv" ]
I have a Heroku project that uses environment variables to get its configuration, but I use virtualenv to test my app locally first. Is there a way to set the environment variables defined on the remote machine inside virtualenv?
Using only virtualenv (without [virtualenvwrapper](http://virtualenvwrapper.readthedocs.org/en/latest/)), setting environment variables is easy through the `activate` script you sourcing in order to activate the virtualenv. Run: ``` nano YOUR_ENV/bin/activate ``` Add the environment variables to the end of the file ...
Python, running command line tools in parallel
9,554,544
7
2012-03-04T11:35:47Z
9,555,046
7
2012-03-04T13:00:14Z
[ "python", "shell", "command-line", "parallel-processing" ]
I am using Python as a script language to do some data processing and call command-line tools for number crunching. I wish to run command-line tools in parallel since they are independent with each other. When one command-line tool is finished, I can collect its results from the output file. So I also need some synchro...
Use the `Pool` object from the `multiprocessing` module. You can then use e.g. `Pool.map()` to do parallel processing. An example would be my markphotos script (see below), where a function is called multiple times in parallel to each process a picture. ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # Adds my copy...
Getting HEAD content with Python Requests
9,554,947
6
2012-03-04T12:44:01Z
9,554,973
11
2012-03-04T12:48:05Z
[ "python", "head", "http-request", "python-requests" ]
I'm trying to parse the result of a HEAD request done using the Python [Requests](http://docs.python-requests.org/en/v0.10.6/index.html) library, but can't seem to access the response content. According to the [docs](http://docs.python-requests.org/en/latest/api/), I should be able to access the content from requests....
By [definition](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4), the responses to HEAD requests do not contain a message-body. Send a GET request if you want to, well, get a response body. Send a HEAD request [iff](http://en.wikipedia.org/wiki/Iff) you are only interested in the response status code and ...
e.printStackTrace equivalent in python
9,555,133
115
2012-03-04T13:13:22Z
9,555,145
164
2012-03-04T13:15:19Z
[ "python", "exception", "stack-trace" ]
I know that print e {where e is Exception} prints the occurred exception but, I was trying to find the python equivalent of `e.printStackTrace()` that exactly traces the exception what line it occurred and prints the entire trace of it. Could anyone please tell me the equivalent of `e.printStackTrace()` in python?
``` import traceback traceback.print_exc() ``` When doing this inside an `except ...:` block it will automatically use the current exception. See <http://docs.python.org/library/traceback.html> for more information.
e.printStackTrace equivalent in python
9,555,133
115
2012-03-04T13:13:22Z
16,417,709
61
2013-05-07T11:19:39Z
[ "python", "exception", "stack-trace" ]
I know that print e {where e is Exception} prints the occurred exception but, I was trying to find the python equivalent of `e.printStackTrace()` that exactly traces the exception what line it occurred and prints the entire trace of it. Could anyone please tell me the equivalent of `e.printStackTrace()` in python?
There is also `logging.exception`. ``` import logging ... try: g() except Exception as ex: logging.exception("Something awful happened!") # will print this message followed by traceback ``` Output: ``` ERROR 2007-09-18 23:30:19,913 error 1294 Something awful happened! Traceback (most recent call last):...
Floating point numbers of Python "float" and PostgreSQL "double precision"
9,556,586
6
2012-03-04T16:24:41Z
9,556,869
8
2012-03-04T16:56:01Z
[ "python", "django", "postgresql", "floating-point" ]
Are Python's "float" type and PostgreSQL's "double precision" type based on the same C implementation? That may not be the real underlying problem here, but anyway, here's what I get when I try to manipulate small numbers in both environments: On Python (2.7.2 GCC 4.2.1, if that's relevant): ``` >>> float('1e-310') 1...
The value float('1e-310') is a [denormal number](http://en.wikipedia.org/wiki/Denormal_number) which is outside the usual range of exponents for 53-bit floats (+308 to -308) so it is stored with less precision in order to achieve gradual underflow. It seems the PostgreSQL has some unresolved issues with denormals: <ht...
How do I install Django on Ubuntu 11.10?
9,558,078
6
2012-03-04T19:27:41Z
9,558,277
17
2012-03-04T19:54:32Z
[ "python", "django", "install" ]
I'm using [The Definitive guide to installing Django on ubuntu](http://felecan.com/2011/definitive-guide-installing-django-ubuntu/) and ironically need something more definitive because I can't make it work. (I have followed the steps before this on the link above) Here is my situation/standstill: ``` drewverlee@ubu...
`pip` is best tool for installing python packages. Here is [link](http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/) to install setup-tools and pip on ubuntu. If you have installed pip then it will be very easy to install django and other python packages. ``` $ sudo pip install django ``` ...
The _imaging C module is not installed (on windows)
9,558,562
6
2012-03-04T20:35:01Z
9,558,617
11
2012-03-04T20:42:16Z
[ "python", "django", "pdf", "python-imaging-library" ]
I'm trying to generate some pdf with django/PIL/Imaging and everything is good until I attempt to put some images into the pdf: ``` Exception Type: ImportError Exception Value: The _imaging C module is not installed Exception Location: D:\install\python27\lib\site-packages\PIL\Image.py in __getattr__, line 37 Pyth...
Yes, this could definitely be (and most likely is) caused by an x64 issue. If you're running Python x64, any module that includes a native DLL needs to be installed in a version compiled for x64 too. Edit: I cannot find an actual precompiled version for x64 at the PIL site, but [here](http://stackoverflow.com/question...
Deal with overflow in exp using numpy
9,559,346
7
2012-03-04T22:18:10Z
9,559,478
10
2012-03-04T22:35:36Z
[ "python", "numpy", "overflow", "exp" ]
Using numpy, I have this definition of a function: ``` def powellBadlyScaled(X): f1 = 10**4 * X[0] * X[1] - 1 f2 = numpy.exp(-numpy.float(X[0])) + numpy.exp(-numpy.float(X[1])) - 1.0001 return f1 + f2 ``` This function is evaluated a huge number of times on an optimization routine. It often raises excepti...
You can use the bigfloat package, with supports arbitrary precision floating point operations. <http://packages.python.org/bigfloat/> ``` import bigfloat bigfloat.exp(5000,bigfloat.precision(100)) # -> BigFloat.exact('2.9676283840236670689662968052896e+2171', precision=100) ``` Are you using a function optimization ...
How to store and compare password in db using py-bcrypt
9,559,549
16
2012-03-04T22:45:02Z
10,437,670
8
2012-05-03T18:56:57Z
[ "python", "bcrypt" ]
I would like to use py-bcrypt to store passwords in a db. Storing is easy: ``` import bcrypt password = u'foobar' password_hashed = bcrypt.hashpw(password, bcrypt.gensalt()) #then store password_hashed in db ``` But how to read and compare later? This is where I'm stuck. Any help would be awesome!
The documentation doesn't mention storing the salt, it says you just have to: ``` #Initial generation hashed = bcrypt.hashpw(password, bcrypt.gensalt()) #Store hashed in your db #Load hashed from the db and check the provided password if bcrypt.hashpw(password, hashed) == hashed: print "It matches" else: prin...
How to store and compare password in db using py-bcrypt
9,559,549
16
2012-03-04T22:45:02Z
13,001,189
29
2012-10-21T19:11:06Z
[ "python", "bcrypt" ]
I would like to use py-bcrypt to store passwords in a db. Storing is easy: ``` import bcrypt password = u'foobar' password_hashed = bcrypt.hashpw(password, bcrypt.gensalt()) #then store password_hashed in db ``` But how to read and compare later? This is where I'm stuck. Any help would be awesome!
With py-bcrypt, you don't need to store the salt seperately. `bcrypt` stores the salt in the hash. You can simply use the hash as a salt, and the salt is stored in the beginning of the hash. ``` >>> import bcrypt >>> salt = bcrypt.gensalt() >>> hash = bcrypt.hashpw('secret', salt) >>> hash.find(salt) 0 >>> hash == bcr...
Break down this list using list comprehension
9,559,646
3
2012-03-04T22:58:12Z
9,559,846
7
2012-03-04T23:23:51Z
[ "python", "list", "list-comprehension" ]
I was wondering if there is a good pythonic way to break down this list: ``` ['1,2,3', '22', '33'] ``` into the list: ``` ['1','2','3','22','33'] ``` using list comprehension?
With a list comprehension, it would look like this: ``` >>> L = ['1,2,3', '22', '33'] >>> [x for l in L for x in l.split(",")] ['1', '2', '3', '22', '33'] ``` ***Note:*** there are clearer and better ways of doing this, as already posted in the other answers (either itertools chain or the generator expression are goo...
Unit testing a python app that uses the requests library
9,559,963
41
2012-03-04T23:40:18Z
9,560,379
19
2012-03-05T00:48:19Z
[ "python", "unit-testing", "testing", "mocking", "python-requests" ]
I am writing an application that performs REST operations using Kenneth Reitz's [requests library](http://docs.python-requests.org/en/v0.10.6/index.html) and I'm struggling to find a nice way to unit test these applications, because requests provides its methods via module-level methods. What I want is the ability to ...
You could use a mocking library such as [Mocker](http://niemeyer.net/mocker) to intercept the calls to the requests library and return specified results. As a very simple example, consider this class which uses the requests library: ``` class MyReq(object): def doSomething(self): r = requests.get('https:/...
Unit testing a python app that uses the requests library
9,559,963
41
2012-03-04T23:40:18Z
18,490,571
27
2013-08-28T14:19:32Z
[ "python", "unit-testing", "testing", "mocking", "python-requests" ]
I am writing an application that performs REST operations using Kenneth Reitz's [requests library](http://docs.python-requests.org/en/v0.10.6/index.html) and I'm struggling to find a nice way to unit test these applications, because requests provides its methods via module-level methods. What I want is the ability to ...
If you use specifically requests try [httmock](https://pypi.python.org/pypi/httmock/). It's wonderfully simple and elegant: ``` from httmock import urlmatch, HTTMock import requests # define matcher: @urlmatch(netloc=r'(.*\.)?google\.com$') def google_mock(url, request): return 'Feeling lucky, punk?' # open cont...
Unit testing a python app that uses the requests library
9,559,963
41
2012-03-04T23:40:18Z
27,077,674
11
2014-11-22T13:02:28Z
[ "python", "unit-testing", "testing", "mocking", "python-requests" ]
I am writing an application that performs REST operations using Kenneth Reitz's [requests library](http://docs.python-requests.org/en/v0.10.6/index.html) and I'm struggling to find a nice way to unit test these applications, because requests provides its methods via module-level methods. What I want is the ability to ...
It is in fact a little strange that the library has a blank page about end-user unit testing, while targeting user-friendliness and ease of use. There's however an easy-to-use library by Dropbox, unsurprisingly called [`responses`](https://pypi.python.org/pypi/responses). Here is its [intro post](http://cramer.io/2014/...
How to count values in a certain range in a Numpy array?
9,560,207
17
2012-03-05T00:22:05Z
9,560,228
32
2012-03-05T00:25:37Z
[ "python", "arrays", "numpy" ]
I have a NumPy array of values. I want to count how many of these values are in a specific range say x<100 and x>25. I have read about the counter, but it seems to only be valid for specif values not ranges of values. I have searched, but have not found anything regarding my specific problem. If someone could point me ...
If your array is called `a`, the number of elements fulfilling `25 < x < 100` is ``` ((25 < a) & (a < 100)).sum() ``` The expression `(25 < a) & (a < 100)` results in a Boolean array with the same shape as `a` with the value `True` for all elements that satisfy the condition. Summing over this Boolean array treats `T...
Sympy "global" substitution
9,560,362
5
2012-03-05T00:45:35Z
9,560,695
8
2012-03-05T01:43:46Z
[ "python", "symbolic-math", "sympy" ]
I have a number of symbolic expressions in sympy, and I may come to realize that one of the coefficients is zero. I would think, perhaps because I am used to mathematica, that the following makes sense: ``` from sympy import Symbol x = Symbol('x') y = Symbol('y') f = x + y x = 0 f ``` Surprisingly, what is returned i...
I think `subs` is the only way to do this. It looks like a sympy expression is something unto itself. It does not reference the pieces that made it up. That is `f` only has the expression `x+y`, but doesn't know it has any link back to the python objects `x` and `y`. Consider the code below: ``` from sympy import Symb...
Sympy "global" substitution
9,560,362
5
2012-03-05T00:45:35Z
9,560,707
7
2012-03-05T01:45:01Z
[ "python", "symbolic-math", "sympy" ]
I have a number of symbolic expressions in sympy, and I may come to realize that one of the coefficients is zero. I would think, perhaps because I am used to mathematica, that the following makes sense: ``` from sympy import Symbol x = Symbol('x') y = Symbol('y') f = x + y x = 0 f ``` Surprisingly, what is returned i...
I don't think there is a way to do that automatically (or at least no without modifying SymPy). The following question from [SymPy's FAQ](https://github.com/sympy/sympy/wiki/Faq) explains why: > ## Why doesn't changing one variable change another that depends it? > > The short answer is "because it **doesn't** depend...
Python string -- swap positions in and out of parentheses
9,560,435
2
2012-03-05T00:57:53Z
9,560,468
7
2012-03-05T01:04:02Z
[ "python" ]
I have the following string: ``` "Person One (Something inside here) Second Thing (another thing) OK (something else)" ``` I need to get the following: ``` "Something inside here (Person One) another thing (Second Thing) something else (OK)" ``` Currently I am doing it like: ``` inside_parens = [] for item in str....
``` >>> s = 'Person One (Something inside here) Second Thing (another thing) OK (something else)' >>> import re >>> re.sub('(.*?) \((.*?)\)( ?)', r'\2 (\1)\3', s) 'Something inside here (Person One) another thing (Second Thing) something else (OK)' ``` The way in which whitespace needs to be not switched around makes ...
How do I use the Python Scrapy module to list all the URLs from my website?
9,561,020
12
2012-03-05T02:43:47Z
9,570,320
33
2012-03-05T16:36:50Z
[ "python", "web-crawler", "scrapy" ]
I want to use the Python [Scrapy module](http://scrapy.org/) to scrape all the URLs from my website and write the list to a file. I looked in the examples but didn't see any simple example to do this.
Here's the python program that worked for me: ``` from scrapy.selector import HtmlXPathSelector from scrapy.spider import BaseSpider from scrapy.http import Request DOMAIN = 'example.com' URL = 'http://%s' % DOMAIN class MySpider(BaseSpider): name = DOMAIN allowed_domains = [DOMAIN] start_urls = [ ...
Vertical and Horizontal Scrollbars on Tkinter Widget
9,561,030
5
2012-03-05T02:45:55Z
9,566,381
7
2012-03-05T12:07:49Z
[ "python", "tkinter", "scrollbar", "tkinter-canvas" ]
I am trying to output the contents of a database to a Tkinter widget. The database has enough rows and columns to where I need to have both horizontal and vertical scrollbars enabled, but I am having a hard time getting horizontal and vertical scrolling to work simultaneously. I am agnostic about which Tkinter widget i...
I don't see any code that would prevent the scrollbars from working. I do see a problem that prevents one of the scrollbars from showing up where you expect it (assuming you expect them to appear in the traditional place). Is that what you mean whey you say you want them to "work simultaneously"? Your layout is done w...
Using setattr() in python
9,561,174
23
2012-03-05T03:11:40Z
9,561,192
40
2012-03-05T03:14:12Z
[ "python", "setattr" ]
I am looking for someone to explain the basics of how to use, and not use `setattr()`. My problem arose trying to use one class method/function to return data that is then put in another method/function. Perhaps a simpler approach would be much better in this case, but I'm trying to understand how classes work/are use...
You are setting `self.name` to the *string* `"get_thing"`, not the function `get_thing`. If you want `self.name` to be a function, then you should set it to one: ``` setattr(self, 'name', self.get_thing) ``` However, that's completely unnecessary for your other code, because you could just call it directly: ``` val...
Using setattr() in python
9,561,174
23
2012-03-05T03:11:40Z
9,561,207
37
2012-03-05T03:15:31Z
[ "python", "setattr" ]
I am looking for someone to explain the basics of how to use, and not use `setattr()`. My problem arose trying to use one class method/function to return data that is then put in another method/function. Perhaps a simpler approach would be much better in this case, but I'm trying to understand how classes work/are use...
The [Python docs](http://docs.python.org/library/functions.html#setattr) say all that needs to be said, as far as I can see. > ### `setattr`(*object*, *name*, *value*) > > This is the counterpart of [`getattr()`](http://docs.python.org/library/functions.html#getattr). The arguments are an object, a string and an arbit...
How to check if something exists in a postgresql database using django?
9,561,243
12
2012-03-05T03:20:49Z
9,562,494
28
2012-03-05T06:27:30Z
[ "python", "database", "django", "postgresql" ]
I want to check to see if row in the database already contains a particular input. If it does already exist, prevent it from being added again, if not then add it like normal. How can I ask the database if something exists without pulling all of the contents out of the database in order to check?
You can use ``` Entry.objects.filter(name='name', title='title').exists() ``` This will return to you true/false values. When you use count the orm generates query which will be executed much longer than in exists method. The get method will raise an exception when object does not exists. request.POST is a dictionar...
What if I don't close the database connection in Python SQLite
9,561,832
28
2012-03-05T04:57:35Z
9,613,153
17
2012-03-08T05:05:25Z
[ "python", "sqlite3", "database-connection" ]
I am doing something like this... ``` conn = sqlite3.connect(db_filename) with conn: cur = conn.cursor() cur.execute( ... ) ``` `with` automatically commits the changes. But the docs say nothing about closing the connection. Actually I can use `conn` in later statements (which I have tested). Hence it seems...
In answer to the specific question of what happens if you do not close a SQLite database, the answer is quite simple and applies to using SQLite in any programming language. When the connection is closed explicitly by code or implicitly by program exit then any outstanding transaction is rolled back. (The rollback is a...
removing buttons/links in django admin
9,563,935
2
2012-03-05T08:59:49Z
9,564,009
7
2012-03-05T09:06:31Z
[ "python", "django", "django-admin" ]
I have an apps and I am making used of django admin, but my apps does not allow deleting of data and django admin have a `delete` button/link. I have already removed the `delete action`. my question is, how can i remove the `delete` button/link in admin page in django?
Do not remove or change anything in the admin. Instead remove user's/group's permission to delete given model. If user does not have the permission to delete, the delete button won't appear at any page related to that model.
removing buttons/links in django admin
9,563,935
2
2012-03-05T08:59:49Z
9,573,364
8
2012-03-05T20:18:11Z
[ "python", "django", "django-admin" ]
I have an apps and I am making used of django admin, but my apps does not allow deleting of data and django admin have a `delete` button/link. I have already removed the `delete action`. my question is, how can i remove the `delete` button/link in admin page in django?
``` class MyAdmin(ModelAdmin): def get_actions(self, request): actions = super(MyAdmin, self).get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions def has_delete_permission(self, request, obj=None): return False ``` If...
Mongoengine... query something not in a ListField?
9,565,194
7
2012-03-05T10:37:38Z
9,565,373
13
2012-03-05T10:51:31Z
[ "python", "django", "mongodb", "mongoengine" ]
for example.. ``` class Page(Document) tags = ListField(StringField()) ``` In this case, we can find out a value in the tags list like this. ``` Page.objects(tags='coding') ``` if tags are like ['coding', 'x', 'y'], then the document will be matched... but My question is how I can find out the value not in the...
To find any pages that don't have the tags coding use the [$nin](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24nin) operator: ``` Page.objects(tags__nin=['coding']) ```
Saving numpy array to txt file row wise
9,565,426
12
2012-03-05T10:55:31Z
9,565,595
15
2012-03-05T11:08:33Z
[ "python", "numpy", "save" ]
I have an numpy array of form ``` a = [1,2,3] ``` which I want to save to a .txt file such that the file looks like: ``` 1 2 3 ``` If I use numpy.savetxt then I get a file like: ``` 1 2 3 ``` There should be a easy solution to this I suppose, any suggestions?
If `numpy >= 1.5`, you can do: ``` numpy.savetxt(filename, a, newline=" ") ``` **Edit** several 1D arrays with same length ``` a = numpy.array([1,2,3]) b = numpy.array([4,5,6]) numpy.savetext(filename, (a,b), fmt="%d") # gives: # 1 2 3 # 4 5 6 ``` several 1D arrays with variable length ``` a = numpy.array([1,2,3...
Find multiple values within a Numpy array
9,566,592
12
2012-03-05T12:24:28Z
9,566,681
19
2012-03-05T12:31:28Z
[ "python", "numpy" ]
I am looking for a numpy function to find the indices at which certain values are found within a vector (xs). The values are given in another array (ys). The returned indices must follow the order of ys. In code, I want to replace the list comprehension below by a numpy function. ``` >> import numpy as np >> xs = np....
For big arrays `xs` and `ys`, you would need to change the basic approach for this to become fast. If you are fine with sorting `xs`, then an easy option is to use `numpy.searchsorted()`: ``` xs.sort() ndx = numpy.searchsorted(xs, ys) ``` If it is important to keep the original order of `xs`, you can use this approac...
Python - Selenium WebDriver - Checking element exists
9,567,069
14
2012-03-05T13:00:31Z
9,587,938
19
2012-03-06T16:37:39Z
[ "python", "selenium", "webdriver" ]
I have a problem - I am using the selenium (firefox) web driver to open a webpage, click a few links etc. then capture a screenshot. My script runs fine from the CLI, but when run via a cronjob it is not getting past the first find\_element() test. I need to add some debug, or something to help me figure out why it is...
A) Yes. The easiest way to check if an element exists is to simply call `find_element` inside a `try/catch`. B) Yes, I always try to identify elements without using their text for 2 reasons: 1. the text is more likely to change and; 2. if it is important to you, you won't be able to run your tests against localized b...
Python - Selenium WebDriver - Checking element exists
9,567,069
14
2012-03-05T13:00:31Z
12,150,013
28
2012-08-27T21:43:55Z
[ "python", "selenium", "webdriver" ]
I have a problem - I am using the selenium (firefox) web driver to open a webpage, click a few links etc. then capture a screenshot. My script runs fine from the CLI, but when run via a cronjob it is not getting past the first find\_element() test. I need to add some debug, or something to help me figure out why it is...
a) ``` from selenium.common.exceptions import NoSuchElementException def check_exists_by_xpath(xpath): try: webdriver.find_element_by_xpath(xpath) except NoSuchElementException: return False return True ``` b) use xpath - the most reliable. Moreover you can take the xpath as a stan...
How does argparse (and the deprecated optparse) respond to 'tab' keypress after python program name, in bash?
9,568,611
10
2012-03-05T14:47:41Z
9,571,453
14
2012-03-05T17:52:58Z
[ "python", "bash", "autocomplete", "argparse", "shebang" ]
I have tested [`optcomplete`](http://furius.ca/optcomplete/) working with the `optparse` module. Its example is a simple file so I could get that working. I also tested it using the `argparse` module as the prior one is deprecated. But I really do not understand how and by whom the python program gets called on tab pre...
To understand what's happening here, let's check what that bash function actually does: ``` COMPREPLY=( $( \ COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \ COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ OPTPARSE_AUTO_COMPLETE=1 $1 ) ) ``` See the `$1` at the end? That means that it actually calls...
Iterate over *args?
9,569,092
7
2012-03-05T15:19:30Z
9,570,395
8
2012-03-05T16:41:38Z
[ "python", "arguments" ]
I have a script I'm working on where I need to accept multiple arguments and then iterate over them to perform actions. I started down the path of defining a function and using \*args. So far I have something like below: ``` def userInput(ItemA, ItemB, *args): THIS = ItemA THAT = ItemB MORE = *args ``` Wh...
Tho get your **precise** syntax: ``` def userInput(ItemA, ItemB, *args): THIS = ItemA THAT = ItemB MORE = args print THIS,THAT,MORE userInput('this','that','more1','more2','more3') ``` You remove the `*` in front of `args` in the assignment to `MORE`. Then MORE becomes a tuple with the variable len...
Which files shoud I tell my VCS to ignore when using Sphinx for documentation?
9,570,382
13
2012-03-05T16:40:54Z
9,570,581
9
2012-03-05T16:53:15Z
[ "python", "git", "version-control", "documentation", "python-sphinx" ]
I want to start using [Sphinx](http://sphinx.pocoo.org/) to document my project. I told Sphinx to use separate source and build directories during `sphinx-quickstart`. Now my directory layout is the following: ``` MyProject/ myproject/ __init__.py mymodule.py docs/ source/ ....
If you take a look at the contents of `Makefile` you'll see something as follows: ``` BUILDDIR = build ... clean: -rm -rf $(BUILDDIR)/* ``` This means that `make clean` just removes the `build` directory so, with regard to version control, ignoring the contents of the `build` directory should be enough as ...
In Python, how do I convert a list of ints and strings to Unicode?
9,571,151
9
2012-03-05T17:30:08Z
9,571,197
10
2012-03-05T17:33:40Z
[ "python", "unicode" ]
``` x = ['Some strings.', 1, 2, 3, 'More strings!', 'Fanc\xc3\xbf string!'] y = [i.decode('UTF-8') for i in x] ``` What's the best way to convert the strings in x to Unicode? Doing a list compression causes an attribute error (`AttributeError: 'int' object has no attribute 'decode'`) because int's don't have a decode ...
You could use the [unicode](http://docs.python.org/library/functions.html#unicode) function: ``` >>> x = ['Some strings.', 1, 2, 3, 'More strings!'] >>> y = [unicode(i) for i in x] >>> y [u'Some strings.', u'1', u'2', u'3', u'More strings!'] ``` **UPDATE**: since you specified that you want the integers to remain as-...
In Python, how do I convert a list of ints and strings to Unicode?
9,571,151
9
2012-03-05T17:30:08Z
9,571,360
8
2012-03-05T17:46:42Z
[ "python", "unicode" ]
``` x = ['Some strings.', 1, 2, 3, 'More strings!', 'Fanc\xc3\xbf string!'] y = [i.decode('UTF-8') for i in x] ``` What's the best way to convert the strings in x to Unicode? Doing a list compression causes an attribute error (`AttributeError: 'int' object has no attribute 'decode'`) because int's don't have a decode ...
If you want to keep the integers as they are in the list while just changing the strings to unicode, you can do ``` x = ['Some strings.', 1, 2, 3, 'More strings!'] y = [i.decode('UTF-8') if isinstance(i, basestring) else i for i in x] ``` which gets you ``` [u'Some strings.', 1, 2, 3, u'More strings!'] ```
base64 encoding unicode strings in python 2.7
9,572,274
5
2012-03-05T18:57:22Z
9,572,394
11
2012-03-05T19:06:34Z
[ "python", "character-encoding", "base64", "unicode-string", "python-unicode" ]
I have a unicode string retrieved from a webservice using the [`requests` module](http://docs.python-requests.org), **which contains the bytes of a binary document** (PCL, as it happens). One of these bytes has the value 248, and attempting to base64 encode it leads to the following error: ``` In [68]: base64.b64encod...
You have a `unicode` string which you want to base64 encode. The problem is that `b64encode()` only works on *bytes*, not *characters*. So, you need to transform your `unicode` string (which is a sequence of abstract Unicode codepoints) into a byte string. The mapping of abstract Unicode strings into a concrete series...
python files run fine when executed from different directory
9,572,429
3
2012-03-05T19:08:47Z
9,572,456
9
2012-03-05T19:11:20Z
[ "python" ]
I have a very wierd problem. When i run the file from a different directory it runs fine. but other wise i get this error ``` from textprocessor import * File "/home/mohit/Documents/analysis/categorization/textprocessor.py", line 2, in <module> import nltk File "/usr/local/lib/python2.7/dist-packages/nltk/__init__....
You've called a script in the same directory "io.py", and this is interfering with the `io` module in the stdlib. Rename it.
Find String index from last in Python
9,572,490
115
2012-03-05T19:13:32Z
9,572,516
197
2012-03-05T19:15:12Z
[ "python", "string" ]
I think it might be a silly question but as I'm totally new to Python, i don't know anything about it. I want to find the last position of a target string in given str as a input. For ex. `str='hello'` and `target='l'` then it should output 3. How can i do this?
Use [`.rfind()`](http://docs.python.org/py3k/library/stdtypes.html#str.rfind): ``` >>> s = 'hello' >>> s.rfind('l') 3 ``` Also don't use `str` as variable name or you'll shadow the built-in [`str()`](http://docs.python.org/py3k/library/functions.html#str).
Find String index from last in Python
9,572,490
115
2012-03-05T19:13:32Z
9,572,521
24
2012-03-05T19:15:18Z
[ "python", "string" ]
I think it might be a silly question but as I'm totally new to Python, i don't know anything about it. I want to find the last position of a target string in given str as a input. For ex. `str='hello'` and `target='l'` then it should output 3. How can i do this?
Use the `str.rindex` method. ``` >>> 'hello'.rindex('l') 3 >>> 'hello'.index('l') 2 ```
Find String index from last in Python
9,572,490
115
2012-03-05T19:13:32Z
26,928,312
21
2014-11-14T10:51:19Z
[ "python", "string" ]
I think it might be a silly question but as I'm totally new to Python, i don't know anything about it. I want to find the last position of a target string in given str as a input. For ex. `str='hello'` and `target='l'` then it should output 3. How can i do this?
You can use [`rfind()`](https://docs.python.org/3/library/stdtypes.html?highlight=rfind#str.rfind) or [`rindex()`](https://docs.python.org/3/library/stdtypes.html?highlight=rfind#str.rindex) Python2 links: [`rfind()`](https://docs.python.org/2/library/string.html#string.rfind) [`rindex()`](https://docs.python.org/2/...
break list comprehension
9,572,833
28
2012-03-05T19:40:16Z
9,572,876
8
2012-03-05T19:43:06Z
[ "python", "list-comprehension" ]
How can I break a list comprehension based on a condition, for instance when the number `412` is found? Code: ``` numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47,...
If 412 will definitely be in the list you could use this: ``` even = [n for n in numbers[:numbers.index(412)] if not n % 2] ``` If you want to include 412 in the result just use `numbers[:numbers.index(412)+1]` for the slice. Note that because of the slice this will be less efficient (at least memory-wise) than an i...
break list comprehension
9,572,833
28
2012-03-05T19:40:16Z
9,572,881
25
2012-03-05T19:43:32Z
[ "python", "list-comprehension" ]
How can I break a list comprehension based on a condition, for instance when the number `412` is found? Code: ``` numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47,...
You can use generator expressions together with `itertools.takewhile()`: ``` even_numbers = (n for n in numbers if not n % 2) list(itertools.takewhile(lambda x: x != 412, even_numbers)) ``` **Edit**: I just noticed the requirement not to use any `import`s. Well, I leave this answer here anyway.
break list comprehension
9,572,833
28
2012-03-05T19:40:16Z
9,572,933
30
2012-03-05T19:46:56Z
[ "python", "list-comprehension" ]
How can I break a list comprehension based on a condition, for instance when the number `412` is found? Code: ``` numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47,...
Use a function to raise `StopIteration` and `list` to catch it: ``` >>> def end_of_loop(): ... raise StopIteration ... >>> even = list(end_of_loop() if n == 412 else n for n in numbers if 0 == n % 2) >>> print(even) [402, 984, 360, 408, 980, 544, 390, 984, 592, 236, 942, 386, 462, 418, 344, 236, 566, 978, 328, 16...
Animating gif in wxPython
9,573,131
3
2012-03-05T20:00:51Z
9,579,790
8
2012-03-06T07:53:38Z
[ "python", "animation", "wxpython", "gif" ]
I'm trying to animate a gif using wx-Python (2.7). The code listed below works but i want to create a function that animates the gif for me, so i can use it elsewhere. I've tried searching the internet but i can only find code that animates the gif within the `__init__` function. Any ideas? ``` # -*- coding: cp1252 -*...
I don't understand your issue.... what is the problem in doing something like this? ``` import wx import wx.animate class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.SetBackgroundColour("black") gif_fname = "skYmk.gif" gif = wx.anim...
Most elegant way to check if the string is empty in Python?
9,573,244
537
2012-03-05T20:09:23Z
9,573,259
745
2012-03-05T20:10:21Z
[ "python", "string" ]
Does Python have something like an empty string variable where you can do?: ``` if myString == string.empty: ``` Regardless what's the most elegant way to check for empty string values? I find hard coding `""` every time for checking an empty string not as good.
Empty strings are ["falsy"](http://docs.python.org/2/library/stdtypes.html#truth-value-testing) which means they are considered false in a Boolean context, so you can just do this: ``` if not myString: ``` This is the preferred way if you know that your variable is a string. If your variable could also be some other ...
Most elegant way to check if the string is empty in Python?
9,573,244
537
2012-03-05T20:09:23Z
9,573,278
91
2012-03-05T20:11:54Z
[ "python", "string" ]
Does Python have something like an empty string variable where you can do?: ``` if myString == string.empty: ``` Regardless what's the most elegant way to check for empty string values? I find hard coding `""` every time for checking an empty string not as good.
The most elegant way would probably be to simply check if its true or falsy, e.g.: ``` if not my_string: ``` However, you may want to strip white space because: ``` >>> bool("") False >>> bool(" ") True >>> bool(" ".strip()) False ``` You should probably be a bit more explicit in this however, unless you ...
Most elegant way to check if the string is empty in Python?
9,573,244
537
2012-03-05T20:09:23Z
9,573,283
158
2012-03-05T20:12:19Z
[ "python", "string" ]
Does Python have something like an empty string variable where you can do?: ``` if myString == string.empty: ``` Regardless what's the most elegant way to check for empty string values? I find hard coding `""` every time for checking an empty string not as good.
From [PEP 8](http://www.python.org/dev/peps/pep-0008/), in the [“Programming Recommendations” section](https://www.python.org/dev/peps/pep-0008/#programming-recommendations): > For sequences, (strings, lists, tuples), use the fact that empty sequences are false. So you should use: ``` if not some_string: ``` or...
Most elegant way to check if the string is empty in Python?
9,573,244
537
2012-03-05T20:09:23Z
24,534,152
24
2014-07-02T14:44:02Z
[ "python", "string" ]
Does Python have something like an empty string variable where you can do?: ``` if myString == string.empty: ``` Regardless what's the most elegant way to check for empty string values? I find hard coding `""` every time for checking an empty string not as good.
I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This is what I would use to test if a String is either None OR Empty OR Blank: ``` def isBlank (myString): if myString and myString.strip(): #myString is not None AND myString is not empty or blank ...
Python C API: Using PyEval_EvalCode
9,573,422
4
2012-03-05T20:22:30Z
9,613,177
7
2012-03-08T05:08:56Z
[ "python", "python-3.x", "python-c-api", "python-c-extension" ]
I'm trying to figure out how to use the Python interpreter from C, and I'm having trouble with `PyEval_EvalCode`. Basically, I'm writing a C function which takes in an arbitrary string of Python code, compiles it, executes it, and then prints out the result. The problem is that when I print out the result, I always ge...
If you want to evaluate an expression, you need to use `Py_eval_input` as an argument to `Py_CompileString`. My understanding of the matter is that: * `Py_eval_input` is equivalent to the built-in `eval` -- it evaluates an expression. * `Py_file_input` is equivalent to `exec` -- It executes Python code, but does not ...
python make class iterable by returning embedded iterable
9,573,591
12
2012-03-05T20:35:46Z
9,573,612
22
2012-03-05T20:36:49Z
[ "python", "iterable" ]
I have a class in python, which has an iterable as instance variable. I want to iterate the instances of the class by iterating over the embedded iterable. I implemented this as follows: ``` def __iter__(self): return self._iterable.__iter__() ``` I don't really feel that comfortable calling the `__iter__()` met...
The "best" way to way to delegate `__iter__` would be: ``` def __iter__(self): return iter(self._iterable) ``` Alternately, it might be worth knowing about: ``` def __iter__(self): for item in self._iterable: yield item ``` Which will let you fiddle with each item before returning it (ex, if you wan...
Is there a Python equivalent for Perl's `study`?
9,574,196
4
2012-03-05T21:23:24Z
9,574,874
8
2012-03-05T22:15:09Z
[ "python", "regex", "perl", "optimization" ]
From Perl's [documentation](http://perldoc.perl.org/functions/study.html): > `study` takes extra time to study SCALAR ($\_ if unspecified) in anticipation of doing > many pattern matches on the string before it is next modified. This may or may not save > time, depending on the nature and number of patterns you are se...
Perl’s study doesn’t really do much anymore. The regex compiled has gotten a whole, whole lot smarter than it was when `study` was created. For example, it compiles alternatives into a trie structure with Aho–Corasick prediction. Run with `perl -Mre=debug` to see the sorts of cleverness the regex compiler and e...
How to convert a python datetime.datetime to excel serial date number
9,574,793
3
2012-03-05T22:08:57Z
9,574,948
10
2012-03-05T22:22:07Z
[ "python", "excel", "data-munging" ]
I need to convert dates into Excel serial numbers for a data munging script I am writing. By playing with dates in my OpenOffice Calc workbook, I was able to deduce that '1-Jan 1899 00:00:00' maps to the number zero. I wrote the following function to convert from a python datetime object into an Excel serial number: ...
It appears that the Excel "serial date" format is actually the number of *days* since 1900-01-00, with a fractional component that's a fraction of a day, based on <http://www.cpearson.com/excel/datetime.htm>. (I guess that date should actually be considered 1899-12-31, since there's no such thing as a 0th day of a mont...
Writing test cases for django models
9,574,810
19
2012-03-05T22:09:45Z
9,575,563
47
2012-03-05T23:14:01Z
[ "python", "django", "django-models", "django-testing" ]
Half way through my current project, after suffering the pain of spending uncountable minutes on debugging, I have decided to adopt TDD. To start, I am planning to write a set of unit tests for each existing models. But for models that only have attributes defined (ie. no additional methods/properties) I am not sure wh...
This was an article I found helpful: <http://toastdriven.com/blog/2011/apr/10/guide-to-testing-in-django/>. Here is a good summary of what to test: > Another common setback for developers/designers new to testing is the > question of 'what should (or shouldn't) I test?' While there are no > hard & fast rules here that...
With boto, how can I name a newly spawned EC2 instance?
9,575,148
22
2012-03-05T22:39:44Z
9,585,424
31
2012-03-06T14:18:31Z
[ "python", "amazon-ec2", "amazon-web-services", "boto" ]
I'm using boto to spawn a new EC2 instance based on an AMI. The ami.run method has a number of parameters, but none for "name" - maybe it's called something different?
``` import boto c = boto.connect_ec2(ec2_key, ec2_secret) image = c.get_image(ec2_ami) reservation = image.run(key_name=ec2_keypair, security_groups=ec2_secgroups, instance_type=ec2_instancetype) instance = reservation.instances[0] c.create_tags([instance.id], {"Name": ...
How can I iterate over ManyToManyField?
9,575,310
18
2012-03-05T22:52:53Z
9,575,414
49
2012-03-05T23:01:11Z
[ "python", "database", "django", "orm", "model" ]
A simple question and yet I can't find an answer for it. I have a model with a ManyToMany field: ``` class Stuff(models.Model): things = models.ManyToManyField(Thing) ``` then in a different function I want to do this: ``` myStuff = Stuff.objects.get(id=1) for t in myStuff.things.all: # ... ``` But that is giv...
Try adding the `()` after `all`: `myStuff.things.all()`
Calling parent class __init__ with multiple inheritance, what's the right way?
9,575,409
47
2012-03-05T23:00:31Z
9,575,426
22
2012-03-05T23:02:04Z
[ "python", "multiple-inheritance" ]
Say I have a multiple inheritance scenario: ``` class A(object): # code for A here class B(object): # code for B here class C(A,B): def __init__(self): # What's the right code to write here to ensure # A.__init__ and B.__init__ get called? ``` There's two typical approaches to writing C...
Both ways work fine. The approach using `super()` leads to greater flexibility for subclasses. In the direct call approach, `C.__init__` can call both `A.__init__` and `B.__init__`. When using `super()`, the classes need to be designed for cooperative multiple inheritance where `C` calls `super`, which invokes `A`'s ...
Mixed shell and python script possible?
9,575,715
6
2012-03-05T23:30:10Z
9,575,745
8
2012-03-05T23:34:01Z
[ "python", "linux", "shell" ]
I swear I have seen this done before but can not find it now. Is it possible to have a shell script start a python interpeter "mid stream", ie: ``` #!/bin/bash #shell stuff.. set +e VAR=aabb for i in a b c; do echo $i done # same file! #!/usr/bin/env python # python would be given this fd which has been seek'...
You can use this shell syntax (it is called *here document* in Unix literature): ``` #!/bin/sh echo this is a shell script python <<@@ print 'hello from Python!' @@ ``` The marker after '<<' operator can by an arbitrary identifier, people often use something like EOF (end of file) or EOD (end of document). If the ma...
Maximum of two tuples
9,575,917
10
2012-03-05T23:51:13Z
9,576,006
12
2012-03-05T23:59:31Z
[ "python", "max" ]
The Python documentation states that, when called with more than one argument, max() returns the *largest* of the arguments. ``` >>> a = (1, 1, 1, 9) >>> b = (4, 5, 6) >>> max(a, b) (4, 5, 6) ``` What defines how *large* a tuple, in this context, is? The tuple *a* has both a higher number of elements (four versus thr...
Tuples like all other sequences are ordered lexicographically: the order of two tuples is decided by the first position where the tuples differ. Quoting from [python reference](http://docs.python.org/reference/expressions.html#comparisons): > Tuples and lists are compared lexicographically using comparison of > corres...
celery - call function on task done
9,576,160
6
2012-03-06T00:20:24Z
9,602,782
11
2012-03-07T13:54:31Z
[ "python", "django", "rabbitmq", "celery" ]
I'm using celery with django and rabbitmq to create a message queue. I also have a worker, which is originating from a different machine. In a django view I'm starting a process like this: ``` def processtask(request, name): args = ["ls", "-l"] MyTask.delay(args) return HttpResponse("Task set to execute.") ``` ...
If you look [here](http://ask.github.com/celery/faq.html#mysql-is-throwing-deadlock-errors-what-can-i-do) you will find the following: Django-celery uses MySQL to keep track of all tasks/results, rabbit-mq is used as a communication bus basically. What really is happening is that you are trying to fetch the `ASyncRes...
Passing STATIC_URL to file javascript with django
9,576,675
19
2012-03-06T01:33:51Z
9,576,892
19
2012-03-06T01:58:26Z
[ "javascript", "python", "django", "static" ]
Which is the best solution to pass {{ STATIC\_URL }} to javascript files? I'm working with django and python. Thanks in advance. Regards.
`django-compressor` lets you do this as well as optimize your site by condensing all of your required JS or CSS into one file and optimizing file size. **UPDATE:** By default, compressor will convert relative urls into absolute urls using `STATIC_URL`. If you download the development version, it comes with a django te...
Passing STATIC_URL to file javascript with django
9,576,675
19
2012-03-06T01:33:51Z
12,881,684
34
2012-10-14T11:12:38Z
[ "javascript", "python", "django", "static" ]
Which is the best solution to pass {{ STATIC\_URL }} to javascript files? I'm working with django and python. Thanks in advance. Regards.
Using a global javascript variable with the static url value is more simple : ``` <script language="javascript">var STATIC_URL = "{{ STATIC_URL|escapejs }}";</script> <script src="{{ STATIC_URL }}js/myfile.js"></script> ``` Then, you can simply use the static url by calling STATIC\_URL in myfile.js : ``` html = '<im...
Is there a friendly name for this data structure?
9,576,676
4
2012-03-06T01:33:57Z
9,576,765
7
2012-03-06T01:43:58Z
[ "python", "algorithm", "data-structures" ]
While working on a feature selector for a machine learning algorithm in Python, I generated a data structure with the following code: ``` # Perform set partitioning on the results groups = [] for t in results: (jthName,kthName) = t jthGroup = -1 kthGroup = -1 # Just a simple list of hashes with online...
I think what you're looking for is something called a [Disjoint-set data structure](http://en.wikipedia.org/wiki/Disjoint-set_data_structure). It's often used when doing Kruskal's because it allows you to do n lookups in amortized nlog\*n (actually less than that) time if you implement the disjoint-set data structure ...
What's the equivalent of Python's Celery project for Java?
9,577,012
17
2012-03-06T02:12:47Z
13,183,009
8
2012-11-01T18:08:19Z
[ "java", "python", "celery", "batch-processing", "spring-batch" ]
I am trying to find an equivalent of Celery project for Java environment, I have looked at Spring Batch, but are there any better alternatives for distributed task queues. Thanks.
Jesque (<https://github.com/gresrun/jesque>) is a Java distributed task queue library. It is a Java port of the Resque library (<https://github.com/defunkt/resque>), which is described like this on its GitHub page: > Resque (pronounced like "rescue") is a Redis-backed library for creating background jobs, placing thos...
What's the equivalent of Python's Celery project for Java?
9,577,012
17
2012-03-06T02:12:47Z
14,733,488
13
2013-02-06T16:07:30Z
[ "java", "python", "celery", "batch-processing", "spring-batch" ]
I am trying to find an equivalent of Celery project for Java environment, I have looked at Spring Batch, but are there any better alternatives for distributed task queues. Thanks.
What Celery is doing is very much akin to [EIP](http://en.wikipedia.org/wiki/Enterprise_Integration_Patterns), and [SEDA](http://en.wikipedia.org/wiki/Staged_event-driven_architecture) with convenient task scheduling... (all you have left to do is add some DB, and async HTTP networking and you have got a complete enter...
Converting a QStringList (PyQt) into a normal python list
9,577,175
3
2012-03-06T02:38:51Z
9,577,217
7
2012-03-06T02:44:39Z
[ "python", "list", "pyqt", "pyqt4", "qstring" ]
I want to take each element within a qstringlist and get the raw data from the list not whatever pyqt is storing it as. ``` def find(self): self.foundFileList.setRowCount(0) fileName = self.inputFileName.currentText() path = self.directoryPath.currentText() maxSize = Decimal(self.maxFi...
How about: ``` print map(str, nameList) print "_____________________________" print [str(f.fileName()) for f in fileList] ``` The first one just converts each QString to a string. The second gets the fileName() value of each QFile You could also write the map as a list comprehension: ``` print [str(name) for name ...
Skip first couple of lines while reading lines in Python file
9,578,580
24
2012-03-06T05:51:19Z
9,578,638
52
2012-03-06T05:57:51Z
[ "python", "file", "lines", "skip" ]
I want to skip the first 17 lines while reading a text file. Let's say the file looks like: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 good stuff ``` I just want the good stuff. What I'm doing is a lot more complicated, but this is the part I'm having trouble with.
Use a slice, like below ``` with open('yourfile.txt') as f: lines_after_17 = f.readlines()[17:] ``` --- If the file is too big to load in memory: ``` with open('yourfile.txt') as f: for _ in xrange(17): next(f) for line in f: # do stuff ```
Skip first couple of lines while reading lines in Python file
9,578,580
24
2012-03-06T05:51:19Z
9,578,684
13
2012-03-06T06:02:32Z
[ "python", "file", "lines", "skip" ]
I want to skip the first 17 lines while reading a text file. Let's say the file looks like: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 good stuff ``` I just want the good stuff. What I'm doing is a lot more complicated, but this is the part I'm having trouble with.
``` import itertools with open('file.txt') as f: for line in itertools.islice(f, 17, None): # start=17, stop=None # process lines ```
Easiest way to combine date and time strings to single datetime object using Python
9,578,906
3
2012-03-06T06:23:43Z
9,579,000
10
2012-03-06T06:33:04Z
[ "python", "datetime" ]
I have a web form which has 2 input fields, "StartDate" and "StartTime". I convert the `StartDate` field's string into a Python `datetime` object, no problem. The `StartTime` field is passed in as a string in the form "0130" for 1:30am. What is the best way to convert the `StartTime` string and combine it with the `Sta...
Use [datetime.combine](http://docs.python.org/library/datetime.html#datetime.datetime.combine): ``` import datetime as dt mytime = dt.datetime.strptime('0130','%H%M').time() mydatetime = dt.datetime.combine(dt.date.today(), mytime) ```
How to convert a random number to another base format?
9,579,091
2
2012-03-06T06:41:46Z
9,579,322
7
2012-03-06T07:03:27Z
[ "python", "math" ]
I want to pick a random number and express that number in the format of a lottery system. For example, a lottery system has 7 groups of 2-digit numbers from 01 to 40 with the total possible combinations of 163,840,000,000 (40 to the 7th power). If I pick a random base-10 number, say 453,867,221, How can I express that ...
The standard library's `random.sample` chooses n values from a population without replacement: ``` >>> import random >>> ' '.join('{:02d}'.format(n) for n in random.sample(xrange(1,41),7)) '25 19 15 09 01 26 06' ``` But here's exactly what you asked for, including the possibility of repeated numbers: ``` import rand...
Troubleshooting 'WSGIRequest' object has no attribute 'user'?
9,579,729
9
2012-03-06T07:46:15Z
9,580,396
10
2012-03-06T08:45:49Z
[ "python", "django" ]
I'm trying to use the `@login_required` decorator but I get a `'WSGIRequest' object has no attribute 'user'` AttributeError. I have the import statement `from django.contrib.auth.decorators import login_required` on the top but I still get the error. When I delete `@login_required` from in front of `def profile(request...
You need to enable 'django.contrib.auth.middleware.AuthenticationMiddleware', because it sets request.user. You should also enable the other default middleware or you're going to have other problems.
parsing gettext .po files with python
9,580,449
7
2012-03-06T08:49:34Z
9,998,895
16
2012-04-03T18:09:12Z
[ "python", "gettext" ]
I need to extract messages from the .po files. Is there a python-module to do that? I write a parser, but it depend on platform (like \r\n, \n), so maybe there is some normal way to da that?
In most cases you don't need to parse `.po` files yourself. Developers give translators a `.pot` template file, they rename it to `xx_XX.po` and translate the strings. Then you as developer only have to "compile" them to `.mo` files using GNU's `gettext` tools (or its Python implementation, `pygettext`) But, if you wa...
What is the simplest way to define setter and getter in Python
9,585,978
4
2012-03-06T14:50:18Z
9,586,026
14
2012-03-06T14:52:36Z
[ "python", "setter", "getter" ]
What is the simplest way to define setter and getter in Python? Is there anything like in C# ``` public int Prop {get; set;} ``` How to make it like this? Since to write both setter and getter methods for one property like this is just too much work. ``` class MyClass(): def foo_get(self): return self._f...
If the setter and getter do nothing else than accessing an underlying real attribute, then the simplest way of implementing them is not to write setters and getters at all. This is the standard behaviour, and there is no point in writing functions recreating the behaviour the attribute has anyway. You don't need gette...
What is the simplest way to define setter and getter in Python
9,585,978
4
2012-03-06T14:50:18Z
9,586,099
7
2012-03-06T14:57:03Z
[ "python", "setter", "getter" ]
What is the simplest way to define setter and getter in Python? Is there anything like in C# ``` public int Prop {get; set;} ``` How to make it like this? Since to write both setter and getter methods for one property like this is just too much work. ``` class MyClass(): def foo_get(self): return self._f...
Usually you don't write setters/getters at all. There's no point since python doesn't prevent anyone from accessing the attributes directly. However, if you need logic, you can use [`property`s](http://docs.python.org/library/functions.html#property) ``` class Foo(object): def __init__(self, db): self.db =...
Virtualenv and source version control
9,586,346
48
2012-03-06T15:11:49Z
9,586,604
54
2012-03-06T15:26:29Z
[ "python", "django", "mercurial", "virtualenv" ]
I recently started a Django project and I quickly realized that virtualenv will be really useful for many reasons. I set up the virtualenv and my project, but now I wonder what file I should add to my source control (in my case, Mercurial). Should I add all the files under the venv folder? How do I make sure a colleagu...
You generate a "requirements" file (usually `requirements.txt`) that you commit with your project: ``` pip freeze > requirements.txt ``` Then, each developer will set up their own virtualenv and run: ``` pip install -r requirements.txt ```
python paths and import order
9,586,630
11
2012-03-06T15:28:04Z
9,588,902
11
2012-03-06T17:34:55Z
[ "python" ]
Ok so I really want to get this right because I keep running into it when generating some big py2app/py2exe packages. So I have my package that contains a lot of modules/packages that might also be in the users site packages/default location (if a user has a python distribution) but I want my distributed packages to ta...
Python searches the paths in `sys.path` in order (see <http://docs.python.org/tutorial/modules.html#the-module-search-path>). easy\_install changes this list directly (see the last line in your easy-install.pth file): ``` import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0);...
Simple cross-tabulation in pandas
9,588,331
20
2012-03-06T17:01:47Z
9,620,832
11
2012-03-08T16:08:29Z
[ "python", "pandas" ]
I stumbled across [pandas](http://pandas.pydata.org/) and it looks ideal for simple calculations that I'd like to do. I have a SAS background and was thinking it'd replace proc freq -- it looks like it'll scale to what I may want to do in the future. However, I just can't seem to get my head around a simple task (I'm n...
Assuming that you have a file called 2010.csv with contents ``` category,value AB,100.00 AB,200.00 AC,150.00 AD,500.00 ``` Then, using the ability to apply [multiple aggregation functions following a groupby](http://pandas.pydata.org/pandas-docs/dev/groupby.html#applying-multiple-functions-at-once), you can say: ```...