text
stringlengths 226
34.5k
|
---|
Python typeError
Question: I am new to programming. I am trying to download race results using Python and
Mechanize. I tried to loop through the pages by creating a `for` loop I have
included the relevant code below. When I run this I get the following error:
TypeError: unsupported operand type(s) for %: 'instance' and 'int'
Why can't I use the variable x in the URL?
import mechanize
br = mechanize.Browser()
for x in range(1, 3):
page = br.open('http://results.chicagomarathon.com/2013/?page=%d&event=MAR') % (x)
print page.read()
Answer: The problem is that you are trying to format the response of mechanize with
the integer when you should be formatting the url.
The following code formats the url and then tries to retrieve it:
import mechanize
br = mechanize.Browser()
for x in range(1, 3):
url = 'http://results.chicagomarathon.com/2013/?page=%d&event=MAR' % (x)
page = br.open(url)
print page.read()
|
Firefox doesn't restore server-sent events connection
Question: Test case implemented with Python and CherryPy:
import cherrypy, time
class Root():
@cherrypy.expose
def index(self):
return r'''<!DOCTYPE html>
<html>
<head>
<title>Server-sent events test</title>
<style>html,body,#test{height:98%;}</style>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var source = new EventSource('gettime');
source.addEventListener('time', function (event) {
document.getElementById('test').innerHTML += event.data + "\n";
});
source.addEventListener('error', function (event){
console.log('SSE error:', event);
console.log('SSE state:', source.readyState);
});
}, false);
</script>
<textarea id="test"></textarea>
</body>
</html>'''
@cherrypy.expose
def gettime(self):
cherrypy.response.headers["Content-Type"] = "text/event-stream"
def generator():
while True:
time.sleep(1)
yield "event: time\n" + "data: " + str(time.time()) + "\n\n"
return generator()
gettime._cp_config = {'response.stream': True}
if __name__ == '__main__':
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(Root())
After receiving some messages successfully I manually drop the connection,
then in Firefox' web console appears JS Error: `The connection to
http://localhost:8080/gettime was interrupted while the page was loading.`
According to the [spec](http://www.w3.org/TR/eventsource/), `Clients will
reconnect if the connection is closed`, but Firefox doesn't. Error event
handler reports that the `source` is in `CLOSED` state.
`CLOSED (numeric value 2) The connection is not open, and the user agent is
not trying to reconnect. Either there was a fatal error or the close() method
was invoked.`
So there was a fatal error?
* In Chromium it works, error handler reports that the `source` is in `CONNECTING` (0) state (as it should) and connection is automatically restored within a few seconds
* Have tried Firefox 26, Firefox 24 ESR and Iceweasel 17 on Linux and Windows platforms, all the same
* Have checked raw protocol and headers, looks ok
* Have tried to add `retry: 3000` to each sent event
* Have tried to move JavaScript out of event listener and wrapping it into setTimeout
Answer: [The bug](https://bugzilla.mozilla.org/show_bug.cgi?id=831392) is fixed in
Firefox 36.
|
scipy.polyfit(x, y, 100) would be 100th order polynome, but matplotlib.pyplot.legend displays 53?
Question: I'm having a hard time figuring out why my plt.legend displays the wrong
polynome degree. It says 53 instead of 100. My code would go like this:
import scipy as sp
import numpy as np
import urllib2
import matplotlib.pyplot as plt
url = 'https://raw.github.com/luispedro/BuildingMachineLearningSystemsWithPython/master/ch01/data/web_traffic.tsv'
src = urllib2.urlopen(url)
data = np.genfromtxt(src)
x = data[:, 0]
y = data[:, 1]
x = x[~sp.isnan(y)]
y = y[~sp.isnan(y)]
def error(f, a, b):
return sp.sum((f(a) - b) ** 2)
fp100 = sp.polyfit(x, y, 100)
f100 = sp.poly1d(fp100)
plt.plot(x, f100(x), linewidth=4)
plt.legend("d={num}".format(num=f100.order), loc=2)
plt.show()
Answer: I can reproduce with your data:
>>> np.__version__
1.8.0
>>> fp100 = sp.polyfit(x, y, 100)
polynomial.py:587: RankWarning: Polyfit may be poorly conditioned
warnings.warn(msg, RankWarning)
>>> f100 = sp.poly1d(fp100)
>>> f100.order
53
Note warning and consult [the
docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html):
> polyfit issues a RankWarning when the least-squares fit is badly
> conditioned. This implies that the best fit is not well-defined due to
> numerical error. **The results may be improved by lowering the polynomial
> degree** or by replacing x by x - x.mean()
Your `y` has low variance:
>>> y.mean()
1961.7438692098092
>>> y.std()
860.64491521872196
So one won't expect higher polinomial to fit it well. Note that after
replacing as proposed by docs, x with `x-x.mean()`, it is approximated by
polinomial of lower degree not worse than with higher:
>>> xp=x-x.mean()
>>> f100 = sp.poly1d(sp.polyfit(xp, y,100))
>>> max(abs(f100(xp)-y)/y)
2.1173504721727299
>>> abs((f100(xp)-y)/y).mean()
0.18100985148093593
>>> f4 = sp.poly1d(sp.polyfit(xp, y, 4))
>>> max(abs(f4(xp)-y)/y)
2.1228866902203842
>>> abs((f4(xp)-y)/y).mean()
0.20139219654066282
>>> print f4
4 3 2
8.827e-08 x + 3.161e-05 x + 0.0003102 x + 0.06247 x + 1621
In fact, most significant component seems to have degree 2. So it's normal,
that best approximating your data polinomial of degree not greater than 100,
in fact has degree 53. All higher monomials are degenerate. Below is picture
representing approximation, red line corresponds to polinomial of degree 4,
green to one with degree 53:

|
need to pass python vars to bash avconv command
Question: bash hacker here getting my feet wet with python. I have almost ported one of
my bash scripts to python, but I cannot seem to figure out how to pass python
vars to the bash command avconv to convert .ogg audio files to .mp3 files
(_sigh_ mp3 player does not play .ogg).
anyway I thought I would paste what I have sofar, and it is all working as
desired until the last four lines of 'if' in final 'for' loop. Of course
bash/avconv doesn't recognize python var 'f' passed from python 'for' loop,
and not sure how to go about doing so.
#!/usr/bin/python
#genre = GET SONG GENRE DIR
#if genre == rock+
# sGenreDir = /media/multiMediaA_intHdA720Gb/music/heavierAlt
import os
def get_filepaths(directory):
#This function will generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3 tuple (dirpath, dirnames, filenames).
file_paths = [] # create list to store full paths to each song contained recursively within
# walk the tree
for root, directories, files in os.walk(directory):
for filename in files:
# join the two strings in order to know the fill file path
filepath = os.path.join(root, filename)
file_paths.append(filepath) # add it to the list
return file_paths
# run the avove function and store its results in a variable
#full_file_paths = get_filepaths("/media/multiMediaA_intHdA720Gb/music/heavierAlt")
full_file_paths = get_filepaths("/media/multiMediaA_intHdA720Gb/music/rockAndHeavier")
#print len(full_file_paths)
cntr = 0
for f in full_file_paths:
if not (f.endswith(".mp3") or f.endswith(".ogg")):
del full_file_paths[cntr]
cntr = cntr + 1
#print len(full_file_paths)
# create random song list avoiding duplicate songs
destDir = "/home/keithpc/tmp/rsList" # will be selected by user
numSongs = 10 # number of songs will be chosen by the user
songList = [] # list to hold randomly selected songs
cntr = 1 # that will be incremented for each song appended to list 'songList'
while cntr <= numSongs: #begin random song selection/list creation
from random import choice
newSong = choice(full_file_paths)
if not newSong in songList: # 'if' newSong is not yet list element then add it and ++cntr
songList.append(newSong)
cntr = cntr + 1
print len(songList)
for f in songList:
print f
for f in songList:
if f.endswith(".mp3"): # cp .mp3 to player
import shutil
shutil.copy2(f, destDir)
else: # need to avconv .ogg before copying to player
import os
cmd = 'avconv -i f -c:a libmp3lame -q:a 4 -map_metadata 0:s $destDir/f/%ogg/mp3'
os.system(cmd)
UPDATED: pasting only the last section of above script dealing with random
song selection that attempts to avconv 'ogg' to '.mp3' on the fly copying from
src to dest
# begin to compile random song list
#destDir = "/home/keithpc/tmp/rsList" # will be var supplied by user ; employed in 'for' loop below instead
numSongs = 3 # number of songs var will be supplied by user
songList = [] # list to hold randomly selected songs
cntr = 1 # that will be incremented for each song appended to list 'songList'
while cntr <= numSongs: # 'while' loop to iterate until 'numSongs' is matched by 'cntr'
from random import choice
newSong = choice(lFullFilePaths) # randomly selected song from list 'lFullFilePaths' to add to list 'songList' if it is not a duplicate
if not newSong in songList: # 'if' var does not exist in list 'songList' then add it and cntr++
songList.append(newSong)
cntr = cntr + 1
#print len(songList)
#for f in songList:
# print f
for f in songList:
destDir = "/home/keithpc/tmp/rsList" # will be var supplied by user ; needs to reset each iteration or else it concantanates with previous song details
if f.endswith(".mp3") # 'if' song type is '.mp3' then copy direct to mp3 player
import shutil
shutil.copy2(f, destDir)
else: # 'else' song type must be '.ogg' and so must be avcon'd to mp3 on the fly to mp3 player
import re # regex function to extract the song name from its path
sName = re.sub(r'^.*/', r'', f) # extract song name from it's path
#print sName
import subprocess
destDir = destDir + "/" + sName + "/%ogg/mp3" # create single var 'destDir' containing args bash/avconv should need to convert '.ogg' sending its output as '.mp3' to mp3 player
print(destDir)
subprocess.call(['avconv', '-i', '%s' % f, '-c:a', 'libmp3lame', '-q:a', '4', '-map_metadata', '0:s', '%s' % destDir])
Terminal output when the final 'subprocess' command is commented out reads
like:
07:54 python $ ./ranS*.py
3
/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Radiohead/The_Best_Of/02_Paranoid_Android.ogg
/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Rod_Stewart/If_We_Fall_In_Love_Tonight/
15_All_For_Love__With_Bryan_Adams_And_Sting.ogg
/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Smashing_PumpkinsThe/Siamese_Dream/12_sweet_sweet.ogg
02_Paranoid_Android.ogg
/home/keithpc/tmp/rsList/02_Paranoid_Android.ogg/%ogg/mp3
15_All_For_Love__With_Bryan_Adams_And_Sting.ogg
/home/keithpc/tmp/rsList/15_All_For_Love__With_Bryan_Adams_And_Sting.ogg/%ogg/mp3
12_sweet_sweet.ogg
/home/keithpc/tmp/rsList/12_sweet_sweet.ogg/%ogg/mp3
Which looks about right(ish).
Terminal output with final 'subprocess' uncommented reads like:
07:57 python $ ./ranS*.py
3
/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Guns_N_Roses/Patience_Live_At_The_Ritz_EP_Japanese/03_I_Used_To_Love_Her.ogg
/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/SmithsThe/The_Best_Of_The_Smiths_Vol_1/05_girlfriend_in_a_coma_the_best_of_the_smiths_vol._1.mp3
/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Oasis/The_Masterplan/14_The_Masterplan.ogg
03_I_Used_To_Love_Her.ogg
/home/keithpc/tmp/rsList/03_I_Used_To_Love_Her.ogg/%ogg/mp3
avconv version 0.8.9-6:0.8.9-1, Copyright (c) 2000-2013 the Libav developers
built on Nov 3 2013 02:10:51 with gcc 4.7.2
Input #0, ogg, from '/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Guns_N_Roses/Patience_Live_At_The_Ritz_EP_Japanese/03_I_Used_To_Love_Her.ogg':
Duration: 00:02:48.69, start: 0.000000, bitrate: 186 kb/s
Stream #0.0: Audio: vorbis, 44100 Hz, stereo, s16, 192 kb/s
Metadata:
ARTIST : Guns N' Roses
ALBUM : Patience (Live At The Ritz) (EP - Japanese)
TITLE : I Used To Love Her
DATE : 1989
GENRE : Rock
track : 03
CDDB : 680adf09
Unable to find a suitable output format for '/home/keithpc/tmp/rsList/03_I_Used_To_Love_Her.ogg/%ogg/mp3'
14_The_Masterplan.ogg
/home/keithpc/tmp/rsList/14_The_Masterplan.ogg/%ogg/mp3
avconv version 0.8.9-6:0.8.9-1, Copyright (c) 2000-2013 the Libav developers
built on Nov 3 2013 02:10:51 with gcc 4.7.2
Input #0, ogg, from '/media/multiMediaA_intHdA720Gb/music/rockAndHeavier/Oasis/The_Masterplan/14_The_Masterplan.ogg':
Duration: 00:05:22.80, start: 0.000000, bitrate: 197 kb/s
Stream #0.0: Audio: vorbis, 44100 Hz, stereo, s16, 192 kb/s
Metadata:
ARTIST : Oasis
ALBUM : The Masterplan
TITLE : The Masterplan
DATE : 1998
GENRE : Rock
track : 14
CDDB : c00fd90e
Unable to find a suitable output format for '/home/keithpc/tmp/rsList/14_The_Masterplan.ogg/%ogg/mp3'
Perhaps the issue is with the /%ogg/mp3 that attempts to replace '.ogg' ext
with '.mp3' ext as part of avconv process? Gawd it looks close, if anyone
might have any suggs to help get me homefree.
BTW I have been scouring the inet, and stackoverflow in particular, for
applicable help. So I have RTFM before askign for help. I just can't seem to
get this last part interacting with bash shell to go.
thanks, nap
Answer: A while back I created a similar script to convert a ton of videos into a
format that could be played on one of my gaming consoles. Here is what I would
change in your current code:
As **Martijn Pieters** recommended I wouldn't use os.system to call avconv,
instead try this:
for f in songList:
if f.endswith(".mp3"): # cp .mp3 to player
import shutil
shutil.copy2(f, destDir)
else: # need to avconv .ogg before copying to player
import subprocess
subprocess.call(['avconv', '-i', '%s' % f, '-c:a',
'libmp3lame', '-q:a', '4', '-map_metadata',
'0:s', '$destDir/f/%ogg/mp3'])
Here is a brief description of changes.. First instead of `os.system` the code
is now using `subprocess.call` which was imported instead of `os`. Second I
reformatted the command being passed to `avconv` to use `'%s' % f` instead of
straight `f`, this will tell Python "Hey, use what is stored in `f` to fill in
this blank!", whereas the original code was saying "Python, use f here!".
While reformatting the command being passed you will notice that each segment
is contained in quotes, this is due to how subprocess interprets the arguments
passed to it. I am sure someone else can explain the whys and hows MUCH better
than I can, but simply put there will be a space automatically added in
between each argument.
**\--EDIT--**
Ok, after reviewing the updated information I went back through and tweaked
the code provided. I was not able to fully test this as I am not at home and
currently do not have avconv or the ability to install it on this computer. I
did however substitute the `shutil` and `subprocess.call` lines with print
statements and everything "_appears_ " to work.
Here is the code, a brief explanation of the changes will be below.
#!/usr/bin/python
import os
import subprocess
import shutil
from random import choice
def get_filepaths(directory):
filenames = {}
for root, directories, files in os.walk(directory):
for file in files:
filenames[file] = os.path.join(root, file)
return filenames
def remove_file(d, key):
r = dict(d)
del r[key]
return r
full_file_paths = get_filepaths("/media/multiMediaA_intHdA720Gb/music/rockAndHeavier")
to_remove = []
for file, file_path in full_file_paths.items():
if not (file.endswith('.mp3') or file.endswith('.ogg')):
to_remove.append(file)
for item in to_remove:
full_file_paths = remove_file(full_file_paths, item)
destDir = "/home/keithpc/tmp/rsList"
songList = []
numSongs = 10
cntr = 1
while cntr <= numSongs:
newSong = choice(full_file_paths.keys())
if newSong not in songList:
songList.append(newSong)
cntr += 1
for f in songList:
finalDest = destDir + '/%ogg/mp3'
if f.endswith('.mp3'):
shutil.copy2(full_file_paths.get(f), '%s/%s' %(destDir, f))
else:
subprocess.call(['avconv', '-i', '%s' % full_file_paths.get(f), '-c:a',
'libmp3lame', '-q:a', '4', '-map_metadata', '0:s',
'%s/%s.mp3' % (finalDest, f.strip('ogg'))])
The first change made was in the `get_filepaths` definition, and I feel makes
renaming a little easier in the end. Instead of building a list as before it
creates a dictionary using the files actual filename as a key with the value
being the entire path to the file.
Next was
to_remove = []
def remove_file(d, key):
r = dict(d)
del r[key]
return r
for file, file_path in full_file_paths.items():
if not (file.endswith('.mp3') or file.endswith('.ogg')):
to_remove.append(file)
for item in to_remove:
full_file_paths = remove_file(full_file_paths, item)
This is similar to how you were original removing unwanted files but rewritten
to handle a dictionary instead.
The last change was to the final `for` loop. This adjustment is primarily due
to me forgetting an important thing with avconv (formally known as FFmpeg),
and that is avconv requires us to tell it what the destination filename will
be. If I recall correctly shutil also needs to know the destination filename,
at least it didn't work correctly on Windows.
for f in songList:
finalDest = destDir + '/%ogg/mp3'
if f.endswith('.mp3'):
shutil.copy2(full_file_paths.get(f), '%s/%s' %(destDir, f))
else:
subprocess.call(['avconv', '-i', '%s' % full_file_paths.get(f), '-c:a',
'libmp3lame', '-q:a', '4', '-map_metadata', '0:s',
'%s/%s.mp3' % (finalDest, f.strip('.ogg'))])
Hope this helps.
|
Why return anything but `self` from `__iadd__`?
Question: Python's [documentation on the methods related to the in-place
operators](http://docs.python.org/3/reference/datamodel.html#object.__iadd__)
like `+=` and `*=` (or, as it calls them, the _augmented arithmetic
assignments_) has the following to say:
> These methods should attempt to do the operation in-place (modifying self)
> and return the result (which could be, but does not have to be, _self_). If
> a specific method is not defined, the augmented assignment falls back to the
> normal methods.
I have two closely related questions:
* Why is it necessary to return anything from these methods if the documentation specifies that, if implemented, they should only be doing stuff in-place anyway? Why don't the augmented assignment operators simply not perform the redundant assignment in the case where `__iadd__` is implemented?
* Under what circumstances would it ever make sense to return something other than `self` from an augmented assignment method?
A little experimentation reveals that Python's immutable types don't implement
`__iadd__` (which is consistent with the quoted documentation):
>>> x = 5
>>> x.__iadd__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__iadd__'
and the `__iadd__` methods of its mutable types, of course, operate in-place
and return `self`:
>>> list1 = []
>>> list2 = list1
>>> list1 += [1,2,3]
>>> list1 is list2
True
As such, I can't figure out what the ability to return things other than
`self` from `__iadd__` is for. It seems like it would be the _wrong_ thing to
do in absolutely all circumstances.
Answer: > Why is it necessary to return anything from these methods if the
> documentation specifies that, if implemented, they should only be doing
> stuff in-place anyway? Why don't the augmented assignment operators simply
> not perform the redundant assignment in the case where `__iadd__` is
> implemented?
One reason is to force them to be statements instead of expressions.
* * *
A bigger reason is that the assignment isn't always superfluous. In the case
where the left-hand side is just a variable, sure, after mutating the object,
re-binding that object to the name it was already bound to is usually not
necessary.
But what about the case where the left-hand side is a more complicated
assignment target? Remember that [you can assign—and augmented-assign—to
subscriptions, slicings, and attribute
references](http://docs.python.org/3/reference/simple_stmts.html#assignment-
statements), like `a[1] += 2` or `a.b -= 2`. In that case, you're actually
calling `__setitem__` or `__setattr__` on an object, not just binding a
variable.
* * *
Also, it's worth noting that the "redundant assignment" isn't exactly an
expensive operation. This isn't C++, where any assignment can end up calling a
custom assignment operator on the value. (It may end up calling a custom
setter operator on an object that the value is an element, subslice, or
attribute of, and that could well be expensive… but in that case, it's not
redundant, as explained above.)
* * *
And the last reason directly ties into your second question: You _almost
always_ want to return `self` from `__ispam__`, but _almost always_ isn't
_always_. And if `__iadd__` ever didn't return `self`, the assignment would
clearly be necessary.
* * *
> Under what circumstances would it ever make sense to return something other
> than self from an augmented assignment method?
You've skimmed over an important related bit here:
> These methods should **_attempt to_** do the operation in-place (modifying
> _self_)
Any case where they can't do the operation in-place, but can do something
_else_ , it will likely be reasonable to return something other than `self`.
Imagine an object that used a copy-on-write implementation, mutating in-place
if it was the only copy, but making a new copy otherwise. You can't do that by
not implementing `__iadd__` and letting `+=` fall back to `__add__`; you can
only do it by implementing an `__iadd__` that may make and return a copy
instead of mutating and returning `self`. (You might do that for performance
reasons, but it's also conceivable that you'd have an object with two
different interfaces; the "high-level" interface looks immutable, and copies-
on-write, while the "low-level" interface exposes the actual sharing.)
So, the first reason it's needed is to handle the non-in-place case.
* * *
But are there other reasons? Sure.
One reason is just for wrapping other languages or libraries where this is an
important feature.
For example, in Objective C, lots of methods return a `self` which is usually
but not always the same object that received the method call. That "not
always" is how ObjC handles things like class clusters. In Python, there are
better ways to do the same thing (even changing your class at runtime is
usually better), but in ObjC, it's perfectly normal and idiomatic. (It's only
used for `init` methods in Apple's current Framework, but it's a convention of
their standard library that mutator methods added by `NSMutableFoo` always
return `void`, just like the convention that mutator methods like `list.sort`
always return `None` in Python, not part of the language.) So, if you wanted
to wrap up the ObjC runtime in Python, how would you handle that?
You could put an extra proxy layer in front of everything, so your wrapper
object can change up what ObjC object it's wrapping. But that means a whole
lot of complicated delegation code (especially if you want to make ObjC
reflection work back up through the wrapper into Python) and memory-management
code, and a performance hit.
Instead, you could just have a generic thin wrapper. If you get back a
different ObjC object than you started with, you return the wrapper around
that thing instead of the wrapper around the one you started with. Trivial
code, memory management is automatic, no performance cost. As long as the
users of your wrapper always do `a += b` instead of `a.__iadd__(b)`, they will
see no difference.
I realize that "writing a PyObjC-style wrapper around a different ObjC
framework library than Apple's Foundation` is not exactly an every-day use
case… but you already knew that this is a feature you don't use every day, so
what else would you expect?
A lazy network object proxy might do something similar—start with a tiny
moniker object, swap that out for a full proxy object the first time you try
to do something to it. You can probably think of other such examples. You will
probably never write any of them… but if you had to, you could.
|
Django ManyToManyField FieldError in second app - Cannot resolve keyword 'xxxx into field
Question: I'm trying to write an application where users can submit photos. Part of this
involves voting for photos. So in my models.py I have:
`photos/models.py`
class Photo(models.Model):
votes = models.IntegerField(default=0)
users_voted = models.ManyToManyField(User, related_name='voters', blank=True, null=True)
The users_voted ManyToManyField ensures that people can't vote twice. This all
works fine, but at the moment I'm developing another app in the project which
does MPTT comments. I want users to be able to vote each other's comments up,
too. So I copied over the voting code into my commenting model:
`comments/models.py`
class MyMPTTComment(MPTTModel, Comment):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
cvotes = models.IntegerField(default=0)
users_voted = models.ManyToManyField(User, related_name='cvoters')
This creates a table in the database as expected. But as soon as I try to
access it with my view.py code, I get the FieldError:
def comment_vote(request):
if request.GET.has_key('id'):
try:
id = request.GET['id']
target = MyMPTTComment.objects.get(id=id)
user_voted = target.users_voted.filter(
username=request.user.username
)
I've been scratching my head over this for a while now. Others with similar
issues found that it might be to do with the times that Django loads the
modules ( <http://chase-seibert.github.io/blog/2010/04/30/django-manytomany-
error-cannot-resolve-keyword-xxx-into-a-field.html> ) but fiddling around with
module orders to try to effect their loading times does nothing.
The error says `Choices are: ... voters`, so why can't `cvoters` be resolved?
EDIT: Adding complete error and traceback:
Internal Server Error: /commentvote/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/root/photoproject/photos/views.py", line 300, in comment_vote
username=request.user.username
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 155, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 615, in get_query_set
return super(ManyRelatedManager, self).get_query_set().using(db)._next_is_sticky().filter(**self.core_filters)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 669, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 687, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1139, in add_filter
process_extras=process_extras)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1337, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'cvoters' into field. Choices are: comment_comments, comment_flags, date_joined, email, first_name, friend_set, groups, id, invitation, is_active, is_staff, is_superuser, last_login, last_name, logentry, moderated_messages, password, photos, received_messages, registrationprofile, sent_messages, to_friend_set, user_permissions, userbio, username, voters
Django v1.5.4
Posting database schema:
CREATE TABLE "comments_mympttcomment" ("rght" integer unsigned NOT NULL, "parent_id" integer, "level" integer unsigned NOT NULL, "lft" integer unsigned NOT NULL, "tree_id" integer unsigned NOT NULL, "cvotes" integer NOT NULL, "comment_ptr_id" integer PRIMARY KEY);
CREATE TABLE "comments_mympttcomment_users_voted" ("id" integer NOT NULL PRIMARY KEY, "mympttcomment_id" integer NOT NULL, "user_id" integer NOT NULL);
CREATE TABLE "photos_photo" (
"id" integer NOT NULL PRIMARY KEY,
...
"votes" integer NOT NULL,
"user_id" integer REFERENCES "auth_user" ("id"),
);
CREATE TABLE "photos_photo_users_voted" (
"id" integer NOT NULL PRIMARY KEY,
"photo_id" integer NOT NULL,
"user_id" integer NOT NULL REFERENCES "auth_user" ("id"),
UNIQUE ("photo_id", "user_id")
);
Just noticed that the comments-user table does not include "REFERENCES
"auth_user" ("id")", but I've no idea why. As stated above, the comments model
includes the ManytoManyField exactly as the photos table does, importing from
django.contrib.auth.models import User.
Answer: I think the problem is caused by the use of multiple inheritance in
`MyMPTTComment`. Remove the `Comment` from model's definition:
class MyMPTTComment(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
cvotes = models.IntegerField(default=0)
users_voted = models.ManyToManyField(User, related_name='cvoters')
You can add again the _parent_ field. I found a similar implementation to what
you want to do [here](http://codeblogging.net/blogs/1/3/).
|
Python reading unicode from local files
Question: I am trying to read some unicode files that I have locally. How do I read
unicode files while using a list? I've read the python docs, and a ton of
stackoverflow Q&A's, which have answered a lot of other questions I had, but I
can't find the answer to this one.
Any help is appreciated.
Edit: Sorry, my files are in utf-8.
Answer: You can open UTF-8-encoded files by using
import codecs
with codecs.open("myutf8file.txt", encoding="utf-8-sig") as infile:
for line in infile:
# do something with line
Be aware that `codecs.open()` does not translate `\r\n` to `\n`, so if you're
working with Windows files, you need to take that into account.
The `utf-8-sig` codec will read UTF-8 files with or without a [BOM (Byte Order
Mark)](http://en.wikipedia.org/wiki/Byte_order_mark) (and strip it if it's
there). On writing, you should use `utf-8` as a codec because [the Unicode
standard recommends against writing a BOM in UTF-8
files](http://stackoverflow.com/a/2223926/20670).
|
.xlsx and xls(Latest Versions) to pdf using python
Question: With the help of this [.doc to pdf using
python](http://stackoverflow.com/questions/6011115/doc-to-pdf-using-python)
Link I am trying for excel (.xlsx and xls formats)
**Following is modified Code for Excel:**
import os
from win32com import client
folder = "C:\\Oprance\\Excel\\XlsxWriter-0.5.1"
file_type = 'xlsx'
out_folder = folder + "\\PDF_excel"
os.chdir(folder)
if not os.path.exists(out_folder):
print 'Creating output folder...'
os.makedirs(out_folder)
print out_folder, 'created.'
else:
print out_folder, 'already exists.\n'
for files in os.listdir("."):
if files.endswith(".xlsx"):
print files
print '\n\n'
word = client.DispatchEx("Excel.Application")
for files in os.listdir("."):
if files.endswith(".xlsx") or files.endswith('xls'):
out_name = files.replace(file_type, r"pdf")
in_file = os.path.abspath(folder + "\\" + files)
out_file = os.path.abspath(out_folder + "\\" + out_name)
doc = word.Workbooks.Open(in_file)
print 'Exporting', out_file
doc.SaveAs(out_file, FileFormat=56)
doc.Close()
**It is showing following error :**
>>> execfile('excel_to_pdf.py')
Creating output folder...
C:\Excel\XlsxWriter-0.5.1\PDF_excel created.
apms_trial.xlsx
~$apms_trial.xlsx
Exporting C:\Excel\XlsxWriter-0.5.1\PDF_excel\apms_trial.pdf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "excel_to_pdf.py", line 30, in <module>
doc = word.Workbooks.Open(in_file)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel
', u"Excel cannot open the file '~$apms_trial.xlsx' because the file format or f
ile extension is not valid. Verify that the file has not been corrupted and that
the file extension matches the format of the file.", u'xlmain11.chm', 0, -21468
27284), None)
>>>
There is problem in
**doc.SaveAs(out_file, FileFormat=56)**
What should be **FileFormat** file format? Please Help
Answer: Link of xlsxwriter :
<https://xlsxwriter.readthedocs.org/en/latest/contents.html>
With the help of this you can generate excel file with **.xlsx** and **.xls**
for example excel file generated name is **trial.xls**
**Now if you want to generate pdf of that excel file then do the following :**
from win32com import client
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open('C:\\excel\\trial.xls')
ws = books.Worksheets[0]
ws.Visible = 1
ws.ExportAsFixedFormat(0, 'C:\\excel\\trial.pdf')
|
Using eval in Python 2.7.3 to solve a maths expression
Question: I am essentially asking if I should use eval in this situation for Python
2.7.3;
**The Actual Question (for understanding read the content below)**
I am essentially asking whether approach 1 is better or approach 2 is better
for this context. I believe that approach 1 will be less time consuming to
code, and that it is generally better to save lines when coding, however I
know that there is obviously a bias people have against the use of eval() in
evaluating an expression since it apparently isn't good form.
Cheers
**The Goal; Debriefing;**
For the context of this question, I am trying to make a function which;
1. Makes a maths question and outputs it as a string, with the topic being Order Of Operations
2. As the 2nd piece of output, it outputs the correct answer to this question
3. As the remaining pieces of output, it outputs answers which are incorrect but which could be reached if the Order Of Operations was changed for example make subtraction occur before multiplication
The function does not require any arguments, but in the course of the question
will require us to do the following importing;
*import random
from random import choice*
This will be necessary to generate random integers as numbers for any question
and to choose the operations involved in the question such as *,/,+,-
**The 2 Approaches**
_Approach 1_
1. I make a string by, for an odd number of turns, I alternate between adding an integer and an operation to the string (hence ending with an integer), then at the end put parenthesis in certain places in the string
2. I use eval() to evaluate the string and hence provide the correct answer
3. I make other versions of the string by inserting parenthesis in different places to essentially return a different answer, and I then use eval() on these to find the other answers
_Approach 2_
1. I do similar for approach 1 except that I put the elements into a list
2. With the order of operations provided as a list as input e.g. the correct one being [*_,(_ ,/),(+,-)], I then find where these operations are in the list and perform the operation on the integers to the left and right, remove the 3 sections of the list and replace them with the answer we have found. We do this for all of the operations for the whole list using repetition
3. I simply get different answers by inputting a different list in terms of order of operations, hence making the step of finding incorrect answers much easier
Answer: Adding and removing parenthesis without parsing the computation is going to be
a nighmare. Using eval() is unsafe if done on user input, should be OK
otherwise, but seems overkill here.
I would build a tree from the calculus (standart AST tree), and then do
permutations in it to generate wrong results.
# Make tree from string
def parse(string):
# implement
return tree
# Make string from tree
def render(tree)
# implement
return string
# Compute result of tree
def compute(tree):
# implement
return integer
# Make wrong solutions with given tree
def getPermutations(tree)
# implement
return [tree]
|
accessing clipboard via win32clipboard
Question: I am working on a project in which i have to continuouly check clipboard
content. If clipboard content matches with certain specified data, then it
should be deleted from clipboard. After doing a lot of googling, I find out
that it can be done easily by win32clipboard api. I am using Python as a
programming language. Following is a code for file(CF_HDROP) format:
import win32clipboard
import win32con
def filecopy():
try:
win32clipboard.OpenClipboard()
print win32clipboard.GetClipboardData(win32con.CF_HDROP)
win32clipboard.CloseClipboard()
except TypeError:
pass
Following is a code for text format:
import win32clipboard
def textcopy():
try:
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
print data
win32clipboard.CloseClipboard()
except TypeError:
pass
I am calling above functions in a infinite loop.
Individual function works correctly. But the problem with win32clipboard is
that, after win32clipboard.OpenClipboard() command, win32clipboard lock the
clipboard and only realise it after CloseClipboard() command. In between i
cant copy anything in clipboard.
How can i solve this problem?? Any other suggestion are also welcome to
achieve ultimate aim.
NOTE: Its not necessary to use python. You can use any other language or any
other approach.
Answer: An infinite polling loop (especially one without delays) is going to be a
problem since there's no way to read the contents without locking. Instead you
should look into becoming a `Clipboard viewer`
([pywin32](http://docs.activestate.com/activepython/2.7/pywin32/win32clipboard__SetClipboardViewer_meth.html)
and [msdn](http://msdn.microsoft.com/en-
us/library/windows/desktop/ms649052%28v=vs.85%29.aspx)), that way you are
notified of the clipboard contents change and then you can inspect it (get it
and get out). If you google a bit on `pywin32` and `WM_DRAWCLIPBOARD`, you'll
find some python
[implementations](https://code.google.com/p/pythonxy/source/browse/src/python/pywin32/PLATLIB/win32/Demos/win32clipboard_bitmapdemo.py).
|
Is there a example in django 1.6 and python 3 to build a accounts app (include:register , login , and logout )
Question: I do have read the offical document, but it describes every facility
separately, after reading 'User authentication in Django' ,'First steps' ,
'The model layer', 'The view layer' and 'The template layer' and 'Forms' , I
still donot know how to create a account system.
there seems no django 1.6 and python 3 built account app source code or
tutorial. where can I get them, thanks.
update:
All I what is a account app which I can plug it into any new project. Its urls
will look like this:
accounts/register (the form class of this page is created from the class User
in django.contrib.auth)
accounts/login
accounts/logout
accounts/profile (the form class of this page is created from the model which
has a field `OneToOneField(User)`)
Answer: In your views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
#Import a user registration form
from YourApp.forms import UserRegisterForm
# User Login View
def user_login(request):
if request.user.is_anonymous():
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
#This authenticates the user
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
#This logs him in
login(request, user)
else:
return HttpResponse("Not active")
else:
return HttpResponse("Wrong username/password")
return HttpResponseRedirect("/")
# User Logout View
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
# User Register View
def user_register(request):
if request.user.is_anonymous():
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid:
form.save()
return HttpResponse('User created succcessfully.')
else:
form = UserRegisterForm()
context = {}
context.update(csrf(request))
context['form'] = form
#Pass the context to a template
return render_to_response('register.html', context)
else:
return HttpResponseRedirect('/')
In your forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2')
In your urls.py:
# Accounts urls
url(r'accounts/login/$', 'YourApp.views.user_login'),
url(r'accounts/logout/$', 'YourApp.views.user_logout'),
url(r'accounts/register/$', 'YourApp.views.user_register'),
At last, in register.html:
<form action="/accounts/register/" method="POST"> {% csrf_token %}
<h2>Please enter your details . . .</h2>
{{ form.as_p }}
<input type="submit" value="Sign Up">
</form>
Hope this helps.
|
How to setup a 'catch all' view in Python Pyramid to log incoming requests for static files?
Question: For debugging purposes I'm trying to see what static files(css, js, jpg, etc)
files are being requested from my html files. I read the docs here: [enter
link description
here](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/assets.html)
I have set up my configuration like so:
config.add_route('catchall_static', 'static/*subpath')
and my view as:
@view_config(route_name='catchall_static')
path_info = request._headers.environ['PATH_INFO']
log.debug('path info = {0} {1}'.format(path_info, query_string))
return request.response
With this code there are several things going on.
1) Although the static files come thru the view they don't get actually loaded
to the browser 2) When the static files come thru the view my code works at
least for the logging, but 50% of the time I get this error:
Traceback: path_info = request._headers.environ['PATH_INFO'] AttributeError:
'NoneType' object has no attribute 'environ'
The errors seem to be concentrated on the eariler 's in my html file such as
css files while the .js file at the bottom of my html file sometimes work.
So basically I have no idea if I'm close or totally went in the wrong
direction to solve the problem. Does anybody know the correct way of doing it?
Answer: Are you sure, this route servers any request successfully at all?
Possibilities to achieve your goal are: A WSGI middleware, a Pyramid Tween or
a custom event subscriber.
The custom subscriber would probably be the most easy one. This subscriber is
called before the response is created, so it can't know the response code,
content etc. To accomplish this you can either add a request finished callback
or use one of the other methods.
from pyramid.events import NewRequest
from pyramid.events import subscriber
@subscriber(NewRequest)
def static_logger(event):
logger = logging.getLogger('static')
request = event.request
if request.path_info.startswith('/static'):
logger.info('static request: {} {}'.format(request.path_info,
request.query_string))
And activate the logger in development.ini:
[loggers]
keys = root, static
[logger_static]
level = DEBUG
handlers = console
qualname = static
|
Wait for callback function to return in Node.js
Question: I'm able to spawn a Python child_process and write the data returned from
Python to the console in Node. However, I'm not able to return the data in a
callback function in Node. I’m thinking this is because the callback function
is asynchronous, so the server returns the result to the browser before the
callback returns.
test_server.js
var sys = require('sys');
var http = require('http');
var HOST = '127.0.0.1';
var PORT = 3000;
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test_data.py']);
var resp = "Testing ";
child.stdout.on('data', function(data) {
console.log('Data: ' + data); // This prints "Data: 123" to the console
resp += data; // This does not concat data ("123") to resp
});
callBack(resp) // This only returns "Testing "
}
http.createServer(function(req, res) {
var result = '';
run(function(data) {
result += data;
});
res.writeHead(200, {'Context-Type': 'text/plain'});
res.end(result);
}).listen(PORT, HOST);
sys.puts('HTTP Server listening on ' + HOST + ':' + PORT);
test_data.py
import sys
out = '123';
print out
When I run: node test_server.js, then hit it in a browser, I get the following
in the console:
c:\>node test_server.js
HTTP Server listening on 127.0.0.1:3000
Data: 123
But I only the following in the browser:
Testing
Could someone explain how I can wait for the callback function to return
before continuing?
Thanks.
Answer: You need to hook your callback up to the `close` event from the child_process.
child.on('close', function() {
callBack(resp);
}
|
Python -- list comprehension with try/exception and nested conditional
Question: This code should find the mode of a list in O(n) linear time. I want to turn
this into a list comprehension because I'm teaching myself Python, and am
trying to improve my list comprehension skills.
These were informative but don't really answer my question:
[Convert nested loops and conditions to a list
comprehension](http://stackoverflow.com/questions/19346063/convert-nested-
loops-and-conditions-to-a-list-comprehension)
[`elif` in list comprehension
conditionals](http://stackoverflow.com/questions/9987483/elif-in-list-
comprehension-conditionals)
[Nested list comprehension
equivalent](http://stackoverflow.com/questions/11598880/nested-list-
comprehension-equivalent)
The problem that I'm running into is nesting the if's and the try/except. I'm
sure this is simple question so a junior Python programmer might have the
answer quickly.
def mode(L):
# your code here
d = {}; mode = 0; freq = 0
for j in L:
try:
d[j] += 1
if d[j] > freq:
mode = j; freq = d[j]
except(KeyError): d[j] = 1
return mode
Note that `L` parameter is a list of ints like this:
L = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]
I was thinking something like:
[try (d[j] += 1) if d[j] > freq (mode = j; freq = d[j]) except(KeyError): d[j] = 1 for j in L]
But I don't have enough duct tape to fix how badly the syntax is off with that
thing.
Answer: I know you're learning comprehensions, but you can do this with a default
dictionary, or a Counter too.
import collections
def mode(L):
# your code here
d = collections.defaultdict(lambda: 1); mode = 0; freq = 0
for j in L:
d[j] += 1
if d[j] > freq:
mode = j; freq = d[j]
return mode
Better still, when you are not trying to learn comprehensions:
import collections
def mode(L):
collections.Counter(L).most_common(1)[0][0]
|
Cannot import Twython
Question: I installed Twython 1.2 using the Windows installer at this link:
<https://pypi.python.org/pypi/twython/1.2>. The installer seems to run fine.
I get the error "ImportError: cannot import name Twython" when I try to do:
from twython import Twython
from twython import TwythonStreamer
Does anybody know why I cannot import twython?
Answer: Mmmm, Twython's current version is 3.x.x, not 1.2. I think that 1.2 installer
is from yeaaars ago when I first started the project - the Twython API and
structure has changed a ton since then.
|
Python curses: addstr() from file prints blanks for the remainder of the line
Question: I'm writing a very simple farming game in Python using curses. At this point I
have been successful in allowing the player (just a "@" character) to move
around within a window.
I have a few files with ascii-art that I print to the window as things to
populate the world in which the player can move around. For example, I have a
file, named "house", that contains:
_ . ^ . _
/____.____\
| |
| ## _ ## |
|_""_H_""_|
I have a Thing class as follows:
class Thing(object):
def __init__(self, Xstart, Ystart, looksLike, list, window):
self.Xstart = Xstart
self.Ystart = Ystart
self.X = Xstart
self.Y = Ystart
self.looksLike = looksLike
self.boundries = []
self.find_boundries()
list.append(self)
self.draw(window)
def find_boundries(self):
file = open(self.looksLike).readlines()
for line in file:
for char in line:
if char == '\n':
pass
elif char == ' ': # skip all whitespace
self.X += 1
else:
self.boundries.append([self.X, self.Y])
self.X += 1
self.Y += 1
self.X = self.Xstart
self.X = self.Xstart # reset x & y to starting coordinates
self.Y = self.Ystart
def draw(self, window):
#file = open(self.looksLike).readlines()
#for line in file:
# window.addstr(self.Y, self.X, line)
# self.Y += 1
#self.Y = self.Ystart
file = open(self.looksLike).read()
for char in file:
window.addch(self.Y, self.X, char)
if char == '\n':
self.Y += 1
self.X = self.Xstart
else:
self.X += 1
self.X = self.Xstart
self.Y = self.Ystart
Thus the constructor for my Thing class takes a filename as an argument
(looksLike) and the draw method opens the file, reads it, and prints its
contents to the window. I can, then, create a house object, pass my "house"
file as an argument, and my ascii house will be printed to the window.
The problem is that once the object is printed to the window, when I move the
player to the right of the printed object the player disappears. Above, below,
and to the left of the printed object, however, the player stays in view. For
example,
_ . ^ . _
/____.____\
| |
| ## _ ## |
|_""_H_""_|
@
In this position the "@" character is visible, but if I move one space up, it
disappears. If I continue moving the player up, the "@" will reappear after it
moves beyond the topmost character of the house.
I assume this issue is due to the nature of both addstr() and addch() ( I have
tried both) printing whitespace until the end of the window, but I have been
unable to find any documentation on this.
I have considered creating a new window for each object printed, but this
seems like it would get quite cumbersome when more than a few objects are
printed to the window. Also, I hope to define borders around the objects
printed to the screen that are shapes other than just squares or rectangles.
Is there anyway to print from a file to the window without the trailing
whitespace and without creating a new window for each printed object?
Answer: Onfortunately I have never used curses, and I cannot see your player class.
Nevertheless maybe this snippet might give you some ideas (press 'x' to exit
game) (use WASD to move the player) (requires ANSI-enabled console:
#! /usr/bin/python3
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
getch = _GetchUnix ()
house = ''' _ . ^ . _
/____.____\\
| |
| ## _ ## |
|_""_H_""_|'''
class Screen:
def __init__ (self, width, height, background):
self.width = width
self.height = height
self.bg = '\x1b[{}m'.format (40 + background)
self.clear = '\x1b[0m'
self.objects = []
def __iadd__ (self, obj):
self.objects.append (obj)
obj.screen = self
return self
def render (self):
print ('\x1b[1;1H', end = '')
for y in range (self.height):
for x in range (self.width):
print (self.bg + ' ' + self.clear, end = '')
print ()
for obj in self.objects: obj.render ()
print ('\x1b[{};1H'.format (self.height) )
class Object:
def __init__ (self, graphics, foreground, background, x, y):
self.graphics = graphics.split ('\n')
self.fg = '\x1b[{}m'.format (30 + foreground)
self.bg = '\x1b[{}m'.format (40 + background)
self.clear = '\x1b[0m'
self.x = x
self.y = y
def render (self):
for y, line in enumerate (self.graphics):
print ('\x1b[{};{}H'.format (self.y + y, self.x), end = '')
print (self.fg + self.bg + line + self.clear)
def collide (self, x, y):
if y < self.y: return False
if x < self.x: return False
if y > self.y + len (self.graphics) - 1: return False
if x > self.x + len (self.graphics [y - self.y] ): return False
return True
def move (self, dx, dy):
nx, ny = self.x + dx, self.y + dy
if ny < 1: return
if ny > self.screen.height: return
if nx < 1: return
if nx > self.screen.width: return
for obj in self.screen.objects:
if obj == self: continue
if obj.collide (nx, ny): return
self.x, self.y = nx, ny
house = Object (house, 0, 7, 6, 3)
player = Object ('@', 1, 3, 10, 10)
s = Screen (40, 20, 3)
s += house
s += player
while True:
c = getch ()
if c == 'x': break
if c == 'w': player.move (0, -1)
if c == 's': player.move (0, 1)
if c == 'a': player.move (-1, 0)
if c == 'd': player.move (1, 0)
s.render ()
Here a screen shot:

|
Create an input box with python
Question: I want to create a box for the user to interact with on screen.
I want to use it like this:
The program runs. A window appears. The box is somewhere in that window. And
the user can click inside with the mouse. He can type, erase, and when he is
done he will be able to press a button "ok" and I'll be able to collect the
text info written by the user in the box and use it for further purposes.
I can't find a tutorial or a reference to help me do something like that.
Answer: You could try the Tkinter module, for example:
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def callback():
print e.get() # This is the text you may want to use later
b = Button(master, text = "OK", width = 10, command = callback)
b.pack()
mainloop()
**Result:**

Of course, you may want to read a **Tkinter** tutorial.
|
lxml returns an empty list on DTD attributes
Question: I'm trying to get the attributes of a DTD element to get their default values
but attributes() is returning always an empty list. Here is the code:
#!/usr/bin/python3 -BEOObbs
# coding=utf-8
import io, lxml.etree
xml = lxml.etree.parse(io.BytesIO(b'''<?xml
version='1.1'
encoding='utf-8'
?>
<!DOCTYPE root [
<!ATTLIST test
attr (A | B | C) 'B'
>
<!ELEMENT test (#PCDATA)>
<!ELEMENT root (test)*>
]>
<root></root>'''))
element = xml.docinfo.internalDTD.elements()[0]
print(element.name)
print(element.attributes())
This is the result:
sworddragon@ubuntu:~/tmp$ ./test.py
test
[]
I'm wondering what is wrong here.
Answer: I have opened a ticket for this
(<https://bugs.launchpad.net/lxml/+bug/1266171>) and they have confirmed this
as a bug and even committed a fix into the master tree of the git repository
so the changes will be in the final 3.3.0 release of lxml.
|
Python not decoding json
Question: I am receiving the error:
No JSON object could be decoded: line 1 column 0 (char 0)
when trying to parse a json object returned from the xbox music api.
Here is my code:
conn = httplib.HTTPSConnection(SERVICE_API)
conn.request("GET", url)
response = conn.getresponse()
data = response.read()
j = json.loads(data)
the last line is what returned the above error. If I comment that out and
print out 'data', I can see the json object. If i copy / past that to
jsonlint.com to see if it's valid, it says that it is. I would post it here
but it is 800 lines.
Answer: You are accessing a Microsoft service that includes the UTF-8 BOM at the
start. But Microsoft is rather fond of the BOM in UTF-8 (which is entirely
redundant here) as it introduced the BOM to UTF-8 to make it easier for
Notepad and other Windows applications to auto-detect the encoding used.
Silly Microsoft, that is very much _not valid_ according to the JSON RFC; if
there is a contact address anywhere you should report this as a bug to them.
You can strip the BOM with:
import codecs
data = response.read()
if data.startswith(codecs.BOM_UTF8):
data = data[3:]
|
Can't create sqlite database on Windows XP with Django Python 2.7
Question: I need to create an SQLite database with Django and Python 2.7.
However, when I run "python manage.py syncdb", I receive:
unable to open database file
Here is a fragment of settings.py file:
import os
MANAGERS = ADMINS
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'db'),....
I have read several books and tutorials, but can't make a database on Windows.
Answer: change 'NAME': os.path.join(PROJECT_DIR, 'db'), to 'NAME': 'database.db',
|
Python - getting source code with socket
Question: I wanna send http get request and receive source code from webpage, this has
to be done through sockets. I set buffer size to 4096, but my script download
only small part from the page
import socket
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
sock.connect ( ( "edition.cnn.com", 80 ) )
host = socket.gethostbyname("edition.cnn.com")
sock.sendall('GET http://edition.cnn.com/index.html HTTP/1.1\r\n'\
+ 'User-Agent: agent123\r\n'\
+ 'Host: '+host+'\r\n'\
+ '\r\n')
print sock.recv(4096)
sock.close()
After I run this code data I get are
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 01 Jan 2014 18:31:25 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: CG=GR:44:Réthimnon; path=/
Last-Modified: Wed, 01 Jan 2014 18:31:22 GMT
Vary: Accept-Encoding
Cache-Control: max-age=60, private
Expires: Wed, 01 Jan 2014 18:32:25 GMT
ac2a
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>CNN.com International - Breaking, World, Business, Sports, Entertainment and Video News</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta http-equiv="last-modified" content="2014-01-01T18:28:34Z"/>
<meta http-equiv="refresh" content="1800;url=http://edition.cnn.com/?refresh=1"/>
<meta name="robots" content="index,follow"/>
<meta name="googlebot" content="noarchive"/>
<meta name="description" content="CNN.com International delivers breaking news from across the globe and information on the latest top stories, business, sports and entertainment headlines. Follow the news as it happens through: special reports, videos, audio, photo galleries plus interactive maps and timelines."/>
<meta name="keywords" content="CNN, CNN news, CNN International, CNN International news, CNN Edition, Edition news, news, news online, breaking news, U.S. news, world news, global news, weather, business, CNN Money, sports, politics, law, technology, entertainment, education,
Which isn't even first 13 rows from source code... view-
source:<http://edition.cnn.com/index.html>
* * *
And another problem, when I try address google.com like a host
import socket
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
sock.connect ( ( "google.com", 80 ) )
host = socket.gethostbyname("google.com")
sock.sendall('GET http://google.com/index.html HTTP/1.1\r\n'\
+ 'User-Agent: agent123\r\n'\
+ 'Host: '+host+'\r\n'\
+ '\r\n')
print sock.recv(4096)
sock.close()
I get this response
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/index.html
Content-Type: text/html; charset=UTF-8
Date: Wed, 01 Jan 2014 18:38:57 GMT
Expires: Fri, 31 Jan 2014 18:38:57 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 229
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/index.html">here</A>.
</BODY></HTML>
which says that page is moved to the same address like i wanted download...
Answer: `sock.recv(4096)` will read **up to** 4096 bytes; it depends on how much data
has already arrived how much can actually be returned by the call. There is no
guarantee that 4096 bytes will actually be available for reading in one go.
You'll have to _continue_ to read from the socket until all data is received:
data = ''
chunk = sock.recv(4096)
while chunk:
data += chunk
if len(data) >= 4096:
break
chunk = sock.recv(4096)
Your request to `http://google.com/index.html` redirects to `www.google.com`,
a **different** hostname. Adjust your request accordingly.
If you wanted to implement a full-on HTTP client, you'd have to parse the
status line, process the `301` redirect response by parsing out the
`Location:` header, and making a new connection to request the new URL given
to you.
|
Multiplication program
Question: I am making this multiplication program in python 2.7.5 for my sister, and I
don't know how to count the correct answers. Here is the code:
import easygui
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
answer = easygui.enterbox("What is " + str(i) + ' times 8?')
if int(answer) == i * 8:
easygui.msgbox("That is correct!")
else:
easygui.msgbox("Wrong!")
Answer: Why not just add a variable to keep count for you?
import easygui
correct_answers = 0 # start with none correct
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
answer = easygui.enterbox("What is " + str(i) + ' times 8?')
if int(answer) == i * 8:
easygui.msgbox("That is correct!")
correct_answers += 1 # increment
else:
easygui.msgbox("Wrong!")
You could improve your program by making the base number a variable, too, and
using Python's `str.format()` rather than addition:
base = 8
...
answer = easygui.enterbox("What is {0} times {1}?".format(i, base))
if int(answer) == i * base:
...
|
How to get each Process ID when multiprocessing
Question: I have some problems because I'm newbie in Python and Pyside.
I have N processes which are running at the same time.
Since these processes take some times to finish their job, it's possible that
end user wants to cancel a specific process. So I need a way to know the IDs
of processes for adding this feature to the program.
There is an [answer](http://stackoverflow.com/a/15875187/3152155) in
Stackoverflow which is exactly what I'm doing.
Here is the code :
#!/usr/bin/env python3
import multiprocessing, multiprocessing.pool, time, random, sys
from PySide.QtCore import *
from PySide.QtGui import *
def compute(num_row):
print("worker started at %d" % num_row)
random_number = random.randint(1, 10)
for second in range(random_number):
progress = float(second) / float(random_number) * 100
compute.queue.put((num_row, progress,))
time.sleep(1)
compute.queue.put((num_row, 100))
def pool_init(queue):
# see http://stackoverflow.com/a/3843313/852994
compute.queue = queue
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.toolBar = self.addToolBar("Toolbar")
self.toolBar.addAction(QAction('Add Task', self, triggered=self.addTask))
self.table = QTableWidget()
self.table.verticalHeader().hide()
self.table.setColumnCount(2)
self.setCentralWidget(self.table)
# Pool of Background Processes
self.queue = multiprocessing.Queue()
self.pool = multiprocessing.Pool(processes=4, initializer=pool_init, initargs=(self.queue,))
# Check for progress periodically
self.timer = QTimer()
self.timer.timeout.connect(self.updateProgress)
self.timer.start(2000)
def addTask(self):
num_row = self.table.rowCount()
self.pool.apply_async(func=compute, args=(num_row,))
label = QLabel("Queued")
bar = QProgressBar()
bar.setValue(0)
self.table.setRowCount(num_row + 1)
self.table.setCellWidget(num_row, 0, label)
self.table.setCellWidget(num_row, 1, bar)
def updateProgress(self):
if self.queue.empty(): return
num_row, progress = self.queue.get() # unpack
print("received progress of %s at %s" % (progress, num_row))
label = self.table.cellWidget(num_row, 0)
bar = self.table.cellWidget(num_row, 1)
bar.setValue(progress)
if progress == 100:
label.setText('Finished')
elif label.text() == 'Queued':
label.setText('Downloading')
self.updateProgress() # recursion
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
I added an "stop" button, and I know how to get the selected row in the table,
but I don't know how to get the process id of the selected row for
terminating.
**update 1** :
for make this easier I can change
`multiprocessing.Pool(processes=4, initializer=pool_init,
initargs=(self.queue,))` to
multiprocessing.Pool(processes=1, initializer=pool_init, initargs=(self.queue,))
in this way all processes have to wait till a process finish
now we have one process running and others are in queue,How I can get just the
process id of that running process ?
Answer: I hacked together an demo that more or less reproduces the multiprocessing
example, with the addition of the ability to abort uploads. It can only handle
six parallel uploads at a time because that is the maximum
QNetworkAccessManager will allow. However, this limit could be increased by
simply adding another QNetworkAccessManager.
There was one issue I came across while testing the demo. It seems that under
some circumstances, the post-data can get sent twice (see
[here](http://lists.qt.nokia.com/public/qt-interest/2011-April/033132.html),
for example). But I don't know whether this is a Qt bug, or an issue with my
test setup (I used a python threaded httpserver). Anyway, it was easy enough
to fix by closing the reply-object in the uploadProgress handler (see below).
from PyQt4 import QtCore, QtGui, QtNetwork
class Window(QtGui.QWidget):
def __init__(self, address):
QtGui.QWidget.__init__(self)
self.address = address
self.table = QtGui.QTableWidget(self)
header = self.table.horizontalHeader()
header.setStretchLastSection(True)
header.hide()
self.table.setColumnCount(2)
self.button = QtGui.QPushButton('Add Upload', self)
self.button.clicked.connect(self.handleAddUpload)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
layout.addWidget(self.button)
self.netaccess = QtNetwork.QNetworkAccessManager(self)
self._uploaders = {}
def handleAddUpload(self):
stream = QtCore.QFile('files/sample.tar.bz2')
if stream.open(QtCore.QIODevice.ReadOnly):
data = stream.readAll()
stream.close()
row = self.table.rowCount()
button = QtGui.QPushButton('Abort', self.table)
button.clicked.connect(lambda: self.handleAbort(row))
progress = QtGui.QProgressBar(self.table)
progress.setRange(0, len(data))
self.table.setRowCount(row + 1)
self.table.setCellWidget(row, 0, button)
self.table.setCellWidget(row, 1, progress)
uploader = self._uploaders[row] = Uploader(row, self.netaccess)
uploader.uploadProgress.connect(self.handleUploadProgress)
uploader.uploadFinished.connect(self.handleUploadFinished)
uploader.upload(data, self.address)
def handleUploadProgress(self, key, sent, total):
print('upload(%d): %d [%d]' % (key, sent, total))
progress = self.table.cellWidget(key, 1)
progress.setValue(sent)
def handleUploadFinished(self, key):
print('upload(%d) finished' % key)
button = self.table.cellWidget(key, 0)
button.setDisabled(True)
uploader = self._uploaders.pop(key)
uploader.deleteLater()
def handleAbort(self, key):
try:
self._uploaders[key].abort()
except (KeyError, AttributeError):
pass
class Uploader(QtCore.QObject):
uploadProgress = QtCore.pyqtSignal(object, int, int)
uploadFinished = QtCore.pyqtSignal(object)
def __init__(self, key, parent):
QtCore.QObject.__init__(self, parent)
self._key = key
self._reply = None
def abort(self):
if self._reply is not None:
self._reply.abort()
def upload(self, data, url):
if self._reply is None:
request = QtNetwork.QNetworkRequest(QtCore.QUrl(url))
request.setHeader(
QtNetwork.QNetworkRequest.ContentTypeHeader,
'application/x-www-form-urlencoded')
self._reply = self.parent().post(request, data)
self._reply.uploadProgress.connect(self.handleUploadProgress)
self._reply.finished.connect(self.handleFinished)
def handleUploadProgress(self, sent, total):
self.uploadProgress.emit(self._key, sent, total)
if sent >= total:
# prevent duplicated uploads
self._reply.close()
def handleFinished(self):
self._reply.deleteLater()
self._reply = None
self.uploadFinished.emit(self._key)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window('http://localhost:54321/upload')
window.setGeometry(500, 300, 500, 300)
window.show()
sys.exit(app.exec_())
|
Drop Down Menu In Python calling information from files
Question: So I need a drop down menu, where the user picks his/her client, and it
returns information about that client.
lets say i have a file:
["client1", "client2", "client3"]
and I have this code:
from tkinter import *
master = Tk()
with open('ubclientlistvars.txt', 'r') as clients:
clients = (clients.readlines())
variable = StringVar(master)
variable.set("Choose Client")
w = OptionMenu(master, variable, clients)
w.pack()
mainloop()
how would I draw the clients from the file into the drop down menu? When I run
this code, i get these two options: `Choose Client` and `{["client1",
"client2", "client3"]}`
Answer: You need to actually parse that file. If the file contents are what you
posted, then `readlines()` is just returning a single line of text. It does
not magically convert the file contents into a Python object. Suppose the file
was:
client1
client2
client3
Then you could use something like `clients = [i.strip() for i in
f.readlines()]` to get a proper list of clients and can pass them to
`OptionMenu`:
w = OptionMenu(master, variable, *clients)
If you cannot change the file format then you will need to clean up the input
before displaying it...
import re
data = f.read() # ["client1", "client2", "client3"]
data = re.sub('["\[\]]', '', data) # remove the ", [, and ] characters
clients = data.split(',') # split the list of clients on the comma
|
Const correctness of Python's C API
Question: It seems that the Python C API is not consistent with the const correctness of
character arrays. For example,
[PyImport_ImportFrozenModule](http://docs.python.org/2/c-api/import.html#PyImport_ImportFrozenModule)
accepts a `char*`, whereas
[PyImport_ImportModule](http://docs.python.org/2/c-api/import.html#PyImport_ImportModule)
accepts a `const char*`.
The implication of all this is that in my C++ application that I am writing
with an embedded Python interpreter, I sometimes have to cast the string
literal that I pass to a Python API call as just a `char*` (as opposed to
`const char*`), and sometimes I don't. For example:
PyObject *os = PyImport_ImportModule("os"); // Works without the const_cast
PyObject *cwd = PyObject_CallMethod(os, const_cast<char*>("getcwd"), NULL); // Accepts char*, not const char*
If I don't do the `const_cast<char*>` (or `(char*)`) on the string literal, I
get a compiler warning about casting string literals to `char*`.
Here are my questions:
1. Is there an advantage/reason to having some of the functions not take a `const char*` (and/or why would the Python API not be consistent in this)? My understanding is that if the function can take a string literal, it cannot change the `char*` so the `const` modifier would just be reinforcing this. I also believe that the `const` distinction is not as important for C (for which the API was written) than it is in C++ (correct me if I am wrong... my strength is python, not C/C++). Is the lack of "const correctness" of the Python API because it's simply not as important in C? (There is an [old thread on the python mailing list](https://mail.python.org/pipermail/python-list/2000-May/060658.html) from 2000 asking the same question, but it didn't seem to go anywhere and it is implied the reason might be due to some compilers not supporting `const`. Since many functions now have `const char*`, this doesn't seem to apply anymore)
2. Because my understanding of C++ is limited, I am unsure if I am going about casting string literals properly. The way I see it, I can either one of the following (I am currently doing the first):
// Method 1) Use const_cast<char*>
PyImport_ImportFrozenModule(const_cast<char*>("mymodule"));
// Method 2) Use (char*)
PyImport_ImportFrozenModule((char*) "mymodule");
// Method 3) Use char array
char mod[] = "mymodule";
PyImport_ImportFrozenModule(mod);
Which is the best method do use?
* * *
**Update:**
It looks like the Python3 branch is slowly trying to fix the const correctness
issue. For example, the `PyImport_ImportFrozenModule` function I use as an
example above now takes a `const char*` in Python 3.4, but there are still
functions that take only a `char*`, such as
[PyLong_FromString](https://docs.python.org/3.3/c-api/long.html#PyLong_FromString).
Answer: Based on some mailing list conversations from python-dev, it looks like the
initial API just simply wasn't created with const correctness in mind,
probably just because Guido didn't think about it. Dating all the way back to
2002, [someone asked](http://code.activestate.com/lists/python-dev/20908/) if
there was any desire to address that by adding const-correctness, complaining
that it's a pain to always have to do this:
somefunc(const char* modulename, const char* key)
{
... PyImport_ImportModule(const_cast<char*>(modulename)) ...
Guido Van Rossum (the creator of Python)
[replied](http://code.activestate.com/lists/python-dev/20914/) (emphasis
mine):
> **I've never tried to enforce const-correctness before** , but I've heard
> enough horror stories about this. The problem is that it breaks 3rd party
> extensions left and right, and fixing those isn't always easy. In general,
> whenever you add a const somewhere, it ends up propagating to some other
> API, which then also requires a const, which propagates to yet another API
> needing a const, ad infinitum.
There was a bit more discussion, but without Guido's support the idea died.
Fast forward nine years, and the topic came up again. This time someone was
simply wondering why some functions were const-correct, while others weren't.
One of the Python core developers [replied with
this](https://mail.python.org/pipermail/python-dev/2011-February/108168.html):
> We have been adding const to many places over the years. I think the
> specific case was just missed (i.e. nobody cared about adding const there).
It seems that when it could be done without breaking backwards compatibility,
const-correctness has been added to many places in the C API (and in the case
of Python 3, in places where it _would_ break backwards compatibility with
Python 2), but there was never a real global effort to fix it _everywhere_. So
the situation is better in Python 3, but the entire API is likely not const
correct even now.
I'm don't think that the Python community has any preferred way to handle
casting with calls that are not `const`-correct (there's no mention of it in
the official [C-API style
guide](http://legacy.python.org/dev/peps/pep-0007/)), probably because there
aren't a ton of people out there interfacing with the C-API from C++ code. I
would say the preferred way of doing it from a pure C++ best-practices
perspective would be the first choice, though. (I'm by no means a C++ expert,
so take that with a grain of salt).
|
How to set background color of a column in a matplotlib table
Question: I have multile .txt files in a directory, say,
d:\memdump\0.txt,1.txt,...10.txt sample text file is given below:
Applications Memory Usage (kB):
Uptime: 7857410 Realtime: 7857410
** MEMINFO in pid 23875 [com.example.twolibs] **
Shared Private Heap Heap Heap
Pss Dirty Dirty Size Alloc Free
------ ------ ------ ------ ------ ------
Native 0 0 0 13504 10836 459
Dalvik 6806 7740 6580 24076 18523 5553
Stack 80 0 80
Cursor 0 0 0
Ashmem 0 0 0
Other dev 14741 836 1028
.so mmap 1367 448 1028
.jar mmap 0 0 0
.apk mmap 225 0 0
.ttf mmap 0 0 0
.dex mmap 1225 340 16
Other mmap 5 8 4
Unknown 3473 564 3432
TOTAL 27922 9936 12168 37580 29359 6012
Objects
Views: 62 ViewRootImpl: 2
AppContexts: 5 Activities: 2
Assets: 3 AssetManagers: 3
Local Binders: 9 Proxy Binders: 18
Death Recipients: 0
OpenSSL Sockets: 0
SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
I have to parse these files to get values of PID, Native Heap Size, Native
Heap Alloc size, Dalvik Heap Size, Dalvik Heap Alloc size and plot a graph
with these heap sizes as below

I am using the following code to achieve this:
import glob
import os
import re
import numpy as np
import matplotlib.pyplot as plt
os.chdir("D:\Python_Trainings\MemInfo\Data")
pid_arr = []
native_heapsize_arr = []
dalvik_heapsize_arr = []
native_heapalloc_arr = []
dalvik_heapalloc_arr = []
pkg_name_arr = []
#Method to parse the memory dump files
def parse_dumpFiles():
for data_file in glob.glob("*.txt"):
try:
fo = open(data_file,"r")
for line in fo:
pid_match = re.search('pid\s+(\d+)',line)
pkg_name_match = re.search("\[(\w+\.+\w+\.+\w+)\]",line)
native_heapsize_match = re.search('(Native+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
dalvik_heapsize_match = re.search('(Dalvik+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
native_heapalloc_match = re.search('(Native+\s+\d+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
dalvik_heapalloc_match = re.search('(Dalvik+\s+\d+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
if pid_match:
pid_arr.append(int(pid_match.group(1)))
if native_heapsize_match:
native_heapsize_arr.append(native_heapsize_match.group(2))
if dalvik_heapsize_match:
dalvik_heapsize_arr.append(dalvik_heapsize_match.group(2))
if native_heapalloc_match:
native_heapalloc_arr.append(native_heapalloc_match.group(2))
if dalvik_heapalloc_match:
dalvik_heapalloc_arr.append(dalvik_heapalloc_match.group(2))
if pkg_name_match:
if pkg_name_match.group(1) not in pkg_name_arr:
pkg_name_arr.append(pkg_name_match.group(1))
except IOError:
print "Error: can\'t find file or read data"
finally:
fo.close()
#end of parse_dumpFiles() Method
#Method to plot from Memory Dumps
def plt_MemDump(pid_arr, native_heapsize_arr, dalvik_heapsize_arr, native_heapalloc_arr, dalvik_heapalloc_arr, pkg_name_arr):
#Create a figure and axes with room for the table
fig = plt.figure()
ax = plt.axes([0.2, 0.2, 0.7, 0.7])
#Create labels for the rows and columns as tuples
colLabels = ('0','10', '20', '30', '40', '50', '60', '70', '80', '90', '100')
rowLabels = ('Native Heap Size','Native Heap Allocated','Dalvik Heap Size','Dalvik Heap Allocated','PID')
#Table data as a numpy array
tableData = np.asarray([native_heapsize_arr,dalvik_heapsize_arr,native_heapalloc_arr,dalvik_heapalloc_arr,pid_arr],dtype=int)
#Get the current color cycle as a list, then reset the cycle to be at the beginning
colors = []
while True:
colors.append(ax._get_lines.color_cycle.next())
if colors[0] == colors[-1] and len(colors)>1:
colors.pop(-1)
break
for i in xrange(len(colors)-1):
ax._get_lines.color_cycle.next()
#Show the table
the_table = plt.table(cellText=tableData, rowLabels=rowLabels, rowColours=colors, colLabels=colLabels, loc='bottom')
#Make some line plots
xAxis_val = [0,10,20,30,40,50,60,70,80,90,100]
ax.plot(xAxis_val,native_heapsize_arr, linewidth=2.5, marker="o", label="Native Heap Size")
ax.plot(xAxis_val,dalvik_heapsize_arr, linewidth=2.5, marker="D", label="Dalvik Heap Size")
ax.plot(xAxis_val,native_heapalloc_arr, linewidth=2.5, marker="^",label="Native Heap Allocated")
ax.plot(xAxis_val,dalvik_heapalloc_arr, linewidth=2.5, marker="h", label="Dalvik Heap Allocated")
#show legend
plt.legend(loc='upper right', fontsize=10)
#set the column color where PID is different from 1st PID
c=the_table.get_celld()[(5,3)]
c.set_color('r')
i=0
while i<=10:
c=the_table.get_celld()[(5,i)]
if(c.get_text().get_text()!=((the_table.get_celld()[(5,0)]).get_text().get_text())):
c.set_color('r')
(the_table.get_celld()[(4,i)]).set_color('r')
(the_table.get_celld()[(3,i)]).set_color('r')
(the_table.get_celld()[(2,i)]).set_color('r')
(the_table.get_celld()[(1,i)]).set_color('r')
i+=1
#Turn off x-axis ticks and show the plot
plt.xticks([])
#Configure Y axis
plt.ylim(0,60000)
plt.yticks([10000,20000,30000,40000,50000,60000])
plt.grid(True)
#Setting the name of the window title of the plot
fig.canvas.set_window_title(pkg_name_arr[0] + "- Memory Dump Plot")
#Setting the Title of the plot
plt.title(pkg_name_arr[0],color='r',fontsize=20)
#Setting Y Label
plt.ylabel('Heap Size', fontsize=14, color='r')
#show plot
plt.show()
#end of plt_MemDump() Method
parse_dumpFiles()
plt_MemDump(pid_arr, native_heapsize_arr, dalvik_heapsize_arr, native_heapalloc_arr, dalvik_heapalloc_arr, pkg_name_arr)
Now I want to mark the columns of the table with some color where PID value
differ with 1st PID value.(eg,column 30,60 & 100).
Can anybody help me to achieve this?
Answer: [`matplotlib.pyplot.table`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.table)
gives you already the tool to do what you need:
* `cellColours` (of the same shape of `cellText`): let you chose the colour for each cell
* `colColours`: works as `rowColours`, but for the column headers
If you want all the cells in a column to have a specific colour you can do
something like this
cellcolours = np.empty_like(tableData, dtype='object')
for i, cl in enumerate(colLabels):
if cl > 50:
cellcolours[:,i] = 'r'
and then call `plt.table` (although I suggest you to change to `ax.table`)
adding the `cellColours=cellcolours` keyword.
If you want also the column headers coloured, just do something like above
* * *
If you want to be able to change the cells after you create the table,
`table.get_celld()` returns a dictionary of cells, whose keys are tuples of
the position of each cell, eg:
{(0, 0): <matplotlib.table.Cell at 0x5d750d0>, # these are column headers
(0, 1): <matplotlib.table.Cell at 0x5d75290>,
(0, 2): <matplotlib.table.Cell at 0x5d75450>,
(0, 3): <matplotlib.table.Cell at 0x5d75610>,
[...]
(1, -1): <matplotlib.table.Cell at 0x5d757d0>, # this is a row header
(1, 0): <matplotlib.table.Cell at 0x5a58110>, # this is a cell
(1, 1): <matplotlib.table.Cell at 0x5d74150>,
(1, 2): <matplotlib.table.Cell at 0x5d74290>,
(1, 3): <matplotlib.table.Cell at 0x5d743d0>,
[...]
(2, -1): <matplotlib.table.Cell at 0x5d75990>, # this is a row header
[...] }
You can access each cell using the tuple, e.g.
c=table.get_celld()[(1,1)]
You can set the cell color with `c.set_color()` and inspect the text in the
cell with `c.get_text().get_text()` (the first `get_text` returns a `Text`
instance, the second the string in it)
|
How to get back an overridden python built-in function?
Question: When I was exploring a solution for the StackOverflow problem, [Python Use
User Defined String Class](http://stackoverflow.com/questions/20884949/python-
use-user-defined-string-class), I came with this strange python behavior.
def overriden_print(x):
print "Overriden in the past!"
from __future__ import print_function
print = overriden_print
print("Hello World!")
Output:
> Overriden in the past!
Now, how can I get back the original `print` behavior in python interpreter?
Answer: Just delete the override:
del print
This deletes the name from the `globals()` dictionary, letting search fall
back to the built-ins.
You can always refer directly to the built-in via the [`__builtin__`
module](http://docs.python.org/2/library/__builtin__.html) as well:
import __builtin__
__builtin__.print('Printing with the original built-in')
|
How to find elements of a list are subset of string using python
Question: I am a Molecular Biologist and new to programming, so excuse me for my
language. I am working with python.
Example:
string = "gctatagcgttatatactagcctatagctata"
list = ["gtagctaggac", "mptalltruiworw", "12365478995", "nvncmvncmvncmvn"]
now coming to question
I want to know a method which can discover that
for element in list:
if element is subset of string (in any order)
return element
In above example the answer should be
gtagctaggac
Answer: Rather than spend time generating permutations, compare the number of letters
in the list element and the string. Note that this code doesn't check for
letters in the string that are not in the pattern.
string = "gctatagcgttatatactagcctatagctata"
list = ["gtagctaggac", "mptalltruiworw", "12365478995", "nvncmvncmvncmvn"]
from collections import defaultdict
def count_letters(string):
counts = defaultdict(int)
for letter in string:
counts[letter] += 1
return counts
sc = count_letters(string)
for element in list:
counts = count_letters(element)
if all([sc[letter] >= counts[letter] for letter in counts]):
print "Found", element
As a matter of style, it's better not to use the names of built-in classes
like "list" and "string".
|
error with gdalbuildvrt, in Python
Question: I am new to python/GDAL and am running into perhaps a trivial issue. This may
stem from the fact that I don't really understand how to use GDAL properly in
python, or something careless, but even though I think I am following the help
doc, I keep getting a syntax error when trying to use "gdalbuildvrt".
What I want to do is take several (amount varies for each set, call it N)
geotagged 1-band binary rasters [all values are either 0 or 1] of different
sizes (each raster in the set overlaps for the most part though), and "stack"
them on top of each other so that they are aligned properly according to their
coordinate information. I want this "stack" simply so I can sum the values and
produce a 'total' tiff that has an extent to match the exclusive extent
(meaning not just the overlap region) of all the original rasters. The
resulting tiff would have values ranging from 0 to N, to represent the total
number of "hits" the pixel in that location received over the course of the N
rasters.
I was led to gdalbuildvrt [http://www.gdal.org/gdalbuildvrt.html] and after
reading about it, it seemed that by using the keyword -separate, I would be
able to achieve what I need. However, each time I try to run my program, I get
a syntax error. The following shows two of the several different ways I tried
calling gdalbuildvrt:
gdalbuildvrt -separate -input_file_list stack.vrt inputlist.txt
gdalbuildvrt -separate stack.vrt inclassfiles
Where inputlist.txt is a text file with a path to the tif on every line, just
like the help doc specifies. And inclassfiles is a python list of the
pathnames. Every single time, no matter which way I call it, I get a syntax
error on the first word after the keywords (i.e. 'inputlist' in inputlist.txt,
or 'stack' in stack.vrt).
Could someone please shed some light on what I might be doing wrong?
Alternatively, does anyone know how else I could use python to get what I
need?
Thanks so much.
Answer: `gdalbuildvrt` is a GDAL command line utility. From your example its a bit
unclear how you actually run it, but when running from within Python you
should execute it as a subprocess.
And in your first line you have the `.vrt` and the `.txt` in the wrong order.
The textfile containing the files should follow directly after the
`-input_file_list`.
From within Python you can call `gdalbuildvrt` like:
import os
os.system('gdalbuildvrt -separate -input_file_list inputlist.txt stack.vrt')
Note that the command is provided as a string. Using a Python list with the
files can be done with something like:
os.system('gdalbuildvrt -separate stack.vrt %s') % ' '.join(data)
The `' '.join(data)` part converts the list to a string with a space between
the items.
Depending on how your GDAL is build, its sometimes possible to use wildcards
as well:
os.system('gdalbuildvrt -separate stack.vrt *.tif')
|
Python Set Lookup Efficiency
Question: I'm aware that python sets have O(1) lookup time and python lists have O(n)
lookup time, but I'm curious about the container size at which it becomes
worthwhile to convert a list to a set.
In other words, if I were to call the below:
arr = [1, 2, 3]
for i in range(1000000):
random.randint(1,3) in arr
would it be more efficient than the calling the following?
s = set([1, 2, 3])
for i in range(1000000):
random.randint(1,3) in s
More importantly, what is the crossover length?
EDIT: The consensus is that this is entirely dependent on the efficient of the
hash method of user defined objects, but for primitives like string, int, etc
-- the cutoff is around 1-3.
Answer: Here's some code you can use to test it for yourself using
[`timeit`](http://docs.python.org/2/library/timeit.html):
import timeit
for i in range(10):
l = list(range(i))
s = set(l)
t1 = timeit.timeit(lambda: None in l, )
t2 = timeit.timeit(lambda: None in s)
print(i, t1, t2)
You should run this on the platform and Python implementation that you
actually care about.
Also notice that I'm searching for `None` rather than `1`, because searching
for a value that's guaranteed to be the first (or second) thing in a list is
constant-time, and that I'm using integers as in your initial test (which are,
of course, trivial to hash). You should test on the actual data you care
about.
Anyway, testing it on all of the implementations I have handy, I get a cutoff
of 0 (64-bit PyPy 2.1.0/2.7.3) to 3 (32-bit PyPy 1.9.0/2.7.2), with most of
them being 1-2. For example, here's 64-bit Python 3.3.2 crossing over at 1:
0 0.10865500289946795 0.11782343708910048
1 0.1330389219801873 0.11656044493429363
If you intentionally create an object that's slow to hash and doesn't cache,
of course, you can push that cutoff as high as you want. For example, by
putting a `time.sleep(1)` in my `__hash__` method, it ends up being around
12M.
|
Python - Extracting files from a large (6GB+) zip file
Question: I have a `Python` script where I need to extract the contents of a ZIP file.
However, the zip file is over 6GB in size.
There is a lot of information about `zlib` and `zipfile` modules, however, I
can't find a single approach that works in my case. I have the code:
with zipfile.ZipFile(fname, "r") as z:
try:
log.info("Extracting %s " %fname)
head, tail = os.path.split(fname)
z.extractall(folder + "/" + tail)
except zipfile.BadZipfile:
log.error("Bad Zip file")
except zipfile.LargeZipFile:
log.error("Zip file requires ZIP64 functionality but that has not been enabled (i.e., too large)")
except zipfile.error:
log.error("Error decompressing ZIP file")
I know that I need to set the `allowZip64` to `true` but I'm unsure of how to
do this. Yet, even as is, the `LargeZipFile` exception is not thrown, but
instead the `BadZipFile` exception is. I have no idea why.
Also, is this the best approach to handle extracting a 6GB zip archive???
Update: Modifying the `BadZipfile` exception to this:
except zipfile.BadZipfile as inst:
log.error("Bad Zip file")
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst
shows:
<class 'zipfile.BadZipfile'>
('Bad magic number for file header',)
Update #2:
The full traceback shows
BadZipfile Traceback (most recent call last)
<ipython-input-1-8d34a9f58f6a> in <module>()
6 for member in z.infolist():
7 print member.filename[-70:],
----> 8 f = z.open(member, 'r')
9 size = 0
10 while True:
/Users/brspurri/anaconda/python.app/Contents/lib/python2.7/zipfile.pyc in open(self, name, mode, pwd)
965 fheader = struct.unpack(structFileHeader, fheader)
966 if fheader[_FH_SIGNATURE] != stringFileHeader:
--> 967 raise BadZipfile("Bad magic number for file header")
968
969 fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
BadZipfile: Bad magic number for file header
Running the code:
import sys
import zipfile
with open(zip_filename, 'rb') as zf:
z = zipfile.ZipFile(zf, allowZip64=True)
z.testzip()
doesn't output anything.
Answer: The problem is that you have a corrupted zip file. I can add more details
about the corruption below, but first the practical stuff:
You can use [this code snippet](http://pastebin.com/ab3JjsHW) to tell you
which member within the archive is corrupted. However, `print z.testzip()`
would already tell you the same thing. And `zip -T` or `unzip` on the command
line should also give you that info with the appropriate verbosity.
* * *
So, what do you do about it?
Well, obviously, if you can get an uncorrupted copy of the file, do that.
If not, if you want to just skip over the bad file and extract everything
else, that's pretty easy—mostly the same code as the snippet linked above:
with open(sys.argv[1], 'rb') as zf:
z = zipfile.ZipFile(zf, allowZip64=True)
for member in z.infolist():
try:
z.extract(member)
except zipfile.error as e:
# log the error, the member.filename, whatever
* * *
The `Bad magic number for file header` exception message means that `zipfile`
was able to successfully open the zipfile, parse its directory, find the
information for a member, seek to that member within the archive, and read the
header of that member—all of which means you probably have no zip64-related
problems here. However, when it read that header, it did not have the expected
"magic" signature of `PK\003\004`. That means the archive is corrupted.
The fact that the corruption happens to be at exactly 4294967296 implies very
strongly that you had a 64-bit problem somewhere along the chain, because
that's exactly 2**32.
* * *
The command-line `zip`/`unzip` tool has some workarounds to deal with common
causes of corruption that lead to problems like this. it looks like those
workarounds may be working for this archive, given that you get a warning, but
all of the files are apparently recovered. Python's `zipfile` library does not
have those workarounds, and I doubt you want to write your own `zip`-handling
code yourself…
However, that does open the door for two more possibilities:
First, `zip` might be able to _repair_ the zipfile for you, using the `-F` of
`-FF` flag. (Read the manpage, or `zip -h`, or ask at a site like SuperUser if
you need help with that.)
And if all else fails, you can run the `unzip` tool from Python, instead of
using `zipfile`, like this:
subprocess.check_output(['unzip', fname])
That gives you a lot less flexibility and power than the `zipfile` module, of
course—but you're not using any of that flexibility anyway; you're just
calling `extractall`.
|
What magic prevents Tkinter programs from blocking in interactive shell?
Question: _Note: This is somewhat a follow-up on the question:[Tkinter - when do I need
to call mainloop?](http://stackoverflow.com/questions/8683217/tkinter-when-do-
i-need-to-call-mainloop)_
Usually when using [Tkinter](http://docs.python.org/3/library/tkinter.html),
you call [Tk.mainloop](http://www.tcl.tk/man/tcl8.5/TkLib/MainLoop.htm) to run
the event loop and ensure that events are properly processed and windows
remain interactive without blocking.
When using Tkinter from within an interactive shell, running the main loop
does not seem necessary. Take this example:
>>> import tkinter
>>> t = tkinter.Tk()
A window will appear, and it will not block: You can interact with it, drag it
around, and close it.
So, something in the interactive shell does seem to recognize that a window
was created and runs the event loop in the background.
Now for the interesting thing. Take the example from above again, but then in
the next prompt (without closing the window), enter anything—without actually
executing it (i.e. don’t press enter). For example:
>>> t = tkinter.Tk()
>>> print('Not pressing enter now.') # not executing this
If you now try to interact with the Tk window, you will see that it completely
_blocks_. So the event loop which we thought would be running in the
background stopped while we were entering a command to the interactive shell.
If we send the entered command, you will see that the event loop _continues_
and whatever we did during the blocking will continue to process.
So the big question is: **What is this magic that happens in the interactive
shell?** What runs the main loop when we are not doing it explicitly? And why
does it need to halt when we _enter_ commands (instead of halting when we
execute them)?
_Note:_ The above works like this in the command line interpreter, not IDLE.
As for IDLE, I assume that the GUI won’t actually tell the underlying
interpreter that something has been entered but just keep the input locally
around until it’s being executed.
Answer: It's actually not being an interactive interpreter that matters here, but
waiting for input on a TTY. You can get the same behavior from a script like
this:
import tkinter
t = tkinter.Tk()
input()
(On Windows, you may have to run the script in pythonw.exe instead of
python.exe, but otherwise, you don't have to do anything special.)
* * *
So, how does it work? Ultimately, the trick comes down to `PyOS_InputHook`—the
same way the `readline` module works.
If stdin is a TTY, then, each time it tries to fetch a line with `input()`,
various bits of the `code` module, the built-in REPL, etc., Python calls any
installed `PyOS_InputHook` instead of just reading from stdin.
It's probably easier to understand [what `readline`
does](http://hg.python.org/cpython/file/045e7a587f3c/Modules/readline.c#l983):
it tries to `select` on stdin or similar, looping for each new character of
input, or every 0.1 seconds, or every signal.
[What `Tkinter`
does](http://hg.python.org/cpython/file/045e7a587f3c/Modules/_tkinter.c#l3051)
is similar. It's more complicated because it has to deal with Windows, but on
*nix it's doing something pretty similar to `readline`. Except that it's
calling `Tcl_DoOneEvent` each time through the loop.
And that's the key. Calling `Tcl_DoOneEvent` repeatedly is exactly the same
thing that
[`mainloop`](http://hg.python.org/cpython/file/045e7a587f3c/Modules/_tkinter.c#l2581)
does.
(Threads make everything more complicated, of course, but let's assume you
haven't created any background threads. In your real code, if you want to
create background threads, you'll just have a thread for all the `Tkinter`
stuff that blocks on `mainloop` anyway, right?)
* * *
So, as long as your Python code is spending most of its time blocked on TTY
input (as the interactive interpreter usually is), the Tcl interpreter is
chugging along and your GUI is responding. If you make the Python interpreter
block on something other than TTY input, the Tcl interpreter is not running
and the your GUI is not responding.
* * *
What if you wanted to do the same thing manually in pure Python code? You'd of
need to do that if you want to, e.g., integrate a Tkinter GUI and a
`select`-based network client into a single-threaded app, right?
That's easy: Drive one loop from the other.
You can `select` with a timeout of 0.02s (the same timeout the default input
hook uses), and call `t.dooneevent(Tkinter.DONT_WAIT)` each time through the
loop.
Or, alternatively, you can let Tk drive by calling `mainloop`, but use `after`
and friends to make sure you call `select` often enough.
|
Facebook Python " ValueError: too many values to unpack"
Question: I am new to programing and Python..
Below is my code.
import csv
import json
import urllib
import sys
import time
import re
class FacebookSearch:
def __init__(self,
query = 'https://graph.facebook.com/search.{mode}?{query}&{access_token}'
):
access_token = 'XXXXXX|XXXXX'
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
return query
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = FacebookSearch()
response, data = ts.search('appliance', type='post') ## here is where I am getting the error.
js = json.loads(data)
messages = ([msg['created_time'], msg['id']] for msg in js.get('data', []))
write_csv('fb_washerdryer.csv', messages, append=True)
if __name__ == '__main__':
main()
Here is the trace back on the error:
Traceback (most recent call last): File "./facebook_washer_dryer1.sh", line
43, in main() File "./facebook_washer_dryer1.sh", line 33, in main response,
data = ts.search('appliance', type='post') ValueError: too many values to
unpack
Answer: Your `FacebookSearch.search` method returns a single value, a query string to
tack onto a URL.
But when you call it, you're trying to unpack the results to two variables:
response, data = ts.search('appliance', type='post')
And that doesn't work.
So, why does the error say "too many values" instead of "too few"? Well, a
string is actually a sequence of single-character strings, so it's trying to
unpack that single string into dozens of separate values, one for each
character.
* * *
However, you've got a much bigger problem here. You clearly _expected_ your
`search` method to return a response and some data, but it doesn't return
anything even _remotely_ like a response and some data, it returns a query
string. I think you wanted to actually build a URL _with_ the query string,
then download that URL, then return the results of that download.
Unless you write code that actually attempts to do that (which probably means
changing `__init__` to store `self.query` and `self.access_token`, using
`self.query.format` in `search`, using `urllib2.urlopen` on the resulting
string, and a bunch of other changes), the rest of your code isn't going to do
anything useful.
If you want to "stub out" `FacebookSearch` for now, so you can test the rest
of your code, you need to make it return appropriate fake data that the rest
of your code can work with. For example, you could do this:
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
# TODO: do the actual query
return 200, '{"Fake": "data"}'
|
How to show hashtag - tweepy?
Question: I want to see all the tweets that have a specific hashtag. I wrote the code
like this:
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey = 'xxx'
csecret = 'xxx'
atoken = 'xxx'
asecret = 'xxx'
class listener(StreamListener):
def on_status(self, status):
print 'Tweet text: ' + status.text
for hashtag in status.entries['hashtags']:
print hashtag['text']
return True
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(follow=[23], track=["#django"])
Follow a number of my friends, track - wants to see the messages with the
hashtag.
On a test account that I wrote constantly follow the hashtag who wants to see.
When I run the program, python crashes.
What I'm doing wrong?
Thanks for help.
Answer:
try something like this:
def on_data(self, data):
jsonData=json.loads(data)
text=jsonData['text']
text2=jsonData['entities']['hashtags']
for hashtag in text2:
text2=hashtag['text']
print text+str(text2)
return True
def on_error(self, status):
print status
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter( track=["django"])
|
Interpolation ignoring zero values in array - Python
Question: I have two arrays of the same length
x = array([-243., -242., -241., -240., -239., -238., -237., -236., -235.,
-234., -233., -232., -231., -230., -229., -228., -227., -226.,
-225., -224., -223., -222., -221., -220., -219., -218., -217.,
-216., -215., -214., -213., -212., -211., -210., -209., -208.,
-207., -206., -205., -204., -203., -202., -201., -200., -199.,
-198., -197., -196., -195., -194., -193., -192., -191., -190.,
-189., -188., -187., -186., -185., -184., -183., -182., -181.,
-180., -179., -178., -177., -176., -175., -174., -173., -172.,
-171., -170., -169., -168., -167., -166., -165., -164., -163.,
-162., -161., -160., -159., -158., -157., -156., -155., -154.,
-153., -152., -151., -150., -149., -148., -147., -146., -145.,
-144., -143., -142., -141., -140., -139., -138., -137., -136.,
-135., -134., -133., -132., -131., -130., -129., -128., -127.,
-126., -125., -124., -123., -122., -121., -120., -119., -118.,
-117., -116., -115., -114., -113., -112., -111., -110., -109.,
-108., -107., -106., -105., -104., -103., -102., -101., -100.,
-99., -98., -97., -96., -95., -94., -93., -92., -91.,
-90., -89., -88., -87., -86., -85., -84., -83., -82.,
-81., -80., -79., -78., -77., -76., -75., -74., -73.,
-72., -71., -70., -69., -68., -67., -66., -65., -64.,
-63., -62., -61., -60., -59., -58., -57., -56., -55.,
-54., -53., -52., -51., -50., -49., -48., -47., -46.,
-45., -44., -43., -42., -41., -40., -39., -38., -37.,
-36., -35., -34., -33., -32., -31., -30., -29., -28.,
-27., -26., -25., -24., -23., -22., -21., -20., -19.,
-18., -17., -16., -15., -14., -13., -12., -11., -10.,
-9., -8., -7., -6., -5., -4., -3., -2., -1.,
-0., 0., 1., 2., 3., 4., 5., 6., 7.,
8., 9., 10., 11., 12., 13., 14., 15., 16.,
17., 18., 19., 20., 21., 22., 23., 24., 25.,
26., 27., 28., 29., 30., 31., 32., 33., 34.,
35., 36., 37., 38., 39., 40., 41., 42., 43.,
44., 45., 46., 47., 48., 49., 50., 51., 52.,
53., 54., 55., 56., 57., 58., 59., 60., 61.,
62., 63., 64., 65., 66., 67., 68., 69., 70.,
71., 72., 73., 74., 75., 76., 77., 78., 79.,
80., 81., 82., 83., 84., 85., 86., 87., 88.,
89., 90., 91., 92., 93., 94., 95., 96., 97.,
98., 99., 100., 101., 102., 103., 104., 105., 106.,
107., 108., 109., 110., 111., 112., 113., 114., 115.,
116., 117., 118., 119., 120., 121., 122., 123., 124.,
125., 126., 127., 128., 129., 130., 131., 132., 133.,
134., 135., 136., 137., 138., 139., 140., 141., 142.,
143., 144., 145., 146., 147., 148., 149., 150., 151.,
152., 153., 154., 155., 156., 157., 158., 159., 160.,
161., 162., 163., 164., 165., 166., 167., 168., 169.,
170., 171., 172., 173., 174., 175., 176., 177., 178.,
179., 180., 181., 182., 183., 184., 185., 186., 187.,
188., 189., 190., 191., 192., 193., 194., 195., 196.,
197., 198., 199., 200., 201., 202., 203., 204., 205.,
206., 207., 208., 209., 210., 211., 212., 213., 214.,
215., 216., 217., 218., 219., 220., 221., 222., 223.,
224., 225., 226., 227., 228., 229., 230., 231., 232.,
233., 234., 235., 236., 237., 238., 239., 240., 241.,
242., 243.])
y = array([ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 8.31593344e-02,
2.35439791e-01, 9.96024791e-01, 2.05616777e+00,
7.18482061e+00, 1.88705079e+01, 2.95964175e+01,
7.67566181e+01, 1.00520725e+02, 1.50101258e+02,
1.30495335e+02, 7.38818649e+01, 7.88215800e+01,
8.27782533e+01, 8.54715249e+01, 0.00000000e+00,
0.00000000e+00, 8.66810877e+01, 0.00000000e+00,
0.00000000e+00, 8.62917273e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 8.43340655e+01,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
8.10109967e+01, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 7.67001996e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 7.19263508e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 6.73025361e+01,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
6.34476840e+01, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
6.08936791e+01, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
6.00000000e+01, 6.00000000e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 6.08936791e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 6.34476840e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 6.73025361e+01,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
7.19263508e+01, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
7.67001996e+01, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 8.10109967e+01, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 8.43340655e+01,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
8.62917273e+01, 0.00000000e+00, 0.00000000e+00,
8.66810877e+01, 0.00000000e+00, 0.00000000e+00,
8.54715249e+01, 8.27782533e+01, 7.88215800e+01,
7.38818649e+01, 1.30495335e+02, 1.50101258e+02,
1.00520725e+02, 7.67566181e+01, 2.95964175e+01,
1.88705079e+01, 7.18482061e+00, 2.05616777e+00,
9.96024791e-01, 2.35439791e-01, 8.31593344e-02,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00])
plotting x against y yields

My question is how can I interpolate y so that the plot ignores the zero
values and gives a smooth curve.
The output should look something like this (ignore the axes): 
Cheers
Answer: Using
[`numpy.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html):
indice = numpy.where(y != 0)
plot(x[indice], y[indice])
or using
[`numpy.nonzero`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html):
indice = numpy.nonzero(y) # OR y.nonzero()
plot(x[indice], y[indice])

* * *
**UPDATE**
interpolation using
[`scipy.interpolate.interp1d`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html):
from scipy.interpolate import interp1d
indice, = y.nonzero()
start, stop = indice[0], indice[-1]+1
f = interp1d(x[indice], y[indice])
y[start:stop] = f(x[start:stop])
plot(x, y)
|
subprocess.check_ouput is hanging up in eclipse and not taking backup for pg_dump in python langauage
Question: postgres dump is not working properly, i run the below python program through
eclipse with linux(ubuntu) background OS.
The problem is eclipse get hanged up and trace information as well as backup
file is empty.
import os
import subprocess
if __name__ == '__main__':
print "test hello"
localhost = 'localhost'
port = '5432'
role = 'serverdb_user'
dump_dir = '/home/backupfile/'
db_username = 'empserverdb_user'
db_names = 'emp1'
try:
bkp_file = 'backup1'
file_path = os.path.join(dump_dir, bkp_file)
print file_path
dumper_cmd = ['pg_dump', '-h', localhost, '-p', port, '-U', db_username, '--role', role, '-W', '-Fc', '-v', '-f', file_path, db_names]
print dumper_cmd
subprocess.check_output(dumper_cmd)
except subprocess.CalledProcessError, ex:
print("Couldn't back up database {0}: pg_dump returned {1} with output {2}".format(db_names, ex.returncode, ex.output))
except Exception, ex:
print("Couldn't backup database {0}: unexpected error {1}".format(db_names, ex))
Please help where im doing wrong.
Answer: The problem get resolved by placing assigning password to env. As well as
people suggestion on post [Postgres Dump is strucked in eclipse, language used
is python](http://stackoverflow.com/questions/20882836/postgres-dump-is-
strucked-in-eclipse-language-used-is-python)
|
How to Write Python Script in html
Question: I want to execute my python code on the side even though there might be
security problem
How can I write with importing modules and all? I have tried using of pyjs to
convert the below code to JS `import socket print
socket.gethostbyname_ex(socket.gethostname())[2][0]` but I am not find how to
do the same.
Please help me how to how can convert this to JS and how to write other the
python scripts and how to import modules in HTML.
Answer: There are more than just security problems. It's just not possible. You can't
use the Python socket library inside the client browser. You can convert
Python code to JS (probably badly) but you can't use a C based library that is
probably not present on the client. You can access the browser only. You
cannot reliably get the hostname of the client PC. Maybe ask another question
talking about what you are **trying to achieve** and someone might be able to
help
|
selenium 2- python- cannot import webdriver even though selenium is up to date
Question: Im trying to use selenium in python 2.7 and when trying to import webdriver it
gives me the error "ImportError: cannot import name webdriver" Ive had a
search around and people seem to say updating it should sort the problem which
i have tried using "pip install -U Selenium" which responds saying it is
already upto date.
This is the full reply i get when running my script:
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 326, in RunScript
exec codeObject in __main__.__dict__
File "C:\Python27\selenium.py", line 1, in <module>
from selenium import webdriver
File "C:\Python27\selenium.py", line 1, in <module>
from selenium import webdriver
ImportError: cannot import name webdriver
Answer: I think looking at what you have (although python is pretty far down my known
languages list) that the problem is related to the wrong selenium being
imported. Have a look at:
[Trying to use Selenium 2 with Python bindings, but I'm getting an import
error](http://stackoverflow.com/questions/7426851/trying-to-use-
selenium-2-with-python-bindings-but-im-getting-an-import-error)
|
How to extract method using Suds in Python
Question: I want to extract all the methods and want to send some parameters using how
can I do automation using python.
I want only methods as user input and send parameters to the method. How can I
achieve this?
from suds.client import client
url="name fo the url"
client=Client(url)
Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913
Service ( Services ) tns="http://www.altoromutual.com/bank/ws/"
Prefixes (1)
ns0 = "http://www.altoromutual.com/bank/ws/"
Ports (2):
(ServicesSoap)
Methods (3):
GetUserAccounts(xs:int UserId, )
IsValidUser(xs:string UserId, )
TransferBalance(MoneyTransfer transDetails, )
Types (4):
AccountData
ArrayOfAccountData
MoneyTransfer
Transaction
(ServicesSoap12)
Methods (3):
GetUserAccounts(xs:int UserId, )
IsValidUser(xs:string UserId, )
TransferBalance(MoneyTransfer transDetails, )
Types (4):
AccountData
ArrayOfAccountData
MoneyTransfer
Transaction
Answer: To list all the methods available in the WSDL:
>>> from suds.client import Client
>>> url_service = 'http://www.webservicex.net/globalweather.asmx?WSDL'
>>> client = Client(url_service)
>>> list_of_methods = [method for method in client.wsdl.services[0].ports[0].methods]
>>> print list_of_methods
[GetWeather, GetCitiesByCountry]
Then to call the method itself:
>>> response = client.service.GetCitiesByCountry(CountryName="France")
Note: Some simple examples are available at "[Python Web Service Client Using
SUDS and
ServiceNow](http://community.servicenow.com/blog/christophermaloy/python-web-
service-client-using-suds-and-servicenow)".
Following @kflaw's comment, this is how to retrieve the list of parameters
that one's should pass to a method:
>>> method = client.wsdl.services[0].ports[0].methods["GetCitiesByCountry"]
>>> params = method.binding.input.param_defs(method)
>>> print params
[(CountryName, <Element:0x10a574490 name="CountryName" type="(u'string', u'http://www.w3.org/2001/XMLSchema')" />)
|
How to use a variable in a module from the script that called the module
Question: I would like to make a plugin system for my script.
**How plugins are loaded**
The plugins are python modules stored in a specified folder.
I import the modules with this code:
class Igor:
# ...
def load_plugins(self):
for file in os.listdir(self.plugins_folder):
try:
__import__(file)
except Exception as error:
sys.exit(error)
# ...
**The variable I want to make available in the plugins**
I have a variable named `igor` who is an instance of `Igor`:
if __name__ == "__main__":
# ...
igor = Igor()
# ...
**What I want the plugins developers able to do**
I want to make plugins development easy and `igor` have all the methods needed
to make it easy.
At best it should be something like this (in `__init__.py`):
from plugins.files.files import Files
igor.register_plugin("files", Files())
**How can I do that?**
I really don't see how to do this `globals()` display `igor` in my main script
but there is nothing in the globals from the menu (as expected from a module,
it is sandboxed I supposed).
Any ideas?
Answer: You will need to change the load_plugins method on your Igor class:
def load_plugins(self):
if not os.path.exists(self.plugins_folder):
os.makedirs(self.plugins_folder)
plugin_folder_content = os.listdir(self.plugins_folder)
for content in plugin_folder_content:
content_path = os.path.join(self.plugins_folder, content)
if os.path.isdir(content_path):
plugin_entry_point_path = os.path.join(content_path, "__init__.py")
if os.path.exists(plugin_entry_point_path):
try:
with open(plugin_entry_point_path, 'r') as file:
sys.path.insert(1, content_path)
exec(compile(file.read(), "script", "exec"), {"igor": self, "IgorPlugin": IgorPlugin, 'path': content_path})
sys.path.remove(content_path)
except Exception as exc:
sys.exit(exc)
This creates another problem: as we are excecuting the **init**.py files on
each module, defined on each subdirectory, you can't import files easily,
that's why I'm passing the path variable, to import files manually, this is an
example of a imaginary **init**.py file which imports files.py plugin:
import os
files_path = os.path.join(path, "files.py")
exec(compile(open(files_path).read(), "script", "exec"), {"igor": igor, "IgorPlugin": IgorPlugin})
|
Getting console.log output from Chrome with Selenium Python API bindings
Question: I'm using Selenium to run tests in Chrome via the Python API bindings, and I'm
having trouble figuring out how to configure Chrome to make the `console.log`
output from the loaded test available. I see that there are `get_log()` and
`log_types()` methods on the WebDriver object, and I've seen [Get chrome's
console log](http://stackoverflow.com/questions/18261338/get-chromes-console-
log/18283831#18283831) which shows how to do things in Java. But I don't see
an equivalent of Java's `LoggingPreferences` type in the Python API. Is there
some way to accomplish what I need?
Answer: Ok, finally figured it out:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# enable browser logging
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=d)
# load some site
driver.get('http://foo.com')
# print messages
for entry in driver.get_log('browser'):
print entry
Entries whose `source` field equals `'console-api'` correspond to console
messages, and the message itself is stored in the `message` field.
|
Styling with classes in Pyside + Python
Question: How can I better style this app using classes rather than redefining the same
styles for every label that should look the same. It makes it a pain to change
a style because I then have to go through every label that is suppose to look
the same and paste the code to match.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
#Add all GUI Elements to Class
self.amountLabel = QtGui.QLabel('Amount')
self.counterLabel = QtGui.QLabel('Counter')
self.totalLabel = QtGui.QLabel('Total')
self.amountSpin = QtGui.QSpinBox()
self.counterSpin = QtGui.QSpinBox()
self.totalOutput = QtGui.QLabel('0')
grid = QtGui.QGridLayout()
grid.setSpacing(0)
grid.addWidget(self.amountLabel, 3, 0)
grid.addWidget(self.counterLabel, 3, 1)
grid.addWidget(self.totalLabel, 3, 2)
grid.addWidget(self.amountSpin, 4, 0)
grid.addWidget(self.counterSpin, 4, 1)
grid.addWidget(self.totalOutput, 4, 2)
self.setLayout(grid)
# STYLING
self.amountLabel.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(188, 188, 188, 50); border: 1px solid rgba(188, 188, 188, 250); }")
self.amountSpin.setStyleSheet("QSpinBox { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(255, 188, 20, 50); }")
self.counterLabel.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(188, 188, 188, 50); border: 1px solid rgba(188, 188, 188, 250); }")
self.counterSpin.setStyleSheet("QSpinBox { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(255, 188, 20, 50); }")
self.totalLabel.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-weight:bold; font-size: 11px; background-color: rgba(26, 188, 182, 150); border: 1px solid rgba(26, 188, 182, 255); }")
self.totalOutput.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-weight:bold; font-size: 11px; background-color: rgba(26, 188, 182, 50); border: 1px solid rgba(26, 188, 182, 255); }")
self.setGeometry(800, 400, 250, 80)
self.setWindowTitle('Simple Calculator')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Answer: If I am not mistaken, stylesheets of a parent are applied to all children
unless overwritten.
You can try this:
# STYLING
self.setStyleSheet("QLabel { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(188, 188, 188, 50); border: 1px solid rgba(188, 188, 188, 250); } QSpinBox { color: rgb(50, 50, 50); font-size: 11px; background-color: rgba(255, 188, 20, 50); }")
#setting CS of self (the widget) and not the children
self.setGeometry(800, 400, 250, 80)
self.setWindowTitle('Simple Calculator')
self.show()
Concerning your different buttons:
label1.setProperty('labelClass', 'red')
label2.setProperty('labelClass', 'blue')
and in the CS of the widget:
QLabel[labelClass="red"] {...}
QLabel[labelClass="blue"] {...}
|
Calling configuration file ID into Linux Command with Date Time from Python
Question: I'm trying to write a script to get the following outputs to a folder
(YYYYMMDDHHMMSS = current date and time) using a Linux command in Python, with
the ID's in a configutation file
1234_YYYYMMDDHHMMSS.txt
12345_YYYYMMDDHHMMSS.txt
12346_YYYYMMDDHHMMSS.txt
I have a config file with the list of ID's
id1 = 1234
id2 = 12345
id3 = 123456
I want to be able to loop through these in python and incorporate them into a
linux command.
Currently, my linux commands are hardcoded in python as such
import subprocess
import datetime
now = datetime.datetime.now()
subprocess.call('autorep -J 1234* -q > /home/test/output/1234.txt', shell=True)
subprocess.call('autorep -J 12345* -q > /home/test/output/12345.txt', shell=True)
subprocess.call('autorep -J 123456* -q > /home/test/output/123456.txt', shell=True)
print now.strftime("%Y%m%d%H%M%S")
The datetime is defined, but doesn't do anything currently, except print it to
the console, when I want to incorporate it into the output txt file. However,
I want to be able to write a loop to do something like this
subprocess.call('autorep -J id1* -q > /home/test/output/123456._now.strftime("%Y%m%d%H%M%S").txt', shell=True)
subprocess.call('autorep -J id2* -q > /home/test/output/123456._now.strftime("%Y%m%d%H%M%S").txt', shell=True)
subprocess.call('autorep -J id3* -q > /home/test/output/123456._now.strftime("%Y%m%d%H%M%S").txt', shell=True)
I know that I need to use ConfigParser and currently have been this piece
written which simply prints the ID's from the configuration file to the
console.
from ConfigParser import SafeConfigParser
import os
parser = SafeConfigParser()
parser.read("/home/test/input/ReportConfig.txt")
def getSystemID():
for section_name in parser.sections():
print
for key, value in parser.items(section_name):
print '%s = %s' % (key,value)
print
getSystemID()
But as mentioned in the beggining of the post, my goal is to be able to loop
through the ID's, and incorporate them into my linux command while adding the
datetime format to the end of the file. I'm thinking all I need is some kind
of while loop in the above function in order to get the type of output I want.
However, I'm not sure how to call the ID's and the datetime into a linux
command.
Answer: So far you have most of what you need, you are just missing a few things.
First, I think using ConfigParser is overkill for this. But it's simple enough
so lets continue with it. Lets change `getSystemID` to a generator returning
your IDs instead of printing them out, its just a one line change.
parser = SafeConfigParser()
parser.read('mycfg.txt')
def getSystemID():
for section_name in parser.sections():
for key, value in parser.items(section_name):
yield key, value
With a generator we can use `getSystemID` in a loop directly, now we need to
pass this on to the subprocess call.
# This is the string of the current time, what we add to the filename
now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# Notice we can iterate over ids / idnumbers directly
for name, number in getSystemID():
print name, number
Now we need to build the subprocess call. The bulk of your problem above was
knowing how to format strings, the syntax is described
[here](http://docs.python.org/2/library/string.html#formatstrings).
I'm also going to make two notes on how you use `subprocess.call`. First, pass
a list of arguments instead of a long string. This helps python know what
arguments to quote so you don't have to worry about it. You can read about it
in the [subprocess](http://docs.python.org/2/library/subprocess.html) and
[shlex](http://docs.python.org/2/library/shlex.html?highlight=shlex#shlex)
documentation.
Second, you redirect the output using `>` in the command and (as you noticed)
need `shell=True` for this to work. Python can redirect for you, and you
should use it.
To pick up where I left off above in the foor loop.
for name, number in getSystemID():
# Make the filename to write to
outfile = '/home/test/output/{0}_{1}.txt'.format(number, now)
# open the file for writing
with open(outfile, 'w') as f:
# notice the arguments are in a list
# stdout=f redirects output to the file f named outfile
subprocess.call(['autorep', '-J', name + '*', '-q'], stdout=f)
|
how to get nested tags with a loaded html page using python or php?
Question: How to do it?
How to get nested tags with a loaded html page using python or php?
Could you give me maybe a site where I can learn?
from HTMLParser import HTMLParser
import urllib
class MyHTMLParser(HTMLParser):
def handlestarttag(self, tag, attrs):
print "Poczatek %s" % tag
def handleendtag(self, tag):
print "Koniec %s tag" % tag
def handledata(self, data):
print "Dane %s" % data
p = MyHTMLParser()
input = urllib.urlopen('url')
html = input.read()
input.close()
p.feed(html)
Answer: Look into [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/):
Here is an example for you:
from bs4 import BeautifulSoup
# Use urlopen to read web pages, this is only an e
test_input = r'<html><body><div id="bar"><p>Foo</p></div></body></html>'
soup = BeautifulSoup(test_input)
print soup.find('div', {'id': 'bar'}).p.text
This yields:
Foo
Look into the docs for BS for more examples. The important thing here is to
use an existing library, and not try to create one for your own.
|
python conversion of two dimensional list of float to two dimensional array of float
Question: I am trying to read a column of float into a list for each of a set of CSV
files, then appending to a two dimensional list, later converting that to a 2D
array, but the array doesn't convert into a two dimensional array of float
(paraphrased below). Where am I going wrong?
import numpy
symbols = ['CVX', 'COP', 'MMM', 'BP', 'HMC', 'TM']
AA_lst = []
nSyms = len(symbols)
shortest = 99999
for sym in symbols
fn = "PricesOf_" + sym + ".csv"
col = getCSVcolumn( fn, "Close" )
print( "type(col)=" + str(type(col)) ) # --> <class 'list'>
print( "type(col[0])=" + str(type(col[0])) ) # --> <class 'float'>
shortest = min(shortest,len(col))
AA_lst.append(col) # appended as a row of AA_lst
AA = numpy.array( AA_lst )
print( "type=(AA)=" + str(type(AA)) ) # --> <class 'numpy.ndarray'>
print( "type=(AA[0]=" + str(type(AA[0])) ) # --> <class 'list'>
#print( "type=(AA[0,0]=" + str(type(AA[0,0])) ) # --> Error, too many indices
# fix up dimensions (so rows are all the same length)
AA = numpy.resize( AA, (nSyms, shortest) )
print( "type=(AA)=" + str(type(AA)) ) # --> <class 'numpy.ndarray'>
print( "type=(AA[0]=" + str(type(AA[0])) ) # --> <class 'numpy.ndarray'>
print( "type=(AA[0,0]=" + str(type(AA[0,0])) ) # --> <class 'list'>
# desire something of the form: array([[1,2,3] [4,5,6] [7,8,9]])
# i.e. expecting type(AA[0,0] to be <class 'float'>, not <class 'list'>
Answer: 1. Make sure the lists in `AA_lst` are of the same length.
2. Consider using [pandas](http://pandas.pydata.org/).
|
Setting PYTHONPATH environment variable in Visual Studio C++
Question: I have a C++ program which imports a Python module, along the lines of this
snippet:
#include <Python.h>
char python_module[] = "my_module";
Py_Initialize();
PyObject* pName;
pName = PyString_FromString(python_module);
pModule = PyImport_Import(pName);
However the module needs to be on the `PYTHONPATH` for this line to actually
load the module. On Mac or Linux this is relatively straightforward - set
`PYTHONPATH` on the term you are running the compiled program from. Is there a
way to do this for Visual Studio C++? Setting the `PYTHONPATH` windows
environment variable hasn't helped.
Answer: Here is scheme to setup module search path:
1. The script location; the current directory without script.
2. The PYTHONPATH variable, if set.
3. For Win32 platforms (NT/95), paths specified in the Registry.
4. Default directories lib, lib/win, lib/test, lib/tkinter; these are searched relative to the environment variable PYTHONHOME, if set, or relative to the executable and its ancestors, if a landmark file (Lib/string.py) is found, or the current directory (not useful).
5. The directory containing the executable.
You probably need to restart IDE to get it working.
|
how to trap the value error in python
Question: If any file is corrupted and cannot be open, the following code raise value
error and stop opening of further files. How can I print out the name of the
file which raised value error, and make the program to run further to detect
and print out next file which raise value error?
import glob
from PIL import Image
files = glob.glob('*.jpg')
for f in files:
im = Image.open(f)
print im
Answer: You can _catch_ the exception with a `try:` / `except:` handler:
for f in files:
try:
im = Image.open(f)
except IOError as e:
print '{} failed to load: {}'.format(f, e)
else:
print im
The Python tutorial has a [chapter devoted to error
handling](http://docs.python.org/2/tutorial/errors.html) you might want to
read.
|
How to add modules from a custom repository that isn't a package? python
Question: I have tried to use `sys.path.append()` with `os.getcwd()` but it didn't work.
The source was from [**here**](https://github.com/alvations/DLTK) and I've
downloaded and extracted them as such:
alvas@ubi:~/test$ wget https://github.com/alvations/DLTK/archive/master.zip
alvas@ubi:~/test$ tar xvzf master.zip
alvas@ubi:~/test$ cd DLTK-master/; ls
dltk
alvas@ubi:~/test/DLTK-master$ cd dltk/; ls
tokenize
alvas@ubi:~/test/DLTK-master/dltk$ cd tokenize/; ls
abbrev.lex jwordsplitter-3.4.jar rbtokenize.pl
banana-split-standalone-0.4.0.jar koehn_senttokenize.pl splicer.py
igerman98_all.xml koehn_wordtokenize.pl tokenizer.py
__init__.py nonbreaking_prefix.de
alvas@ubi:~/test/DLTK-master/dltk/tokenize$ cat __init__.py
from tokenizer import punct_tokenize, rb_tokenize
from tokenizer import koehn_tokenize, deupunkt_tokenize
from splicer import jwordsplitter, jwordsplitteralvas
Those are the functions I want to access from the `~/text/` directory, e.g.
the `koehn_tokenize` function. But i can't seem to add the modules/functions
into my python interpreter.
alvas@ubi:~/test$ wget https://github.com/alvations/DLTK/archive/master.zip
alvas@ubi:~/test$ tar xvzf master.zip
alvas@ubi:~/test$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys, os
>>> os.getcwd()
'/home/alvas/test'
>>> sys.path.append(os.path.join(os.getcwd(),'DLKT-master/dltk'))
['','/usr/local/lib/python2.7/dist-packages/...', ...,'/home/alvas/test/DLKT-master/dltk']
>>>
>>> import dltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named dltk
>>>
>>> from dltk.tokenize import koehn_tokenize
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named dltk.tokenize
**From the python interpreter at`~/test/` directory, how can I access the the
`dltk.tokenize` module?**
The functions works if it `cd` into `~/test/DLTK-master/dltk/tokenize`:
alvas@ubi:~/test$ cd DLTK-master/dltk/tokenize/
alvas@ubi:~/test/DLTK-master/dltk/tokenize$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __init__ import koehn_tokenize
>>>
But I **DO NOT** want to `cd` into the `~/test/DLTK-master/dltk/tokenize`
before using the python interpreter. I need to somehow append the
module/functions within python.
Answer: If `master.zip` would contain `dltk/__init__.py`, `dltk/tokenize/__init__.py`
then you could try to add it to `sys.path` directly:
import sys; sys.path.append('master.zip')
from dltk.tokenize import koehn_tokenize
* * *
> From the python interpreter at `~/test/` directory, how can I access the the
> `dltk.tokenize` module?
Just add `~/test/DLTK-master` directory to `sys.path`:
import sys; sys.path.append('DLTK-master')
from dltk.tokenize import koehn_tokenize
|
Python argparse example?
Question: I'm trying to learn argparse in order to use it in my program, the syntax
should be like this:
-a --aLong <String> <String>
-b --bLong <String> <String> <Integer>
-c --cLong <String>
-h --help
I have this code:
#!/usr/bin/env python
#coding: utf-8
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Lorem Ipsum')
parser.add_argument('-a','--aLong', help='Lorem Ipsum', required=False)
parser.add_argument('-b','--bLong', help='Lorem Ipsum', required=False)
parser.add_argument('-c','--cLong', help='Lorem Ipsum', required=False)
parser.add_argument('-h','--help', help='Lorem Ipsum', required=False)
parser.parse_args()
The question is, I read in the official doc, saw YouTube videos, etc, but I
couldn't understand how can I determine the number of "sub-arguments" of the
"main-argument"?
Example: `myApp.py -b Foobar 9000`, how can I set that `-b` must have two
"sub-arguments", and how can I get the values, `Foobar` and `9000`?
And another doubt, I know I can set an argument to be `required` or not, but I
wanted to make my program only executes when **at least one** argument is
passed, any of the four mentioned.
Maybe it's a stupid question, but sorry, I can't understand it, and hopefully
there is someone here with "teacher powers" to explain it.
Answer:
import argparse
# Use nargs to specify how many arguments an option should take.
ap = argparse.ArgumentParser()
ap.add_argument('-a', nargs=2)
ap.add_argument('-b', nargs=3)
ap.add_argument('-c', nargs=1)
# An illustration of how access the arguments.
opts = ap.parse_args('-a A1 A2 -b B1 B2 B3 -c C1'.split())
print(opts)
print(opts.a)
print(opts.b)
print(opts.c)
# To require that at least one option be supplied (-a, -b, or -c)
# you have to write your own logic. For example:
opts = ap.parse_args([])
if not any([opts.a, opts.b, opts.c]):
ap.print_usage()
quit()
print("This won't run.")
|
ImportError: cannot import name SSLError
Question: I need the SSLError utility function but ...
from requests.exceptions import SSLError
and I get ImportError: cannot import name SSLError :(
PS: I have installed python-requests in Ubuntu using the python-requests
package
Answer: Your `requests` library version is too old. The `SSLError` exception was not
added to `requests.exceptions` until version 0.8.8, in [revision
9a1a413](https://github.com/kennethreitz/requests/commit/9a1a4136ac69cce55d8d5f27a0ab1caadb0a6e90).
|
Pyint tip 'Unable to import <module>'
Question:
testproject/src/pkga/pkgb/pkgc/module.py
testproject/test/pkga/pkgb/pkgc/module_test.py
src and test is the source folder,
src/pkga and test/pkga is the root package
in file module_test.py
from pkga.pkgb.pkgc import module
pylint module_test.py will tip `Unable to import pkga.pkgb.pkgc` even add
'testproject/src/' to the `PYTHONPATH`
it's seems pylint will only find 'pkga/pkgb/pkgc/module.py' in dir
'testproject/test/'
however, it will be ok if change 'testproject/src/pkga/pkgb/pkgc/module.py' to
'testproject/src/pkganew/pkgb/pkgc/module.py'
Any suggestion?
Answer: Does it work when you run `python module_test.py`? Which directories have
`__init__.py` file ?
I suppose that there is either a PYTHONPATH problem or a package conflict,
i.e. pylint/python picks the first `pkga` package directory, which is probably
the one where `module_test` is, hence does'nt find `module` in it.
|
Scrapy Spider for JSON Response
Question: I am trying to write a spider which crawls through the following JSON
response:
[http://gdata.youtube.com/feeds/api/standardfeeds/UK/most_popular?v=2&alt=json](http://gdata.youtube.com/feeds/api/standardfeeds/UK/most_popular?v=2&alt=json)
How would the spider look if I would want to crawl all the titles of the
videos? All my Spiders dont work.
from scrapy.spider import BaseSpider
import json
from youtube.items import YoutubeItem
class MySpider(BaseSpider):
name = "youtubecrawler"
allowed_domains = ["gdata.youtube.com"]
start_urls = ['http://www.gdata.youtube.com/feeds/api/standardfeeds/DE/most_popular?v=2&alt=json']
def parse(self, response):
items []
jsonresponse = json.loads(response)
for video in jsonresponse["feed"]["entry"]:
item = YoutubeItem()
print jsonresponse
print video["media$group"]["yt$videoid"]["$t"]
print video["media$group"]["media$description"]["$t"]
item ["title"] = video["title"]["$t"]
print video["author"][0]["name"]["$t"]
print video["category"][1]["term"]
items.append(item)
return items
I always get following error:
2014-01-05 16:55:21+0100 [youtubecrawler] ERROR: Spider error processing <GET http://gdata.youtube.com/feeds/api/standardfeeds/DE/most_popular?v=2&alt=json>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1201, in mainLoop
self.runUntilCurrent()
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 824, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 382, in callback
self._startRunCallbacks(result)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 490, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 577, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/bxxxx/svn/ba_txxxxx/scrapy/youtube/spiders/test.py", line 15, in parse
jsonresponse = json.loads(response)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
exceptions.TypeError: expected string or buffer
Answer: found two issues in your code:
1. start url is not accessible, I took out the `www` from it
2. changed `json.loads(response)` to `json.loads(response.body_as_unicode())`
this works well for me:
class MySpider(BaseSpider):
name = "youtubecrawler"
allowed_domains = ["gdata.youtube.com"]
start_urls = ['http://gdata.youtube.com/feeds/api/standardfeeds/DE/most_popular?v=2&alt=json']
def parse(self, response):
items = []
jsonresponse = json.loads(response.body_as_unicode())
for video in jsonresponse["feed"]["entry"]:
item = YoutubeItem()
print video["media$group"]["yt$videoid"]["$t"]
print video["media$group"]["media$description"]["$t"]
item ["title"] = video["title"]["$t"]
print video["author"][0]["name"]["$t"]
print video["category"][1]["term"]
items.append(item)
return items
|
Numba error: NotImplementedError: Unable to cast from { i64, i8* }* to { i64, i8* }
Question: I am getting a strange error with numba.
I am using Anacondas, Python 3.3
The function I am trying to autojit is
@autojit
def _generate_broadcasted_forecasts(self):
x = np.array( self.residuals[1:] , dtype=float)
y = np.array( self.sigma[1:-1] , dtype=float)
errors = x/y
self.errors = errors
The data is:
self.residuals
Out[1]:
array([ 0.00027274, 0.06000376, 0.01042219, 0.02850773, -0.01411178,
-0.01929838, 0.00385101, -0.01630044, 0.03715821, 0.02258934,
0.05662874, -0.02359702, -0.01823098, -0.03092986, 0.02994069,
0.01090546, -0.02475619, -0.01020354, -0.00332659, -0.01734819,
0.01957363, -0.02706434, 0.01215692, -0.05122325, -0.02016905,
-0.0472204 , 0.0183388 , 0.00319104, -0.04198954, 0.00586023,
-0.03320624, 0.0061127 , -0.04101338, 0.07630624, -0.04561496,
-0.01602609, 0.03317164, -0.02177255, -0.001892 , -0.01752149,
-0.01062089, -0.00036998, -0.02321696, -0.01139503, -0.04052122,
0.01033072, -0.04154074, 0.00703859, 0.01299577, 0.0532591 ,
0.02145779, 0.06422423, -0.02635143, -0.01230678, -0.00905247,
-0.03167185, 0.02384259, 0.03086425, 0.02310251, -0.003188 ,
0.01928799, -0.02143164, -0.01694362, 0.00274987, -0.03429799,
0.00123984, -0.01234553, -0.01822308, 0.01739987, 0.05260887,
-0.01671929, -0.0451185 , -0.00253769, -0.01643629, 0.0689997 ,
0.07316202, -0.05564215, 0.02830494, 0.02396265, -0.00335834,
-0.00328183, -0.01633152, -0.02944809, -0.01730992, 0.02290413,
0.03344062, -0.03211203, 0.00115551, -0.0348293 , 0.01106866,
-0.00334149, -0.000305 , 0.00499175, -0.00023061, 0.00635803,
-0.01883831, -0.01078026, 0.01491779, 0.04605717, -0.01274995,
-0.00380779, 0.03336405, -0.01263997, 0.02967207, -0.00949215,
-0.0239608 , 0.02311184, -0.03347211, -0.01047334, 0.02570358,
-0.02749113, 0.01718504, -0.00012177, 0.03942462, -0.02854834,
-0.00689199, 0.00769279, 0.01237644, -0.02212167, 0.02312826,
-0.00335928, 0.00626517, 0.0127933 , 0.00980856, 0.02102578,
-0.00291102, 0.02605287, 0.00453684, 0.01697849, -0.01733679,
0.02957533, -0.00981372, 0.01504038, -0.00308469, -0.01067471,
0.02550573, 0.01636283, 0.00386063, 0.01584089, 0.02774164,
0.01026229, -0.01319894, 0.0047792 , 0.01137512, -0.00017363,
-0.0026951 , 0.023888 , -0.0178131 , -0.00043418, 0.00078961,
-0.01046682, -0.01422187, 0.02284845, 0.01530962, -0.00277356,
-0.047021 , -0.0233437 , -0.00700932, -0.00461674, 0.04386189,
0.03214708, 0.02512427, 0.05888554, 0.00946264, -0.01649079,
-0.01824022, 0.00305155, 0.02141179, 0.02040107, 0.01223521,
0.04182406, 0.01200173, -0.00666375, 0.00839121, 0.00601783,
0.00727748, -0.01839253, -0.02627941, 0.00040831, -0.00348844,
0.0396223 , 0.01587524, 0.05635961, 0.00638051, 0.03315842,
-0.02278018, -0.00149056, -0.00028848, -0.09895528, 0.02313064,
0.02065743, -0.00115973, -0.00135562, -0.02609936, 0.00146749,
0.01020923, -0.07006086, 0.04481519, 0.02428593, 0.00513643,
0.00386419, -0.03904007, 0.02584459, 0.02042376, -0.00415313,
0.0250591 , 0.0078504 , 0.01071272, 0.01446379, 0.04678684,
-0.030569 , 0.00499873, -0.00121879, -0.00028605, -0.01341486,
-0.00119668, 0.0102857 , -0.03408491, -0.01151752, 0.02421846,
-0.0126916 , 0.03427147, -0.00672604, 0.00265135, 0.04540966,
-0.05231339, 0.00802635, 0.02506964, 0.00188135, 0.03521239,
-0.01252548, -0.0487149 , -0.01607805, 0.06138833, -0.02267715,
-0.00883121, 0.04540312, -0.02248676, 0.01033092, -0.01845178,
-0.00950717, -0.03646932, 0.05394227, -0.03149327, -0.02139244,
-0.00629822, -0.01885609, -0.00724694, 0.01627761, 0.02120749])
self.sigma
Out[1]:
array([ 0.02647903, 0.02580863, 0.02854044, 0.02781347, 0.02778348,
0.02719822, 0.02682252, 0.02614003, 0.02575487, 0.02647783,
0.02629712, 0.0285969 , 0.02826486, 0.02776125, 0.0278659 ,
0.02790585, 0.02723722, 0.02708099, 0.02646327, 0.02580474,
0.02548335, 0.025272 , 0.02542612, 0.0249857 , 0.02698342,
0.02665878, 0.02803867, 0.02755763, 0.02681504, 0.02775527,
0.02702024, 0.02733631, 0.02663591, 0.0275261 , 0.0317507 ,
0.03234794, 0.03145869, 0.03131707, 0.03068293, 0.02970747,
0.02906351, 0.02830046, 0.02749342, 0.02724532, 0.02663881,
0.02749216, 0.02684456, 0.02774718, 0.02702682, 0.02647462,
0.02842004, 0.02801799, 0.03078638, 0.03037759, 0.02954908,
0.0287226 , 0.02876979, 0.02843258, 0.02846502, 0.02812427,
0.02733939, 0.026951 , 0.02667852, 0.02626748, 0.02562064,
0.02616582, 0.02552095, 0.02507717, 0.02485235, 0.02461849,
0.0268124 , 0.02638272, 0.02762759, 0.02687628, 0.02643228,
0.03003171, 0.0333827 , 0.03453727, 0.03389183, 0.03312942,
0.03199099, 0.03093019, 0.03015629, 0.02994792, 0.02927847,
0.02885815, 0.0289911 , 0.02903535, 0.0281757 , 0.02846391,
0.02775531, 0.02699883, 0.02628887, 0.0256573 , 0.02505049,
0.02453268, 0.02438172, 0.02399769, 0.02375888, 0.02547854,
0.02504846, 0.02450438, 0.02512236, 0.02471973, 0.02508061,
0.02461088, 0.02467567, 0.02469342, 0.02529554, 0.02482779,
0.02495733, 0.02516796, 0.02489793, 0.02435106, 0.02542535,
0.02564393, 0.02508549, 0.02458393, 0.02422082, 0.02423858,
0.02430145, 0.0238144 , 0.02339728, 0.02315016, 0.02285179,
0.02295964, 0.02258121, 0.02297639, 0.02260993, 0.02257341,
0.02255411, 0.02316487, 0.02286531, 0.0227356 , 0.02237744,
0.0221682 , 0.02258031, 0.02252393, 0.02219001, 0.02215312,
0.02269849, 0.02245043, 0.02230218, 0.02199653, 0.02184009,
0.02154876, 0.02129164, 0.02171611, 0.02180259, 0.02151474,
0.02125285, 0.02114355, 0.02115455, 0.02153887, 0.02154778,
0.02129126, 0.02352853, 0.02367564, 0.0232808 , 0.02288927,
0.02455152, 0.02508442, 0.02515797, 0.02789379, 0.0271991 ,
0.0267295 , 0.02635739, 0.02570532, 0.02554735, 0.02536272,
0.02492956, 0.02611233, 0.02561108, 0.02505219, 0.02456478,
0.02408222, 0.0236572 , 0.02357261, 0.02386815, 0.0234048 ,
0.02299286, 0.02427669, 0.0240433 , 0.02672357, 0.02607349,
0.02649293, 0.02631903, 0.02566302, 0.02505579, 0.03301026,
0.03228805, 0.03153822, 0.03050111, 0.02953701, 0.02922853,
0.02835562, 0.02763884, 0.03111266, 0.03172814, 0.03115373,
0.03016414, 0.02923511, 0.02967298, 0.02934095, 0.02882213,
0.0279922 , 0.0277788 , 0.02706721, 0.02646064, 0.02599358,
0.02743368, 0.02755225, 0.02682387, 0.02612851, 0.0254851 ,
0.02507182, 0.02451255, 0.02410654, 0.02482254, 0.02441787,
0.02451516, 0.02416618, 0.0248875 , 0.02438786, 0.02388931,
0.02553014, 0.02754089, 0.02685012, 0.02674541, 0.026058 ,
0.02661146, 0.02608169, 0.02767567, 0.02715383, 0.0297839 ,
0.02931113, 0.02849885, 0.02948042, 0.02902629, 0.02826068,
0.02776472, 0.02708077, 0.0275969 , 0.02942746, 0.02939432,
0.02890609, 0.02808997, 0.02762202, 0.02691396, 0.02646187,
0.02622503])
The full error is:
Traceback (most recent call last):
File "C:\Anaconda\envs\p33\lib\site-packages\IPython\core\interactiveshell.py", line 2732, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-d063d30a36f8>", line 1, in <module>
execfile('C:\\Users\\Jon\\workspace\\FundsAnalysis\\src\\examples\\ar-garch\\ar_garch3.py')
File "C:\eclipse_kepler\plugins\org.python.pydev_2.7.5.2013052819\pysrc\_pydev_execfile.py", line 38, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script
File "C:\Users\Jon\workspace\FundsAnalysis\src\examples\ar-garch\ar_garch3.py", line 225, in <module>
ar_garch.evaluate()
File "C:\Users\Jon\workspace\FundsAnalysis\src\examples\ar-garch\ar_garch3.py", line 158, in evaluate
self._generate_broadcasted_forecasts()
File "numbawrapper.pyx", line 287, in numba.numbawrapper.BoundSpecializingWrapper.__call__ (numba\numbawrapper.c:5041)
File "numbawrapper.pyx", line 189, in numba.numbawrapper._NumbaSpecializingWrapper.__call__ (numba\numbawrapper.c:3726)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\wrapping\compiler.py", line 68, in compile_from_args
return self.compile(signature)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\wrapping\compiler.py", line 83, in compile
compiled_function = dec(self.py_func)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\decorators.py", line 222, in _jit_decorator
env, func, argtys, restype=return_type, nopython=nopython, **kwargs)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\decorators.py", line 133, in compile_function
func_env = pipeline.compile2(env, func, restype, argtypes, **kwds)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\pipeline.py", line 134, in compile2
post_ast = pipeline(func_ast, env)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\pipeline.py", line 181, in __call__
ast = self.transform(ast, env)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\pipeline.py", line 602, in transform
ast = stage(ast, env)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\pipeline.py", line 587, in _stage
return _check_stage_object(stage_obj)(ast, env)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\pipeline.py", line 184, in __call__
ast = self.transform(ast, env)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\pipeline.py", line 499, in transform
func_env.translator.translate()
File "C:\Anaconda\envs\p33\lib\site-packages\numba\codegen\translate.py", line 314, in translate
self.visit(node)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\codegen\translate.py", line 128, in visit
return fn(node)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\codegen\translate.py", line 554, in visit_Assign
decref=decref, incref=incref)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\codegen\translate.py", line 566, in generate_assign_stack
lvalue = self.caster.cast(lvalue, ltarget.type.pointee)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\llvm_types.py", line 91, in cast
return self.build_cast(self.builder, lvalue, dst_ltype, *args, **kws)
File "C:\Anaconda\envs\p33\lib\site-packages\numba\llvm_types.py", line 191, in build_cast
(str(lty1), str(lty2)))
NotImplementedError: Unable to cast from { i64, i8* }* to { i64, i8* }.
Setting a breakpoit in
File "C:\Anaconda\envs\p33\lib\site-packages\numba\llvm_types.py", line 191, in build_cast
line 190, I look a few lines before and find the error is triggered because
lkind1==14
lkind2==12
Unfortunately, I do not know enough about numba to understand what that means.
For completeness, the function where the error occurs is:
@classmethod
def build_cast(cls, builder, lval1, lty2, *args, **kws):
ret_val = lval1
lty1 = lval1.type
lkind1 = lty1.kind
lkind2 = lty2.kind
# This looks like the wrong place to enforce this
# TODO: We need to pass in the numba types instead
# if lc.TYPE_INTEGER in (lkind1, lkind2) and 'unsigned' not in kws:
# # Be strict about having `unsigned` define when
# # we have integer types
# raise ValueError("Unknown signedness for integer type",
# '%s -> %s' % (lty1, lty2), args, kws)
if lkind1 == lkind2:
if lkind1 in cls.CAST_MAP:
ret_val = cls.CAST_MAP[lkind1](cls, builder, lval1, lty2,
*args, **kws)
else:
raise NotImplementedError(lkind1)
else:
map_index = (lkind1, lkind2)
if map_index in cls.CAST_MAP:
ret_val = cls.CAST_MAP[map_index](cls, builder, lval1, lty2,
*args, **kws)
else:
raise NotImplementedError('Unable to cast from %s to %s.' %
(str(lty1), str(lty2)))
return ret_val
What am I doing wrong? I tried making a code snippet to post here, but cannot
reproduce the error. i.e. the below works on my machine:
from numba import autojit
import numpy as np
@autojit
def numba1():
return np.array( [1,2,3] )
@autojit
def numba2():
x = np.array([1.0,2.0,3.0,4.0])
y = np.array([1.0,2.0,3.0,4,5.0])
z = x[1:] / y[1:-1]
return np.sqrt( z )
print( numba1() )
print( numba2() )
Answer: I found a fix from the **Classes** section of [This Examples
Page](http://numba.pydata.org/numba-doc/0.11/examples.html)
What I had to do was declare self.errors in **init**(...)
i.e.
def __init__( self ):
self.errors = np.ndarray(0)
|
What does it mean to put a dot in a Python class argument?
Question: In Python, I saw a class definition as the following:
from protorpc import messages
# Create the request string containing the user's name
class HelloRequest(messages.Message):
my_name = messages.StringField(1, required=True)
What does `messages.Message` mean?
Answer:
from protorpc import messages
class HelloRequest(messages.Message):
Is just another way of spelling:
from protorpc.messages import Message
class HelloRequest(Message):
Or even...
import protorpc
class HelloRequest(protorpc.messages.Message):
That is, `HelloRequest` derives from the `Message` `class` in the `messages`
_submodule_ of the `protorpc`
[package](http://docs.python.org/2/tutorial/modules.html#packages).
|
Python - Time delta from string and now()
Question: I have spent some time trying to figure out how to get a time delta between
time values. The only issue is that one of the times was stored in a file. So
I have one string which is in essence `str(datetime.datetime.now())` and
`datetime.datetime.now()`.
Specifically, I am having issues getting a delta because one of the objects is
a datetime object and the other is a string.
I think the answer is that I need to get the string back in a datetime object
for the delta to work.
I have looked at some of the other Stack Overflow questions relating to this
including the following:
[Python - Date & Time Comparison using timestamps,
timedelta](http://stackoverflow.com/questions/12131766/python-date-time-
comparison-using-timestamps-timedelta)
[Comparing a time delta in
python](http://stackoverflow.com/questions/2591845/comparing-a-time-delta-in-
python)
[Convert string into datetime.time
object](http://stackoverflow.com/questions/14295673/convert-string-into-
datetime-time-object)
[Converting string into
datetime](http://stackoverflow.com/questions/466345/converting-string-into-
datetime)
Example code is as follows:
f = open('date.txt', 'r+')
line = f.readline()
date = line[:26]
now = datetime.datetime.now()
then = time.strptime(date)
delta = now - then # This does not work
Can anyone tell me where I am going wrong?
For reference, the first 26 characters are acquired from the first line of the
file because this is how I am storing time e.g.
f.write(str(datetime.datetime.now())
Which would write the following: 2014-01-05 13:09:42.348000
Answer: `time.strptime` returns a struct_time. `datetime.datetime.now()` returns a
`datetime` object. The two can not be subtracted directly.
Instead of `time.strptime` you could use `datetime.datetime.strptime`, which
returns a `datetime` object. Then you could subtract `now` and `then`.
For example,
import datetime as DT
now = DT.datetime.now()
then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
delta = now - then
print(delta)
# 3 days, 8:17:14.428035
* * *
By the way, you need to supply a date format string to `time.strptime` or
`DT.datetime.strptime`.
time.strptime(date)
should have raised a ValueError.
* * *
It looks like your date string is 26 characters long. That might mean you have
a date string like `'Fri, 10 Jun 2011 11:04:17 '`.
If that is true, you may want to parse it like this:
then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
print(then)
# 2011-06-10 11:04:17
There is a table describing the available directives (like `%Y`, `%m`, etc.)
[here](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-
behavior).
|
Syntax error while parsing Json data in javascript
Question: I am returning this in my views.py through a dictionary
{"injured_json": [{"pk": 24, "model": "appvisual.injured_count", "fields": {"Y_2010": 75445, "Y_2008": 70251, "Y_2009": 70504, "Y_2004": 57283, "Y_2005": 62006, "Y_2006": 64342, "Y_2007": 71099, "State_UT": "Tamil Nadu", "Y_2003": 55242, "Y_2011": 74245}}], "total_json": [{"pk": 23, "model": "appvisual.total_accident", "fields": {"Y_2010": 64996, "Y_2008": 60409, "Y_2009": 60794, "Y_2004": 52508, "Y_2005": 53866, "Y_2006": 55145, "Y_2007": 59140, "State_UT": "Tamil Nadu", "Y_2003": 51025, "Y_2011": 65873}}], "killed_json": [{"pk": 24, "model": "appvisual.killed_count", "fields": {"Y_2010": 75445, "Y_2008": 70251, "Y_2009": 70504, "Y_2004": 57283, "Y_2005": 62006, "Y_2006": 64342, "Y_2007": 71099, "State_UT": "Tamil Nadu", "Y_2003": 55242, "Y_2011": 74245}}, {"pk": 60, "model": "appvisual.killed_count", "fields": {"Y_2010": 15409, "Y_2008": 12784, "Y_2009": 13746, "Y_2004": 9507, "Y_2005": 9758, "Y_2006": 11009, "Y_2007": 12036, "State_UT": "Tamil Nadu", "Y_2003": 9275, "Y_2011": 15422}}]}
while retrieving the about json in javascript, the json data gets enclosed
with ( and ) as follows :
({injured_json:[{pk:24, model:"appvisual.injured_count", fields:{Y_2010:75445, Y_2008:70251, Y_2009:70504, Y_2004:57283, Y_2005:62006, Y_2006:64342, Y_2007:71099, State_UT:"Tamil Nadu", Y_2003:55242, Y_2011:74245}}], total_json:[{pk:23, model:"appvisual.total_accident", fields:{Y_2010:64996, Y_2008:60409, Y_2009:60794, Y_2004:52508, Y_2005:53866, Y_2006:55145, Y_2007:59140, State_UT:"Tamil Nadu", Y_2003:51025, Y_2011:65873}}], killed_json:[{pk:24, model:"appvisual.killed_count", fields:{Y_2010:75445, Y_2008:70251, Y_2009:70504, Y_2004:57283, Y_2005:62006, Y_2006:64342, Y_2007:71099, State_UT:"Tamil Nadu", Y_2003:55242, Y_2011:74245}}, {pk:60, model:"appvisual.killed_count", fields:{Y_2010:15409, Y_2008:12784, Y_2009:13746, Y_2004:9507, Y_2005:9758, Y_2006:11009, Y_2007:12036, State_UT:"Tamil Nadu", Y_2003:9275, Y_2011:15422}}]})
Because of additionally added "**(** " and "**)** " i could not parse the json
dta in javascript. How can i eliminate this syntax error.
My Views.py
def get_details(request):
import pdb;pdb.set_trace();
total_details = total_accident.objects.filter(State_UT='Tamil Nadu')
total_details = serializers.serialize('python', total_details)
killed_details = Killed_Count.objects.filter(State_UT='Tamil Nadu')
killed_details = serializers.serialize('python', killed_details)
injured_details = Injured_Count.objects.filter(State_UT='Tamil Nadu')
injured_details = serializers.serialize('python', injured_details)
page_data = {
"total_json" : total_details,
"killed_json" : killed_details,
"injured_json" : injured_details,
}
page_data= simplejson.dumps(page_data)
print page_data
return render_to_response('dvslzer.html', {'page_data':page_data})
My Script:
function test() {
var dataRows = {{page_data}};
console.log(dataRows.toSource());
var data=JSON.parse(dataRows.total_accident); // throws syntax error
console.log(data[0].pk);
};
Is there any solution to get rid of this syntax error??
Answer: Piecing together what we managed to establish in comments above, this line:
var data=JSON.parse(dataRows.total_accident);
...should actually be:
var data = dataRows.total_json;
Because firstly there is no property in the object called `total_accident`,
and secondly it doesn't make sense to try to use `JSON.parse()` because you're
not actually dealing with JSON at that point.
(The JS isn't really dealing with JSON at all, because the server-side
`{{page_data}}` outputs the JSON directly into the page source, so by the time
the browser sees it it just appears as an object literal in your JS code. If
it was JSON you'd need to use `JSON.parse()` on `dataRows` before you could
start accessing properties with dot notation.)
|
Urllib2.urlopen python chinese in windows
Question: I'm making a little scrip in python. The objective is to make a request to a
page that returns a Json file and work with the information. The problem is
that I need to work with chinese words in the urls. When I make the request
with (for example):
f = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=江苏省苏州市中国新加坡工业园区独墅湖科教创新区仁爱路111号&sensor=false")
In ubuntu I don't have problems and all is great, and give me the crrect json
file. But when I try in Windows the resquest fails (said me that the url
didn't exist). There is a problem with chinese caracters in windows with
urllib2?
The version of windows is 7, ubuntu 12.4. And I'm using python 2.7.
Thanks!
Marcos
Answer: You should urlencode the query:
# -*- coding: utf-8 -*-
from urllib import urlencode
from urllib2 import urlopen
params = dict(address=u"我不知道中国人。", sensor="false")
query = urlencode([(k, v.encode('utf-8') if isinstance(v, unicode) else v)
for k, v in params.items()])
r = urlopen("http://maps.googleapis.com/maps/api/geocode/json?" + query)
# ...
|
Module name conflict in Python, how to resolve?
Question: I came across a file in our project, called - wait for it - celery.py. Yes,
and celery.py imports from the installed celery module (see
<http://www.celeryproject.org/>) which is not an issue because the project's
celery.py uses
from __future__ import absolute_import
before importing from the installed celery module. Now, the problem comes from
djcelery (django-celery) which also would like to import from celery (the
installed one, not the project celery.py). This is where the clash comes
because djcelery encounters the project's celery.py before it encounters the
installed celery. How can I resolve this?
Answer: The easiest and most sane way to do it is to refactor you project and change
the name of the file.
There are probably some way strange way around this, but I would hardly
consider that worth it, as it would most likely complicate your code, and make
it prone to errors.
|
How to modify an html tree in python?
Question: Suppose there is some variable fragment html code
<p>
<span class="code"> string 1 </ span>
<span class="code"> string 2 </ span>
<span class="code"> string 3 </ span>
</ p>
<p>
<span class="any"> Some text </ span>
</ p>
I need to modify the contents of all the tags with the class code `<span>`
skipping content through some function, such as `foo`, which returns the
contents of the modified tag `<span>`. Ultimately, I should get a new piece of
html document like this:
<p>
<span class="code"> modify string 1 </ span>
<span class="code"> modify string 2 </ span>
<span class="code"> modify string 3 </ span>
</ p>
<p>
<span class="any"> Some text </ span>
</ p>
I have been suggested that the search for the specific html nodes can be easy
using the python library **BeautifulSoup4**. How to perform a modification of
content `<span class="code">` and save a new version as a new file ? I guess
to find you need to use `soup.find_all ('span', class = re.compile ("code"))`,
only this function returns a `list` ( copy) of the sample objects ,
modification of which does not change the contents of soup. How do I solve
this problem?
Answer: `</ span>` is invalid HTML and not even a web browser's lenient parser will
parse it properly.
Once you fix your HTML, you can use `.replaceWith()`:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''
<p>
<span class="code"> string 1 </span>
<span class="code"> string 2 </span>
<span class="code"> string 3 </span>
</p>
<p>
<span class="any"> Some text </span>
</p>
''', 'html5lib')
for span in soup.find_all('span', class_='code'):
span.string.replaceWith('modified ' + span.string)
|
How to run test suite in python setup.py
Question: I am trying to setup a Python package using `setup.py`. My directory structure
looks like this:
setup.py
baxter/
__init__.py
baxter.py
tests/
test_baxter.py
Here is `setup.py`:
from setuptools import setup, find_packages
setup(name='baxter',
version='1.0',
packages=find_packages()
)
I first do a `python setup.py build`. When I then run `python setup.py test` I
immediately get this result:
running test
and nothing else. The unit tests have not run since the tests take at least 15
seconds to finish and the message `running test` comes back right away.
So it appears that `python setup.py test` is not finding the unit tests. What
am I doing wrong?
Answer: Pretty simple, add the following to your setup() call:
test_suite="tests",
|
Matching something or the end of the content
Question: How can I ask to look for a word followed by `%`, this special character being
optional if the word is at the end of the text to analyze ?
The following code prints only `showme` but I would also like to have `metoo`.
#! /usr/bin/env python3
import re
p = re.compile(r"(?<!@)\w+(?=%)")
for m in p.finditer(r"@hideme showme% metoo"):
print(m.group())
Answer: Simple look for \% OR $ (the end of text char).
` p = re.compile(r"(?<!@)\w+(?=%|$)") `
|
Auto-indenting graphviz .dot file
Question: I am working on a long and complex architectural graph. The document
indentation mixes tabs, spaces and indentation levels, which drives me crazy.
**Is there a simple way to automatically indent graphviz`.dot` files in Linux
environment?**
A pure command line tool would be best, but plugins to popular editors like
vim would be a good solution too.
**Update** :
The vim indentation has a bug with `:` in node names in edges. For example,
`server_a:event -> log_server;` causes the next line to be further indented,
presumably because the `:` is parsed as a block declaration (see comments on
[Harry Pehkonen's answer](http://stackoverflow.com/a/20961629/51197)). Quoting
the node name (e.g. `"server_a":event -> log_server;`) solves this issue:
#!/usr/bin/python3
import re
dot=open('components.dot').read()
reg=re.compile("(\s)(\S+)(\:.*\-\>)")
print(reg.sub(r'\1"\2"\3', dot))
Answer: Vim has dot syntax knowledge out of the box, and seems to re-indent dot files
for me.
I removed all indentation, went to the top of the file, and did =G
Your global tab-related values determine whether to use tabs/spaces, how many,
etc.
If you want, you can create a script with:
> vim -W reIndentAndSave whatever.dot
Edit your dot file by re-indenting from top with
gg=G
...Save
:x
Then, for each file you want to re-indent via the script that you just
recorded,
> vim -s reIndentAndSave somegraph.dot
|
subprocess.call() for shell program which write a file
Question: I need to execute a shell script using python. Output of shell program is a
text file. No inputs to the script. Help me to resolve this.
def invokescript( shfile ):
s=subprocess.Popen(["./Script1.sh"],stderr=subprocess.PIPE,stdin=subprocess.PIPE);
return;
invokescript("Script1.sh");
On using above code., I receive the following error.
Traceback (most recent call last):
File "./test4.py", line 12, in <module>
invokescript("Script1.sh");
File "./test4.py", line 8, in invokescript
s=subprocess.Popen(["./Script1.sh"],stderr=subprocess.PIPE,stdin=subprocess.PIPE);
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error
Thanks in advance...
Answer: Try this:
import shlex
def invokescript(shfile):
return subprocess.Popen(
shlex.split(shfile),
stderr=subprocess.PIPE,
stdin=subprocess.PIPE
)
invokescript("Script1.sh");
And add `#!/usr/bin/env bash` to your bash file of course.
|
Finding full pathname in a Python trace
Question: When turning on Python trace, the filename is provided, along with the module
and sourcecode.
Is it possible to show the file path as well as the filename?
I am using:
-m trace -t
In the example below there are two different **account_bank_statement.py**
files in different directories.
17 --- modulename: account_bank_statement, funcname: button_create_invoice
18 account_bank_statement.py(329): if context is None:
19 account_bank_statement.py(333): currency = self.read(cr, uid, ids, ['currency'])[0]['currency']
20 --- modulename: account_bank_statement, funcname: _currency
21 account_bank_statement.py(107): res = {}
22 account_bank_statement.py(108): res_currency_obj = self.pool.get('res.currency')
This is a duplicate of this (unanswered) question: [Tracing fIle path and line
number](http://stackoverflow.com/questions/14638041/tracing-file-path-and-
line-number#comment31443029_14638041)
An answer that would involve hacking the trace module would work for me.
**EDIT**
A solution, based on Alfe's answer below. It **is** intrusive, but is does
what I an looking for. I have left the modulename and also added the pathname.
I am working with OpenERP and there is often the same modulename defined in
multiple locations.
I have not posted this an answer as it is really a refinement of Alfe's
solution, so if you like please up vote his answer.
(1) Copy trace.py to your local path (2) Edit as below:
171 def modname(path):
172 """Return a plausible module name for the patch."""
173
174 base = os.path.basename(path)
175 filename, ext = os.path.splitext(base)
176 return filename
593 def globaltrace_lt(self, frame, why, arg):
594 """Handler for call events.
595
596 If the code block being entered is to be ignored, returns `None',
597 else returns self.localtrace.
598 """
599 if why == 'call':
600 code = frame.f_code
601 filename = frame.f_globals.get('__file__', None)
602 if filename:
603 # XXX modname() doesn't work right for packages, so
604 # the ignore support won't work right for packages
605 #modulename = fullmodname(filename)
606 modfile, ext = os.path.splitext(filename)
607 modulename = fullmodname(modfile)
608 if modulename is not None:
609 ignore_it = self.ignore.names(modfile, modulename)
610 if not ignore_it:
611 if self.trace:
612 print (" --- modulename: %s, funcname: %s, filename: %s"
613 % (modulename, code.co_name, filename))
614 return self.localtrace
615 else:
616 return None
**Sample Output**
Note there are 2 different module names, contained in different directories,
with the same filenames. This modified _trace.py_ * handles this.
2 --- modulename: register_accounting, funcname: button_create_invoice, filename: /home/sean/unifield/utp729/unifield-wm/register_accounting/account_bank_statement.pyc
3 account_bank_statement.py(329): if context is None:
4 account_bank_statement.py(333): currency = self.read(cr, uid, ids, ['currency'])[0]['currency']
5 --- modulename: account, funcname: _currency, filename: /home/sean/unifield/utp729/unifield-addons/account/account_bank_statement.pyc
6 account_bank_statement.py(107): res = {}
7 account_bank_statement.py(108): res_currency_obj = self.pool.get('res.currency')
Answer: If patching of `trace.py` is allowed, this task is easy.
Copy `trace.py` (from `/usr/lib/python2.7/` in my case) to a local directory
(e. g. the current one), then patch the function `modname(path)` in that local
copy. That function strips the directories off the module paths, so the
package information is lost. The original contains the line
filename, ext = os.path.splitext(base)
which can be changed to
filename, ext = os.path.splitext(path)
in order to _not_ strip the directory.
The output of a call like `./trace.py --trace t.py` then looks like this:
--- modulename: t, funcname: <module>
t.py(3): import mypackage.mymodule
--- modulename: mypackage/__init__, funcname: <module>
__init__.py(1): --- modulename: mypackage/mymodule, funcname: <module>
mymodule.py(1): print 42
42
t.py(5): print 5
5
--- modulename: ./trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)
I'm tracing a test script called `t.py` which imports a module `mymodule.py`
which is in a package `mypackage` (so the filename is
`./mypackage/mymodule.py`). That module only prints 42, the test script itself
prints 5.
Does this solve your issue?
EDIT:
Upon second view, I propose a different patch.
In function `globaltrace_lt()` the modulename is derived by calling
`modname()`; patch this to call `fullmodname()`:
modulename = fullmodname(filename)
I think this might be a less intrusive patch.
|
python: how to cast a list to c_byte array
Question: I have a c function in dll.
It has a interface like `int dcm(char inmsg[], int length);`
Now I have a list like(the number of member are more than 1000 sometimes)
a = [0x41,0x00,0x00,0xC8,0x08,0x01,0x03,0x00,0x00,0x02,0x10,0x00,0x66,0x62,0x05,0x00,0x06,0x00,0x57,0x02,0x01,0xBF,0xFF,0x00,0xBF,0x9A,0x00,0x05,0x80,0x10,0x32,0x00,0x07,0x1F,0x00,0x00,0x05,0x00,0xD1,0x01,0x01,0xBF,0x04,0x00,0x03,0xBF,0x04,0x00,0x21,0x64,0x00,0x00,0x0A,0xBF,0xFF,0x00,0xBF,0xFF,0x00,0xBF,0xFF,0x00,0xBF,0xF3,0x00]
I want to cast the list to `c_byte` array and pass it as the first parameter
for the function `dcm`.
How to cast it to c_byte array?
Answer: You can do this -
import ctypes
a = [0x41,0x00,0x00,0xC8,0x08,0x01,0x03,0x00,0x00,0x02,0x10,0x00,0x66,0x62,0x05,0x00,0x06,0x00,0x57,0x02,0x01,0xBF,0xFF,0x00,0xBF,0x9A,0x00,0x05,0x80,0x10,0x32,0x00,0x07,0x1F,0x00,0x00,0x05,0x00,0xD1,0x01,0x01,0xBF,0x04,0x00,0x03,0xBF,0x04,0x00,0x21,0x64,0x00,0x00,0x0A,0xBF,0xFF,0x00,0xBF,0xFF,0x00,0xBF,0xFF,0x00,0xBF,0xF3,0x00]
arr = (ctypes.c_byte * len(a))(*a)
Then you can pass `arr` to your C function. More details are [in the
doc](http://docs.python.org/2/library/ctypes.html#arrays).
|
manage.py help has different python path in virtualenv
Question: I have a problem in virtualenv that a wrong python path is imported.
The reason is that by running the command:
`manage.py help
--pythonpath=/home/robert/Vadain/vadain.webservice.curtainconfig/`
The result is right, but when I run `manage.py help` then I missing some
imports.
I searched on the internet, but nothing is helped. The last change I have done
is at the end of the file virtualenvs/{account}/bin/activate added the
following text:
export PYTHONPATH=/home/robert/Vadain/vadain.webservice.curtainconfig
But this not solving the problem, somebody else's suggestion to fix this
problem?
Answer: Don't see any problem there. You could also insert something like:
import sys
sys.path.append('/home/robert/Vadain/vadain.webservice.curtainconfig/')
into your manage.py
Or you write a `setup.py` for your package and install it into your virtualenv
(which would be the preferred way (`pip install -e`)
|
How to sort Counter by value? - python
Question: Other than doing list comprehensions of reversed list comprehension, is there
a pythonic way to sort Counter by value? If so, it is faster than this:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x)
['a', 'b', 'c']
>>> sorted(x.items())
[('a', 5), ('b', 3), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()])]
[('b', 3), ('a', 5), ('c', 7)]
>>> [(l,k) for k,l in sorted([(j,i) for i,j in x.items()], reverse=True)]
[('c', 7), ('a', 5), ('b', 3)
Answer: Use the [`Counter.most_common()`
method](http://docs.python.org/2/library/collections.html#collections.Counter.most_common),
it'll sort the items _for you_ :
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
It'll do so in the most efficient manner possible; if you ask for a Top N
instead of all values, a `heapq` is used instead of a straight sort:
>>> x.most_common(1)
[('c', 7)]
Outside of counters, sorting can always be adjusted based on a `key` function;
`.sort()` and `sorted()` both take callable that lets you specify a value on
which to sort the input sequence; `sorted(x, key=x.get, reverse=True)` would
give you the same sorting as `x.most_common()`, but only return the keys, for
example:
>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
or you can sort on only the value given `(key, value)` pairs:
>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
See the [Python sorting howto](http://docs.python.org/2/howto/sorting.html)
for more information.
|
An elegant way to use a resource in Python?
Question: I want to find an elegant way to do the following:
try:
with some_resource:
# got it
do_something()
except ResourceUnavailableError:
# didn't get it
do_something_else()
This:
1. tries to get a resource
2. on success, it does something, and then releases the resource correctly
3. on failure, it does something else
Although not many lines of code, I find that if I have to keep writing this in
many different places, it's not very elegant.
I almost wish I could write something as follows (I know this is not real
Python code):
with some_resource:
# got it
do_something()
# an optional else
else:
# didn't get it
do_something_else()
Does anyone know if it's possible to write something along those lines in
Python? Thanks!!
Answer: No, `with` has no `else` block. But you can write your own context manager
that handles the `else` part:
from contextlib import contextmanager
@contextmanager
def handle_unavailable(resource, exception, exception_handler):
try:
with resource:
yield resource
except exception:
exception_handler()
and use it like this everywhere as:
with handle_unavailable(some_resource, ResourceUnavailableError, do_something_else):
do_something()
So if `ResourceUnavailableError` is raised in the `with` block,
`do_something_else` is called for you.
This makes use of the [`@contextlib.contextmanager()`
decorator](http://docs.python.org/2/library/contextlib.html#contextlib.contextmanager),
which makes writing your own context managers almost trivial.
|
Creating a syntax highlighter in python(PyQt4)
Question: I've been searching the internet about the **Syntax highlighting** of a
particular file in a text editor and i read about **Lexers and Yacc**. i'm
quite confuse about the concepts on syntax highlighting.
I've created a simple text editor using **PyQt4** and i want it to enable
syntax highlighting of programming languages such as HTML,CSS,Python,C/C++.
But i've no clue on how to start implementing this and where to start. Please
someone point me to the right direction and pliz clear my doubts on syntax
highlighting. please.
Answer: If you want to make your life easy, use
[QScintilla](http://pyqt.sourceforge.net/Docs/QScintilla2/) \- it does
everything you need and more straight out of the box.
QScintilla is included with the PyQt binary installers for Windows (which can
be found [here](http://www.riverbankcomputing.com/software/pyqt/download)),
and almost all Linux distros will have QScintilla packages in their
repositories. Alternatively, the QScintilla source code can be found
[here](http://www.riverbankcomputing.com/software/qscintilla/download).
And here's a minimal QScintilla example that shows how easy it is to get
started:
import sys, os
from PyQt4 import QtGui, Qsci
class Window(Qsci.QsciScintilla):
def __init__(self):
Qsci.QsciScintilla.__init__(self)
self.setLexer(Qsci.QsciLexerPython(self))
self.setText(open(os.path.abspath(__file__)).read())
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 500, 500)
window.show()
sys.exit(app.exec_())
|
Paramiko: ssh.exec_command to collect output says open channel in response
Question: I have python script with paramiko and ssh somewhat as below
import paramiko
# setup ssh connection this works. no problem.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn = ssh.connect(MACHINEIP, username=ROOTUSER, password=ROOTUSER_PASSWORD, port=22)
# This first ssh exec works perfect.
(sshin1, sshout1, ssherr1) = ssh.exec_command(cmd1)
# When I print the output of 2nd and 3rd ssh exec, I get output saying of channel open
(sshin2, sshout2, ssherr2) = ssh.exec_command(cmd2)
print sshout2
(sshin3, sshout3, ssherr3) = ssh.exec_command(cmd3)
print sshout3
Channel open messages in output when exec_command is used more than once to
collect output:
<paramiko.ChannelFile from <paramiko.Channel 2 (open) window=2097152
-> <paramiko.Transport at 0x1d42bd0L (cipher aes128-ctr, 128 bits)
(active; 1 open channel(s))>>>
<paramiko.ChannelFile from <paramiko.Channel 6 (open) window=2097152
-> <paramiko.Transport at 0x1d42bd0L (cipher aes128-ctr, 128 bits)
(active; 2 open channel(s))>>>
**How can I close this open channel?** Or any solution on this? I am using
python 2.7.
Answer: Should have used as `sshout.read` and rather I used `sshout` only while
printing.
|
/usr/lib/python2.7/subprocess.py OSError: [Errno 2] No such file or directory
Question: I'm trying to use MEGAM with NLTK.
This is my code:
import nltk
import os
megam_path = os.path.expanduser("~/nltk_data/megam_i686.opt")
nltk.config_megam(megam_path)
me_classifier = MaxentClassifier.train(train_feats, algorithm='megam')
print me_classifier.show_most_informative_features(n=4)
print("accuracy of Maxent Classifier : ", accuracy(me_classifier, test_feats))
When running the file the output is:
[Found /home/ubuntu/nltk_data/megam_i686.opt: /home/ubuntu/nltk_data/megam_i686. opt]
Traceback (most recent call last):
File "./classifying.py", line 494, in <module>
me_classifier = MaxentClassifier.train(train_feats, algorithm='megam')
File "/usr/local/lib/python2.7/dist- packages/nltk/classify/maxent.py", line 31 9, in train
gaussian_prior_sigma, **cutoffs)
File "/usr/local/lib/python2.7/dist-
packages/nltk/classify/maxent.py", line 15 22, in train_maxent_classifier_with_megam
stdout = call_megam(options)
File "/usr/local/lib/python2.7/dist- packages/nltk/classify/megam.py", line 167 , in call_megam
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
But the file subprocess.py exists.
Any hints or suggestions?
Answer: It is not about `subprocess.py` file. `subprocess.Popen()` starts a
subprocess. Check that `cmd` is in `$PATH`. You probably need to install some
command-line utility to use `MaxentClassifier`.
|
Dealing with Unicode range in Python
Question: I am trying to test if a given string is within the Katakana range or not.
I tried the solution asked here : [Python and Unicode Blocks for
regex](http://stackoverflow.com/questions/3145232/python-and-unicode-blocks-
for-regex). But still, my output is "None". What am i missing here ?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
print re.search(u'[\u30A0-\u30FF]', u'カタカ')
Answer: Your problem is that you're using Windows. You specify that the source file is
UTF-8, but Windows doesn't use UTF-8 - it uses various code pages, depending
on the language version and settings in Windows itself.
Many editors will have a way to override the Windows code page and save a file
as UTF-8. Notepad for example has an `Encoding` list on the Save As dialog.
|
How do I get warnings.warn to issue a warning and not ignore the line?
Question: I'm trying to raise a `DeprecationWarning`, with a code snippet based on the
example shown in the docs.
<http://docs.python.org/2/library/warnings.html#warnings.warn>
Official
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
Mine
import warnings
warnings.warn("This is a warnings.", DeprecationWarning, stacklevel=2) is None # returns True
I've tried removing the stacklevel argument, setting it to negative, 0, 2 and
20000. The warning is always silently swallowed. It doesn't issue a warning or
raise an exception. It just ignores the line and returns `None`. The docs
doesn't mention the criteria for ignoring. Giving a message, makes
warnings.warn correctly issue a `Userwarning.`
What can be causing this and how do I get warn to actually warn?
Answer: From the docs:
> By default, Python installs several warning filters, which can be overridden
> by the command-line options passed to -W and calls to filterwarnings().
>
> * DeprecationWarning and PendingDeprecationWarning, and ImportWarning are
> ignored.
> * BytesWarning is ignored unless the -b option is given once or twice; in
> this case this warning is either printed (-b) or turned into an exception
> (-bb).
>
By default, `DeprecationWarning` is ignored. You can change the filters using
the following:
warnings.simplefilter('always', DeprecationWarning)
Now your warnings should be printed:
>>> import warnings
>>> warnings.simplefilter('always', DeprecationWarning)
>>> warnings.warn('test', DeprecationWarning)
/home/guest/.env/bin/ipython:1: DeprecationWarning: test
#!/home/guest/.env/bin/python
|
python multiprocessing: why is process defunct after terminate?
Question: I have some python multiprocessing code with the parent process starting a
bunch of child worker processes and then terminating them after awhile:
from multiprocessing import Process
nWorkers = 10
curWorkers = []
for iw in range(nWorkers):
pq = Process(target=worker, args=(worker's_args_here))
pq.start()
curWorkers.append(pq)
# Do work here...
for pw in curWorkers:
pw.terminate()
However, the child processes all are showing as defunct long after
termination. Are they zombie processes? More importantly, how should I
terminate them so that they really go away?
Answer: Try adding:
for pw in curWorkers:
pw.join()
at the end. `.terminate()` just kills the process. The parent process still
needs to reap it (at least on Linux-y systems) before the child process goes
away entirely.
|
'str' object is not callable,how to deal?
Question: when I'm trying to run my python-django app, the error says: 'str' object is
not callable
I've tried the solution here but not worked for me: [TypeError: 'str' object
is not callable
(Python)](http://stackoverflow.com/questions/6039605/typeerror-str-object-is-
not-callable-python)
I'm trying to run django book sample here:
[TypeError: 'str' object is not callable
(Python)](http://stackoverflow.com/questions/6039605/typeerror-str-object-is-
not-callable-python)
this is my view.py:
# Create your views here.
from django.http import HttpResponse
import datetime
def current_time(request):
now = datetime.datetime.now()
html = "<html><head></head><body>%s</body></html>" % str(now)
return HttpResponse(html)
def hello(request,name):
return HttpResponse("Hello django")
def what(request):
return HttpResponse("what's the problem django?")
this is urls.py:
from django.conf.urls import patterns, include, url
from hello_django.views import current_time,hello,what
urlpatterns = patterns('',
url(r'^time/$','current_time'),
url(r'^what/$','what'),
url(r'^hello/([a-zA-Z0-9]+)','hello'),
)
this is the url I'm trying:
http://127.0.0.1:8000/what/
stack trace:
TypeError at /what/
'str' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/what/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
'str' object is not callable
Exception Location: C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response, line 115
Python Executable: C:\Python27\python.exe
Python Version: 2.7.4
Python Path:
['D:\\Developer Center\\PyCharm\\helloDjango',
'C:\\Python27\\lib\\site-packages\\pip-1.3.1-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\mysql_python-1.2.4-py2.7-win32.egg',
'D:\\Developer Center\\PyCharm\\helloDjango',
'C:\\Windows\\SYSTEM32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\PIL']
Server time: Tue, 7 Jan 2014 11:44:30 +0330
Traceback Switch to copy-and-paste view
C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
Answer: You need to give the actual **view** to `url()`:
urlpatterns = patterns('',
url(r'^time/$', current_time),
url(r'^what/$', what),
url(r'^hello/([a-zA-Z0-9]+)', hello),
)
Note that I removed the quotes around `what` and the other view functions.
You can still use strings in the `url()` configurations, but then you need to
use a `<modulename>.<viewname>` syntax or name the module in the first
argument to `patterns()` (the string), and then you also don't need to import
the functions:
urlpatterns = patterns('',
url(r'^time/$', 'hello_django.views.current_time'),
url(r'^what/$', 'hello_django.views.what'),
url(r'^hello/([a-zA-Z0-9]+)', 'hello_django.views.hello'),
)
or
urlpatterns = patterns('hello_django.views',
url(r'^time/$', 'current_time'),
url(r'^what/$', 'what'),
url(r'^hello/([a-zA-Z0-9]+)', 'hello'),
)
See the [detailed URL dispatcher
documentation](https://docs.djangoproject.com/en/1.6/topics/http/urls/).
|
A faster way to evaluate 2D-array items than nested for loops?
Question: I'm using python 2.7
I have a 2-dimensional array that is several hundred elements on each axis.
Each element is either '0', or '255' I need to look at each element and write
a '0' or '1' into a different array that has the same dimensions. Currently I
have a nested for-loop structure iterating over the rows and columns.
This is turning out to be really, really slow. What is a better
implementation? What if I multiplied the matrix by a constant 1/255. This
would keep the zeros as zeros, and convert the 255 to '1'. but this is just
trading the loops for an enormous number of multiplies, which probably has its
own speed issues.
Thoughts?
Answer: I'd also use numpy.array for fast array manipulation, here's an example :
import numpy as np
# Create an example array of shape (100, 100) filled with either 0 or 255
a = 255*np.random.randint(2, size=10000).reshape(100,100)
# Transform it as you want
1*(a==255)
|
Scrapy key error
Question: I am having issues creating the Scrapy spider in the Scrapy tutorial:
<http://doc.scrapy.org/en/latest/intro/tutorial.html#our-first-spider>
Here is what I have in my spiders/dmoz_spider.py file:
class DmozSpider(object):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
@classmethod
def from_crawler(cls, crawler):
spider = crawler.spiders
return cls(spider)
def parse(self, response):
filename = response.url.split("/")[-2]
open(filename, 'wb').write(response.body)
The good news is I am pretty sure a spider is getting created. The bad news is
I get this error:
(scrapestat)unknownc8e0eb148153:tutorial christopherspears$ scrapy crawl dmoz
Traceback (most recent call last):
File "/Users/christopherspears/.virtualenvs/scrapestat/bin/scrapy", line 4, in <module>
execute()
File "/Users/christopherspears/.virtualenvs/scrapestat/lib/python2.7/site-packages/scrapy/cmdline.py", line 143, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/Users/christopherspears/.virtualenvs/scrapestat/lib/python2.7/site-packages/scrapy/cmdline.py", line 89, in _run_print_help
func(*a, **kw)
File "/Users/christopherspears/.virtualenvs/scrapestat/lib/python2.7/site-packages/scrapy/cmdline.py", line 150, in _run_command
cmd.run(args, opts)
File "/Users/christopherspears/.virtualenvs/scrapestat/lib/python2.7/site-packages/scrapy/commands/crawl.py", line 48, in run
spider = crawler.spiders.create(spname, **opts.spargs)
File "/Users/christopherspears/.virtualenvs/scrapestat/lib/python2.7/site-packages/scrapy/spidermanager.py", line 44, in create
raise KeyError("Spider not found: %s" % spider_name)
KeyError: 'Spider not found: dmoz'
Not sure what the issue is. Any hints?
Answer: DmozSpider should inherit from BaseSpider (or Spider, depends on your scrapy
version). So, make a following change in your code:
from scrapy.spider import BaseSpider
class DmozSpider(BaseSpider):
...
I tried that by myself and when spider class inherits from object that
KeyError is raised.
|
QGLWidget don't move its contents on scroll
Question: I'm using Qt from python with PySide bindings. The main part of my application
is the OpenGL view that can be resized to particular value (this is a
simulator for testing my game in different resolutions of mobile devices). I
use QGLWidget to render graphics from my game engine and QScrollArea for
scrolling.
When I try to scroll GL view nothing happens - it just stays at the same
place, but coordinates of QGLWidget are updated just fine which I see through
print statements.
Playing around with resizing main window I've came to conclusion that
everything inside QGLWidget is snapped to the bottom-left corner of currently
visible area. So this would explain why I can't see scrolling.
Am I supposed to update projection matrix manually?
Answer: It sounds like some kind of parenting issue. This works as expected:
import sys
from PySide.QtGui import *
from PySide.QtOpenGL import *
from OpenGL.GL import *
from OpenGL.GLU import *
class GLWidget(QGLWidget):
def __init__(self, *args, **kwargs):
QGLWidget.__init__(self, *args, **kwargs)
def initializeGL(self):
glShadeModel(GL_SMOOTH)
glEnable(GL_DEPTH_TEST)
glClearColor(0.0, 0.0, 0.0, 1.0)
glClearDepth(1.0)
def resizeGL(self, w, h):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glViewport(0, 0, w, h)
gluPerspective(45.0, w / h, 1, 1000)
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0.0, 0.0, -6.0)
glBegin(GL_TRIANGLES)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(0.0, 1.0, 0.0)
glColor3f(0.0, 0.0, 1.0)
glVertex3f(-1.0, -1.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex3f(1.0, -1.0, 1.0)
glEnd()
class Window(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.scroll = QScrollArea(self)
self.glWidget = GLWidget(self.scroll)
self.glWidget.resize(600, 400)
self.scroll.setWidget(self.glWidget)
self.layout = QHBoxLayout()
self.layout.addWidget(self.scroll)
self.setLayout(self.layout)
self.resize(400, 300)
self.show()
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
* OS: Windows 7 SP1 (32bit)
* PySide: 1.2.1
* Qt: 4.8.5
* PyOpenGL: 3.0.2
|
IndexError in unused conditional
Question:
def menurender():
global pos
global menulist
line1=menulist[pos]
if pos == len(menulist):
line2="back"
else:
line2=menulist[pos+1]
lcd.clear()
lcd.message(str(pos)+' ' +line1+ "\n"+str(pos+1)+' '+ line2)
In my block of code, I have a conditional in the menurender() function that
checks to make sure that the list menulist has a valid index before
referencing it, but i receive IndexError: list index out of range. I
understand that the else statement is causing it, but I am confused because
python shouldn't be executing it.
Full code
#!/usr/bin/python
#################################################
#IMPORTS#########################################
#################################################
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from Adafruit_I2C import Adafruit_I2C
#################################################
#OBJECTS#########################################
#################################################
lcd = Adafruit_CharLCDPlate()
#################################################
#VARIABLES#######################################
#################################################
#current button value
prevbutton = "NULL"
#for SELECT key and determining clicks
action = False
#variable for menu position
pos = 0
#on screen cursor 0 for top line, 1 for bottom line
cursor = 0
#Handles list structure and action when clicked
menulist= []
menulist.append("CPU")
menulist.append("RAM")
menulist.append("STORAGE")
menulist.append("NETWORK")
#get input from keys and return the currently pressed key
def buttonstatus():
bstatus = "Null"
if lcd.buttonPressed(lcd.SELECT) == True:
bstatus="SELECT"
elif lcd.buttonPressed(lcd.UP) == True:
bstatus="UP"
elif lcd.buttonPressed(lcd.DOWN) == True:
bstatus="DOWN"
elif lcd.buttonPressed(lcd.LEFT) == True:
bstatus="LEFT"
elif lcd.buttonPressed(lcd.RIGHT) == True:
bstatus="RIGHT"
return bstatus
#checks buttons pressed and converts that into action for top menu
def getinput():
global prevbutton
global pos
if buttonstatus() != prevbutton:
prevbutton = buttonstatus()
if buttonstatus() == "SELECT":
print "select"
elif buttonstatus() == "DOWN":
pos = pos + 1
elif buttonstatus() == "UP":
pos = pos -1
#elif buttonstatus() == "LEFT":
#print "left"
#elif buttonstatus() == "RIGHT":
#print "right"
#defines bounds for the position of the cursor
def posbounds():
global pos
global menulist
if pos < 0:
pos = 0
if pos == len(menulist):
pos = len(menulist)
#code renders the menu on the LCD
def menurender():
global pos
global menulist
line1=menulist[pos]
if pos == len(menulist):
line2="back"
else:
line2=menulist[pos+1]
lcd.clear()
lcd.message(str(pos)+' ' +line1+ "\n"+str(pos+1)+' '+ line2)
while True:
getinput()
posbounds()
menurender()
Answer: There are lots if values for `pos != len(menulist)` for which
`menulist[pos+1]` gives an `IndexError` (including `pos == len(menulist) -
1`). You should check
if pos > (len(menulist) - 2):
|
Python Tkinter Toplevel
Question: I am working on a program that requires multiple windows, and the first one to
appear is the login window, I used the Toplevel widget in order to make other
windows its children, but this code keeps showing two windows instead of one.
from Tkinter import Frame, Toplevel
from ttk import Label, Entry, Button
class loginWindow(Toplevel):
def __init__(self):
Toplevel.__init__(self)
self.title("Title")
self.frame = Frame(self)
self.frame.pack()
self.__make_layout()
self.mainloop()
def __make_layout(self):
self.frame.user_name_label = Label(text="User name:")
self.frame.user_name_text = Entry()
self.frame.user_name_label.grid(row=0, column=0)
self.frame.user_name_text.grid(row=0, column=1)
self.frame.password_label = Label(text="Password:")
self.frame.password_text = Entry()
self.frame.password_label.grid(row=1, column=0)
self.frame.password_text.grid(row=1, column=1)
self.frame.login_button = Button(text="Login")# , command=self.__create_window)
self.frame.login_button.grid(row=2, column=0, columnspan=2)
if __name__ == '__main__':
win1 = loginWindow()
Answer: This must be a platform dependent issue, since abarnert isn't having issues
with multiple windows. I use OS X with XQuartz and the following code gives me
two windows:
from Tkinter import Toplevel, Tk
Toplevel().mainloop()
However, this code gives me one window:
from Tkinter import Toplevel, Tk
Tk().mainloop()
I believe your first window should be declared `Tk()` and subsequent windows
should be `Toplevel()`.
|
Print all fields of ctypes "Structure" with introspection
Question: test.c:
#include <stdio.h>
#include <stdlib.h>
struct s {
char a;
int b;
float c;
double d;
};
struct s *create_struct()
{
struct s *res = malloc(sizeof(struct s));
res->a = 1; res->b = 2; res->c = 3.0f; res->d = 4.0;
return res;
}
test.py:
from ctypes import *
class S(Structure):
_fields_ = [
('a', c_byte),
('b', c_int),
('c', c_float),
('d', c_double)
]
lib = CDLL('./test.so')
create_struct = lib.create_struct
create_struct.restype = POINTER(S)
create_struct.argtypes = []
s_ptr = create_struct()
s = s_ptr.contents
print s._fields_[0][0], s.a
print s._fields_[1][0], s.b
print s._fields_[2][0], s.c
print s._fields_[3][0], s.d
print s.__dict__
output:
a 1
b 2
c 3.0
d 4.0
{}
I'd like to adapt the python script above to print each field of my s
structure without having to do explicitly for each field. From what I
understand, this can be done using the __dict__ attribute but mine is empty.
Is there any way to do this for a class that extends ctypes.Structure?
Answer: How about using
[`getattr`](http://docs.python.org/2/library/functions.html#getattr)?
>>> from ctypes import *
>>>
>>> class S(Structure):
... _fields_ = [
... ('a', c_byte),
... ('b', c_int),
... ('c', c_float),
... ('d', c_double)
... ]
...
>>> s = S(1, 2, 3, 4.0)
>>>
>>> for field_name, field_type in s._fields_:
... print field_name, getattr(s, field_name)
...
a 1
b 2
c 3.0
d 4.0
**UPDATE**
If there is a bitfield in the structure (or union), iterating `_fields_` yield
a tuple of 3 items which will cause `ValueError`. To prevent that you need to
adjust the code:
...
for field in s._fields_:
print field[0], getattr(s, field[0])
|
How to decrement an entire csv column with Python - what am I doing wrong?
Question: I am very new to programming so please be patient with me.
I am reading from a .csv like so:
1, -2
2, 3
3, -6
4, 5
5, 7
and so on. My goal here, essentially is just to delete the first row, and then
decrement the remaining first column by 1, so I'd have something like..
1, 3
2, -6
3, 5
4, 7
5, *some randomly generated number*
Here is what I have so far:
del data[0]
for i in range(len(data)):
newTime = data[i][0] - 1
oldNum = data[0][1]
data.insert(i, [newTime, oldNum])
however this is just taking 1, 3 and inserting it len(data) times.. what am I
doing wrong? Please don't be mean, I really am trying to learn!
I was using this as guidance:
<http://docs.python.org/release/1.5.1p1/tut/range.html>, and to me it seems
like this should work.. :/ Haaaalp!
Answer:
import random
data = [[1,2],
[2,4],
[3,-5],
[4,9],
[5,7]]
l = len(data)
for i in range(l-1):
data[i][1] = data[i+1][1]
data[l-1][1] = random.randint(-3,3)
print(data)
output:
[[1, 4],
[2, -5],
[3, 9],
[4, 7],
[5, 0]]
|
Python TCP socket.recv() returns with nothing as soon as connection is made
Question: I'm trying to implement the most basic python TCP server. Windows 8, Python
2.7, firewall is turned off. Code is from here:
<https://wiki.python.org/moin/TcpCommunication>
If I do the client stuff (`socket(...), connect(...), send(...)`) via python
repl, things work fine, ie the server correctly blocks when calling `recv`.
However if I run the exact same code via python script (both with and without
explicitly calling python.exe at windows command line), the `recv` returns
immediately with no data. I read elsewhere on SO this means it's an invalid
socket, but I'm not sure what that means or how to check for it. I'm using the
socket returned by `accept()` not the one used to initiate the connection.
I'm trying to block on `recv` so I can take advantage of the timeout (I don't
want to use select module, which BTW also returns immediately) and process
some keyboard stuff between attempts to `recv`, ie user presses 'q' to quit.
In various experiments I've shown that once this occurs, `recv` will always
return immediately (as will `select.select(...)`) if I put it in a loop, so
it's not like the client is sending a single "bad" packet initially. If the
client happens to have sent something, then the `recv` returns with that data,
but it certainly doesn't block waiting for data when put in a tight loop.
Is this behavior expected?
Server code:
import sys
import socket
TCP_IP = '192.168.1.10'
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE) # This returns immediately with no data, when client connection is run from script and doesn't send() anything, just connects.
if not data:
print "broken"
break
print "received data:", data
conn.send(data) # echo
conn.close()
sys.exit()
Client code:
import sys
import socket
TCP_IP = '192.168.1.10'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
# Commenting out the following to prove the recv() call on the other
#end returns with nothing instead of blocking indefinitely. If I
#type the rest of this at the REPL the server behaves correctly,
#ie, the recv call blocks forever until socket.send("bla") from client.
#s.send(MESSAGE) data = s.recv(BUFFER_SIZE)
#s.close()
#print "received data:", data
sys.exit()
Answer: Yes, this is expected behavior.
The client does not send anything. And it exit as soon as it connect to the
server; cause disconnection.
[`socket.recv`](http://docs.python.org/2/library/socket.html#socket.socket.recv)
returns an empty string if the peer performed shutdown (disconnect).
While, in the REPL, the socket is not closed until you issue `sys.exit()` or
you quit the interactive shell.
|
Python: time.sleep functions unexpectedly?
Question: I'm trying to make a simple function that will type out a string letter by
letter, such as in a game, where text scrolls.
Here's what my code looks like:
import time
def ScrollingText(s):
s=str(s)
for letter in s:
print(letter, end="")
time.sleep(.05)
print("") # newline at the end
if __name__=='__main__':
ScrollingText("Hello World!")
However when I run, it waits, then dumps out the whole string at once. I'm new
to python (and this forum as well) so if anyone can point me in the right
direction and show me what I'm missing here in time.sleep I'd greatly
appreciate it. Thanks!
Answer: As you do not have a newline in your string, python will buffer it. You have
to explicitly flush the output after each character like this:
import sys
import time
def ScrollingText(s):
s=str(s)
for letter in s:
print(letter, end="")
sys.stdout.flush()
time.sleep(.05)
print("") # newline at the end
For better performance, I/O is usually buffered, that is, python will collect
the data you print until it can send it out as a large block (this also goes
for file I/O by the way). By calling
[flush()](http://docs.python.org/2/library/stdtypes.html#file.flush) on
sys.stdout (which is the file object where print writes to by default), you
force python to send your data to the operating system (and that will send it
to your terminal).
|
Python-random number and its frequency
Question: > The function `randint` from the random module can be used to produce random
> numbers. A call on `random.randint(1, 6)`, for example, will produce the
> values 1 to 6 with equal probability. Write a program that loops 1000 times.
> On each iteration it makes two calls on `randint` to simulate rolling a pair
> of dice. Compute the sum of the two dice, and record the number of times
> each value appears.
>
> The output should be two columns. One displays all the sums (i.e. from 2 to
> 12) and the other displays the sums' respective frequencies in 1000 times.
My code is shown below:
import random
freq=[0]*13
for i in range(1000):
Sum=random.randint(1,6)+random.randint(1,6)
#compute the sum of two random numbers
freq[sum]+=1
#add on the frequency of a particular sum
for Sum in xrange(2,13):
print Sum, freq[Sum]
#Print a column of sums and a column of their frequencies
However, I didn't manage to get any results.
Answer: You shouldn't use `Sum` because simple variables should not be capitalized.
You shouldn't use `sum` because that would shadow the built-in `sum()`.
Use a different non-capitalized variable name. I suggest `diceSum`; that's
also stating a bit about the context, the idea behind your program etc. so a
reader understands it faster.
You don't want to make any readers of your code happy? Think again. You asked
for help here ;-)
|
Numpy loadtxt Behavior change with Python 3
Question: I have some code that has been working fine in Python 2.7 using numpy's
loadtxt function to read in a csv file into a numpy array. The file can be
seen [here](http://www.andrewhowe.com/INDEX_20140101.csv). I use this command
inp = numpy.loadtxt(filename, dtype=str, delimiter=',',skiprows=1
With this, I get this in python 2.7
array([['BKNIF', '01-Jan-2014', '11418.9', '11432.55', '11361', '11385.6',
'0'],
['BSESN', '01-Jan-2014', '21222.19', '21244.35', '21133.82',
'21140.48', '0'],
['DXY', '01-Jan-2014', '80.21', '80.24', '80.16', '80.19', '0'],
['FBV', '01-Jan-2014', '0', '0', '0', '0', '0']],
dtype='|S11')
However, with python 3.3, I'm getting
array([["b'BKNIF'", "b'01-Jan-2014'", "b'11418.9'", "b'11432.55'",
"b'11361'", "b'11385.6'", "b'0'"],
["b'BSESN'", "b'01-Jan-2014'", "b'21222.19'", "b'21244.35'",
"b'21133.82'", "b'21140.48'", "b'0'"],
["b'DXY'", "b'01-Jan-2014'", "b'80.21'", "b'80.24'", "b'80.16'",
"b'80.19'", "b'0'"],
["b'FBV'", "b'01-Jan-2014'", "b'0'", "b'0'", "b'0'", "b'0'", "b'0'"]],
dtype='<U14')
Note how the import has inserted the double quote around every item, and the b
in front. It has also apparently decide to code it differently. Even if I use
`dtype='|S11'` instead of `dtype=str`, I get the same behavior.
Please don't comment on why am I using numpy loadtxt for this, or if you think
my use of loadtxt is inefficient. Right now, I need help with figuring out why
the behavior changed, and how to fix it. Thanks.
Answer:
In [20]: m=loadtxt(fname, dtype='S20', delimiter=',', skiprows=1)
In [21]: m.astype(str)
Out[21]:
array([['BKNIF', '01-Jan-2014', '11418.9', '11432.55', '11361', '11385.6',
'0'],
['BSESN', '01-Jan-2014', '21222.19', '21244.35', '21133.82',
'21140.48', '0'],
['DXY', '01-Jan-2014', '80.21', '80.24', '80.16', '80.19', '0'],
['FBV', '01-Jan-2014', '0', '0', '0', '0', '0'],
['NSEI', '01-Jan-2014', '6323.8', '6327.2', '6298.25', '6301.65',
'0'],
['NVOT', '01-Jan-2014', '30783.764', '2313498.5', '30783.764',
'2313498.5', '0'],
['RUI', '01-Jan-2014', '1027.14', '1030.97', '1027.14', '1030.364',
'0'],
['RUT', '01-Jan-2014', '1160.64', '1165.64', '1160.64', '1163.637',
'0'],
['SENSEX', '01-Jan-2014', '21222.19', '21244.35', '21133.82',
'21140.48', '0']],
dtype='<U20')
but still the elements are `numpy.bytes_`:
m[0][0]
Out[22]: b'BKNIF'
type(m[0][0])
Out[23]: numpy.bytes_
i think it's just looks not pretty?
|
Python: io.TextIOWrapper illegal newline
Question: I'm trying to set the newline character for SiRF binary messages, but the IO
wrapper doesn't seem to accept the newline chars.
Code:
import serial
import io
port = serial.Serial(port='/dev/ttyUSB0', baudrate=4800, timeout=2)
sio = io.TextIOWrapper(io.BufferedRWPair(port, port), newline='\xb0\xb3')
Output:
>>> sio = io.TextIOWrapper(io.BufferedRWPair(port, port, 1), newline='\xb3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: illegal newline value: �
>>>
Note: It does accept '\x0d'
Answer: You can not just use any character as the newline. From the
[`io.TextIOWrapper()`
documentation](http://docs.python.org/3/library/io.html#io.TextIOWrapper):
> _newline_ controls how line endings are handled. It can be `None`, `''`,
> `'\n'`, `'\r'`, and `'\r\n'`.
You'll have to handle those bytes manually instead of a newline, directly.
|
How to find visible bluetooth devices in Python?
Question: I need to find the list of visible Bluetooth devices with their respective
details in the range of my Bluetooth modem. I only need to do Bluetooth 2.0
and below. I don't need to do Bluetooth 4.0.
Like you do on an Android phones using "Search for devices".
I'm sorry I can't give any code I tried because I don't know how to do
Bluetooth with python.
Answer: PyBluez link
[here](http://homepages.ius.edu/RWISMAN/C490/html/PythonandBluetooth.htm) and
[here](https://code.google.com/p/pybluez/):
from bluetooth import *
print "performing inquiry..."
nearby_devices = discover_devices(lookup_names = True)
print "found %d devices" % len(nearby_devices)
for name, addr in nearby_devices:
print " %s - %s" % (addr, name)
Another good link to
[here](http://www.robertprice.co.uk/robblog/2007/01/programming_bluetooth_using_python-
shtml/)
The importent thing is you can use `lookup_names = True`
from bluez Docs:
if lookup_names is False, returns a list of bluetooth addresses.
if lookup_names is True, returns a list of (address, name) tuples
**It's for python 2.6...** if you want for 2.7 you can find it
[here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pybluez)
|
Create a half circle in angle 45 in Python
Question: I need to create a half circle in angle 45 (a moon) , of radius 20 in the left
side of a pic. I'm new to the image processing in Python. I've downloaded the
PIL library, can anyone give me an advice? Thanks
Answer: This might do what you want:
import Image, ImageDraw
im = Image.open("Two_Dalmatians.jpg")
draw = ImageDraw.Draw(im)
# Locate the "moon" in the upper-left region of the image
xy=[x/4 for x in im.size+im.size]
# Bounding-box is 40x40, so radius of interior circle is 20
xy=[xy[0]-20, xy[1]-20, xy[2]+20, xy[3]+20]
# Fill a chord that starts at 45 degrees and ends at 225 degrees.
draw.chord(xy, 45, 45+180, outline="white", fill="white")
del draw
# save to a different file
with open("Two_Dalmatians_Plus_Moon.png", "wb") as fp:
im.save(fp, "PNG")
Ref: <http://effbot.org/imagingbook/imagedraw.htm>
* * *
This program might satisfy the newly-described requirements:
import Image, ImageDraw
def InitializeMoonData():
''''
Return a 40x40 half-circle, tilted 45 degrees, as raw data
Only call once, at program initialization
'''
im = Image.new("1", (40,40))
draw = ImageDraw.Draw(im)
# Draw a 40-diameter half-circle, tilted 45 degrees
draw.chord((0,0,40,40),
45,
45+180,
outline="white",
fill="white")
del draw
# Fetch the image data:
moon = list(im.getdata())
# Pack it into a 2d matrix
moon = [moon[i:i+40] for i in range(0, 1600, 40)]
return moon
# Store a copy of the moon data somewhere useful
moon = InitializeMoonData()
def ApplyMoonStamp(matrix, x, y):
'''
Put a moon in the matrix image at location x,y
Call whenever you need a moon
'''
# UNTESTED
for i,row in enumerate(moon):
for j,pixel in enumerate(row):
if pixel != 0:
# If moon pixel is not black,
# set image pixel to white
matrix[x+i][y+j] = 255
# In your code:
# m = Matrix(1024,768)
# m = # some kind of math to create the image #
# ApplyMoonStamp(m, 128,128) # Adds the moon to your image
|
No module named lxml.html while running python script on Fedora
Question: I'm trying to run a python script on Fedora Server. I'm getting the following
error.
/usr/bin/python report_generation.py
Traceback (most recent call last):
File "report_generation.py", line 9, in ?
import lxml.html
ImportError: No module named lxml.html
Doing some research, I found it needs python-lxml package to run the script.
This machine already have some lxml installations. But, I'm not able to make
this work.
yum search libxml
libxml2.i386 : Library providing XML and HTML support
libxml2.x86_64 : Library providing XML and HTML support
libxml2-devel.i386 : Libraries, includes, etc. to develop XML and HTML applications
libxml2-devel.x86_64 : Libraries, includes, etc. to develop XML and HTML applications
libxml2-python.x86_64 : Python bindings for the libxml2 library
libxslt.i386 : Library providing the Gnome XSLT engine
libxslt.x86_64 : Library providing the Gnome XSLT engine
libxslt-devel.i386 : Libraries, includes, etc. to embed the Gnome XSLT engine
libxslt-devel.x86_64 : Libraries, includes, etc. to embed the Gnome XSLT engine
libxslt-python.x86_64 : Python bindings for the libxslt library
Also, it says all of them are up to date when I tried to install the packages.
For some reason, its not picking up the lxml module and throwing this error
while running the script. I'm new to both Linux and Python. Please provide me
any clue to debug this issue.
Answer:
sudo yum install python-lxml
or
sudo apt-get install python-lxml
|
Pig game in Python
Question: I'm trying to write a pig game in python. Here is my code:
from random import *
roll_q = raw_input('would you like to roll')
if roll_q == (' yes'):
while True:
num1 = randint(1,6)
print str(randint)
if randint == 1:
print('your turn is over')
total = 0
else:
num1 = randint(1,6)
print ('you got ') + str(randint) + ('points')
total = randint
print str(total)
total=total + randint
cont_q = raw_input('would you like to continue playing')
if cont_q == ('yes'):
print ('awesome')
else:
print ('ok')
else:
print ('awesome')
When I ran this program I got asked if I wanted to roll and printed something.
But then it gave me an error I didn't understand.
would you like to roll yes
<bound method Random.randint of <random.Random object at 0x89b010>>
you got <bound method Random.randint of <random.Random object at 0x89b010>>points
<bound method Random.randint of <random.Random object at 0x89b010>>
Traceback (most recent call last):
File "/Users/centralcity/Desktop/Computer Science!/pig game", line 15, in <module>
total=total + randint
TypeError: unsupported operand type(s) for +: 'instancemethod' and 'instancemethod'
Please help me understand the error and why my program isn't printing right.
Thanks in advance.
Answer: You keep saying `randint` where you should say `num1`. After you call
`randint` with `randint(1,6)` you store the result in `num1`, so the lines
afterward should refer to `num1`.
if roll_q == (' yes'):
while True:
num1 = randint(1,6)
print str(num1)
if num1 == 1:
print('your turn is over')
total = 0
else:
num1 = randint(1,6)
print ('you got ') + str(num1) + ('points')
total = num1
print str(total)
total=total + num1
cont_q = raw_input('would you like to continue playing')
if cont_q == ('yes'):
print ('awesome')
else:
print ('ok')
|
Python/PyGame functions not working as hoped
Question: I have this project to create a game with a main menu. I have created a very
basic main menu at the moment just for prototype purposes. I have my main menu
load up and then i want to hit "f" to play game, but it's not working as
hoped. When i launch it the g It was fine before I added the functions, but i
need these functions. Anybody got any ideas? Thanks.
import pygame, math, sys, random
pygame.init()
#Variables
darkYellow = 204,204,0
grey = 102, 102, 102
black = 0, 0, 0
white = 255, 255, 255
red = 255,0,0
marroon = 120, 0, 0
green = 0,255,0
blue = 0,0,255
darkBlue = 0,0,128
resolution = 650, 600
myFont = pygame.font.SysFont("Times New Roman", 30)
myFont2 = pygame.font.SysFont("Times New Roman", 15)
myFont3 = pygame.font.SysFont("Times New Roman", 60)
redLeft = 150, 575
redRight = 280, 575
blackLeft = 370, 575
blackRight = 500, 575
radius = 20
window = pygame.display.set_mode(resolution)
window.fill(grey)
pygame.display.set_caption('Harrys Game')
def mainMenu():
rectWidth = 150
rectHeight = 40
#Draw buttons
pygame.draw.rect(window, (white),(250, 150, rectWidth, rectHeight),0)
pygame.draw.rect(window, (white),(250, 225, rectWidth, rectHeight),0)
pygame.draw.rect(window, (white),(250, 300, rectWidth, rectHeight),0)
highlight = pygame.draw.rect(window, (darkYellow),(250, 150, rectWidth, rectHeight),0)
pygame.display.update()
playGameText = myFont.render("Play Game", 1, red)
window.blit(playGameText, (260, 150))
optionsText = myFont.render("Options", 1, red)
window.blit(optionsText, (275, 225))
exitText = myFont.render("Exit", 1, red)
window.blit(exitText, (300, 300))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_f:
break
game()
def game():
while False:
startBar = pygame.draw.lines(window, black, False, [(0,545.46),(541.7,545.46)], 5)
bar2 = pygame.draw.lines(window, black, False, [(0,490.92),(541.7,490.92)], 5)
bar3 = pygame.draw.lines(window, black, False, [(0,436.38),(541.7,436.38)], 5)
bar4 = pygame.draw.lines(window, black, False, [(0,381.84),(541.7,381.84)], 5)
bar5 = pygame.draw.lines(window, black, False, [(0,327.3),(541.7,327.3)], 5)
bar6 = pygame.draw.lines(window, black, False, [(0,272.76),(541.7,272.76)], 5)
bar7 = pygame.draw.lines(window, black, False, [(0,218.22),(541.7,218.22)], 5)
bar8 = pygame.draw.lines(window, black, False, [(0,163.68),(541.7,163.68)], 5)
bar9 = pygame.draw.lines(window, black, False, [(0,109.14),(541.7,109.14)], 5)
bar10 = pygame.draw.lines(window, black, False, [(0,54.6),(541.7,54.6)], 5)
#Draw side columns
rightBar = pygame.draw.lines(window, black, False, [(541.7,600),(541.7,0)], 5)
leftBar = pygame.draw.lines(window, black, False, [(108.3,600),(108.3,0)], 5)
centreBar = pygame.draw.lines(window, black, False, [(325,0),(325,600)], 5)
#Right column text
label1 = myFont2.render("You rolled a:", 1, black)
window.blit(label1, (545, 20))
rollLabel = myFont2.render("Hit space", 1, black)
window.blit(rollLabel, (545, 100))
rollLabel2 = myFont2.render("to roll again", 1, black)
window.blit(rollLabel2, (545, 117))
#Display column numbers
start1 = myFont.render("START", 1, black)
window.blit(start1, (8, 545.46))
side2 = myFont.render("2", 1, black)
window.blit(side2, (54.15, 490.92))
side3 = myFont.render("3", 1, black)
window.blit(side3, (54.15, 436.38))
side4 = myFont.render("4", 1, black)
window.blit(side4, (54.15, 381.84))
side5 = myFont.render("SAFE 5", 1, black)
window.blit(side5, (8, 327.3))
side6 = myFont.render("6", 1, black)
window.blit(side6, (54.15, 272.76))
side7 = myFont.render("7", 1, black)
window.blit(side7, (54.15, 218.22))
side8 = myFont.render("8", 1, black)
window.blit(side8, (54.15, 163.68))
side9 = myFont.render("9", 1, black)
window.blit(side9, (54.15, 109.14))
side10 = myFont.render("10", 1, black)
window.blit(side10, (54.15, 54.6))
finish11 = myFont.render("FINISH", 1, black)
window.blit(finish11, (8, 0))
pygame.display.update()
redCountLeft = pygame.draw.circle(window, marroon, redLeft, radius)
redCountRight = pygame.draw.circle(window, marroon, redRight, radius)
blackCountLeft = pygame.draw.circle(window, black, blackLeft, radius)
blackCountRight = pygame.draw.circle(window, black, blackRight, radius)
mainMenu()
pygame.display.update()
Answer: A few things:
`main_menu()` has a `while True:` loop with no `break`, `raise` or `return`,
so would continue looping indefinitely if ever called.
`game()` contains a `while False:` "loop" that will never start.
This line makes no sense:
mainMenu() == False
and nor does:
game() == True
For some reason, you define functions (e.g. `def counters:`) then just call
them straight away (e.g. `counters()`).
When you run your code, this happens:
1. All the definitions before `def main():` happen;
2. `main` is defined then immediately called;
3. `mainMenu` is defined;
4. `game` is defined then immediately called, but doesn't do anything (see above);
5. `counters` is defined then immediately called; and
6. You call `pygame.display.update()`.
_That's it_. `mainMenu` is never called (a good thing, as it would uselessly
loop forever).
A pseudo code suggestion:
set up variables
set up window
main menu:
setup on screen text
while True:
get user input
if correct user input:
break
call game
game:
while True:
play game
call main menu
|
How to load all entries in an infinite scroll at once to parse the HTML in python
Question: I am trying to extract information from [this
page](https://medium.com/top-100/december-2013). The page loads 10 items at a
time, and I need to scroll to load all entries (for a total of 100). I am able
to parse the HTML and get the information that I need for the first 10
entries, but I want to fully load all entries before parsing the HTML.
I am using python, requests, and BeautifulSoup. The way I parse the page when
it loads with the first 10 entries is as follows:
from bs4 import BeautifulSoup
import requests
s = requests.Session()
r = s.get('https://medium.com/top-100/december-2013')
page = BeautifulSoup(r.text)
But this only loads the first 10 entries. So I looked at the page and got the
AJAX request used to load the subsequent entries and I get a response but it's
in the a funky JSON and I'd rather use the HTML parser instead of parsing
JSON. Here's the code:
from bs4 import BeautifulSoup
import requests
import json
s = requests.Session()
url = 'https://medium.com/top-100/december-2013/load-more'
payload = {"count":100}
r = s.post(url, data=payload)
page = json.loads(r.text[16:]) #skip some chars that throw json off
This gives me the data but it's in a very long and convoluted JSON, I would
much rather load all the data on the page and simply parse the HTML. In
addition, the rendered HTML provides more information than the JSON response
(i.e. the name of the author instead of obscure userID, etc.) There was a
similar question [here](http://stackoverflow.com/questions/19512250/parse-
html-infinite-scroll) but no relevant answers. Ideally I want to make the POST
call and _then_ request the HTML and parse it, but I haven't been able to do
that.
Answer: This you won't be able to do with requests and BeautifulSoup as the page that
you want to extract the information from loads the rest of the entries through
JS when you scroll down. You can do this using [selenium](http://selenium-
python.readthedocs.org/en/latest/api.html) which opens a real browser and you
can pass page down key press events programmatically. Watch this video to see
the action. <http://www.youtube.com/watch?v=g54xYVMojos>
Below is the script that extracts all the 100 post titles using selenium.
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
browser.get("https://medium.com/top-100/december-2013")
time.sleep(1)
elem = browser.find_element_by_tag_name("body")
no_of_pagedowns = 20
while no_of_pagedowns:
elem.send_keys(Keys.PAGE_DOWN)
time.sleep(0.2)
no_of_pagedowns-=1
post_elems = browser.find_elements_by_class_name("post-item-title")
for post in post_elems:
print post.text
Output:
When Your Mother Says She’s Fat
When “Life Hacking” Is Really White Privilege
As tendências culturais dos anos 2000 adiantadas pelo É o Tchan na década de 90
Coming Out as Biracial
Como ganhar discussões com seus parentes de direita neste Natal
How to save local bookstores in two easy steps
Welcome to Dinovember
How to Piss Off Your Barista
The boy whose brain could unlock autism
CrossFit’s Dirty Little Secret
Welcome to Medium
Here’s How the Military Wasted Your Money in 2013
Why I Wear Nail Polish
The day of High School I’ll never forget
7 Reasons Buffalonians Shouldn’t Hate Snow
Dear Guy Who Just Made My Burrito:
Is the Mona Lisa Priceless?
Please stop live tweeting people’s private conversations
Your Friends and Rapists
Eight things you can live without
The Value of Content
40 Ways To Make Life Simple Again
Manila-Beijing-Washington:
Things I Wish Someone Had Told Me When I Was Learning How to Code
Dear Ticketmaster,
Steve Jobs Danced To My Song
11 Things I Wish I Knew When I Started My Business
Bullish: Benevolent Sexism and “That Guy” Who Makes Everything Awkward
Advice to a College Music Student
Silver Gyninen joutui sotaan
Imagining the Post-Antibiotics Future
Which side are you on?
Put it away, junior.
Casual Predation
The sad little iPhone commercial
How Node.js is Going to Replace JavaScript
Why you should have your heart broken into a million little pieces.
How to Write Emails Like a CEO
Designing Products That Scale
How radioactive poison became the assassin’s weapon of choice
Why do people hate CrossFit?
We (Still) Need Feminism
10 Advanced Hearthstone Arena Tips
Let It Full-Bleed
What Medium Is For
How a Small Force of Finnish Ski Troops Fought Off a Massive Soviet Army
An Introvert’s Guide to Better Presentations
Mandela The Terrorist
Why You Should have a Messy Desk
Why I’m Not a TEDx Speaker
Fonts have feelings too
You Don’t Want Your Thanksgiving to Go Like This
What I’ve Learned in My First Month as a VC
Why Quantity Should be Your Priority
My Airbnb story
I Wanna Date You Like An Animal
The GIF Guide to Getting Paid
How We Discovered the Underground Chinese App Market
First Images of a Heart Injected with Liquid Metal
Beyonce Broke the Music Business
“View mode” approach to responsive web design
Sometimes You Will Forget Your Mom Has Cancer
Darkness Ray Beams Invisibility From A Distance
Why Work As We Know It May Be Immoral
Staying Ahead of the Curve
The Geekiest Game Ever Made Has Been Released In Germany
The Dirty Secret Behind the Salesforce $1M Hackathon
I’m a really good impostor
Mathematical Model of Zombie Epidemics Reveals Two Types of Living-Dead Infections
The Heartbreak Kid
200 Things
I’m Not Racist But—
Duel of the Superbattleships
23 and You
The Seattle NO
I’m a vaccine refuser. There, I said it.
The Year We Broke Everything
How to make a DIY home alarm system with a raspberry pi and a webcam
Strike While the App is Hot
How to Fall In (and Out) of Love:
Why did Google make an ad for promoting “Search” in India where it has over 97% market share?
A Holiday Message From Jesus
Revealed: The Soviet Union’s $1 Billion ‘Psychotronic’ Arms Race with the US
Postmortem of a Venture-backed Startup
The 1.x Crore Myth
The “Getting Shit Done” Sleep Cycle
Is the F-35 Joint Strike Fighter the New F-4?
Can the F-35 Win a Dogfight?
Responsive Photosets
Fightball: Millennials vs Boomers
The iconicity of “peaceful resistance”
How We Make Chocolate
Five Ships of the Chinese Navy You Really Ought to Know About
Glassholes and Black Rock City
Bad News for U.S. Warplane Pilots: Russia’s New Dogfighting Missile Can’t Miss
How Antisec Died
10 ways you’ll probably f**k up your startup
UPDATED: Finding the unjustly homeless, and teaching them to code.
Technology hasn’t Changed Us.
What I’ve learned from fatherhood
|
Sending an Email with Python Issue
Question: I have this code and I cannot seem to get it to work. When I run it, the
script doesn't finish in IDLE unless I kill it manually. I have looked all
over and rewritten the code a few times, and no luck.
import smtplib
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = '[email protected]'
password = '123'
recipient = '[email protected]'
subject = 'Test Results'
body = """** AUTOMATED EMAIL ** \r\n Following are
the test results: \r\n"""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient]
headers = "\r\n".join(headers)
try:
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
except smtplib.SMTPException:
print "Error: Unable to send email."
session.quit()
Answer: Not sure why you're using `ehlo`; contrary to popular opinion, it's not
actually required so long as you set the headers correctly. Here's a tested
and working script -- it works on *nix and OSX. Since you're using Windows
though, we need to troubleshoot further.
import smtplib, sys
def notify(fromname, fromemail, toname, toemail, subject, body, password):
fromaddr = fromname+" <"+fromemail+">"
toaddrs = [toname+" <"+toemail+">"]
msg = "From: "+fromaddr+"\nTo: "+toemail+"\nMIME-Version: 1.0\nContent-type: text/plain\nSubject: "+subject+"\n"+body
# Credentials (if needed)
username = fromemail
password = password
# The actual mail send
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print "success"
except smtplib.SMTPException:
print "failure"
fromname = "Your Name"
fromemail = "[email protected]"
toname = "Recipient"
toemail = "[email protected]"
subject = "Test Mail"
body = "Body....."
notify(fromname, fromemail, toname, toemail, subject, body, password)
|
C DLL to Python Callback
Question: I have a Visual C++ DLL. I have a SetCallback( function-pointer) exported in
the DLL. I use this function to set a callback function from a python2.7
script. I follow what is given in the Python documentation.
from ctypes import *
def mypy_callback(number):
print str(number)
d = cdll.LoadLibrary(r"myfunctions.dll")
callback_type = CFUNCTYPE(None, c_int )
d.SetCallback(callback_type(mypy_callback))
In the C code I have
typedef void (*callback_function)(int);
void SetCallback(callback_function aCallback)
{
py_callback = aCallback;
}
When I call this function from C DLL, like so: py_callback(999), python just
crashes. What could I be doing wrong?
Answer: The following callback indirection will solve this problem:
d = cdll.LoadLibrary(r"myfunctions.dll")
callback_type = CFUNCTYPE(None, c_int )
callback = callback_type(mypy_callback)
d.SetCallback(callback)
|
Is it possible to emit valid YAML with anchors / references disabled using Ruby or Python?
Question: Is it possible to disable creating anchors and references (and effectively
list redundant data explicitly) either in `PyYAML` or Ruby's `Psych` engine?
Perhaps I missed something while searching the web, but it seems there are not
many options available in `Psych` and I was not able to determine if `PyYAML`
allows for that either.
The rationale is I have to serialize some data and pass it in a readable form
to a not-really-technical co-worker for manual validation. Some data is
redundant but I need it listed in a most explicit manner for readability
(anchors and references are a nice concept for efficiency, but not for human-
readability).
Ruby and Python are my tools of choice, but if there is some other reasonably
simple way of 'unfolding' YAML documents, it might just do.
Answer: I found this related ticket on the PyYAML website
(<http://pyyaml.org/ticket/91>), it looks like anchors can be disabled by
using a custom dumper along the lines of:
import yaml
class ExplicitDumper(yaml.SafeDumper):
"""
A dumper that will never emit aliases.
"""
def ignore_aliases(self, data):
return True
So, for example, the following outputs can be achieved using the standard
dumper and the new explicit dumper:
>>> yaml.dump([1L, 1L])
"[&id001 !!python/long '1', *id001]\n"
>>> yaml.dump([1L, 1L], Dumper=ExplicitDumper)
'[1, 1]\n'
You can customise further properties to ensure pretty-printing etc. in the
`yaml.dump(...)` call.
|
Import python packages that have similar internal module names, by full path
Question: In my project I need to import two external packages from two different full
paths.
When I had only one external package, I added its path to `sys.path` and it
worked, I could do that for both of the package but unfortunately both
packages have similar internal modules, so if I add them both to `sys.path`
they will cross import internal modules from each other.
To clarify, the folder structure of the packages looks like this:
package1\
__init__.py
settings.py
a.py # does 'import settings'
package2\
__init__.py
settings.py
b.py # also does 'import settings'
How can I import both packages without conflicts? I've tried using
`imp.load_source` but it looks like it can only load files.
**Edit:** When I only had one package, I would import from it using the
following code:
sys.path.insert(1, "PATH TO PACKAGE1")
from package1 import a
**Edit 2:** The directory structure of the packages is actually much more
complicated than the one in the one above, and contains hundreds of files.
There are also internal modules that may import `settings.py`, for example:
package1\
__init__.py
settings.py
internal_module\
__init__.py
a.py # does 'import settings'
This means I can't assume that `a.py` and `settings.py` are in the same
directory.
Answer: if you import settings in package1/a.py, python will look for settings.py
first in the current director i.e package1 and not package2 even if they both
are in sys.path. So even if you import as (based on the directory structure
you have shown above) assuming you have added pacakge1 and package2 in
sys.path:
from package1 import a
from package2 import b
This is going to work without any problem and a.py will import setttings
module from package1 and b.py will import the settings from package2.
If you have modules with same name both in package1 and package2, then the
good way to do the imports is
import package1.settings as package1_settings
import package2.settings as package2_settings
Now you can access your variables in package1_settings and package2_settings
as
package1_settings.var1
package2_settings.var1
All this will work if you have added the absolute path to "package1" and
"package2" to sys.path:
sys.path.append(os.path.abspath("package1")) # something like that
Here is a little experiment I did:
The package structure is:
package1
__init__.py
a.py
settings.py
package2
__init__.py
b.py
settings.py
test.py
a.py
import settings
def print_a():
print settings.a
b.py
import settings
def print_a():
print settings.a
package1.settings.py
a = "settings.py in package1"
package2.settings.py
a = "settings.py in package2"
test.py
import sys
import os
dir_name = os.path.abspath(os.path.dirname("__file__"))
package1_path = os.path.join(dir_name, "package1")
package2_path = os.path.join(dir_name, "package2")
sys.path.append(package1_path)
sys.path.append(package2_path)
from package1 import a
from package2 import b
a.print_a()
b.print_a()
Output of "python test.py"
>>> python test.py
settings.py in package1
settings.py in package2
**Edit** For such cases, the good practice is
> Always reference your imports from your top level package
You will add package1 and package2 to your sys.path and reference all your
imports from them.
import package1.settings as package1_settings
import package1.internal_module.a as package1_internal_module_a #give a shorter name
import package1.internal_module.other_module.settings as package1_internal_other_settings
This way it can be ensured that your import paths never collide with each
other. One other advantage of this is portability of your package. Tomorrow if
you decide to change the location of package1, all the code in your package1
would just work because all your imports are referenced from package1.
|
how to fix "AttributeError: 'module' object has no attribute 'set_binary' "?
Question: i compiled mercurial successfully as follows: ...
copying build/scripts-2.7/hg -> /usr/local/bin
changing mode of /usr/local/bin/hg to 755
running install_egg_info
Writing /usr/local/lib/python2.7/site-packages/mercurial-2.8.1-py2.7.egg-info
as3:~/mercurial-2.8.1# cd ~
as3:~# hg clone http://hg.cat-v.org/werc/
Traceback (most recent call last):
File "/usr/bin/hg", line 25, in <module>
mercurial.util.set_binary(fp)
File "/usr/local/lib/python2.7/site-packages/mercurial/demandimport.py", line 103, in __getattribute__
return getattr(self._module, attr)
AttributeError: 'module' object has no attribute 'set_binary'
as3:~#
how to fix it?tks. my python version:2.7.6
Answer: Note that you have installed mercurial from sources into `/usr/local/bin`, but
the error message mentions `/usr/bin/hg`. It means you have a different
version of mercurial main script installed under `/usr/bin/hg`, which then
tries to use new mercurial library from `/usr/local`. The error occurs,
because the 2 are incompatible.
To fix this, remove older mercurial from `/usr/bin`. You may need to call
`rehash` in your shell as well, for it to pick it up, depending on the shell.
If mercurial does not work then, it means `/usr/local/bin` is not in your
PATH. If that is the case you'll need to fix the PATH, or just symlink new hg,
like so:
# ln -s /usr/local/bin/hg /usr/bin
But that will require root access, for example, calling it through sudo.
|
How to ZIP an Excel file using python?
Question: How can I zip a excel file using python ? I have a excel sheet. I want to
change ZIP the excel Sheet Using Python. So that It can have less network
usages when I try to download from mine Site. Just Another Requirements.
Thanks in Advance.
Please Help
Answer: Python's built in zipfile library can be used to compress any file. Below code
should work for you.
#!/usr/bin/env python3
import zipfile
zip_file = zipfile.ZipFile('file_name.zip', 'w')
zip_file.write('/tmp/hello.txt')
zip_file.close()
|
How to get input of arguments from the terminal along with the filename in python?
Question: For example if I want to compare two numbers(compare which is greater, for
example) and get this input from the terminal in linux along with the
filename.
Like:
python myfilename.py 2 3
This program should output 3. I think that this can be done with the help of
sys module.
Answer: Use `sys.argv` like in:
import sys
print sys.argv
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.