text
stringlengths 226
34.5k
|
---|
Unable to get python embedded to work with zip'd library
Question: I'm trying to embed python, and provide the dll and a zip of the python
libraries and not use any installed python. That is, if a user doesn't have
python, I want my code to work using the provided dll/zip.
This [post](http://stackoverflow.com/questions/1387906/c-with-python-
embedding-crash-if-python-not-installed) seems to describe the process, except
it isn't working for me.
If I run the following, my code will run as long as I have Python27.dll and a
_folder_ named Python27 that contains the DLL and Lib folders.
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_SetPythonHome("Python27");
Py_Initialize();
If I remove the Python27 folder, the code fails - so I am pulling in the local
copy, not any installed python.
However, if I zip the local Python27 folder, the code stops running, giving
"ImportError: No module named site".
[PEP273](http://www.python.org/dev/peps/pep-0273/) makes it sound like this
should just work, but everything I've tried has failed.
Can anyone shed light on how to get embedded python to run from a zip file?
Given that there are related questions that have gone unanswered, I think it
would be helpful if people would add a comment if they have successfully
gotten reading from a zip file working, even if they aren't sure what I might
need to fix.
That would at least help me understand if I should keep looking for an answer!
**Update** : No matter what I try (even with LoadLibrary as suggested), I can
run my program from a fully unzipped directory. Any time I remove the
directory with DLLs/* and Lib/* and put in Python27.zip instead, I just get
ImportError: No module named site
Answer: I had two issues.
The not well documented 'Py_NoSiteFlag' fixed the
ImportError: No module named site
first problem. Next, I had to update paths. In the end, I ended up with the
following for initialization:
Py_NoSiteFlag=1;
Py_SetProgramName(argv[0]);
Py_SetPythonHome(".");
Py_InitializeEx(0);
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path = ['.','python27.zip','python27.zip/DLLs','python27.zip/Lib','python27.zip/site-packages']");
[edit to address question in comments] Once you have the zip'd file loading,
you still need to pass files to the python engine. Here's what I use (argument
and file existence checks not included).
PyObject* PyFileObject = PyFile_FromString(argv[1], "r");
int res = PyRun_SimpleFile(PyFile_AsFile(PyFileObject), argv[1]);
[/edit]
|
Real-time visualisations with audio and video, which direction should I look?
Question: I have a little pet project with a friend where we're looking to create a
program for real-time visualisations, mainly utilising audio/video material,
controlled by MIDI. Now, the MIDI part is not a problem, you seem to find
decent solutions for almost any language, but I find myself terribly unsure of
which way I should look regarding handling the video in a smart way. I'm
looking for both fast seeking and additional visualisations (multiple
superimposed pictures for example).
I have already experimented with a couple of options that I found were
extremely easy to play with and seemed to offer at least something for the
task, but with each of them I felt I might run into dead ends or low
performance later on when looking to add features etc. So far, I tried Pure
Data, Max and Processing.
What I'm mostly asking advice for is to direct me onto an optimal or at least
a decent path regarding dealing with the videos. The biggest problem is I find
myself using all my time only trying to find out what programming language or
library I should use. If I only got that much guidance I could finally start
really working on it and advance.
I suppose I'm most comfortable with python but any suggestions are welcome. I
have read a little about gstreamer and I'm thinking there might be something
there, but now we're talking about a relatively low level library that would
take at least some time to produce any results with, as opposed to Processing
or Pure Data/Max, for instance.
In addition to the language/library I'm curious about the importance of the
video format. It goes a little beyond me when we start talking about codecs,
I-, P-, B-frames and whatnot. Who knows, there could even be a solution where
we'd use an optimal video format, cram that baby into RAMdisk or something and
get satisfactory seek speed with only that.
Answer: I recommend having a look at creative toolkits and for practical reasons
choose what language your prefer:
* MaxMSP with Jitter/PureData
* for c++ try [OpenFrameworks](http://openframeworks.cc) with [ofxMixi](https://github.com/danomatika/ofxMidi) or [Cinder](http://libcinder.org/) (and there should be MIDI block/addon for it)
* for Java try [Processing](http://libcinder.org/) with [proMIDI](http://creativecomputing.cc/p5libs/promidi/)
If language isn't an issue, maybe go ahead with MaxMSP and Jitter. Max has
objects for handling midi input and parsing it. Jitter deals with fast matrix
operations(images/video/gl/etc.) I think the equivalent for PureData is
[Gem](http://gem.iem.at/)
From experience, Java's garbage collector sometimes has the nasty habit of
getting in the way when dealing with realtime audio, but that's mostly true
for synthesis. You should be fine with MIDI. Depending on the
resolution/amount of content the video part might get a bit slow.
Which is why I recommend either going straight for a c++ creative toolkit or
Max. If you're not sure about video content, need many tweaks/iterations and
fast changes, maybe you should go straight for Max which is easy to prototype
in/pretty fast and you can pretty much 'live code' adapt you patcher while the
code is executing and update/adapt/improvize based on your needs.
|
Abstract Base Classes versus Duck Typing
Question: Python has specific [ABCs for container
types](http://docs.python.org/3/library/collections.abc.html). It says
they're, "…used to test whether a class provides a particular interface." (And
that they're also useful for some mixins, but let's ignore that for the
moment.)
I'm having trouble figuring out why some of these ABCs are really useful.
Perhaps my problem is just that the examples in the doc are too academic, but
using these examples:
# Verbatim
size = None
if isinstance(myvar, collections.abc.Sized):
size = len(myvar)
# Is that so much better than
size = None
if hasattr(myvar, '__len__'):
size = len(myvar)
In the second case you avoid an import and the code seems more explicit to me.
You can infer what collections.abc.Sized means from its name, or look it up,
but it's just not as explicit is "If it has a length, get its length."
Is the abc approach to collection-type testing really more idiomatic Python
than explicit `hasattr` testing, and if so, why? (Does _simple is better than
complex_ trump _explicit is better than implicit_ in this case?)
Answer: You can achieve the same results with either approach. The main benefit of the
ABC approach is that some of the logic is provided for you. For example, to
implement a Set type via duck typing, you would have to write and test 14
interfaces - `__contains__, __iter__, __len__, __le__, __lt__, __eq__, __ne__,
__gt__, __ge__, __and__, __or__, __sub__, __xor__, and isdisjoint`.
However if you use the ABC, you only need to define `__contains__, __iter__
and __len__` \- the ABC uses these function you provide to implement the
remaining 11 methods for you. ABC does what you would do, but with less
effort. It's a shortcut that gets you to the same destination.
|
Error Trying to Import JSON to Django Database - TypeError: string indices must be integers
Question: I've been self-teaching myself programming for less than a month. I'm trying
to build a Django site to help the process. I've spent the last 3 days
searching for a solution to this problem to no avail.
I stole this code from someone on Github, and it works fine when calling the
JSON URL file for which it was specifically written. But I've been trying to
modify it to work with another JSON URL file and it's not working. It's a
command file that is used to import data into the database. So here's what
happens when I run the command:
PS C:\django-1.5.1\dota\mysite> python manage.py update_items
Fetching item list..
TypeError: string indices must be integers
I apologize if there is too much code below, I really don't know what kinds of
things people would already implicitly know. I'm trying to import the fields
from each game item listed in this JSON file. I'm just starting with 2 fields
to try to get this working.
You can view the JSON file from the URL below, but it is formatted like this:
{
"itemdata": {
"blink": {
"id": 1,
"img": "blink_lg.png",
"dname": "Blink Dagger",
"qual": "component",
"cost": 2150,
"desc": "Active: Blink - Teleport to a target point up to 1200 units away. If damage is taken from an enemy hero, Blink Dagger cannot be used for 3 seconds.",
"attrib": "",
"mc": 75,
"cd": 12,
"lore": "The fabled dagger used by the fastest assassin ever to walk the lands.",
"components": null,
"created": false
},
"blades_of_attack": {
"id": 2,
And here are the 4 files related to the command file update_items.py:
models.py -- this model defines the database fields
from django.db import models
class Item(models.Model):
unique_id = models.IntegerField(unique=True)
dname = models.CharField(max_length=255)
def __unicode__(self):
return self.dname
update_items.py -- this is the command file to import the json data into the
database
from django.core.management.base import BaseCommand, CommandError
from django.core.management.base import NoArgsCommand
from items.utils.api import SteamWrapper
from items.models import Item
class Command(NoArgsCommand):
help = 'Fetches and updates the items'
def update_item(self, item):
try:
db_item = Item.objects.get(unique_id=item['id'])
print 'Updating %s..' % item['dname']
except Item.DoesNotExist:
print 'Creating %s..' % item['dname']
db_item = Item()
db_item.unique_id = item['id']
db_item.dname = item['dname']
db_item.save()
print 'Done.'
def fetch_items(self, result):
try:
for item in result['itemdata']:
self.update_item(item)
except KeyError:
print "Error while contacting steam API. Please retry."
def handle(self, *args, **options):
self.stdout.write('Fetching item list..')
result = SteamWrapper.get_item_list()
self.fetch_items(result)
self.stdout.write('Finished.')
api.py -- this is the web api call function thing
import requests
from mysite import settings_local
class SteamWrapper():
''' Steam API wrapper '''
API_KEY = settings_local.STEAM_API_KEY
@classmethod
def _item_send_request(cls, endpoint, *args, **kwargs):
params = {'key': cls.API_KEY}
params.update(kwargs)
request = requests.get(endpoint, params=params)
return request.json()
@classmethod
def get_item_list(cls):
return cls._item_send_request(settings_local.DOTA2_ITEM_LIST_ENDPOINT)
local-settings.py
DOTA2_ITEM_LIST_ENDPOINT = 'http://www.dota2.com/jsfeed/itemdata'
So any ideas? Thanks so much...
Answer: The problem is here:
for item in result['itemdata']
itemdata is a _dict_ (of dicts). In Python, iterating through a dict yields
the _keys_ : so `item` there is "blink", "blades_of_attack", and so on, hence
the error.
You don't seem to want the keys at all, so you should iterate through
`result['itemdata'].values()`.
(Note there is an indentation error in `update_item`: the line `db_item =
Item()` should be indented within the `except`, otherwise a new item will
always be created.)
|
Python all combinations of data
Question: So I have a file structure like this _(data on each line)_ :
A
B
C
...
I want to read each line of this file and combine those into all possible
combinations, the result I'm looking for would be this _(which I would put in
a list)_ :
A
AB
AC
ABC
ACB
B
BA
BC
BCA
BAC
C
CA
CB
CBA
CAB
Obviously I'd be looking to deal with more than just those three lines...
thanks
Answer: You should use the `itertools` library. You want to generate all unique
permutations of each element in the powerset. Some code might look like
from itertools import permutations, combinations, chain
# Taken from itertools page, but edited slightly to not return empty set
def powerset(iterable):
"powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
Then
In [1]: s = ('A', 'B', 'C')
In [2]: [j for i in powerset(s) for j in permutations(i)]
Out[2]:
[('A',),
('B',),
('C',),
('A', 'B'),
('B', 'A'),
('A', 'C'),
('C', 'A'),
('B', 'C'),
('C', 'B'),
('A', 'B', 'C'),
('A', 'C', 'B'),
('B', 'A', 'C'),
('B', 'C', 'A'),
('C', 'A', 'B'),
('C', 'B', 'A')]
|
for loop in for loop, python, csv reader/writer
Question: I am new in python, but after 3 days of reading and finding solution without
success i am lost.
I've got mysql table with data (id, user_id...). I connect to db, read user_id
and save data into array "user". Then i open csv file with a lot of rows and
columns (user_id, name, mail, telephone, address...). In the next step i
compare if user_id from db matches with user_id in csv file. If answer is yes
then i write this row in another csv file.
Problem is that my code works only for first id_user. Please, can you help me?
**Example table:**
table in db:
id user_id
1 318604
2 318624
**csv file:**
318604; John; [email protected]
318604; 053746; USA
318624; Lucy; [email protected]
318624; 058839 Sweeden
318630; Luke; [email protected]
**Expected result in new file:**
318604; John; [email protected]
318604; 053746; USA
318624; Lucy; [email protected]
318624; 058839 Sweeden
**Code:**
cur = con.cursor()
with open('input.csv', mode='rb') as f:
reader = csv.reader(f, delimiter=';')
with open('output.csv', mode='a') as w:
writer = csv.writer(w)
with con:
cur.execute("SELECT user_id FROM users")
user=cur.fetchall()
for i in range(len(user)):
for row in reader:
if(user[i][0]==row[0]):
writer.writerow(row)
con.close()
Answer: You need to reopen the **input.csv** file. When you go through each line of
the file without reopening it your courser will always be on the last line of
the file. To fix that move opening of the input file to the `for user` loop:
cur = con.cursor()
with open('output.csv', mode='a') as w:
writer = csv.writer(w)
with con:
cur.execute("SELECT user_id FROM users")
user=cur.fetchall()
for i in range(len(user)):
with open('input.csv', mode='rb') as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
if(user[i][0]==row[0]):
writer.writerow(row)
con.close()
I tested it with this code:
import csv
user = [[1,318604],[2,318624]]
with open('output.csv', mode='a') as w:
writer = csv.writer(w)
for i in range(len(user)):
with open('input.csv', mode='rb') as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
if(str(user[i][1])==row[0]):
writer.writerow(row)
Instead output from your database I used list with integers in it. So I needed
to convert `user[i][1]` to string. Also `user[i][0]` is `id`, when
`user[i][1]` is `user_id`, don't know if it the same for your output from
database.
Output:
318604, John, [email protected]
318604, 053746, USA
318624, Lucy, [email protected]
318624, 058839 Sweeden
|
Simple Python - Error in Programming
Question: I've been stuck on this issue for over two hours, this is homework so please
don't give me a direct answer just point me in the right direction.
So... This program is designed to input a "speed limit", input "Current speed"
and give you a print response of either "Speed OK" (if you are below or equal
to the speed limit) and "Slow down!" (if you are speeding). When I input the
following data, as required on the task: Speed Limit of 50. Current Speed of
50, 45, 55, 52, and 50.
The answer should read -
Speed limit: 50
Current speed: 50
Speed OK
Current speed: 45
Speed OK
Current speed: 55
Slow down!
Current speed: 52
Slow down!
Current speed: 50
Speed OK
Current speed:(White space)
Instead I get -
Current speed: 50
Speed OK
Current speed: 45
*Then the program stops.*
My Program Reads -
limit = int(input("Speed limit: "))
speed = int(input("Current speed: "))
if speed <= limit:
print("Speed OK")
speed = int(input("Current speed: "))
false = speed > limit
while false:
print("Slow down!")
speed = int(input("Current speed: "))
If somebody could point me in the right direction that would be wonderful ;).
Cheers,
Ron
Answer: First of all, keep in mind that the one of the most important rules of
programming is to avoid code doubling. This means that it nearly _never_ a
good idea to have the same `speed = int(input("Current speed: "))` line three
times in your program. If there's an error in that line, fixing it will
probably leave the error in the two other places untouched.
If you follow that rule, you will probably find out that you only need one
loop which should terminate on `(White space)` (so this check should be in the
condition, not `false`). And _inside_ that loop you should check with `if`
which response your program should give.
Finally, I _strongly_ disapprove of having a variable named `false`. In case
`speed` is larger than `limit`, your variable `false` will hold the value
`True` (which is quite peculiar and surprising). Any other programmer would
probably misunderstand this.
Never forget that writing a program also is communicating with the next
programmer who has to maintain your code.
|
Excluding web links with specific extensions in web scraper
Question: I need to exclude printing links in my web scraper that end in .od .jpg .pdf
or .mp3
Here's my `if` statement
if link in linkList():
print link
Is there some library in Python for that? I only know of"RegEx" but I'm not
the greatest user of it.
Answer: Assuming that your link is just the path, you can do something like the
following:
import os
if os.path.splitext(link)[1] not in ['.jpg', '.pdf', '.mp3']:
print link
The function `splitext` takes a path and returns a tuple containing the path
without the extension, followed by the extension. For example:
>>> os.path.splitext('http://www.example.com/path/to/filename.ext')
('http://www.example.com/path/to/filename', '.ext')
So if you split the link with that function, you can check whether the last
element of the tuple is a member of another list/set/tuple containing your
blacklist of extensions.
|
Create a xls file from a dict python
Question: Anyone knows how to create a xls file from a dict? I have a dictionary filled
with words in a text, i want to put this DICT in a xls
def contar_Repetidas(texto):
dic={}
l=texto.split()
for palabra in l:
if palabra not in dic:
dic[palabra] = 1
else:
dic[palabra] +=1
return dic
It's diferent becorse, i want to create a MS Excel from a DICT, a DICT
Answer: Using the [`xlwt`](https://pypi.python.org/pypi/xlwt) module:
import xlwt
dic = contar_Repetidas("Some Text Here")
wb = xlwt.Workbook()
ws = wb.add_sheet("Your Sheet")
count = 0
for word, num in dic.items():
count += 1
ws.write(count, 1, word)
ws.write(count, 2, num)
wb.save("/Path/To/Save/Example.xls")
|
Dynamic Library causes error when added to setup.py file (on Mac OS.X)
Question: I have a dynamic library, built in cpp that actually works in cpp but is
causing much headache when I try to import it from a python class. The error
appears simply when I add the lib to my setup.py file. Error:
MacBook-Pro-de-Marcelo-Salloum:python_cpp_interface marcelosalloum$ python userect.py
Traceback (most recent call last):
File "userect.py", line 2, in <module>
from rectangle import Rectangle
ImportError: dlopen(/Users/marcelosalloum/Projects/CppOpenCV/python_cpp_interface/rectangle.so, 2): Symbol not found: __XEatDataWords
Referenced from: /opt/local/lib/libXext.6.dylib
Expected in: /opt/local/lib/libX11.6.dylib
in /opt/local/lib/libXext.6.dylib
Setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'DyCppInterface',
version = '1.0',
author = 'Marcelo Salloum dos Santos',
# The ext modules interface the cpp code with the python one:
ext_modules=[
Extension("rectangle",
sources=["rectangle.pyx", "cpp_rect.cpp"], # Note, you can link against a c++ library instead of including the source
include_dirs=[".","source", "/opt/local/include/opencv", "/opt/local/include"],
language="c++",
# extra_link_args = ['-arch x86_64'],
# extra_link_args = ['-arch i386', '-arch x86_64'],
library_dirs=['/usr/local/lib', 'source'],
runtime_library_dirs=['/Users/marcelosalloum/Projects/CppOpenCV/python_cpp_interface/source'],
libraries=['LibCppOpenCV'])
],
cmdclass = {'build_ext': build_ext},
)
It is known that This *.so file uses a c++ OpenCV library. Before adding this
lib to my shared library, everything was working perfectly.
* How to figure out what is causing the error?
* Should I try with a static library instead of a dynamic one?
* P.S.: my **DYLD_LIBRARY_PATH = ~/Projects/CppOpenCV/python_cpp_interface/source/:/usr/local/mysql/lib/**
Answer: Thanks to the comments of abarnert, I solved the problem updating and
upgrading MacPorts. As abarnert observed, there was a linking problem between
`/opt/local/lib/libXext.6.dylib` and `/opt/local/lib/libX11.6.dylib`.
So I did:
$ sudo port selfupdate
$ sudo port upgrade outdated
|
Adding Button and Separate Window to Python QProcess Example
Question: I'm trying to use QProcess and read the stdout to a QTextEdit initiated by a
button. How can I adapt [this
example](http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=408&key=QTextEditRedStdOutput)
to do so? Do I have to call a separate class for the QProcess?
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class MyQProcess(QProcess):
def __init__(self):
#Call base class method
QProcess.__init__(self)
#Create an instance variable here (of type QTextEdit)
self.edit = QTextEdit()
self.edit.setWindowTitle("QTextEdit Standard Output Redirection")
self.edit.show()
#Define Slot Here
@pyqtSlot()
def readStdOutput(self):
self.edit.append(QString(self.readAllStandardOutput()))
def main():
app = QApplication(sys.argv)
qProcess = MyQProcess()
qProcess.setProcessChannelMode(QProcess.MergedChannels);
qProcess.start("ldconfig -v")
QObject.connect(qProcess,SIGNAL("readyReadStandardOutput()"),qProcess,SLOT("readStdOutput()"));
return app.exec_()
if __name__ == '__main__':
main()
Answer: Use `QPushButton` to make a button.
Use `QPushButton.clicked.connect` to bind event.
For example:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyWindow(QWidget):
def __init__(self):
QWidget.__init__(self)
self.edit = QTextEdit()
self.edit.setWindowTitle("QTextEdit Standard Output Redirection")
self.button = QPushButton('Run ldconfig')
self.button.clicked.connect(self.onClick)
layout = QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
@pyqtSlot()
def readStdOutput(self):
self.edit.append(QString(self.proc.readAllStandardOutput()))
def onClick(self):
self.proc = QProcess()
self.proc.start("echo hello")
self.proc.setProcessChannelMode(QProcess.MergedChannels);
QObject.connect(self.proc, SIGNAL("readyReadStandardOutput()"), self, SLOT("readStdOutput()"));
def main():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
return app.exec_()
if __name__ == '__main__':
main()
|
removing specific row in csv file, python
Question: I woud like to remove (delete) specific rows in csv file. But there are some
conditions.
1.) File can't be buffered in memmory, becuse of it's size (1GB+)
2.) File MUST NOT be "touched" (rewriting file)
My job is just to delete some rows in csv file, without changing any other
rows - Very important, becuse of encoding and sending filtered csv file to
company which prints that files.
Is there solution?
Thank you!
Answer: It can't be done. You want to delete content from a file, without modifying
it. Those are mutually exclusive.
|
understanding nltk with python
Question: My nltk data is `~/nltk_data/corpora/words/(en,en-basic,README)`
According to `__init__.py` inside `~/lib/python2.7/site-packages/nltk/corpus`,
to read a list of the words in the Brown Corpus, use
`nltk.corpus.brown.words()`:
from nltk.corpus import brown
print brown.words()
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
This `__init__.py` has
words = LazyCorpusLoader(
'words', WordListCorpusReader, r'(?!README|\.).*')
1. So when I write `from nltk.corpus import words`, am I importing the 'words' function from `__init__.py` which resides in directory `python2.7/site-packages/nltk/corpus`?
2. Also why does this happen:
import nltk.corpus.words
ImportError: No module named words
from nltk.copus import words
# WORKS FINE
3. The "brown" corpus resides inside `~/nltk_data/corpora` (and not in nltk/corpus). So why does this command work?
from nltk.corpus import brown
Shouldn't it be this?
from nltk_data.corpora import brown
Answer: Re. point 2: You can import either a module (`import module.submodule`), or an
object from a module (`from module.submodule import variable`). While you can
treat a module as a variable, because it actually is a variable in that scope
(`from module import submodule`), it doesn't work the other way. That's why
when you try doing `import module.submodule.variable`, it fails.
Re. point 3: Depends on what `nltk.corpus` does. Maybe it searches/loads the
`nltk_data` for you automatically.
|
Creating Matplotlib Toolbar in Python Traits Editor
Question: I'm working on a QT4 Traits-GUI in Python using Matplotlib for image display,
and so far I have [this](https://mail.enthought.com/pipermail/enthought-
dev/2012-May/031065.html) editor modified in an attempt to include a toolbar.
from traitsui.qt4.editor import Editor
from pyface.qt import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
class _MPLFigureEditor(Editor):
"""
Building custom figure editor for displaying matplotlib figures with a qt4-based Traits interface
"""
scrollable = True
def init(self, parent):
self.control = self._create_canvas(parent)
self.set_tooltip()
def update_editor(self):
pass
def _create_canvas(self, parent):
mpl_canvas = FigureCanvas(self.value) #self.value is the figure linked to the editor factory
mpl_toolbar = NavigationToolbar(mpl_canvas,???)
layout = QtGui.QVBoxLayout()
layout.addWidget(mpl_toolbar)
layout.addWidget(mpl_canvas)
return layout
Is this the correct place to create the toolbar? What would be second argument
to NavigationToolbar in this case? I'm trying to follow the examples I've
found on adding toolbars as QWidgets to figures, but these all create a
main_frame within a QMainWindow-based class, not a Traits Editor. Thanks in
advance.
Answer: Found the answer. Since `parent` is a `QGridLayout` itself, we can add the
toolbar widget directly to the layout in row 2, column 1 (to place it below
the canvas, which I believe is added as a widget in the view-editor creation).
from traitsui.qt4.editor import Editor
from pyface.qt import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
class _MPLFigureEditor(Editor):
"""
Building custom figure editor for displaying matplotlib figures with a qt4-based Traits interface
"""
scrollable = True
def init(self, parent):
self.control = self._create_canvas(parent)
mpl_toolbar = NavigationToolbar(self.control,None)
parent.addWidget(mpl_toolbar,2,1)
self.set_tooltip()
return
def update_editor(self):
pass
def _create_canvas(self, parent):
""" Create the MPL canvas. """
mpl_canvas = FigureCanvas(self.value)
return mpl_canvas
Image zoom/pan does seem to run a bit slow, but that could be another issue
altogether.
|
Python text processing and parsing
Question: I have a file in `gran/config.py` AND I cannot import this file (not an
option).
Inside this config.py, there is the following code
...<more code>
animal = dict(
bear = r'^bear4x',
tiger = r'^.*\tiger\b.*$'
)
...<more code>
I want to be able parse `r'^bear4x'` or `r'^.*\tiger\b.*$'` based on bear or
tiger.
I started out with
try:
text = open('gran/config.py','r')
tline = filter('not sure', text.readlines())
text.close()
except IOError, str:
pass
I was hoping to grab the whole animal dict by
`grab = re.compile("^animal\s*=\s*('.*')")` or something like that
and maybe change `tline` to `tline = filter(grab.search,text.readlines())`
but it only grabs `animal = dict(` and not the following lines of dict.
how can i grab multiple lines?
look for animal then confirm the first '(' then continue to look until ')' ??
Note: the size of animal dict may change so anything static approach (like
grab 4 extra lines after animal is found) wouldnt work
Answer: I am not getting what exactly are you trying to do.
If you want to process **each line** with regular expression - you have `^` in
regular expression `re.compile("^animal\s*=\s*('.*')")`. It matches only when
`animal` is at the start of line, not after some spaces. Also of course it
does not match `bear` or `tiger` \- use something like
`re.compile("^\s*([a-z]+)\s*=\s*('.*')")`.
If you want to process **multiple lines** with single regular expression, read
about re.DOTALL and re.MULTILINE and how they affect matching newline
characters:
<http://docs.python.org/2/library/re.html#re.MULTILINE>
Also note that text.readlines() reads lines, so the filter function in
`filter('not sure', text.readlines())` is run on each line, not on whole file.
You cannot pass regular expression in this `filter(<re here>,
text.readlines())` and hope it will match multiple lines.
BTW processing Python files (and HTML, XML, JSON... files) using regular
expressions is not wise. For every regular expression you write there are
cases where it will not work. Use parser designed for given format - for
Python source code it's [ast](http://docs.python.org/2/library/ast.html). But
for your use case `ast` is too complex.
Maybe it would be better to use classic config files and
[configparser](http://docs.python.org/2/library/configparser.html). More
structured data like lists and dicts can be easily stored in
[JSON](http://docs.python.org/2/library/json.html) or
[YAML](https://bitbucket.org/xi/pyyaml) files.
|
How to avoid hanging Xvfb processes [while using PyVirtualDisplay]?
Question: Trying to find how to avoid hanging Xvfb processes in our Python application,
when using PyVirtualDisplay. The essential problem is that calling
`display.stop()` (see code sample below) does not seem to properly shut down
the Xvfb process.
PyVirtualDisplay is very simply used:
from pyvirtualdisplay import Display
display = Display(backend='xvfb')
display.start()
... # Some stuff happens here
display.stop()
Now, the Display class has a slight modification to prevent Xvfb from using
TCP ports: basically, add `-nolisten tcp` to the executing command. The
modification is done by overriding the appropriate XfvbDisplay class's _cmd
property:
@property
def _cmd(self):
cmd = [PROGRAM,
dict(black='-br', white='-wr')[self.bgcolor],
'-screen',
str(self.screen),
'x'.join(map(str, list(self.size) + [self.color_depth])),
self.new_display_var,
'-nolisten',
'tcp'
]
return cmd
What is the proper way to end the Xvfb processes in this context so that they
are terminated and do not linger?
Thanks very much!
Answer: Your display, since it inherits from EasyProcess, will have a popen attribute
at `display.popen`. You can use this to terminate, if EasyProcess isn't
working properly.
So, you can do something like this:
display.popen.terminate()
or
display.popen.kill()
|
Python Multiprocessing Kill Processes
Question: I am learning how to use the Python multiprocessing library. However, while I
am going through some of the examples, I ended up with many python processes
running in my background.
One of the [example](http://docs.python.org/2/library/multiprocessing.html)
looks like below:
from multiprocessing import Process, Lock
def f(l, i):
l.acquire()
print 'hello world', i
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10): # I changed the number of iterations from 10 to 1000...
Process(target=f, args=(lock, num)).start()
Now here is a screen shot of my 'TOP' command:
88950 Python 0.0 00:00.00 1 0 9 91 1584K 5856K 2320K 1720K 2383M 82441 1 sleeping 1755113321 799
88949 Python 0.0 00:00.00 1 0 9 91 1584K 5856K 2320K 1720K 2383M 82441 1 sleeping 1755113321 798
88948 Python 0.0 00:00.00 1 0 9 91 1580K 5856K 2316K 1716K 2383M 82441 1 sleeping 1755113321 797
88947 Python 0.0 00:00.00 1 0 9 91 1580K 5856K 2316K 1716K 2383M 82441 1 sleeping 1755113321 796
88946 Python 0.0 00:00.00 1 0 9 91 1576K 5856K 2312K 1712K 2383M 82441 1 sleeping 1755113321 795
88945 Python 0.0 00:00.00 1 0 9 91 1576K 5856K 2312K 1712K 2383M 82441 1 sleeping 1755113321 794
88944 Python 0.0 00:00.00 1 0 9 91 1576K 5856K 2312K 1712K 2383M 82441 1 sleeping 1755113321 794
88943 Python 0.0 00:00.00 1 0 9 91 1572K 5856K 2308K 1708K 2383M 82441 1 sleeping 1755113321 792
88942 Python 0.0 00:00.00 1 0 9 91 1568K 5856K 2304K 1708K 2383M 82441 1 sleeping 1755113321 790
88941 Python 0.0 00:00.00 1 0 9 91 1564K 5856K 2300K 1704K 2383M 82441 1 sleeping 1755113321 789
88938 Python 0.0 00:00.00 1 0 9 91 1564K 5856K 2300K 1704K 2383M 82441 1 sleeping 1755113321 788
88936 Python 0.0 00:00.00 1 0 9 91 1576K 5856K 2296K 1716K 2383M 82441 1 sleeping 1755113321 787
88935 Python 0.0 00:00.00 1 0 9 91 1560K 5856K 2296K 1700K 2383M 82441 1 sleeping 1755113321 787
88934 Python 0.0 00:00.00 1 0 9 91 1560K 5856K 2296K 1700K 2383M 82441 1 sleeping 1755113321 786
88933 Python 0.0 00:00.00 1 0 9 91 1556K 5856K 2292K 1696K 2383M 82441 1 sleeping 1755113321 785
88932 Python 0.0 00:00.00 1 0 9 91 1556K 5856K 2292K 1696K 2383M 82441 1 sleeping 1755113321 784
88931 Python 0.0 00:00.00 1 0 9 91 1552K 5856K 2288K 1692K 2383M 82441 1 sleeping 1755113321 783
88930 Python 0.0 00:00.00 1 0 9 91 1612K 5856K 2288K 1752K 2383M 82441 1 sleeping 1755113321 783
88929 Python 0.0 00:00.00 1 0 9 91 1588K 5856K 2288K 1728K 2383M 82441 1 sleeping 1755113321 782
88927 Python 0.0 00:00.00 1 0 9 91 1608K 5856K 2284K 1748K 2383M 82441 1 sleeping 1755113321 781
88926 Python 0.0 00:00.00 1 0 9 91 1548K 5856K 2284K 1688K 2383M 82441 1 sleeping 1755113321 780
88924 Python 0.0 00:00.00 1 0 9 91 1556K 5856K 2276K 1700K 2383M 82441 1 sleeping 1755113321 778
88923 Python 0.0 00:00.00 1 0 9 91 1540K 5856K 2276K 1684K 2383M 82441 1 sleeping 1755113321 777
88922 Python 0.0 00:00.00 1 0 9 91 1540K 5856K 2276K 1684K 2383M 82441 1 sleeping 1755113321 776
88921 Python 0.0 00:00.00 1 0 9 91 1536K 5856K 2272K 1680K 2383M 82441 1 sleeping 1755113321 774
88920 Python 0.0 00:00.00 1 0 9 91 1528K 5856K 2264K 1672K 2383M 82441 1 sleeping 1755113321 771
88919 Python 0.0 00:00.00 1 0 9 91 1528K 5856K 2264K 1672K 2383M 82441 1 sleeping 1755113321 771
88918 Python 0.0 00:00.00 1 0 9 91 1528K 5856K 2264K 1672K 2383M 82441 1 sleeping 1755113321 770
....
1. I don't know how to kill them in one go.
ps ... | grep python .... kill?
2. what kind of python code do I need to add to avoid this miserable situation again. Thanks!
Answer: You need to .join() on your processes in a worker Queue, which will lock them
to the calling application until all of them succeed or kill when the parent
is killed, and run them in daemon mode.
[http://forums.xkcd.com/viewtopic.php?f=11&t=94726](http://forums.xkcd.com/viewtopic.php?f=11&t=94726)
[end daemon processes with multiprocessing
module](http://stackoverflow.com/questions/4792473/end-daemon-processes-with-
multiprocessing-module)
<http://docs.python.org/2/library/multiprocessing.html#the-process-class>
<http://www.python.org/dev/peps/pep-3143/#correct-daemon-behaviour>
|
Matplotlib imshow() too many objects for cmap
Question: I'm trying to create a simple imshow() plot (matplotlib v.1.2.1) of a 2D
gaussian function:
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
def gaussian(x,y,stdx,stdy):
return 1.0/(2*np.pi*stdx*stdy) * (np.exp(-0.5*(x**2/stdx**2 + y**2/stdy**2)))
coords = np.linspace(-1,1,100)
X,Y = np.meshgrid(coords,coords)
std_list = np.linspace(1,2,20)
output = [gaussian(X,Y,std_list[i],std_list[i]) for i in range(len(std_list))]
for i in range(len(output)):
plt.imshow(X,Y,np.array(output[i]),cmap='bone')
plt.show()
And I get the following error:
Traceback (most recent call last):
File "blur.py", line 14, in <module>
plt.imshow(X,Y,np.array(output[i]),cmap='bone')
TypeError: imshow() got multiple values for keyword argument 'cmap'
In fact, to make sure I wasn't crazy, I took out the cmap argument altogether,
and now I'm getting the following error:
Traceback (most recent call last):
File "blur.py", line 14, in <module>
plt.imshow(X,Y,np.array(output[i]))
File "/home/username/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2737, in imshow
imlim=imlim, resample=resample, url=url, **kwargs)
File "/home/username/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 7098, in imshow
if norm is not None: assert(isinstance(norm, mcolors.Normalize))
AssertionError
I've made sure that the arguments of imshow( ) all have the same shape, so I'm
not entirely sure what I'm doing wrong. Could this be a bug?
Answer: `imshow` doesn't take `x`, `y`, `z` as input. (`pcolor` and `pcolormesh` do,
however).
Either use `pcolormesh(x, y, z)`, or use the `extent` kwarg to imshow.
e.g.
plt.imshow(Z, extent=[X.min(), X.max(), Y.min(), Y.max()],
cmap='bone')
or
plt.pcolormesh(X, Y, Z, cmap='bone')
* * *
What's happening is that `imshow` expects
imshow(X, cmap=None, norm=None, aspect=None, interpolation=None,
alpha=None, vmin=None, vmax=None, origin=None, extent=None,
**kwargs)
Notice that the second argument is `cmap`, which explains why you're getting
the error you are when you pass in an additional `cmap` kwarg.
Hopefully that clarifies things a touch! Good luck!
|
Aggregate and fill data for missing dates (days and hours)
Question: Suppose we have a list like this showing the count of each object on a
particular date (mm-dd-yyyy-hour-minute):
A = [
[
['07-07-2012-21-04', 'orange', 1],
['08-16-2012-08-57', 'orange', 1],
['08-18-2012-03-30', 'orange', 1],
['08-18-2012-03-30', 'orange', 1],
['08-19-2012-03-58', 'orange', 1],
['08-19-2012-03-58', 'orange', 1],
['08-19-2012-04-09', 'orange', 1],
['08-19-2012-04-09', 'orange', 1],
['08-19-2012-05-21', 'orange', 1],
['08-19-2012-05-21', 'orange', 1],
['08-19-2012-06-03', 'orange', 1],
['08-19-2012-07-51', 'orange', 1],
['08-19-2012-08-17', 'orange', 1],
['08-19-2012-08-17', 'orange', 1]
],
[
['07-07-2012-21-04', 'banana', 1]
],
[
['07-07-2012-21-04', 'mango', 1],
['08-16-2012-08-57', 'mango', 1],
['08-18-2012-03-30', 'mango', 1],
['08-18-2012-03-30', 'mango', 1],
['08-19-2012-03-58', 'mango', 1],
['08-19-2012-03-58', 'mango', 1],
['08-19-2012-04-09', 'mango', 1],
['08-19-2012-04-09', 'mango', 1],
['08-19-2012-05-21', 'mango', 1],
['08-19-2012-05-21', 'mango', 1],
['08-19-2012-06-03', 'mango', 1],
['08-19-2012-07-51', 'mango', 1],
['08-19-2012-08-17', 'mango', 1],
['08-19-2012-08-17', 'mango', 1]
]
]
What I need to do in A is to fill all the missing dates (from minimum date to
maximum date of A) for each object with value as 0. Once the missing dates and
their corresponding values (0) are in, I want to sum up the values for each
date, so that no date repeats - for each sublist.
Now, What I am trying to goes as follows: I am breaking up A's dates and
values separately (in lists named u and v) and converting each sublist into a
pandas Series, and allocating their respective indices to them. So for each
zip(u,v):
def generate(values, indices):
indices = flatten(indices)
date_index = DatetimeIndex(indices)
ts = Series(values, index=date_index)
ts.reindex(date_range(min(date_index), max(date_index)))
return ts
But in here, the reindexing is causing raising an exception. What I am looking
for is a purely pythonic way (without pandas) which is totally based on either
list comprehension or maybe even numpy arrays.
There is another issue of aggregation over hours, which means that if all the
dates are same and only the hours are different then I want to fill in all the
missing hours of the day and then repeat the same process of aggregation over
each hour, with missing hours filled in with 0 values.
Thanks in advance.
Answer: What about this:
from collections import defaultdict, OrderedDict
from datetime import datetime, timedelta
from itertools import chain, groupby
flat = sorted((datetime.strptime(d, '%m-%d-%Y-%H-%M').date(), f, c)
for (d, f, c) in chain(*A))
counts = [(d, f, sum(e[2] for e in l))
for (d, f), l
in groupby(flat, key=lambda t: (t[0], t[1]))]
# lets assume that there are some data
start = counts[0][0]
end = counts[-1][0]
result = OrderedDict((start+timedelta(days=i), defaultdict(int))
for i in range((end-start).days+1))
for day, data in groupby(counts, key=lambda d: d[0]):
result[day].update((f, c) for d, f, c in data)
My question is: do we **really** need to fill non existing dates - I can
easily imagine situation when this will be **a lot** of data, even dangerous
amount of data... I think that it is better to use simple general function and
generator if you want to list them somewhere:
from collections import defaultdict
from datetime import datetime, timedelta
from itertools import chain, groupby
def aggregate(data, resolution='daily'):
assert resolution in ['hourly', 'daily']
if resolution == 'hourly':
round_dt = lambda dt: dt.replace(minute=0, second=0, microsecond=0)
else:
round_dt = lambda dt: dt.date()
flat = sorted((round_dt(datetime.strptime(d, '%m-%d-%Y-%H-%M')), f, c)
for (d, f, c) in chain(*A))
counts = [(d, f, sum(e[2] for e in l))
for (d, f), l
in groupby(flat, key=lambda t: (t[0], t[1]))]
result = {}
for day, data in groupby(counts, key=lambda d: d[0]):
d = result[day] = defaultdict(int)
d.update((f, c) for d, f, c in data)
return result
def xaggregate(data, resolution='daily'):
aggregated = aggregate(data, resolution)
curr = min(aggregated.keys())
end = max(aggregated.keys())
interval = timedelta(days=1) if resolution == 'daily' else timedelta(seconds=3600)
while curr <= end:
# None is sensible value in case of missing data I think
yield curr, aggregated.get(curr)
curr += interval
In general my suggestion is that you should not use lists as ordered
structures (I mean `['07-07-2012-21-04', 'mango', 1]`). I think that `tuple`
is more appropriate for this purpose and of course `collections.namedtuple` is
even more desired.
|
Why Ruby and Python long division differs from GMP and Java BigInteger?
Question: I'm developing a Big Integer class(didactic purpose) and I have been using
Ruby to generate test cases. My class fails in the following test:
a = -48197174570431531987668852939807674377435188974148779416366905274642031729688518691
b = 4322669160730708444058642850762359547515258361061655693150034467061
a / b = -11149864303351921 # Ruby answer
I could not find the bug in my code so I tried to verify the result with other
tools and surprise :o.
GMP, Java BigInteger and my class coincides with this results:
11149864303351920
-11149864303351920
But Ruby and Python coincides with this:
-11149864303351921
11149864303351920
Can somebody explain why this behavior?, Please.
Answer: the issue is with integer division. python 2.x (and, I assume, ruby, though
I'm not an expert there) do integer division by default. if you do this in
python:
from __future__ import division
a = -48197174570431531987668852939807674377435188974148779416366905274642031729688518691
b = 4322669160730708444058642850762359547515258361061655693150034467061
print int(a/b)
you'll see the answer you're expecting.
note that this behaviour is default in python 3+, and that the `from
__future__` import is only available in python 2.2+.
Here's some more info. on integer division, courtesy of
[Wikipedia](https://en.wikipedia.org/wiki/Integer_division) :)
**edit:**
As Steve Rumbalski points out, the significant difference is the way in which
the rounding takes place. Python's integer division rounds towards negative
infinity, instead of towards zero (such that -0.2 becomes -1). Forcing
floating point ("true") division and then casting to `int` at the end, as I
have done above, means that the rounding is done differently, and that's why
my example above gets the "correct" answer.
|
Python Dictionary value assignment with list comprehension
Question: I would like to take a python dictionary of lists, convert the lists to numpy
arrays, and restore them in the dictionary using list comprehension.
For example, if I had a dictionary
myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
I wish to convert the lists under keys A and B to numpy arrays, but leave the
other parts of the dictionary untouched. Resulting in
myDict = {'A':array[1,2,3,4], 'B':array[5,6,7,8], 'C':'str', 'D':'str'}
I can do this with a for loop:
import numpy as np
for key in myDict:
if key not in ('C', 'D'):
myDict[key] = np.array(myDict[key])
But is it possible to do this with list comprehension? Something like
[myDict[key] = np.array(myDict[key]) for key in myDict if key not in ('C', 'D')]
Or indeed what is the fastest most efficient way to achieve this for a large
dictionaries of long lists. Thanks, labjunky
Answer: With Python 2.7 and above, you can use a [dictionary
comprehension](http://docs.python.org/2/tutorial/datastructures.html#dictionaries):
myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
myDict = {key:np.array(val) if key not in {'C', 'D'} else val for key, val in myDict.iteritems()}
If you're below version 2.7 (and hence don't have dictionary comprehensions),
you can do:
myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
dict((key, np.array(val) if key not in {'C', 'D'} else val for key, val in myDict.iteritems())
|
Migrating Excel financial model to and Corkscrew calculation in Python Pandas
Question: I'm working on replacing an Excel financial model into Python Pandas. By
financial model I mean forecasting a cash flow, profit & loss statement and
balance sheet over time for a business venture as opposed to pricing swaps /
options or working with stock price data that are also referred to as
financial models. It's quite possible that the same concepts and issues apply
to the latter types I just don't know them that well so can't comment.
So far I like a lot of what I see. The models I work with in Excel have a
common time series across the top of the page, defining the time period we're
interested in forecasting. Calculations then run down the page as a series of
rows. Each row is therefore a `TimeSeries` object, or a collection of rows
becomes a `DataFrame`. Obviously you need to transpose to read between these
two constructs but this is a trivial transformation.
Better yet each Excel row should have a common, single formula and only be
based on rows above on the page. This lends itself to vector operations that
are computationally fast and simple to write using Pandas.
The issue I get is when I try to model a corkscrew-type calculation. These are
often used to model accounting balances, where the opening balance for one
period is the closing balance of the prior period. You can't use a `.shift()`
operation as the closing balance in a given period depends, amongst other
things, on the opening balance in the same period. This is probably best
illustrated with an example:
Time 2013-04-01 2013-05-01 2013-06-01 2013-07-01 ...
Opening Balance 0 +3 -2 -10
[...]
Some Operations +3 -5 -8 +20
[...]
Closing Balance +3 -2 -10 +10
In pseudo-code my solution to how to calculate these sorts of things is a
follows. It is not a vectorised solution and it looks like it is pretty slow
# Set up date range
dates = pd.date_range('2012-04-01',periods=500,freq='MS')
# Initialise empty lists
lOB = []
lSomeOp1 = []
lSomeOp2 = []
lCB = []
# Set the closing balance for the initial loop's OB
sCB = 0
# As this is a corkscrew calculation will need to loop through all dates
for d in dates:
# Create a datetime object as will reference it several times below
dt = d.to_datetime()
# Opening balance is either initial opening balance if at the
# initial date or else the last closing balance from prior
# period
sOB = inp['ob'] if (dt == obDate) else sCB
# Calculate some additions, write-off, amortisation, depereciation, whatever!
sSomeOp1 = 10
sSomeOp2 = -sOB / 2
# Calculate the closing balance
sCB = sOB + sSomeOp1 + sSomeOp2
# Build up list of outputs
lOB.append(sOB)
lSomeOp1.append(sSomeOp1)
lSomeOp2.append(sSomeOp2)
lCB.append(sCB)
# Convert lists to timeseries objects
ob = pd.Series(lOB, index=dates)
someOp1 = pd.Series(lSomeOp1, index=dates)
someOp2 = pd.Series(lSomeOp2, index=dates)
cb = pd.Series(lCB, index=dates)
I can see that where you only have one or two lines of operations there might
be some clever hacks to vectorise the computation, I'd be grateful to hear any
tips people have on doing these sorts of tricks.
Some of the corkscrews I have to build, however, have 100's of intermediate
operations. In these cases what's my best way forward? Is it to accept the
slow performance of Python? Should I migrate to Cython? I've not really looked
into it (so could be way off base) but the issue with the latter approach is
that if I'm moving 100's of lines into C why am I bothering with Python in the
first place, it doesn't feel like a simple lift and shift?
Answer: This following makes in-place updates, which should improve performance
import pandas as pd
import numpy as np
book=pd.DataFrame([[0, 3, np.NaN],[np.NaN,-5,np.NaN],[np.NaN,-8,np.NaN],[np.NaN,+20,np.NaN]], columns=['ob','so','cb'], index=['2013-04-01', '2013-05-01', '2013-06-01', '2013-07-01'])
for row in book.index[:-1]:
book['cb'][row]=book.ix[row, ['ob', 'so']].sum()
book['ob'][book.index.get_loc(row)+1]=book['cb'][row]
book['cb'][book.index[-1]]=book.ix[book.index[-1], ['ob', 'so']].sum()
book
|
Python multicore without communication
Question: I want to call a methode getRecommendations which just pickle recommendations
to a specific user to a file. I used a code from a book which works. But I saw
that only one core works and I want that all my cores do the work, because
this would be much faster.
Here is the method.
def getRecommendations(prefs,person,similarity=sim_pearson):
print "working on recommendation"
totals={}
simSums={}
for other in prefs:
# don't compare me to myself
if other==person: continue
sim=similarity(prefs,person,other)
# ignore scores of zero or lower
if sim<=0: continue
for item in prefs[other]:
# only score movies I haven't seen yet
if item not in prefs[person] or prefs[person][item]==0:
# Similarity * Score
totals.setdefault(item,0)
totals[item]+=prefs[other][item]*sim
# Sum of similarities
simSums.setdefault(item,0)
simSums[item]+=sim
# Create the normalized list
rankings=[(total/simSums[item],item) for item,total in totals.items( )]
# Return the sorted list
rankings.sort( )
rankings.reverse( )
ranking_output = open("data/rankings/"+str(int(person))+".ranking.recommendations","wb")
pickle.dump(rankings,ranking_output)
return rankings
It is called via
for i in customerID:
print "working on ", int(i)
#Make this working with multiple CPU's
getRecommendations(pickle.load(open("data/critics.recommendations", "r")), int(i))
as you can see i try to make a recommendation to every customer. Which will be
used later.
So how can i multiprocess this method? I don't get it by reading a few
examples or even the
[documentation](http://docs.python.org/2/library/multiprocessing.html)
Answer: You want something (roughly, untested) like:
from multiprocessing import Pool
NUMBER_OF_PROCS = 5 # some number... not necessarily the number of cores due to I/O
pool = Pool(NUMBER_OF_PROCS)
for i in customerID:
pool.apply_async(getRecommendations, [i])
pool.close()
pool.join()
(this is assuming you only pass 'i' into getRecommendations, since the
pickle.load should only be done once)
|
Python: Unzipping and decompressing .Z files inside .zip
Question: I am trying to unzip a Alpha.zip folder which contains a Beta directory which
contains a Gamma Folder which contains a.Z, b.Z, c.Z, d.Z files. Using zip and
7-zip I was able to extract all a.D, b.D, c.D, d.D files stored within the .Z
files.
I tried this in python using Import gzip and Import zlib.
import sys
import os
import getopt
import gzip
f = open('a.d.Z','r')
file_content = f.read()
f.close()
I keep getting all sorts of errors including: this is not a zip file, return
codecs.charmap_encode(input self.errors encoding_map) 0. Any suggestions as to
how to code this?
Answer: You need to actually make use of a zip library of some kind. Right now you're
importing `gzip`, but you're not doing anything with it. Try taking a look at
the [`gzip` documentation](http://docs.python.org/2/library/gzip) and opening
the file using that library.
gzip_file = gzip.open('a.d.Z') # use gzip.open instead of builtin open function
file_content = gzip_file.read()
Edit based on your comment: you can't just open all kinds of compressed files
with any compression library. Since you have a `.Z` file, it's likely that you
want to use [`zlib`](http://docs.python.org/2/library/zlib.html) rather than
`gzip`, but since extensions are just conventions, only you know for sure what
compression format your file is in. To use `zlib`, do something like this
instead:
# Note: untested code ahead!
import zlib
with open('a.d.Z', 'rb') as f: # Notice that I open this in binary mode
file_content = f.read() # Read the compressed binary data
decompressed_content = zlib.decompress(file_content) # Decompress
|
Django to desktop app with pyinstaller
Question: I'm trying to convert a django project into a desktop app. I've downloaded the
developer version of pyinstaller: github/pyinstaller/pyinstaller.
hookutils.py is modified as stated here:
<http://www.pyinstaller.org/ticket/754> in order for pyinstaller to find my
root directory: _Django root directory c:\Workspace\mysite\mysite_
The project I'm trying to compile is the initial project gotten after running:
_django-admin.py startproject mysite_ , so no apps created yet.
When following the steps as described on pyinstaller
(<http://www.pyinstaller.org/wiki/Recipe/DjangoApplication>) I get some errors
when trying to run the server ( .\dist\mysite\mysite.exe runserver
localhost:8080):
c:\Workspace\compiled>.\dist\mysite\mysite.exe runserver
Traceback (most recent call last):
File "<string>", line 11, in <module>
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management", line 453, in execute_from_command_line
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management", line 392, in execute
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management", line 263, in fetch_command
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management", line 109, in get_commands
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.conf", line 53, in __getattr__
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.conf", line 49, in _setup
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.conf", line 71, in _configure_logging
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.utils.log", line 6, in <module>
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.views.debug", line 11, in <module>
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.http", line 1, in <module>
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.http.cookie", line 5, in <module>
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.utils.six", line 84, in __get__
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.utils.six", line 103, in _resolve
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.utils.six", line 74, in _import_module
ImportError: No module named Cookie
If I then import Cookie in manage.py then, another error appears:
Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x02D86CF0>>
Traceback (most recent call last):
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management.commands.runserver", line 92, in inner_run
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management.base", line 280, in validate
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.core.management.validation", line 35, in get_validation_errors
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.db.models.loading", line 166, in get_app_errors
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.db.models.loading", line 75, in _populate
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.db.models.loading", line 96, in load_app
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.utils.importlib", line 35, in import_module
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.contrib.auth.models", line 18, in <module>
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.contrib.auth.hashers", line 8, in <module>
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.test", line 6, in <module>
File "C:\Workspace\pyinstaller-develop\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "c:\Workspace\compiled\build\mysite\out00-PYZ.pyz\django.test.testcases", line 35, in <module>
ImportError: cannot import name _doctest
I have tried to import doctest, but it doesn't help.
Using python 2.7.4 and django 1.5.1
**Edit:** So by adding django.test and HTMLParser to the manage.py, I got it
to work:
import os
import sys
import Cookie
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OTA.settings")
from django.core.management import execute_from_command_line
import django.test
import HTMLParser
execute_from_command_line(sys.argv)
Answer: Django imports local doctest module. Maybe try `import django.test`?
Also from the PyInstaller docs about including additional modules:
> * You can give additional files on the PyInstaller command line.
> * You can give additional import paths on the command line.
> * You can edit the myscript.spec file that PyInstaller writes the first
> time you run it for your script. In the spec file you can tell PyInstaller
> about code and data files that are unique to your script.
> * You can write "hook" files that inform PyInstaller of hidden imports. If
> you "hook" imports for a package that other users might also use, you can
> contribute your hook file to PyInstaller.
>
I also recommend py2exe, if PyInstaller won't meet Your needs.
|
Append to several lists inside list
Question: I have an empty list of empty lists defined like so:
lis_A = [[], [], []]
to which I need, at some point in my code, to append values recursively like
so:
lis_A[0].append(some_value0)
lis_A[1].append(some_value1)
lis_A[2].append(some_value2)
so it looks like this:
print lis_A
[[some_value0], [some_value1], [some_value2]]
What is the pythonic way of doing this?
Answer:
>>> lis_A = [[], [], []]
>>> vals = [1,2,3]
>>> [x.append(y) for x, y in zip(lis_A, vals)]
>>> lis_A
[[1], [2], [3]]
Or if you wan't a fast for loop without side effects use:
from itertools import izip
for x, y in izip(lis_A, vals):
x.append(y)
|
Python - Process Disappearing and Freezing when working with large Dict?
Question: I'm in the process of dealing with XML files that are about 85MB in size.
Currently I'm just trying to process one. What I'm doing is download a zip,
extract to disk, then convert the XML to a Python Dict, change a couple
things, then save the Dict, and send it to a MongoDB. Except when I get to
converting to a Python dict, process freezes/disappears..
I'm running this script on a VM with Ubuntu 13.04 Server, 4 cores at 2.6, 16GB
of ram, and a 1TB 15,000RPM. I'm monitoring the script as it runs, essentially
python takes up 12% of RAM over 7 minutes, and then gone, process falls off my
high usage list and my pipe from the terminal just doesn't move. I kill it
with CTRL+Z and get returned _"Write failed: Broken pipe"_.
The last thing printed on terminal is **"Converting
dailyprice_0505_eur.xml.zip"** , which makes me suspect something maybe with
xmltodict, but I'm honestly stuck. The example code, with data, should work
for anyone who willing to help me test this out. Any help is appreciated!
Thanks.
#Importing
import urllib, xmltodict, os
from zipfile import ZipFile
#Getting Working Dir
abspath = os.path.abspath(__file__)
root = os.path.dirname(abspath) + "/"
print "Current Working Directory: " + root
#Defining
urlAuth = 'https://dl.dropboxusercontent.com/u/9235267/'
dailypriceFL = ['dailyprice_0505_eur.xml.zip']
dailyPriceDict = {}
for x in dailyPriceFL:
print ' * Downloading',x
urllib.urlretrieve(urlAuth+x, x)
print ' * Extracting',x
with ZipFile(x, "r") as z:
z.extractall(root)
print ' * Converting',x
f = open(root+x.replace(".zip",""))
data = xmltodict.parse(f.read())
f.close()
print ' * Adding Currency to Dict',x
for y in data['prices']['price']:
y.update({"currency": x[-7:].replace(".xml","").upper()})
print ' * Ammending',x
dailyPriceDict.update(data)
print ' * Deleting',x
os.remove(root+x)
os.remove(root+x.replace(".zip",""))
print ' * Finished',x
Answer: I wonder if it's not a memory error despite the specs you listed. When I
attempt to load your XML just in `xml.dom.minidom` I get this:
Traceback (most recent call last):
File "c:\python27\lib\xml\dom\minidom.py", line 1930, in parseString
return expatbuilder.parseString(string)
File "c:\python27\lib\xml\dom\expatbuilder.py", line 940, in parseString
return builder.parseString(string)
File "c:\python27\lib\xml\dom\expatbuilder.py", line 223, in parseString
parser.Parse(string, True)
File "c:\python27\lib\xml\dom\expatbuilder.py", line 751, in start_element_handler
node = minidom.Element(qname, uri, prefix, localname)
File "c:\python27\lib\xml\dom\minidom.py", line 653, in __init__
self._attrs = {} # attributes are double-indexed:
MemoryError
This does seem to work on my side of things though:
>>> import xmltodict, os
>>> data = open('price.xml').read()
>>> xml = xmltodict.parse(data)
>>> xml['prices']['price'][0]
OrderedDict([(u'code', u'AD1550.301.1'),
(u'startdate', u'2013-08-24'),
(u'enddate', u'2013-09-30'),
(u'rentalprice', u'126.00'),
(u'midweekrentalprice', u'0.00'),
(u'weekendrentalprice', u'0.00'),
(u'fixprice', u'0.00')])
That does take nearly 800Mb on my system, but I don't seem to get errors.
However, if I try to parse it into xmltodict _after_ I've attempted to use
minidom, I get something more like this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\site-packages\xmltodict.py", line 228, in parse
parser.Parse(xml_input, True)
xml.parsers.expat.ExpatError: out of memory: line 1, column 0
Which suggests rather directly that, because both are based on `expat`,
something is not getting freed up between runs of your script (or iterations
of your loop), and you'll need to refactor somehow.
|
importing system in python - import packages
Question: When I have the following packages:
src
/__main__.py
/dir1
/__init__.py
/main_code1.py
/service.py
/config.py
/dir2
/__init__.py
/maincode2.py
/dir3
/__init__.py
/maincode3.py
What is the difference between using the following statement in the file
`__main__.py`
import dir1
&
from dir1 import *
&
from dir1 import main_code1
The second question is: How to import maincode3.py (present in dir3) to the
maincode.py script present in dir1? I am searching for way without changing
sys.path list.
Answer:
import dir1
Imports dir1's `__init__.py`. You can access whatever is there using
`dir1.my_var_from_dir1_init`. You cannot access the modules, only what's on
dir1's `__init__`.
from dir1 import *
Imports the modules specified on the `__all__` variable defined on dir1's
`__init__.py`. If there isn't such variable, then it imports all of dir1's
modules. You can access them directly, like `main_code1.myvar`.
from dir1 import maincode
Assuming it's a typo and you actually have a `maincode` module or class, it
imports the `maincode` module/class from dir1. You can access it directly like
mentioned above.
Note that each option imports dir1's `__init__.py`, implicitly or explicitly.
If you import the modules on `__init__.py`, then using `import dir1` will
allow you to use `dir1.module`.
* * *
To import dir3's `maincode3` to `maincode.py`, simply use `from dir3 import
maincode3`. Just be careful with circular imports, which will generate an
import error. You can also take a look on [relative
imports](http://stackoverflow.com/questions/72852/how-to-do-relative-imports-
in-python).
|
How to remove insignificant whitespace in lxml.html?
Question: I'm rather surprised that lxml.html leaves insignificant whitespace when
parsing HTML by default. I'm also surprised that I can't find any obvious way
to make it not do that.
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml.etree
>>> parser = lxml.etree.HTMLParser(remove_blank_text=True)
>>> html = lxml.etree.HTML("<p> Hello World </p>", parser=parser)
>>> print lxml.etree.tostring(html)
<html><body><p> Hello World </p></body></html>
I expect the result would be something like:
>>> print lxml.etree.tostring(html)
<html><body><p>Hello World</p></body></html>
BeautifulSoup4 does the same thing with the html5lib parser:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("<p> Hello World </p>", "html5lib")
>>> soup.p
<p> Hello World </p>
After doing some research, I found that the HTML5 parsing specification does
not specify to remove consecutive whitespace; that is done at render time
instead. So I understand that's it technically not the responsibility of any
of these libraries to perform the same behavior, but it seems useful enough
that I'm surprised none of them have it anyway.
Can somebody prove me wrong?
Edit:
I know how to remove whitespace using a regex — that was not my question. (I
also know how to search SO for questions about regex.)
My question has to do with the _insignificant_ whitespace, where
_significance_ is defined by the standards for rendering HTML. I doubt that a
1-liner regex can correctly implement this standard. And let's not even delve
into the regex vs CFG debate again, please?
[RegEx match open tags except XHTML self-contained
tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-
xhtml-self-contained-tags)
Edit 2:
In case it's not clear from the context, I am interested in HTML, not
XHTML/XML. Whitespace does have some non-trivial rules of significance in
HTML, however those rules are implemented in the renderer, not the parser. I
understand that, as evidenced in my initial post. My question is whether
anybody has implemented the white space logic of an HTML renderer in a library
that operates at the DOM level rather than at the rendering level?
Answer: I came across this
[library](https://htmlmin.readthedocs.org/en/latest/index.html).
Can be installed with pip:
pip install htmlmin
It's used like:
from htmlmin import minify
html=u"<html><body><p> Hello World </p></body></html>"
minified_html = minify(html)
print minified_html
Which returns:
<html><body><p> Hello World </p></body></html>
I thought it would do what you were looking for, but as you see, some
irrelevant spaces were kept.
|
Django error while template rendering: NoReverseMatch found
Question: The following piece of code is throwing an error. I searched for the solution,
but couldn't find anything which is pertaining to my scenario. Any help would
be appreciated.
#urls.py
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)\/(?P<token>.+)/$',
app_name.password_reset_confirm,name='auth_password_reset_confirm'),
I need to render an email template as a string in my view.
#views.py
from django.template import Context, loader
t = loader.get_template('app_name/email.html')
message = t.render(Context({"domain":"foo.com","protocol":"https"}))
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
Following is the html file, simplified for SO:
{% load i18n %}{% autoescape off %}
<html>
<body>
{% block reset_link %}<br />
<a href="{{ protocol }}://{{ domain }}/accounts/password/reset/confirm/{{uid}}/{{token}}">{{ protocol }}://{{ domain }}/accounts/password/reset/confirm/{{uid}}/{{token}}</a>
<br />
{% endblock %}
{% trans "Thanks for using our product!" %}<br /><br />
{% blocktrans %}Regards, <br />{{ site_name }} team{% endblocktrans %}
</body>
</html>
{% endautoescape %}
Error Traceback:
NoReverseMatch Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 message = t.render(Context({"domain":"foo.com","protocol":"https"}))
/usr/local/lib/python2.7/dist-packages/django/template/base.pyc in render(self, context)
138 context.render_context.push()
139 try:
--> 140 return self._render(context)
141 finally:
142 context.render_context.pop()
/usr/local/lib/python2.7/dist-packages/django/template/base.pyc in _render(self, context)
132
133 def _render(self, context):
--> 134 return self.nodelist.render(context)
135
136 def render(self, context):
/usr/local/lib/python2.7/dist-packages/django/template/base.pyc in render(self, context)
828 for node in self:
829 if isinstance(node, Node):
--> 830 bit = self.render_node(node, context)
831 else:
832 bit = node
/usr/local/lib/python2.7/dist-packages/django/template/debug.pyc in render_node(self, node, context)
72 def render_node(self, node, context):
73 try:
---> 74 return node.render(context)
75 except Exception as e:
76 if not hasattr(e, 'django_template_source'):
/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.pyc in render(self, context)
31 old_setting = context.autoescape
32 context.autoescape = self.setting
---> 33 output = self.nodelist.render(context)
34 context.autoescape = old_setting
35 if self.setting:
/usr/local/lib/python2.7/dist-packages/django/template/base.pyc in render(self, context)
828 for node in self:
829 if isinstance(node, Node):
--> 830 bit = self.render_node(node, context)
831 else:
832 bit = node
/usr/local/lib/python2.7/dist-packages/django/template/debug.pyc in render_node(self, node, context)
72 def render_node(self, node, context):
73 try:
---> 74 return node.render(context)
75 except Exception as e:
76 if not hasattr(e, 'django_template_source'):
/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.pyc in render(self, context)
52 if block_context is None:
53 context['block'] = self
---> 54 result = self.nodelist.render(context)
55 else:
56 push = block = block_context.pop(self.name)
/usr/local/lib/python2.7/dist-packages/django/template/base.pyc in render(self, context)
828 for node in self:
829 if isinstance(node, Node):
--> 830 bit = self.render_node(node, context)
831 else:
832 bit = node
/usr/local/lib/python2.7/dist-packages/django/template/debug.pyc in render_node(self, node, context)
72 def render_node(self, node, context):
73 try:
---> 74 return node.render(context)
75 except Exception as e:
76 if not hasattr(e, 'django_template_source'):
/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.pyc in render(self, context)
422 # the path relative to the project. This makes a
423 # better error message.
--> 424 raise e
425 else:
426 if self.asvar is None:
NoReverseMatch: Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{u'uidb36': '', u'token': ''}' not found.
Answer: As FoxMaSk has commented you should replace:
{{ protocol }}://{{ domain }}/accounts/password/reset/confirm/{{uid}}/{{token}}
with:
{{ protocol }}://{{ domain }}{% url 'auth_password_reset_confirm' uid36=uid token=token %}
Note the single quotes around the view name in the url, this is required in
Django 1.5+ (not sure what version you are using).
More importantly I believe the error lies here:
message = t.render(Context({"domain":"foo.com","protocol":"https"}))
You are not passing your uid or token into the context when rendering the
template which is why you are seeing empty values in the traceback message for
these variables:
NoReverseMatch: Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{u'uidb36': '', u'token': ''}' not found.
|
How to make a text dialogue appear in wxpython
Question: I have been looking around the web since early morning and I can't seem to
figure out how to get wxPython to show a dialogue box on my main frame.
import wx
class MainWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Window',size=(400,300))
panel = wx.Panel(self)
test = wx.TextEntryDialog(panel, 'Enter your word:',"New word","",
style=wx.OK|wx.CANCEL|wx.CENTRE,pos=(100,200))
def main():
pass
if __name__ == '__main__':
app = wx.App()
frame=MainWindow(parent=None,id=1)
frame.Show()
app.MainLoop()
It just opens a window without a text dialogue.
Answer: Use:
Dlg = wx.TextEntryDialog(panel, 'Enter your word:',"New word","",
style=wx.OK|wx.CANCEL|wx.CENTRE,pos=(100,200))
if Dlg.ShowModal() == wx.OK:
test = Dlg.GetValue()
del Dlg
As wx.TextEntryDialog is a dialogue class **not** one of the convenience
dialogue functions **_you_** need to show it and get the value rather than
just getting a reply.
|
strange result in using python's property
Question: I spent some time to learn Python's property magic. But when I am writing a
simple case with a small mistake, I get a strange result. Here is my code:
class PropertyShow(object):
def __init__(self):
self.__num = 90
def setNum(self,value):
self.__num = value
def getNum(self):
return self.__num
def delNum(self):
del self.__num
#num = property(getNum,setNum,delNum)
# I made a mistake here!
__num = property(getNum,setNum,delNum)
class PropertyTwo(object):
def __init__(self):
self.__num = None
@property
def num(self):
"""OK, use a decorator, you can do something here!"""
return self.__num
@num.setter
def num(self,value):
self.__num = value
@num.deleter
def num(self):
del self.__num
one = PropertyShow()
print one.num
two = PropertyTwo()
print two.num
In the key line, "num = property(getNum,setNum,delNum)". I changed this line
to this careless, now like this "__num = property(getNum,setNum,delNum)".
The result of this code:
File "property.py", line 6, in setNum
self.__num = value
RuntimeError: maximum recursion depth exceeded
1. Why do I get this unexpected result when replacing `num` to `__num`?
2. How to understand the magic of `property()` and why should one use private variables?*
Answer: The line `self.__num = value` results in the property setter being invoked.
The property setter tries to set `self.__num`, which results in the property
setter being invoked. The property setter tries to set `self.__num`, which
results in the property setter being invoked. The property setter tries to set
`self.__num`, which results in the property setter being invoked. The property
setter tries to set `self.__num`, which results in the property setter being
invoked. The property setter tries to set `self.__num`, which results in the
property setter being invoked. The property setter tries to set `self.__num`,
which results in the property setter being invoked. The property setter tries
to set `self.__num`, which results in the property setter being invoked. The
property setter tries to set `self.__num`, which results in the property
setter being invoked.
Infinite recursion detected.
When your property is _not_ named `__num`, this obviously does not happen.
To be explicit: Python sees the line `self.__num = value` as a `STORE_ATTR`
opcode:
>>> import dis
>>> def setNum(self, value):
... self.__num = value
...
>>> dis.dis(setNum)
2 0 LOAD_FAST 1 (value)
3 LOAD_FAST 0 (self)
6 STORE_ATTR 0 (__num)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
The implementation for `STORE_ATTR` will first look for a data descriptor on
the class, and finds your `__num` `property` object. The call is then
effectively translated to:
PropertyShow.__num.__set__(self, value)
The `property` object looks up the configured setter function, which is
`PropertyShow.setNum` and calls it as `PropertyShow.setNum(self, value)`. This
in turn calls `self.__num = value` again and recursion takes over from there.
|
python if $_GET is empty do something & url path
Question:
import cgi
form = cgi.FieldStorage()
test = form['name'].value
if test is None:
print('empty')
else:
print ('Hello ' + test)
... and that doesn't seem to display anything when my url is something like
.../1.py
if i set it to .../1.py?name=asd it will display `Hello asd`
also how to get everything after the question mark and after the domain name:
for example if i try to access `http://localhost/thisis/test` i want to get
`/thisis/test`.
edit: i tried to use `try:` and i couldn't get it working.
Answer: To answer the first part of my question, i found what the problem is and
that's the correct code:
import cgi
form = cgi.FieldStorage()
try:
test = form['name'].value
except KeyError:
print('not found')
else:
print(test)
for my second question:
import os
print(os.environ["REQUEST_URI"])
|
How to include python-dateutil in Google App Engine?
Question: How can I use the `python-dateutil` library in Google App Engine? I am using
the `webapp2` framework and need to know how to include the library and use it
in my script.
Answer: EDIT2: Here's the recommended way to do this now:
<https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring>
~~EDIT: Thanks to @TimHoffman, the correct (App Engine) way to do this is
documented[here](https://developers.google.com/appengine/docs/python/tools/appengineconfig#Configuring_Your_Own_Modules).
Ignore what I said below.
I've actually had to do this exact thing. First, I created a folder in my app
project called 'lib' to hold any python libraries that aren't included with
App Engine (for project organization). Then, I downloaded the dateutil python
source and placed it in the new 'lib' folder. Finally, in your actual app
code, before importing the desired libraries, you must add this line:
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
which just places the 'lib' folder in the python path so that python knows
where the module actually is. Then simply:
import dateutil
Alternatively, you could just put the module code directly in your app folder,
and python will automatically look in your program's folder for the module.
Also, make sure it's included somewhere in your app.yaml so that it actually
gets uploaded to google's servers.
The key, though, is that you must include the code for the module somewhere
with your app.~~
|
Use regex to add string to different multilines with simularities
Question: I have a .txt file with multiple lines (Different yet simular for each one)
that I want to add a "*.tmp" at the end.
I'm trying to use python2.7 regex to do this.
Here is what I have for the python script:
import sys
import os
import re
import shutil
#Sets the buildpath variable to equal replace one "\" with two "\\" for python code to input/output correctly
buildpath = sys.argv[1]
buildpath = buildpath.replace('\\', '\\\\')
#Opens a tmp file with read/write/append permissions
tf = open('tmp', 'a+')
#Opens the selenium script for scheduling job executions
with open('dumplist.txt') as f:
#Sets line as a variable for every line in the selenium script
for line in f.readlines():
#Sets build as a variable that will replace the \\build\path string in the line of the selenium script
build = re.sub (r'\\\\''.*',''+buildpath+'',line)
#Overwrites the build path string from the handler to the tmp file with all lines included from the selenium script
tf.write(build)
#Saves both "tmp" file and "selenium.html" file by closing them
tf.close()
f.close()
#Copies what was re-written in the tmp file, and writes it over the selenium script
shutil.copy('tmp', 'dumplist.txt')
#Deletes the tmp file
os.remove('tmp')
#exits the script
exit()
Current File Before Replacing the Line:
\\server\dir1\dir2\dir3
DUMP3f2b.tmp
1 File(s) 1,034,010,207 bytes
\\server\dir1_1\dir2_1\dir3_1
DUMP3354.tmp
1 File(s) 939,451,120 bytes
\\server\dir1_2\dir2_2\dir3_2
Current file after replacing string:
\*.tmp
DUMP3f2b.tmp
1 File(s) 1,034,010,207 bytes
\*.tmp
DUMP3354.tmp
1 File(s) 939,451,120 bytes
\*.tmp
Desired file after replacing string:
\\server\dir1\dir2\dir3\*.tmp
DUMP3f2b.tmp
1 File(s) 1,034,010,207 bytes
\\server\dir1_1\dir2_1\dir3_1\*.tmp
DUMP3354.tmp
1 File(s) 939,451,120 bytes
\\server\dir1_2\dir2_2\dir3_2\*.tmp
If anyone could help me in solving this that would be great. Thanks :)
Answer: You should use capturing groups:
>>> import re
>>> s = "\\server\dir1\dir2\dir3"
>>> print re.sub(r'(\\.*)', r'\\\1\*.tmp', s)
\\server\dir1\dir2\dir3\*.tmp
Then, modify `build = re.sub (r'\\\\''.*',''+buildpath+'',line)` line this
way:
build = re.sub (r'(\\.*)', r'\\\1%s' % buildpath, line)
Also, you shouldn't call `readlines()`, just iterate over `f`:
for line in f:
|
Python to C++ Program Questions
Question: It's my second week of my junior year of college and my professor has given me
the assignment of taking a python program, which i'm very familiar with, and
turning it into a C++ program. I know next to nothing about C++ having only
had 1 lecture on the topic and my book not arriving for another couple days.
Here is the python program..
import random
import sys
import time
print( "BATTLE GAME" );
done = False
combatRound = 0
playerHP = 20
playerAtk = random.randint( 5, 8 )
playerDef = random.randint( 5, 8 )
playerAgi = random.randint( 5, 8 )
enemyHP = 20
enemyAtk = random.randint( 5, 7 )
enemyDef = random.randint( 5, 7 )
enemyAgi = random.randint( 5, 7 )
delayLength = 0.5
print()
print( "-------------" )
print( "FIGHTER STATS" )
print( "-------------" )
print()
print( "PLAYER STATS:" )
print( "HP " + str( playerHP ) )
print( "ATK " + str( playerAtk ) )
print( "DEF " + str( playerDef ) )
print( "AGI " + str( playerAgi ) )
print()
print( "ENEMY STATS:" )
print( "HP " + str( enemyHP ) )
print( "ATK " + str( enemyAtk ) )
print( "DEF " + str( enemyDef ) )
print( "AGI " + str( enemyAgi ) )
print()
choice = input( "Ready to begin? (yes/no) " )
while ( choice != "yes" ):
print( "Well, what are you waiting for? \n" )
choice = input( "Ready to begin? (yes/no) " )
while ( done == False ):
combatRound += 1
print()
print( "###########################################" )
print( "-------------------------------------------" )
print( "ROUND " + str( combatRound ) )
print( "PLAYER:\t HP " + str( playerHP ) + " ATK " + str( playerAtk ) + " DEF " + str( playerDef ) + " AGI " + str( playerAgi ) )
print( "ENEMY:\t HP " + str( enemyHP ) + " ATK " + str( enemyAtk ) + " DEF " + str( enemyDef ) + " AGI " + str( enemyAgi ) )
print( "-------------------------------------------" )
print( "1. Quick Attack" )
print( "2. Standard Attack" )
print( "3. Heavy Attack" )
playerChoice = input( "What will you do? " )
playerChoice = int( playerChoice )
while ( playerChoice < 1 or playerChoice > 3 ):
playerChoice = input( "Invalid choice, choose between 1 and 3: " )
playerChoice = int( playerChoice )
enemyChoice = random.randint( 1, 3 )
print( "Enemy chooses option " + str( enemyChoice ) )
print( "-------------------------------------------" )
# Adjust player and enemy stats based on the type of attack they're doing
adjustedPlayerAtk = playerAtk
adjustedPlayerAgi = playerAgi
adjustedEnemyAtk = enemyAtk
adjustedEnemyAgi = enemyAgi
if ( playerChoice == 1 ):
adjustedPlayerAgi += 2
adjustedPlayerAtk -= 1
elif ( playerChoice == 3 ):
adjustedPlayerAgi -= 1
adjustedPlayerAtk += 2
if ( enemyChoice == 1 ):
adjustedEnemyAgi += 2
adjustedEnemyAtk -= 1
elif ( enemyChoice == 3 ):
adjustedEnemyAgi -= 1
adjustedEnemyAtk += 2
# Begin battle
print( "PLAYER attacks ENEMY!" )
time.sleep( delayLength )
randDiff = random.randint( 0, adjustedPlayerAgi )
time.sleep( delayLength )
if ( randDiff >= 1 ):
# Calculate damage
damage = int( adjustedPlayerAtk - enemyDef / 2 )
print( "PLAYER hits ENEMY for " + str( damage ) + " damage!" )
enemyHP -= damage
else:
print( "PLAYER misses!" )
time.sleep( delayLength )
print( "ENEMY attacks PLAYER!" )
time.sleep( delayLength )
randDiff = random.randint( 0, adjustedEnemyAgi )
time.sleep( delayLength )
if ( randDiff >= 1 ):
# Calculate damage
damage = int( adjustedEnemyAtk - playerDef / 2 )
print( "ENEMY hits PLAYER for " + str( damage ) + " damage!" )
playerHP -= damage
else:
print( "ENEMY misses!" )
time.sleep( delayLength )
# Check to see if either player is knocked out
if ( playerHP <= 0 ):
print( "PLAYER has fallen!" )
done = True
elif ( enemyHP <= 0 ):
print( "ENEMY has fallen!" )
done = True
# Game main loop
# At this point, either player or enemy has fallen.
print()
print( " ##################################### " )
print( " #### ####" )
print( "# G A M E O V E R #" )
print( "# ######################################### #" )
print( "## ##" )
print()
if ( playerHP <= 0 ):
print( "Too bad, you lose!" )
elif ( enemyHP <= 0 ):
print( "Congratulations, you won!" )
And here is my C++ code
#include <iostream>
#include <string>
#include <random>
using namespace std;
int playerHP = 20, int enemyHP = 20;
int playerAtk =random.randint(5,8); //How do you do random in C+++
int playerDef = random.randint(5,8);
int playerAgi = random.randint(5,8);
int enemyAtk = random.randint(5,7);
int enemyDef = random.randint (5,7);
int enemyAgi = random.randint (5,7);
float delayLength=.5;
cout<<"---------------"<< endl;
cout<<"FIGHTER STATS"<< endl;
cout<<"----------------"<<endl;
cout<<"Player Stats:"<<endl;
cout<<"HP "<<playerHP<<endl;
cout<<"ATK "<<playerAtk<<endl;
cout<<"DEF "<<playerDef<<endl;
cout<<"AGI "<<playerAgi<<endl;
cout<<"ENEMY STATS:"<<endl;
cout<<"HP "<<enemyHP<<endl;
cout<<"ATK "<<enemyAtk<<endl;
cout<<"DEF "<<enemyDef<<endl;
cout<<"AGI "<<enemyAgi<<endl;
while (playerHP>0 || enemyHP>0)
{
int combatRound=0;
int playerChoice;
int enemyChoice;
int adjustedPlayerAtk;
int adjustedPlayerAgi;
int adjustedEnemyAtk;
int adjustedEnemyAgi;
int randDiff;
int damage;
int damage2;
int randDiff2
combatRound +=1
cout<<""<<endl;
cout<<"############################"<<endl;
cout<<"----------------------------"<<endl;
cout<<"Round "<<combatRound<<endl;
cout<<"Player:"<<playerHP<<playerAtk<<playerAgi<<endl;
cout<<"Enemy:"<<enemyHP<<enemyAtk<<enemyAgi<<endl;
cout<<"----------------------------"<<endl;
cout<<"1. Quick Attack"<<endl;
cout<<"2. Standard Attack"<<endl;
cout<<"3. Heavy Attack"<<endl;
cout<<"What will you do? "<<endl;
cin>>playerChoice;
while playerChoice != 1 || 2 || 3
cout<<"Invalid choice, choose between 1 and 3:"<<endl;
cout<<"What will you do?"<<endl;
cin>>playerChoice;
enemyChoice=random.randint (1,3);
cout<< "Enemy chooses option "<<enemyChoice<<endl;
cout<<"--------------------------------"<<endl;
if playerChoice ==1
adjustedPlayerAgi +=2
adjustedPlayerAtk -=1
if playerChoice ==3
adjustedPlayerAgi -=1
adjustedPlayerAtk +=2
if enemyChoice ==1
adjustedEnemyAgi += 2
adjustedEnemyAtk -= 1
if enemyChoice ==3
adjustedEnemyAgi -= 1
adjustedEnemyAtk += 2
cout<<"PLAYER attacks ENEMY!"<<endl;
time.sleep( delayLength ) //How do you do this in C++?
randDiff = random.randint(0, adjustedPlayerAgi)
time.sleep(delayLength)
if randDiff >=1
damage=(adjustedPlayerAtk-enemyDef/2)
enemyHP -= damage
else
cout<<"PLAYER misses!"<<endl;
time.sleep (delayLength)
cout<<"ENEMY attacks PLAYER!"<<endl;
time.sleep(delayLength)
randDiff2= random.randint( 0,adjustedEnemyAgi)
time.sleep(delayLength)
if randDiff >=1
damage2= (adjustedEnemyAtk - playerDef/2)
cout<<"ENEMY hits PLAYER for "<<damage2<<"damage!"<<endl;
playerHP -= damage2
else
cout<<"ENEMY misses!"<<endl;
time.sleep (delayLength)
}
cout<<""<<endl;
cout<<"GAME OVER"<<endl;
if playerHP <=0
cout<<"Too bad you lose"<<endl;
if enemyHP <=0
cout<<"YOU WON"<<endl;
I honestly have no idea how correct or how wrong it is. I'm currently writing
it in notepad because the professor hasn't given us access to Visual Studios.
Any tips, tricks, or advice is EXTREMELY appreciated. Once again I apologize
for how nasty it looks but I really did do my best on it and I can't wait to
learn more about this new and exciting language.
Answer: To do random numbers in C++:
rand() % 10 + 1
That will give you a random value between 1 and 10. `rand()` will give a
random number from 0, to `RAND_MAX` (32727); so use maths to turn all the
numbers into the range you want.
Also:
Make sure you use `;` at the end
`combatRound +=1` is one example of where you didn't.
Also make sure you use `(` and `)`
`if playerChoice == 1` is an example of where you didn't.
And: `while playerChoice != 1 || 2 || 3`
should be
`while( playerChoice != 1 && playerChoice != 2 && playerChoice != 3 )`
And finally:
To delay in C++:
If you use Windows (Also use `include <windows.h>`): `Sleep()` and use
milliseconds
And if you use UNIX use `sleep` and it is in seconds(use `include
<unistd.h>`).
|
PyGTK, "do-configure-event" doesn't work?
Question: The title of the window doesn't display event.x && event.y (see the code :D) .
I discover the method do_configure_event doesn't been called.
new to pygtk, many thx! :D
#!/usr/bin/env python2.7
# encoding:utf8
# sources: zetcode
import gtk
import gobject
class pyapp:
__gsignals__ = {
"configure-event" : "override"
}
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", gtk.main_quit)
self.window.set_size_request(350,200)
self.window.show_all()
def do_configure_event(self, event):
title = "%s, %s" % ( event.x, event,y)
self.window.set_title(title)
gtk.Window.do_configure_event(self, event)
pyapp()
gtk.main()
Answer: _Name your sources!_ It seems you're trying to adapt example code from
[Zetcode](http://zetcode.com/gui/pygtk/signals/) you do not fully comprehend.
Your problem is: to put your class attribute `__gsignals__` into use, you have
to derive from `gtk.Window`. The window instance looks up the signals and
therefore its gsignals dictionary has to be filled. At the moment, this
dictionary resides in `pyapp`.
|
Watermark GIF with Python PIL
Question: I'm trying to find a way to watermark a gif image, below is my code:
img = Image.open("my.gif")
watermark = Image.open("watermark.gif")
img.paste(watermark, (1, 1))
img.save("out.gif")
File: my.gif:

File: watermark.gif:

the output "out.gif" is no longer animated, it shows one frame with the
watermark: 
I know that PIL supports the GIF format, so I must be doing something wrong.
All help is appreciated.
Answer: Animated GIFs are actually a sequence of images with rules and times for
switching between them you need to modify all of them and output all of them -
you can use [images2gif](http://i.stack.imgur.com/Khnut.gif) for this - or you
can do a lot of work yourself.
Example of using images2gif, after downloading from the above link:
from PIL import Image
import images2gif as i2g
images = i2g.readGif('Animated.gif', False)
watermark = Image.open("Watermark.gif")
for i in images: i.paste(watermark, (1, 1))
i2g.writeGif('Out.gif', images, 0.5) # You may wish to play with the timing, etc.
exit()
And the results: 
|
Python extracting sentence containing 2 words
Question: I have the same problem that was discussed in this link [Python extract
sentence containing word](http://stackoverflow.com/questions/16032832/python-
extract-sentence-containing-word), but the difference is that I want to find 2
words in the same sentence. I need to extract sentences from a corpus, which
contains 2 specific words. Does anyone could help me, please?
Answer: This would be simple using the
[TextBlob](https://textblob.readthedocs.org/en/latest/) package together with
Python's builtin [sets](http://docs.python.org/2/library/sets.html).
Basically, iterate through the sentences of your text, and check if their
exists an intersection between the set of words in the sentence and your
search words.
from text.blob import TextBlob
search_words = set(["buy", "apples"])
blob = TextBlob("I like to eat apple. Me too. Let's go buy some apples.")
matches = []
for sentence in blob.sentences:
words = set(sentence.words)
if search_words & words: # intersection
matches.append(str(sentence))
print(matches)
# ["Let's go buy some apples."]
Update: Or, more Pythonically,
from text.blob import TextBlob
search_words = set(["buy", "apples"])
blob = TextBlob("I like to eat apple. Me too. Let's go buy some apples.")
matches = [str(s) for s in blob.sentences if search_words & set(s.words)]
print(matches)
# ["Let's go buy some apples."]
|
split a dataset in two sets of rows depending on specific column value [python, unix]
Question: I have a data set with rows and columns saved as a tab-delimited text format.
I would like to divide this data set into two smaller data sets depending on
whether or not column[x] has a certain value.
Here is an example of the data set (there are no headers): dataset.txt
test1 abc 1
test2 efg 2
test3 hdh 1
test4 xyz 24
The expected outputs should look like this: dataset1.txt
test1 abc 1
test3 hdh 1
dataset2.txt
test2 efg 2
test4 xyz 24
I would like to implement this with import sys so that I can input the
filename of the original dataset as a unix command with and specify the output
option I want. In this case, I will define an option called "unique" to output
dataset1.txt and an option "multi" to output dataset2.txt. The command line
should look like this:
python code.py [option] [filename] > [output]
e.g.
python code.py unique dataset.txt > dataset1.txt
python code.py multi dataset.txt > dataset2.txt
Here is the code I wrote:
import sys
option = sys.argv[1]
filename = sys.argv[2]
options = ['unique','multi']
def out_unique(data):
for row in data:
if column[2] == 1:
print row
def out_multi(data):
for row in data:
if column[2] != 1:
print row
if option == 'unique':
out_unique(filename)
elif option == 'multi':
out_multi(filename)
else:
print 'available options:', options
Here is the error I get:
Traceback (most recent call last):
File "out_if_col.py", line 23, in <module>
out_unique(filename)
File "out_if_col.py", line 13, in out_unique
if column[3] == 1:
NameError: global name 'column' is not defined
I am aware that this may look fairly ridiculous to the experts out there, but
it's my first time trying to get something done in python. To be honest I
spent a fair amount of time writing the above code, and have come to a point
where I would appreciate it if someone would point out what I am getting
wrong.
Answer: Your script with corrections:
import sys
option = sys.argv[1]
filename = sys.argv[2]
options = ['unique','multi']
def out_unique(data):
for row in data.readlines():
column = row.strip().split()
if column[2] == 1:
print row
def out_multi(data):
for row in data.readlines():
column = row.strip().split()
if column[2] != 1:
print row
if option == 'unique':
out_unique(open(filename, 'r'))
elif option == 'multi':
out_multi(open(filename, 'r'))
else:
print 'available options:', options
The same but with comprehensive lists (IMHO looks more pythonic):
import sys
option = sys.argv[1]
filename = sys.argv[2]
options = ['unique','multi']
def out_unique(data):
print '\n'.join(row for row in data.readlines() if row.strip().split()[2] == '1')
def out_multi(data):
print '\n'.join(row for row in data.readlines() if row.strip().split()[2] != '1')
if option == 'unique':
out_unique(open(filename, 'r'))
elif option == 'multi':
out_multi(open(filename, 'r'))
else:
print 'available options:', options
|
pythonic equivalent this sed command
Question: I have this awk/sed command
awk '{full=full$0}END{print full;}' initial.xml | sed 's|</Product>|</Product>\
|g' > final.xml
to break an XML doc containing large number of tags such that the new file
will have all contents of the product node in a single line
I am trying to run it using os.system and subprocess module however this is
wrapping all the contents of the file into one line.
Can anyone convert it into equivalent python script? Thanks!
Answer: Something like this?
from __future__ import print_function
import fileinput
for line in fileinput.input('initial.xml'):
print(line.rstrip('\n').replace('</Product>','</Product>\n'),end='')
I'm using the `print` function because the default `print` in Python 2.x will
add a space or newline after each set of output. [There are various other ways
to work around that](http://stackoverflow.com/questions/4499073/printing-
without-newline-print-a-prints-a-space-how-to-remove), some of which involve
buffering your output before printing it.
For the record, your problem could equally well be solved in just a simple Awk
script.
awk '{ gsub(/<Product>/,"&\n"); printf $0 }' initial.xml
Printing output as it arrives without a trailing newline is going to be a lot
more efficient than buffering the whole file and then printing it at the end,
and of course, Awk has all the necessary facilities to do the substition as
well. (`gsub` is not available in all dialects of Awk, though.)
|
Django: Get all model instances of top level category
Question: I've got a heirarchy like so:
Parent Cat
Sub Cat
Item
Sub Cat
Item
Item
Parent Cat
...
Having the name/instance of a parent category I'd like to get all items which
are related to the parent cat. I'm currently using Django-Categories which
makes use of Django-MTPP but I can't figure out how to do this without
building the for loops myself. Thought the whole point of these packages were
so I wouldn't have to do that.
My models look like:
class Item(models.Model):
title = models.TextField() # `null` and `blank` are false by default
category = models.ForeignKey('ProductCategory')
price = ....
def __unicode__(self): # Python 3: def __str__(self):
return self.title
from categories.models import CategoryBase
class ProductCategory(CategoryBase):
class Meta:
verbose_name_plural = 'simple categories'
I've tried doing:
parent_category = ProductCategory.objects.get(slug=parent_cat, parent=None)
items = parent_category.item_set.all()
But that doesn't produce any results.
Answer: You should filter your items:
items = Item.objects.filter(category__parent=parent_category)
The double score is used to follow model relationships or to use more complex
lookups than a simple equal. Documentation
[here](https://docs.djangoproject.com/en/1.5/topics/db/queries/#lookups-that-
span-relationships)
|
Numpy longdouble arithmetic does not seem to be in long double with conversion
Question: I have been playing C99's [quad
precision](http://en.wikipedia.org/wiki/Quadruple-precision_floating-
point_format) long double. It is my understanding that (platform specific)
numpy supports [long
double](http://docs.scipy.org/doc/numpy/reference/c-api.dtype.html#NPY_LONGDOUBLE)
and 128bit floats.
I have run across something I cannot explain however.
Given:
>>> import numpy as np
Calculate a number that will require more than 64 bits but less than 128 bits
to represent as an integer:
>>> 2**64+2
18446744073709551618 # note the '8' at the end
>>> int(2**64+2)
18446744073709551618 # same obviously
If I [calculate](http://codepad.org/0Dbd7hHS) the same number in C99 128 bit
long double, I get `18446744073709551618.000000`
Now, if I use numpy long double:
>>> a=np.longdouble(2)
>>> b=np.longdouble(64)
>>> a**b+a
18446744073709551618.0 # all good...
What about these incorrect results:
>>> np.longdouble(2**64+2)
18446744073709551616.0 # Note '6'; appears 2**64 not done in long double
>>> np.longdouble(int(2**64+2))
18446744073709551616.0 # can't force the use of a Python long
>>> n=int(2**64+2)
>>> np.longdouble(n)
18446744073709551616.0
>>> np.longdouble(18446744073709551618)
18446744073709551616.0 # It really does not want to do '8' at the end
But, this works:
>>> np.longdouble(2**64)+2
18446744073709551618.0
Question: Does numpy have issues converting values correctly into long
doubles? Is there something I am doing incorrect?
Answer: You're trying to perform a type conversion between non-directly-convertible
types. Take a look at the stack:
#0 0x00002aaaaab243a0 in PyLong_AsDouble ()
from libpython2.7.so.1.0
#1 0x00002aaaaab2447a in ?? ()
from libpython2.7.so.1.0
#2 0x00002aaaaaaf8357 in PyNumber_Float ()
from libpython2.7.so.1.0
#3 0x00002aaaae71acdc in MyPyFloat_AsDouble (obj=0x2aaaaae93c00)
at numpy/core/src/multiarray/arraytypes.c.src:40
#4 0x00002aaaae71adfc in LONGDOUBLE_setitem (op=0x2aaaaae93c00,
ov=0xc157b0 "", ap=0xbf6ca0)
at numpy/core/src/multiarray/arraytypes.c.src:278
#5 0x00002aaaae705c82 in PyArray_FromAny (op=0x2aaaaae93c00,
newtype=0x2aaaae995960, min_depth=<value optimized out>, max_depth=0,
flags=0, context=<value optimized out>)
at numpy/core/src/multiarray/ctors.c:1664
#6 0x00002aaaae7300ad in longdouble_arrtype_new (type=0x2aaaae9938a0,
args=<value optimized out>, __NPY_UNUSED_TAGGEDkwds=<value optimized out>)
at numpy/core/src/multiarray/scalartypes.c.src:2545
As you can see, the Python `long` (unlimited-precision integer) `2**64 + 2` is
being converted to `float` (i.e. 64-bit double), which loses precision; the
float is then used to initialise the long double but the precision has already
been lost.
The problem is that 128-bit double is not a native Python type, so `long`
doesn't have a native conversion to it, only to 64-bit double. It probably
would be possible for NumPy to detect this situation and perform its own
conversion using the [`long` C
API](http://docs.python.org/dev/c-api/long.html), but might be fairly
complicated for relatively little benefit (you can just do arithmetic in
`np.longdouble` from the start).
|
Speed up sampling of kernel estimate
Question: Here's a `MWE` of a much larger code I'm using. Basically, it performs a Monte
Carlo integration over a KDE ([kernel density
estimate](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html))
for all values located below a certain threshold (the integration method was
suggested over at this question BTW: [Integrate 2D kernel density
estimate](http://stackoverflow.com/questions/17822282/integrate-2d-kernel-
density-estimate?rq=1)).
import numpy as np
from scipy import stats
import time
# Generate some random two-dimensional data:
def measure(n):
"Measurement model, return two coupled measurements."
m1 = np.random.normal(size=n)
m2 = np.random.normal(scale=0.5, size=n)
return m1+m2, m1-m2
# Get data.
m1, m2 = measure(20000)
# Define limits.
xmin = m1.min()
xmax = m1.max()
ymin = m2.min()
ymax = m2.max()
# Perform a kernel density estimate on the data.
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
values = np.vstack([m1, m2])
kernel = stats.gaussian_kde(values)
# Define point below which to integrate the kernel.
x1, y1 = 0.5, 0.5
# Get kernel value for this point.
tik = time.time()
iso = kernel((x1,y1))
print 'iso: ', time.time()-tik
# Sample from KDE distribution (Monte Carlo process).
tik = time.time()
sample = kernel.resample(size=1000)
print 'resample: ', time.time()-tik
# Filter the sample leaving only values for which
# the kernel evaluates to less than what it does for
# the (x1, y1) point defined above.
tik = time.time()
insample = kernel(sample) < iso
print 'filter/sample: ', time.time()-tik
# Integrate for all values below iso.
tik = time.time()
integral = insample.sum() / float(insample.shape[0])
print 'integral: ', time.time()-tik
The output looks something like this:
iso: 0.00259208679199
resample: 0.000817060470581
filter/sample: 2.10829401016
integral: 4.2200088501e-05
which clearly means that the _filter/sample_ call is consuming almost all of
the time the code uses to run. I have to run this block of code iteratively
several thousand times so it can get pretty time consuming.
Is there any way to speed up the filtering/sampling process?
* * *
## Add
Here's a slightly more realistic `MWE` of my actual code with Ophion's multi-
threading solution written into it:
import numpy as np
from scipy import stats
from multiprocessing import Pool
def kde_integration(m_list):
m1, m2 = [], []
for item in m_list:
# Color data.
m1.append(item[0])
# Magnitude data.
m2.append(item[1])
# Define limits.
xmin, xmax = min(m1), max(m1)
ymin, ymax = min(m2), max(m2)
# Perform a kernel density estimate on the data:
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
values = np.vstack([m1, m2])
kernel = stats.gaussian_kde(values)
out_list = []
for point in m_list:
# Compute the point below which to integrate.
iso = kernel((point[0], point[1]))
# Sample KDE distribution
sample = kernel.resample(size=1000)
#Create definition.
def calc_kernel(samp):
return kernel(samp)
#Choose number of cores and split input array.
cores = 4
torun = np.array_split(sample, cores, axis=1)
#Calculate
pool = Pool(processes=cores)
results = pool.map(calc_kernel, torun)
#Reintegrate and calculate results
insample_mp = np.concatenate(results) < iso
# Integrate for all values below iso.
integral = insample_mp.sum() / float(insample_mp.shape[0])
out_list.append(integral)
return out_list
# Generate some random two-dimensional data:
def measure(n):
"Measurement model, return two coupled measurements."
m1 = np.random.normal(size=n)
m2 = np.random.normal(scale=0.5, size=n)
return m1+m2, m1-m2
# Create list to pass.
m_list = []
for i in range(60):
m1, m2 = measure(5)
m_list.append(m1.tolist())
m_list.append(m2.tolist())
# Call KDE integration function.
print 'Integral result: ', kde_integration(m_list)
The solution presented by _Ophion_ works great on the original code I
presented, but fails with the following error in this version:
Integral result: Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 319, in _handle_tasks
put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
I tried moving the `calc_kernel` function around since one of the answers in
this question [Multiprocessing: using Pool.map on a function defined in a
class](http://stackoverflow.com/questions/3288595/multiprocessing-using-pool-
map-on-a-function-defined-in-a-class) states that _"the function that you give
to map() must be accessible through an import of your module"_ ; but I still
can't get this code to work.
Any help will be very much appreciated.
* * *
## Add 2
Implementing _Ophion's_ suggestion to remove the `calc_kernel` function and
simply using:
results = pool.map(kernel, torun)
works to get rid of the `PicklingError` but now I see that if I create an
initial `m_list` of anything more than around 62-63 items I get this error:
Traceback (most recent call last):
File "~/gauss_kde_temp.py", line 67, in <module>
print 'Integral result: ', kde_integration(m_list)
File "~/gauss_kde_temp.py", line 38, in kde_integration
pool = Pool(processes=cores)
File "/usr/lib/python2.7/multiprocessing/__init__.py", line 232, in Pool
return Pool(processes, initializer, initargs, maxtasksperchild)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 161, in __init__
self._result_handler.start()
File "/usr/lib/python2.7/threading.py", line 494, in start
_start_new_thread(self.__bootstrap, ())
thread.error: can't start new thread
Since my actual list in my real implementation of this code can have up to
2000 items, this issue renders the code unusable. Line `38` is this one:
pool = Pool(processes=cores)
so apparently it has something to do with the number of cores I'm using?
This question ["Can't start a new thread error" in
Python](http://stackoverflow.com/questions/10589766/cant-start-a-new-thread-
error-in-python) suggests using:
threading.active_count()
to check the number of threads I have going when I get that error. I checked
and it always crashes when it reaches `374` threads. How can I code around
this issue?
* * *
Here's the new question dealing with this last issue: [Thread error: can't
start new thread](http://stackoverflow.com/questions/18602236/thread-error-
cant-start-new-thread)
Answer: Probably the easiest way to speed this up is to parallelize `kernel(sample)`:
Taking this code fragment:
tik = time.time()
insample = kernel(sample) < iso
print 'filter/sample: ', time.time()-tik
#filter/sample: 1.94065904617
Change this to use `multiprocessing`:
from multiprocessing import Pool
tik = time.time()
#Create definition.
def calc_kernel(samp):
return kernel(samp)
#Choose number of cores and split input array.
cores = 4
torun = np.array_split(sample, cores, axis=1)
#Calculate
pool = Pool(processes=cores)
results = pool.map(calc_kernel, torun)
#Reintegrate and calculate results
insample_mp = np.concatenate(results) < iso
print 'multiprocessing filter/sample: ', time.time()-tik
#multiprocessing filter/sample: 0.496874094009
Double check they are returning the same answer:
print np.all(insample==insample_mp)
#True
A 3.9x improvement on 4 cores. Not sure what you are running this on, but
after about 6 processors your input array size is not large enough to get
considerably gains. For example using 20 processors its only about 5.8x
faster.
|
Python "R Cut" function
Question: I am wondering if there is a function in Python already written for the goal
that I describe later. If not, what would be the easiest way to implement. My
code is attached.
Say I have a range from 1 to 999999999. Given a list of numbers like this:
[9, 44, 99]
It would return
[(1,9), (10,44), (45,99), (100, 999999999)]
If the number which are the limits are included in the input numbers, it
should handle that also. Say input is
[1, 9, 44, 999999999]
The return should be:
[(1,9), (10,44), (45, 999999999)]
I could write a for loop comparing with a few conditional statement but
wondering if there is a more 'smart way'.
Some data massage that might be helpful:
points = [1, 9, 44, 99]
points = sorted(list(set(points + [1, 999999999])))
_**UPDATED INFO: FINAL CREDITS GIVEN TO alecxe, thanks for your inspiring list
comprehension solution_**
l = sorted(list(set(points + [1, 999999999])))
[(l[i] + int(i != 0), l[i + 1]) for i in xrange(len(l) - 1)]
You can put all that in one line but I think that is unnessary.
Answer:
def myCut(low, high, points):
answer = []
curr = low
for point in points:
answer.append((curr, point))
curr = point + 1
answer.append((curr, high))
return answer
>>> low = 1
>>> high = 999999999
>>> points = [9, 44, 109]
>>> myCut(low, high, points)
[(1, 9), (10, 44), (45, 109), (110, 999999999)]
Inspired by [this answer](http://stackoverflow.com/a/18538981/198633) and the
discussions that followed, here's a solution in fewer lines, with `itertools`.
This uses `itertools.chain` and `itertools.izip` (in python2.7; `zip` in
python3.x) to reduce the time and space complexities arising from adding
lists, sorting and setifying. Note that the solution assumes that the input
list is already sorted, failing which, erroneous results will be produced
cuts = [(i+1, j) for i,j in itertools.izip(itertools.chain([0], myList), itertools.chain(myList, [999999999]))]
>>> import itertools
>>> myList = [9, 44, 99]
>>> [(i+1, j) for i,j in itertools.izip(itertools.chain([0], myList), itertools.
chain(myList, [999999999]))]
[(1, 9), (10, 44), (45, 99), (100, 999999999)]
|
Find Python module filename
Question: I got module name which contains declaration of `os.path.isfile`.
[Jedi](https://github.com/davidhalter/jedi) lib gave me `genericpath` (without
file path). Now i want to get full filename of PY file with this `genericpath`
module. E.g. "C:\Py27\Lib\genericpath.py". How can I do it? Jedi cannot do it?
Answer: You could check the value of `__file__`:
>>> import genericpath
>>> genericpath.__file__
'/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/genericpath.pyc'
|
How would I create a Python web server that downloads a file on any GET request?
Question: I am attempting to create an easy solution to file sharing across computers in
my local network. I used to execute `python -m SimpleHTTPServer` in bash
whenever I wanted to share a directory, but I wanted a way to share only one
specific file. Can anyone point me in the right direction for how I might
create a web server, and then have it download a file for each GET request.
For example, someone on my network could go to my IP and have the file
download.
P.S. What would be even cooler is if there was a way to password protect a
file! Also, I have Python 2.7.2, if that matters. Anyway, As you have probably
noticed, I know almost nothing about Python, but I learn by example so I am
hoping this will help me some as well.
Thanks a bunch in advance!
Answer: Try following:
import BaseHTTPServer
import os
import shutil
import sys
FILEPATH = sys.argv[1] if sys.argv[1:] else __file__
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
with open(FILEPATH, 'rb') as f:
self.send_response(200)
self.send_header("Content-Type", 'application/octet-stream')
self.send_header("Content-Disposition", 'attachment; filename="{}"'.format(os.path.basename(FILEPATH)))
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs.st_size))
self.end_headers()
shutil.copyfileobj(f, self.wfile)
def test(HandlerClass=SimpleHTTPRequestHandler,
ServerClass=BaseHTTPServer.HTTPServer,
protocol="HTTP/1.0"):
if sys.argv[2:]:
port = int(sys.argv[2])
else:
port = 8000
server_address = ('', port)
HandlerClass.protocol_version = protocol
httpd = BaseHTTPServer.HTTPServer(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "...", FILEPATH
httpd.serve_forever()
if __name__ == '__main__':
test()
Usage: `python script_path [filepath_to_serve [port]]`
|
how to count the repetition of the elements in a list python, django
Question: I have a django app, i am using `django-taggit` for my blog.
Now i have a list of elements(In fact objects) that i got from database in one
of my view as below
tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>]
Now how to find the count of each element in the list and return a list of
tuples as below
**result should be as below**
[(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)]
so that i can use them in template by looping it something like below
**view**
def display_list_of_tags(request):
tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>]
# After doing some operation on above list as indicated above
tags_with_count = [(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)]
return HttpResponse('some_template.html',dict(tags_with_count:tags_with_count))
**template**
{% for tag_obj in tags_with_count %}
<a href="{% url 'tag_detail' tag_obj %}">{{tag_obj}}</a> <span>count:{{tags_with_count[tag_obj]}}</span>
{% endfor %}
so as described above how to count the occurences of each element in the list
? The process should be ultimately fast, because i may have hundreds of tags
in the tagging application right ?
If the list contains only strings as elements, we could use something like
`from collections import counter` and calculate the count, but how do do in
the above case ?
All my intention is to count the occurences and print them in the template
like `tag object and occurences`,
So i am searching for a fast and efficient way to perform above functionality
?
**Edit** :
So i got the required answer from and i am sending the result to template by
converting the resultant `list of tuples` to dictionary as below
{<Tag: created>: 1, <Tag: some>: 2, <Tag: here>: 2, <Tag: tags>: 2}
and tried to print the above dictionary by looping it in the format like
{% for tag_obj in tags_with_count %}
<a href="{% url 'tag_detail' tag_obj %}">{{tag_obj}}</a> <span>count:{{tags_with_count[tag_obj]}}</span>
{% endfor %}
But its displaying the below error
TemplateSyntaxError: Could not parse the remainder: '[tag_obj]' from 'tags_with_count[tag_obj]'
So how to display the dictionary in the django templates by like key and value
?
Done we can change the above template looping as below
{% for tag_obj, count in tags_with_count.iteritems %}
Answer: Try Python's
[Counter](http://docs.python.org/2/library/collections.html#collections.Counter):
from collections import Counter
l = ['some', 'here', 'tags', 'some', 'created', 'here', 'tags']
print(Counter(l).items())
Output:
[('created', 1), ('some', 2), ('here', 2), ('tags', 2)]
|
Python Tkinter OptionMenu command Exception
Question: I want to create a tkinter `OptionMenu` that edits another `OptionMenu` when
it's changed. So I tried to create a `command=` argument which makes a
specific command run on every update of the `OptionMenu`, like it does when I
pass the command-Argument to a button, spinbox etc.
tl.wktype = OptionMenu(tl,wktypevar, *wk_types,command=typeupdate)
somewhere else in the code is the `typeupdate()` Command - for debug purposes
right now.
def typeupdate():
typeval = tl.wktype.get()
print(typeval)
The exception python throws is the following:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\lib\tkinter\__init__.py", line 3300, in __call__
self.__callback(self.__value, *args)
TypeError: typeupdate() takes 0 positional arguments but 1 was given
what positional arguments does `typeupdate()` think is given to it and how do
I fix this?
Answer: It is given the value that is clicked. To demonstrate, consider this script:
from tkinter import Tk, OptionMenu, StringVar
root = Tk()
def func(val):
print(val)
var = StringVar()
OptionMenu(root, var, "one", command=func).grid()
root.mainloop()
When run (and when I click on the option "one" in the optionmenu), it prints
"one" in the terminal.
So, in summary, add `val` (or any other argument name) to your function
declaration and it will work:
def typeupdate(val):
|
python find the 2nd highest element
Question: 1.In a given array how to find the 2nd or 3rd,4th ,5th values.
2.Also if we use max() function in python what is the order of complexity i.e,
associated with this function max()
def nth_largest(li,n):
li.remove(max(li))
print max(ele) //will give me the second largest
#how to make a general algorithm to find the 2nd,3rd,4th highest value
#n is the element to be found below the highest value
Answer: I'd go for:
import heapq
res = heapq.nlargest(2, some_sequence)
print res[1] # to get 2nd largest
This is more efficient than sorting the entire list, then taking the first `n`
many elements. See the [heapq
documentation](http://docs.python.org/2/library/heapq.html) for further info.
|
Any way to bypass namedtuple 255 arguments limitation?
Question: I'm using a namedtuple to hold sets of strings and their corresponding values.
I'm not using a dictionary, because I want the strings accessible as
attributes.
Here's my code:
from collections import namedtuple
# Shortened for readability :-)
strings = namedtuple("strings", ['a0', 'a1', 'a2', ..., 'a400'])
my_strings = strings(value0, value1, value2, ..., value400)
Ideally, once `my_strings` is initialized, I should be able to do this:
print(my_strings.a1)
and get `value1` printed back.
**However** , I get the following error instead:
strings(value0, value1, value2, ...value400)
^SyntaxError: more than 255 arguments
It seems python functions (including namedtuple's **init**()), do not accept
more than 255 arguments when called. Is there any way to bypass this issue and
have named tuples with more than 255 items? Why is there a 255 arguments limit
anyway?
Answer: This is a limit to CPython function definitions; you cannot specify more than
255 explicit arguments to a callable. This applies to any function definition,
not just named tuples.
It is the generated code for the class that is hitting this limit. You cannot
define a function with more than 255 arguments; the `__new__` class method of
the resulting class is thus not achievable in the CPython implementation.
You'll have to ask yourself, however, if you really should be using a
different structure instead. It looks like you have a list-like piece of data
to me; 400 numbered names is a sure sign of your [data bleeding into your
names](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html).
You can work around this by creating your own subclass, manually:
from operator import itemgetter
from collections import OrderedDict
class strings(tuple):
__slots__ = ()
_fields = tuple('a{}'.format(i) for i in range(400))
def __new__(cls, *args, **kwargs):
req = len(cls._fields)
if len(args) + len(kwargs) > req:
raise TypeError(
'__new__() takes {} positional arguments but {} were given'.format(
req, len(args) + len(kwargs)))
if kwargs.keys() > set(cls._fields):
raise TypeError(
'__new__() got an unexpected keyword argument {!r}'.format(
(kwargs.keys() - set(cls._fields)).pop()))
missing = req - len(args)
if kwargs.keys() & set(cls._fields[:-missing]):
raise TypeError(
'__new__() got multiple values for argument {!r}'.format(
(kwargs.keys() & set(cls._fields[:-missing])).pop()))
try:
for field in cls._fields[-missing:]:
args += (kwargs[field],)
missing -= 1
except KeyError:
pass
if len(args) < req:
raise TypeError('__new__() missing {} positional argument{}: {}'.format(
missing, 's' if missing > 1 else '',
' and '.join(filter(None, [', '.join(map(repr, cls._fields[-missing:-1])), repr(cls._fields[-1])]))))
return tuple.__new__(cls, args)
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new strings object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != len(self._fields):
raise TypeError('Expected %d arguments, got %d' % (len(self._fields), len(result)))
return result
def __repr__(self):
'Return a nicely formatted representation string'
format = '{}({})'.format(self.__class__.__name__, ', '.join('{}=%r'.format(n) for n in self._fields))
return format % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
__dict__ = property(_asdict)
def _replace(self, **kwds):
'Return a new strings object replacing specified fields with new values'
result = self._make(map(kwds.pop, self._fields, self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
return None
for i, name in enumerate(strings._fields):
setattr(strings, name,
property(itemgetter(i), doc='Alias for field number {}'.format(i)))
This version of the named tuple avoids the long argument lists altogether, but
otherwise behaves exactly like the original. The somewhat verbose `__new__`
method is not strictly needed but does closely emulate the original behaviour
when arguments are incomplete. Note the construction of the `_fields`
attribute; replace this with your own to name your tuple fields.
Pass in a generator expression to set your arguments:
s = strings(i for i in range(400))
or if you have a list of values:
s = strings(iter(list_of_values))
Either technique bypasses the limits on function signatures and function call
argument counts.
Demo:
>>> s = strings(i for i in range(400))
>>> s
strings(a0=0, a1=1, a2=2, a3=3, a4=4, a5=5, a6=6, a7=7, a8=8, a9=9, a10=10, a11=11, a12=12, a13=13, a14=14, a15=15, a16=16, a17=17, a18=18, a19=19, a20=20, a21=21, a22=22, a23=23, a24=24, a25=25, a26=26, a27=27, a28=28, a29=29, a30=30, a31=31, a32=32, a33=33, a34=34, a35=35, a36=36, a37=37, a38=38, a39=39, a40=40, a41=41, a42=42, a43=43, a44=44, a45=45, a46=46, a47=47, a48=48, a49=49, a50=50, a51=51, a52=52, a53=53, a54=54, a55=55, a56=56, a57=57, a58=58, a59=59, a60=60, a61=61, a62=62, a63=63, a64=64, a65=65, a66=66, a67=67, a68=68, a69=69, a70=70, a71=71, a72=72, a73=73, a74=74, a75=75, a76=76, a77=77, a78=78, a79=79, a80=80, a81=81, a82=82, a83=83, a84=84, a85=85, a86=86, a87=87, a88=88, a89=89, a90=90, a91=91, a92=92, a93=93, a94=94, a95=95, a96=96, a97=97, a98=98, a99=99, a100=100, a101=101, a102=102, a103=103, a104=104, a105=105, a106=106, a107=107, a108=108, a109=109, a110=110, a111=111, a112=112, a113=113, a114=114, a115=115, a116=116, a117=117, a118=118, a119=119, a120=120, a121=121, a122=122, a123=123, a124=124, a125=125, a126=126, a127=127, a128=128, a129=129, a130=130, a131=131, a132=132, a133=133, a134=134, a135=135, a136=136, a137=137, a138=138, a139=139, a140=140, a141=141, a142=142, a143=143, a144=144, a145=145, a146=146, a147=147, a148=148, a149=149, a150=150, a151=151, a152=152, a153=153, a154=154, a155=155, a156=156, a157=157, a158=158, a159=159, a160=160, a161=161, a162=162, a163=163, a164=164, a165=165, a166=166, a167=167, a168=168, a169=169, a170=170, a171=171, a172=172, a173=173, a174=174, a175=175, a176=176, a177=177, a178=178, a179=179, a180=180, a181=181, a182=182, a183=183, a184=184, a185=185, a186=186, a187=187, a188=188, a189=189, a190=190, a191=191, a192=192, a193=193, a194=194, a195=195, a196=196, a197=197, a198=198, a199=199, a200=200, a201=201, a202=202, a203=203, a204=204, a205=205, a206=206, a207=207, a208=208, a209=209, a210=210, a211=211, a212=212, a213=213, a214=214, a215=215, a216=216, a217=217, a218=218, a219=219, a220=220, a221=221, a222=222, a223=223, a224=224, a225=225, a226=226, a227=227, a228=228, a229=229, a230=230, a231=231, a232=232, a233=233, a234=234, a235=235, a236=236, a237=237, a238=238, a239=239, a240=240, a241=241, a242=242, a243=243, a244=244, a245=245, a246=246, a247=247, a248=248, a249=249, a250=250, a251=251, a252=252, a253=253, a254=254, a255=255, a256=256, a257=257, a258=258, a259=259, a260=260, a261=261, a262=262, a263=263, a264=264, a265=265, a266=266, a267=267, a268=268, a269=269, a270=270, a271=271, a272=272, a273=273, a274=274, a275=275, a276=276, a277=277, a278=278, a279=279, a280=280, a281=281, a282=282, a283=283, a284=284, a285=285, a286=286, a287=287, a288=288, a289=289, a290=290, a291=291, a292=292, a293=293, a294=294, a295=295, a296=296, a297=297, a298=298, a299=299, a300=300, a301=301, a302=302, a303=303, a304=304, a305=305, a306=306, a307=307, a308=308, a309=309, a310=310, a311=311, a312=312, a313=313, a314=314, a315=315, a316=316, a317=317, a318=318, a319=319, a320=320, a321=321, a322=322, a323=323, a324=324, a325=325, a326=326, a327=327, a328=328, a329=329, a330=330, a331=331, a332=332, a333=333, a334=334, a335=335, a336=336, a337=337, a338=338, a339=339, a340=340, a341=341, a342=342, a343=343, a344=344, a345=345, a346=346, a347=347, a348=348, a349=349, a350=350, a351=351, a352=352, a353=353, a354=354, a355=355, a356=356, a357=357, a358=358, a359=359, a360=360, a361=361, a362=362, a363=363, a364=364, a365=365, a366=366, a367=367, a368=368, a369=369, a370=370, a371=371, a372=372, a373=373, a374=374, a375=375, a376=376, a377=377, a378=378, a379=379, a380=380, a381=381, a382=382, a383=383, a384=384, a385=385, a386=386, a387=387, a388=388, a389=389, a390=390, a391=391, a392=392, a393=393, a394=394, a395=395, a396=396, a397=397, a398=398, a399=399)
>>> s.a391
391
|
Pack labels right next to entry box in tkinter python
Question: I have a window that prompts users to enter the directory of their log files.
However, my label seems to pack on top of my entrybox. Any idea on how to pack
them side by side?
labelText=StringVar()
labelText.set("Enter directory of log files")
labelDir=Label(app,textvariable=labelText,height=4)
labelDir.pack()
directory=StringVar(None)
dirname=Entry(app,textvariable=directory,width=50)
dirname.pack()
Answer: Yes, you need to set the `side` option to "left". See below:
from Tkinter import Tk, Label, Entry, StringVar
app = Tk()
labelText=StringVar()
labelText.set("Enter directory of log files")
labelDir=Label(app, textvariable=labelText, height=4)
labelDir.pack(side="left")
directory=StringVar(None)
dirname=Entry(app,textvariable=directory,width=50)
dirname.pack(side="left")
app.mainloop()
example:

|
converting a float to decimal type in Python
Question: I have an array that grows with each iteration of a loop:
for i in range(100):
frac[i] = some fraction between 0 and 1 with many decimal places
This all works fine. When I check the **type(frac[i])** , I am told that it is
**'numpy.float64'**.
For my code to be as precise as I need it to be, I need to use the decimal
module and change each **frac[i]** to the decimal type.
I updated my code:
for i in range(100):
frac[i] = some fraction between 0 and 1 with many decimal places
frac[i] = decimal.Decimal(frac[i])
But when I check the type, I am STILL told that **frac[i]** is
**'numpy.float64'**.
I have managed to change other variables to decimal in this way before, so I
wonder if you could tell me why this doesn't seem to work.
Thank you.
Answer: Depending where your fractions are coming from, you may find it ideal to use
the [fractions](http://docs.python.org/2/library/fractions.html) module. Some
examples from the docs:
>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)
You can also perform all of the regular arithmetic operations; if the result
can't be expressed as a fraction, it will be converted to a float:
>>> Fraction(3, 4) + Fraction(1, 16)
Fraction(13, 16)
>>> Fraction(3, 4) * Fraction(1, 16)
Fraction(3, 64)
>>> Fraction(3, 4) ** Fraction(1, 16)
0.982180548555
|
Why are my App tests not being recognized by Django tests?
Question: ## Background:
I have the following django project setup:
>TopLevel:
> - App1:
> * models.py
> * forms.py
> * views.py
> * __init__.py
> * Tests/
> * __init__.py
> * test_simple.py
Here is the code in test_simple.py:
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
Now, when I run:
> python manage.py test app1
I get the following output:
>Creating test database for alias 'default'...
>
>----------------------------------------------------------------------
>Ran 0 tests in 0.000s
>
>OK
>Destroying test database for alias 'default'...
But, if I instead use the following project structure:
>TopLevel:
> - App1:
> * models.py
> * forms.py
> * views.py
> * __init__.py
> * tests.py
Where tests.py has the following code:
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
Now, when I run:
> python manage.py test app1
I get:
>Creating test database for alias 'default'...
>.
>----------------------------------------------------------------------
>Ran 1 test in 0.002s
>
>OK
>Destroying test database for alias 'default'...
## Question:
Why does Django not recognize my Tests directory && why won't any tests listed
inside Tests/ be picked up by Django's unittest structure to run?
Answer: One option to have a good sleep and don't even think about test discovery is
to use [nose](http://nose.readthedocs.org/en/latest/). It has a lot features,
one of it is [automatic tests
discovery](http://nose.readthedocs.org/en/latest/finding_tests.html).
There is package called [django_nose](https://github.com/jbalogh/django-nose)
that will help you to integrate your django project with nose:
> Features
>
> All the goodness of nose in your Django tests, like...
>
> * ...
> * Obviating the need to import all your tests into `tests/__init__.py`.
> This not only saves busy-work but also eliminates the possibility of
> accidentally shadowing test classes.
> * ...
>
Hope that helps.
|
Find all the contents between two tags in python
Question:
<p>This is the first paragraph with some details</p>
<p><a href = "user123">user1</a><font>This is opening contents for user1</font></p>
<p><font>This is the contents from user1</font></p>
<font><p>This is more content from user1</p></font>
<p><a href = "user234">user2</a><font>This is opening contents for user2</font></p>
<p><font>This is the contents from user2</font></p>
<font><p>This is more content from user1</p></font>
!----There is n number of data like this-----!
This is the structure of my html. My aim is to extract the users and their
contents. In this case it should print all the contents between two 'a' tags.
This is just an example of my structure, but in real html, i have different
types of tags between two 'a' tags. I need a solution to iterate all the tags
below a 'a' tag till it finds another 'a' tag. Hope thats clear.
The code which i tried is :
for i in soup.findAll('a'):
while(i.nextSibling.name!='a'):
print i.nextSibling
I returns me an infinite loop. So if anyone has idea how i can solve this
issue please share it with me.
Expected output is :
username is : user1
text is : This is opening contents for user1 This is the contents from user1
This is more content from user1
username is : user2
text is : This is opening contents for user2 This is the contents from user2
This is more content from user2
and so on......
Answer: Try this:
from bs4 import BeautifulSoup
html="""
<p>This is the first paragraph with some details</p>
<p><a href="user123">user1</a><font>This is opening contents for user1</font></p>
<p><font>This is the contents from user1</font></p>
<font><p>This is more content from user1</p></font>
<p><a href="user234">user2</a><font>This is opening contents for user2</font></p>
<p><font>This is the contents from user2</font></p>
<font><p>This is more content from user1</p></font>
"""
soup = BeautifulSoup(html)
for i in soup.find_all('a'):
print 'name:', i.text
for s in [i, i.parent.find_next_sibling()]:
while s <> None:
if s.find('a') <> None:
break
print 'contents:', s.text
s = s.find_next_sibling()
(Note: `find_all` is the recommended name for `findAll`, it may not work in
older soups. Same with `find_next_sibling`.)
|
global var becomes local --UnboundLocalError: local variable referenced before assignment
Question: I initialized `rate` as a global var:
import os, sys
rate=30
def foo():
print('#########rate:', rate)
if False:
rate=int(sys.argv[2])
foo()
but when running the script, I get the following error:
Traceback (most recent call last):
Line 10, in <module>
foo()
Line 5, in foo
print('#########rate:', rate)
UnboundLocalError: local variable 'rate' referenced before assignment
although the `if False: rate=int(sys.argv[2])` statement is not executed, it
seems has some influence, is there some python rules explains this?
Answer: You should declare `rate` as global:
import os, sys
rate=30
def foo():
global rate # <----
print('#########rate:', rate)
if False:
rate=int(sys.argv[2])
foo()
If there is assignment to a varaint (without global declaration), it is
treated as local variable.
|
Add a service in Mac Finder using CLI
Question: I write a Python script and I want to add it as a service item in Mac Finder.
I know I can open `Automator` window and set it. But I need a command line
way. I search the method for a long time and still get nothing...
Do anyone know how to achieve this? Thanks a lot. (Using python, apple script
or any builtin CLI tool is also acceptable to me)
Answer: To go with my comment here is a very basic example.
Which is to show you how services are registered, even the Automator ones. And
why I think you may not be able to do what you want.
Using Xcode I have created a new project.
Code in the .m file:
//
// AppDelegate.m
// testServiceExample
//
// Created by Mark Hunte on 02/09/2013.
// Copyright (c) 2013 Mark Hunte. All rights reserved.
//
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[NSApp setServicesProvider:self];//Registers a given object as the service provider.
NSUpdateDynamicServices();//Causes the services information for the system to be updated.
}
-(void) runAService:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
NSLog(@" files %@", files);
}
[[NSApplication sharedApplication] terminate:nil];
}
@end
Note the :
[NSApp setServicesProvider:self];//Registers a given object as the service provider.
NSUpdateDynamicServices();//Causes the services information for the system to be updated.
Then I added the Array to the applications info-plist

<array>
<dict>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>Service Test</string>
</dict>
<key>NSMessage</key>
<string>runAService</string>
<key>NSSendTypes</key>
<array>
<string>public.item</string>
</array>
</dict>
</array>
`<string>Service Test</string>` menu displayed
`<string>runAService</string>` method to run in the application
`<string>public.item</string>` objects that the service will work on
The first run of the app (double clicking will register the service to the
system. But I make sure it is checked in the keyboard shortcuts.
The result from the NSLog can be seen in the console.app which will list the
files paths
* * *
So even if I could add a item using something like defaults write to the plist
file that holds the registered applications in the system prefs services. I
doubt anything would actually work without any of the above.
Obviously the Automator application can write the correct info to a the plist
file and the **runAservice** method.
The actual method in a service workflows name is: **_runWorkflowAsService_**.
Thinking about it. You can write and build apps from the command line. And
have it run you python But it is a lot of trouble to go to.
For more info on services see the apple docs
[here](https://developer.apple.com/library/mac/documentation/cocoa/conceptual/SysServices/introduction.html#//apple_ref/doc/uid/10000101-SW1)
|
What's the best way to search a number and replace it after calculation in a string by Python?
Question: For example. I have a string: "[bezierPath moveToPoint: CGPointMake(7.98,
6.11)];". I want to do some calculation on the two float number and replace
them.
Answer: You can use `re.sub`:
>>> import re
>>> def action(matchObj):
... return str(float(matchObj.group(0)) * 2)
...
>>> re.sub('\d+\.\d+', action, "[bezierPath moveToPoint: CGPointMake(7.98, 6.11)];")
'[bezierPath moveToPoint: CGPointMake(15.96, 12.22)];'
|
enforce column encoding with sqlalchemy
Question: I am using sqlalchemy to create the schema of my database. I have no success
in enforcing the use of utf-8, no matter what I tried.
Here is a minimal python script that recreates my problem:
from sqlalchemy import create_engine, Column, Unicode
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+mysqldb://user:password@localhost/multidic?charset=utf8', echo=True)
Base = declarative_base()
class MyTableName(Base):
__tablename__ = "mytablename"
test_column = Column(Unicode(2),primary_key=True)
Base.metadata.create_all(engine)
After running this script, when I look into the database, I see that the
encoding is latin1 instead of utf-8:
mysql> SHOW FULL COLUMNS FROM mytablename;
+-------------+------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-------------+------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| test_column | varchar(2) | latin1_swedish_ci | NO | PRI | NULL | | select,insert,update,references | |
+-------------+------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
1 row in set (0.00 sec)
I have tried changing the type of the column created (**String** instead of
**Unicode**), and tried also to add the argument **encoding = "utf8"** in the
call to **create_engine** , but none of it worked.
So, my question is:
_How to enforce the use of a given character encoding (utf-8 in my case) in
MySQL, with sqlalchemy ?_
Thank you :)
## Notes:
I am using sqlalchemy 0.7 and python 2.7; I can possibly upgrade one or both,
but only if it is the only solution!
I have mysql 5, and it supports utf-8:
mysql> show character set where charset="utf8";
+---------+---------------+-------------------+--------+
| Charset | Description | Default collation | Maxlen |
+---------+---------------+-------------------+--------+
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
+---------+---------------+-------------------+--------+
1 row in set (0.00 sec)
Answer: To specify a specific collation per column, use the
[`collation`](http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dialects.mysql.NVARCHAR)
parameter on the data type:
class MyTableName(Base):
__tablename__ = "mytablename2"
test_column = Column(Unicode(2),
primary_key=True)
test_column2 = Column(Unicode(2, collation='utf8_bin'))
# ^^^^^^^^^^^^^^^^^^^^
Mind that MySQL understands this as both the set of codepoints to describe the
text as well as the sort order the text will be indexed with; the usual
suspects like 'utf8' or 'utf-8' won't be familiar to MySQL (use `SHOW
COLLATION` to see the full list)
mysql> show full columns from mytablename2;
+--------------+------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+--------------+------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| test_column | varchar(2) | latin1_swedish_ci | NO | PRI | NULL | | select,insert,update,references | |
| test_column2 | varchar(2) | utf8_bin | YES | | NULL | | select,insert,update,references | |
+--------------+------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
2 rows in set (0.00 sec)
mysql>
|
OpenCV Python can't use SURF, SIFT
Question: I'm trying a simple thing like
detector = cv2.SIFT()
and get this bad error
detector = cv2.SIFT()
AttributeError: 'module' object has no attribute 'SIFT'
I do not understand that because cv2 is installed.
cv2.**version** is
$Rev: 4557 $
my system is Ubuntu 12.04
maybe someone has got the same problem and could help me
thanks a lot
EDIT*:
long story short testypypypy.py
import cv2
detector = cv2.SIFT()
ERROR
Traceback (most recent call last):
File "testypypy.py", line 3, in <module>
detector = cv2.SIFT()
AttributeError: 'module' object has no attribute 'SIFT
if i take "SURF" it works because SURF is in dir(cv2) but if i also take
cv2.BFMatcher() i get the same error...so it's missing and i have to add it
but i don't know how
Answer: FYI, as of 3.0.0 SIFT and friends are in a contrib repo located at
<https://github.com/Itseez/opencv_contrib> and are not included with opencv by
default.
|
python, tkinter: Using grid layout, my frame refuses to display its contents
Question: Trying to use grid geometry instead of pack(), but using a frame without use
of pack() has me lost. All I Want is a frame around it so that I can have a
border and label around certain sections. I suspect the width and height
parameters are the problem here.
from tkinter import *
class App:
def __init__(self,master):
frame = Frame(master,height=20,width=25)
#Multiple buttons, over n rows and columns, these are just here to demonstrate my syntax
self.action = Button(frame,text="action",command=self.doAction)
self.action.grid(row=n,column=n)
def doAction(self):
print('Action')
root = Tk()
app = App(root)
root.mainloop()
Answer: The frame you create in the first statement of the constructor is never placed
anywhere in its parent window. Since the other widgets are children of this
widget, they won't be displayed either.
|
Python 2.7 not searching folders inside of site-packages
Question: I'm running Windows 7 x64. I've installed Python 2.7 32-bit into the default
directory (C:/Python27).
I used Pip to install a few modules (e.g. social-auth), but when I try to
import them, Python says there is no module with that name. For example,
"import linkedin" results in an ImportError.
Google search suggests that the problem might be with a missing __init__.py,
but all the subdirectories have an __init__.py (although I'm not sure what
those files are supposed to contain).
Answer: For Linkedin authentication backend, you should import this way,
`from social.backends.linkedin import LinkedinOAuth`
for OAuth2, `from social.backends.linkedin import LinkedinOAuth2`
|
Python can't authenticate with ntlm
Question: I am trying to parse a site on my intranet and when authenticating as below I
get an error saying that authentication is required, which I have already
done. Why am I still getting this 401 error?
Thanks in advance!
> File "C:\Python27\lib\urllib2.py", line 531, in http_error_default raise
> HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP
> Error 401: Authorization Required
import urllib2
from ntlm import HTTPNtlmAuthHandler
user = r'domain\myuser'
password = 'mypasswd'
url = 'http://myinternal.homepage'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
# create the NTLM authentication handler
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
# create and install the opener
opener = urllib2.build_opener(auth_NTLM)
urllib2.install_opener(opener)
# retrieve the result
response = urllib2.urlopen(url)
print(response)
Answer: Try not putthing the 'r' in front of 'domain\myuser'. I have used this without
the 'r' and it works for me. One thing that helped me- ( i'm guessing you
probably already did . . . just in case though) check the headers that the url
returns to you. I did this with Mechanize
<http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/>
and based of the headers returned figured out I should be using NTLM auth ( as
seen here). I also have a similar question [How to 'convert' variable of type
instance such that the variable can be used to authenticate when making system
calls](http://stackoverflow.com/questions/21026430/how-to-convert-variable-of-
type-instance-such-that-the-variable-can-be-used-to).
|
Writing bytes to file, bad encoding
Question: I have a problem in Python 3.x with writing to file, write function in FOR is
writing czech signs in utf-8 coding. I am new in Python but i set up IDE and
.py, .xml files for 'utf-8' encoding and i have no idea why is output file
looking like that. My code:
-*- coding: utf-8 -*-
from lxml import etree
from io import BytesIO
import sys
import codecs
f = open('uzivatelska_prirucka.xml','rb')
fo = open('try.xml','wb',1)
header = '?xml version="1.0" encoding="utf-8"?>\n<root\n'
fo.write(bytes(header,'UTF-8'))
some_file_like_object = f
tree = etree.parse(some_file_like_object)
root = tree.getroot()
node = tree.xpath('/prirucka/body/p');
for a in node:
for b in a.getiterator():
if not (b.find('r') is None):
text = etree.tostring(b.find('r'))
fo.write(bytes(str(text),'UTF-8'))
Thanks for your help and advices
Answer: Is it necessary to read and write in binary mode??
I think a XML file is a simple text file and you could use it just like a txt
file
also you should know python3.2 and newer versions of python don't make any
difference between ASCII and UTF strings
python3.2 and above see all strings as unicode strings so you can write your
string in the output file whether the string contains non-ASCII characters or
not
Also I find no need to open file in binary mode to use with `lxml.etree`
package
Try to open files in text mode ( get rid of that `b` in opening mode ) and see
if it works but keep in mind tell open to use `utf-8` encoding to open your
files
f = open('uzivatelska_prirucka.xml', 'r', encoding='utf-8')
fo = open('try.xml', 'w', 1, encoding='utf-8')
As a side note, you could just write:
if b.find('r'):
instead of:
if not (b.find('r') is None):
because `None` in if clauses assumed as `False` and if `find()` returns `None`
python itself don't run the code in if block and jump it:
$ python3.3
Python 3.3.1 (default, Apr 17 2013, 22:30:32)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(1) if None else print(0)
0
>>> print(1) if not None else print(0)
1
Have fun coding ;)
|
Python sort a list by two values
Question: I'm trying to sort this list first by name in reverse. Then, after the first
set of results (where flag = "ZAR"), I want to sort the remaining elements by
time not in reverse:
import operator
list = [
{"flag":"ZAR", "time":"17:45"},
{"flag":"AUS", "time":"17:30"},
{"flag":"AUS", "time":"17:15"},
{"flag":"USA", "time":"17:00"},
{"flag":"GBP", "time":"16:55"},
{"flag":"ZAR", "time":"16:45"},
{"flag":"USA", "time":"16:35"},
{"flag":"GBP", "time":"16:25"},
{"flag":"ZAR", "time":"16:15"},
]
list.sort(key=operator.itemgetter("time"))
list.sort(key=operator.itemgetter("flag"),reverse=True)
print list
[{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]
As you can see the flag sort was done correctly, but the other elements are
only sorted by time within the sorted country.
What I want is to always have the ZAR first and after that it does not matter
what the flag name is, only the time. So it should give this result:
[{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]
How would this be done?
Answer: Amend your code to:
import operator
data = [
{"flag":"ZAR", "time":"17:45"},
{"flag":"AUS", "time":"17:15"},
{"flag":"USA", "time":"17:00"},
{"flag":"GBP", "time":"16:55"},
{"flag":"ZAR", "time":"16:45"},
{"flag":"USA", "time":"16:35"},
{"flag":"GBP", "time":"16:25"},
{"flag":"ZAR", "time":"16:15"},
]
data.sort(key=operator.itemgetter("time"))
data.sort(key=lambda L: L['flag'] == 'ZAR', reverse=True)
# [{'flag': 'ZAR', 'time': '16:15'}, {'flag': 'ZAR', 'time': '16:45'}, {'flag': 'ZAR', 'time': '17:45'}, {'flag': 'GBP', 'time': '16:25'}, {'flag': 'USA', 'time': '16:35'}, {'flag': 'GBP', 'time': '16:55'}, {'flag': 'USA', 'time': '17:00'}, {'flag': 'AUS', 'time': '17:15'}, {'flag': 'AUS', 'time': '17:30'}]
|
Flask-Superadmin - 'module' object has no attribute 'FileField'
Question: I'm tring to launch simple code from the docs:
<https://flask-superadmin.readthedocs.org/en/latest/quickstart.html>
Here is the code:
from flask import Flask
from flask.ext.superadmin import Admin
app = Flask(__name__)
admin = Admin(app)
app.run()
but the following error occures:
Traceback (most recent call last):
File "test.py", line 2, in <module>
from flask.ext.superadmin import Admin
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask/exthook.py", line 62, in load_module
__import__(realname)
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/__init__.py", line 2, in <module>
from model import ModelAdmin
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/model/__init__.py", line 1, in <module>
from .base import ModelAdmin, AdminModelConverter
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/model/base.py", line 10, in <module>
from flask_superadmin.form import BaseForm, ChosenSelectWidget, DatePickerWidget, \
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/form.py", line 115, in <module>
class FileField(wtf.FileField):
AttributeError: 'module' object has no attribute 'FileField'
I use the following versions of libraries:
Flask==0.10.1
Flask-Script==0.6.2
Flask-SuperAdmin==1.7
Flask-WTF==0.9.1
flask-mongoengine==0.7.0
WTForms==1.0.4
What is wrong, or where could I find working examples?
Answer: This is a bug in the import. I fixed it in my
[fork](https://github.com/burhan/Flask-SuperAdmin); clone from there and then
try it again.
|
pygame and python not working for me
Question: I'm just starting out with pygame and I'm have a bit of an issue, here is my
code...
import pygame, sys from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
and here is the error i keep getting...
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1521, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Jason\Documents\Python\pygame.… line 1, in <module>
import pygame, sys
File "C:\Users\Jason\Documents\Python\pygame.… line 2, in <module>
from pygame.locals import *
ImportError: No module named 'pygame.locals'; pygame is not a package
So my question is how do i get pygame to work with python? python version
3.3.2 pygame version: Python 3.3 pygame-1.9.2pre(64-bit)
Answer: Your pygame install was no successful what you need to do is install python
2.7 from [here](http://www.python.org/download/releases/2.7/)
then you need to reinstall your pygame. If you are using python 3.3 you will
want to make a new install with the older version it will not delete your
newer one. Make sure that it says the install is sucsessful. If that doesn't
work try rebooting and/or reinstalling. GOOD LUCK!!
|
what is similar function to epoll's unregister function for kqueue?
Question: Python Epoll has function called epoll.unregister which removes a registered
file descriptor from the epoll object. Does any one know what is the function
in Kqueue which is similar this. For kqueue I could only find how to delete
events.
Answer: You use `kqueue.control` to register or unregister an event.
An example:
import select
import os
os.mkfifo('my.fifo')
f = os.open('my.fifo', os.O_RDONLY|os.O_NONBLOCK)
try:
kq = select.kqueue()
# Add FD to the queue
kq.control([select.kevent(f, select.KQ_FILTER_READ, select.KQ_EV_ADD|select.KQ_EV_ENABLE)], 0)
# Should break as soon as we received something.
i = 0
while True:
events = kq.control(None, 1, 1.0) # max_events, timeout
print(i, events)
i += 1
if len(events) >= 1:
print('We got:', os.read(f, events[0].data))
break
# Remove FD from the queue.
kq.control([select.kevent(f, select.KQ_FILTER_READ, select.KQ_EV_DELETE)], 0)
# Should never receive anything now even if we write to the pipe.
i = 0
while True:
events = kq.control(None, 1, 1.0) # max_events, timeout
print(i, events)
i += 1
if len(events) >= 1:
print('We got:', os.read(f, events[0].data))
break
finally:
os.close(f)
os.remove('my.fifo')
You could also check the [test
case](http://hg.python.org/cpython/file/tip/Lib/test/test_kqueue.py) for
kqueue to see how it's used. (And like `select()`, the file descriptor could
be any Python objects with a `fileno()` method as well.)
|
Count how many times a dictionary value is found with more than one key
Question: I'm working in python. Is there a way to count how many times values in a
dictionary are found with more than one key, and then return a count?
So if for example I had 50 values and I ran a script to do this, I would get a
count that would look something like this:
1: 23
2: 15
3: 7
4: 5
The above would be telling me that 23 values appear in 1 key, 15 values appear
in 2 keys, 7 values appear in 3 keys and 5 values appear in 4 keys.
Also, would this question change if there were multiple values per key in my
dictionary?
Here is a sample of my dictionary (it's bacteria names):
`{'0': ['Pyrobaculum'], '1': ['Mycobacterium', 'Mycobacterium',
'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium',
'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium',
'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium'], '3':
['Thermoanaerobacter', 'Thermoanaerobacter'], '2': ['Helicobacter',
'Mycobacterium'], '5': ['Thermoanaerobacter', 'Thermoanaerobacter'], '4':
['Helicobacter'], '7': ['Syntrophomonas'], '6': ['Gelria'], '9':
['Campylobacter', 'Campylobacter'], '8': ['Syntrophomonas'], '10':
['Desulfitobacterium', 'Mycobacterium']}`
So from this sample, there are 8 unique values, I the ideal feedback I would
get be:
1:4
2:3
3:1
So 4 bacteria names are only in one key, 3 bacteria are found in two keys and
1 bacteria is found in three keys.
Answer: If I understand correctly, you want to count the counts of dictionary values.
If the values are countable by `collections.Counter`, you just need to call
`Counter` on the dictionaries values and then again on the first counter's
values. Here is an example using a dictionary where the keys are `range(100)`
and the values are random between 0 and 10:
from collections import Counter
d = dict(enumerate([str(random.randint(0, 10)) for _ in range(100)]))
counter = Counter(d.values())
counts_counter = Counter(counter.values())
**EDIT** :
After the sample dictionary was added to the question, you need to do the
first count in a slightly different way (`d` is the dictionary in the
question):
from collections import Counter
c = Counter()
for v in d.itervalues():
c.update(set(v))
Counter(c.values())
|
Python, install .pyd file: ImportError: DLL load failed
Question: I am trying to install the PyLZJB.pyd file from here:
https://code.google.com/p/pylzjb/downloads/list
I have downloaded the file and placed it in my Python27/DLLs folder where I
also see some other .pyd files. I am on Windows.
I have tried
import PyLZJB.pyd
and
import PyLZJB
Based on another answer I also tried:
import sys
sys.path.append("C:\Python27\DLLs")
before the import.
I continue to get the message:
ImportError: DLL load failed: The specified module could not be found.
Answer: There's only dlls built for Python-2.6 in the site.
You cannot use dll built for Python2.6 in Python 2.7.
Find the dll built for your system (platform, python version should match). Or
build it yourself.
|
ImportError: No module named mpl_toolkits with maptlotlib 1.3.0 and py2exe
Question: I can't figure out how to be able to package this via py2exe now:
I am running the command:
python setup2.py py2exe
via python 2.7.5 and matplotlib 1.3.0 and py2exe 0.6.9 and 0.6.10dev
This worked with matplotlib 1.2.x
I have read <http://www.py2exe.org/index.cgi/ExeWithEggs> and tried to
implement the suggestions for handling the mpl_toolkits since it's having
become a namespace package.
I'm trying to get an answer here too:
<http://matplotlib.1069221.n5.nabble.com/1-3-0-and-py2exe-regression-
td41723.html>
Adding an empty `__init__.py` to mpl_toolkits makes it work, but this is only
a workaround to the problem.
**Can anyone suggest what I need to make py2exe work with
mpl_toolkits.axes_grid1 in matplotlib 1.3.0 ?:**
* * *
test_mpl.py is:
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
if __name__ == '__main__':
print make_axes_locatable, axes_size
* * *
setup2.py is:
import py2exe
import distutils.sysconfig
from distutils.core import setup
# attempts to get it to work
import modulefinder
import matplotlib
import mpl_toolkits.axes_grid1
__import__('pkg_resources').declare_namespace("mpl_toolkits")
__import__('pkg_resources').declare_namespace("mpl_toolkits.axes_grid1")
modulefinder.AddPackagePath("mpl_toolkits", matplotlib.__path__[0])
modulefinder.AddPackagePath("mpl_toolkits.axes_grid1", mpl_toolkits.axes_grid1.__path__[0])
# end of attempts to get it to work
options={'py2exe': {'packages' : ['matplotlib', 'mpl_toolkits.axes_grid1', 'pylab', 'zmq'],
'includes': ['zmq', 'six'],
'excludes': ['_gdk', '_gtk', '_gtkagg', '_tkagg', 'PyQt4.uic.port_v3', 'Tkconstants', 'Tkinter', 'tcl'],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgdk_pixbuf-2.0-0.dll',
'libgobject-2.0-0.dll',
'tcl85.dll',
'tk85.dll'],
'skip_archive': True },}
setup(console=['test_mpl.py'], options=options)
* * *
output is:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "setup2.py", line 23, in <module>
setup(console=['test_mpl.py'], options=options)
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1308, in find_needed_modules
mf.import_hook(f)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named mpl_toolkits
Answer: There is a quite simple workaround to this problem. Find the directory from
which mpl_tools is imported and simply add an empty text file named
`__init__.py` in that directory. py2exe will now find and include this module
without any special imports needed in the setup file.
You can find the mpl_tools directory by typing the following in a python
console:
import importlib
importlib.import_module('mpl_toolkits').__path__
I found the solution here <http://stackoverflow.com/a/11632115/2166823> and it
seems to apply to namespace packages in general.
|
TF-IDF in python and not desired results
Question: I found a python tutorial on the web for calculating tf-idf and cosine
similarity. I am trying to play with it and change it a bit.
The problem is that I have weird results and almost without any sense.
For example I am using 3 documents. `[doc1,doc2,doc3]` doc1 and doc2 are
similars and doc3 are totaly different.
The results are here:
[[ 0.00000000e+00 2.20351188e-01 9.04357868e-01]
[ 2.20351188e-01 -2.22044605e-16 8.82546765e-01]
[ 9.04357868e-01 8.82546765e-01 -2.22044605e-16]]
First, I thought that the numbers on the main diagonal should be 1 and not 0.
After that, the similarity score for doc1 and doc2 is around 0.22 and doc1
with doc3 around 0.90. I expected the opposite results. Could you please check
my code and maybe help me understand why I have those results?
Doc1, doc2 and doc3 are tokkenized texts.
articles = [doc1,doc2,doc3]
corpus = []
for article in articles:
for word in article:
corpus.append(word)
def freq(word, article):
return article.count(word)
def wordCount(article):
return len(article)
def numDocsContaining(word,articles):
count = 0
for article in articles:
if word in article:
count += 1
return count
def tf(word, article):
return (freq(word,article) / float(wordCount(article)))
def idf(word, articles):
return math.log(len(articles) / (1 + numDocsContaining(word,articles)))
def tfidf(word, document, documentList):
return (tf(word,document) * idf(word,documentList))
feature_vectors=[]
for article in articles:
vec=[]
for word in corpus:
if word in article:
vec.append(tfidf(word, article, corpus))
else:
vec.append(0)
feature_vectors.append(vec)
n=len(articles)
mat = numpy.empty((n, n))
for i in xrange(0,n):
for j in xrange(0,n):
mat[i][j] = nltk.cluster.util.cosine_distance(feature_vectors[i],feature_vectors[j])
print mat
Answer: if you can try any other package such as sklearn then try it
this code might help
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import numpy.linalg as LA
from sklearn.feature_extraction.text import TfidfVectorizer
f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")
train_set = [doc1, doc2, doc3]
test_set = ["age salman khan wife"] #Query
stopWords = stopwords.words('english')
tfidf_vectorizer = TfidfVectorizer(stop_words = stopWords)
tfidf_matrix_test = tfidf_vectorizer.fit_transform(test_set)
print tfidf_vectorizer.vocabulary_
tfidf_matrix_train = tfidf_vectorizer.transform(train_set) #finds the tfidf score with normalization
print 'Fit Vectorizer to train set', tfidf_matrix_train.todense()
print 'Transform Vectorizer to test set', tfidf_matrix_test.todense()
print "\n\ncosine simlarity not separated sets cosine scores ==> ", cosine_similarity(tfidf_matrix_test, tfidf_matrix_train)
refer to this tutorials
[part-I](http://pyevolve.sourceforge.net/wordpress/?p=1589),[part-
II](http://pyevolve.sourceforge.net/wordpress/?p=1747),[part-
III](http://pyevolve.sourceforge.net/wordpress/?p=2497). This can help.
|
python multicore queue randomly hangs for no reason, despite queue size being tiny
Question: in python here is my multiprocessing setup. I subclassed the Process method
and gave it a queue and some other fields for pickling/data purposes.
This strategy works about 95% of the time, the other 5% for an unknown reason
the queue just hangs and it never finishes (it's common that 3 of the 4 cores
finish their jobs and the last one takes forever so I have to just kill the
job).
I am aware that queue's have a fixed size in python, or they will hang. My
queue only stores one character strings... the id of the processor, so it
can't be that.
Here is the exact line where my code halts:
res = self._recv()
Does anyone have ideas? The formal code is below. Thank you.
from multiprocessing import Process, Queue
from multiprocessing import cpu_count as num_cores
import codecs, cPickle
class Processor(Process):
def __init__(self, queue, elements, process_num):
super(Processor, self).__init__()
self.queue = queue
self.elements = elements
self.id = process_num
def job(self):
ddd = []
for l in self.elements:
obj = ... heavy computation ...
dd = {}
dd['data'] = obj.data
dd['meta'] = obj.meta
ddd.append(dd)
cPickle.dump(ddd, codecs.open(
urljoin(TOPDIR, self.id+'.txt'), 'w'))
return self.id
def run(self):
self.queue.put(self.job())
if __name__=='__main__':
processes = []
for i in range(0, num_cores()):
q = Queue()
p = Processor(q, divided_work(), process_num=str(i))
processes.append((p, q))
p.start()
for val in processes:
val[0].join()
key = val[1].get()
storage = urljoin(TOPDIR, key+'.txt')
ddd = cPickle.load(codecs.open(storage , 'r'))
.. unpack ddd process data ...
Answer: Do a `time.sleep(0.001)` at the beginning of your `run()` method.
|
Is there any way I can import the python 3 version of 'bytes' into python 2?
Question: I am writing python code and I want to support python 2 and 3. One of the most
prominent data types I'm dealing with is immutable sequences of bytes, so I
want to find an elegant way to deal with the disparity between python 2
'bytes' (aliased to 'str') and python 3 'bytes' (specifically, the different
ways in which they slice and iterate are very annoying to me).
At first I tried using 'bytearray' because it seemed to have the same behavior
in both python 2 and 3, but the fact that it is mutable is problematic,
because I need my objects to be hashable.
If there is no way to access the python3 'bytes' behavior in python 2, the
current solution I'm thinking of trying is this: convert all sequences
(whether they be python 2 'bytes'/'str' or python 3 'bytes') to tuples of
integers.
Is there anything else I should consider for a solution assuming I can't use
the python 3 'bytes' type in python 2?
Answer: Use [`six` module](http://pythonhosted.org/six/) and its [`b()`
literal](http://pythonhosted.org/six/#six.b) or [`binary_type`
class](http://pythonhosted.org/six/#six.binary_type). This will take burden of
checking Python version from you.
|
matplotlib bar3d clipping problems
Question: I am trying to create a 3D bar graph with Matplotlib 1.2.0 and Python 2.7.3. I
followed the advice in <http://www.mail-archive.com/matplotlib-
[email protected]/msg19740.html> and plotted the bar one by one, but
I am still getting rendering problems (i.e., bars on top of each other).
Moreover, I get the following when I invoke my code:
/usr/apps/python/lib/python2.7/site-
packages/mpl_toolkits/mplot3d/axes3d.py:1476: RuntimeWarning: divide by zero
encountered in divide for n in normals])
/usr/apps/python/lib/python2.7/site-
packages/mpl_toolkits/mplot3d/axes3d.py:1476: RuntimeWarning: invalid value
encountered in divide for n in normals])
My questions:
1. Are these serious warnings? Do I need to look into them and try to eliminate them? How do I eliminate them?
2. What is the difference between zsort='max' and zsort='average'?
3. What else can I do to eliminate rendering problems?
Thanks in advance!
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as colors
import matplotlib.cm as cmx
# my data
dat = [2.31778665482167e-310, 0.006232785101850947, 0.0285075971030949, 0.0010248181570355695, 0.0048776795767614825, 0.02877090365176044, 0.002459331469834533, 0.0008594610645495889, 0.002919824084878003, 0.000968081117692596, 0.0, 0.0, 0.0319623949119874, 0.00568752311279771, 0.009994801469036968, 0.03248018520506219, 0.006686905726805326, 0.005987863156039365, 0.0072955095915350045, 0.005568911905473998, 0.0, 0.0, 0.0, 0.028483143996551524, 0.031030793902192794, 0.06125216053962635, 0.02935971973938871, 0.028507530280092265, 0.030112963748812088, 0.028293406731749605, 0.0, 0.0, 0.0, 0.0, 0.004510645022825792, 0.028998119822468988, 0.0013993630391143715, 0.0010726572949244424, 0.002288215944285159, 0.0006513973584945584, 0.0, 1.1625e-320, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.03148966953869102, 0.005215047563268979, 0.004491716298086729, 0.006010166308872446, 0.005186976949223524, 0.0, 0.0, 0.0, 0.0, 0.0, 1.107e-320, 0.02983657915729719, 0.028893006725328373, 0.030526067389954753, 0.028629390713739978, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0015217840289869456, 0.002751587509779179, 0.001413669523724954, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0024680339073824705, 0.0008254364860386303, 0.0, 0.0, 0.0, 9.965e-321, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.0, 0.0, 0.002621588539481613, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.41e-321, 1.15348834e-316, 2.3177866547513e-310]
dat = np.reshape(dat,[10,10],order='F')
lx = len(dat[0])
ly = len(dat[:,0])
n = lx*ly
# generate colors
cm = plt.get_cmap('jet')
vv = range(len(dat))
cNorm = colors.Normalize(vmin=0, vmax=vv[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
colorVals = [scalarMap.to_rgba(i) for i in range(ly)]
# generate plot data
xpos = np.arange(0,lx,1)
ypos = np.arange(0,ly,1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(n)
dx = 0.5*np.ones_like(zpos)
dy = dx.copy()
dz = dat.flatten()
cc = np.tile(range(lx), (ly,1))
cc = cc.T.flatten()
# generate plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
opacity = 1
for i in range(n):
ax.bar3d(xpos[i], ypos[i], zpos[i], dx[i], dy[i], dz[i],
color=colorVals[cc[i]], alpha=opacity, zsort='max')
plt.autoscale(enable=True, axis='both', tight=True)
plt.grid()
plt.show(block=False)
Answer: This isn't the answer that you are looking for, but I think that this might be
a bug in matplotlib. I think that the same problem was [encountered
here](https://github.com/matplotlib/matplotlib/issues/1292/). The problem was
described as "intractable" according to the [mplot3d
FAQ](http://matplotlib.org/mpl_toolkits/mplot3d/faq.html#my-3d-plot-doesn-t-
look-right-at-certain-viewing-angles).
But to me it doesn't seem intractable. You simple need to figure out which
object is closer to the viewer and set the z-order accordingly. So, I think
that the problem might just be a bug.
If I take the matplotlib 3D [histogram
example](http://matplotlib.org/examples/mplot3d/hist3d_demo.html) and just
change "bins=4" to "bins=6" or a higher number, then I get the same
"axes3d.py:1476: RuntimeWarning: invalid value encountered in divide / for n
in normals])". Also, I can reproduce the wrong z-order of the bars (check out
the tall guy near the front who jumps in front of his short friend):

The incorrect ordering of the bars seems linked to the divide by zero error,
since the plots look just fine when I use a smaller number of bins.
Line 1476 in axes.py is:
shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5]) for n in normals])
Basically, I think it is trying to figure out the shading using the normal
vectors to each face. But, one or more of the normal vectors is zero, which
should not be the case. So, I think that this is just some bug in matplotlib
that can probably be fixed by someone with more programming skills than
myself.
The mplot3d FAQ is correct that MayaVI can be used if you want a better 3D
engine. I used
from mayavi import mlab
mlab.barchart(xpos,ypos,dz*100)
to generate a plot of your data: 
I hope that this gets figured out soon. I would like to make some similar 3D
barcharts in the near future.
|
Solve sparse upper triangular system
Question: I'm trying to figure out how to efficiently solve a sparse triangular system,
Au*x = b in scipy sparse.
For example, we can construct a sparse upper triangular matrix, Au, and a
right hand side b with:
import scipy.sparse as sp
import scipy.sparse.linalg as sla
import numpy as np
n = 2000
A = sp.rand(n, n, density=0.4) + sp.eye(n)
Au = sp.triu(A).tocsr()
b = np.random.normal(size=(n))
We can get a solution to the problem using spsolve, however it is clear that
the triangular structure is not being taken advantage of. This can be
demonstrated by timing the solution and comparing it to the solve method in
splu. (Here using iPython's %time magic)
%time x1 = sla.spsolve(Au,b)
CPU times: user 3.63 s, sys: 79.1 ms, total: 3.71 s
Wall time: 1.1 s
%time Au_lu = sla.splu(Au)
CPU times: user 3.61 s, sys: 62.2 ms, total: 3.67 s
Wall time: 1.08 s
%time x2 = Au_lu.solve(b)
CPU times: user 25 ms, sys: 332 µs, total: 25.4 ms
Wall time: 7.01 ms
As Au is already upper-triangular the call to splu really shouldn't be doing
much of anything, however, as n gets large this call becomes prohibitively
expensive (as does the use of spsolve), while the solve time remains small.
Is there any way of using superLU's triangular solver without first calling
splu? Or is there a better way of doing this altogether?
Answer: I'm afraid this isn't terribly instructive, but have you tried changing the
column permutation? When I use "NATURAL", I get huge speedups.
%time x1 = sla.spsolve(Au, b, permc_spec="NATURAL")
CPU time: user 46.7 ms, sys: 0 ns, total: 46.7 ms
Wall time: 49 ms
For me, it's not quite as fast as using the solve methods of the splu function
output, but it seems to get reasonably close (and avoids calling splu).
Perhaps that will suffice? [Scipy
Docs](http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.spsolve.html#scipy.sparse.linalg.spsolve)
|
Progress indicator during pandas operations (python)
Question: I regularly perform pandas operations on data frames in excess of 15 million
or so rows and I'd love to have access to a progress indicator for particular
operations.
Does a text based progress indicator for pandas split-apply-combine operations
exist?
For example, in something like:
df_users.groupby(['userID', 'requestDate']).apply(feature_rollup)
where `feature_rollup` is a somewhat involved function that take many DF
columns and creates new user columns through various methods. These operations
can take a while for large data frames so I'd like to know if it is possible
to have text based output in an iPython notebook that updates me on the
progress.
So far, I've tried canonical loop progress indicators for Python but they
don't interact with pandas in any meaningful way.
I'm hoping there's something I've overlooked in the pandas
library/documentation that allows one to know the progress of a split-apply-
combine. A simple implementation would maybe look at the total number of data
frame subsets upon which the `apply` function is working and report progress
as the completed fraction of those subsets.
Is this perhaps something that needs to be added to the library?
Answer: Due to popular demand, `tqdm` has added support for `pandas`. Unlike the other
answers, this **will not noticeably slow pandas down** \-- here's an example
for `DataFrameGroupBy.progress_apply`:
import pandas as pd
import numpy as np
from tqdm import tqdm, tqdm_pandas
df = pd.DataFrame(np.random.randint(0, int(1e8), (10000, 1000)))
# Create and register a new `tqdm` instance with `pandas`
# (can use tqdm_gui, optional kwargs, etc.)
tqdm_pandas(tqdm())
# Now you can use `progress_apply` instead of `apply`
df.groupby(0).progress_apply(lambda x: x**2)
In case you're interested in how this works (and how to modify it for your own
callbacks), see the [examples on
github](https://github.com/tqdm/tqdm/tree/master/examples), the [full
documentation on pypi](https://pypi.python.org/pypi/tqdm), or import the
module and run `help(tqdm)`.
**EDIT**
* * *
To directly answer the original question, replace:
df_users.groupby(['userID', 'requestDate']).apply(feature_rollup)
with:
from tqdm import tqdm, tqdm_pandas
tqdm_pandas(tqdm())
df_users.groupby(['userID', 'requestDate']).progress_apply(feature_rollup)
|
Sorting and Organization of letter frequency - python
Question: I'm trying to find a way to count the number of occurrences of letters in a
text file than display them in greatest to lowest depending upon there
frequency. This is what I have so far, please help get over this brain block.
def me():
info= input("what file would you like to select?")
filehandle= open(info,"r")
data=filehandle.read()
case = data.upper()
s=('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
for i in range(26):
print(s[i],case.count(s[i]))
me()
Answer: Python has a nice built-in class for this: `collections.Counter`.
In [8]: from collections import Counter
In [9]: with open('Makefile', 'r') as f:
...: raw = Counter(f.read())
...:
In [10]: raw
Out[10]: Counter({' ': 61, 'e': 46, 'p': 38, 'a': 29, '\n': 27, 'c': 27, 'n': 27, 'l': 26, 'd': 25, '-': 22, 's': 22, 'y': 22, 't': 20, 'i': 18, 'o': 18, 'r': 17, '.': 16, 'u': 13, '\t': 12, 'm': 12, 'b': 11, 'x': 10, 'h': 9, '/': 8, ':': 8, '_': 7, "'": 6, ';': 5, '\\': 5, 'f': 5, '*': 3, 'v': 3, '{': 3, '}': 3, 'k': 2, 'H': 1, 'O': 1, 'N': 1, 'P': 1, 'Y': 1, 'g': 1})
This is from the `pandas` library's `Makefile`, BTW. To sort them by their
frequency in descending order, do:
In [22]: raw.most_common()
Out[22]:
[(' ', 61),
('e', 46),
('p', 38),
('a', 29),
('\n', 27),
('c', 27),
('n', 27),
('l', 26),
('d', 25),
('-', 22),
('s', 22),
('y', 22),
('t', 20),
('i', 18),
('o', 18),
('r', 17),
('.', 16),
('u', 13),
('\t', 12),
('m', 12),
('b', 11),
('x', 10),
('h', 9),
('/', 8),
(':', 8),
('_', 7),
("'", 6),
(';', 5),
('\\', 5),
('f', 5),
('*', 3),
('v', 3),
('{', 3),
('}', 3),
('k', 2),
('H', 1),
('O', 1),
('N', 1),
('P', 1),
('Y', 1),
('g', 1)]
I'm purposefully not using your exact data so that you can try and adapt my
solution to your problem.
|
Python interactive shell running copy.py on current directory?
Question: I have a script named `copy.py` on my current directory with the following
content:
#!/usr/bin/env python3
print("Ahoy, matey!")
If I run Python interactive shell and do some action which raise an exception
(e.g. referring to non-existent variable), to my surprise, the sentence "Ahoy,
matey!" got printed.
When I rename the `copy.py` script to anything else, e.g. `script.py`, it no
longer behaves like that. My question is, why the interactive shell have to
call `copy.py` on error? Is this behavior expected and/or documented
somewhere?
Thanks!
Answer: When Python imports a module, the [module search path
order](http://docs.python.org/3.3/tutorial/modules.html#the-module-search-
path) is:
* the directory containing the input script (or the current directory).
* PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
* the installation-dependent default.
Now, when raising an exception, Python runs specific code. Any code that tries
to import the `copy` Python module will instead import your module and print
the string in it. This is why you shouldn't use names that are also names of
standard Python modules.
|
Python: How to time script from beginning to end?
Question: I've created a script which processes files and returns the size of each file
in bytes. The time it takes is dependent on how large the directory is that
you scan.
At the top of my script, I placed in:
now = "\n", strftime("%Y-%m-%d %H:%M:%S", gmtime())
print "Started processing data at:",now
and at the bottom:
finish = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print "Finished processing data at: ", strftime("%Y-%m-%d %H:%M:%S", gmtime())
difference = now.strftime("%H:%M:%S", gmtime()) - finish.strftime("%H:%M:%S", gmtime())
I didn't think it was going to work, but I hope you understand my logic. I
want to subtract the `now` hours, minutes & seconds from the `finish` hours,
minutes & seconds.
What is the correct way of doing this?
Many thanks.
Answer: Try datetime module.
from datetime import datetime
start = datetime.now()
Later
difference = datetime.now() - start
|
Subscribe and unsubscribe to channels after the connection has been made with txredisapi
Question: Working with Python, Twisted, Redis and txredisapi.
How can I get the SubscriberProtocol for subscribe and unsubscribe to channels
after the connection has been made?
I guess I need to get the instance of the SubscriberProtocol and then I can
use "subscribe" and "unsubscribe" methods but don't know how to get it.
**Code example:**
import txredisapi as redis
class RedisListenerProtocol(redis.SubscriberProtocol):
def connectionMade(self):
self.subscribe("channelName")
def messageReceived(self, pattern, channel, message):
print "pattern=%s, channel=%s message=%s" %(pattern, channel, message)
def connectionLost(self, reason):
print "lost connection:", reason
class RedisListenerFactory(redis.SubscriberFactory):
maxDelay = 120
continueTrying = True
protocol = RedisListenerProtocol
Then from outside of these classes:
# I need to sub/unsub from here! (not from inside de protocol)
protocolInstance = RedisListenerProtocol # Here is the problem
protocolInstance.subscribe("newChannelName")
protocolInstance.unsubscribe("channelName")
Any suggestion?
Thanks!
* * *
**The next code solves the problem:**
@defer.inlineCallbacks
def subUnsub():
deferred = yield ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)
deferred.subscribe("newChannelName")
deferred.unsubscribe("channelName")
**Explanation:** Use "ClientCreator" to get an instance of SubscriberProtocol
inside a function with the flag "@defer.inlineCallbacks" and don't forget the
"yield" keyword for wait to complete the deferred data. Then you can use this
deferred to suscribe and unsubscribe.
In my case I forgot the yield keyword, so the deferred wasn't complete and the
method suscribe and unsubscribe didn't work.
Answer:
connecting = ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)
def connected(listener):
listener.subscribe("newChannelName")
listener.unsubscribe("channelName")
connecting.addCallback(connected)
|
Looking for an algorithm to count the number of possible patterns
Question: I need your help in constructing an algorithm to solve the following problem:
`A 5x5 table can be filled with the values 0 and 1 so that each line and
each column of the table consists of exactly two ones and three zeros. How
many solutions exist?`
If you want to provide some code, you can freely use your preferred language.
I mostly use R, Matlab and Python.
I tried to convert the table into a vector:
unique(perms([ones(1,10),zeros(1,15)]), 'rows')
Then, for each row, I would form the 5x5 table and check if all row sums and
col sums equal 2. But the above command generated the error: `??? Maximum
variable size allowed by the program is exceeded.`
Answer: Here is a python expression that bute forces all the matrices with two 1s per
row:
from itertools import *
print len(filter(
lambda candidate: all(imap(
lambda index: sum(imap(lambda _: _[index], candidate)) == 2,
xrange(5)
)),
product(set(permutations([0,0,0,1,1])), repeat=5)
))
|
printing long string with a single write call
Question: I found a quite unexpected feature(or bug ?) when trying to write a long
string with a single `write` call using python (python 2.7.3-32 bit, windows
7).
Calling `print "a"*4000` prints on stdout a line that seems ok but calling
`print "a"*5000` just produces a line with 5000 white spaces instead of 'a'
character.
Would you have any idea of what is going wrong and how I can circumvent that
problem ?
Additional information:
using a newer version of python (2.7.5) still produces the same error. Here is
a snippet that produces the aformentionned problem.
f = open("toto.dat","w",1000000)
s = "a"*5000
f.write(s)
f.write("\n")
f.close()
thanks a lot.
Eric
Answer: Maybe a problem of buffer ?
Try this please:
from os import fsync
fh = open("test.dat","w")
s = "a"*5000
fh.write(s)
fh.write("\n")
fh.flush()
fsync(fh.fileno())
fh.close()
There's no reason that closing the file-handler wouldn't empty the buffer and
write in the file, as far as I know, but who knows ?....
|
python threading : cannot switch thread to Daemon
Question: I would expect next code to be executed simultaneously and all filenames from
os.walk iterations , that got 0 at random , will get in result dictionary. And
all threads that have some timeout would get into deamon mode and will be
killed as soon as script reaches end. However, script respects all timeouts
for each thread.
Why is this happening? Should it put all threads in backgroung and kill them
if they will not finish and return result before the end of script execution?
thank you.
import threading
import os
import time
import random
def check_file(file_name,timeout):
time.sleep(timeout)
print file_name
result.append(file_name)
result = []
for home,dirs,files in os.walk("."):
for ifile in files :
filename = '/'.join([home,ifile])
t = threading.Thread(target=check_file(filename,random.randint(0,5)))
t.setDaemon(True)
t.start()
print result
Solution: I found my mistake:
t = threading.Thread(target=check_file(filename,random.randint(0,5)))
has to be
t = threading.Thread(target=check_file, args=(filename,random.randint(0,5)))
In this case, threading will spawn a thread with function as object ang give
it arguments. In my initial example, function with args has to be resolved
BEFORE thread spawns. And this is fair.
However, example above works for me at 2.7.3 , but at 2.7.2 i cannot make it
working. I `m getting got exception that
function check_file accepts exactly 1 argument (34 is given).
Soulution : in 2.7.2 i had to put ending coma in args tuple , considering that
i have 1 variable only . God knows why this not affects 2.7.3 version . It was
t = threading.Thread(target=check_file, args=(filename))
and started to work with
t = threading.Thread(target=check_file, args=(filename,))
Answer: I understand what you were trying to do, but you're not using the right format
for threading. I fixed your example...look up the Queue class on how to do
this properly.
Secondly, never ever do string manipulation on file paths. Use the `os.path`
module; there's a lot more than adding separators between strings that you and
I don't think about most of the time.
Good luck!
import threading
import os
import time
import random
import Queue
def check_file():
while True:
item = q.get()
time.sleep(item[1])
print item
q.task_done()
q = Queue.Queue()
result = []
for home,dirs,files in os.walk("."):
for ifile in files:
filename = os.path.join(home, ifile)
q.put((filename, random.randint(0,5)))
number_of_threads = 25
for i in range(number_of_threads):
t = threading.Thread(target=check_file)
t.daemon = True
t.start()
q.join()
print result
|
python: checking for errors in the users input
Question: I would like to check if a string can be a float before I attempt to convert it
to a float. This way, if the string is not float, we can print an error message
and exit instead of crashing the program. so when the user inputs something, I
wanna see if its a float so it will print "true" if its not then it will
print"false" rather than crashing. I don't want to use built in functions for
this. I need to make my own function for this.
I tried : import types
def isFloat():
x = raw_input("Enter: ")
if(x) == float:
print("true")
if(x) == str:
print("false")
isFloat()
I don't know if its true or not but it wont work it wont print anything either
Answer: The recommended thing to do here is to `try` it:
try:
f = float(x)
print("true")
except ValueError:
# handle error here
print("false")
This underscores the Python philosophy _"It's better to ask for forgiveness
than for permission"_.
|
Python bottle accept data send by jquery
Question: I'm using Python bottle, html/css, and Javascript to develop a website. Now in
the Javascript part, I want to send a list data to the back end Python using
Jquery:
$.ajax({
type: "POST",
url: '/deleteauthor',
data: keys,
success: function() {
for (var i=0, n=checkboxes.length; i<n; ++i)
if (checkboxes[i].checked==true) {
var id = "#" + checkboxes[i].value;
$(id).hide();
}
}
});
In the Python bottle side, how can I receive the the data?
Answer: Something like:
from bottle import route, run, request
@route('/deleteauthor', method='POST')
def index():
request.body.seek(0)
data = request.body.read()
#do something with data
run(host='localhost', port=8080, debug=True)
|
Downloading files from an HTTP that looks like a FTP
Question: Thinking that I was dealing with a ftp site, I tried to login to
e4ftl01.cr.usgs.gov/ using this Python simple script:
import ftplib
ftp = ftolib.FTP("e4ftl01.cr.usgs.gov")
ftp.login()
I got this error:
socket.error: [Errno 101] Network is unreachable
which is probably because the site is actually HTTP.
Now, my goal is to download files from the folders within the site, and it
seems like ftplib is not working in this case, or am I wrong? What solution
would you suggest?
Answer: Well, I found this simple solution:
import urllib
urllib.urlretrieve("http://e4ftl01.cr.usgs.gov/MOLT/MOD11A1.005/2012.07.11/BROWSE.MOD11A1.A2012193.h00v08.005.2012196013549.1.jpg","Downloaded.jpg")
|
Segmentation fault: 11 when importing math into Python
Question: It crashes everytime I try to import from math. Is there a way to reinstall
the math library? I'm on Python 3.3.2.
sidwyn$ python3
>>> from math import pi
Segmentation fault: 11
Answer: Please try this:
$ env -i python3.3
>>> import faulthandler
>>> faulthandler.enable()
>>> import math
>>> math
<module 'math' (built-in)>
>>> from math import pi
# should segfault
and try to run python inside the GNU debugger. You have to type "run" into the
gdb shell to start Python and "backtrace" to get the C call stack.
$ gdb python3.3
(gdb) run
>>> from math import pi
# should segfault
(gdb) backtrace
and post the output here.
|
How can I programmatically change the argspec of a function *not* in a python decorator?
Question: Very closely related to: [How can I programmatically change the argspec of a
function in a python
decorator?](http://stackoverflow.com/questions/3729378/how-can-i-
programmatically-change-the-argspec-of-a-function-in-a-python-decorato)
The decorator module provides the means to make a decorator function that
preserves the argspec of the decorated function.
If I define a function that is not used as a decorator, is there a way to copy
another function's argspec?
Example use case:
class Blah(object):
def foo(self, *args, **kwargs):
""" a docstr """
result = bar(*args, **kwargs)
result = result**2 # just so it's clear we're doing something extra here...
return result
def bar(x, y, z=1, q=2):
""" a more useful docstr, saying what x,y,z,q do """
return x+y*z+q
I would like to have `foo`'s argspec look like `bar`'s, but the source to stay
unchanged (i.e., `inspect.getsource(foo)` would still show the `result` junk).
The main purpose for this is to get sphinx docs and ipython's interactive help
to show the appropriate arguments.
As the answers to the other question said, the [decorator
package](http://code.google.com/p/micheles/source/browse/decorator/src/decorator.py)
shows a way to do this, but I got lost within the meat of that code. It seems
that the `decorator` package is recompiling the source, or something like
that. I had hoped a simpler approach, e.g. something like `foo.argspec =
bar.argspec`, would be possible.
Answer: A decorator is simply a function that does something with another function.
So, technically, you could put the required code directly underneath the `foo`
method and then, technically, you would be changing `foo` without using a
decorator, but it would be a horrible mess.
The easiest way to do what you want is going to be to make a decorator that
takes a second function (`bar` in this case) as an argument so it knows which
signature to copy. The class code would then look something like:
class Blah(object):
@copy_argspec(bar)
def foo(self, *args, **kwargs):
""" a docstr """
result = bar(*args, **kwargs)
result = result**2 # just so it's clear we're doing something extra here...
return result
You'll have to have `bar` defined before instead of after the class.
.
.
.
. . . _time passes_ . . . .
.
.
Okay, luckily I found an old decorator I could adapt.
`help(Blah.foo)` looks like this before decoration:
Help on method foo in module __main__:
foo(self, *args, **kwargs) unbound __main__.Blah method
a docstr
and after decoration it looks like this:
Help on method foo in module __main__:
foo(self, x, y, z=1, q=2) unbound __main__.Blah method
a more useful docstr, saying what x,y,z,q do
Here's the decorator I used:
import inspect
class copy_argspec(object):
"""
copy_argspec is a signature modifying decorator. Specifically, it copies
the signature from `source_func` to the wrapper, and the wrapper will call
the original function (which should be using *args, **kwds). The argspec,
docstring, and default values are copied from src_func, and __module__ and
__dict__ from tgt_func.
"""
def __init__(self, src_func):
self.argspec = inspect.getargspec(src_func)
self.src_doc = src_func.__doc__
self.src_defaults = src_func.func_defaults
def __call__(self, tgt_func):
tgt_argspec = inspect.getargspec(tgt_func)
need_self = False
if tgt_argspec[0][0] == 'self':
need_self = True
name = tgt_func.__name__
argspec = self.argspec
if argspec[0][0] == 'self':
need_self = False
if need_self:
newargspec = (['self'] + argspec[0],) + argspec[1:]
else:
newargspec = argspec
signature = inspect.formatargspec(
formatvalue=lambda val: "",
*newargspec
)[1:-1]
new_func = (
'def _wrapper_(%(signature)s):\n'
' return %(tgt_func)s(%(signature)s)' %
{'signature':signature, 'tgt_func':'tgt_func'}
)
evaldict = {'tgt_func' : tgt_func}
exec new_func in evaldict
wrapped = evaldict['_wrapper_']
wrapped.__name__ = name
wrapped.__doc__ = self.src_doc
wrapped.func_defaults = self.src_defaults
wrapped.__module__ = tgt_func.__module__
wrapped.__dict__ = tgt_func.__dict__
return wrapped
|
Calculator in python problems
Question: I made a calculator in python
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = input()
print("Number 2")
y = input()
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)
but when i run it and do for example 123 and 321 i get 123321 instead of 444,
what am i doing wrong, btw dont call me a noob im new to programming
Answer: `input()` returns string not number . That's why instead of addition , String
concatenation is performed.
you need to use `int(x)` and `int(y)` for conversion.
use this statement `answear = int(x) + int(y)`
|
Mining pdf Data with python through clipboard - Python Scripting the OS
Question: I have written a script that extracts data from pdf. I am using the
win32clipboard module to copy the the data into python. Got the logic working
on how to get the data I need in each file.
The shortcoming of my process is that I have to open each pdf Ctr-A to Select
all then Ctrl-C to get it into clipboard. I then run my script. for reference
it is running within Excel using DataNitro.
I have tried PDFMiner, but it seems like it is not being maintained and tend
break the text into small bits. The PDF that I am mining contain lots of
"small" tables. the copy from clipboard seem to do a pretty descent job of
keeping related things together.
Any suggestions on how I can script the opening of PDF selecting all and
copying. Basically I am looking for a python way to script the OS. Gut feel is
that this is not possible, but maybe somebody knows.
Answer: I have settled on using pyPdf. It has a simple method that just extracts the
text from the pdf. I have written simple functions to find the relevant
information I need in this text. Splitting the text into list for easy data
identification.
Have also written a loop to to pick up the relevant files using glob search
and feeding it into the parser.
import pyPdf
pdf = pyPdf.PdfFileReader(open(filename, "rb"))
data = ''
for page in pdf.pages:
data += page.extractText()
data2 = data.split('\n')
|
Execute in fabric run('hg pull')
Question: I'm developing some Django application on Windows host computer. I've created
fabfile with tasks. In one of my steps I execute something like that:
local("hg pull")
local("hg update")
and it works properly.
In other task I try to execute on remote machine something similar:
run("hg pull")
but after that I get error:
[XXX.XXX.XXX.XXX] run: hg pull
Exception in thread Thread-6:
Traceback (most recent call last):
File "C:\Python27\Lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "C:\Users\Grzegorz\VirtualEnvs\Dummy\lib\site-packages\paramiko\agent.py", line 116, in run
self._communicate()
File "C:\Users\Grzegorz\VirtualEnvs\Dummy\lib\site-packages\paramiko\agent.py", line 122, in _communicate
import fcntl
ImportError: No module named fcntl
Do you have any advices how can I pull and updated changes from my mercurial
repository?
Answer: OK, now it works. I didn't change anything in my virtual environments but set
proper path to my source code from repository and call something like that:
run('hg pull https://usr:[email protected]/account/myproject')
|
Scraping and stripping off child tags python
Question: I have following code structure from a website I wanna scrape.
<span class="blk">Society/Project: <b>Sai Sparsh</b></span>
<i class="blk">
Built-up Area: <b>1005 Sq.Ft.</b>
@ <i class="WebRupeesmall b mr_5 f14">Rs.</i>6109/sq.ft</i>
I am already scraping few data by the following code
properties = soup.findAll('a', title=re.compile('Bedroom'))
for eachproperty in properties:
print today,","+"http:/"+ eachproperty['href']+",", eachproperty.string+"," +",".join(re.findall("'([a-zA-Z0-9,\s]*)'", eachproperty['onclick']))
and my output is
2013-09-05 ,http://Residential-Apartment-Flat-in-Velachery-Chennai South-3-Bedroom-bhk-for-Sale-spid-E10766779, 3 Bedroom, Residential Apartment in Velachery,E10766779,9952946340,,Dealer,Bala
So for the above defined HTML sturcture I am trying to strip and get the
output as follows
Sai Sparsh, 1005 Sq.Ft, 6109/sq.ft
and attach it to the already generating output(mentioned above). I have been
breaking my head to navigate down the tree and use REGEX for it.
**Update**
Here is what I tried with the code
cname = soup.findAll('span', {'class':'blk'})
pmoney = soup.findAll('i',{'class':'blk'})
for eachproperty in cname:
for each in pmoney:
tey = re.sub('(\s{2,})', ' ', eachproperty.text)[17:]
ting = re.sub('([0-9,\s]*)', ' ', each.text)
print tey + ting
And my output is
Rams Jai Vignesh Built-up Area: 1050 Sq.Ft. @ Rs.5524/sq.ft
Shrudhi Homes Built-up Area: 1050 Sq.Ft. @ Rs.5524/sq.ft
Ashtalakshmi Homes Built-up Area: 1050 Sq.Ft. @ Rs.5524/sq.ft
Raj Flats Built-up Area: 1050 Sq.Ft. @ Rs.5524/sq.ft
But I want my output to not have 'Built-up Area:' ,' @ ', ' Rs '. So it should
be just
Rams Jai Vignesh ,1050 ,5524
Shrudhi Homes ,1050 , 5524
Answer: Why don't just use `text` property:
import re
from bs4 import BeautifulSoup as Soup
soup = Soup("""<span class="blk">Society/Project: <b>Sai Sparsh</b></span>
<i class="blk">
Built-up Area: <b>1005 Sq.Ft.</b>
@ <i class="WebRupeesmall b mr_5 f14">Rs.</i>6109/sq.ft</i>""")
print re.sub('(\s{2,})', ' ', soup.text)
prints:
Society/Project: Sai Sparsh Built-up Area: 1005 Sq.Ft. @ Rs.6109/sq.ft
FYI, `re.sub` is here to prettify the string, since there are multiple spaces
etc.
UPD: here's the scraper script for you:
import re
import urllib2
from bs4 import BeautifulSoup as Soup
html = urllib2.urlopen("http://www.99acres.com/property-in-velachery-chennai-south-ffid").read()
soup = Soup(html)
re_digit = re.compile('(\d+)')
for div in soup.find_all('div', {'class': 'sT_disc grey'}):
try:
project = div.find('span').find('b').text.strip()
except:
project = 'No project'
area = re.findall(re_digit, div.find('i', {'class': 'blk'}).text.strip())
print ", ".join([project] + area)
|
how to have a web.py python webservice return a jsonp call to jquery
Question: **So I'm trying to get a web.py based python webservice to send back a list
object trough JSONP after jQuery makes an ajax call to it.**
Problem is after reading up a lot of examples I'm still failing to understand
how to make it work. Here's the code I got I'm working with atm:
Javascript:
xmlrpcproxy = 'http://0.0.0.0:1885/'; //Back To The Future III reference on the port :)
jQuery.ajaxSetup ({
url: xmlrpcproxy, // <--- returns valid json if accessed in the browser
type: "GET",
cache: false,
contentType: "jsonp", // Pay attention to the dataType/contentType
dataType: 'jsonp', // Pay attention to the dataType/contentType
});
jQuery.ajax({
success: function(data) {
console.log("You made it!");
},
error: function (xhr) {
console.log("Error: " + xhr.statusText);
}
}).done(function(data){
console.log(data);
var firstoption = '<option value="select" selected>Please Select</option>';
jQuery("select#ItemIDSelect").html(firstoption);
var i;
var erplist = JSON.parse(data);
jQuery("responsearea").append(erplist);
for (i = 0; i < erplist.length; ++i) {
jQuery("select#ItemIDSelect").append('<option value="' + erplist[i] + '">' + erplist[i] + '</option>');
}
});
Python web.py code
#!/usr/bin/python
# _*_ encoding: utf-8 _*_
import web
import xmlrpclib
import json
urls = (
'/(.+)', 'index',
)
class index:
def GET(self):
#THE FOLLOWING IS A SUCCESFULL QUERY FOR DATA TO AN ERP SERVER
server = '***.***.*.**' #hidden the openerp server for stackoverflow post
username = 'admin' #the user
pwd = 'admin' #the password of the user
dbname = 'demo' #the database
# Get the uid
sock_common = xmlrpclib.ServerProxy ('http://%s:8069/xmlrpc/common'%(server))
uid = sock_common.login(dbname, username, pwd)
#replace localhost with the address of the server
sock = xmlrpclib.ServerProxy('http://%s:8069/xmlrpc/object'%(server))
# Unactive all product with a stock = 0.0 and using the ancient code
ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', [])
p_ids = sock.execute(dbname, uid, pwd, 'res.partner', 'read', ids, ['name'])
#END OF THAT PARTICULAR QUERY
a=[]
for p in p_ids:
a.append(p['name'])
b = json.dumps(a)
return 'some_function(' + b + ')
example: typical content of **b**
["The Jackson Group's Project", "Research & Development", "E-Learning Integration", "Website Design Templates", "Data Import/Export Plugin", "1", "Project XXX", "Contract Agrolait", "Project : Agrolait"]
Can anyone help? As I understand there is a way of setting the name of the
function in the javascript side so perhaps that would be one way to solve it,
setting that to some_function I mean. But all idea's/ways as how to fix this
are welcome ofc, so far nothing I tried worked >.<
Thanks for reading!
Answer: JQuery seems to provide callback function name in `callback` query param. And
make sure to set correct content type header.
callback_name = web.input(callback='callback').callback
web.header('Content-Type', 'application/javascript')
return '%s(%s)' % (callback_name, b)
|
Does selenium python bindings require firefox
Question: Hi I just downloaded and installed selenium but, I can't figure out how to get
it working I am using the following example as a test....
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox() #this is where I hit the error
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
assert "Google" in driver.title
driver.close()
I do not have firefox installed on my computer is this why it is giving me an
error? this is the error output I get when I try and run it
Traceback (most recent call last):
File "C:/Python27/test/helloworld.py", line 4, in <module>
driver = webdriver.Firefox()
File "C:\Python27\lib\site-packages\selenium-2.35.0-py2.7.egg\selenium\webdriver\firefox\webdriver.py", line 60, in __init__
self.binary, timeout),
File "C:\Python27\lib\site-packages\selenium-2.35.0-py2.7.egg\selenium\webdriver\firefox\extension_connection.py", line 47, in __init__
self.binary.launch_browser(self.profile)
File "C:\Python27\lib\site-packages\selenium-2.35.0-py2.7.egg\selenium\webdriver\firefox\firefox_binary.py", line 60, in launch_browser
self._start_from_profile_path(self.profile.path)
File "C:\Python27\lib\site-packages\selenium-2.35.0-py2.7.egg\selenium\webdriver\firefox\firefox_binary.py", line 83, in _start_from_profile_path
env=self._firefox_env).communicate()
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
WindowsError: [Error 87] The parameter is incorrect
Answer: Following line starts Firefox browser so yes, it requires installed Firefox.
driver = webdriver.Firefox()
If you don't have Firefox installed you can use different browser instead:
webdriver.Opera
webdriver.Ie
webdriver.Chrome
...
See
help(webdriver)
|
Can't create new threads in Python
Question:
import threading
threads = []
for n in range(0, 60000):
t = threading.Thread(target=function,args=(x, n))
t.start()
threads.append(t)
for t in threads:
t.join()
It is working well for range up to 800 on my laptop, but if I increase range
to more than 800 I get the error `can't create new thread`.
How can I control number to threads to get created or any other way to make it
work like timeout? I tried using `threading.BoundedSemaphore` function but
that doesn't seem to work properly.
Answer: The problem is that no major platform (as of mid-2013) will let you create
anywhere near this number of threads. There are a wide variety of different
limitations you could run into, and without knowing your platform, its
configuration, and the exact error you got, it's impossible to know which one
you ran into. But here are two examples:
* On 32-bit Windows, the default thread stack is 1MB, and all of your thread stacks have to fit into the same 2GB of virtual memory space as everything else in your program, so you will run out long before 60000.
* On 64-bit linux, you will likely exhaust one of your session's soft `ulimit` values before you get anywhere near running out of page space. (Linux has a variety of different limits beyond the ones required by POSIX.)
* * *
> So, how can i control number to threads to get created or any other way to
> make it work like timeout or whatever?
Using as many threads as possible is very unlikely to be what you actually
want to do. Running 800 threads on an 8-core machine means that you're
spending a whole lot of time context-switching between the threads, and the
cache keeps getting flushed before it ever gets primed, and so on.
Most likely, what you really want is one of the following:
* One thread per CPU, serving a pool of 60000 tasks.
* Maybe processes instead of threads (if the primary work is in Python, or in C code that doesn't explicitly release the GIL).
* Maybe a fixed number of threads (e.g., a web browsers may do, say, 12 concurrent requests at a time, whether you have 1 core or 64).
* Maybe a pool of, say, 600 batches of 100 tasks apiece, instead of 60000 single tasks.
* 60000 cooperatively-scheduled fibers/greenlets/microthreads all sharing one real thread.
* Maybe explicit coroutines instead of a scheduler.
* Or "magic" cooperative greenlets via, e.g. `gevent`.
* Maybe one thread per CPU, each running 1/Nth of the fibers.
* * *
But it's certainly _possible_.
Once you've hit whichever limit you're hitting, it's very likely that trying
again will fail until a thread has finished its job and been joined, and it's
pretty likely that trying again will succeed after that happens. So, given
that you're apparently getting an exception, you could handle this the same
way as anything else in Python: with a `try`/`except` block. For example,
something like this:
threads = []
for n in range(0, 60000):
while True:
t = threading.Thread(target=function,args=(x, n))
try:
t.start()
threads.append(t)
except WhateverTheExceptionIs as e:
if threads:
threads[0].join()
del threads[0]
else:
raise
else:
break
for t in threads:
t.join()
Of course this assumes that the first task launched is likely to be the one of
the first tasks finished. If this is not true, you'll need some way to
explicitly signal doneness (condition, semaphore, queue, etc.), or you'll need
to use some lower-level (platform-specific) library that gives you a way to
wait on a whole list until at least one thread is finished.
Also, note that on some platforms (e.g., Windows XP), you can get bizarre
behavior just getting _near_ the limits.
* * *
On top of being a lot better, doing the right thing will probably be a lot
simpler as well. For example, here's a process-per-CPU pool:
with concurrent.futures.ProcessPoolExecutor() as executor:
fs = [executor.submit(function, x, n) for n in range(60000)]
concurrent.futures.wait(fs)
… and a fixed-thread-count pool:
with concurrent.futures.ThreadPoolExecutor(12) as executor:
fs = [executor.submit(function, x, n) for n in range(60000)]
concurrent.futures.wait(fs)
… and a balancing-CPU-parallelism-with-numpy-vectorization batching pool:
with concurrent.futures.ThreadPoolExecutor() as executor:
batchsize = 60000 // os.cpu_count()
fs = [executor.submit(np.vector_function, x,
np.arange(n, min(n+batchsize, 60000)))
for n in range(0, 60000, batchsize)]
concurrent.futures.wait(fs)
* * *
In the examples above, I used a list comprehension to submit all of the jobs
and gather their futures, because we're not doing anything else inside the
loop. But from your comments, it sounds like you do have other stuff you want
to do inside the loop. So, let's convert it back into an explicit `for`
statement:
with concurrent.futures.ProcessPoolExecutor() as executor:
fs = []
for n in range(60000):
fs.append(executor.submit(function, x, n))
concurrent.futures.wait(fs)
And now, whatever you want to add inside that loop, you can.
* * *
However, I don't think you actually want to add anything inside that loop. The
loop just submits all the jobs as fast as possible; it's the `wait` function
that sits around waiting for them all to finish, and it's probably there that
you want to exit early.
To do this, you can use `wait` with the `FIRST_COMPLETED` flag, but it's much
simpler to use
[`as_completed`](http://docs.python.org/dev/library/concurrent.futures.html#concurrent.futures.as_completed).
Also, I'm assuming `error` is some kind of value that gets set by the tasks.
In that case, you will need to put a
[`Lock`](http://docs.python.org/dev/library/threading.html#threading.Lock)
around it, as with any other mutable value shared between threads. (This is
one place where there's slightly more than a one-line difference between a
`ProcessPoolExecutor` and a `ThreadPoolExecutor`—if you use processes, you
need `multiprocessing.Lock` instead of `threading.Lock`.)
So:
error_lock = threading.Lock
error = []
def function(x, n):
# blah blah
try:
# blah blah
except Exception as e:
with error_lock:
error.append(e)
# blah blah
with concurrent.futures.ProcessPoolExecutor() as executor:
fs = [executor.submit(function, x, n) for n in range(60000)]
for f in concurrent.futures.as_completed(fs):
do_something_with(f.result())
with error_lock:
if len(error) > 1: exit()
* * *
However, you might want to consider a different design. In general, if you can
avoid sharing between threads, your life gets a lot easier. And futures are
designed to make that easy, by letting you return a value or raise an
exception, just like a regular function call. That `f.result()` will give you
the returned value or raise the raised exception. So, you can rewrite that
code as:
def function(x, n):
# blah blah
# don't bother to catch exceptions here, let them propagate out
with concurrent.futures.ProcessPoolExecutor() as executor:
fs = [executor.submit(function, x, n) for n in range(60000)]
error = []
for f in concurrent.futures.as_completed(fs):
try:
result = f.result()
except Exception as e:
error.append(e)
if len(error) > 1: exit()
else:
do_something_with(result)
Notice how similar this looks to the [ThreadPoolExecutor
Example](http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-
example) in the docs. This simple pattern is enough to handle almost anything
without locks, as long as the tasks don't need to interact with each other.
|
Sublime Text 2 - SublimeREPL - key bindings for eval file stopped working
Question: On mac osx 10.8.4. Sublime Text 2.0.2
My python interpreter invoked through Tools -> SublimeREPL -> Python -> Python
Run current file will run the file that I wish it to run without issue.
However, when I invoke Tools -> SublimeREPL -> Eval in REPL -> File (^,,f),
nothing happens. Similarly, if I invoke Ctrl+, f nothing happens. I have
uninstalled SublimeREPL and then reinstalled, however, I am still seeing the
same issue. The user keymap config (Default (OSX).sublime-keymap) is empty.
When I invoke ^,,f the sublime console issues:
Traceback (most recent call last):
File "./sublime_plugin.py", line 356, in run_
File "./text_transfer.py", line 124, in run
ValueError: zero length field name in format
Excluding the option of uninstalling and re-install Sublime Text 2, are there
any ideas where I might start?
Thanks
**UPDATED**
Uninstalled ST 2, removed contents from ~/Library/Application Support/Sublime\
Text\ 2/
Installed ST 3, package manager, installed SublimeREPL. Create hello.py and
add:
import sys
def main():
print "Hello"
if __name__ == '__main__':
main()
Invoke Ctrl+, f results in nothing. Replace file contents with:
import sys
print "hello"
Invoke Ctrl+, f results in hello being echoed to REPL window. Why does the
former script not work while the latter runs fine...?
**Resolved** When opening REPL, I was selecting SublimeREPL -> Python:
IPython. Just selecting SublimeREPL -> Python to open the interpreter resolves
the issue.
Answer: **Resolved** When opening REPL, I was selecting SublimeREPL -> Python:
IPython. Just selecting SublimeREPL -> Python to open the interpreter resolves
the issue.
|
How to make Pacman's ghost randomly move around in Python?
Question: How do I make a ghost in Pacman move around randomly? I figured out how to
move your own player. I tried using the random.randiant command but instead it
kept coming up with a blank screen. I tried bliting all the images but it
still keeps coming up with a blank screen. I just want to experiment with the
ghost first before I program it to kill the player. I'm running Window 7,
Python 3.1 and Pygame 3.1.
import pygame, sys
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((640,480), 0, 32)
pygame.display.set_caption('Pacman')
background = pygame.image.load('back.jpg').convert()
pacman = pygame.image.load('aimball.png').convert_alpha()
ghost = pygame.image.load('ghosts.png').convert_alpha()
food = pygame.image.load('food.png').convert_alpha()
windowSurface.blit(background, (0,0))
windowSurface.blit(pacman, (0,0))
windowSurface.blit(pacman,(x,y))
windowSurface.blit(ghost, (100,100))
windowSurface.blit(ghost, (x,y ))
windowSurface.blit(food, (0,0))
def pacman():
x, y = 0,0
movex, movey = 0,0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_q:
pygame.quit()
sys.exit()
elif event.key == K_LEFT:
movex = -1
elif event.key == K_RIGHT:
movex = +1
elif event.key == K_UP:
movey = -1
elif event.key == K_DOWN:
movey = +1
elif event.type == KEYUP:
if event.key == K_LEFT:
movex = 0
elif event.key == K_RIGHT:
movex = 0
elif event.key == K_UP:
movey = 0
elif event.key == K_DOWN:
movey = 0
x+=movex
y+=movey
def ghosts():
x, y = 0,0
movex, movey = 0,0
while True:
random.randiant = move(1,2,3,4)
if random.randiant == 1:
movex=-1
elif random.randiant == 2:
movex=+1
elif random.randiant == 3:
movey=-1
elif random.randiant == 4:
movey=+1
x+=movex
y+=movey
windowSurface.blit(background,(0,0))
windowSurface.blit(pacman,(x,y))
windowSurface.blit(pacman, (0,0))
windowSurface.blit(ghost, (x,y ))
windowSurface.blit(ghost, (100,100))
windowSurface.blit(food, (0,0))
pygame.display.update()
pygame.display.flip()
NOTE: I will not be making boundaries for my Pacman game. The ghost can move
freely around the Pygame screen display.
Answer: so here is my pacman game, i hope it helps
import pygame
from pygame.locals import *
from sys import exit
import random as r
import time
# SET CHARECTERS POSITIONS START
player_x = 400
player_y = 200
ghost_1_x = -50
ghost_1_y = r.randint(1, 400)
ghost_2_x = r.randint(1, 800)
ghost_2_y = -50
ghost_3_x = 850
ghost_3_y = r.randint(1, 400)
ghost_4_x = r.randint(1, 800)
ghost_4_y = 450
point_x = r.randint(50, 750)
point_y = r.randint(10, 390)
# SET CHARECTERS POSITIONS END
# EXTRA VARIABLES START
points = .2
speed = points
running = True
size = 20
# EXTRA VARIABLES END
# START THE BEGINING OF THE MAIN PYTHON CODE START
pygame.init()
# START THE BEGINING OF THE MAIN PYTHON CODE END
# SET SCREEN SIZE START
screen = pygame.display.set_mode((800, 400))
# SET SCREEN SIZE END
# SET TITLE START
pygame.display.set_caption('my pac_man')
# SET TITLE END
# LOADING THE IMAGES OF THE CHARACTARS START
player = pygame.image.load ('pacman.png').convert()
ghost_1 = pygame.image.load('ghost1.png').convert()
ghost_2 = pygame.image.load('ghost2.png').convert()
ghost_3 = pygame.image.load('ghost1.png').convert()
ghost_4 = pygame.image.load('ghost2.png').convert()
point = pygame.image.load('Star.png').convert()
# LOADING THE IMAGES OF THE CHARECTERS END
# DEFINING DIRECTIONS START
up = 1
down = 2
left = 3
right = 4
# DEFINING DIRECTIONS END
# DEFINING STARTING DIRECTION VARIABLE START
direction = up
# DEFINING STARTING DIRECTION VARIABLE END
# MAIN GAME LOOP START
while running:
# TRANSFORMING THE IMAGES SO THAT THEY FIT ON THE SCREEN START
player = pygame.transform.scale(player, (size, size))
ghost_1 = pygame.transform.scale(ghost_1, (size, size))
ghost_2 = pygame.transform.scale(ghost_2, (size, size))
ghost_3 = pygame.transform.scale(ghost_1, (size, size))
ghost_4 = pygame.transform.scale(ghost_2, (size, size))
point = pygame.transform.scale(point, (size, size))
# TRANSFORMING THE IMAGES SO THAT THEY FIT ON THE SCREEN END
# EXTRA VARIABLES NEEDED IN GAME LOOP START
speed = points
# EXTRA VARIABLES NEEDED IN GAME LOOP END
# LOOK FOR EVENTS IN PYGAME START
for event in pygame.event.get():
# CHECK IF THE MOUSE HITS THE X START
if event.type == pygame.QUIT:
# IF THE MOUSE HITS THE X THEN EXIT START
pygame.quit()
exit()
# IF THE MOUSE HITS THE X THEN EXIT END
#CHECK IF THE MOUSE HITS THE X END
# SENCE A KEY IS PRESSED START
if event.type == pygame.KEYDOWN:
# SENCE IF AN ARROW KEY IS PRESSED
if event.key == pygame.K_LEFT:
direction = left
if event.key == pygame.K_RIGHT:
direction = right
if event.key == pygame.K_UP:
direction = up
if event.key == pygame.K_DOWN:
direction = down
# SENCE IF AN ARROW KEY IS PRESSED END
# SENCE IF A KEY IS PERSSED END
# LOOK FOR EVENTS IN PYGAME END
# PLAYER MOVEMENT START
if direction == up:
player_y -= speed
if direction == down:
player_y += speed
if direction == left:
player_x -= speed
if direction == right:
player_x += speed
# PLAYER MOVEMENT END
# PLAYER EDGE SENCING START
if player_x >= 800:
running = False
if player_x <= 0:
running = False
if player_y >= 400:
running = False
if player_y <= 0:
running = False
# PLAYER EDGE SENCING END
# GHOST 1 MOVEMENT START
if ghost_1_x <= player_x:
ghost_1_x += speed / 2
if ghost_1_x >= player_x:
ghost_1_x -= speed / 2
if ghost_1_y <= player_y:
ghost_1_y += speed / 2
if ghost_1_y >= player_y:
ghost_1_y -= speed / 2
# GHOST 1 MOVEMSNT END
# GHOST 2 MOVEMENT START
if ghost_2_x <= player_x:
ghost_2_x += speed / 2
if ghost_2_x >= player_x:
ghost_2_x -= speed / 2
if ghost_2_y <= player_y:
ghost_2_y += speed / 2
if ghost_2_y >= player_y:
ghost_2_y -= speed / 2
# GHOST 2 MOVEMSNT END
# GHOST 3 MOVEMENT START
if ghost_3_x <= player_x:
ghost_3_x += speed / 2
if ghost_3_x >= player_x:
ghost_3_x -= speed / 2
if ghost_3_y <= player_y:
ghost_3_y += speed / 2
if ghost_3_y >= player_y:
ghost_3_y -= speed / 2
# GHOST 3 MOVEMSNT END
# GHOST 4 MOVEMENT START
if ghost_4_x <= player_x:
ghost_4_x += speed / 2
if ghost_4_x >= player_x:
ghost_4_x -= speed / 2
if ghost_4_y <= player_y:
ghost_4_y += speed / 2
if ghost_4_y >= player_y:
ghost_4_y -= speed / 2
# GHOST 4 MOVEMSNT END
# BACKGROUND COLOR START
screen.fill((0, 0, 0))
# BACKGROUND COLOR END
# collision sencing format
# if rect_1 x < rect_2 x + rect_1 width and rect_1 x + rect_2 width > rect_2 x and rect_1 y < rect_2 y + rect_1 height and rect_1 height + rect_1 y > rect_2 y
# CHECKING FOR COLLISION START
if player_x < ghost_1_x + size and player_x + size > ghost_1_x and player_y < ghost_1_y + size and size + player_y > ghost_1_y:
running = False
if player_x < ghost_2_x + size and player_x + size > ghost_2_x and player_y < ghost_2_y + size and size + player_y > ghost_2_y:
running = False
if player_x < ghost_3_x + size and player_x + size > ghost_3_x and player_y < ghost_3_y + size and size + player_y > ghost_3_y:
running = False
if player_x < ghost_4_x + size and player_x + size > ghost_4_x and player_y < ghost_4_y + size and size + player_y > ghost_4_y:
running = False
if player_x < point_x + size and player_x + size > point_x and player_y < point_y + size and size + player_y > point_y:
points += 0.1
size += 5
point_x = r.randint(50, 750)
point_y = r.randint(10, 390)
# CHECKING FOR COLLISION END
# PLACE CHARACTERS START
screen.blit(player, (player_x, player_y))
screen.blit(ghost_1, (ghost_1_x, ghost_1_y))
screen.blit(ghost_2, (ghost_2_x, ghost_2_y))
screen.blit(ghost_3, (ghost_3_x, ghost_3_y))
screen.blit(ghost_4, (ghost_4_x, ghost_4_y))
screen.blit(point, (point_x, point_y))
# PLACE CHARECTERS END
# SHOW SCORE START
font = pygame.font.Font(None, size)
if size == 20:
text = font.render(('20'), 1, (255, 0, 0))
if size == 25:
text = font.render(('25'), 1, (255, 0, 255))
if size == 30:
text = font.render(('30'), 1, (255, 255, 0))
if size == 35:
text = font.render(('35'), 1, (0, 255, 0))
if size == 40:
text = font.render(('40'), 1, (0, 0, 255))
if size == 45:
text = font.render(('45'), 1, (255, 0, 255))
if size == 50:
text = font.render(('50'), 1, (255, 255, 255))
if size == 55:
text = font.render(('55'), 1, (255, 255, 255))
if size == 60:
text = font.render(('YOU WIN'), 1, (255, 255, 255))
screen.blit(text, (200,200))
# SHOW SCORE END
# UPDATE CHANGES IN CODE, VARIABLES, PICTURES, ECT... IN PYGAME START
pygame.display.update()
# UPDATE CHANGES IN CODE, VARIABLES, PICTURES, ECT... IN PYGAME END
# MAIN GAME LOOP END
|
TypeError: 'module' object is not callable when importing glob in Eclipse
Question: I am working with Eclipse Kepler(2013) and python 3.3.2 and running a simple
import like
import glob
a = glob.glob('*')
print(a)
gives a:
TypeError: 'module' object is not callable
This is not the case if I run the same code in Idle. I know I am missing
something.
Any help is appreciated.
Answer: Probably in your Eclipse environment there's a module named `glob` that gets
imported before the standard library one.
Try printing the `glob.__file__` to check it out.
|
wxPython EVT_CHAR not called when a panel is added to a frame
Question: I need to bind the EVT_CHAR event for a GUI application I am developing using
wxPython. I tried the following and I cann understand the beahviour of the
code.
import wx
import wx.lib.agw.flatnotebook as fnb
class DemoApp(wx.App):
def __init__(self):
wx.App.__init__(self, redirect=False)
self.mainFrame = DemoFrame()
self.mainFrame.Show()
def OnInit(self):
return True
class DemoFrame(wx.Frame):
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, wx.ID_ANY,
"FlatNotebook Tutorial",
size=(600,400)
)
panel = wx.Panel(self)
button = wx.Button(panel, label="Close", pos=(125, 10), size=(50, 50))
self.Bind(wx.EVT_CHAR, self.character)
def character(self, event):
print "Char keycode : {0}".format(event.GetKeyCode())
if __name__ == "__main__":
app = DemoApp()
app.MainLoop()
The character function never gets called. However, when I comment out the two
lines call to the Frame constructor, I character function is called. Adding a
panel to the frame seems to interfere with the binding of the frame's
EVT_CHAR.
How do I address this problem? Am I doing something wrong in my code?
Answer: The problem is that you are catching events that happen to the frame, but the
frame is not in focus. The button is. In wxPython, events are sent to the
widget in focus. If you add this to the end of your **init** , it works:
self.SetFocus()
However, if you change the focus to the button, then it will stop working
again. See also:
* [wxpython capture keyboard events in a wx.Frame](http://stackoverflow.com/questions/8707160/wxpython-capture-keyboard-events-in-a-wx-frame)
* <http://www.blog.pythonlibrary.org/2009/08/29/wxpython-catching-key-and-char-events/>
* <http://wxpython-users.1045709.n5.nabble.com/Catching-key-events-from-a-panel-and-follow-up-to-stacked-panels-td2360109.html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.