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 |
|---|---|---|---|---|---|---|---|---|---|
Convert Javascript array to python list? | 10,641,893 | 3 | 2012-05-17T19:00:25Z | 10,641,983 | 11 | 2012-05-17T19:06:24Z | [
"python"
] | I want to make google trasnlate script.
I am making a request to translate.google.com and google return an array but the array contains undefined items.You can imagine response comes as string.
I can remove commas if there is more than one consecutive with regex etc. but I am looking best solution :)
How can I convert... | ## JavaScript part - encoding
In Javascript you do:
```
var arr = ["a","b",,,"e"];
var json_string = JSON.stringify(arr);
```
then you somehow pass `json_string` (now equal to "`["a","b",null,null,"e"]`" string) from JavaScript to Python.
## Python part - decoding
Then, on Python side do:
```
json_string = '["a",... |
Heroku deployment of Django app unsuccessful | 10,643,447 | 2 | 2012-05-17T21:00:50Z | 10,647,421 | 7 | 2012-05-18T05:56:23Z | [
"python",
"django",
"heroku"
] | I am trying to deploy a Django app to Heroku but I get this strange error when i run the following command.
Any idea why this happens? I've googled it but I found nothing that would help.
```
root@ubuntu:~/Desktop/djangos/jobs# git push heroku master
Warning: Permanently added the RSA host key for IP address '50.19.8... | I had same problem , Add your ssh key to heroku by `$ heroku keys:add` .
check out my blogpost <http://www.codesucksmybrain.blogspot.com/2012/04/deploy-django-app-on-heroku-platform.html> |
Randomly Interleave 2 Arrays In Python | 10,644,925 | 12 | 2012-05-17T23:42:14Z | 10,645,044 | 13 | 2012-05-17T23:57:36Z | [
"python",
"arrays",
"random"
] | Suppose I have two arrays:
```
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
```
I want to interleave these two arrays to a variable 'c' (note 'a' and 'b' aren't necessarily of equal length) but I don't want them interleaved in a deterministic way. In short, it isn't enough to just zip these two arrays. I don't want:
```
c =... | **edit:** I think this recent one is best:
```
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = [x.pop(0) for x in random.sample([a]*len(a) + [b]*len(b), len(a)+len(b))]
```
Or more efficiently:
```
c = map(next, random.sample([iter(a)]*len(a) + [iter(b)]*len(b), len(a)+len(b)))
```
Note that the first method above modifie... |
Randomly Interleave 2 Arrays In Python | 10,644,925 | 12 | 2012-05-17T23:42:14Z | 10,645,233 | 9 | 2012-05-18T00:27:30Z | [
"python",
"arrays",
"random"
] | Suppose I have two arrays:
```
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
```
I want to interleave these two arrays to a variable 'c' (note 'a' and 'b' aren't necessarily of equal length) but I don't want them interleaved in a deterministic way. In short, it isn't enough to just zip these two arrays. I don't want:
```
c =... | **Edited to remove superfluous clutter:** Here's a solution that works on any number of input lists, doesn't trash the input lists and doesn't copy them either:
```
import random
def interleave(*args):
iters = [i for i, b in ((iter(a), a) for a in args) for _ in xrange(len(b))]
random.shuffle(iters)
retur... |
Emacs python-mode | 10,645,401 | 8 | 2012-05-18T00:53:47Z | 10,645,653 | 8 | 2012-05-18T01:36:45Z | [
"python",
"emacs",
"configure",
"python-mode"
] | I'm trying to configure Emacs23.2 to work with python2.7.3, using the package [python-mode.el-6.0.7](http://launchpad.net/python-mode)
After adding to my *.emacs* file these LISP lines, as indicated in the INSTALL instructions,...
```
(add-to-list 'load-path "PATH/TO/PYTHON-MODE/")
(setq py-install-directory "PATH/T... | (I imagine someone will provide a better answer, but...)
The documentation for Python support on the EmacsWiki used to be pretty messy, in part because there were two different major modes to choose from, and information for each was all mixed into the same page.
It's clearly been cleaned up a great deal since I firs... |
unbound method with instance as first argument got string but requires something else | 10,645,444 | 9 | 2012-05-18T01:01:14Z | 10,645,564 | 9 | 2012-05-18T01:20:23Z | [
"python"
] | ```
#Maps.py
class Maps(object):
def __init__(self):
self.animals = []
self.currently_occupied = {}
def add_animal(self, name):
self.animals.append(name)
self.currently_occupied = {robot:[0, 0]}
#animal.py
class Animal(object):
def __init__(self, name):
import m... | You need an instance of Maps, not the Maps class:
```
maps.Maps.add_animal("Fred") # gives error
mymap = maps.Map()
mymap.add_animal("Fred") # should work
```
So you should either have a mymap attribute on the Animal class, per Animal instance or as a global object (whatever works best for your case). |
How would someone SQL inject this? | 10,645,454 | 4 | 2012-05-18T01:02:58Z | 10,645,489 | 9 | 2012-05-18T01:07:31Z | [
"python",
"mysql",
"sql"
] | I have been told the following is insecure:
```
cursor.execute("""SELECT currency FROM exchange_rates WHERE date='%s'"""%(self.date))
```
Why exactly is the `'%s'` bad? How would someone actually do a SQL injection here? | Imagine if `self.date` is `"'; DROP TABLE exchange_rates --"`. Then you'll execute:
`SELECT currency FROM exchange_rates WHERE date=''; DROP TABLE exchange_rates -- '`
and boom, you're hosed. You have to escape the `'` so the value of `self.date` will be completely contained in the string, not executed as a query. |
How do I remove the last n characters from a string? | 10,645,959 | 3 | 2012-05-18T02:22:36Z | 10,645,972 | 20 | 2012-05-18T02:24:14Z | [
"python"
] | If I have a string and want to remove the last 4 characters of it, how do I do that?
So if I want to remove `.bmp` from `Forest.bmp` to make it just `Forest`
How do I do that? Thanks. | Two solutions here.
To remove the last 4 characters in general:
```
s = 'this is a string1234'
s = s[:-4]
```
yields
```
'this is a string'
```
And more specifically geared toward filenames, consider [os.path.splitext()](http://docs.python.org/library/os.path.html?highlight=splitext#os.path.splitext) meant for sp... |
Custom sort python | 10,645,986 | 5 | 2012-05-18T02:25:57Z | 10,646,263 | 10 | 2012-05-18T03:16:51Z | [
"python",
"sorting"
] | I have a question:
This is list of lists, formed by ElementTree library.
```
[['word1', <Element tag at b719a4cc>], ['word2', <Element tag at b719a6cc>], ['word3', <Element tag at b719a78c>], ['word4', <Element tag at b719a82c>]]
```
word1..4 may contain unicode characters i.e (â,ü,ç).
**I want to sort this li... | Your first link more or less solves the problem. You just need to have the lambda function only look at the first item in your list:
```
alphabet = "zyxwvutsrqpomnlkjihgfedcba"
new_list = sorted(inputList, key=lambda word: [alphabet.index(c) for c in word[0]])
```
One modification I might suggest, if you're sorting ... |
How do you merge images into a canvas using PIL/Pillow? | 10,647,311 | 29 | 2012-05-18T05:45:59Z | 10,649,311 | 54 | 2012-05-18T08:35:42Z | [
"python",
"image",
"canvas",
"python-imaging-library",
"pillow"
] | I'm not familiar with PIL, but I know it's very easy to put a bunch of images into a grid in ImageMagick.
How do I, for example, put 16 images into a 4×4 grid where I can specify the gap between rows and columns? | This is easy to do in `PIL` too. Create an empty image and just paste in the images you want at whatever positions you need using [paste](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.paste). Here's a quick example:
```
import Image
#opens an image:
im = Image.open("1_tree.jpg")
#create... |
Python -- import the package in a module that is inside the same package | 10,647,729 | 10 | 2012-05-18T06:25:11Z | 10,648,065 | 12 | 2012-05-18T06:57:50Z | [
"python"
] | I have a project structure something like this...
```
/some_app
build/
README
out.py
some_app/
__init__.py
mod1.py
mod2.py
```
Now I want to import `some_app` package into `mod2`, without messing with `sys.path` trickery. What I simply did is...
```
# mod2.py
import some_app
`... | `mod2.py` is part of `some_app`. As such, it makes no sense to import the module, since you're already inside it.
You can still `import mod1`. I'm assuming you need `some_app/__init__.py` to run. Not sure that's possible.
---
### EDIT:
Looks like `from . import some_module` will do what you're after. |
Uploading Python third party libraries | 10,648,256 | 4 | 2012-05-18T07:12:59Z | 10,650,995 | 11 | 2012-05-18T10:33:21Z | [
"python",
"google-app-engine"
] | Google App engine documentation states that it is possible to upload and use third party libraries provided they written in pure Python.
What are the steps I need to take to do this? | What I did is created a file called fix\_path.py in my root directory that looks like this:
```
import os
import sys
import jinja2
# path to lib direcotory
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))
```
Then I created a lib directory, and drop the module in there.
For example, I use WTForm... |
Interleaving multiple iterables randomly while preserving their order in python | 10,648,331 | 8 | 2012-05-18T07:19:26Z | 10,648,439 | 9 | 2012-05-18T07:27:36Z | [
"python"
] | Inspired by [this earlier stack overflow question](http://stackoverflow.com/questions/10644925/randomly-interleave-2-arrays-in-python) I have been considering how to randomly interleave iterables in python while preserving the order of elements within each iterable. For example:
```
>>> def interleave(*iterables):
...... | Here is one way to do it using a generator:
```
import random
def interleave(*args):
iters = map(iter, args)
while iters:
it = random.choice(iters)
try:
yield next(it)
except StopIteration:
iters.remove(it)
print list(interleave(xrange(1, 5), xrange(5, 10), xrange(10, 15)))
``` |
Removing first appearance of word from a string? | 10,648,490 | 6 | 2012-05-18T07:31:09Z | 10,648,554 | 16 | 2012-05-18T07:35:52Z | [
"python",
"regex"
] | I'm not familiar with regex, and it would be great if someone giving a solution using regex could explain their syntax so I can apply it to future situations.
I have a string (ie. `'Description: Mary had a little lamb'`), and I would like to remove `'Description: '` such that the string would read `'Mary had a little ... | Python's [str.replace](http://docs.python.org/library/string.html#string.replace) has a max replace argument. So, in your case, do this:
```
>>>mystring = "Description: Mary had a little lamb Description: "
>>>print mystring.replace("Description: ","",1)
"Mary had a little lamb Description: "
```
Using regex is basi... |
Dump in PyYaml as utf-8 | 10,648,614 | 5 | 2012-05-18T07:40:30Z | 10,656,291 | 10 | 2012-05-18T16:22:30Z | [
"python",
"utf-8",
"pyyaml"
] | I'm trying to load a bunch of utf-8 encoded strings and dump them again with PyYaml. This is the code for loading/dumping:
```
lang_yml = yaml.load(codecs.open(lang + ".yml.old", "r", "utf-8"))
test_file_path = lang + '.yml'
stream = file(test_file_path, 'w')
yaml.dump(lang_yml, stream, default_flow_style=False, enco... | Found the answer myself. I just had to dump it with the argument
```
allow_unicode=True
```
Source: <http://dpinte.wordpress.com/2008/10/31/pyaml-dump-option/> |
Executing Javascript Submit form functions using scrapy in python | 10,648,644 | 5 | 2012-05-18T07:42:20Z | 10,651,243 | 7 | 2012-05-18T10:49:31Z | [
"python",
"scrapy"
] | I am scrapping a site using scrapy framework and having trouble clicking on a javascript link for opening another page.
I can identify the code on the page as:
```
<a class="Page" alt="Click to view job description" title="Click to view job description" href="javascript:sysSubmitForm('frmSR1');">Accountant </a>
... | Checkout the below snipped on how to use scrapy with selenium. Crawling will be slower as you aren't just downloading the html but you will get full access to the DOM.
Note: I have copy-pasted this snippet as the links previously provided no longer work.
```
# Snippet imported from snippets.scrapy.org (which no longe... |
PEP 8: How should __future__ imports be grouped? | 10,649,145 | 9 | 2012-05-18T08:19:32Z | 10,649,225 | 10 | 2012-05-18T08:26:07Z | [
"python",
"coding-style",
"python-import",
"pep8"
] | According to [PEP 8](https://www.python.org/dev/peps/pep-0008/#imports):
> Imports should be grouped in the following order:
>
> 1. standard library imports
> 2. related third party imports
> 3. local application/library specific imports
>
> You should put a blank line between each group of imports.
But it does not m... | I personally separate them. A `__future__` import isn't just binding a name like other imports, it changes the meaning of the language. With things like `from __future__ import division` the module will likely run fine both with and without the import, but give different (wrong) results at places that have nothing tell... |
How to generate a fully connected subgraph from node list using python's networkx module | 10,649,673 | 9 | 2012-05-18T09:02:02Z | 10,651,524 | 9 | 2012-05-18T11:09:49Z | [
"python",
"networkx"
] | I need to generate a fully connected subgraph with [networkx](http://networkx.lanl.gov/), starting from the list of nodes I want to connect. Basically, I want all the nodes in the list I pass to the function to be all connected with each other.
I wonder if there is any built-in function to achieve this (which I haven'... | I don't know of any method which does this, but you can easily mimic the complete\_graph() method of networkx and slightly change it(almost like a builtin):
```
import networkx
import itertools
def complete_graph_from_list(L, create_using=None):
G = networkx.empty_graph(len(L),create_using)
if len(L)>1:
... |
Python Flask + nginx fcgi - output large response? | 10,650,537 | 6 | 2012-05-18T10:00:36Z | 10,652,246 | 10 | 2012-05-18T11:58:26Z | [
"python",
"http",
"web",
"flask"
] | I'm using Python Flask + nginx with FCGI.
On some requests, I have to output large responses. Usually those responses are fetched from a socket. Currently I'm doing the response like this:
```
response = []
while True:
recv = s.recv(1024)
if not recv: break
response.append(recv)
s.close()
response = ''.jo... | if `response` in `flask.make_response` is an iterable, it will be iterated over to produce the response, and each string is written to the output stream on it's own.
what this means is that you can also return a generator which will yield the output when iterated over. if you know the content length, then you can (and... |
Python: Calculate Voronoi Tesselation from Scipy's Delaunay Triangulation in 3D | 10,650,645 | 13 | 2012-05-18T10:08:15Z | 10,657,011 | 16 | 2012-05-18T17:18:09Z | [
"python",
"3d",
"scipy",
"delaunay",
"voronoi"
] | I have about 50,000 data points in 3D on which I have run scipy.spatial.Delaunay from the new scipy (I'm using 0.10) which gives me a very useful triangulation.
Based on: <http://en.wikipedia.org/wiki/Delaunay_triangulation> (section "Relationship with the Voronoi diagram")
...I was wondering if there is an easy way ... | The adjacency information can be found in the `neighbors` attribute of the Delaunay object. Unfortunately, the code does not expose the circumcenters to the user at the moment, so you'll have to recompute those yourself.
Also, the Voronoi edges that extend to infinity are not directly obtained in this way. It's still ... |
Python: Calculate Voronoi Tesselation from Scipy's Delaunay Triangulation in 3D | 10,650,645 | 13 | 2012-05-18T10:08:15Z | 15,783,581 | 7 | 2013-04-03T09:27:58Z | [
"python",
"3d",
"scipy",
"delaunay",
"voronoi"
] | I have about 50,000 data points in 3D on which I have run scipy.spatial.Delaunay from the new scipy (I'm using 0.10) which gives me a very useful triangulation.
Based on: <http://en.wikipedia.org/wiki/Delaunay_triangulation> (section "Relationship with the Voronoi diagram")
...I was wondering if there is an easy way ... | I came across the same problem and built a solution out of pv.'s answer and other code snippets I found across the web. The solution returns a complete Voronoi diagram, including the outer lines where no triangle neighbours are present.
```
#!/usr/bin/env python
import numpy as np
import matplotlib
import matplotlib.p... |
How to quiet SimpleHTTPServer? | 10,651,052 | 8 | 2012-05-18T10:38:27Z | 10,651,234 | 10 | 2012-05-18T10:48:52Z | [
"python",
"simplehttpserver"
] | I have the following simple Threaded fileserver to be used by my application:
```
class FileServer(Thread):
"""Simple file server exposing the current directory for the thumbnail
creator
"""
def __init__(self, port):
Thread.__init__(self)
self.port = port
Handler = SimpleHTTPS... | Run it this way in bash:
```
python -m SimpleHTTPServer > /dev/null 2>&1
``` |
How to quiet SimpleHTTPServer? | 10,651,052 | 8 | 2012-05-18T10:38:27Z | 10,651,257 | 21 | 2012-05-18T10:50:39Z | [
"python",
"simplehttpserver"
] | I have the following simple Threaded fileserver to be used by my application:
```
class FileServer(Thread):
"""Simple file server exposing the current directory for the thumbnail
creator
"""
def __init__(self, port):
Thread.__init__(self)
self.port = port
Handler = SimpleHTTPS... | You can subclass `SimpleHTTPServer.SimpleHTTPRequestHandler` and override the `log_message` method. Here is the method you will be overriding, sans docstring:
```
def log_message(self, format, *args):
sys.stderr.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_... |
Simulating the passing of time in unittesting | 10,652,097 | 16 | 2012-05-18T11:48:38Z | 10,652,680 | 15 | 2012-05-18T12:29:12Z | [
"python",
"testing",
"mocking",
"integration-testing",
"celery"
] | I've built a paywalled CMS + invoicing system for a client and I need to get more stringent with my testing.
I keep all my data in a Django ORM and have a bunch of Celery tasks that run at different intervals that makes sure that new invoices and invoice reminders get sent and cuts of access when users don't pay their... | You can use [mock](http://www.voidspace.org.uk/python/mock/) to change the return value of the function you use to get the time (`datetime.datetime.now` for example).
There are various ways to do so (see the mock documentation), but here is one :
```
import unittest
import datetime
from mock import patch
class SomeT... |
django 1.4 - can't compare offset-naive and offset-aware datetimes | 10,652,819 | 73 | 2012-05-18T12:39:51Z | 10,653,144 | 146 | 2012-05-18T13:01:09Z | [
"python",
"django",
"timezone"
] | I am in the process of migrating an application from django 1.2 To 1.4.
I have a daily task object which contains a time of day that task should be completed:
```
class DailyTask(models.Model):
time = models.TimeField()
last_completed = models.DateTimeField()
name = models.CharField(max_length=100)
de... | Check [the thorough document](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/) for detail info.
Normally, use `django.utils.timezone.now` to make an offset-aware current datetime
```
>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2012, 5, 18, 13, 0, 49, 803031, tzinfo=<UTC>)
`... |
PyQt connect SIGNAL to multiple SLOT | 10,653,704 | 3 | 2012-05-18T13:37:25Z | 10,653,995 | 8 | 2012-05-18T13:56:09Z | [
"python",
"qt",
"pyqt4"
] | I am trying to learn `PyQt` from `rapid gui programming with python and qt` and currently learning `Signals` and `Slots`.
Below is a short snippet of my code:
```
self.connect(self.dial, SIGNAL("valueChanged(int)"),self.spinbox.setValue) #1
self.connect(self.dial, SIGNAL("valueChanged(int)"),self.getValue_dial) #2... | The way you're doing it is fine. If you had quite a few things to do you could connect to a new function that handles everything for you.
I notice in your connected `getValue` functions you're getting the value straight from the object; are you aware that the value is passed as a parameter with the `valueChanged(int)`... |
ipython notebook --pylab inline: zooming of a plot | 10,655,217 | 30 | 2012-05-18T15:13:07Z | 10,660,806 | 11 | 2012-05-18T23:06:11Z | [
"python",
"matplotlib",
"ipython"
] | Is it possible to zoom into a plot if inline is activated? Especially regarding to 3d-plots rotating and zooming is a necessary feature. | At present, the closest you can come is to redraw it at a larger size using the `figsize` function. It expects dimensions in inches, which caught me out the first time I tried to use it.
There are some plants for a rich backend that would allow plots to be manipulated live, using HTML5, but I think it will be a few mo... |
ipython notebook --pylab inline: zooming of a plot | 10,655,217 | 30 | 2012-05-18T15:13:07Z | 22,949,003 | 36 | 2014-04-08T21:57:26Z | [
"python",
"matplotlib",
"ipython"
] | Is it possible to zoom into a plot if inline is activated? Especially regarding to 3d-plots rotating and zooming is a necessary feature. | Now thanks to [mpld3](http://mpld3.github.io/) it's super easy to enable zooming in inline plots!
All you have to do is install mpld3 (`pip install mpld3`), and then add this to your notebook:
```
%matplotlib inline
import mpld3
mpld3.enable_notebook()
```
Now your plots will get a toolbar menu at the bottom left, i... |
python remove all whitespace from entries in a list | 10,656,607 | 4 | 2012-05-18T16:45:14Z | 10,656,686 | 11 | 2012-05-18T16:51:39Z | [
"python",
"string",
"list"
] | while calling `readlines()` on a .srt file , I got a list of characters with lots of leading and trailing whitespace like below
```
with open(infile) as f:
r=f.readlines()
return r
```
I got this list
```
['\xef\xbb\xbf1\r\n', '00:00:00,000 --> 00:00:03,000\r\n', "[D. Evans] Now that you've written your firs... | You can strip each line. Running it as a generator could also save you some memory if you're working on a big file.
Also, looks like you're working on a UTF-8 file with a BOM (which is sort of silly, or at least unnecessary) for the first several characters, so you need to open it differently.
```
import codecs
def ... |
redis + gevent - Poor performance - what am I doing wrong? | 10,656,953 | 16 | 2012-05-18T17:13:26Z | 10,663,498 | 43 | 2012-05-19T08:08:20Z | [
"python",
"performance",
"redis",
"gevent"
] | I just wrote a simple piece of code to perf test Redis + gevent to see how async helps perforamance and I was surprised to find bad performance. here is my code. If you get rid of the first two lines to monkey patch this code then you will see the "normal execution" timing.
On a Ubuntu 12.04 LTS VM, I am seeing a timi... | This is expected.
You run this benchmark on a VM, on which the cost of system calls is higher than on physical hardware. When gevent is activated, it tends to generate more system calls (to handle the epoll device), so you end up with less performance.
You can easily check this point by using strace on the script.
W... |
Installing PIL on OS X Lion | 10,657,363 | 5 | 2012-05-18T17:45:10Z | 10,659,028 | 9 | 2012-05-18T20:05:05Z | [
"python",
"osx-lion",
"python-imaging-library"
] | I am trying to install PIL on **Mac OSX 10.7.4** but after several hours attempt couldn't succeed. All the time I have encountered the same problem provided detail in pastebin link below. Enlighten me!!
## Setting
```
tbc:~ mystic$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
```
[**Past... | If you are on Lion, using the newest XCode, then a potential problem for you is that they moved the location of the developer SDKs. Packages that expected them to live in `/Developer/` would no longer find them as needed.
Reference this article about specifics:
<http://www.agile-workers.com/web/2012/03/qt-qmake-osx_... |
Stitching Photos together | 10,657,383 | 7 | 2012-05-18T17:46:56Z | 10,657,449 | 13 | 2012-05-18T17:52:39Z | [
"python",
"image-processing"
] | So for this project I'm working on, I have 2 photos. These two photos need to be stitched together, one on the top and one on the bottom, and then you will be able to see the whole picture. Any ideas on what module I should use to do this? | The [python imaging library](http://www.pythonware.com/products/pil/) will eat that task for breakfast.
See the [tutorial](https://pillow.readthedocs.org/en/latest/handbook/tutorial.html) in particular the "Cutting, Pasting and Merging Images" section for some relevant help.
For rough outline, load both images with `... |
Python evaluation returning False even though individual items are shown as equivalent in interpreter | 10,657,840 | 2 | 2012-05-18T18:24:15Z | 10,657,854 | 9 | 2012-05-18T18:24:57Z | [
"python",
"boolean",
"return"
] | Why does this not work?
```
def straight(ranks):
"Return True if the ordered ranks form a 5-card straight."
return range(max(ranks)-4, max(ranks)+1) == ranks.sort()
```
Assuming ranks is:
```
>>> ranks = [9, 8, 7, 6, 5]
>>> range(max(ranks)-4, max(ranks)+1)
[5, 6, 7, 8, 9]
>>> ranks.sort()
[5, 6, 7, 8, 9]
``... | `s.sort()` returns `None` because it sorts the list in place. Use `sorted(s)`.
```
>>> s = [1,3,2]
>>> repr(s.sort())
'None'
>>> repr(s)
'[1, 2, 3]'
>>> repr(sorted(s))
'[1, 2, 3]'
``` |
Add all values in a CSV column in Python | 10,657,965 | 3 | 2012-05-18T18:33:35Z | 10,658,044 | 8 | 2012-05-18T18:40:03Z | [
"python",
"csv"
] | These seems like something very simple, but search as I might I just can't get past it.
I have a CSV file like this:
```
Day,Event,Value
1,"Rent",500
7,"Wage Payments",1000
```
I wish to add up all of the numbers in the 'value' column. So far, my code is this:
```
cr = csv.reader(open("file.csv","rb"))
for row in ... | Considering the first line of `csv` file is `'Day,Event,Value'`, you can use a `generator expression` with `sum()`
```
>>> cr = csv.reader(open("file.csv","rb"))
>>> cr.next()
>>> print sum(int(x[2]) for x in cr)
1500
``` |
Selenium python find_element_by_class_name() stopped working from v 2.2 to 2.21 -- cannot use 'Compound Class Name' | 10,658,907 | 7 | 2012-05-18T19:54:35Z | 10,672,847 | 10 | 2012-05-20T11:02:03Z | [
"python",
"selenium",
"webdriver"
] | I am using Selenium's python library to scrape data from a html page in Firefox.
I have had to update from Selenium 2.0 to 2.21 because the server has updated Firefox.
In v 2.21 calls to `find_element_by_class_name("grid-cell-inner grid-col-name")` fails with:
```
selenium.common.exceptions.WebDriverException: Messa... | The problem about WebDriver is that it still evolves. A lot. I personally don't know about a version that supported searching by many classes in one command, so it must have been a fairly old one :).
Searching by a [CSS selector](http://www.w3.org/TR/CSS2/selector.html) should work, however:
```
find_element_by_css_s... |
scala equivalent of python __getattr__ / __setattr__ | 10,658,920 | 2 | 2012-05-18T19:55:53Z | 10,659,900 | 9 | 2012-05-18T21:19:27Z | [
"python",
"scala",
"dynamic",
"properties",
"getter-setter"
] | Is there scala equivalent of python `__getattr__ / __setattr__` (and other `__*__` methods?). Some thing built-in or maybe some traits? | For `__getattr__` and `__setattr__` youâll have to wait until someone with more insight describes the new Scala 2.10 reflection API. (And of course: it wonât be directly translatable ever. It depends completely on your use case. If you just want a dynamic class, there will be a `Dynamic` trait in the future; if you... |
How to create windows installer for pyqt project | 10,659,829 | 5 | 2012-05-18T21:14:05Z | 10,660,263 | 14 | 2012-05-18T22:02:44Z | [
"python",
"qt",
"pyqt4"
] | How can I convert my python program with Qt for GUI to .exe file??
I want to make an installation file for my python source code | **First part : "How can I convert my python program with Qt for GUI to .exe file??"**
You can use PyInstaller, which supports python 2.2 - 2.7 and it has a hook system for including Qt with all dlls and plugins.
You can use also :
* bbfreeze
* cxfreeze
* py2exe (pretty old)
* esky (a wrapper of all the above except ... |
Where to host a Flask + SQLite3 web app? | 10,660,277 | 9 | 2012-05-18T22:03:44Z | 13,932,849 | 11 | 2012-12-18T12:18:36Z | [
"python",
"sql",
"sqlite3",
"hosting",
"flask"
] | I'm trying to host my small personal website online for free, but I can't find a host that supports Python and the use of SQLite3. I've looked at Heroku but using PostgreSQL with Flask (without ORM) is extremely confusing to me. Where can I find a host? | We have a 1-click deploy for flask apps, with full support for sqlite. and there's a free plan:
<http://www.pythonanywhere.com/> |
difference between cursor and connection objects | 10,660,411 | 5 | 2012-05-18T22:16:45Z | 10,660,570 | 9 | 2012-05-18T22:37:36Z | [
"python",
"python-db-api"
] | I am confused about why python needs cursor object. I know jdbc and there the database connection is quite intuitive but in python I am confused with cursor object. Also I am doubtful about what is the difference between cursor.close() and connection.close() function in terms of resource release. | The cursor paradigm is not specific to Python but are a frequent data structure in [databases themselves](http://en.wikipedia.org/wiki/Cursor_%28databases%29).
Depending on the underlying implementation it may be possible to generate several cursors sharing the same connection to a database. Closing the cursor should ... |
Pythonic way to create a long multi-line string | 10,660,435 | 354 | 2012-05-18T22:21:09Z | 10,660,443 | 608 | 2012-05-18T22:22:54Z | [
"string",
"python"
] | I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E... | Are you talking about multi-line strings? Easy, use triple quotes to start and end them.
```
s = """ this is a very
long string if I had the
energy to type more and more ..."""
```
You can use single quotes too (3 of them of course at start and end) and treat the resulting string `s` just like any oth... |
Pythonic way to create a long multi-line string | 10,660,435 | 354 | 2012-05-18T22:21:09Z | 10,660,477 | 58 | 2012-05-18T22:26:35Z | [
"string",
"python"
] | I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E... | If you don't want a multiline string but just have a long single line string, you can use parentheses, just make sure you don't include commas between the string segments, then it will be a tuple.
```
query = ('SELECT action.descr as "action", '
'role.id as role_id,'
'role.descr as role'
'... |
Pythonic way to create a long multi-line string | 10,660,435 | 354 | 2012-05-18T22:21:09Z | 14,155,520 | 22 | 2013-01-04T10:39:29Z | [
"string",
"python"
] | I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E... | I found myself happy with this one:
```
string = """This is a
very long string,
containing commas,
that I split up
for readability""".replace('\n',' ')
``` |
Pythonic way to create a long multi-line string | 10,660,435 | 354 | 2012-05-18T22:21:09Z | 24,300,699 | 17 | 2014-06-19T07:06:24Z | [
"string",
"python"
] | I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E... | I find that when building long strings, you are usually doing something like building an SQL query, in which case this is best:
```
query = ' '.join(( # note double parens, join() takes an iterable
"SELECT foo",
"FROM bar",
"WHERE baz",
))
```
What Levon suggested is good, but might be vulnerable to mist... |
Pythonic way to create a long multi-line string | 10,660,435 | 354 | 2012-05-18T22:21:09Z | 24,331,604 | 47 | 2014-06-20T16:16:55Z | [
"string",
"python"
] | I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E... | Breaking lines by `\` works for me. Here is an example:
```
longStr = "This is a very long string " \
"that I wrote to help somebody " \
"who had a question about " \
"writing long strings in Python"
``` |
Pythonic way to create a long multi-line string | 10,660,435 | 354 | 2012-05-18T22:21:09Z | 32,980,897 | 8 | 2015-10-06T22:33:07Z | [
"string",
"python"
] | I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). E... | You can also concatenate variables in when using """ notation:
```
foo = '1234'
long_string = """fosdl a sdlfklaskdf as
as df ajsdfj asdfa sld
a sdf alsdfl alsdfl """ + foo + """ aks
asdkfkasdk fak"""
```
EDIT: Found a better way, with named params and .format():
```
body = """
<html>
<head>
</head>
<body>
<p>... |
Why does shell=True eat my subprocess.Popen stdout? | 10,661,457 | 8 | 2012-05-19T00:55:52Z | 10,661,488 | 13 | 2012-05-19T01:03:18Z | [
"python",
"subprocess",
"pipe",
"popen"
] | It seems that using shell=True in the first process of a chain somehow drops the stdout from downstream tasks:
```
p1 = Popen(['echo','hello'], stdout=PIPE)
p2 = Popen('cat', stdin=p1.stdout, stdout=PIPE)
p2.communicate()
# outputs correctly ('hello\n', None)
```
Making the first process use shell=True kills the outp... | When you pass `shell=True`, Popen expects a single string argument, not a list. So when you do this:
```
p1 = Popen(['echo','hello'], stdout=PIPE, shell=True)
```
What happens is this:
```
execve("/bin/sh", ["/bin/sh", "-c", "echo", "hello"], ...)
```
That is, it calls `sh -c "echo"`, and `hello` is effectively ign... |
Use Python format string in reverse for parsing | 10,663,093 | 12 | 2012-05-19T07:01:15Z | 10,665,138 | 8 | 2012-05-19T12:22:44Z | [
"python"
] | I've been using the following python code to format an integer part ID as a formatted part number string:
```
pn = 'PN-{:0>9}'.format(id)
```
I would like to know if there is a way to use that same format string (`'PN-{:0>9}'`) in reverse to extract the integer ID from the formatted part number. If that can't be done... | You might find [simulating scanf](http://docs.python.org/library/re.html#simulating-scanf) interresting. |
Use Python format string in reverse for parsing | 10,663,093 | 12 | 2012-05-19T07:01:15Z | 18,620,969 | 11 | 2013-09-04T18:12:36Z | [
"python"
] | I've been using the following python code to format an integer part ID as a formatted part number string:
```
pn = 'PN-{:0>9}'.format(id)
```
I would like to know if there is a way to use that same format string (`'PN-{:0>9}'`) in reverse to extract the integer ID from the formatted part number. If that can't be done... | The [parse module](https://github.com/r1chardj0n3s/parse) "is the opposite of format()".
Example usage:
```
>>> format = 'PN-{:0>9}'
>>> format_string = 'PN-{:0>9}'
>>> import parse
>>> format_string = 'PN-{:0>9}'
>>> id = 123
>>> pn = format_string.format(id)
>>> pn
'PN-000000123'
>>> parsed = parse.parse(format_str... |
converting a time string to seconds in python | 10,663,720 | 18 | 2012-05-19T08:43:57Z | 10,663,851 | 21 | 2012-05-19T09:07:29Z | [
"python",
"time"
] | I need to convert time value strings given in the following format to seconds.I am using `python2.6`
eg:
```
1.'00:00:00,000' -> 0 seconds
2.'00:00:10,000' -> 10 seconds
3.'00:01:04,000' -> 64 seconds
4. '01:01:09,000' -> 3669 seconds
```
Do I need to use regex to do this ?I tried to use time module,but `time.s... | For Python 2.7:
```
>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0
``` |
converting a time string to seconds in python | 10,663,720 | 18 | 2012-05-19T08:43:57Z | 12,739,542 | 17 | 2012-10-05T04:34:55Z | [
"python",
"time"
] | I need to convert time value strings given in the following format to seconds.I am using `python2.6`
eg:
```
1.'00:00:00,000' -> 0 seconds
2.'00:00:10,000' -> 10 seconds
3.'00:01:04,000' -> 64 seconds
4. '01:01:09,000' -> 3669 seconds
```
Do I need to use regex to do this ?I tried to use time module,but `time.s... | A little more pythonic way I think would be:
```
timestr = '00:04:23'
ftr = [3600,60,1]
sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])
```
Output is 263Sec.
I would be interested to see if anyone could simplify it further. |
Is it possible to use Python to write cross-platform apps for both iOS and Android? | 10,664,196 | 50 | 2012-05-19T10:05:52Z | 10,664,207 | 19 | 2012-05-19T10:07:35Z | [
"android",
"python",
"ios",
"cross-platform"
] | Is it possible to use Python to write cross-platform apps for both iOS and Android | For Android Google provides something called ASE (Android Scripting Environment) which allows scripting languages (Python included) to run on Android. More details [here](http://google-opensource.blogspot.com/2009/06/introducing-android-scripting.html)
For iOS, it might be quite a bit more complicated (and I'd advise ... |
Is it possible to use Python to write cross-platform apps for both iOS and Android? | 10,664,196 | 50 | 2012-05-19T10:05:52Z | 11,000,596 | 58 | 2012-06-12T16:14:41Z | [
"android",
"python",
"ios",
"cross-platform"
] | Is it possible to use Python to write cross-platform apps for both iOS and Android | An option is [kivy](http://kivy.org): a cool cross platform Python framework which works for Android, Win7, Linux, MacOSX and iOS.
Update: kivy project is growing daily, now supports also Raspberry Pi |
Django: How to manage development and production settings? | 10,664,244 | 41 | 2012-05-19T10:12:34Z | 10,664,326 | 9 | 2012-05-19T10:24:31Z | [
"python",
"django"
] | I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.
It would be great to know the following:
* How best to deal with development and production settings.
* How to keep apps such as django-debug-toolbar only in a development... | Create multiple `settings*.py` files, extrapolating the variables that need to change per environment. Then at the end of your master `settings.py` file:
```
try:
from settings_dev import *
except ImportError:
pass
```
You keep the separate `settings_*` files for each stage.
At the top of your `settings_dev.py` ... |
Django: How to manage development and production settings? | 10,664,244 | 41 | 2012-05-19T10:12:34Z | 10,664,412 | 47 | 2012-05-19T10:36:40Z | [
"python",
"django"
] | I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.
It would be great to know the following:
* How best to deal with development and production settings.
* How to keep apps such as django-debug-toolbar only in a development... | My favorite way of doing this is to use the `DJANGO_SETTINGS_MODULE` environment variable and use two (or more) settings files, e.g. `production_settings.py` and `test_settings.py`.
You can then use a bootstrap script or a process manager to load the correct settings (by setting the environment). If you're using a vir... |
Django: How to manage development and production settings? | 10,664,244 | 41 | 2012-05-19T10:12:34Z | 10,664,795 | 18 | 2012-05-19T11:28:31Z | [
"python",
"django"
] | I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.
It would be great to know the following:
* How best to deal with development and production settings.
* How to keep apps such as django-debug-toolbar only in a development... | I usually have one settings file per environment, and a shared settings file:
```
/myproject/
settings.production.py
settings.development.py
shared_settings.py
```
Each of my environment files has:
```
try:
from shared_settings import *
except ImportError:
pass
```
This allows me to override shared se... |
How to get a python .pyd for Windows from c/c++ source code? (update: brisk now in Python in case that's what you want) | 10,664,658 | 9 | 2012-05-19T11:10:41Z | 10,917,622 | 10 | 2012-06-06T15:46:13Z | [
"c++",
"python",
"c",
"opencv"
] | # How to get from C/C++ extension source code to a pyd file for windows (or other item that I could import to Python)?
***edit:*** The specific library that I wanted to use (BRISK) was included in [OpenCV](http://opencv.org/) 2.4.3 so my need for this skill went away for the time being. In case you came here looking f... | Are you sure that this brisk library even exports python bindings? I can't see any reference to it in the source code - it doesn't even seem to import python header files. This would certainly explain why you've not had much success so far - you can't just compile plain C++ code and expect python to interface with it.
... |
make dictionary with duplicate keys in python | 10,664,856 | 17 | 2012-05-19T11:37:28Z | 10,664,876 | 47 | 2012-05-19T11:41:15Z | [
"python"
] | I have the following list which contains duplicate car registration numbers with different values. I want to convert it into a dictionary which accepts this multiple keys of car registration numbers. So far when I try to convert list to dictionary it eliminates one of the keys. Can someone show me how to make dictionar... | Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.
One easy way to achieve this is by using [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict):
```
from collections import defaultdict
data_dict = defaultdict(list)
``... |
make dictionary with duplicate keys in python | 10,664,856 | 17 | 2012-05-19T11:37:28Z | 10,665,285 | 21 | 2012-05-19T12:42:38Z | [
"python"
] | I have the following list which contains duplicate car registration numbers with different values. I want to convert it into a dictionary which accepts this multiple keys of car registration numbers. So far when I try to convert list to dictionary it eliminates one of the keys. Can someone show me how to make dictionar... | You can change the behavior of the built in types in python. For your case it's really easy to create dict subclass that will store duplicated values in lists under the same key automatically:
```
class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
... |
Draw rectangle (add_patch) in pylab mode | 10,665,163 | 9 | 2012-05-19T12:26:59Z | 10,665,448 | 16 | 2012-05-19T13:05:43Z | [
"python",
"matplotlib"
] | I'm using IPython in pylab mode (all functions at fingertip), and wanted to annotate certain plot, lets say `plot([1,3,2])` with rectangle `Rectangle((1,1),1,1)`
How can I draw a simple rectangle in this pylab mode, that is without using figure, axes, subplots... but reference just created plot in easiest possible way | > in this pylab mode, that is without using figure, axes, subplots
Figues, axes, and subplots exist in the pylab framework too. If I were using the pylab interface, I'd simply throw a `subplot(111)` in there and then use `sp.add_patch(Rectangle(etc))`. But you can also grab the current axes/figure using `gca()` and `g... |
Websocket/event-source/... implementation to expose a two-way RPC to a python/django application | 10,665,569 | 3 | 2012-05-19T13:27:51Z | 10,724,512 | 7 | 2012-05-23T16:55:29Z | [
"python",
"django",
"websocket",
"rpc"
] | for a django application I'm working on, I need to implement a two ways RPC so :
* the clients can call RPC methods from the platform and
* the platform can call RPC methods from each client.
As the clients will mostly be behind NATs (which means no public IPs, and unpredictable weird firewalling policies), the platf... | websocket is a moving target, with new specifications from time to time. Brave developpers implements server side library, but few implements client side. The client for web socket is a web browser.
websocket is not the only way for a server to talk to a client, [event source](http://dev.w3.org/html5/eventsource/) is ... |
How to take column-slices of dataframe in pandas | 10,665,889 | 81 | 2012-05-19T14:11:42Z | 10,666,301 | 18 | 2012-05-19T15:02:43Z | [
"python",
"numpy",
"pandas",
"slice"
] | I load a some machine learning data from a csv file. The first 2 columns are observations and the remaining columns are features.
Currently, I do the following :
```
data = pandas.read_csv('mydata.csv')
```
which gives something like:
```
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
```
I... | You can slice along the columns of a `DataFrame` by referring to the names of each column in a list, like so:
```
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
data_ab = data[list('ab')]
data_cde = data[list('cde')]
``` |
How to take column-slices of dataframe in pandas | 10,665,889 | 81 | 2012-05-19T14:11:42Z | 10,677,896 | 102 | 2012-05-20T22:51:30Z | [
"python",
"numpy",
"pandas",
"slice"
] | I load a some machine learning data from a csv file. The first 2 columns are observations and the remaining columns are features.
Currently, I do the following :
```
data = pandas.read_csv('mydata.csv')
```
which gives something like:
```
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
```
I... | The DataFrame.ix index is what you want to be accessing. It's a little confusing (I agree that Pandas indexing is perplexing at times!), but the following seems to do what you want:
```
>>> df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df.ix[:,'b':]
b c d e
0 0.418762 ... |
How to take column-slices of dataframe in pandas | 10,665,889 | 81 | 2012-05-19T14:11:42Z | 22,018,873 | 25 | 2014-02-25T15:33:29Z | [
"python",
"numpy",
"pandas",
"slice"
] | I load a some machine learning data from a csv file. The first 2 columns are observations and the remaining columns are features.
Currently, I do the following :
```
data = pandas.read_csv('mydata.csv')
```
which gives something like:
```
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
```
I... | Also, Given a DataFrame
> data
as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:
``... |
How to take column-slices of dataframe in pandas | 10,665,889 | 81 | 2012-05-19T14:11:42Z | 26,320,276 | 9 | 2014-10-11T23:21:52Z | [
"python",
"numpy",
"pandas",
"slice"
] | I load a some machine learning data from a csv file. The first 2 columns are observations and the remaining columns are features.
Currently, I do the following :
```
data = pandas.read_csv('mydata.csv')
```
which gives something like:
```
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
```
I... | And if you came here looking for slicing two ranges of columns and combining them together (like me) you can do something like
```
op = df[list(df.columns[0:899]) + list(df.columns[3593:])]
print op
```
This will create a new dataframe with first 900 columns and (all) columns > 3593 (assuming you have some 4000 colum... |
How to take column-slices of dataframe in pandas | 10,665,889 | 81 | 2012-05-19T14:11:42Z | 33,997,632 | 13 | 2015-11-30T11:32:15Z | [
"python",
"numpy",
"pandas",
"slice"
] | I load a some machine learning data from a csv file. The first 2 columns are observations and the remaining columns are features.
Currently, I do the following :
```
data = pandas.read_csv('mydata.csv')
```
which gives something like:
```
data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
```
I... | Lets use the titanic dataset from the seaborn package as an example
```
# Load dataset (pip install seaborn)
>> import seaborn.apionly as sns
>> titanic = sns.load_dataset('titanic')
```
> # using the column names
```
>> titanic.loc[:,['sex','age','fare']]
```
> # using the column indices
```
>> titanic.iloc[:,[2,... |
How to check if all elements of a list matches a condition? | 10,666,163 | 53 | 2012-05-19T14:45:37Z | 10,666,320 | 123 | 2012-05-19T15:04:53Z | [
"python",
"list",
"for-loop",
"while-loop"
] | I have a list consisting of like 20000 lists. I use each list's 3rd element as a flag. I want to do some operations on this list as long as at least one element's flag is 0, it's like:
```
my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....]
```
In the beginning all flags are 0. I use a while loop to check ... | The best answer here is to use [`all()`](http://docs.python.org/library/functions.html#all), which is the builtin for this situation. We combine this with a [generator expression](https://www.youtube.com/watch?v=t85uBptTDYY) to produce the result you want cleanly and efficiently. For example:
```
>>> items = [[1, 2, 0... |
Is there a effective way to get only K combinations of a list? | 10,666,343 | 2 | 2012-05-19T15:06:48Z | 10,666,424 | 11 | 2012-05-19T15:15:46Z | [
"python",
"algorithm"
] | Say I have a simple list from 1 to 8 and only want the combinations that include 7 characters. How could I do that efficiently? Is it possible to do it without iterating the entire list?
For example, This does the entire list:
```
import itertools
stuff = [1, 2, 3,4,5,6,7,8]
count = 0
for L in range(0, len(stuff)+1):... | `itertools.combinations` works just fine:
```
>>> for c in itertools.combinations(stuff, 7):
... print(c)
...
(1, 2, 3, 4, 5, 6, 7)
(1, 2, 3, 4, 5, 6, 8)
(1, 2, 3, 4, 5, 7, 8)
(1, 2, 3, 4, 6, 7, 8)
(1, 2, 3, 5, 6, 7, 8)
(1, 2, 4, 5, 6, 7, 8)
(1, 3, 4, 5, 6, 7, 8)
(2, 3, 4, 5, 6, 7, 8)
```
The duplicates are ... |
Can Python generate a random number that excludes a set of numbers, without using recursion? | 10,666,661 | 23 | 2012-05-19T15:46:56Z | 10,666,731 | 22 | 2012-05-19T15:56:41Z | [
"python",
"recursion",
"random",
"range"
] | I looked over [Python Docs](http://docs.python.org) (I may have misunderstood), but I didn't see that there was a way to do this (look below) without calling a recursive function.
What I'd like to do is generate a random value which excludes values in the middle.
In other words,
Let's imagine I wanted `X` to be a ... | Use random.choice().
In this example, a is your lower bound, the range between b and c is skipped and d is your upper bound.
```
import random
numbers = range(a,b) + range(c,d)
r = random.choice(numbers)
``` |
Can Python generate a random number that excludes a set of numbers, without using recursion? | 10,666,661 | 23 | 2012-05-19T15:46:56Z | 10,666,781 | 9 | 2012-05-19T16:03:47Z | [
"python",
"recursion",
"random",
"range"
] | I looked over [Python Docs](http://docs.python.org) (I may have misunderstood), but I didn't see that there was a way to do this (look below) without calling a recursive function.
What I'd like to do is generate a random value which excludes values in the middle.
In other words,
Let's imagine I wanted `X` to be a ... | A possible solution would be to just shift the random numbers out of that range. E.g.
```
def NormalWORange(a, b, sigma):
r = random.normalvariate(a,sigma)
if r < a:
return r-b
else:
return r+b
```
That would generate a normal distribution with a hole in the range (a-b,a+b).
Edit: If you ... |
Can Python generate a random number that excludes a set of numbers, without using recursion? | 10,666,661 | 23 | 2012-05-19T15:46:56Z | 10,666,802 | 38 | 2012-05-19T16:06:34Z | [
"python",
"recursion",
"random",
"range"
] | I looked over [Python Docs](http://docs.python.org) (I may have misunderstood), but I didn't see that there was a way to do this (look below) without calling a recursive function.
What I'd like to do is generate a random value which excludes values in the middle.
In other words,
Let's imagine I wanted `X` to be a ... | Generate one random number and map it onto your desired ranges of numbers.
If you wanted to generate an integer between `1-4` or `7-10`, excluding `5` and `6`, you might:
1. Generate a random integer in the range `1-8`
2. If the random number is greater than 4, add `2` to the result.
The mapping becomes:
```
Random... |
How to iterate over several list at the same time? | 10,667,073 | 3 | 2012-05-19T16:42:52Z | 10,667,084 | 17 | 2012-05-19T16:43:58Z | [
"python",
"django",
"django-views",
"python-2.7"
] | I have a bit of a riddle here
what i want to do is have a "for in" which loops on 3 variables from request.POST and request.FILES
what i did is:
```
images = request.FILES.getlist('image')
titles = request.POST.getlist('title')
captions = request.POST.getlist('caption')
for image,title,caption in images,titles,caption... | ```
for image, title, caption in zip(images, titles, captions):
```
..is what you want. ([zip docs](http://docs.python.org/library/functions.html#zip)) |
Python script with arguments for command line Blender | 10,667,314 | 6 | 2012-05-19T17:15:10Z | 10,863,965 | 8 | 2012-06-02T16:17:23Z | [
"python",
"batch-file",
"rendering",
"blender-2.50"
] | I'm new to blender and python. I have a blender model (.blend) that I want to batch-render as several images providing some properties for each image.
I wrote a python script with those parameters, something like:
```
import bpy
pi = 3.14159265
fov = 50
scene = bpy.data.scenes["Scene"]
# Set render resolution
scen... | I found the solution for what I was looking for intially.
As Junuxx said "You can't pass command line arguments directly to python in *this situation*..." but you actually CAN pass arguments to python but in another situation.
So the way to do what i want is to RENDER AND SAVE DIRECTLY INSIDE the python script
```
i... |
Python Requests throwing up SSLError | 10,667,960 | 113 | 2012-05-19T18:45:20Z | 10,668,173 | 62 | 2012-05-19T19:20:07Z | [
"python",
"ssl",
"python-requests",
"urllib3"
] | I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't know what Python requests is wanting? Where i... | From requests [documentation on SSL verification](http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification):
> Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a hostâs SSL certificate, you can use the verify argument:
```
>>> requests.get('https://ken... |
Python Requests throwing up SSLError | 10,667,960 | 113 | 2012-05-19T18:45:20Z | 12,864,892 | 144 | 2012-10-12T18:19:07Z | [
"python",
"ssl",
"python-requests",
"urllib3"
] | I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't know what Python requests is wanting? Where i... | The problem you are having is caused by an untrusted SSL certificate.
Like @dirk mentioned in a previous comment, the *quickest* fix is setting `verify=False`.
Please note that this will cause the certificate not to be verified. **This will expose your application to security risks, such as man-in-the-middle attacks.... |
Python Requests throwing up SSLError | 10,667,960 | 113 | 2012-05-19T18:45:20Z | 12,865,159 | 32 | 2012-10-12T18:38:46Z | [
"python",
"ssl",
"python-requests",
"urllib3"
] | I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't know what Python requests is wanting? Where i... | The name of CA file to use you could pass via `verify`:
```
cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
r = requests.get(url, verify=cafile)
```
If you use `verify=True` then `requests` uses its own CA set that might not have CA that signed your server certificate. |
Python Requests throwing up SSLError | 10,667,960 | 113 | 2012-05-19T18:45:20Z | 16,085,737 | 8 | 2013-04-18T14:29:46Z | [
"python",
"ssl",
"python-requests",
"urllib3"
] | I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't know what Python requests is wanting? Where i... | I have found an specific approach for solving a similar issue. The idea is pointing the cacert file stored at the [system](http://hearsum.ca/blog/python-and-ssl-certificate-verification/#comment-443) and used by another ssl based applications.
In Debian (I'm not sure if same in other distributions) the certificate fil... |
Pyramid: Views registered with `view_config` not being associated with routes | 10,668,130 | 5 | 2012-05-19T19:15:33Z | 10,670,155 | 7 | 2012-05-20T01:41:50Z | [
"python",
"pyramid"
] | I'm declaring a route like this:
```
from my_package import views
config.add_route("hello", "/hello")
config.scan(views)
```
And in `my_package.views` I have the view:
```
from pyramid.view import view_config
@view_config(name="hello")
def hello(request):
return Response("Hello, world!")
```
But route isn't bei... | You are naming the *view*, not the *route* in your @view\_config decorator. You want:
```
@view_config(route_name='hello')
def hello(request):
return Response("Hello, world!")
``` |
one-liner to check if at least one item in list exists in another list? | 10,668,282 | 25 | 2012-05-19T19:35:07Z | 10,668,319 | 31 | 2012-05-19T19:39:23Z | [
"python"
] | Lets say I have a list
`a=[1,2,3]`
And I want to know if at least one of the numbers in it exist in another list, like this one:
`b=[4,5,6,7,8,1]`
In other words, I want to know if 1,2 or 3 exist(s) in list `b`.
I now I could do something like
```
def func(a, b):
for i in a:
if i in b:
return True... | There are many ways to do this. The most direct translation is:
```
any_in = lambda a, b: any(i in b for i in a)
```
You could also use various things involving sets, such as:
```
any_in = lambda a, b: bool(set(a).intersection(b))
```
(which depends on the elements of `a` being hashable, but if that's true, it'll p... |
one-liner to check if at least one item in list exists in another list? | 10,668,282 | 25 | 2012-05-19T19:35:07Z | 10,668,321 | 12 | 2012-05-19T19:39:30Z | [
"python"
] | Lets say I have a list
`a=[1,2,3]`
And I want to know if at least one of the numbers in it exist in another list, like this one:
`b=[4,5,6,7,8,1]`
In other words, I want to know if 1,2 or 3 exist(s) in list `b`.
I now I could do something like
```
def func(a, b):
for i in a:
if i in b:
return True... | a simple one-liner would be:
```
any(i in b for i in a)
``` |
one-liner to check if at least one item in list exists in another list? | 10,668,282 | 25 | 2012-05-19T19:35:07Z | 10,668,329 | 30 | 2012-05-19T19:40:14Z | [
"python"
] | Lets say I have a list
`a=[1,2,3]`
And I want to know if at least one of the numbers in it exist in another list, like this one:
`b=[4,5,6,7,8,1]`
In other words, I want to know if 1,2 or 3 exist(s) in list `b`.
I now I could do something like
```
def func(a, b):
for i in a:
if i in b:
return True... | Python 2.6 and above:
```
def func(a, b):
return not set(a).isdisjoint(b)
```
For 2.4 or 2.5:
```
def func(a, b):
return len(set(a).intersection(b)) != 0
```
For 2.3 and below:
```
sudo apt-get update
sudo apt-get upgrade
```
;) |
one-liner to check if at least one item in list exists in another list? | 10,668,282 | 25 | 2012-05-19T19:35:07Z | 10,668,354 | 8 | 2012-05-19T19:43:46Z | [
"python"
] | Lets say I have a list
`a=[1,2,3]`
And I want to know if at least one of the numbers in it exist in another list, like this one:
`b=[4,5,6,7,8,1]`
In other words, I want to know if 1,2 or 3 exist(s) in list `b`.
I now I could do something like
```
def func(a, b):
for i in a:
if i in b:
return True... | This is a *set* problem, not a *list* problem. With the right data type, the answer is often immediately obvious :-)
```
def func(a, b):
return not set(a).isdisjoint(b)
``` |
Create 3D array using Python | 10,668,341 | 12 | 2012-05-19T19:41:59Z | 10,668,376 | 9 | 2012-05-19T19:47:03Z | [
"python",
"arrays",
"python-2.7",
"multidimensional-array"
] | I would like to create a 3D array in Python (2.7) to use like this:
```
distance[i][j][k]
```
And the sizes of the array should be the size of a variable I have. (n\*n\*n)
I tried using:
```
distance = [[[]*n]*n]
```
but that didn't seem to work.
Any ideas? Thanks a lot!
EDIT: I can only use the deafult librarie... | `numpy.array`s are designed just for this case:
```
numpy.zeros((i,j,k))
```
will give you an array of dimensions i\*j\*k, filled with zeroes.
depending what you need it for, [numpy](http://pypi.python.org/pypi/numpy) may be the right library for your needs. |
Create 3D array using Python | 10,668,341 | 12 | 2012-05-19T19:41:59Z | 10,668,448 | 25 | 2012-05-19T19:57:10Z | [
"python",
"arrays",
"python-2.7",
"multidimensional-array"
] | I would like to create a 3D array in Python (2.7) to use like this:
```
distance[i][j][k]
```
And the sizes of the array should be the size of a variable I have. (n\*n\*n)
I tried using:
```
distance = [[[]*n]*n]
```
but that didn't seem to work.
Any ideas? Thanks a lot!
EDIT: I can only use the deafult librarie... | You should use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
```
>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, ... |
python "or" when one of the vars might not exist? | 10,668,474 | 4 | 2012-05-19T20:03:17Z | 10,668,484 | 10 | 2012-05-19T20:04:53Z | [
"python",
"list",
"if-statement"
] | Assume something like this:
```
if mylist[0] == 1 or mylist[12] == 2:
# do something
```
But I'm not sure if `mylist[12]` will always not be out of range. What do to keep things simple and still check if index exists? Wouldn't want to do
```
if mylist[0] == 1:
# do something
elif mylist[12] == 2:
# do the... | You could check the length of the list:
```
if mylist[0] == 1 or (len(mylist) > 12 and mylist[12] == 2):
```
This uses the [short-circuting](http://en.wikipedia.org/wiki/Short-circuit_evaluation) behaviour of `and` to ensure that `mylist[12]` won't be evaluated if the list has 12 items or fewer. |
How to get max value in django ORM | 10,668,585 | 7 | 2012-05-19T20:22:31Z | 10,668,593 | 16 | 2012-05-19T20:23:34Z | [
"python",
"django",
"django-models"
] | ```
>>> AuthorizedEmail.objects.filter(group=group).values('added')
[{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)},
{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)},
{'added': datetime.datetime(2012, 5, 19, 13, 7, 23)},
{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)}]
```
What would be the best way to ... | ```
>>> from django.db.models import Max
>>> AuthorizedEmail.objects.all().aggregate(Max('added'))
```
And to fetch the value in the template:
```
{{ item.added__max }}
``` |
How to efficiently remove columns from a sparse matrix that only contain zeros? | 10,668,916 | 10 | 2012-05-19T21:16:44Z | 13,404,348 | 7 | 2012-11-15T19:03:25Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] | What is the best way to efficiently remove columns from a sparse matrix that only contain zeros. I have a matrix which I have created and filled with data:
```
matrix = sp.sparse.lil_matrix((100, 100))
```
I now wish to remove ~ the last 20 columns which only contain zero data. How can I do this? | If this were just a numpy array, `X`, then you could say `X!=0` which would give you a boolean array of the same shape as `X`, and then you could index `X` with the boolean array, i.e. `non_zero_entries = X[X!=0]`
But this is a sparse matrix which does not support boolean indexing and also will not give you what you w... |
Paramiko "Unknown Server" | 10,670,217 | 18 | 2012-05-20T01:59:50Z | 10,671,298 | 17 | 2012-05-20T06:33:14Z | [
"python",
"osx",
"paramiko"
] | I'm trying to get started with the Paramiko library, but the library is throwing an exception as soon as I try to connect with the following simple program:
```
import paramiko
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username='boatzart', password='mypassword')
```
The error I get is:
```
Traceback (most ... | The exception was raised because you are missing a host key, the rather cryptic "Unknown server" is the clue - since the exception was raised from `missing_host_key`
Try this instead:
```
import paramiko
paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.load_system_host_key... |
Paramiko "Unknown Server" | 10,670,217 | 18 | 2012-05-20T01:59:50Z | 11,644,305 | 64 | 2012-07-25T07:01:56Z | [
"python",
"osx",
"paramiko"
] | I'm trying to get started with the Paramiko library, but the library is throwing an exception as soon as I try to connect with the following simple program:
```
import paramiko
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username='boatzart', password='mypassword')
```
The error I get is:
```
Traceback (most ... | I experienced the same issue and here's the solution that worked out for me:
```
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('127.0.0.1', username=username, password=password)
stdin, stdout, stderr = client.exec_command('ls -l')
```
This i... |
Calling parent class with multiple inheritance in python | 10,671,889 | 2 | 2012-05-20T08:17:48Z | 10,671,914 | 12 | 2012-05-20T08:23:39Z | [
"python"
] | I'm apologizing in advance if this question was already answered, I just couldn't find it.
When using multiple inheritance, how can I use a method of a specific parent?
Let's say I have something like this
```
Class Ancestor:
def gene:
Class Dad(Ancestor):
def gene:
...
Class Mom(Ancestor):
def g... | That's not what `super` is for. `super` is just meant to call the next item in the inheritance hierarchy, whatever it is - in other words, it's supposed to be used when you don't know or care what that hierarchy is.
For your case, you probably just want to call the method directly. But note that you don't actually nee... |
Class constants in python | 10,672,419 | 31 | 2012-05-20T09:51:25Z | 10,672,434 | 9 | 2012-05-20T09:53:44Z | [
"python"
] | In python, I want a class to have some "constants" (practically, variables) which will be common in all subclasses. Is there a way to do it with friendly syntax?
Right now I use:
```
class Animal:
SIZES=["Huge","Big","Medium","Small"]
class Horse(Animal):
def printSize(self):
print(Animal.SIZES[1])
``... | You can get to `SIZES` by means of `self.SIZES` (in an instance method) or `cls.SIZES` (in a class method).
In any case, you will have to be explicit about where to find `SIZES`. An alternative is to put `SIZES` in the module containing the classes, but then you need to define all classes in a single module. |
Class constants in python | 10,672,419 | 31 | 2012-05-20T09:51:25Z | 10,672,749 | 44 | 2012-05-20T10:46:20Z | [
"python"
] | In python, I want a class to have some "constants" (practically, variables) which will be common in all subclasses. Is there a way to do it with friendly syntax?
Right now I use:
```
class Animal:
SIZES=["Huge","Big","Medium","Small"]
class Horse(Animal):
def printSize(self):
print(Animal.SIZES[1])
``... | Since `Horse` is a subclass of `Animal`, you can just change
```
print(Animal.SIZES[1])
```
with
```
print(self.SIZES[1])
```
Still, you need to remember that `SIZES[1]` means "big", so probably you could improve your code by doing something like:
```
class Animal:
SIZE_HUGE="Huge"
SIZE_BIG="Big"
SIZE_... |
Extract Video Frames In Python | 10,672,578 | 9 | 2012-05-20T10:16:45Z | 10,672,679 | 12 | 2012-05-20T10:31:56Z | [
"python",
"ffmpeg"
] | I want to extract video frames and save them as image.
```
import os, sys
from PIL import Image
a, b, c = os.popen3("ffmpeg -i test.avi")
out = c.read()
dp = out.index("Duration: ")
duration = out[dp+10:dp+out[dp:].index(",")]
hh, mm, ss = map(float, duration.split(":"))
total = (hh*60 + mm)*60 + ss
for i in xrange(9... | ffmpeg is complaining about there being a missing `%d` in the filename because you've asked it to convert multiple frames.
[This post](https://web.archive.org/web/20130118060805/http://www.techskater.com/random/extracting-video-frame-at-specific-time-using-ffmpeg/) suggests this would be a better way of using ffmpeg t... |
Extract Video Frames In Python | 10,672,578 | 9 | 2012-05-20T10:16:45Z | 17,109,400 | 7 | 2013-06-14T13:16:42Z | [
"python",
"ffmpeg"
] | I want to extract video frames and save them as image.
```
import os, sys
from PIL import Image
a, b, c = os.popen3("ffmpeg -i test.avi")
out = c.read()
dp = out.index("Duration: ")
duration = out[dp+10:dp+out[dp:].index(",")]
hh, mm, ss = map(float, duration.split(":"))
total = (hh*60 + mm)*60 + ss
for i in xrange(9... | Easy way, use Open CV.
```
import cv2
vc = cv2.VideoCapture('Test.mp4')
c=1
if vc.isOpened():
rval , frame = vc.read()
else:
rval = False
while rval:
rval, frame = vc.read()
cv2.imwrite(str(c) + '.jpg',frame)
c = c + 1
cv2.waitKey(1)
vc.release()
``` |
Python: Optimizing imports | 10,672,709 | 8 | 2012-05-20T10:37:56Z | 10,672,733 | 9 | 2012-05-20T10:42:35Z | [
"python",
"import"
] | Does it matter where modules are loaded in a code?
Or should they all be declared at the top, since during load time the external modules will have to be loaded regardless of where they are declared in the code...?
Example:
```
from os import popen
try:
popen('echo hi')
doSomethingIllegal;
except:
import... | [This](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead) indicates it may make a difference:
"import statements can be executed just about anywhere. *It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time*. Although Python's int... |
Which database model should I use for dynamic modification of entities/properties during runtime? | 10,672,939 | 19 | 2012-05-20T11:16:20Z | 10,712,269 | 18 | 2012-05-23T01:18:49Z | [
"python",
"database",
"dynamic",
"sqlalchemy",
"redis"
] | I am thinking about creating an open source data management web application for various types of data.
A privileged user must be able to
* add new entity types (for example a 'user' or a 'family')
* add new properties to entity types (for example 'gender' to 'user')
* remove/modify entities and properties
These will... | The SQL or NoSQL choice is not your problem. You need to read little more about database design in general. As you said, you're not a database expert(and you don't need to be), but
you absolutely **must** study a little more the RDBMS paradigm.
It's a common mistake for amateur enthusiasts to choose a NoSQL solution. ... |
Loop over list of lists given list of indices in tuple form | 10,673,176 | 4 | 2012-05-20T11:56:02Z | 10,673,201 | 7 | 2012-05-20T11:59:12Z | [
"python",
"list",
"tuples"
] | I have a list of tuples like
```
a = [(1, 2), (2, 2), (3, 2)]
```
the length of this list will vary. The order may also be inverted eg:
```
a = [(3, 2), (2, 2), (1, 2)]
```
I also have a list of lists like:
```
b = [['0', '0', '0'], ['0', '0', '0'], ['0', '0', '0'], ['0', '0', '0']]
```
Now I would like to loop o... | One problem is that your list of indexes is called `a` but you refer to `indexes_list`.
Fix this error and it works: [(ideone)](http://ideone.com/rgSsX)
```
indexes_list = [(3, 2), (2, 2), (1, 2)]
b = [['0', '0', '0'], ['0', '0', '0'], ['0', '0', '0'], ['0', '0', '0']]
for item in indexes_list:
b[item[0]][item[1... |
Generate list of all palindromic numbers of 3 digits in python | 10,673,422 | 5 | 2012-05-20T12:33:00Z | 10,673,456 | 11 | 2012-05-20T12:37:35Z | [
"python",
"list-comprehension",
"itertools",
"palindrome"
] | I can code this in a crude way but is there some intuitive way using list comprehension or itertools etc?
And also, How to do it if it is given the number is `k` digits instead of just 3? | ```
>>> L = [int("%d%d%d" % (x,y,x)) for x in range(1,10) for y in range(10)]
>>> L
[101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252,
262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414,
424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565... |
Count number of lines in a txt file with Python - but exclude blank lines | 10,673,560 | 5 | 2012-05-20T12:51:08Z | 10,673,569 | 14 | 2012-05-20T12:53:00Z | [
"python"
] | I wish to count the number of lines in a .txt file which looks something like this
```
apple
orange
pear
hippo
donkey
```
Where there are blank lines used to separate blocks. The result I'm looking for, based on the above sample, is five (lines).
How can I achieve this?
Thank you.
P.S. As a bonus, it would be nic... | ```
non_blank_count = 0
with open('data.txt') as infp:
for line in infp:
if line.strip():
non_blank_count += 1
print 'number of non-blank lines found %d' % non_blank_count
```
UPDATE: Re-read the question, OP wants to count *non-blank* lines .. (sigh .. thanks @RanRag).
(I need a break from the ... |
How do I generalize a list comprehension of this kind in Python? | 10,673,798 | 2 | 2012-05-20T13:26:10Z | 10,673,865 | 11 | 2012-05-20T13:33:30Z | [
"python",
"list-comprehension"
] | I have a integer list say `l1=[a,b,c]` and `_1to9=range(1,10)`. I'd like to get this:
```
[a*i1+b*i2+c*i3 for i1 in _1to9 for i2 in _1to9 for i3 in _1to9]
```
but the problem is that the `l1` is not necessarily a list of 3 elements. so how do I generalize?
***EDIT***: to help visualize what I'm trying to achieve:
... | Some basic math might help here. First, realise that `a*i1+b*i2+c*i3` is the [inner (dot) product](https://en.wikipedia.org/wiki/Dot_product) of two three-element lists, which can be generalized to
```
def dot_product(a, b):
return sum(x * y for x, y in zip(a, b))
```
and `for i1 in _1to9 for i2 in _1to9 for i3 i... |
Creating instances in a loop with different variables | 10,674,093 | 2 | 2012-05-20T14:06:27Z | 10,674,269 | 7 | 2012-05-20T14:30:16Z | [
"python"
] | I'm tring to create class instances in a loop. All instances need to be assinged to a different variable. These variables can be a sequence of letters like [a,b,c].
```
class MyClass(object):
pass
for i in something:
#create an instance
```
If the loop turns 3 times, I want the loop make something like that:... | Using independent variable names this way is a bit odd; using either a dict or a list, as shown above, seems better.
Splitting it down the middle, how about
```
a,b,c = (MyClass() for _ in range(3))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.