text
stringlengths 226
34.5k
|
---|
Python Reportlab - Unable to print special characters
Question: `Python Reportlab`:
I am facing problem while printing special characters in my `pdf` like `"&"`
# -*- coding: utf-8 -*-
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch
styles = getSampleStyleSheet()
def myFirstPage(canvas, doc):
canvas.saveState()
def go():
doc = SimpleDocTemplate("phello.pdf")
Story = [Spacer(1,2*inch)]
Story.append(Paragraph("Some text", styles["Normal"]))
Story.append(Paragraph("Some other text with &", styles["Normal"]))
doc.build(Story, onFirstPage=myFirstPage)
go()
I Expected following output
Some text
Some other text with &
But the output I get is
Some text
Some other text with
Where did '&' get vanished.
I have searched some forums which say that I need to encode it as `&` but
is there not easier way to handle this than encoding each special character?
I have added `"# -*- coding: utf-8 -*-"` at the top of my script but that does
not solve my problem
Answer: You should replace &, < and > with the &, < and >. One easy way to do that is
the Python escape function:
from cgi import escape
Story.append(Paragraph(escape("Some other text with &"), styles["Normal"]))
However, HTML tags need to have real < and > so a typical use would be more
like:
text = "Some other text with &"
Story.append(Paragraph(escape("<b>" + text + "</b>"), styles["Normal"]))
|
Python Jenkins API does not allow to queue several jobs at once. Is there a way to work around the restriction?
Question: There is a parametrized job in my Jenkins server. I would like to initiate
several builds of the job with different parameters using Python Jenkins API.
This is completely legitimate in Jenkins. If I call 'invoke' method of the
same job instance several times, the API starts only the first build and
rejects to queue another builds because it considers that the job is already
in the queue.
I am using Python Jenkins API version 0.2.14. This is the latest version of
the API on the current moment. I have taken a look into the Jenkins API source
code and it really restricts to invoke a new build until there is another job
in the queue (job.py: lines 104,105):
if self.is_queued():
raise WillNotBuild('%s is already queued' % repr(self))
Is there a way to get over the restriction? I have found some way (see the
sample below), but I am not sure it is the best way to do it. Maybe there are
different solutions. I would like to know about these solutions if there are
ones.
In my solution I have created a subclass `ParameterizedJob` of the original
`jenkinsapi.job.Job` class and I have overridden four methods: `__init__`,
`invoke`, `is_queued`, `is_queued_or_running`. I have instantiated a job
object from my class instead of calling get_job method from the Jenkins
instance. This approach works fine for me.
import jenkinsapi
from jenkinsapi.job import Job
class ParametrizedJob(Job):
def __init__(self, jobname, jenkins_instance):
self._allowQueuingMultipleBuilds = False
jobExists = False
for info in jenkins_instance._data["jobs"]:
if info["name"] == jobname:
Job.__init__(self, info["url"], info["name"], jenkins_obj=jenkins_instance)
jobExists = True
break
if not jobExists:
raise UnknownJob(jobname)
def invoke(self, securitytoken=None, block=False, skip_if_running=False, invoke_pre_check_delay=3, invoke_block_delay=15, build_params=None, cause=None):
self._allowQueuingMultipleBuilds = True
try:
Job.invoke(self, securitytoken, block, skip_if_running, invoke_pre_check_delay, invoke_block_delay, build_params, cause)
except:
raise
finally:
self._allowQueuingMultipleBuilds = False
def is_queued_or_running(self):
if not self._allowQueuingMultipleBuilds:
return Job.is_queued_or_running(self)
else:
return False
def is_queued(self):
if not self._allowQueuingMultipleBuilds:
return Job.is_queued(self)
else:
return False
def startJenkinsJob(jenkinsInstance, jobName, parameters):
#targetJob = jenkinsInstance.get_job(jobName)
targetJob = ParametrizedJob(jobName, jenkinsInstance)
targetJob.invoke(securitytoken='TOKEN', build_params=parameters, block=True)
return
Answer: You can not schedule the same job several times through the UI either.
Exception is, if you have a parametrized job, and both starts have different
parameters.
|
Can't set up neo4jDjango graph database: object has no attribute 'db_type'
Question: I'm starting a project and I keep getting this error when executing the
manage.py sql *ApplicationName*
The trace back is as follows:
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 304, in handle
app_output = self.handle_app(app, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/sql.py", line 19, in handle_app
return u'\n'.join(sql_create(app, self.style, connections[options.get('database')])).encode('utf-8')
File "/usr/lib/python2.7/site-packages/django/core/management/sql.py", line 31, in sql_create
output, references = connection.creation.sql_create_model(model, style, known_models)
File "/usr/lib/python2.7/site-packages/django/db/backends/creation.py", line 44, in sql_create_model
col_type = f.db_type(connection=self.connection)
File "/usr/lib/python2.7/site-packages/neo4django/utils.py", line 161, in __getattr__
return getattr(super(AttrRouter, self), name)
AttributeError: 'super' object has no attribute 'db_type'
The code is pretty much a simple example of the tutorial after many attempts
to try to solve the problem.
The setings.py are also supposed to be correct, since they are copied from
neo4Django tutorial.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'Database.db',
}
}
NEO4J_DATABASES = {
'default' : {
'HOST':'localhost',
'PORT':7474,
'ENDPOINT':'/db/data'
}
}
DATABASE_ROUTERS = ['neo4django.utils.Neo4djangoIntegrationRouter']
Neo4j server is running, and in the sqllite and also in a mysql database
things are working, so the problem must be on the neo4j or neo4django side.
Also things work when not using neo4Django models in the domain.
The model is as presented:
from neo4django.db import models
class Person(models.NodeModel):
name = models.StringProperty()
age = models.IntegerProperty()
friends = models.Relationship('self',rel_type='friends_with')
Answer: The `manage.py sql appname` command _(copied from the django documentation)_
> Prints the CREATE TABLE SQL statements for the given app name(s).
So If you are going to use `Νeo4j` and not `MySQL` or `SQLite`, there is no
need to get the CREATE TABLE SQL statements. Besides that you probably would
like to better run the `syncdb` command, but once more you are not using a
relational db, but `Neo4j`, so you don't need to run neither.
The only reason you should include a db at the `DATABASES` declaration on your
`settings.py` is just because, if you don't, an `ImproperlyConfigured` error
will be raised.
So the simple answer is that the error is correct, just don't run any
Relational db related django command.
One more tip, don't use the pypi package but the github version
<https://github.com/scholrly/neo4django> (`pip install -e
git+https://github.com/scholrly/neo4django/#egg=neo4django`)
|
Round timestamp to nearest day in Python
Question: In Python 2.7.2 I am getting the seconds since epoch using:
`sec_since_epoch = (date_obj - datetime(1970, 1, 1, 0, 0)).total_seconds()`
Now I want to round these seconds to the nearest day e.g. if:
`datetime.fromtimestamp(sec_since_epoch)`
corresponds to `datetime(2013, 12, 14, 5, 0, 0)`
I want the new timestamp to correspond to `datetime(2013, 12, 14, 0, 0, 0)`
I know the ugly way of doing it, but is there an elegant way ?
Answer: You can use `datetime.timetuple()` to manipulate with the date. E.g. in this
way:
from datetime import datetime
dt = datetime(2013, 12, 14, 5, 0, 0)
dt = datetime(*dt.timetuple()[:3]) # 2013-12-14 00:00:00
print dt.strftime('%s') # 1386997200
[**DEMO**](http://codepad.org/7vpTqE1O)
|
Python: Pixel values in image display?
Question: Using any of the numpy, scikit-image libraries, I can easily load and display
an image as an ndarray. However, I'd like some sort of display where I can
move the cursor around the image, and see the indices of the current pixel,
and its gray (or RGB) values, for example: (213,47: 178) or (213,47:
122,10,205) - these values of course constantly changing as the cursor moves.
Is there an easy way to do this? Oh: I'm using Linux, but my students will be
using Windows, so I'm hoping for a cross-platform solution.
Answer: I am using `tkinter` for displaying and `PIL` for reading any image kind. It
is a veeerryyy slow solution.
def pil2tkinter_image(img_path, master = None, *args, **kw):
import tkinter, PIL.Image
img = PIL.Image.open(img_path)
x0, y0, width, height = img.getbbox()
l = []
for y in range(y0, height):
l.append('{')
for x in range(x0, width):
l.append('#%02X%02X%02X' % img.getpixel((x, y))[:3])
l.append('}')
data = ' '.join(l) # slow part
pi = tkinter.PhotoImage(master = master, *args, **kw)
pi.put(data, (0,0))
return pi
The function `pil2tkinter_image` takes a path to an image of any kind, png,
bmp, jpg, gif and creates a tkinter PhotoImage out of it.
You can embed this Image in a tkinter Widget and use mouse events to read the
pixel values.
|
why telnetlib write function not working in my python code?
Question: I was learning python for a few weeks, I was trying to build a chat app, I
chose twisted and felt comfortable with it, but I run into a strange problem
in client tesing code.
Here is my server code:
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class ChatServer(LineReceiver):
def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"
def connectionMade(self):
self.sendLine("What's your name?")
print 'DEBUG: Name Input Request Send Back To Client.'
def connectionLost(self, reason):
if self.users.has_key(self.name):
del self.users[self.name]
def lineReceived(self, line):
print 'DEBUG: A Message Recieved From Client.'
if self.state == "GETNAME":
self.handle_GETNAME(line)
else:
self.handle_CHAT(line)
def handle_GETNAME(self, name):
if self.users.has_key(name):
self.sendLine("Name taken, please choose another.")
return
self.sendLine("Welcome, %s!" % (name,))
print 'DEBUG: Welcome Message Send Back To Client.'
self.name = name
self.users[name] = self
self.state = "CHAT"
def handle_CHAT(self, message):
message = "<%s> %s" % (self.name, message)
for name, protocol in self.users.iteritems():
if protocol != self:
protocol.sendLine(message)
class ChatServerFactory(Factory):
def __init__(self):
self.users = {}
def buildProtocol(self, addr):
return ChatServer(self.users)
reactor.listenTCP(8123, ChatServerFactory())
reactor.run()
and this is my client testing code, I tried to test server in telnet way.
import telnetlib
import cmd
import sys
import time
def test_telnet(Host, Port):
# connected to the server
tn = telnetlib.Telnet(Host, Port)
print 'Client Connecton Made.'
# tn.set_debuglevel(2)
# read back from server
greeting = tn.read_until("What's your name?")
print 'Recieved Name Input Request From Server'
print greeting
print "DEBUG: Before telnet write data"
username = 'amber'
tn.write(username + '\n')
print "DEBUG: After telnet write data"
# welcome = tn.read_until('see', 5)
# print 'Recieved Welcome Message From Server'
# print welcome
time.sleep(7)
tn.write("exit\n")
print 'Client Connection Lost.'
test_telnet('localhost', 8123)
However, tn.write() send message, but in server console, I noticed that
lineReceived is never get called, but in real telnet, it's called, why is
that? Many thanks!
Answer: [`LineReceiver`](http://twistedmatrix.com/documents/current/api/twisted.protocols.basic.LineReceiver.html)
expects lines end with
[`\r\n`](http://twistedmatrix.com/documents/current/api/twisted.protocols.basic.LineReceiver.html#delimiter),
not `\n`.
Replacing `\n` in the code with `\r\n` solves the problem.
* * *
Alternatively you can change the line delimiter:
class ChatServer(LineReceiver):
delimiter = '\n' # <----
...
|
Why am I getting repetitive output while trying to scrape data from Google Scholar?
Question: I am trying to scrape the PDF links from the search results from Google
Scholar. I have tried to set a page counter based on the change in URL, but
after the first eight output links, I am getting repetitive links as output.
#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup
import urllib2
import requests
#modifying the url as per page
urlCounter = 0
while urlCounter <=30:
urlPart1 = "http://scholar.google.com/scholar?start="
urlPart2 = "&q=%22entity+resolution%22&hl=en&as_sdt=0,4"
url = urlPart1 + str(urlCounter) + urlPart2
page = urllib2.Request(url,None,{"User-Agent":"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"})
resp = urllib2.urlopen(page)
html = resp.read()
soup = BeautifulSoup(html)
urlCounter = urlCounter + 10
recordCount = 0
while recordCount <=9:
recordPart1 = "gs_ggsW"
finRecord = recordPart1 + str(recordCount)
recordCount = recordCount+1
#printing the links
for link in soup.find_all('div', id = finRecord):
linkstring = str(link)
soup1 = BeautifulSoup(linkstring)
for link in soup1.find_all('a'):
print(link.get('href'))
Answer: Change the following line in your code:
finRecord = recordPart1 + str(recordCount)
To
finRecord = recordPart1 + str(recordCount+urlCounter-10)
The real problem: div ids in the first page are gs_ggsW[0-9], but ids on the
second page are gs_ggsW[10-19]. So beautiful soup will find no links on the
2nd page.
Python's variable scope may confuse people from other languages, like Java.
After the for loop below being executed, the variable `link` still exists. So
the link is referenced to the last link on the 1st page.
for link in soup1.find_all('a'):
print(link.get('href'))
* * *
Updates:
Google may not provide pdf download links for some papers, so you can't use id
to match the link of each paper. You can use css selecters to match all the
links together.
soup = BeautifulSoup(html)
urlCounter = urlCounter + 10
for link in soup.select('div.gs_ttss a'):
print(link.get('href'))
|
Segfault 11 with pandas with Python v2.7.6 RC1 on Mac OS X 10.9
Question:
In [1]: import json
In [2]: path = 'ch02/usagov_bitly_data2012-03-16-1331923249.txt'
In [3]: from pandas import DataFrame, Series;
In [4]: records = [json.loads(line) for line in open(path)]
In [5]: frame = DataFrame(records)
In [6]: frame['tz'][:10]
Segmentation fault: 11
Any access to frame results in a segfault. I have already upgraded to Python
2.7.6 RC1. Also happened in 2.7.5, also happens outside ipython. What am I to
do?
Answer: This appears to be a bug in Numpy that has been fixed recently. See
<https://github.com/numpy/numpy/issues/3962>
|
Nonblocking client-server in python
Question: I have been coding a blocking client-server in python. how can I change it to
nonblocking without thread?
Answer: Check out the [asyncore](http://docs.python.org/2/library/asyncore.html) and
[asynchat](http://docs.python.org/2/library/asynchat.html) Python modules.
Here's a basic echo server (taken from the asyncore documentation):
import asyncore
import socket
class EchoHandler(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(8192)
if data:
self.send(data)
class EchoServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
handler = EchoHandler(sock)
server = EchoServer('localhost', 8080)
asyncore.loop()
|
Python: Get caret position
Question: I'm trying to get the caret position in Python. I tried using
`win32gui.GetCaretPos()` but it always returns 0,0.
Do you have any ideas how to make it work?
Thanks Chris
Answer: If the caret is in a window created by another thread, you need to call
[`AttachThreadInput`](http://msdn.microsoft.com/en-
us/library/windows/desktop/ms681956%28v=vs.85%29.aspx). Assuming you want the
caret of the foreground window, you can get to it like this:
import win32gui
import win32process
import win32api
fg_win = win32gui.GetForegroundWindow()
fg_thread, fg_process = win32process.GetWindowThreadProcessId(fg_win)
current_thread = win32api.GetCurrentThreadId()
win32process.AttachThreadInput(current_thread, fg_thread, True)
try:
print win32gui.GetCaretPos()
finally:
win32process.AttachThreadInput(current_thread, fg_thread, False) #detach
|
Python function always returns false when comparing to ints
Question:
from pip.backwardcompat import raw_input
from PFD import *
def getInput():
try:
n = raw_input("Please enter the file size: ")
int(n)
print(str(n))
order = raw_input("Please enter a Fib Order [3/4]: ")
int(order)
except ValueError:
getInput()
if order == 3:
Fib.three(n)
elif order == 4:
Fib.four(n)
else:
print("You did something wrong, idiot.")
getInput()
getInput();
So this is the problem. No matter what I do, it tells me I did something wrong
and calls me an idiot. :(
Answer: Your line
int(order)
needs to be assigned back to the order variable like so:
order = int(order)
edit: As alKid pointed out, the same for n:
n = int(n)
|
How to Calculate Dry and Wet Spell in Python?
Question: I have a random time series data with four columns like: year, month, day,
precipitation. I want to calculate dry/wet spell for different spell-length. I
am looking for a more convenient way to do that while currently doing with
some ugly codes like below:
import numpy as np
data = np.loadtxt('Data Series.txt', usecols=(1,3))
dry = np.zeros(12)
wet = np.zeros(12)
rows,cols = data.shape #reading number of rows and columns into variables
for i in xrange (0,rows):
for m in xrange(0,12):
if data[i,1] == 0 and data[i-1,1] == 0 and data[i-2,1] == 0:
if data[i,0] == m+1:
dry[m] += 1.0
if data[i,1] > 0 and data[i-1,1] > 0 and data[i-2,1] > 0:
if data[i,0] == m+1:
wet[m] += 1.0
print '3 Days Dry Spell\n', dry
print '3 Days Wet Spell\n', wet
Now, if I want to calculate the 4,5,6 days spells, than "if data[i,1] == 0 and
data[i-1,1] == 0....." becomes a huge one. Can anyone please help me so that I
may give the spell-length only instead of this long-ugly line?
Answer: You may want to try something like this:
# first extract precipitation data for later use
precipitation = [data[i][1] for i in xrange(0, rows)]
# then test the range (i, i+m)
all_dry = all([(data==0) for data in precipitation[i:i+m]])
all_wet = not any([(data==0) for data in precipitation[i:i+m]])
# of course you can also use
all_wet = all([(data>0) for data in precipitation[i:i+m]])
However please notice this method introduces redundant calculations when
testing adjacent days, and thus may be not suitable for processing a large
amount of data.
**EDITED:**
Okay this time let us look for a more efficient method.
# still extract precipitation data for later use first
precipitation = [data[i][1] for i in xrange(0, rows)]
# let's start our calculations by counting the longest consecutive dry days
consecutive_dry = [1 if data == 0 else 0 for data in precipitation]
for i in xrange(1, len(consecutive_dry))
if consecutive_dry[i] == 1:
consecutive_dry[i] += consecutive_dry[i - 1]
# then you will see, if till day i there're m consecutive dry days, then:
consecutive_dry[i] >= m # here is the test
# ...and it would be same for wet day testings.
This is obviously more efficient then the method above: for testing a total of
N days with M consecutive range, the previous one requires O(N * M) operations
to calculate and this one requires O(N).
**AGAIN EDITED:**
This is an edited version of your original code. As your code could run, this
shall also run on your PC or what.
import numpy as np
data = np.loadtxt('Data Series.txt', usecols=(1,3))
dry = np.zeros(12)
wet = np.zeros(12)
rows,cols = data.shape #reading number of rows and columns into variables
# prepare
precipitation = [data[i][1] for i in xrange(0, rows)]
# collecting data for consecutive dry days
consecutive_dry = [1 if data == 0 else 1 for data in precipitation]
for i in xrange(1, len(consecutive_dry))
if consecutive_dry[i] == 1:
consecutive_dry[i] += consecutive_dry[i - 1]
# ...and for wet days
consecutive_wet = [1 if data > 0 else 0 for data in precipitation]
for i in xrange(1, len(consecutive_wet))
if consecutive_wet[i] == 1:
consecutive_wet[i] += consecutive_wet[i - 1]
# set your day range here.
day_range = 3
for i in xrange (0,rows):
if consecutive_dry[i] >= day_range:
month_id = data[i,0]
dry[month_id - 1] += 1
if consecutive_wet[i] >= day_range:
month_id = data[i,0]
wet[month_id - 1] += 1
print '3 Days Dry Spell\n', dry
print '3 Days Wet Spell\n', wet
Please try this and let me know if there're any problems.
|
How do I calculate how many hashes I need in order to find a collision?
Question: I'm working on a program that hashes image URLs to a 10 character string using
hexadecimal characters, e.g. 64fd54ad29.
It's written in Python, and the hash is calculated like this:
def hash_short(self, url):
return hashlib.sha1(url).hexdigest()[:10]
I'm concerned about collisions with such a short hash. I expected a collision
after around one million hashes, but I required ten million hashes when I ran
a brute force.
## Calculations
A hexadecimal digit has 16 possible values, or 2^4. With ten characters I have
2^40 possibilities, or 40 bits of entropy.
To have a probability of 1, we'd need to look at 2^40 + 1 URLs (by the
pigeonhole principle), but we would expect a collision much sooner.
A birthday attack (i.e. a bruteforce) of a n-bit hash will find a collision
after 2^(n/2) attempts. Therefore we'll see a collision after around 2^20
URLs, which is 1,048,576.
## Brute forcing
I wrote a simple Python script that iterated over a long list of URLs and
compared each hash to those I'd seen before. It took me 10,800,000 URLs to
find my first collision:
`"http://c69025.r25.cf3.rackcdn.com/_image1/_Model/34897.jpg"` and
`"http://media.editd.com/assets/matrix/full/72f9a997b67c65c66f4adc769ee0a127d1db25eb.jpg"`
both hash to `"ba2be44bd1"`.
import hashlib
import json
def calculate_short_hash(url):
return hashlib.sha1(url).hexdigest()[:10]
def url_from_json(json_string):
return json.loads(json_string)['image_url']
if __name__ == '__main__':
short_hashes = set()
for i, line in enumerate(open('urls.all')):
short_hash = calculate_short_hash(url_from_json(line))
if short_hash in short_hashes:
print "Already seen: %s" % short_hash
break
else:
short_hashes.add(short_hash)
if i % 100000 == 0:
print "Processed %d lines" % (i,)
## Summary
Either my maths is incorrect or I was very unlucky. Which is it? How unlucky
was I?
Answer: I think your collision detection code is wrong:
import hashlib
import random
import string
def hash_short(url):
return hashlib.sha1(url).hexdigest()[:10]
hashes = dict()
while True:
if len(hashes) % 10000 == 0:
print len(hashes)
newurl = ''.join(random.choice(string.lowercase) for _ in xrange(30))
newhash = hash_short(newurl)
if newhash in hashes and newurl != hashes[newhash]:
print 'found a collision!'
print newhash
print newurl
print hashes[newhash]
print len(hashes)
break
hashes[newhash] = newurl
Output (run once):
...
770000
780000
found a collision!
216be03ec7
txnbkwrfkpkmiexloxrifdsnjumkex
xlnmlhobtsswjvmqnjupaybkspptpo
780758
Obviously my so-called urls aren't, but that _should_ make no difference with
a good hash function (and SHA1 is good for this purpose). If you've found a
dataset that genuinely has an unusually low rate of collisions on the first 5
bytes of SHA1 then well done! Try it again with the last 5 bytes :-)
How unlucky were you? By the time you have 10 million hashes, your `2**40`
space is full to about one part in 100k. So the probability of no collision is
roughly (finger in the air), `(99999.0/100000) ** 10 million`, which is
`3.7e-44`. So if my maths is correct [Edit: which it isn't, see comments] you
were astronomically, convicted-beyond-reasonable-doubt unlucky.
As a conservative upper bound on the probability of getting no collision by
chance, you did 9 million trials after there were 1 million hashes already in
play. The probability of no collisions is strictly less than `(999999.0 /
1000000) ** 9000000`, which is only 0.0001. You could produce smaller such
bounds by splitting it up a bit further: you made 1 million trials with 9
million hashes occupied. Or you could compute the probability exactly (which
CodesInChaos did: `1e-20`)
So, Bayesian statistics being what it is, I reckon the probability of a bug in
your code is higher than all of those numbers, even the really large
conservative bound :-)
|
How to use iter function to loop through a list until a certain match is found
Question: I frankly don't understand how to use the
[`iter(o[,sentinel])`](http://docs.python.org/2/library/functions.html#iter)
function and I'm trying to loop through `lst` _(a list)_ and print all the
values until `'kdawg'`
Code:
lst = [2,3,4,'kdawg',5,6,'hey']
class foo:
def __str__(self):
return str(lst)
for i in iter(foo,'kdawg'):
print i
I expect it to return:
2
3
4
However it returns the whole list **continuously:**
[2,3,4,'kdawg',5,6,'hey']
Why doesn't my `iter()` function work?
Answer: Use
[`itertools.takewhile()`](http://docs.python.org/2/library/itertools.html#itertools.takewhile):
>>> from itertools import takewhile
>>>
>>> l = [2,3,4,'kdawg',5,6,'hey']
>>>
>>> for i in takewhile(lambda s: s != 'kdawg', l):
... print i
...
2
3
4
|
Google Map API Signature Generation in Python
Question: I'm basically doing the following:
<https://developers.google.com/maps/documentation/business/webservices/auth>
In Python 2.7.3 on my MacBook and on 2.7.5 on a Windows 64bit Server
environment I fail to reproduce the correct signature, while I follow the
original example exactly. I make a function like this:
import sys
import hashlib
import urllib
import hmac
import base64
import urlparse
def process_url(input_url, private_key):
print("URL To Sign: " + input_url)
url = urlparse.urlparse(input_url)
print("Private Key: " + private_key)
url_to_sign = url.path + "?" + url.query
print("Original Path + Query: " + url_to_sign)
decoded_key = base64.urlsafe_b64decode(private_key)
signature = hmac.new(decoded_key, url_to_sign, hashlib.sha1)
encodedSignature = base64.urlsafe_b64encode(signature.digest())
print("B64 Signature: " + encodedSignature)
original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query
full_url = original_url + "&signature=" + encodedSignature
print "Full URL: " + full_url
return full_url
Now this should give the following according to google:
* URL: [http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=](http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=){clientID}
* Private Key: vNIXE0xscrmjlyV-12Nj_BvUPaw=
* URL Portion to Sign: /maps/api/geocode/json?address=New+York&sensor=false&client={clientID}
* Signature: KrU1TzVQM7Ur0i8i7K3huiw3MsA=
* Full Signed URL: [http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=](http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=){clientID}&signature=KrU1TzVQM7Ur0i8i7K3huiw3MsA=
However, when I do the following:
process_url('http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client={clientID}', 'vNIXE0xscrmjlyV-12Nj_BvUPaw=')
I get:
* URL To Sign: [http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=](http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=){clientID}
* Private Key: vNIXE0xscrmjlyV-12Nj_BvUPaw=
* Original Path + Query: /maps/api/geocode/json?address=New+York&sensor=false&client={clientID}
* B64 Signature: WlcBIkr9WMB9uPhXWmAGcjG_2M4=
* Full URL: [http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=](http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=){clientID}&signature=WlcBIkr9WMB9uPhXWmAGcjG_2M4=
So I get "WlcBIkr9WMB9uPhXWmAGcjG_2M4=" and not
"KrU1TzVQM7Ur0i8i7K3huiw3MsA=". I swear this used to work, but I get this new
W-value consistently over different systems.
Does anyone have any clue what I'm doing wrong? Is the page incorrect or am I
doing something basic incorrect??
Answer: You are not doing anything wrong, you are signing different data thus getting
a different signature.
In the Google example, if you copy and paste you'll notice that the braces are
omitted in the clipboard; so it's signing the following URL:
http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client=clientID
But when you tried it, you copied it verbatim, including the curly braces:
http://maps.googleapis.com/maps/api/geocode/json?address=New+York&sensor=false&client={clientID}
So rejoice yourself, your code is right, the only problem is in the sample
data!
|
Parsing Nested JSON using Python
Question: This JSON output is from a MongoDB aggregate query. I essentially need to
parse the nested data JSON down to the following to the total and _id values.
{
'ok': 1.0,
'result': [
{
'total': 142250.0,
'_id': 'BC'
},
{
'total': 210.88999999999996,
'_id': 'USD'
},
{
'total': 1065600.0,
'_id': 'TK'
}
]
}
I've tried 5 different techniques to get what i need from it, however I've run
into issues using the json and simplejson modules.
Ideally, the output will be something like this:
142250.0, BC
210.88999999999996, USD
1065600.0, TK
Answer: NOTE: Your JSON response from MongoDB is not actually valid. JSON requires
double-quotes (`"`), not single-quotes (`'`).
I'm not sure why your response has single-quotes instead of double-quotes but
from the looks of it you can replace them and then just use the built-in
`json` module:
from __future__ import print_function
import json
response = """{
'ok': 1.0,
'result': [
{
'total': 142250.0,
'_id': 'BC'
},
{
'total': 210.88999999999996,
'_id': 'USD'
},
{
'total': 1065600.0,
'_id': 'TK'
}
]
}"""
# JSON requires double-quotes, not single-quotes.
response = response.replace("'", '"')
response = json.loads(response)
for doc in response['result']:
print(doc['_id'], doc['total'])
|
Bitmap fonts in SFML (OpenGL)
Question: I'm writting a simple bitmap font renderer in pySFML and wanted to ask is
there a better and faster way to approach this problem.
I'm using [VertexArray](http://www.python-sfml.org/api/graphics.html#id22) and
create a quad for each character in a string. Each quad has appropriate
texture coordinates applied.
Example font (PNG file): 
Font rendering code:
import sfml
class BitmapFont(object):
'''
Loads a bitmap font.
`chars` is string with all characters available in the font file, example: '+0123456789x'.
`widths` is mapping between characters and character width in pixels.
'''
def __init__(self, path, chars, widths, colors=1, kerning=0):
self.texture = sfml.Texture.from_file(path)
self.colors = colors
self.height = self.texture.height / self.colors
self.chars = chars
self.kerning = kerning
self.widths = widths
self.glyphs = []
y = 0
for color in range(self.colors):
x = 0
self.glyphs.append({})
for char in self.chars:
glyph_pos = x, y
glyph_size = self.widths[char], self.height
glyph = sfml.Rectangle(glyph_pos, glyph_size)
self.glyphs[color][char] = glyph
x += glyph.width
y += self.height
class BitmapText(sfml.TransformableDrawable):
'''Used to render text with `BitmapFonts`.'''
def __init__(self, string='', font=None, color=0, align='left', position=(0, 0)):
super().__init__()
self.vertices = sfml.VertexArray(sfml.PrimitiveType.QUADS, 4)
self.font = font
self.color = color
self._string = ''
self.string = string
self.position = position
@property
def string(self):
return self._string
@string.setter
def string(self, value):
'''Calculates new vertices each time string has changed.'''
# This function is slowest and probably can be optimized.
if value == self._string:
return
if len(value) != len(self._string):
self.vertices.resize(4 * len(value))
self._string = value
x = 0
y = 0
vertices = self.vertices
glyphs = self.font.glyphs[self.color]
for i, char in enumerate(self._string):
glyph = glyphs[char]
p = i * 4
vertices[p + 0].position = x, y
vertices[p + 1].position = x + glyph.width, y
vertices[p + 2].position = x + glyph.width, y + glyph.height
vertices[p + 3].position = x, y + glyph.height
vertices[p + 0].tex_coords = glyph.left, glyph.top
vertices[p + 1].tex_coords = glyph.right, glyph.top
vertices[p + 2].tex_coords = glyph.right, glyph.bottom
vertices[p + 3].tex_coords = glyph.left, glyph.bottom
x += glyph.width + self.font.kerning
def draw(self, target, states):
'''Draws whole string using texture from a font.'''
states.texture = self.font.texture
states.transform = self.transform
target.draw(self.vertices, states)
Simple benchmark with FPS counter:
from random import random, randint
import sfml
from font import BitmapFont, BitmapText
font = sfml.Font.from_file('arial.ttf')
bitmap_font = BitmapFont('font.png', chars='-x+0123456789 ', kerning=-3,
widths={'x': 21, '+': 18, '0': 18, '1': 14, '2': 18, '3': 18, '4': 19, '5': 18, '6': 18,
'7': 17, '8': 18, '9': 18, '-': 17, ' ': 8})
window = sfml.RenderWindow(sfml.VideoMode(960, 640), 'Font test')
fps_text = sfml.Text('', font, 18)
fps_text.position = 10, 10
fps_text.color = sfml.Color.WHITE
fps_text_shadow = sfml.Text('', font, 18)
fps_text_shadow.position = 12, 12
fps_text_shadow.color = sfml.Color.BLACK
frame = fps = frame_time = 0
clock = sfml.Clock()
texts = [BitmapText('x01234 56789', font=bitmap_font, color=randint(0, bitmap_font.colors - 1)) for i in range(1000)]
while window.is_open:
for event in window.events:
if type(event) is sfml.CloseEvent:
window.close()
time_delta = clock.restart().seconds
if time_delta > .2:
continue
frame_time += time_delta
if frame_time >= 1:
fps = frame
frame_time = frame = 0
fps_text_shadow.string = fps_text.string = 'FPS: {fps}'.format(fps=fps)
else:
frame += 1
window.clear(sfml.Color(63, 63, 63))
for t in texts:
t.position = random() * 960, random() * 640
t.string = str(randint(0, 10000000))
window.draw(t)
window.draw(fps_text_shadow)
window.draw(fps_text)
window.display()
I'm using Python 3.3, pySFML 1.3, SFML 2.0 and Windows.
Answer: Laurent Gomila (author of SFML) confirmed in [other forum](http://en.sfml-
dev.org/forums/index.php?topic=13455.0), that my approach to bitmap fonts is
same as vector fonts implementation in SFML (namely VertexArray and quad for
each character).
|
How do I preserve symlinks when unzipping an archive using Python?
Question: Many zip archives (especially those include OS X applications) contain
symlinks. When using the `zipfile.extractall` method, symlinks are turned into
regular files. Anyone know how to preserve them as links?
Answer: There seems to be no way to do this using the zipfile module. I solved it
using the subprocess module:
from subprocess import check_output, CalledProcessError, STDOUT
try:
check_output(['unzip', '-q', my_zipfile, '-d', destination], stderr=STDOUT)
...
except CalledProcessError as err:
(use err.cmd, err.returncode and err.output to take action)
|
Cannot bring any url in browser from PyCharm/selenium: http proxy responds regardless of settings
Question: I have Python 2.7.4 and selenium bindings (installed via "pip install
selenium") on Ubuntu 13.04 with Firefox 25. I have PyCharm Community Edition
3.0.1 I'm behind a proxy. I have a very simple python test, test_selenium.py:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("seleniumhq.org/")
When I try to run the above from PyCharm, a Firefox browser is brought up but
no url shows up in the location bar. Instead the following is displayed:
Traceback (most recent call last):
File "/home/nimbula/svn/nimbula/ui-selenium-tests/test-selenium.py", line 18, in <module>
browser = webdriver.Firefox()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 60, in __init__
desired_capabilities=capabilities)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 71, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 113, in start_session
'desiredCapabilities': desired_capabilities,
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 164, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 136, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: u'
The message is an html file that contains the following error:
The proxy could not connect to the destination in time. Please verify the site you are attempting to access and retry.\n </td>\n </tr>\n</table>\n<!--/Content-->\n\n<!--Info-->\n<table class="infoTable">\n <tr>\n <td class="infoData">\n <b>URL: </b><script type="text/javascript">break_line("http://127.0.0.1:51991/hub/session");</script>
Thus from the above it looks like selenium webdriver is trying to access
127.0.0.1:5199 but the proxy intercepts the call. I tried the following code:
from selenium import webdriver
PROXY_HOST = "<corp proxy>"
PROXY_PORT = 80
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", PROXY_HOST)
profile.set_preference("network.proxy.http_port", PROXY_PORT)
profile.set_preference("network.proxy.ftp", PROXY_HOST)
profile.set_preference("network.proxy.ftp_port", PROXY_PORT)
profile.set_preference("network.proxy.ssl", PROXY_HOST)
profile.set_preference("network.proxy.ssl_port", PROXY_PORT)
profile.set_preference("network.proxy.socks", PROXY_HOST)
profile.set_preference("network.proxy.socks_port", PROXY_PORT)
profile.set_preference("network.proxy.no_proxies_on", "127.0.0.1")
profile.update_preferences()
browser = webdriver.Firefox(firefox_profile=profile)
browser.get("seleniumhq.org/")
Still the same error is displayed. Since I have the browser window open, I
checked Networking settings and they are as specified in the python code: the
127.0.0.1 shows up in the "No proxy for" box. I also tried the following:
1. Set proxy to None in PyCharm -> Settings -> Http Proxy, execute code that does not set proxies.
2. Set proxy to "Use proxy" in PyCharm -> Settings -> Http Proxy, and specify all the required information with 127.0.0.1 in exceptions box.
None of the above worked. I also tried executing my script from command line.
It only works if I first execute "unset http_proxy" and then execute the
script without proxy settings. If I try with proxy settings, it does not work
again. I need to be able to run the tests from PyCharm. Thus my question is
two fold:
1. How do I force no proxy from PyCharm (the Settings->Proxy->None didn't work)? Perhaps, if I run "unset http_proxy" on command line and then start PyCharm from that same command line window, it may work. How do I start pycharm from command line? 'pycharm' is not found, /bin/pycharm is not found either.
2. How do I force Firefox to have "None" for proxy setting from selenium?
Thanks for any inputs.
Answer: Here are my findings so far:
1. Forcing PyCharm to use no proxy:
a. In a command line window (Accessories - > Terminal) unset proxy:
unset http_proxy
b. Start pycharm from the same command line window:
<install dir>/bin/pycharm.sh
The above solves my problem.
2. I cannot find a way to set proxy in Firefox to "No proxy" from selenium/python. When launching webdirver with the following:
browser = webdriver.Firefox(proxy=None)
the browser window that's launnched does not have proxy set to "No proxy" but
to "Use system proxy settings". If anyone is aware of a way to set Firefox
proxy to "No proxy" programmatically from python, please share. Otherwise, I
think it is a limitation of selenium/python.
I am not certain how selenium webdriver works, but my guess is that setting
browser's proxy to "No proxy" (if possible) may still not fix the above
problem. It may be necessary to have system proxy unset, in order for
webdriver to work properly. On unix use
unset http_proxy
on windows
set proxy to none from IE (that will change the system proxy).
If anybody has an explanation or better solution, please share.
|
randint() error 'empty range for randrange' in the python random module
Question: when I use randint() sometimes this error will appear:
ValueError: empty range for randrange() (1,1, 0)
why is this/how do i stop it from happening?
im not doing anything wrong as far as i can tell, this error dosnt apppear on
any specific randit() call and only appears every now and then.
the error takes me to the actual random module:
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
Here is my whole program (i call randint() often)
from random import randint
units = 5
food = 20
days_without_food = 0
SP = 4
print '------------------------------------------------------'
print 'welcome! starting a new game'
print '------------------------------------------------------'
location = 'plains'
def search(): #do2 create leadership skill or search skill
global units
global food
global SP
if SP > 0:
SP = SP - 1
found = randint(1,3)
if found == 1 or found == 2:
if units == 0:
units = randint(1,5)
print '------------------------------------------------------'
print 'you recruited %s units!' %units
main()
a = units / 2
ammount = randint(1,a)
units = units + ammount
print '------------------------------------------------------'
print 'you recruted %s units!' %ammount #recruit a random ammount of units not over half ammount of already owned.
main()
else:
print '------------------------------------------------------'
print 'you did not find anything'
main()
else:
print '------------------------------------------------------'
print 'your army is too tired to look for anything'
main()
def battle(): #do1 create villages with a random amount of units between 100-300
global SP
global units
global food
if SP == 0:
print '------------------------------------------------------'
print 'your army is too tired to fight'
main()
else:
SP = SP -1
if units == 0:
print '------------------------------------------------------'
print 'it is madness to go looking for a fight without an army'
main()
a = units / 2
b = units * 2
e_units = randint(a,b)
e_units = int(e_units) #random ammount of enemy units reletave to ammount of player units
if e_units == 0:
e_units = randint(1,3)
guess = randint(e_units-5,e_units+5)
if guess < 0:
guess = randint(1,e_units+10)
print '------------------------------------------------------'
print 'it looks like the enemy has %s units' %guess #unacurate guess of how many enemy units there are
print 'a: attack'
print 'b: leave'
action = raw_input('a or b?')
if action == 'a':
units = units - e_units
if units <0:
units = 0
print '------------------------------------------------------'
print 'you lost the battle and all of your units'
main()
else:
a = e_units * 2
ammount = randint(1,a)
food = food + ammount
print '------------------------------------------------------'
print 'you won the battle and found %s food!' %ammount + ' after the battle you have %s units' %units
main() # battle
else:
chance = randint(1,10)
if chance == 10:
units = units - e_units
if units <0:
units = 0 #attempt to leve
print '------------------------------------------------------'
print 'it is to late, they spotted you!' + ' after the battle you have %s units' %units
main()
else:
print '------------------------------------------------------'
print 'you leave without the enemy spotting you'
main()
def change_location():
global food
global units
global SP
global days_without_food
if food < 0:
days_without_food = days_without_food + 1
if days_without_food > 0 and days_without_food < 3:
chance = randint (1,5)
if not chance == 5:
print '------------------------------------------------------'
print 'you have no food, but your men are stll loyal to you'
food = 0
main()
elif chance == 5:
deserters = randint(1,int(units/4))
units = units - deserters
print '------------------------------------------------------'
print 'without any food, %d men deserted your army' % deserters
food = 0
main()
else:
chance = randint(1,2)
if chance == 1:
men_starved = randint(1,int(units/4))
units = units - men_starved
print '------------------------------------------------------'
print 'without any food, %d units starved to death' % men_starved
food = 0
main()
else:
deserters = randint(1,int(units/4))
units = units - deserters
print '------------------------------------------------------'
print 'without any food, %d men deserted your army' % deserters
food = 0
main()
days_without_food = 0
SP = 3
food = food - int(units / 2)
places = ['plains','beach','river','mountain','sea','desert','hills',
'forest','volcano','jungle','storm','village'] #do3 add more places
location = places[randint(0,len(places)-1)]
main()
def main(): #do1 Create nomadic and settled versions
global units
global location
global food
global SP
print '------------------------------------------------------'
print 'you are at a %s' %location
print 'a:look for a fight'
print 'b:look for supplies'
print 'c:Take stock'
print 'd:Move on'
action = raw_input('a,b,c, or d?')
if action == 'a':
battle()
elif action == 'b':
search()
elif action == 'c':
print '------------------------------------------------------'
print 'food: %s. ' %food + ' units: %s. ' %units + ' Search points %s. ' %SP
main()
elif action == 'd':
change_location()
else:
main()
main()
Answer: randint(a, b) should be called with the arguments a and b in which b should be
greater than a. Else the randrange() method called by randint() will raise a
value error like this:
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
Check this source for random module with [randint()(line:237) and randrange()
(line:173)](http://svn.python.org/view/python/branches/release27-maint/Lib/random.py?view=markup)
methods for better understanding.
|
Python Selenium, scraping webpage javascript table
Question: I am going to scrap the javascript tables inside below link.
<http://data2.7m.cn/history_Matches_Data/2009-2010/92/en/index.shtml>
import codecs
import lxml.html as lh
from lxml import etree
import requests
from selenium import webdriver
import urllib2
from bs4 import BeautifulSoup
URL = 'http://data2.7m.cn/history_Matches_Data/2009-2010/92/en/index.shtml'
profile = webdriver.FirefoxProfile()
profile.set_preference('network.http.max-connections', 30)
profile.update_preferences()
browser = webdriver.Firefox(profile)
browser.get(URL)
content = browser.page_source
soup = BeautifulSoup(''.join(content))
When I get the contents of the webpage, then I need to know the number of
round of soccer matches in that particular league.
Below codes has only found out the only table, may I know how to get all 38
soccer matches' tables? Thank you.
# scrap the round of soccer matches
soup.findAll('td', attrs={'class': 'lsm2'})
# print the soccer matches' result of default round, but there have 38 rounds (id from s1 to s38)
print soup.find("div", {"id": "Match_Table"}).prettify()
Answer:
# ============================================================
import codecs
import lxml.html as lh
from lxml import etree
import requests
from selenium import webdriver
import urllib2
from bs4 import BeautifulSoup
from pandas import DataFrame, Series
import html5lib
URL = 'http://data2.7m.cn/history_Matches_Data/2009-2010/92/en/index.shtml'
profile = webdriver.FirefoxProfile()
profile.set_preference('network.http.max-connections', 30)
profile.update_preferences()
browser = webdriver.Firefox(profile)
browser.get(URL)
content = browser.page_source
soup = BeautifulSoup(''.join(content))
# num = soup.findAll('td', attrs={'class': 'lsm2'})
# num = soup.findAll('table')[2].findAll('td')[37].text
# soup.findAll('table',attrs={'class':'e_run_tb'})
num1 = soup.findAll('table')[2].findAll('tr')
for i in range(1,len(num1)+1):
for j in range(1,len(num1[i-1])+1):
# click button on website
clickme = browser.find_element_by_xpath('//*[@id="e_run_tb"]/tbody/tr'+'['+str(i)+']'+'/td'+'['+str(j)+']')
clickme.click()
content = browser.page_source
soup = BeautifulSoup(''.join(content))
table = soup.find('div', attrs={'class': 'e_matches'})
rows = table.findAll('tr')
# for tr in rows:
# cols = tr.findAll('td')
# for td in cols:
# text = td.find(text=True)
# print text,
# print
for tr in rows[5:16]: #from row 5 to 16
cols = tr.findAll('td')
for td in cols:
text = td.find(text=True)
print text,
print
print
|
Multiplying Block Matrices in Numpy
Question: Hi Everyone I am python newbie I have to implement lasso L1 regression for a
class assignment. This involves solving a quadratic equation involving block
matrices.
minimize x^t * H * x + f^t * x
where x > 0
Where H is a 2 X 2 block matrix with each element being a k dimensional matrix
and x and f being a 2 X 1 vectors each element being a k dimension vector.
I was thinking of using ndarrays.
Such that :
np.shape(H) = (2, 2, k, k)
np.shape(x) = (2, k)
But I figured out that np.dot(X, H) doesn't work here. Is there an easy way to
solve this problem? Thanks in advance.
Answer: First of all, I am convinced that converting to matrices will lead to more
efficient computations. Stating that, if you consider your 2k x 2k matrix
being a 2 x 2 matrix, then you operate in a tensor product of vector spaces,
and have to use `tensordot` instead of `dot`.
Let give it a try, with k=5 for example:
>>> import numpy as np
>>> k = 5
Define our matrix `a` and vector `x`
>>> a = np.arange(1.*2*2*k*k).reshape(2,2,k,k)
>>> x = np.arange(1.*2*k).reshape(2,k)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
now we can multipy our tensors. Be sure to choose right axes, I didn't tested
following formula explicetely, and there might be an error
>>> result = np.tensordot(a,x,([1,3],[0,1]))
>>> result
array([[ 985., 1210., 1435., 1660., 1885.],
[ 3235., 3460., 3685., 3910., 4135.]])
>>> np.shape(result)
(2, 5)
|
make a total list of a returned map (python)
Question: I have the lambda function f:
f = lambda x:["a"+x, x+"a"]
and I have the list lst:
lst = ["hello", "world", "!"]
So I did map on the function and the list to get a bigger list but it didn't
work as I thought:
print map(f, lst)
>>[ ["ahello", "helloa"], ["aworld", "worlda"], ["a!", "!a"] ]
As you can see I got lists inside list, but I wanted all of these strings to
be in **one** list
How can I do that?
Answer: Use
[`itertools.chain.from_iterable`](http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable):
>>> import itertools
>>> f = lambda x: ["a"+x, x+"a"]
>>> lst = ["hello", "world", "!"]
>>> list(itertools.chain.from_iterable(map(f, lst)))
['ahello', 'helloa', 'aworld', 'worlda', 'a!', '!a']
Alternative (list comprehension):
>>> [x for xs in map(f, lst) for x in xs]
['ahello', 'helloa', 'aworld', 'worlda', 'a!', '!a']
|
In Python edit Non Global Names
Question: In Python Version: 2.7.5, I have Zelle's Graphics installed and I have no idea
what to do because I am trying to edit a non global name in a function with a
different function. Here is an example of my code.
from graphics import *
import time
keyPad=GraphWin("Key Pad",300,400)
def Game():
Buttons()
testFor_keyPad_press()
def Buttons():
button1=Rectangle(Point(1,1),Point(100,100))
button1.setFill('gold')
button.draw(keyPad)
def testFor_keyPad_press():
userInput=keyPad.getMouse()
userInputX=str(userInput.getX())
userInputY=str(userInput.getY())
if(userInputX<101 and userInputY<100):
button1.setFill('grey')
keyPad.update()
time.sleep(0.5)
button1.setFill('gold')
keyPad.update()
Game()
I thought that should work, but it gives me an error saying that global name
'button1' is not defined... so is there a way I can edit button1 inside of the
user defined function "Buttons()" ? Or is that not possible? Please let me
know if there is a way to do this or not... all help is
Answer:
def Buttons():
global button1
button1=Rectangle(Point(1,1),Point(100,100))
button1.setFill('gold')
button.draw(keyPad)
would make it accessible outside the function ... but really you should
probably encapsulate your logic in classes
|
Losing queued tasks in Python apply_async
Question: I am attempting to write a wrapper that iterates through running another
program with different input files. The program (over which I have no control,
but need to use) needs to be run out of the same directory as the input
file(s). So far my method is to use OS-module to change/create directory
structure, use apply-async to run the program given a sub-directory, and each
child in apply-async changes directory, creates the file, and the first 8
processes run successfully (i have 8 virtual cores)
However, I am queueing up to 100 of these processes (they run a simulation
which takes a few minutes, I'm looking to optimize). I use "call" on the
outside executable I am running. I thought everything was going great, but
then after the 8th simulation runs, everything stops, I check 0 processes are
running. It is as if the queue forgot about the other processes.
What can I do to fix this? I know my RAM only goes up about 300 MB out of 8GB.
Do I need to look into implementing some sort of queue myself that waits for
the exit code of the simulation executable?
Thank you in advance.
Answer: Maybe better than nothing. This shows a correct way to use `apply_async()`,
and demonstrates that - yup - there's no problem creating many more tasks than
processes. I'd tell you how this differs from what you're doing, but I have no
idea what you're doing ;-)
import multiprocessing as mp
def work(i):
from time import sleep
sleep(2.0 if i & 1 else 1.0)
return i*i
if __name__ == "__main__":
pool = mp.Pool(4)
results = [pool.apply_async(work, (i,)) for i in range(100)]
results = [r.get() for r in results]
print len(results), results
pool.close()
pool.join()
|
Python 2.7 & Regular Expressions: False if statement returns
Question: To practice regular expressions, I'm trying to create a very simple text based
game similar to Zork. However I can't seem to have the code work using regular
expressions.
**Movement.py**
import re
def userMove():
userInput = raw_input('Which direction do you want to move?')
textArray = userInput.split()
analyse = [v for v in textArray if re.search('north|east|south|west|^[NESW]', v, re.IGNORECASE)]
print textArray
print analyse
movement = 'null'
for string in analyse:
if string is 'North' or 'n':
movement = 'North'
elif string is 'East'or'e':
movement = 'East'
elif string is 'South'or's':
movement = 'South'
elif string is 'West'or'w':
movement = 'West'
print movement
**if/elif Sample Run**
>>> import movement
>>> moves = movement.userMove()
Which direction do you want to move?Lets walk East
['Lets', 'walk', 'East']
['East']
North
**if Sample Run**
>>> import movement
>>> moves = movement.userMove()
Which direction do you want to move?I`ll run North
['I`ll', 'run', 'North']
['North']
West
If the `for` loop will constantly set `movement` to North; and using `if`
statements instead of `elif` will set it to West. Making the regex use
`userInput` in place of `textArray` cause the method to keep `movement` as
null.
**_Edit_** After further testing and changing the code, I'm sure the regex is
fine and it's a bug with the `if` statements or the `for` loop.
Answer: Your problem is with these `if` statements:
if string is 'North' or 'n':
movement = 'North'
elif string is 'East'or'e':
movement = 'East'
elif string is 'South'or's':
movement = 'South'
etc...
They don't work quite how you're expecting. First, you shouldn't compare
strings with `is` \- you should use `==`. Secondly, the statement is evaluated
more like:
if (string is 'North') or 'n':
movement = 'North'
So, `'n'` is always `True` \- meaning your `movement` variable is always set
to `North`.
Try this instead:
if string in ('North', 'n'):
etc...
|
notify user from service with python
Question: In the following text the word "write" refers to the unix write command which
writes a message to another user's tty.
I have a service running (in inetd, but that shouldn't matter) which needs to
notify an arbitrary user. Until now I tried to call the write command with
subprocess. But that doesn't work always and on some machines leads to an
error message like:
write: you are uid 65534, but your login is as uid 1000
(please note that the service is running as nobody.) Write permission to the
terminal is turned on with mesg. So I looked at inetutils-talkd (the GNU
implementation), which does the same. I saw that it uses the ttymsg function
and believe that this function does what I want, but I think that this
function isn't available to python.
So the main questions are: Is there something like the ttymsg function in
python OR how can i get write to do what i want?
Answer: The file /var/run/utmp contains information about the active sessions on
terminals. It can be parsed with:
import struct
sig = 'hi32s4s32s256shhiii36x'
size = struct.calcsize(sig)
file = open('/var/run/utmp', 'rb')
chunk = file.read(size)
entrys = []
while len(chunk) == size:
entry = struct.unpack(chunk)
entrys.append()
chunk = file.read(size)
With that approach I can gather the needed data to choose a terminal and write
to that terminal.
|
Options for audio input into Kivy?
Question: I saw from [here](http://kivy.org/docs/api-kivy.core.audio.html) that
"Recording audio is not supported" in kivy. Some googling told me that [there
is some work being done on this](https://groups.google.com/forum/#!topic/kivy-
users/LsEuwhuKQek), but nothing looked conclusive or settled.
I'm wondering how people work around this, especially for Ubuntu or Android.
If there are other solutions, I'm just plain looking for something that would
let me code in python and produce something like a visualizer that runs on
android and ubuntu, and allows multi-touch input--whatever modifications I
have to make to keep a reasonably centralized codebase across the 2 platforms.
Kivy looked like a solution, but this audio problem seem to be hamstringing.
Answer: `Audiostream` mentioned in link you've found has an
[example](http://audiostream.readthedocs.org/en/latest/) of reading bytes from
microphone. You can find examples of integration with kivy
[here](https://github.com/kivy/audiostream/tree/master/examples). For Ubuntu
you can try [PyAudio](http://people.csail.mit.edu/hubert/pyaudio/). See this
[example](http://stackoverflow.com/questions/4160175/detect-tap-with-pyaudio-
from-live-mic/4160733#4160733). In your kivy application you can detect system
through code like:
from kivy.utils import platform
def do_smth(self):
p = platform()
if p == 'android':
# ...
elif p == 'ios':
# ...
elif p == 'win':
# ...
elif p == 'macosx':
# ...
else
# linux
It looks like you need to handle sound input separately but you can have rest
of the code common for both platforms.
|
Django Settings folder ImportError
Question: I am replacing the Django settings file for a folder of different settings.
The directory of the structure looks like this:
.
├── manage.py
├── media
├── quito_events
│ ├── __init__.py
│ ├── urls.py
│ └── wsgi.py
├── settings
│ ├── __init__.py
│ ├── base.py
│ ├── ci.py
│ ├── local.py
│ ├── production.py
│ ├── staging.py
│ └── test.py
├── static
├── templates
└── users
├── __init__.py
├── models.py
├── tests.py
└── views.py
When I try to run:
django-admin.py shell --settings=quito_events.settings.local
Traceback (most recent call last):
File "/Users/eduardo/.virtualenvs/quito_events/bin/django-admin.py", line 5, in <module>
management.execute_from_command_line()
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/core/management/__init__.py", line 263, in fetch_command
app_name = get_commands()[subcommand]
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/core/management/__init__.py", line 109, in get_commands
apps = settings.INSTALLED_APPS
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup
self._wrapped = Settings(settings_module)
File "/Users/eduardo/.virtualenvs/quito_events/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'quito_events.settings.local' (Is it on sys.path?): No module named quito_events.settings.local
What I am doing wrong?
Answer: You can switch to use manage.py, e.g.
python manage.py shell --settings=quito_events.settings.local
or use django-admin.py with specified project path, e.g.
django-admin.py shell --pythonpath=your_project_path --settings=quito_events.settings.local
|
file.readlines() leaving blank lines
Question: I have read the `file.readlines()` reads the whole file line by line and
stores it in a list. If I have a file like so -
Sentence 1
Sentence 2
Sentence 3
and I use `.readlines()` to print each sentence like so -
file = open("test.txt")
for i in file.readlines():
print i
enter code here
The output is
Sentence 1
Sentence 2
Sentence 3
My question is why do I get the extra line between each sentence and how can I
get rid of it ? Please excuse me if this question is pretty stupid but I am
not very experienced in Python.
**UPDATE**
I found that using `i.strip()` also removes the extra lines , why does this
happen ? As far as I know, `.split()` removes the white spaces at the end and
beginning of a string.
Answer: `file.readlines()` return list of strings. Each string contain trailing
newlines. `print` statement prints the passed parameter with newlnie.; That's
why you got extra lines.
To remove extra newline, use `str.rstrip`:
print i.rstrip('\n')
or use `sys.stdout.write`
sys.stdout.write(i)
BTW, don't use `file.readlines` unless you need all lines at once. Just
iterate the file.
with open("test.txt") as f:
for i in f:
print i.rstrip('\n')
...
**UPDATE**
In Python 3, to prevent `print` prints trailing newline, you can use `print(i,
end='')`.
In Python 2, you can use same feature if you do : [`from __future__ import
print_function`](http://docs.python.org/2/library/__future__.html)
**Answer to UPDATE**
Tabs, Newlines are also considers as whitespaces.
>> ' \r\n\t\v'.isspace()
True
|
Python script sys.argv error
Question: This is my first python script:
#!/usr/bin/env python
# Years till 100
import sys
name = sys.argv[1]
age = int(sys.argv[2])
diff = 100 - age
print 'Hello', name + ', you will be 100 in', diff, 'years!'
When I run it, it gives the following error:
name = sys.argv[1]
IndexError: list index out of range
Can anyone help me spot the problem please?
Answer: I found that I was not executing the program properly.
I was doing the following:
$ chmod u+x pytest3_variable1.py
$ ./pytest3_variable1.py
I should have done:
$ chmod u+x pytest3_variable1.py
$ ./pytest3_variable1.py Abhinav 22
|
Decrypt an AES encoded message (encrypted in Python) in Java
Question: I want to decrypt an AES encrypted message in Java. I’ve been trying various
Algorithm/Mode/Padding options from the [standard
library](http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html)
and from [BouncyCastle](http://www.bouncycastle.org/). No luck :-(
The encrypting entity is written in Python and is already in production.
Encrypted messages have already gone out, so I cannot easily change that part.
The Python code looks like this:
from Crypto.Cipher import AES
import base64
import os
import sys
BLOCK_SIZE = 16
PADDING = '\f'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
secret = 'XXXXXXXXXXXXXXXX'
cipher = AES.new(secret)
clear='test'
encoded = EncodeAES(cipher, clear)
print 'Encrypted string:>>{}<<'.format(encoded)
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string:>>{}<<'.format(decoded)
Obviously AES is used, and I figured out that I have to use ECB mode. But I
have not found a padding mode that works on the Java side. If the input fits
within the block size and no padding is happening, I can decrypt the message
in Java. If the message needs to be padded, decryption fails.
The Java code to decrypt looks like this:
public class AESPaddingTest {
private enum Mode {
CBC, ECB, CFB, OFB, PCBC
};
private enum Padding {
NoPadding, PKCS5Padding, PKCS7Padding, ISO10126d2Padding, X932Padding, ISO7816d4Padding, ZeroBytePadding
}
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = new byte[] { 'X', 'X', 'X', 'X',
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' };
@BeforeClass
public static void configBouncy() {
Security.addProvider(new BouncyCastleProvider());
}
@Test
public void testECBPKCS5Padding() throws Exception {
decrypt("bEpi03epVkSBTFaXlNiHhw==", Mode.ECB,
Padding.PKCS5Padding);
}
private String decrypt(String valueToDec, Mode modeOption,
Padding paddingOption) throws GeneralSecurityException {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
Cipher c = Cipher.getInstance(ALGORITHM + "/" + modeOption.name() + "/" + paddingOption.name());
c.init(Cipher.DECRYPT_MODE, key);
byte[] decValue = c.doFinal(valueToDec.getBytes());
String clear = new String(Base64.encodeBase64(decValue));
return clear;
}
}
The error thrown is:
> javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16
> when decrypting with padded cipher
Any ideas?
Answer: thanks for the good question, answer and comments. I did minor changes to the
code and now it works like a charm for me.
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public class AESTest {
public enum Mode {
CBC, ECB, CFB, OFB, PCBC
};
public enum Padding {
NoPadding, PKCS5Padding, PKCS7Padding, ISO10126d2Padding, X932Padding, ISO7816d4Padding, ZeroBytePadding
}
private static final String ALGORITHM = "AES";
private static final byte[] keyValue ="myKey".getBytes();
String decrypt(String valueToDec, Mode modeOption,
Padding paddingOption) throws GeneralSecurityException {
byte[] decodeBase64 = Base64.decode(valueToDec.getBytes(),0);
Key key = new SecretKeySpec(keyValue, ALGORITHM);
Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
c.init(Cipher.DECRYPT_MODE, key);
byte[] encValue = c.doFinal(decodeBase64);
return new String(encValue).trim();
}
}
Then, I used the class in my Android Activity as follows:
AESTest aes=new AESTest();
String decrypted = aes.decrypt(myCipheredText,Mode.ECB,Padding.NoPadding);
Note that the secret in python code and mykey in java code are tthe same.
|
Searching a file for a list of regexs, Python
Question: I'm having a bit of trouble searching a file using python regex.
I would like to input a list of regexs and return the lines of the file that
match one of them in a jagged list that is indexed in the same way was the
rexex list, i.e. if a line matches the 1st regex it will be added with:
`results[0].append(line)` and if the second is matched:
`results[1].append(line)` and so on...
import re
def search(path, regex_list):
reg_list = [re.compile(regex) for regex in regex_list]
results = reg_list.__len__()*[[]]
with open(path, 'r') as fp:
for line in fp:
for i, reg in enumerate(reg_list):
if reg.search(line):
results[i].append[line]
return results
print(search("./log", ['1234', '1233']))
I woud like my output to be:
`[['log entry 1234\n'], ['log entry 1233\n']]`
but what I really get is:
`[['log entry 1234\n', 'log entry 1233\n'], ['log entry 1234\n', 'log entry
1233\n']]`
I'm pretty new to python so I could be doing something really stupid, any
ideas what it is?
Answer: By multiplying the list of an empty list (`results = reg_list.__len__()*[[]]`)
in your code, you simply create several pointers all pointing to the same
empty list.
If some code later appends something to that list, all pointers point to that
extended list.
Instead create a list of (non-identical) empty lists at init:
[[] for reg in reg_list]
|
Real time matplotlib plot is not working while still in a loop
Question: I want to create a real time graph plotting program which takes input from
serial port. Initially, I had tried a lot of code that posted on websites, but
none of them worked. So, I decided to write code on my own by integrating
pieces of code I've seen on the websites. But the problem is the graph will
pop out only when the program ends,in other words, out of the loop. While in
the loop, it shows nothing, just a blank canvas. I'm still pretty new to
python. Here is my code.
import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np
# simulates input from serial port
def random_gen():
while True:
val = random.randint(1,10)
yield val
time.sleep(0.1)
a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()
line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()
for i in range(0,20):
a1.appendleft(next(d))
datatoplot = a1.pop()
line.set_ydata(a1)
plt.draw()
print a1[0]
i += 1
time.sleep(0.1)
Also, I use Enthought Canopy academic license ver 1.1.0.
Answer: **Here is the solution add this`plt.pause(0.0001)` in your loop as below:**
import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np
# simulates input from serial port
def random_gen():
while True:
val = random.randint(1,10)
yield val
time.sleep(0.1)
a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()
line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()
for i in range(0,20):
a1.appendleft(next(d))
datatoplot = a1.pop()
line.set_ydata(a1)
plt.draw()
print a1[0]
i += 1
time.sleep(0.1)
plt.pause(0.0001) #add this it will be OK.
|
How to organize database connections in larger Python/Flask applications?
Question: I am currently trying to write a little web-application using python, flask
and sqlite and I'm not sure about how to handle the database-connections.
Basically I've been following the "official" Tutorial (and
<http://flask.pocoo.org/docs/patterns/sqlite3/#sqlite3> ), leaving me with
code like this in my main Flask/App module (drastically shortened):
@vs_app.before_request
def before_request():
g.db = sqlite3.connect("somedb.db")
def execute_db(command):
return g.db.cursor().execute(command).fetchall()
@app.route("/givemeallusers")
def foo():
return execute_db("SELECT * FROM users")
So this creates a DB-Connection for each request that can be used by my
application to execute sql-commands and it works fine for smaller
applications.
But for a larger project I'd like to put my database-code (with some utility
methods) and app-code in different modules, so I could (for example) write:
from my_database_module import user_auth #
@app.route("/login")
def foo():
if user_auth(request.form["name"], request.form["pw"]):
pass
But for that I would need access to g (or g.db) from my database-class and the
only way I could get that to work was by "manually" handing over the db-
connection to each method, leaving me with code like this:
@app.route("/login")
def foo():
if user_auth(g.db, request.form["name"], request.form["pw"]):
pass
and in my database-module
def user_auth(database, name, pw):
pass
I don't think thats the best approach, but other ideas I had (like importing
the g object into my database-class) don't work. I also don't know whether my
approach is safe with regards to concurrent db-access, so any help with this
would be appreciated.
tl;dr How to split Flask-App and Database/Database-Utility the right way?
Answer: Just in case someone stumbles upon this question:
The correct answer is to not bother with the approaches described in the
Question, and instead just start working with Flask-SQLAlchemy.
|
Upload with wtforms - unexpected end of regular expression
Question: I am trying this code from here
[docs](http://wtforms.simplecodes.com/docs/0.6/fields.html#wtforms.fields.FileField)
class Form(Form):
image = FileField(u'Image File', validators=[Regexp(u'^[^/\\]\.jpg$')])
def validate_image(form, field):
if field.data:
field.data = re.sub(r'[^a-z0-9_.-]', '_', field.data)
Here is the error:
Traceback (most recent call last):
File "tornadoexample2-1.py", line 111, in <module>
class Form(Form):
File "tornadoexample2-1.py", line 119, in Form
image = FileField(u'Image File', validators=[Regexp(u'^[^/\\]\.jpg$')])
File "/usr/local/lib/python2.7/dist-packages/wtforms/validators.py", line 256, in __init__
regex = re.compile(regex, flags)
File "/usr/lib/python2.7/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.7/re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression
Any idea about what the problem?
Answer: The regexp in `Regexp(u'^[^/\\]\.jpg$')` is not quite good.
Try running this, you will get the same exception:
import re
re.compile(u'^[^/\\]\.jpg$')
You need to escape each `\` slash twice inside the `[]` brackets.
So you can rewrite it as `u'^[^/\\\\]\.jpg$'` or as a raw string
`ur'^[^/\\]\.jpg$'`.
Hope this helps.
|
Need to modify files top to bottom using python's os walk. Generator object?
Question: I need to modify some files using a python script, and I figure OS walk is the
way to go about it. I need to modify everything under
/foo/bar
/foo/baz
/foo/bat
....for example
I've never used os.walk before, I read a bit about it and I see that it
traverses down the file structure top to bottom. However, when I did a bit of
debugging, the object os.walk returns is something called a generator, and I'm
not sure how to go about modifying the files with this object. Does anyone
know how to modify files in a top to bottom order using pythons os.walk?
Examples, links to examples?
Answer:
import os
for root, dirs, files in os.walk('.'):
print root, dirs,files
|
Searching strings with Python
Question: I have the following sentence:
Dave put the rubbish in the {{ if dave_good }}bin{{ else }}street{{ endif }}.
I'm currently replacing variables in text strings by capturing `[[ something
]]` and replacing the whole instance with a value _(not a problem)_. But
that's using python's `re` library.
I was wondering if someone could show me how to:
1. search for single instances of `{{ if dave_good }}` in the string
2. count forward from the `{{ if dave_good }}` to make sure there is a `{{ endif }}` before the end of the string
3. if there is no `{{ else }}` then remove the tags, or the tags and their content, _(at their location in the text)_ based on the boolean attribute of `dave_good`
4. if there is an `{{ else }}`
1. if `dave_good` is `TRUE` then remove `{{ if dav_good }}` and `{{ else }}street{{ endif}}`
2. if `dave_good` is `FALSE` then remove `{{ endif }}` and `{{ if dave_good }}bin{{ else }}`
Answer: try with [Regular Expressions](http://docs.python.org/2/howto/regex.html).
Example:
import re
result = re.match("\{\{((if|else|endif).*?)\}\}","{{if 100 > 1}}",re.I)
print result.groups()
result = re.match("\{\{((if|else|endif).*?)\}\}","{{else}}",re.I)
print result.groups()
result = re.match("\{\{((if|else|endif).*?)\}\}","{{endif}}",re.I)
print result.groups()
Or use a template engine for python
1. [jinja](http://jinja.pocoo.org/)
2. [cheetah](http://www.cheetahtemplate.org/)
3. [Templating](https://wiki.python.org/moin/Templating)
4. [bottlepy](http://bottlepy.org/docs/dev/stpl.html)
Good Luck!
|
Getting WindowsError when trying ot copy a file from one directory to another w/ paramiko
Question: Good afternoon,
I am getting the following error whenever I am trying to copy a test file from
one directory to another on a remote server:
**Traceback (most recent call last): File "", line 1, in File
"C:\Python27\lib\site-
packages\paramiko-1.12.0-py2.7.egg\paramiko\sftp_client.py", line 612, in put
file_size = os.stat(localpath).st_size WindowsError: [Error 3] The system
cannot find the path specified: '/brass/prod/bin/chris/test1/km_cust'**
The file I am looking to copy is called km_cust.
I am executing these commands in python 2.7.
Please note that the hostname, uid, and password were changed to generic
versions and the real hostname, uid, and password can be used to ssh to the
box in question and preform all functionality.
Here is my code:
import paramiko
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect('hostname',username='test',password='pw')
filepath = '/brass/prod/bin/chris/test1/km_cust'
localpath = 'brass/prod/bin/chris/test2'
sftp = s.open_sftp()
sftp.put(filepath, localpath)
Any help will be apprecaited. Let me know if any other information is needed.
Answer: The problem is that [`put`](http://docs.paramiko.org) copies a _local_
file—that is, a file n your Windows box—to the server. As the documentation
says:
put(self, localpath, remotepath, callback=None, confirm=True)
Copy a local file (localpath) to the SFTP server as remotepath.
Note that you're also specifying (or at least naming) the paths backward… but
that doesn't really matter here, because neither one is _actually_ a local
path. So when you do this:
sftp.put(filepath, localpath)
… it's looking for a file named `'/brass/prod/bin/chris/test1/km_cust'` on
your Windows box, and of course it can't find such a file.
If you want to copy a remote file to a different remote file, you need to do
something like this:
f = sftp.open(filepath)
sftp.putfo(f, localpath)
Or:
f = sftp.open(localpath, 'wx')
sftp.getfo(filepath, f)
* * *
Also, I'm guessing your `filepath` is supposed to start with a `/`.
* * *
However, this probably isn't what you wanted to do in the first place. Copying
a file from the remote server to the remote server via sftp involves
downloading all of the bytes to your Windows machine and then uploading them
back to the remote machine. A better solution would be to just tell the
machine to do the copy itself:
s.exec_command("cp '{}' '{}'".format(filepath, localfile))
s.close()
Note that in anything but the most trivial of cases, you're going to have to
deal with the `Channel` and its in/out/err and wait on its exit status. But I
believe that for this case, you should be fine.
|
qwebview in pyside after packaged with pyinstaller goes wrong
Question: Here's my code
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
from encodings import *
from codecs import *
class BrowserWindow( QWidget ):
def __init__( self, parent=None ):
QWidget.__init__( self, parent )
self.Setup()
self.SetupEvent()
def Setup( self ):
self.setWindowTitle( u"Truease Speedy Browser" )
self.addr_input = QLineEdit()
self.addr_go = QPushButton( "GO" )
self.addr_bar = QHBoxLayout()
self.addr_bar.addWidget( self.addr_input )
self.addr_bar.addWidget( self.addr_go )
for attr in [
QWebSettings.AutoLoadImages,
QWebSettings.JavascriptEnabled,
QWebSettings.JavaEnabled,
QWebSettings.PluginsEnabled,
QWebSettings.JavascriptCanOpenWindows,
QWebSettings.JavascriptCanAccessClipboard,
QWebSettings.DeveloperExtrasEnabled,
QWebSettings.SpatialNavigationEnabled,
QWebSettings.OfflineStorageDatabaseEnabled,
QWebSettings.OfflineWebApplicationCacheEnabled,
QWebSettings.LocalStorageEnabled,
QWebSettings.LocalStorageDatabaseEnabled,
QWebSettings.LocalContentCanAccessRemoteUrls,
QWebSettings.LocalContentCanAccessFileUrls,
]:
QWebSettings.globalSettings().setAttribute( attr, True )
self.web_view = QWebView()
self.web_view.load( "http://www.baidu.com" )
layout = QVBoxLayout()
layout.addLayout( self.addr_bar )
layout.addWidget( self.web_view )
self.setLayout( layout )
def SetupEvent( self ):
self.connect(
self.addr_input,
SIGNAL("editingFinished()"),
self,
SLOT("Load()"),
)
self.connect(
self.addr_go,
SIGNAL("pressed()"),
self,
SLOT("Load()")
)
self.connect(
self.web_view,
SIGNAL("urlChanged(const QUrl&)"),
self,
SLOT("SetURL()"),
)
def Load( self, *args, **kwargs ):
url = self.GetCleanedURL()
if url != self.CurrentURL():
self.web_view.load( url )
def SetURL( self, *args, **kwargs ):
self.addr_input.setText( self.CurrentURL() )
def GetCleanedURL( self ):
url = self.addr_input.text().strip()
if not url.startswith("http"):
url = "http://" + url
return url
def CurrentURL( self ):
url = self.web_view.url().toString()
return url
def Main():
app = QApplication( sys.argv )
widget = BrowserWindow()
widget.show()
return app.exec_()
if __name__ == '__main__':
sys.exit( Main() )
I works well when i using `python browser.py`. but it goes wrong after
packaged with `pyinstaller -w browser.py`.

1. it doesn't load images
2. can only display correct text in utf-8
And this is the pyinstaller output:
E:\true\wuk\app2>pyinstaller -w b.py
16 INFO: wrote E:\true\wuk\app2\b.spec
16 INFO: Testing for ability to set icons, version resources...
32 INFO: ... resource update available
32 INFO: UPX is not available.
46 INFO: Processing hook hook-os
141 INFO: Processing hook hook-time
157 INFO: Processing hook hook-cPickle
218 INFO: Processing hook hook-_sre
312 INFO: Processing hook hook-cStringIO
407 INFO: Processing hook hook-encodings
421 INFO: Processing hook hook-codecs
750 INFO: Processing hook hook-httplib
750 INFO: Processing hook hook-email
843 INFO: Processing hook hook-email.message
1046 WARNING: library python%s%s required via ctypes not found
1171 INFO: Extending PYTHONPATH with E:\true\wuk\app2
1171 INFO: checking Analysis
1171 INFO: building because b.py changed
1171 INFO: running Analysis out00-Analysis.toc
1171 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable
1171 INFO: Searching for assembly x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww ...
1171 INFO: Found manifest C:\WINDOWS\WinSxS\Manifests\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375.manifest
1187 INFO: Searching for file msvcr90.dll
1187 INFO: Found file C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375\msvcr90.dll
1187 INFO: Searching for file msvcp90.dll
1187 INFO: Found file C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375\msvcp90.dll
1187 INFO: Searching for file msvcm90.dll
1187 INFO: Found file C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375\msvcm90.dll
1266 INFO: Analyzing D:\Applications\Python\lib\site-packages\pyinstaller-2.1-py2.7.egg\PyInstaller\loader\_pyi_bootstrap.py
1266 INFO: Processing hook hook-os
1282 INFO: Processing hook hook-site
1296 INFO: Processing hook hook-encodings
1391 INFO: Processing hook hook-time
1407 INFO: Processing hook hook-cPickle
1468 INFO: Processing hook hook-_sre
1578 INFO: Processing hook hook-cStringIO
1671 INFO: Processing hook hook-codecs
2016 INFO: Processing hook hook-httplib
2016 INFO: Processing hook hook-email
2109 INFO: Processing hook hook-email.message
2312 WARNING: library python%s%s required via ctypes not found
2468 INFO: Processing hook hook-pydoc
2516 INFO: Analyzing D:\Applications\Python\lib\site-packages\pyinstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_importers.py
2609 INFO: Analyzing D:\Applications\Python\lib\site-packages\pyinstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_archive.py
2687 INFO: Analyzing D:\Applications\Python\lib\site-packages\pyinstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_carchive.py
2782 INFO: Analyzing D:\Applications\Python\lib\site-packages\pyinstaller-2.1-py2.7.egg\PyInstaller\loader\pyi_os_path.py
2782 INFO: Analyzing b.py
2796 INFO: Processing hook hook-PySide
2875 INFO: Hidden import 'codecs' has been found otherwise
2875 INFO: Hidden import 'encodings' has been found otherwise
2875 INFO: Looking for run-time hooks
7766 INFO: Using Python library C:\WINDOWS\system32\python27.dll
7796 INFO: E:\true\wuk\app2\build\b\out00-Analysis.toc no change!
7796 INFO: checking PYZ
7812 INFO: checking PKG
7812 INFO: building because E:\true\wuk\app2\build\b\b.exe.manifest changed
7812 INFO: building PKG (CArchive) out00-PKG.pkg
7828 INFO: checking EXE
7843 INFO: rebuilding out00-EXE.toc because pkg is more recent
7843 INFO: building EXE from out00-EXE.toc
7843 INFO: Appending archive to EXE E:\true\wuk\app2\build\b\b.exe
7843 INFO: checking COLLECT
7843 INFO: building COLLECT out00-COLLECT.toc
Use `pyinstaller browser.py`, and in the console window i got
QFont::setPixelSize: Pixel size <= 0 (0)
QSslSocket: cannot call unresolved function SSLv23_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QSslSocket: cannot call unresolved function SSLv23_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QSslSocket: cannot call unresolved function SSLv23_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QSslSocket: cannot call unresolved function SSLv23_client_method
QSslSocket: cannot call unresolved function SSL_CTX_new
QSslSocket: cannot call unresolved function SSL_library_init
QSslSocket: cannot call unresolved function ERR_get_error
QFont::setPixelSize: Pixel size <= 0 (0)
Answer: I encountered this same problem. It is caused by PyInstaller using incorrect
versions of ssleay32.dll and libeay32.dll.
To fix, download and install "[Win32 OpenSSL
v1.0.1e](http://slproweb.com/products/Win32OpenSSL.html)".
Then create a spec file for your PyInstaller project:
pyi-makespec browser.py
Open your spec file, named `browser.spec`, and below the `a =
Analysis(['browser.py'])` line, add:
for d in range(len(a.binaries)):
if a.binaries[d][0].lower() == 'ssleay32.dll':
print a.binaries[d]
a.binaries[d] = ('ssleay32.dll', 'C:\\\OpenSSL-Win32\\ssleay32.dll', 'BINARY')
if a.binaries[d][0].lower() == 'libeay32.dll':
print a.binaries[d]
a.binaries[d] = ('libeay32.dll', 'C:\\OpenSSL-Win32\\libeay32.dll', 'BINARY')
This will tell PyInstaller to use the OpenSSL-Win32 dlls instead of the ones
your Python installation is using.
When running the Python script, my Python installation preferred the DLLs in
my system path to those installed by pyOpenSSL/egenix, but when bundling with
PyInstaller, it seems to prefer the pyOpenSSL/egenix ones. This should fix
that.
|
Why does php md5() always different from python's hash.md5() if using chinese character?
Question: here is my php code:
$str = '你好';
$input_encoding = mb_detect_encoding($str, array('ASCII','GB2312','GBK','UTF-8'), true);
echo sprintf('input encoding:%s', $input_encoding);
$str_gb = iconv($input_encoding, 'GBK', true);
echo sprintf("utf8 encoding:%s\n", $str);
echo sprintf("gb encoding md5:%s\n", md5($str_gb));
echo sprintf("utf8 encoding md5:%s\n", md5($str));
here is my python code:
#!/usr/bin/env python
#coding:utf-8
import urllib
import hashlib
str_u = u'你好'
str_gb = str_u.encode('gbk')
str_u8 = str_u.encode('utf-8')
m = hashlib.md5()
m.update(str_gb)
str_gb_md5 = m.hexdigest()
m.update(str_u8)
str_u8_md5 = m.hexdigest()
print 'gb md5:%s' % str_gb_md5
print 'utf-8 md5:%s' % str_u8_md5
PHP code result is:
input encoding:CP936
utf8 encoding:你好
gb encoding md5:c4ca4238a0b923820dcc509a6f75849b
utf8 encoding md5:7eca689f0d3389d9dea66ae112e5cfd7
python code result is:
gb md5:b94ae3c6d892b29cf48d9bea819b27b9
utf-8 md5:a8a343223373c7d78c3fb8bad2d786c3
And here is my programming environment: PHP 5.5.4 (cli)&Python 2.6.8
THX!
Answer: There are mistakes in both your php and python code. The gbk md5 in you php
code and utf8 md5 in you python code are wrong.
Python part:
You misunderstand the usage of Python hashlib's `hash.update` function.
[hash.update(arg)](http://docs.python.org/2/library/hashlib.html#hashlib.hash.update)
> Update the hash object with the string arg. Repeated calls are equivalent to
> a single call with the concatenation of all the arguments: **m.update(a);
> m.update(b) is equivalent to m.update(a+b)**.
Fix:
print hashlib.md5(str_u8).hexdigest()
7eca689f0d3389d9dea66ae112e5cfd7
PHP part:
You forget to pass $str to the iconv function, instead you passed a true
value( which is coverts to 1).
Fix:
$str = '你好';
$str_gb = iconv('UTF-8', 'GBK', $str);
echo sprintf("gb encoding md5:%s\n", md5($str_gb));
output:
gb encoding md5:b94ae3c6d892b29cf48d9bea819b27b9
[iconv definition](http://www.php.net/manual/en/function.iconv.php):
string iconv ( string $in_charset , string $out_charset , string $str )
|
How to use spectral python to handle multispectral raster files?
Question: I'm interested in using [Spectral
Python](http://spectralpython.sourceforge.net/) (SPy) to visualize and
classify multiband raster GeoTIFF (not hyperspectral data). Currently it
appaers that only `.lan`, `.gis` File Formats are readable.
I've tried to convert files to `.lan` with `gdal_translate` but the image
format is not supported( `IOError: Unable to determine file type or type not
supported`).
Any idea how to use this library for non hypersperctral dataset?
Answer: Convert the GeoTIFF file to a compatible format (e.g. LAN). This can be done
in one of two ways. From a system shell, use
[gdal_translate](http://www.gdal.org/gdal_translate.html):
gdal_translate -of LAN file.tif file.lan
Or similar within Python:
from osgeo import gdal
src_fname = 'file.tif'
dst_fname = 'file.lan'
driver = gdal.GetDriverByName('LAN')
sds = gdal.Open(src_fname)
dst = driver.CreateCopy(dst_fname, sds)
dst = None # close dataset; the file can now be used by other processes
Note that the first method is actually better, as it also transfers other
metadata, such as the spatial reference system and possibly other data. To
correctly do the same in Python would require adding more lines of code.
|
Memoize a costly computation of a data frame
Question: I have a costly computation, running on pandas `DataFrames`. I'd like to
memoize it. I'm trying to figure out, what I can use for this.
In [16]: id(pd.DataFrame({1: [1,2,3]}))
Out[16]: 52015696
In [17]: id(pd.DataFrame({1: [1,2,3]}))
Out[17]: 52015504
In [18]: id(pd.DataFrame({1: [1,2,3]}))
Out[18]: 52015504
In [19]: id(pd.DataFrame({1: [1,2,3]})) # different results, won't work for my case
Out[19]: 52015440
In [20]: hash(pd.DataFrame({1: [1,2,3]})) # throws
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-3bddc0b20163> in <module>()
----> 1 hash(pd.DataFrame({1: [1,2,3]}))
/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in __hash__(self)
52 def __hash__(self):
53 raise TypeError('{0!r} objects are mutable, thus they cannot be'
---> 54 ' hashed'.format(self.__class__.__name__))
55
56 def __unicode__(self):
TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
Is it possible to do what I want, given that I'm sure that I'm not mutating
the `DataFrame` that gets memoized?
Answer: If you don't mind comparing indexes or column names, you can convert your
DataFrame to tuple:
>>> df1 = pd.DataFrame({1: [1,2,3]})
>>> df2 = pd.DataFrame({1: [1,2,3]})
>>> hash(tuple(tuple(x) for x in df1.values)) == hash(tuple(tuple(x) for x in df2.values))
True
>>> id(df1) == id(df2)
False
You can also use map function instead of generator:
tuple(map(tuple, df1.values))
If you need to compare indexes too, you can add it as a column. You can also
keep column names by creating namedtuple:
>>> from collections import namedtuple
>>> from pprint import pprint
>>> df = pd.DataFrame({1: [1,2,3], 2:[3,4,5]})
>>> df['index'] = df.index
>>> df
1 2 index
0 1 3 0
1 2 4 1
2 3 5 2
>>>
>>> dfr = namedtuple('row', map(lambda x: 'col_' + str(x), df.columns))
>>> res = tuple(map(lambda x: dfr(*x), df.values))
>>> pprint(res)
(row(col_1=1, col_2=3, col_index=0),
row(col_1=2, col_2=4, col_index=1),
row(col_1=3, col_2=5, col_index=2))
Hope it helps.
|
How to close wx.DirDialog programatically?
Question: I have wxpython app that open wx.DirDialog on button click.
dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
# Do some stuff
Since my application is multithreaded and uses wxTaskbaricon which allow user
(on Win 7) to close application even when modal DirDialog is open, I want to
close the DirDialog before closing main app. Somehow non of below method work:
dlg.Destroy()
dlg.Close(True)
Answer: It is my testing code.
I can test `Destroy()`, `Close()` and `EndModal()` on Modal and Non-Modal
`wx.DirDialog()`
To close modal dialog I had to use Timer - because modal dialog is blocking
access to the main window.
It can't close dialog only if I do
self.dlg = None
self.dlg.EndModal(wx.CANCEL) # or Destroy() or Close(True)
And one more thing - I use Linux Mint 15, Python 2.7.4, wxPython 2.8.12.1 :)
* * *
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import wx
import sys # to get python version
#----------------------------------------------------------------------
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(600,100))
self.panel = wx.Panel(self)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.panel.SetSizer(self.sizer)
self.label = wx.StaticText(self.panel, label="Python "+sys.version+"\nwxPython"+wx.version())
self.button1 = wx.Button(self.panel, label="On")
self.button2 = wx.Button(self.panel, label="Off")
self.sizer.Add(self.label)
self.sizer.Add(self.button1)
self.sizer.Add(self.button2)
self.Bind(wx.EVT_BUTTON, self.OpenDialog, self.button1)
self.Bind(wx.EVT_BUTTON, self.CloseDialog, self.button2)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.TimerCloseDialog, self.timer)
self.Show(True)
self.dlg = None
def OpenDialog(self, event):
print "OpenDialog"
self.timer.Start(3000, oneShot=True)
print "wait 3s ..."
if not self.dlg:
self.dlg = wx.DirDialog(self)
self.dlg.ShowModal()
#self.dlg.Show(True)
def CloseDialog(self, event):
print "CloseDialog"
if self.dlg:
#self.dlg = None
#self.dlg.EndModal(wx.CANCEL)
self.dlg.Destroy()
#self.dlg.Close(True)
def TimerCloseDialog(self, event):
print "TimerCloseDialog"
if self.dlg:
#self.dlg = None
self.dlg.EndModal(wx.CANCEL)
#self.dlg.Destroy()
#self.dlg.Close(True)
#----------------------------------------------------------------------
print "Python", sys.version
print "wxPython", wx.version()
app = wx.App()
frame = MyFrame(None, "Hello Dialog")
app.MainLoop()
|
Python Global Variable with thread
Question: How do I share a global variable with thread?
My Python code example is:
from threading import Thread
import time
a = 0 #global variable
def thread1(threadname):
#read variable "a" modify by thread 2
def thread2(threadname):
while 1:
a += 1
time.sleep(1)
thread1 = Thread( target=thread1, args=("Thread-1", ) )
thread2 = Thread( target=thread2, args=("Thread-2", ) )
thread1.join()
thread2.join()
I don't know how to get the two threads to share one variable.
Answer: You just need to declare `a` as a global in `thread2`, so that you aren't
modifying an `a` that is local to that function.
def thread2(threadname):
global a
while True:
a += 1
time.sleep(1)
In `thread1`, you don't need to do anything special, as long as you don't try
to modify the value of `a` (which would create a local variable that shadows
the global one; use `global a` if you need to)>
def thread1(threadname):
#global a # Optional if you treat a as read-only
while a < 10:
print a
|
Selenium configuration in Firefox using proxy
Question: I'm try to test a sample in Selenium using Python. I'm using a proxy server to
my connection to Internet with authentication. When I try to run the following
code :
from selenium import webdriver
if __name__ == '__main__':
proxy = "some_IP"
port = 3128
fp = webdriver.FirefoxProfile()
fp.set_preference('network.proxy.ssl_port', int(port))
fp.set_preference('network.proxy.ssl', proxy)
fp.set_preference('network.proxy.http_port', int(port))
fp.set_preference('network.proxy.http', proxy)
fp.set_preference('network.proxy.ftp', proxy)
fp.set_preference('network.proxy.ftp_port', int(port))
fp.set_preference('network.proxy.socks', proxy)
fp.set_preference('network.proxy.socks_port', int(port))
fp.set_preference('network.proxy.type', 1)
browser = webdriver.Firefox(firefox_profile=fp)
browser.set_page_load_timeout(15)
browser.get('http://www.google.com')
print browser.title
The Firefox browser open without any problem and in its proxy configuration
all it's ok, even the pop-up of authentication is opened. If I authenticate
myself I can navigate without any problem. The problem is that behind of this
I get the following errors :
Traceback (most recent call last):
File "D:/_Vkt0r/iStuffs/Jobs/Projects/test-proxy/test.py", line 25, in <module>
browser = webdriver.Firefox(firefox_profile=fp)
File "D:\_Vkt0r\iStuffs\Jobs\Projects\test-proxy\selenium\webdriver\firefox
\webdriver.py", line 62, in __init__ desired_capabilities=capabilities)
File "D:\_Vkt0r\iStuffs\Jobs\Projects\test-proxy\selenium\webdriver\remote
\webdriver.py", line 72, in __init__ self.start_session(desired_capabilities,
browser_profile)
File "D:\_Vkt0r\iStuffs\Jobs\Projects\test-proxy\selenium\webdriver\remote
\webdriver.py", line 114, in start_session 'desiredCapabilities':
desired_capabilities,
File "D:\_Vkt0r\iStuffs\Jobs\Projects\test-proxy\selenium\webdriver\remote
\webdriver.py", line 165, in execute
self.error_handler.check_response(response)
File "D:\_Vkt0r\iStuffs\Jobs\Projects\test-proxy\selenium\webdriver\remote
\errorhandler.py", line 136, in check_response raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>ERROR: Acceso Denegado a la Cach\xc3\xa9</title> <style type="text/css"><!-- /*\n Stylesheet for Squid Error pages\n Adapted from design by Free CSS Templates\n http://www.freecsstemplates.org\n Released for free under a Creative Commons Attribution 2.5 License\n*/\n\n/* Page basics */\n* {\n\tfont-family: verdana, sans-serif;\n}\n\nhtml body {\n\tmargin: 0;\n\tpadding: 0;\n\tbackground: #efefef;\n\tfont-size: 12px;\n\tcolor: #1e1e1e;\n}\n\n/* Page displayed title area */\n#titles {\n\tmargin-left: 15px;\n\tpadding: 10px;\n\tpadding-left: 100px;\n\tbackground: url(\'http://www.squid-cache.org/Artwork/SN.png\') no-repeat left;\n}\n\n/* initial title */\n#titles h1 {\n\tcolor: #000000;\n}\n#titles h2 {\n\tcolor: #000000;\n}\n\n/* special event: FTP success page titles */\n#titles ftpsuccess {\n\tbackground-color:#00ff00;\n\twidth:100%;\n}\n\n/* Page displayed body content area */\n#content {\n\tpadding: 10px;\n\tbackground: #ffffff;\n}\n\n/* General text */\np {\n}\n\n/* error brief description */\n#error p {\n}\n\n/* some data which may have caused the problem */\n#data {\n}\n\n/* the error message received from the system or other software */\n#sysmsg {\n}\n\npre {\n font-family:sans-serif;\n}\n\n/* special event: FTP / Gopher directory listing */\n#dirmsg {\n font-family: courier;\n color: black;\n font-size: 10pt;\n}\n#dirlisting {\n margin-left: 2%;\n margin-right: 2%;\n}\n#dirlisting tr.entry td.icon,td.filename,td.size,td.date {\n border-bottom: groove;\n}\n#dirlisting td.size {\n width: 50px;\n text-align: right;\n padding-right: 5px;\n}\n\n/* horizontal lines */\nhr {\n\tmargin: 0;\n}\n\n/* page displayed footer area */\n#footer {\n\tfont-size: 9px;\n\tpadding-left: 10px;\n}\n body :lang(fa) { direction: rtl; font-size: 100%; font-family: Tahoma, Roya, sans-serif; float: right; } :lang(he) { direction: rtl; } --></style> </head><body id=ERR_CACHE_ACCESS_DENIED> <div id="titles"> <h1>ERROR</h1> <h2>Cache Acceso Denegado</h2> </div> <hr> <div id="content"> <p>Se encontr\xc3\xb3 el siguiente error al intentar recuperar la direcci\xc3\xb3n URL: <a href="http://127.0.0.1:12233/hub/session">http://127.0.0.1:12233/hub/session</a></p> <blockquote id="error"> <p><b>Acceso Denegado a la Cach\xc3\xa9</b></p> </blockquote> <p>Lo lamento, tu no est\xc3\xa1s autorizado a solicitar http://127.0.0.1:12233/hub/session de este cach\xc3\xa9 hasta que te hayas autenticado.</p> <p>Please contact the <a href="mailto:webmaster?subject=CacheErrorInfo%20-%20ERR_CACHE_ACCESS_DENIED&body=CacheHost%3A%20squid.proxy%0D%0AErrPage%3A%20ERR_CACHE_ACCESS_DENIED%0D%0AErr%3A%20%5Bnone%5D%0D%0ATimeStamp%3A%20Tue,%2005%20Nov%202013%2019%3A44%3A22%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.10.33%0D%0A%0D%0AHTTP%20Request%3A%0D%0APOST%20%2Fhub%2Fsession%20HTTP%2F1.1%0AAccept-Encoding%3A%20identity%0D%0AContent-Length%3A%20131%0D%0AHost%3A%20127.0.0.1%3A12233%0D%0AAccept%3A%20application%2Fjson%0D%0AUser-Agent%3A%20Python-urllib%2F2.7%0D%0AConnection%3A%20close%0D%0AContent-Type%3A%20application%2Fjson%3Bcharset%3DUTF-8%0D%0A%0D%0A%0D%0A">cache administrator</a> if you have difficulties authenticating yourself.</p> <br> </div> <hr> <div id="footer"> <p>Generado Tue, 05 Nov 2013 19:44:22 GMT por squid.proxy (squid/3.1.19)</p> <!-- ERR_CACHE_ACCESS_DENIED --> </div> </body></html> '
I'm working with selenium 2.34 and Firefox 17. Any help is appreciated.
Answer: After 4 days finding a solution to this problem, finally I find it. The
problem is with the browser exclusions, I means the tab in proxy configuration
in any browser. You need to put in any browser you have in the exclusions the
two address:
localhost and 127.0.0.1
This is very important because if one left this cause problem with Selenium
because it try to connect to a address like two mentioned above.
|
Using the with statement in Python 2.5: SyntaxError?
Question: I have the following python code, its working fine with python 2.7, but I want
to run it on python 2.5.
I am new to Python, I tried to change the script multiple times, but i always
I got syntax error. The code below throws a `SyntaxError: Invalid syntax`:
#!/usr/bin/env python
import sys
import re
file = sys.argv[1]
exp = sys.argv[2]
print file
print exp
with open (file, "r") as myfile:
data=myfile.read()
p = re.compile(exp)
matches = p.findall(data)
for match in matches:
print " ".join("{0:02x}".format(ord(c)) for c in match)
Answer: Python 2.5 doesn't support the `with` statement yet.
To use it in Python 2.5, you'll have to import it from `__future__`:
## This shall be at the very top of your script ##
from __future__ import with_statement
Or, as in the previous versions, you can do the procedure manually:
myfile = open(file)
try:
data = myfile.read()
#some other things
finally:
myfile.close()
Hope it helps!
|
Authentication failing for MongoEngineResource with ReferenceField
Question: The request to the embedded field of MongoEngineResource doesn't go through
Authentication process, if it contains reference field.
My case is the following:
* there is a document Section, which consist of FieldDefinitions
* FieldDefinitions are EmbeddedDocuments
* FieldDefinition contains `embedded_section` (optional), which references to the Section, and there is a signal that excludes self-referencing (e.g. embedded_section can only reference to the section, which doesn't contain the FieldDefinition)
* this all is a part of moderator's interface, so i use authorization for all kinds of requests (get, post, patch, etc.)
Here is the code:
from tastypie_mongoengine.resources import MongoEngineResource
from tastypie.authentication import ApiKeyAuthentication
from apps.api.auth import CustomAuthorization
class FieldDefinitionResource(MongoEngineResource):
embedded_section = ReferenceField(attribute='embedded_section',
to='myproject.apps.api.resources.SectionResource',
full=True, null=True)
class Meta:
object_class = models.FieldDefinition # mongoengine EmbeddedDocument
authentication = ApiKeyAuthentication()
authorization = CustomAuthorization()
class SectionResource(MongoEngineResource):
fields = EmbeddedListField(attribute='fields',
of='myproject.apps.api.resources.FieldDefinitionResource',
full=True, null=True)
class Meta:
object_class = models.Section # mongoengine Document
authentication = ApiKeyAuthentication()
authorization = CustomAuthorization()
So, when i'm asking for a Section detail (e.g.
/api/v1/section/524df40502c8f109b07ed6ae/), everything goes smooth, and
`fields` attr is being displayed correctly in both cases of the presence and
absence of `embedded_section`.
But an attempt to refer to a specific field (e.g.
/api/v1/section/524df40502c8f109b07ed6ae/fields/0/) throws an error:
error_message: "'AnonymousUser' object has no attribute 'has_permission'"
has_permission is a method of MongoUser, which inherits from Django auth.User.
In the first case described (Section detail) it does go through Authentication
and fills request.user with a proper user object, while in the second case
(Section field) it skips Authentication stage entirely, going straight to
Authorization.
Am i doing something wrong?
Here is a full traceback:
{"error_message": "'AnonymousUser' object has no attribute 'has_permission'", "traceback": "Traceback (most recent call last):
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 195, in wrapper
response = callback(request, *args, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 277, in dispatch_subresource
return resource.dispatch(request=request, **kwargs)
File "/vagrant/myproject/myproject/apps/api/resources.py", line 248, in dispatch
super(FieldDefinitionResource, self).dispatch(request_type, request, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 776, in dispatch
self.instance = self._safe_get(bundle, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 768, in _safe_get
return self.parent.cached_obj_get(bundle=bundle, **filters)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 1113, in cached_obj_get
cached_bundle = self.obj_get(bundle=bundle, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie_mongoengine/resources.py", line 528, in obj_get
return super(MongoEngineResource, self).obj_get(bundle=bundle, **kwargs)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 2069, in obj_get
self.authorized_read_detail(object_list, bundle)
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/tastypie/resources.py", line 589, in authorized_read_detail
auth_result = self._meta.authorization.read_detail(object_list, bundle)
File "/vagrant/myproject/myproject/apps/api/auth.py", line 201, in read_detail
bundle.request.user.has_permission('read_detail',
File "/var/www/vhosts/myproject/local/lib/python2.7/site-packages/django/utils/functional.py", line 205, in inner
return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute 'has_permission'
"}
Answer: It is a known issue in django-tastypie-mongoengine: see
<https://github.com/wlanslovenija/django-tastypie-mongoengine/issues/71>
<https://github.com/wlanslovenija/django-tastypie-mongoengine/issues/72>
and <https://github.com/wlanslovenija/django-tastypie-mongoengine/issues/70>
Those 3 issues are about the same problem:
The Authentication is being performed only before the action itself, but not
before actions on a resource prior to the target action.
Example (using the code in my question): the target action `update_detail` of
the instance of FieldDefinitionResource, which is a child of SectionResource.
Prior to updating a detail of FieldDefinitionResource, there is a
`read_detail` of SectionResource - and this is an action, for which django-
tastypie-mongoengine skips the Authentication stage. It results in the absence
of request.user, which in its turn prevents the work-flow from moving towards
the target action (update_detail of the child resource).
This applies for EmbeddedDocumentField, EmbeddedListField, ReferencedListField
and ReferenceField.
One possible workaround is to override the authorization for embedded /
referenced document:
class CustomAuthorization(Authorization):
def read_detail(self, object_list, bundle):
# Double-check anonymous users, because operations
# on embedded fields do not pass through authentication.
if bundle.request.user.is_anonymous():
MyAuthentication().is_authenticated(bundle.request)
# Now authorize.
try:
return bundle.request.user.has_permission(object_list, 'read_detail')
except AttributeError:
raise Unauthorized(_('You have to authenticate first!'))
But of course, it would be nice to have it solved in the future releases.
|
Crash on call from boost::python::exec( anything )
Question: I'm trying to implement some Python stuff into my program and I've decided to
use Boost::Python, so I compiled it according to the instructions, with bjam,
using mingw/gcc, getting dlls and .a files
I'm using Code::Blocks for this, so I've put the dlls in the working directory
of my project, where the rest of dlls I use are, and decided to run
`boost::python::exec("b = 5");`
Instantly I get a crash. Ideas?
#include <boost/python.hpp>
float func(int a)
{
return a*a-0.5;
}
BOOST_PYTHON_MODULE(test_module)
{
using namespace boost::python;
def("func", func);
}
int main()
{
//Try one
boost::python::exec("b = 5");
//Crash
//Try two
Py_Initialize();
boost::python::exec("b = 5");
//Works fine
//Try three
Py_Initialize();
boost::python::exec("import test_module");
//Throws boost::python::error_already_set and crashes
/*
Something along the lines of
boost::python::exec("import test_module\n"
"var = test_module.func( 3 )\n");
*/
}
Under the build options section of my project, I've added
`libboost_python3-mgw48-d-1_54.dll` and `libpython33` to be linked so it'd
compile.
Ideas?
Answer: When embedding Python, almost all calls to Python or Boost.Python should occur
after the interpreter has been initialized with
[`Py_Initialize()`](http://docs.python.org/3.3/c-api/init.html#Py_Initialize).
Trying to invoke the interpreter before initialization, such as with
`boost::python::exec()`, will result in undefined behavior.
While that identifies the source of the crash, there are some subtle details
to obtain the accomplish the final goal of embedding Python and a module, then
have `exec` import the embedded module.
* When importing a module, Python will first check if the module is a built-in module. If the module is not a built-in module, then Python will try to load a library based on the module name, and expects the library to provide a function that will initialize the module. As the `test_module` is being embedded, its initialization needs to be explicitly added so that `import` can find it when searching for built-in modules.
* The `import` statement uses the `__import__` function. This function needs to be available within `exec`'s globals.
Here is a complete example demonstrating how to accomplish this:
#include <boost/python.hpp>
float func(int a)
{
return a*a-0.5;
}
BOOST_PYTHON_MODULE(test_module)
{
using namespace boost::python;
def("func", func);
}
// Use macros to account for changes in Python 2 and 3:
// - Python's C API for embedding requires different naming conventions for
// module initialization functions.
// - The builtins module was renamed.
#if PY_VERSION_HEX >= 0x03000000
# define MODULE_INIT_FN(name) BOOST_PP_CAT(PyInit_, name)
# define PYTHON_BUILTINS "builtins"
#else
# define MODULE_INIT_FN(name) BOOST_PP_CAT(init, name)
# define PYTHON_BUILTINS "__builtin__"
#endif
int main()
{
// Add the test_module module to the list of built-in modules. This
// allows it to be imported with 'import test_module'.
PyImport_AppendInittab("test_module", &MODULE_INIT_FN(test_module));
Py_Initialize();
namespace python = boost::python;
try
{
// Create an empty dictionary that will function as a namespace.
python::dict ns;
// The 'import' statement depends on the __import__ function. Thus,
// to enable 'import' to function the context of 'exec', the builtins
// module needs to be within the namespace being used.
ns["__builtins__"] = python::import(PYTHON_BUILTINS);
// Execute code. Modifications to variables will be reflected in
// the ns.
python::exec("b = 5", ns);
std::cout << "b is " << python::extract<int>(ns["b"]) << std::endl;
// Execute code using the built-in test_module.
python::exec(
"import test_module\n"
"var = test_module.func(b)\n",
ns);
std::cout << "var is " << python::extract<float>(ns["var"]) << std::endl;
}
catch (python::error_already_set&)
{
PyErr_Print();
}
}
When executed, its output is:
b is 5
var is 24.5
|
Sublime Text Plugin : Adding python libraries
Question: I'm trying to write a sublime text plugin which would make some windows api
calls. I did some research and found out that [this python
library](http://sourceforge.net/projects/pywin32/) provides the API's that I
need to use.
So, I'm trying to to use this library. When I add import statement for it in
my sublime text plugin it gives me error
ImportError: No module named win32api
I'd assume that it's because sublime text comes with inbuilt python and I
haven't actually installed these libraries on my system it's throwing up these
errors. How do I add such libraries in my sublime plugin also How would I
distribute such plugin?
Answer: In order to use a third-party library in Sublime, you'll need to include it in
your plugin directory, and you'll need to include the correct version for the
Python you're working with - 2.6 for ST2, 3.3 for ST3. In order for the next
step to succeed properly, install the version of Python you're targeting on
your system from [python.org](http://python.org/download). For example, if
you're working with ST3, make sure you install Python 3.3.2 on your system.
Then, download the correct version of `pywin32` from Christoph Gohlke's
[Python Extension Packages for
Windows](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32) repository.
Install it on your system, then try copying `c:\Python33\Lib\site-
packages\win32\` to your `Packages/MyPlugin` folder in Sublime. The installer
makes several directories in `site-packages`, so depending on the system calls
you're planning on making you might need to copy other directories as well -
`win32com`, `win32comext`, `pywin32_system32`, and/or `pythonwin`.
You should now be able to `import win32` or `import .win32` in your plugin.
Good luck!
|
Python code to retrieve absolute path of tomcat service
Question: I am trying to write a python code that retrieves the absolute path of tomcat
service by searching through the services with the service name in linux. Is
there any module i can use, Code snipplets will be highly appreciated.
Thanks in advance.
Answer: `psutil` is probably what you're looking for.
<https://pypi.python.org/pypi/psutil>
import psutil
process_name = u'jboss' # Place your case-insensitive process name here...
interesting_processes = []
# Loop over all processes, and see if process_name is in any segment of their command lines
for process in psutil.get_process_list():
try: # You cannot access some processes unless you're root, so we try here
for cmd_segment in process.cmdline:
if process_name.lower() in cmd_segment.lower():
interesting_processes.append(process)
except psutil.error.AccessDenied:
continue # processing other processes.
# Show off our results
for interesting_process in interesting_processes:
print 'Process ID: {} has command: {}\n'.format(interesting_process.pid, u' '.join(interesting_process.cmdline))
In the above example, interesting_process.cmdline will be a list of arguments
which make up the command line of your application.
HTH
|
Grail (web browser) installation on Scientific Linux
Question: I'm not sure if Grail browser is a good choice nowadays, however I want to try
it, because I have some problems about graphics running on Firefox-Fermi. The
next, is what I obtain after trying grail-0.6 (tgz)
# python grail.py
Traceback (most recent call last):
File "grail.py", line 43, in ?
from Tkinter import *
After installing "tkinter" adequately, I run "grail.py" again, and I get
# python grail.py
/root/grail-0.6/grailbase/app.py:6: Deprecation Warning: the regex module is
deprecated; please use the re module
import regex
/usr/lib/python2.4/regsub.py:15: DeprecationWarning: the regsub module is
deprecated; please use re.sub()
DeprecationWarning)
Traceback (most recent call last):
File "grail.py", line 499, in ?
main()
File "grail.py", line 108, in main
app = Application(prefs=prefs, display=display)
File "grail.py", line 248, in __init__
self.stylesheet = Stylesheet.Stylesheet(self.prefs)
File "/root/grail-0.6/Stylesheet.py", line 21, in __init__
self.load()
File "/root/grail-0.6/Stylesheet.py", line 45, in load
massaged.append((g, c), v % fparms_dict)
TypeError: append() takes exactly one argument (2 given)
but now, I'm not able to understand the message at all. May you advice me
about this problem?
Answer: Wow - that's a blast from the past! My advice is to give up: Grail hasn't been
touched in more than a dozen years. It's dead.
The error message you're getting stems from a change made way back in Python
1.6 (released 5 September 2000). Here's the message from the release notes:
> * The append() method for lists can no longer be invoked with more than
> one argument. This used to append a single tuple made out of all arguments,
> but was undocumented. To append a tuple, use e.g. l.append((a, b, c)).
>
So, you can:
1. Give up. Recommended ;-)
2. Install an ancient version of Python; or,
3. Change that line to
`massaged.append(((g, c), v % fparms_dict))`
and see what breaks next ;-)
## About the next problem
Python 0.9.1 is _extremely_ old, from early 1991. The language changed in
many, many ways before 1.0 was released.
According to [the old Grail home page](http://grail.sourceforge.net/), Grail
0.6:
> requires Python 1.5 or newer, and Tcl/Tk 8.0 or newer.
So find Python 1.5 if you're determined to pursue this ;-) Note that the
`.append()` semantics were changed in version 1.6, so the original `.append()`
code that hurt you at first should still work OK in 1.5.
|
python setup.py to install multiple modules
Question: Below is my setup.py code :
from os import path
import sys
python_version = sys.version_info[:2]
if python_version < (2, 6):
raise Exception("This version of xlrd requires Python 2.6 or above. "
"For older versions of Python, you can use the 0.8 series.")
av = sys.argv
if len(av) > 1 and av[1].lower() == "--egg":
del av[1]
from setuptools import setup
else:
from distutils.core import setup
from xlrd.xlrd.info import __VERSION__ as p
from xlwt.xlwt import __VERSION__
DESCRIPTION = (
'Library to create spreadsheet files compatible with '
'MS Excel 97/2000/XP/2003 XLS files, '
'on any platform, with Python 2.3 to 2.7'
)
CLASSIFIERS = [
'Operating System :: OS Independent',
'Programming Language :: Python',
'License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Office/Business :: Financial :: Spreadsheet',
'Topic :: Database',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',
]
KEYWORDS = (
'xls excel spreadsheet workbook worksheet pyExcelerator'
)
setup(
name = 'xlrd',
version = p,
author = 'John Machin',
author_email = '[email protected]',
url = 'http://www.python-excel.org/',
packages = ['xlrd'],
scripts = [
'xlrd/scripts/runxlrd.py',
],
package_data={
'xlrd/xlrd': [
'doc/*.htm*',
# 'doc/*.txt',
'examples/*.*',
],
},
keywords = ['xls', 'excel', 'spreadsheet', 'workbook'],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
'Topic :: Database',
'Topic :: Office/Business',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
setup (
name = 'xlwt',
version = __VERSION__,
maintainer = 'John Machin',
maintainer_email = '[email protected]',
url = 'http://www.python-excel.org/',
download_url = 'http://pypi.python.org/pypi/xlwt',
description = DESCRIPTION,
long_description = LONG_DESCRIPTION,
license = 'BSD',
platforms = 'Platform Independent',
packages = ['xlwt'],
keywords = KEYWORDS,
classifiers = CLASSIFIERS,
package_data = {
'xlwt/xlwt': [
'doc/*.*',
'examples/*.*',
'tests/*.*',
],
},
)
I have tried to marge `setup.py` of both `xlrd` and `xlwt` here and trying to
run master `setup.py` to install both the modules at one shot. It is
installing the modules but not the attributes so can't use those modules.
Basically my need is to run a single script and install multiple modules in
clients machine. Is is possible? Please guide me if ay other way I can do this
. Thanks in advance.
Answer: As an example of invoking setup.py of both packages. Let's consider that you
are in a some top level directory with the following structure:
mydir
|
|--setup.sh # global setup script
|
|--xlrd
| |
| |--...
| |--setup.py
| |--...
|
|--xlwt
|
|--...
|--setup.py
|--...
A shell script is simple:
#!/bin/sh
python ./xlrd/setup.py install
python ./xlwt/setup.py install
A batch script should be pretty similar:
xlrd\setup.py install
xlwt\setup.py install
|
Python itertools chain: possible to fill the shorter iterable with None
Question: When using the `itertools.chain` method to flatten a list like:
list(itertools.chain(*zip(itr1,itr2)))
Is it possible to fill the shorter iterable with None like in `itertools.imap`
for example? So I won't end up with:
In [1]: a = [1]
In [2]: b=[]
In [3]: list(itertools.chain(*zip(a,b)))
Out[3]: []
Answer: Use
[`itertools.izip_longest`](http://docs.python.org/2/library/itertools.html#itertools.izip_longest),
pass the default value to the `fillvalue` parameter.
Demo:
In [1]: from itertools import chain, izip_longest
In [2]: a = [1]
In [3]: b = []
In [5]: list(chain(*izip_longest(a, b, fillvalue='foo')))
Out[5]: [1, 'foo']
Default value of `fillvalue` is `None`.
|
How to connect to and keep the session alive using python requests
Question: I am trying to login to a site, and then view user details.
The API documentation from the site is:
LogOn : All Calls with JSON and return JSON type
post - https://www.bit2c.co.il/Account/LogOn {UserName:'',Password:'',SecondFactor:[optional]}
return true if OK , error list of strings if not
Balance - GET https://www.bit2c.co.il/Account/Balance
return UserBalance as JSON
I've tried connecting to the site using
import requests
session=requests.session()
session.auth = ("username", "pass")
session.post("https//www.bit2c.co.il/Account/Balance")
but i am getting response 200 and the response content is "you must login".
What am I doing wrong ?
Answer: What kind of _session_? What is on server-side? Can you post the raw
request/response pair(s)?
If PHP or ASP runs on server-side, you must capture the `Set-Cookie` header of
the response to the login request, find the session cookie and in consequent
requests you must set the `Cookie` header with the session cookie name and
value captured previously.
|
Python newbie, equal to a string?
Question: Trying to get my head arround why I cannot match the output of the IP against
a set IP and therefore render a outcome.
import urllib
import re
ip = '212.125.222.196'
url = "http://checkip.dyndns.org"
print url
request = urllib.urlopen(url).read()
theIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
print "your IP Address is: ", theIP
if theIP == '211.125.122.192':
print "You are OK"
else:
print "BAAD"
The result is always "BAAD"
Answer: `re.findall` returns a list of matches, not a string. So you've two options
now, either iterate over the list and use `any`:
theIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
if any(ip == '211.125.122.192' for ip in theIP):
print "You are OK"
else:
print "BAAD"
#or simply:
if '211.125.122.192' in theIp:
print "You are OK"
else:
print "BAAD"
or use `re.search`:
theIP = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
if theIP and (theIP.group() == '211.125.122.192'):
print "You are OK"
else:
print "BAAD"
|
Initialize a Python Constant Using a Function Declared After It
Question: I'm used to writing the following piece of code in Java or C# without errors.
It allows me to centralize the conversion of string to a floating point
representation. Unlike the simple implementation below, I have a lot more
going on in there to handle commas or brackets for negative numbers in Excel.
I can understand why Python gives an error. Python code is not compiled but
interpreted in sequence and `toFloat` does not exist for Python while its
processing the declaration of `ZERO` .
I was wondering if there is a pythonic way of doing this without having to
pull the `toFloat` function to another module OR without having to not declare
`ZERO` at the very top?
ZERO = toFloat('0.0') # <-- ERROR on this line "Undefined variable: toFloat"
def toFloat(val):
"""Function to convert a string to a float"""
return Decimal(val)
Answer: You are accessing an undefined symbol, which is a bad idea in many languages.
Python has no idea, what the symbol `toFloat` might refer to.
For illustration, what would you expect this code to do? Should `ZERO` be zero
or one?
ZERO = toFloat('0.0')
def toFloat(val): return Decimal(val)
def toFloat(val): return 1
Or in this case:
ZERO = toFloat('0.0')
if ZERO: from libone import toFloat #where toFloat returns 0
else: from libtwo import toFloat #where toFloat returns 1
The thing is you can redefine your symbols as many times you want. E.g. this
is legit code:
def f(): return 0
print(f())
def f(): return 1
print(f())
* * *
If it is of vital importance that `ZERO` be declared at the top of your code,
maybe you can use this ugly hack for your constants:
Put this in another file, let's say const.py:
class Constant:
def __init__(self, cf):
self.cf = cf
@property
def c(self):
try: return self.__c
except: self.__c = self.cf()
return self.__c
And then in your file, you can use:
from const import Constant
ZERO = Constant(lambda: toFloat('0.0'))
def toFloat(x): return 42
print(ZERO.c)
|
Create a dictionary from a csv file in python 3
Question: I am using Python 3.2 with a Mac OS Maverick and I am trying to get a .cvs
file with this format:
'Lisa plowed ', '1A', 'field', 'field', 'field', 'field', 'field'
'John greased ', '1A', 'axle', 'wheel', 'wheels', 'wheel', 'engine'
'Tracy freed ', '1A', 'animals', 'fish', 'slaves', 'slaves', 'slaves'
'Paul alleged ', '1A', 'truth', 'crime', 'facts', 'infidelity', 'incident'
into a dictionary, with the first item in each row being the key and the
remainder of the row being values mapped to that key. I have tried different
things, and the closest I got was with this code, but unfortunately, I am not
there yet:
import csv
data =open('test.csv', encoding = 'utf=8')
reader = csv.reader(data, delimiter=",")
for col in reader:
print(col)
result = {}
for row in reader:
key = row[0]
result[key] = row[1:]
print(result)
the result I got is just {} as if the dictionary was empty. I would really
appreciate any help on this, either by offering a new alternative or referring
me to where I can find an answer. Thanks a lot!
Answer: After the first time you iterate over `reader`, it is empty.
|
python dictionary into sqlite
Question: I have built a sqlite db and table in Python 2.7 with 6 variables, based on
reading a URL file.
I used JSON and created a dictionary. The code reads everything well and loops
through the keys and values.
I need to insert this into my table. That is where I am a little lost. I will
provide the code and I think my hole will be obvious.
import json
import urllib2
#Read file and print a line
webFD=urllib2.urlopen("http://rasinsrv07.cstcis.cti.depaul.edu/CSC455/assignment4.txt")
tweet = webFD.readline()
tweet
#create dictionary
dictt=json.loads(tweet)
#print dictionary
dictt.keys()
#print values
dictt.values()
#loop through tweets
for (key, value) in dictt.items():
print key, '->', value
#Created the DB
import sqlite3
conn = sqlite3.connect('twitter.db')
c = conn.cursor()
#Created the table for the tweets
c.execute("CREATE TABLE Tweet(created_at, id, text, source, in_reply_to_user_ID,retweet_Count)")
Here is my disconnect. Want to load those tweets (6 keys and values in the
dict into the Tweet tables:
for elt in tweet:
currentRow = elt[:-1].split(", ")
insert = """insert into Tweet values ('%s', '%s', '%s', '%s', '%s', '%s')""" %("created_at", "id", "text", 'source', 'in_reply_to_user_ID', 'retweet_Count')
print insert
Answer: What you're doing here makes no sense:
insert = """insert into Tweet values ('%s', '%s', '%s', '%s', '%s', '%s')""" %("created_at", "id", "text", 'source', 'in_reply_to_user_ID', 'retweet_Count')
Using `%`-formatting with literal strings just replaces each `%s` with the
literal string. So you'll get this:
insert into Tweet values ('created_at', 'id', 'text', 'source', 'in_reply_to_user_ID', 'retweet_Count')
And that's obviously nonsense; you want to insert the _values_ , not the
_column names_.
You _could_ —but should not—fix this by putting the six values into the `%`
operation, like this:
insert = """insert into Tweet values ('%s', '%s', '%s', '%s', '%s', '%s')""" % currentRow
But this is still a bad idea. What happens if one of those values could have a
quote in it? [This](http://xkcd.com/327/).
What you _want_ to do is this:
c.execute("insert into Tweet values (?, ?, ?, ?, ?, ?)", currentRow)
This lets the database handle formatting the values, making sure they're
quoted properly, etc.
|
After Anaconda installation, conda command fails with "ImportError: no module named conda.cli"
Question: I installed 64 bit Linux version of Anaconda recently (1.8.0-Linux-x86_64).
The installation seemed to work fine:
$ python
Python 2.7.5 |Continuum Analytics, Inc.| (default, Nov 4 2013, 15:30:26)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>>
##No issues here
However if I try any of the conda commands, I get an error:
$ conda info
Traceback (most recent call last):
File "~/anaconda/bin/conda", line 3, in <module>
from conda.cli import main
ImportError: No module named conda.cli
Installation is under my user directory (~/anaconda). I have verified that
$PATH contains ~/anaconda/bin. $PYTHONPATH is also set to ~/anaconda/lib.
Any thoughts on what is wrong with the 'conda' command? My searches do not
appear to show any one else reporting this error.
Answer: When you were installing it, you missed a section. When conda asked you if it
can set your .bashrc file, you probably clicked NO. It's a simple fix: fire up
your interpreter and add this line:
`export PATH=/home/add your username here/anaconda/bin:$PATH`
Now type `python` into the interpreter and you will see Anaconda 1.8.0 or
whatever version you have. You will have to do this each time you start a new
interpreter.
Enjoy!
|
Python - how to convert ctime to '%m/%d/%Y %H:%M:%S'
Question: Is there any direct way to convert ctime value to '%m/%d/%Y %H:%M:%S' format?
For example, convert "Wed Nov 6 15:43:54 2013" to "11/06/2013 15:43:54"
I tried the following but does not give me the format I want, which is
"11/06/2013 15:43:54":
>>> t = time.ctime()
>>> f = datetime.datetime.strptime(t, '%a %b %d %H:%M:%S %Y')
>>> print f
2013-11-06 15:43:54
But if I pass it directly to time.strftime, it'll want 9-item sequence:
>>> n = time.strftime(t, '%D %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Answer: In your example, you could just use `datetime.now`:
from datetime import datetime
d = datetime.now()
d.strftime('%m/%d/%Y %H:%M:%S')
Out[7]: '11/06/2013 18:59:38'
But. If you're taking in a `ctime` style string from somewhere else, parse it
with `datetime.strptime` then format it in the way you want using datetime's
`strftime` (not `time`'s).
from datetime import datetime
import time
d = datetime.strptime(time.ctime(),"%a %b %d %H:%M:%S %Y")
d.strftime('%m/%d/%Y %H:%M:%S')
Out[9]: '11/06/2013 19:01:11'
|
Python - PyQT4 how to detect the mouse click position anywhere in the window?
Question: I have 1024x768 resolution window, when there is a click or mouse over, i want
to find the x, y values. How can i do that?
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
#qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
qbtn.clicked.connect(self.test)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(0, 0, 1024, 768)
self.setWindowTitle('Quit button')
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show()
def test(self):
print "show the position of mouse cursor in screen resolution: x is ?? , y is ??"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Answer:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def mousePressEvent(self, QMouseEvent):
print QMouseEvent.pos()
def mouseReleaseEvent(self, QMouseEvent):
cursor =QtGui.QCursor()
print cursor.pos()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
#qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
#qbtn.clicked.connect(self.test)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(0, 0, 1024, 768)
self.setWindowTitle('Quit button')
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
#self.connect("clicked", self.test)
self.show()
def test(self):
print "test"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Output:
PyQt4.QtCore.QPoint(242, 285)
PyQt4.QtCore.QPoint(1741, 423)
PyQt4.QtCore.QPoint(439, 372)
PyQt4.QtCore.QPoint(1509, 549)
PyQt4.QtCore.QPoint(90, 6)
PyQt4.QtCore.QPoint(1468, 50)
PyQt4.QtCore.QPoint(302, 372)
PyQt4.QtCore.QPoint(1674, 382)
PyQt4.QtCore.QPoint(501, 416)
PyQt4.QtCore.QPoint(1867, 416)
PyQt4.QtCore.QPoint(605, 391)
PyQt4.QtCore.QPoint(1971, 391)
PyQt4.QtCore.QPoint(18, 16)
PyQt4.QtCore.QPoint(1384, 16)
PyQt4.QtCore.QPoint(12, 12)
PyQt4.QtCore.QPoint(1378, 12)
PyQt4.QtCore.QPoint(12, 12)
PyQt4.QtCore.QPoint(1378, 12)
PyQt4.QtCore.QPoint(12, 12)
PyQt4.QtCore.QPoint(1378, 12)
PyQt4.QtCore.QPoint(1019, 14)
PyQt4.QtCore.QPoint(2385, 14)
|
python isinstance(n, int) and int(n) == n
Question: Two functions:
def check(n):
if int(n) != n:
print("int(n) != n")
else:
print("int(n) == n")
and
def check2(n):
if not isinstance(n, int):
print("n is not an int")
else:
print("n is an int")
What's the difference? And which one is better?
Answer: The second one actually works (because it doesn't error out on something not
coerceable to int), but it really depends what you want to do. If you're
working in pure Python, the best thing to do is duck type - a function like
this is a slight tweak on check that will check if something is an integral
value (so, for example, it will work with `2.0` and also `2`, but not `'2'`
but not error out:
def check3(n):
"prints 'n is an int' if the value is integral"
try:
val = int(n)
if val == n:
print("n is an int")
except ValueError:
pass # return False would also work
print("n is not an int")
In contrast, if it's important to know the difference between `1.0` and `1`
(e.g., you have an int64 ndarray), then you'd want to use your instance
checking `check2`, because it will let you know that it's _exactly_ an int.
It boils down to this question: must it _be_ an int or just _act_ like an
integral number? If it has to be an int, then use check2, if it has to _act_
like an int, use check (but probably modify it to be within a try/except like
shown above).
The other option is to take advantage of abstract base classes to allow for
int-likes (for example, numpy int dtypes that are integral, but not actually
subclasses of int), using an abstract base class, `numbers.Integral`.
def check4(n):
if isinstance(n, (int, numbers.Integral)):
print("n is an int")
else:
print("n is not an int")
As an aside, `check4` is _much_ slower than _check3_ , because the lookup for
instance checking on abstract base classes involves some processing.
|
How to read line by line a particular length of a file and write it to a list using python programme
Question: > This is my python programme
IPS=[] # creating a list of IP addresses
w=sum(1 for line in open('my_dict.json')) # w=total no. of lines in my_dict.json file
ins=open("my_dict.json","r")
for lin in ins: # from each line of my_dict.json,storing IP addresses in IPS
IPS.append(lin[2:10])
print IPS
> Inside my_dict.json file IP addresses are stored as ["10.0.0.1/8"]
> ["10.0.0.2/8"]....["10.0.0.10/8"] ["10.0.0.11/8"]....etc..Now the problem
> is, for the IP values from 10.0.0.1 to 10.0.0.9 we can store that exactly in
> IPS as 10.0.0.1 to 10.0.0.9.But after that while 10.0.0.10,10.0.0.11 etc.
> comes then only 10.0.0.1 writes to IPS removing the last digit.Because we
> are writing lin[2:10] only.If we use it as lin[2:11] then the '/' value that
> immediately follows after ip address within the range 10.0.0.1 to 10.0.0.9
> will get written to IPS.So how should I modify programme to receive letters
> from 2 to 10 i.e lin[2:10] for ip addresses in the range 10.0.0.1 to
> 10.0.0.9 and after that letters from 2 to 11 i.e lin[2:11] for ip addresses
> 10.0.0.10,10.0.0.11,10.0.0.12 etc..
Answer: I think you can use regular expression to extract the IP part, code like this
import re
p = re.compile('\d+?\.\d+?\.\d+?\.\d+?')
IPS=[] # creating a list of IP addresses
w=sum(1 for line in open('my_dict.json')) # w=total no. of lines in my_dict.json file
ins=open("my_dict.json","r")
for lin in ins: # from each line of my_dict.json,storing IP addresses in IPS
result = p.search(a)
if result is not None
IPS.append(result.group(0))
print IPS
|
Python- Copy folders to another location without using disutils
Question: I'm iterating through a directory that contains lots of folders. I want to
copy each one of those folders from `src` to `dest`.
I have tried using `shutil's copytree`, but there is an issue involving
overriding existing folders. I see that the solution is to use disutils, but I
can't download disutils because my work computer prevents installation of new
packages and pip install doesn't appear to be working from work, either.
Is there an alternate solution using default packages?
Here's the code so you can understand what I'm working with:
import os
from os.path import join
import shutil
def main():
directory = "Daily_Completed_Surveys"
for root, dirs, files in os.walk(directory):
for i in dirs:
if "POP" in i:
src = os.path.join(root, i)
dest = "C:\ALLPOP"
shutil.copytree(src, dest)
The Daily_Completed_Surveys folder contains a structure like
/[somedate]/POP[ComputerID][SomeDate]/[zipped files]
I want to get every folder labeled POP and copy them to the destination
directory. (The folders themselves and the data, not just the zipped data) How
do I do this?
Answer: You could just check if the a directory in `src` exists in `dest`, and if it
does, remove it from `dest` using `shutil.rmtree()`, then use
`shutil.copytree()` to copy the directory and its content over.
Also, not being able to use `pip` somewhat sucks. If you have a proxy to the
outside world you can go through that by using
pip install --proxy="user:password@server:port" packagename
|
Sending binary/hex through socket (Python)
Question: I'm developing a secure file transfer system with Python and I'm dealing now
with the protocol. My idea is to have something like:
[Command:1byte][DataLength:2bytes][Data]
My problem is that I have no idea on how to deal with binary/hex in Python.
Imagine that I send a packet which command (in binary) is `00000001` (1byte).
The dataLength = 200 bytes, then, since I have 16bits to store it, I have
`0000000011001000`. So the header is: `000000010000000011001000`. The question
is: how to send that "raw", without coding the 0's and 1's with 1byte each?
Answer: You can use the modules
[`struct`](http://docs.python.org/2/library/struct.html) and
[`array`](http://docs.python.org/2/library/array.html) for this as:
>>> from struct import pack, unpack
>>> from array import array
>>>
>>> # byte (unsigned char) + 2 bytes (unsigned short)
>>> header = pack('BH', 0, 15)
>>> # array of 15 null byte, you can also use string
>>> buffer = array('B', '\0' * 15).tostring()
>>>
>>> header
'\x00\x00\x0f\x00'
>>> buffer
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>
>>> header + buffer
'\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>
You should consider of the byte order. Now to unpack that buffer you can do:
>>> package = header + buffer
>>>
>>> package
'\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>>
>>> # unpacking the header
>>> unpack('BH', package[:4])
(0, 15)
>>>
>>> # unpacking the payload
>>> array('B', package[4:])
array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>>
|
PyQt: displaying Python interpreter output
Question: I've implemented [this answer](http://stackoverflow.com/a/8356465/889604) into
my code, which I was hoping would do what I want. However, I'm running a
method via a connection on a `QPushButton`, and I want to pipe what happens in
this method to the GUI.
The first time I click the button the `stdout` appears in the interpreter
window; however, on subsequent presses of the button, the `stdout` appears in
the `QTextEdit` \- I assume there's some intricacy of the print statement, or
of `QPushButton`, that I don't understand - if anyone can give any pointers
where I need to start changing my code I'll be eternally grateful!
I think this is the smallest amount of code I can use to demonstrate the
problem..
import os, sys
from PyQt4 import QtCore, QtGui
def main():
app = QtGui.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
self.runBtn = QtGui.QPushButton('Run!', self)
self.runBtn.clicked.connect(self.runCmd)
self.te = QtGui.QTextEdit()
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.runBtn)
layout.addWidget(self.te)
self.setLayout(layout)
def runCmd(self):
print "here"
print sys.stdout
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
def __del__(self):
sys.stdout = sys.__stdout__
def normalOutputWritten(self, text):
cursor = self.te.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.te.setTextCursor(cursor)
self.te.ensureCursorVisible()
class EmittingStream(QtCore.QObject):
textWritten = QtCore.pyqtSignal(str)
def write(self, text):
self.textWritten.emit(str(text))
if __name__ == "__main__":
main()
Answer: You're mixing signals with method calls:
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
I'm not sure what this is supposed to do. You should do this instead:
self.stream = EmittingStream()
self.stream.textWritten.connect(self.normalOutputWritten)
but only once when you start the program. When you want to see the output, do
this:
try:
sys.stdout = self.stream
... code to print something ...
finally:
sys.stdout = sys.__stdout__ # reset stdout to default
|
Python regex, pulling patterns out of a match and using them as input back into the match
Question: I have searched for an answer. I am sure they are out there, but there are way
too many false hits.
This is my script (my attempt fails):
#!/bin/env python
import re
usage="""
My favorite restaurant is <<<res>>>
My favorite person is <<<per>>>
"""
res="pizza hut"
per="my sister"
def main():
value = re.sub(r'<<<(\w+)>>>', globals()[r'\1'], usage)
print 'value=%s.' % (value)
if ( __name__ == "__main__"):
main()
What I am trying to output is:
value=
My favorite restaurant is pizza hut
My favorite person is my sister
.
The closest [answer](http://stackoverflow.com/questions/6206804/regex-to-
replace-variables) that I have seen, involves maintaining a separate list. I
do not want to have to maintain a separate list.
Answer: You can use a function as the replacement in `re.sub()`. The function will
receive the [match object](http://docs.python.org/2/library/re.html#match-
objects) as the only argument and should return a string. The best way to do
this is to create a dictionary with your replacements:
import re
usage="""
My favorite restaurant is <<<res>>>
My favorite person is <<<per>>>
"""
rep = {"res": "pizza hut",
"per": "my sister"}
print re.sub(r'<<<(\w+)>>>', lambda m: rep.get(m.group(1), ""), usage)
You could use this exact same method with `globals()`, but using `globals()`
in this way is generally discouraged when a dictionary offers the same
behavior in a safer way.
|
Stop python from going to the very last statement
Question: I am currently writing a program that will solve the pythagorean theorem.
However, I have a bug in the program. Whenever I put in a negative number for
length a or b, it prints out "A cannot be less than zero" but goes ahead and
solves for C anyway and prints out the length of C even though the user hasn't
input b yet. How can I make it so when the user inputs a negative number it
prints out the statement "A cannot be less than zero" and then loops again to
inputting a length for the side, instead of how it is now where after it
prints out the statement it redirects to the end?
Here is my code:
import math
print"This program will solve the pythagorean theorem for you"
unit=raw_input('Enter the unit you will be using')
a=float(raw_input('Enter the length of side a'))
if a<=0:
print"A cannot be less than zero"
else:
b=float(raw_input('Enter the length of side b'))
if b<=0:
print"B cannot be less than zero"
else:
c2=(a**2)+(b**2)
c=math.sqrt(c2)
c=str(c)
print "The length of side C is: "+ c + " " + unit + "."
Answer: You missed one indentatino level. Try it like this :
if a<0:
print"A cannot be less than zero"
else:
b=raw_input('Enter the length of side b')
b=float(b)
if b<0:
print"B cannot be less than zero"
else:
c2=(a**2)+(b**2)
c=math.sqrt(c2)
c=str(c)
print "The length of side C is: "+ c + " " + unit + "."
|
Matplotlib funcanimation blit slow
Question: I'm having issues with a slow animation in Matplotlib. I'm animating results
from a simulation, which is easiest visualized with an array of rectangles
that change color with time.
Following recommendations
[here](http://stackoverflow.com/questions/8955869/why-is-plotting-with-
matplotlib-so-slow/8956211#8956211), I'm using blitting to only draw the
(small fraction) of rectangles that change in each frame. I also tried to
implement this using FuncAnimation, but when using that with Blit=True, the
script runs much slower.
I'm wondering if this is because I'm returning _all_ of the rectangles to
FuncAnimation, so it redraws all of them even if they haven't changed. Is
there a way to pass different artists at each frame to FuncAnimation? I tried
just passing a tuple of the ones that had changed (the commented out block in
the "animate" function), but that led to seemingly random animation frames...
Use:
$ python2 [script].py blit
$ python2 [script].py anim
Thanks!
import sys
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.animation as manim
def animate_data(plot_type):
"""
Use:
python2 plot_anim.py [option]
option = anim OR blit
"""
# dimension parameters
Nx = 30
Ny = 20
numtimes = 100
size = 0.5
if plot_type == "blit":
# "interactive mode on"
plt.ion()
# Prepare to do initial plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
# An array in which to store the rectangle artists
rects = np.empty((Nx, Ny), dtype=object)
# Generate initial figure of all green rectangles
for (i,j),k in np.ndenumerate(rects):
color = 'green'
rects[i, j] = plt.Rectangle([i - size / 2, j - size / 2],
size, size, facecolor=color, edgecolor=color)
ax.add_patch(rects[i, j])
ax.autoscale_view()
# "Old" method using fig.canvas.blit()
if plot_type == "blit":
plt.show()
fig.canvas.draw()
# Step through time updating the rectangles
for tind in range(1, numtimes):
updated_array = update_colors(rects)
for (i, j), val in np.ndenumerate(updated_array):
if val:
ax.draw_artist(rects[i, j])
fig.canvas.blit(ax.bbox)
# New method using FuncAnimate
elif plot_type == "anim":
def animate(tind):
updated_array = update_colors(rects)
# # Just pass the updated artists to FuncAnimation
# toupdate = []
# for (i, j), val in np.ndenumerate(updated_array):
# if val:
# toupdate.append(rects[i, j])
# return tuple(toupdate)
return tuple(rects.reshape(-1))
ani = manim.FuncAnimation(fig, animate, frames=numtimes,
interval=10, blit=True, repeat=False)
plt.show()
return
# A function to randomly update a few rectangles
def update_colors(rects):
updated_array = np.zeros(rects.shape)
for (i, j), c in np.ndenumerate(rects):
rand_val = np.random.rand()
if rand_val < 0.003:
rects[i, j].set_facecolor('red')
rects[i, j].set_edgecolor('red')
updated_array[i, j] = 1
return updated_array
if __name__ == "__main__":
if len(sys.argv) > 1:
plot_type = sys.argv[1]
else:
plot_type = "blit"
animate_data(plot_type)
Answer: Update 600 rectangles every frame is very slow, `cbar_blit` mode in your code
is faster because you only update the rectangles which's color is changed. You
can use `PatchCollection` to speedup drawing, here is the code:
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import matplotlib.animation as manim
from matplotlib.collections import PatchCollection
Nx = 30
Ny = 20
numtimes = 100
size = 0.5
x, y = np.ogrid[-1:1:30j, -1:1:20j]
data = np.zeros((numtimes, Nx, Ny))
for i in range(numtimes):
data[i] = (x-i*0.02+1)**2 + y**2
colors = plt.cm.rainbow(data)
fig, ax = plt.subplots()
rects = []
for (i,j),c in np.ndenumerate(data[0]):
rect = plt.Rectangle([i - size / 2, j - size / 2],size, size)
rects.append(rect)
collection = PatchCollection(rects, animated=True)
ax.add_collection(collection)
ax.autoscale_view(True)
def animate(tind):
c = colors[tind].reshape(-1, 4)
collection.set_facecolors(c)
return (collection,)
ani = manim.FuncAnimation(fig, animate, frames=numtimes,
interval=10, blit=True, repeat=False)
plt.show()
|
What factors cause data not to go through in sockets in python (or python/node.js)?
Question: (Suggestions for rephrasing questions?)
I'm sending data over a socket with client/server pattern. When I run python
(in pycharms) the output on the receiving end doesn't get data. However, when
I use the re-rerun icon (in pycharms) the data goes through.
I'm confused to be honest by this behavior and not sure what to ask besides
telling you what I observe.
Here is the client code. It's talking to server setup with `net` (node.js)
**client.py**
import socket // python version 2.7.*
if __name__ == "__main__":
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 7000))
client.sendall("test data to transmit")
data = client.recv(50)
client.close()
print 'Received', repr(data)
**server.js**
var net = require('net'); // node v0.10.21 (latest)
var PYTHON = {HOST :'127.0.0.1', PORT :7000};
net.createServer(function(socket) {
console.log('CONNECTION for Python: ' + socket.remoteAddress +':'+ socket.remotePort);
var body = '';
socket.on('data', function(data) {
console.log('DATA ' + socket.remoteAddress );
body += data;
});
socket.on('close', function(err) {
console.log('finish transmitting data... ');
console.log(body);
});
}).listen(PYTHON.PORT, PYTHON.HOST, function() {
console.log('---->socket to talk to python '
+ PYTHON.HOST + ':' + PYTHON.PORT);
});
**update** : added server.js code
Answer: I have a guess at the problem.
The client calls `sendall` to send some data, then calls `recv` to get a
response.
But the server doesn't have any code anywhere to send a response. So the
client will wait forever. That means it will never close the socket. Which
means the `socket.on('close')` callback in your server will never get called.
Since that's where you're printing the body, nothing will get printed out.
When you hit the "re-run" icon, presumably it kills the previous instance of
your client before launching a new one. Killing the client will cause the
socket to close, so the server will finally get to the `console.log(body)`
call.
And it's definitely possible (but certainly not guaranteed) for the new client
to start up and connect before the server can finish processing the old
client's close, so these could show up in either order.
* * *
So, how can you fix this?
Well, I'm not sure whether the problem is that the client is trying to receive
data when it shouldn't be expecting any, or that the server isn't sending data
when it should be.
If it's the former, just remove the `data = client.recv(50)` line (and the
`print` at the end) from the client.
If it's the latter, add a line somewhere in the server that sends something
back to the client. You most likely want it in the `on('data')` callback, but
that's not the _only_ place it could conceivably make sense (for example, you
could do it right at the top of the socket connection callback). And you might
as well add a callback so you can see it succeeding. So:
socket.on('data', function(data) {
// your existing code here
socket.write("Here's a response", function() {
console.log('finish writing...');
});
});
|
Get elements out of list in python
Question: Hi i just started with python and have a pretty nooby question.
I have a list which looks like this:
[(1.0, 'Test1'), (1,3 'Test2'), (1.4 'Test3')]
How can i get only "Test1 Test2 Test3" as a return?
best regards
Answer:
>>> L = [(1.0, 'Test1'), (1.3, 'Test2'), (1.4, 'Test3')]
>>> [x[1] for x in L]
['Test1', 'Test2', 'Test3']
>>> " ".join(x[1] for x in L)
'Test1 Test2 Test3'
You could also use `itemgetter(1)`, but the methods above would generally be
preferred
>>> from operator import itemgetter
>>> " ".join(map(itemgetter(1), L))
'Test1 Test2 Test3'
|
Distribute a simple python script
Question: I have a simple python script which reads a text file and do some processing
on it. I need to distribute this code. So any one with Ubuntu operating system
could run it. I import some modules as follows.
import pandas
import httpbl
from prettytable import from_csv
etc...
My question is how to make these packages installable with my script in any
other users machine(Ubuntu).
There are lot of questions asked and I found
[this](http://stackoverflow.com/questions/1950218/distributing-python-
programs) as the closest match. But any way I do not have much knowledge on
doing this.
Answer: You should checkout setuptools: <http://pythonhosted.org/setuptools/> which
can do exactly what you're looking for.
As an example (this is just a script in the same directory called "recat"):
from setuptools import setup
setup(
name = 'recat',
version = '0.1',
packages = [],
author = 'Name',
author_email = 'email',
description = 'Replay log files simply and easily',
license = 'GPLv3',
keywords = 'log replay',
url = 'URL',
scripts = ['recat']
)
You might also consider creating a Ubuntu package out of it. The FPM project
can help you with that: <https://github.com/jordansissel/fpm>
|
How does `findAll` work in BeautifulSoup?
Question: Can someone please explain how `findAll` works in BeautifulSoup?
My doubt is this row: `A = soup.findAll('strong',{'class':'name fn'})`. it
looks like find some characters matching certain criteria.
but the original codes of the webpage is like ......`<STRONG class="name
fn">iPod nano 16GB</STRONG>`......
how does the `('strong',{'class':'name fn'})` pick it up? thanks.
original Python codes
from bs4 import BeautifulSoup
import urllib2
import re
url="http://m.harveynorman.com.au/ipods-audio-music/ipods/ipods"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
A = soup.findAll('strong',{'class':'name fn'})
for B in A:
print B.renderContents()
Answer: From the docs: [Beautifulsoup Docs
](http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#The%20basic%20find%20method%3a%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20%2a%2akwargs%29)
Beautiful Soup provides many methods that traverse(goes through) the parse
tree, gathering `Tags` and `NavigableStrings` that match criteria you specify.
From The basic find method: `findAll(name, attrs, recursive, text, limit,
**kwargs)`
The `findAll` method traverses the tree, starting at the given point, and
finds all the `Tag` and `NavigableString` objects that match the criteria you
give. The signature for the `findall` method is this:
findAll(name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
The `name` argument can be used to pass in a:
* tag name (e.g. < B >)
* a regular expression
* a list or dictionary
* the value True
* a callable object
The keyword arguments impose restrictions on the attributes of a tag.
It's very useful to search for a tag that has a certain CSS class, but the
name of the CSS attribute, `class`, is also a Python reserved word.
You could search by CSS class with `soup.find("tagName", { "class" :
"cssClass" })`,like the code you gave) but that's a lot of code for such a
common operation. Instead, you can pass a string for `attrs` instead of a
dictionary.
The doc has further examples to help you understand.
|
Python exercise with url and string counting
Question: i'm having a little problem with an exercise i have to do : Basically the
assignment is to open an url, convert it into a given format, and count the
number of occurrences of given strings in the text.
import urllib2 as ul
def word_counting(url, code, words):
page = ul.urlopen(url)
text = page.read()
decoded = ext.decode(code)
result = {}
for word in words:
count = decoded.count(word)
counted = str(word) + ":" + " " + str(count)
result.append(counted)
return finale
The result i should get is like " word1: x, word2: y, word3: z " with x,y,z
being the number of occurrences. But it seems that i only get ONE number, when
i try to run the test program i get as result only like 9 for the first
occurrences, 14 for the second list, 5 for the third, missing the other
occurrences and the whole counted value. What am i doing wrong? Thanks in
advance
Answer: You're not appending to the dictionary correctly.
The correct way is `result[key] = value`.
So for your loop it would be
for word in words:
count = decoded.count(word)
result[word] = str(count)
An example without decode but using `.count()`
words = ['apple', 'apple', 'pear', 'banana']
result= {}
for word in words:
count = words.count(word)
result[word] = count
>>> result
>>> {'pear': 1, 'apple': 2, 'banana': 1}
|
sending mail from gmail account - Python
Question: could someone kindly tell me, what's wrong with the code below? TIA :)))
import smtplib
if raw_input("if you want to send a message from a gmail account, type yes: ") == 'yes':
try:
sender = raw_input("from:\n")
senders_pwd = raw_input("password:\n")
recipient = raw_input("to:\n")
print 'ok, now compile your message:'
subject = raw_input("subject:\n")
body = raw_input("your message:\n")
message = "subject: %s\n%s" %(subject,body)
server = smtplib.SMTP("smtp.gmail.com",587)
server.ehlo()
server.starttls()
server.ehlo()
print "ok, I've sent your email"
except:
print 'failed to send'
Answer: You need to call the sendmail() function. Add something like these three lines
after the last server.ehlo():
server.login(sender, senders_pwd)
server.sendmail(sender, recipient, message)
server.close()
|
NZEC Runtime Error in Python 2.7 in SPOJ
Question: I think my algo is right(may be done very badly) But I get the desired outputs
in ideone.com. But in SPOJ it keeps on saying "Runtime Error NZEC". Please
suggest a few changes to get this right.
Here is the link to the Question :
<http://www.spoj.com/problems/RAFANOLE/>
Here is my code :
import sys;
inp=sys.stdin.read().split("\n");
t=int(inp[0]);
i=1;
g_N=dict();
g_D=dict();
t_N=dict();
t_D=dict();
while(i<t+2):
a=inp[i].split();
game_N =0;
curr_N =0;
game_D =0;
curr_D =0;
tie_N=0;
tie_D=0;
k=0;
n=len(a);
while ((k<n)and((game_N<6)or(game_D<6))):
if(a[k]=='N'):
curr_N = curr_N +1;
if(curr_N==4 and curr_D < 3):
game_N=game_N +1;
curr_N=0;
curr_D=0;
if(curr_N==3 and curr_D ==3) :
while(a[k]!=a[k+1]):
k=k+1;
if(a[k]=='N'):
game_N=game_N+1;
curr_N=0;
curr_D=0;
if(a[k]=='D'):
curr_D=curr_D+1;
if(curr_D==4 and curr_N<3):
game_D=game_D+1;
curr_D=0;
curr_N=0;
if(curr_N==3 and curr_D ==3) :
while(a[k]!=a[k+1]):
k=k+1;
if(a[k]=='D'):
game_D=game_D+1;
curr_N=0;
curr_D=0;
k=k+1;
if (game_N==6 and game_D ==6):
break;
if((game_N==6 and game_D==5 ) or (game_N==5 and game_D==6)):
curr_N=0
while(game_N != 7 and game_D != 7):
if (a[k]=='N'):
curr_N=curr_N+1;
if(a[k]=='D'):
curr_D=curr_D+1;
if(curr_N==4 and curr_D<3):
game_N=game_N+1;
if(curr_D==4 and curr_N<3):
game_D=game_D+1;
if (game_N==6 and game_D ==6):
while (1):
if(a[k]=='N'):
tie_N=tie_N+1;
if(a[k]=='D'):
tie_D=tie_D+1;
if(((tie_D==7 or tie_N==7) and (abs(tie_D-tie_N)>=2)) or ((tie_D>7 or tie_N>7)and(abs(tie_D-tie_N)>=2))):
break;
k=k+1;
if(tie_N>tie_D):
game_N=game_N+1;
elif(tie_N<tie_D) :
game_D=game_D+1;
g_N[i]=game_N;
g_D[i]=game_D;
t_N[i]=tie_N;
t_D[i]=tie_D;
i=i+2;
i=1;
while(i<t+2):
if(g_N[i]>g_D[i]):
if(t_N[i]==0 and t_D[i] ==0):
print ("N %d" % g_N[i]);
print ("D %d" % g_D[i]);
print "\t";
else :
print ("N %d(%d-%d)"%(g_N[i],t_N[i],t_D[i]));
print ("D %d" % g_D[i]);
else:
if(t_N[i]==0 and t_D[i] ==0):
print ("D %d" % g_D[i]);
print ("N %d" % g_N[i]);
else :
print ("D %d(%d-%d)"%(g_D[i],t_D[i],t_N[i]));
print ("N %d" % g_N[i]);
i=i+2;
Thanks in Advance.
Answer: You are not considering the fact that the input data ends. `sys.stdin` is a
file like object and requires an EOF character to mark the end. As it is not
present, python tries to read more data when none is present and you get an
error.
You should use `input` or `raw_input` instead of `sys.stdin`. As an example,
in the code above, replace the 2nd and the 3rd lines with (assuming you use
Python 2.7)
t = input("")
Also replace the first line in the first `while` with
a = input("")
|
Rendering Persian (Farsi) words in PIL for Python
Question: I am trying to make images based on Persian (Farsi) text. I am using PIL for
Python3. Here is my code:
from PIL import Image, ImageFont, ImageDraw
text = "خطاب"
image = Image.new("RGBA", (100,100), (255,255,255))
font = ImageFont.truetype("FreeFarsiMono.ttf", 60, encoding='unic')
draw = ImageDraw.Draw(image)
draw.text((0,0), text, (0,0,0), font=font)
image.save("Test.png")
image.show()
However when I run the code I get some rectangular boxes with question mark in
them, instead of the image of the text! I would appreciate any help on this.
Answer: First you have to set the coding of the source:
# -*- coding: utf-8 -*-
Then you have to decode your text:
text = text.decode('utf-8')
Your final code should be sth like this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image, ImageFont, ImageDraw
text = "ﻡﻼﺳ"
text = text.decode('utf-8')
image = Image.new("RGBA", (100,100), (255,255,255))
font = ImageFont.truetype("yekan.ttf", 45, encoding='unic')
draw = ImageDraw.Draw(image)
draw.text((0,0), text, (0,0,0), font=font)
image.save("Test.png")
image.show()
_Note_ If you had your letters separated, you'd convert them; e.g. you can use
[awebfont](http://awebfont.ir/convert/) to solve that problem.
Output:

|
python pandas beginner: multi-dimensional data-analysis workflow (groupby+agg+plot)
Question: I'm new into pandas and try to learn how to process my multi-dimensional data.
## My data
Let's assume, my data is a big CSV of the columns ['A', 'B', 'C', 'D', 'E',
'F', 'G']. This data describes some simulation results, where ['A', 'B', ...,
'F'] are simulation parameters and 'G' is one of the ouputs (only existing
output in this example!).
**EDIT / UPDATE:** As _Boud_ suggested in the comments, let's generate some
data which is compatible to mine:
import pandas as pd
import itertools
import numpy as np
npData = np.zeros(5000, dtype=[('A','i4'),('B','f4'),('C','i4'), ('D', 'i4'), ('E', 'f4'), ('F', 'i4'), ('G', 'f4')])
A = [0,1,2,3,6] # param A: int
B = [1000.0, 10.000] # param B: float
C = [100,150,200,250,300] # param C: int
D = [10,15,20,25,30] # param D: int
E = [0.1, 0.3] # param E: float
F = [0,1,2,3,4,5,6,7,8,9] # param F = random-seed = int -> 10 runs per scenario
# some beta-distribution parameters for randomizing the results in column "G"
aDistParams = [ (6,1),
(5,2),
(4,3),
(3,4),
(2,5),
(1,6),
(1,7) ]
counter = 0
for i in itertools.product(A,B,C,D,E,F):
npData[counter]['A'] = i[0]
npData[counter]['B'] = i[1]
npData[counter]['C'] = i[2]
npData[counter]['D'] = i[3]
npData[counter]['E'] = i[4]
npData[counter]['F'] = i[5]
np.random.seed = i[5]
npData[counter]['G'] = np.random.beta(a=aDistParams[i[0]][0], b=aDistParams[i[0]][1])
counter += 1
data = pd.DataFrame(npData)
data = data.reindex(np.random.permutation(data.index)) # shuffle rows because my original data doesn't give any guarantees
Because the parameters ['A', 'B', ..., 'F'] are generated as a cartesian-
product (meaning: nested for-loops; a priori), i want to use groupby for
obtaining each possible 'simulation scenario' before analysing the output.
The parameter 'F' describe multiple runs for each scenario (each scenario
defined by 'A', 'B', ..., 'E' ; let's assume, that 'F' is the random-seed), so
my code becomes:
grouped = data.groupby(['A','B','C','D','E'])
# -> every group defines one simulation scenario
grouped_agg = grouped.agg(({'G' : np.mean}))
# -> the mean of the simulation output in 'G' over 'F' is calculated for each group/scenario
## What do i want to do now?
* **I** : display all the (unique) values of each scenario-parameter within these groups -> grouped_agg gives me an iterable of tuples, where for example all the entries at each position 0 give me all the values for 'A' (so with a few lines of python i would get my unique values, but maybe there is a function for that)
* **Update: my approach**
* `list(set(grouped_agg.index.get_level_values('A')))` (when interested in 'A'; using set for obtaining unique values; probably not the stuff you want to do, if you need high performance)
* => `[0, 1, 2, 3, 6]`
* **II** : generate some plots (of lower dimension) -> i need to make some variables constant and filter/select my data before plotting (therefore step I needed) =>
* 'B' const
* 'C', const
* 'E' const
* 'D' = x-axis
* 'G' = y-axis / output from my aggregation
* 'A' = one more dimension = multiple colors within 2d-plot -> one G/y-axis for each value of 'A'
**How would i generate a plot like that?**
I think, that reshaping my data is the key step and pandas plotting
capabilities will handle it then. Maybe achieving a shape, where there are 5
columns (one for each value of parameter A) and the corresponding G-values for
each index-selection + param-A-selection is enough, but i wasn't able to
achieve that form yet.
Thanks for your input!
(i'm using pandas 0.12 within enthought canopy)
Sascha
Answer: I: If I understand your example and desired output, I don't see why grouping
is necessary.
data.A.unique()
II: Updated....
I will implement the example you sketch above. Assume that we have averaged
'G' over the random seed ('F') like so:
data = data.groupby(['A','B','C','D','E']).agg(({'G' : np.mean})).reset_index()
Start by selecting the rows where B, C, and E have some constant values that
you specify.
df1 = data[(data['B'] == const1) & (data['C'] == const2) & (data['E'] == const3)]
Now we want to plot 'G' as a function of 'D', with a different color for every
value of 'A'.
df1.set_index('D').groupby('A')['G'].plot(legend=True)
I tested the above on some dummy data, and it works as you describe. The range
of 'G' corresponding to each 'A' are plotting in the distinct color on the
same axes.
III: I don't know how to answer that broad question.
IV: No, I don't think that's an issue for you here.
I suggest playing with simpler, small data sets and getting more familiar with
pandas.
|
ValueError: Invalid \escape while running query
Question: I am trying to query DBpedia using SPARQLWrapper in Python (v3.3). This is my
query:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?slot WHERE {
<http://dbpedia.org/resource/Week> <http://www.w3.org/2002/07/owl#sameAs> ?slot
}
It results in an error from the SPARQLWrapper package:
> ValueError: Invalid \escape: line 118 column 74 (char 11126)
Code:
query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?slot WHERE{{ {subject} {predicate} {object} }} "
query = query.format(subject=subject, predicate=predicate, object= objectfield)
self.sparql.setQuery(query)
self.sparql.setReturnFormat(JSON)
results = self.sparql.query().convert() # Error thrown at this line
Error :
Traceback (most recent call last):
File "getUriLiteralAgainstPredicate.py", line 84, in <module>
sys.exit(main())
File "getUriLiteralAgainstPredicate.py", line 61, in main
entity,predicateURI,result = p.getObject(dataAtURI,predicates, each["entity"])
File "getUriLiteralAgainstPredicate.py", line 30, in getObject
result = self.run_sparql("<"+subjectURI+">","<"+predicateURI+">","?slot")
File "getUriLiteralAgainstPredicate.py", line 24, in run_sparql
results = self.sparql.query().convert()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/Wrapper.py", line 539, in convert
return self._convertJSON()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/Wrapper.py", line 476, in _convertJSON
return jsonlayer.decode(self.response.read().decode("utf-8"))
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/jsonlayer.py", line 76, in decode
return _decode(string)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/SPARQLWrapper-1.5.2-py3.3.egg/SPARQLWrapper/jsonlayer.py", line 147, in <lambda>
_decode = lambda string, loads=json.loads: loads(string)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py", line 368, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Invalid \escape: line 118 column 74 (char 11126)
Answer: The problem is, that dbpedia output has this line:
{ "slot": { "type": "uri", "value": "http://got.dbpedia.org/resource/\U00010345\U00010339\U0001033A\U00010349" }},
Notice literals which start with `\U` (capital U). This is not valid JSON and
python doesn't know how to handle it. So, problem is on DBPedia side and it
can't be handled on SPARQLWrapper side.
But… You can handle it yourself like this:
results = self.sparql.query()
body = results.response.read()
fixed_body = body.decode("unicode_escape")
from SPARQLWrapper.Wrapper import jsonlayer
results = jsonlayer.decode(fixed_body)
|
Where is font 'nametofont' in python33?
Question: This code generates an error:
import tkinter
from tkinter.font import Font, nametofont
default_font = Font.nametofont("TkDefaultFont")
The error is:
Traceback (most recent call last):
File "C:\__P\nametofont.pyw", line 4, in <module>
default_font = Font.nametofont("TkDefaultFont")
AttributeError: type object 'Font' has no attribute 'nametofont'
>>>
How do I get access to 'nametofont'?
Answer: Ok, I figured out what I needed. Here is the modified and working code, with
an added print statement:
from tkinter import Tk
from tkinter.font import Font, nametofont
root = Tk()
default_font = nametofont("TkDefaultFont")
print(default_font)
The `Font.nametofont(...)` needed to be just `nametofont(...)`, and then it
needed the `TK()` to get a window context to look in.
|
"Cannot import name __version__" when installing pip package in Python 3
Question: I've created a fresh venv running Python 3.3.2. While trying to install
Campaign Monitor's createsend package via pip, it yields:
Running setup.py egg_info for package createsend
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/vagrant/3.3.2venv/build/createsend/setup.py", line 5, in <module>
from createsend import __version__
File "./createsend/__init__.py", line 1, in <module>
from createsend import __version__
ImportError: cannot import name __version__
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/vagrant/3.3.2venv/build/createsend/setup.py", line 5, in <module>
from createsend import __version__
File "./createsend/__init__.py", line 1, in <module>
from createsend import __version__
ImportError: cannot import name __version__
I believe this package is Python 3 compatible. I'm running the latest version
of pip. Can anyone explain why I'm receiving this error?
Answer: No, this package is **not** Python 3 compatible. It is using relative imports:
from createsend import __version__
File "./createsend/__init__.py", line 1, in <module>
from createsend import __version__
where the second `createsend` is meant to be
[`createsend/createsend.py`](https://github.com/campaignmonitor/createsend-
python/blob/master/createsend/createsend.py#L16). Instead, Python 3 sees it as
an absolute package and the recursive import fails to find the `__version__`
name.
|
Insert a file to google drive using google app engine. python client api used
Question: Using Google App Engine, I am trying to insert a file "a.txt" into my google
drive. The error that i get when i view page source of InsertDrive page is
HttpError 401 "Login Required" **_bound method InsertDrive.error of
main.InsertDrive object at 0x10f884b0_**
Note: I am calling class InsertDrive from my MainHandler Class by showing the
url in the Jinja template for the MainHandler class.
import httplib2
import logging
import os
import sys
from os import path
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
from apiclient import discovery
from oauth2client import appengine
from oauth2client import client
from google.appengine.api import memcache
from apiclient import errors
from apiclient.http import MediaFileUpload
import webapp2
import jinja2
CREDENTIAL = 'drive.credential'
CLIENT_SECRET_JSON = 'client_secrets.json'
SCOPE = 'https://www.googleapis.com/auth/drive'
FILE_NAME = 'a.txt'
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
autoescape=True,
extensions=['jinja2.ext.autoescape'])
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
MISSING_CLIENT_SECRETS_MESSAGE = """
Warning: Please configure OAuth 2.0
""" % CLIENT_SECRETS
http = httplib2.Http(memcache)
service = discovery.build('drive', 'v2', http=http)
decorator = appengine.oauth2decorator_from_clientsecrets(
CLIENT_SECRETS,
scope=[
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.apps.readonly',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata.readonly',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive.scripts',
],
message=MISSING_CLIENT_SECRETS_MESSAGE)
title="a.txt"
description="none"
mime_type="text/*"
filename="a.txt"
parent_id=None
class MainHandler(webapp2.RequestHandler):
@decorator.oauth_aware
def get(self):
insert_url = "/InsertDrive"
if not decorator.has_credentials():
url = decorator.authorize_url()
self.redirect(url)
self.response.write("Hello")
#variables = {
# 'url': decorator.authorize_url(),
# 'has_credentials': decorator.has_credentials(),
# 'insert_url': "/InsertDrive"
# }
template = JINJA_ENVIRONMENT.get_template('main.html')
self.response.write(template.render(insert_url=insert_url))
class InsertDrive(webapp2.RequestHandler):
# ADDED FUNCTION TO UPLOAD #
def get(self):
self.response.out.write('<h1>entered</h1>')
media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
self.response.write(media_body)
body = {
'title': title,
'description': description,
'mimeType': mime_type
}
self.response.write(body)
# Set the parent folder.
if parent_id:
body['parents'] = [{'id': parent_id}]
self.response.write(parent_id)
try:
file = service.files().insert(
body=body,
media_body=media_body).execute()
self.response.write(file)
# Uncomment the following line to print the File ID
# print 'File ID: %s' % file['id']
except errors.HttpError , error:
self.response.write('<h1>checking if error</h1>: %s' % error)
self.response.write(self.error)
print 'An error occured: %s' % error
app = webapp2.WSGIApplication(
[
('/', MainHandler),
('/InsertDrive' , InsertDrive),
(decorator.callback_path, decorator.callback_handler()),
],
debug=True)
Any help would be greatly appreciated Thanks, kira_111
Answer: i tried your code and the problem is fixed if when u try to upload the file
instead of using this code
file = service.files().insert(
body=body,
media_body=media_body).execute()
you use this
file = service.files().insert(
body=body,
media_body=media_body).execute(http=decorator.http())
the difference is that you specify that the credentials that will be used for
the upload are the ones that you have authenticated using the decorator.
Hope it helps
|
Installing Mapnik 2.2.0 in windows 7 with Python 2.7
Question: I've been trying to install mapnik on my computer for hours but what i always
get when I import mapnik is `ImportError: DLL load failed: The specified
procedure could not be found`.
I'm using Windows 7. The currently installed software is Geoserver from
Opengeo suite.
**Here is my path**
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\Java\jre7\bin;C:\Program Files\Java\jdk1.7.0_45\bin;C:\Python27;C:\mapnik-v2.2.0\lib
**My python path:**
C:\Python27;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Program Files\ArcGIS\bin;C:\\mapnik-v2.2.0\python\2.7\site-packages\;C:\mapnik-v2.2.0\bin\;
Answer: ### Follow the [install
instructions](https://gist.github.com/springmeyer/5651701)
> First ensure you have 32 bit python 27 installed.
You can do this by typing the following into a python shell
>>> import platform
>>> platform.architecture()
('32bit', 'WindowsPE')
If you see `'64bit'`, try reinstalling
[python](http://www.python.org/download/) with the `32bit` version (look for
the "Python 2.7.5 Windows Installer" link).
After that,
* [Download](https://gist.github.com/springmeyer/5651701) the `mapnik` package (I tested it with the full SDK version)
* Extract the archive to `C:\mapnik-v2.2.0`
* Add `C:\mapnik-v2.2.0\lib;` and `C:\mapnik-v2.2.0\bin;` to your `PATH`
* Add `C:\mapnik-v2.2.0\python\2.7\site-packages;` to your `PYTHONPATH`
`import mapnik`
|
rearrange the array elements using numpy in python
Question: How to get new array (NEW) from old array (OLD)?
import numpy as np
OLD=np.array([1,4,7,2,5,8,3,6,9])
NEW = [[1,2,3],[4,5,6],[7,8,9]]
NEW = OLD.reshape (???
Answer: Do you mean like this?
>>> import numpy as np
>>> OLD = np.array([1,4,7,2,5,8,3,6,9])
>>> OLD.reshape((3, 3), order='F')
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
|
How to give multiple values to a single key using a dictionary?
Question: I have a html form which has `Firstname`, `LastName`, `Age` and `Gender` and a
`ADD` button. I enter the data into the form and that gets into the Berkeelys
db. What my code does is it prints only the last values. I want that it should
show all the values related to particular key
#!/usr/bin/python
import bsddb
import cgi
form = cgi.FieldStorage()
print "Content-type:text/html\n"
Fname = form.getvalue('firstname', '')
Lname = form.getvalue('lastname', '')
Age = form.getvalue('age', 0)
Gender = form.getvalue('gender', '')
#print Fname, Lname, Age
db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db","w")
db['FirstName'] = Fname
db['LastName'] = Lname
db['Age'] = Age
db['Gender'] = Gender
db.close()
db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db","r")
#db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db")
print db['FirstName'], db['LastName'], db['Age'], db['Gender']
db.close()
print db
Answer: You should use an SQL database instead of the `dict`-based interface, since
SQL databases already handle multiple tuples in a table.
Anyway, if you want to have a `dict` interface you can use the `shelve` module
(`bsddb` is deprecated, so you should avoid it) and save each value in a
`list`:
import shelve
COLUMNS = ('FirstName', 'LastName', 'Age', 'Sex')
the_db = shelve.open('test.db', writeback=True)
for col_name in COLUMNS:
if col_name not in the_db:
the_db[col_name] = []
records = [
('John', 'Deer', 20, 'M'),
('Ada', 'Lovelace', 23, 'F'),
]
for record in records:
for col_name, value in zip(COLUMNS, record):
the_db[col_name].append(value)
the_db.close()
the_db = shelve.open('test.db')
for record in zip(*(the_db[col_name] for col_name in COLUMNS)):
print(record)
the_db.close()
The above code outputs:
('John', 'Deer', 20, 'M')
('Ada', 'Lovelace', 23, 'F')
* * *
If you want to use an SQL database you could use the `sqlite3` module. For
example:
import sqlite3
conn = sqlite3.connect('test.sqlite')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE people (
FirstName text,
LastName text,
Age int,
Sex text
)''')
cursor.execute('''
INSERT INTO people values ('John', 'Deer', 20, 'M')''')
cursor.execute('''
INSERT INTO people values ('Ada', 'Lovelace', 23, 'F')''')
conn.commit()
for record in cursor.execute('''SELECT * FROM people'''):
print(record)
The above code outputs:
(u'John', u'Deer', 20, u'M')
(u'Ada', u'Lovelace', 23, u'F')
(Note the `u'...'` simply means that the strings are unicode, it doesn't
change their value)
However this code has some problems (e.g. try to run it twice...), but if you
want to follow this path then you **must** learn SQL first, so go ahead and
stufy it (there are a lot of online tutorials. For example `w3schools` ones).
|
Python Script invalid syntax answer
Question: This is a python script i am working on, i am new to pyhton scripting, this is
what we are learning in school, i need some help with it. this is the error i
keep getting, i dont understand what the invalid syntax is. thank you for any
help. The "import maya.cmds as cmds", this is part of the program i am working
on,
#Error: line 1: invalid syntax
# File "<maya console>", line 27
# transformInScene = cmds.ls(type='transform')
# ^
# SyntaxError: invalid syntax #
cmds.file(new=True,force=True)
import maya.cmds as cmds
def changeXtransformValue(myList, percentage=1.0):
"""
Changes the value of each transform in the scene by a percentange.
Parameters:
percentage - Percentange to change each transform's value. Default value is 1.
Returns:
Nothing.
"""
*# The ls command is the list command. It is used to list various nodes
# in the current scene. You can also use it to list selected nodes.*
transformInScene = cmds.ls(type='transform')
found = False
for thisTransform in transformInScene:
if i not in ['front','persp','side','top']:
found = True
break
else:
found = False
if found == False:
sphere1 = cmds.polySphere()[0]
cmds.xform(sphere1, t = (0.5, 0.5, 0.5)
*#This is the line where I am having problems*
transformInScene = cmds.ls(type='transform')
sel =cmds.ls(sl=True)
if sel :
transformInScene = sel
# If there are no transforms in the scene, there is no point running this script
if not transformInScene:
raise RuntimeError, 'There are no transforms in the scene!'
badAttrs = list()
# Loop through each transform
for thisTransform in transformInScene:
if thisTransform not in ['front','persp','side','top']:
allAttrs = cmds.listAttr(thisTransform, keyable=True, scalar=True)
allAttrs = [ i for i in allAttrs if i = "visibility" ]
print allAttrs
for attr in myList:
if attr in allAttrs:
currentVal = cmds.getAttr( thisTransform + "." + attr )
newVal = currentVal * percentage
cmds.setAttr(thisTransform + "." + attr, newval)
print "Changed %s. %s from %s to %s" % (thisTransform,attr,currentVal,newVal)
else:
badAttrs.append(attr)
if badAttrs:
print "These attributes $s are not valid" % str()
myList = ["translateX", "translateY", "translateZ", "scaleX"]
changeXtransformVal(myList, percentage=1.0)
This is part of a school project and after fixing the indent, I cant seem to
find the problem
Answer: The line above...
cmds.xform(sphere1, t = (0.5, 0.5, 0.5)
is missing a closing parentheses for the `xform` call.
|
Efficient way to shift 2D-matrixes in python in both directions
Question: Given a two dimensional matrix, e.g.
l = [[1,1,1],
[2,5,2],
[3,3,3]])
what is the most efficient way of implementing a shift operation on columns
and rows?
E.g.
shift('up', l)
[[2, 5, 2],
[3, 3, 3],
[1, 1, 1]]
but
shift('left', l)
[[1, 1, 1],
[5, 2, 2],
[3, 3, 3]]
I'm using `collections.deque` on both depths because of [this
answer](http://stackoverflow.com/a/2150125/931303) but while a 'up' or 'down'
only requires 1 shift, a 'left' or 'right' requires N shifts (my
implementation is using a for cycle for each row).
In C I think this can be improved using pointer arithmetic (see e.g. [this
answer](http://stackoverflow.com/a/1479089/931303)).
Is there a better pythonic way?
**EDIT:**
* By efficient I mean if there is a way of avoiding the N shifts.
* We can assume the matrix is squared.
* The shift can be in place.
Thanks to martineau for pointing out these important points of the question.
I'm sorry I didn't pointed them out before.
Answer: Numpy provides a method called roll() to shift entries.
>>> import numpy as np
>>> x = np.arange(9)
>>> x = x.reshape(3, 3)
>>> print(x)
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> x = np.roll(x, -1, axis=0) # up
>>> print(x)
[[3 4 5]
[6 7 8]
[0 1 2]]
>>> x = np.roll(x, 1, axis=0) # down
>>> print(x)
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> x = np.roll(x, 2, axis=1) # right
>>> print(x)
[[1 2 0]
[4 5 3]
[7 8 6]]
>>> x = np.roll(x, -2, axis=1) # left
>>> print(x)
[[0 1 2]
[3 4 5]
[6 7 8]]
I guess that [Numpy](http://en.wikipedia.org/wiki/NumPy) will be pretty
efficient compared to most solutions
in terms of matrix operations and you won't be bound to a 2 dimensional
matrix.
|
Interactive input/output using python
Question: I have a program that interacts with the user (acts like a shell), and I want
to run it using python subprocess module interactively. That means, I want the
possibility to write to stdin and immediately get the output from stdout. I
tried many solutions offered here, but none of them seems to work for my
needs.
The code I've written based on [Running an interactive command from within
python](http://stackoverflow.com/questions/11457931/running-an-interactive-
command-from-within-python)
import Queue
import threading
import subprocess
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
def getOutput(outQueue):
outStr = ''
try:
while True: #Adds output from the Queue until it is empty
outStr+=outQueue.get_nowait()
except Queue.Empty:
return outStr
p = subprocess.Popen("./a.out", stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize = 1)
#p = subprocess.Popen("./a.out", stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, universal_newlines=True)
outQueue = Queue()
errQueue = Queue()
outThread = Thread(target=enqueue_output, args=(p.stdout, outQueue))
errThread = Thread(target=enqueue_output, args=(p.stderr, errQueue))
outThread.daemon = True
errThread.daemon = True
outThread.start()
errThread.start()
p.stdin.write("1\n")
p.stdin.flush()
errors = getOutput(errQueue)
output = getOutput(outQueue)
p.stdin.write("5\n")
p.stdin.flush()
erros = getOutput(errQueue)
output = getOutput(outQueue)
The problem is that the queue remains empty, as if there is no output. Only if
I write to stdin all the input that the program needs to execute and
terminate, then I get the output (which is not what I want). For example if I
do something like:
p.stdin.write("1\n5\n")
errors = getOutput(errQueue)
output = getOutput(outQueue)
Is there any way to do what I want to do?
**EDIT:** The script will run on a Linux machine. I changed my script and
deleted the universal_newlines=True + set the bufsize to 1 and flushed stdin
immediately after wrtie. Still I get no output.
**Second try:** I tried this solution and it works for me:
from subprocess import Popen, PIPE
fw = open("tmpout", "wb")
fr = open("tmpout", "r")
p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)
p.stdin.write("1\n")
out = fr.read()
p.stdin.write("5\n")
out = fr.read()
fw.close()
fr.close()
Answer: Two solutions for this issue on Linux:
First one is to use a file to write the output to, and read from it
simultaneously:
from subprocess import Popen, PIPE
fw = open("tmpout", "wb")
fr = open("tmpout", "r")
p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)
p.stdin.write("1\n")
out = fr.read()
p.stdin.write("5\n")
out = fr.read()
fw.close()
fr.close()
Second, as J.F. Sebastian offered, is to make p.stdout and p.stderr pipes non-
blocking using fnctl module:
import os
import fcntl
from subprocess import Popen, PIPE
def setNonBlocking(fd):
"""
Set the file description of the given file descriptor to non-blocking.
"""
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
flags = flags | os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
p = Popen("./a.out", stdin = PIPE, stdout = PIPE, stderr = PIPE, bufsize = 1)
setNonBlocking(p.stdout)
setNonBlocking(p.stderr)
p.stdin.write("1\n")
while True:
try:
out1 = p.stdout.read()
except IOError:
continue
else:
break
out1 = p.stdout.read()
p.stdin.write("5\n")
while True:
try:
out2 = p.stdout.read()
except IOError:
continue
else:
break
|
Restart gobject.timeout_add_seconds counter after a socket.error
Question: I decided to make some modifications to the weather tray applet **[found
here](http://heap.zloduch.cz/software/scripts/weatherboy)**.
After many tests, I found that **update_tray()** stops updating after my
computer spends some time on hibernation. Only updating it manually works.
After examining the code, I found the line responsible for the update is this:
gobject.timeout_add_seconds(self.args.delta * 60, self.update_tray)
The **[gobject documentation](http://www.pygtk.org/pygtk2reference/gobject-
functions.html#function-gobject--timeout-add)** says that _this function is
called repeatedly until it returns FALSE, at which point the timeout is
automatically destroyed and the function will not be called again._ But it
seems the counter is destroyed because the system clock changes so suddenly.
I'd like to know how can I get the timer restarted when this problem happens.
Here is the complete code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Released under the terms of the GNU GPLv2.
#
import gtk
import gobject
import time
import webbrowser
from urllib2 import urlopen, URLError
from argparse import ArgumentParser
from xml.dom import minidom
parser = ArgumentParser(description='Simple weather applet', epilog='Written by Roman Komkov and updated at 06.06.2012.\nPlease, report bugs to <[email protected]>')
parser.add_argument('-l', '--location', required=True, metavar='WOEID', help='location WOEID (more on http://developer.yahoo.com/weather/)')
parser.add_argument('-u', '--units', choices=['c','f'], default='c', metavar='c|f', help='units to display')
parser.add_argument('-d', '--delta', default='10', type=int, metavar='N', help='timeout in minutes between next weather data query')
parser.add_argument('-a', '--advanced', action = 'store_true', default=False, help='Advanced tooltip')
class Api:
def __init__(self, location, units):
self.params = (location,units)
self.url = 'http://xml.weather.yahoo.com/forecastrss?w=%s&u=%s'
self.namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
self.website = 'http://weather.yahoo.com/'
self.codes = { #code:icon name
'0':'weather-severe-alert',
'1':'weather-severe-alert',
'2':'weather-severe-alert',
'3':'weather-severe-alert',
'4':'weather-storm',
'5':'weather-snow-rain',
'6':'weather-snow-rain',
'7':'weather-snow',
'8':'weather-freezing-rain',
'9':'weather-fog',
'10':'weather-freezing-rain',
'11':'weather-showers',
'12':'weather-showers',
'13':'weather-snow',
'14':'weather-snow',
'15':'weather-snow',
'16':'weather-snow',
'17':'weather-snow',
'18':'weather-snow',
'19':'weather-fog',
'20':'weather-fog',
'21':'weather-fog',
'22':'weather-fog',
'23':'weather-few-clouds',
'24':'weather-few-clouds',
'25':'weather-few-clouds',
'26':'weather-overcast',
'27':'weather-clouds-night',
'28':'weather-clouds',
'29':'weather-few-clouds-night',
'30':'weather-few-clouds',
'31':'weather-clear-night',
'32':'weather-clear',
'33':'weather-clear-night',
'34':'weather-clear',
'35':'weather-snow-rain',
'36':'weather-clear',
'37':'weather-storm',
'38':'weather-storm',
'39':'weather-storm',
'40':'weather-showers-scattered',
'41':'weather-snow',
'42':'weather-snow',
'43':'weather-snow',
'44':'weather-few-clouds',
'45':'weather-storm',
'46':'weather-snow',
'47':'weather-storm',
'3200':'stock-unknown'
}
def conv_direction(self, value):
value = int(value)
if value >= 0 and value < 45:
return u'\u2191 (N)'
elif value >= 45 and value < 90:
return u'\u2197 (NE)'
elif value >= 90 and value < 135:
return u'\u2192 (E)'
elif value >= 135 and value < 180:
return u'\u2198 (SE)'
elif value >= 180 and value < 225:
return u'\u2193 (S)'
elif value >= 225 and value < 270:
return u'\u2199 (SW)'
elif value >= 270 and value < 315:
return u'\u2190 (W)'
elif value >= 315 and value < 360:
return u'\u2196 (NW)'
else:
return u'\u2191 (N)'
def get_data(self):
try:
url = self.url % self.params
dom = minidom.parse(urlopen(url))
units_node = dom.getElementsByTagNameNS(self.namespace, 'units')[0]
units = {'temperature': units_node.getAttribute('temperature'),
'distance': units_node.getAttribute('distance'),
'pressure': units_node.getAttribute('pressure'),
'speed': units_node.getAttribute('speed')}
forecasts = []
for node in dom.getElementsByTagNameNS(self.namespace, 'forecast'):
forecasts.append({
'date': node.getAttribute('date'),
'low': node.getAttribute('low')+u'\u00B0 '+units['temperature'],
'high': node.getAttribute('high')+u'\u00B0 '+units['temperature'],
'condition': node.getAttribute('text'),
'icon': self.codes.get(node.getAttribute('code'))
})
condition = dom.getElementsByTagNameNS(self.namespace, 'condition')[0]
location = dom.getElementsByTagNameNS(self.namespace, 'location')[0]
wind = dom.getElementsByTagNameNS(self.namespace, 'wind')[0]
atmosphere = dom.getElementsByTagNameNS(self.namespace, 'atmosphere')[0]
return {
'current_condition': condition.getAttribute('text'),
'current_icon': self.codes.get(condition.getAttribute('code')),
'current_temp': condition.getAttribute('temp')+u'\u00B0 '+units['temperature'],
'extra':{
'wind': {'direction':self.conv_direction(wind.getAttribute('direction')),
'speed':wind.getAttribute('speed')+' '+units['speed']},
'atmosphere': {'humidity':atmosphere.getAttribute('humidity')+'%',
'visibility':atmosphere.getAttribute('visibility')+' '+units['distance'],
'pressure':atmosphere.getAttribute('pressure')+' '+units['pressure']}},
'forecasts': forecasts,
'location' : {'city' : location.getAttribute('city'),'country' : location.getAttribute('country')}
}
except URLError, ex:
return None
class MainApp:
def __init__(self,args):
self.args = args
self.weather = None
self.tooltip = None
self.tray = gtk.StatusIcon()
self.tray.connect('popup-menu', self.on_right_click)
self.tray.connect('activate', self.on_left_click)
self.tray.set_has_tooltip(True)
if self.args.advanced:
self.tray.connect('query-tooltip', self.on_tooltip_advanced)
self.api = Api(self.args.location, self.args.units)
self.update_tray()
gobject.timeout_add_seconds(self.args.delta * 60, self.update_tray)
def on_tooltip_advanced(self, widget, x, y, keyboard_mode, tooltip):
#if self.tooltip:
#tooltip.set_text(self.tooltip)
if self.weather:
weather = self.weather
tooltip_text = '%s\n%s' % (self.weather['current_temp'],self.weather['current_condition'])
vbox = gtk.VBox()
header = gtk.Label()
header.set_markup('<u><b>'+self.weather['location']['city']+', '+self.weather['location']['country']+'</b></u>')
header.set_alignment(1.0, 0.5)
separator_h = gtk.HSeparator()
hbox = gtk.HBox()
now_image = gtk.Image()
now_image.set_padding(0,5)
now_image.set_pixel_size(48)
now_image.set_from_icon_name(weather['current_icon'],48)
now_label = gtk.Label()
now_label.set_markup('<b>'+tooltip_text+'</b>')
now_label.set_padding(5,5)
table = gtk.Table(columns=2, homogeneous=False)
u = 0
l = 1
for k,v in self.weather['extra'].iteritems():
h_label = gtk.Label()
h_label.set_markup('<b>'+k+'</b>')
h_label.set_alignment(0.0, 0.5)
h_label.set_padding(5,0)
table.attach(h_label,0,1,u,l)
for i,j in v.iteritems():
u +=1
l +=1
k_label = gtk.Label(i)
k_label.set_alignment(0.0, 0.5)
v_label = gtk.Label(j)
v_label.set_alignment(0.0, 0.5)
table.attach(k_label,0,1,u,l)
table.attach(v_label,1,2,u,l)
u +=1
l +=1
hbox.pack_start(now_image, False, False, 0)
hbox.pack_start(now_label, False, False, 0)
vbox.pack_start(header, True, False, 0)
vbox.pack_start(separator_h, False, False, 0)
vbox.pack_start(hbox, False, False, 0)
vbox.pack_start(table, False, False, 0)
vbox.show_all()
tooltip.set_custom(vbox)
else:
tooltip.set_text('Connection error!')
return True
def on_refresh(self,widget):
self.update_tray()
def on_right_click(self, icon, event_button, event_time):
menu = gtk.Menu()
refresh = gtk.MenuItem('Refresh')
refresh.show()
refresh.connect('activate', self.on_refresh)
quit = gtk.MenuItem('Quit')
quit.show()
quit.connect('activate', gtk.main_quit)
menu.append(refresh)
menu.append(quit)
menu.popup(None, None, gtk.status_icon_position_menu,
event_button, event_time, self.tray)
def on_left_click(self, widget):
webbrowser.open(self.api.website)
def update_tray(self):
self.weather = self.api.get_data()
if self.weather != None:
self.tray.set_from_icon_name(self.weather['current_icon'])
if not self.args.advanced:
tooltip_text = '%s / %s' % (self.weather['current_temp'],self.weather['current_condition'])
self.tray.set_tooltip_markup(tooltip_text)
else:
if not self.args.advanced:
self.tray.set_tooltip_text('Connection error!')
self.tray.set_from_stock('gtk-dialog-error')
return True
if __name__ == "__main__":
try:
args = parser.parse_args()
MainApp(args)
gtk.main()
except KeyboardInterrupt:
pass
As requested by @J.F.Sebastian, here is a smaller example of the code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import gtk, gobject, time
from datetime import datetime
class MainApp:
def __init__(self):
self.update_tray()
gobject.timeout_add_seconds(15 * 60, self.update_tray)
def update_tray(self):
print time.strftime('%c')
return True
if __name__ == "__main__":
try:
MainApp()
gtk.main()
except KeyboardInterrupt:
pass
**UPDATE:** I set it to update every minute, hibernated and, when returned,
the script kept working. After 10 minutes I got a **socket.error** and it just
didn't update anymore. I thought the problem wasn't with the internet
connection, because I couldn't reproduce it by just unplugging the cable. Now,
my question is: how can I restart the counter upon finding this error, or
avoid this error, since **get_data already has a`try:` statement?**
Traceback (most recent call last):
File "weatherboy", line 333, in update_tray
self.weather = self.api.get_data()
File "weatherboy", line 145, in get_data
dom = minidom.parse(urlopen(url))
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 401, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 419, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1211, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
r = h.getresponse(buffering=True)
File "/usr/lib/python2.7/httplib.py", line 1034, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 407, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 365, in _read_status
line = self.fp.readline()
File "/usr/lib/python2.7/socket.py", line 447, in readline
data = self._sock.recv(self._rbufsize)
socket.error: [Errno 104] Connection reset by peer
Answer: `update_tray()` should return True if you want it to be called. Unhandled
`socket.error` prevents that. You could use `except EnvironmentError` instead
of `except URLError` to catch wider range of errors inside `get_data()`.
To ignore other kind of errors, you could add `try: ... except Exception:
log_it()` to `update_tray()`.
|
Python timer clocking
Question: I am thinking to implement a function like below:
timeout = 60 second
timer = 0
while (timer not reach timeout):
do somthing
if another thing happened:
reset timer to 0
My question is how to implement the timer stuff? Multiple thread or a
particular lib?
I hope the solution is based on the python built-in lib rather than some
third-part fancy package.
Thanks in advance.
PS: A clue should be fine, you don't need to give the whole solution.
Answer: I don't think you need threads for what you have described.
import time
timeout = 60
timer = time.clock()
while timer + timeout < time.clock():
do somthing
if another thing happened:
timer = time.clock()
Here, you check every iteration.
The only reason you would need a thread is if you wanted to stop _in the
middle_ of an iteration if something was taking too long.
|
Creating buttons dependent on input, getting user data
Question: Relative noob to Python, still learning all the ins and outs, but I'm
learning. I'm diving into GUI for the first time for a personal project I'm
working on. (I'm a linguistics grad student and this will greatly improve my
ability to research.) I know about Tkinter and the Button class (basically,
that they exist), but I need some help to get me started. I think once I know
the magic words, I'll be able to adapt it to the situation I need.
Basically, I have sample text excerpt of about 180 words. What I am looking to
do is figure out a way to create a GUI interface such that each individual
word in the 180-word excerpt appears as a separate button, and the user is
prompted to, for example, click the verb. The value that is clicked gets
stored, and I then go on to whatever my next question is.
What I need to know: How to create the buttons depending on whatever the text
is. (I'm assuming each button will need a different variable name.) -Would it
matter if the length of one excerpt differs from another? (I'm assuming not.)
-Would it matter if there are several of the same words within the excerpt?
(I'm assuming not, since you could use indexing to remember where the word
clicked is in the original excerpt.) How to get the data stored depending on
the button clicked. How to clean the slate and go on to whatever my next
question would be.
Thanks in advance for your help.
Answer: This is a small example and demo -- it has everything you need to start your
program. See the comments inside the code:

import tkinter
app = tkinter.Tk()
# Create a set for all clicked buttons (set prevents duplication)
clicked = set()
# Create a tuple of words (your 180 verb goes here)
words = 'hello', 'world', 'foo', 'bar', 'baz', 'egg', 'spam', 'ham'
# Button creator function
def create_buttons( words ):
# Create a button for each word
for word in words:
# Add text and functionality to button and we are using a lambda
# anonymous function here, but you can create a normal 'def' function
# and pass it as 'command' argument
button = tkinter.Button( app,
text=word,
command=lambda w=word: clicked.add(w) )
# If you have 180 buttons, you should consider using the grid()
# layout instead of pack() but for simplicity I used this one for demo
button.pack()
# For demo purpose I binded the space bar, when ever
# you hit it, the app will print you out the 'clicked' set
app.bind('<space>', lambda e: print( *clicked ))
# This call creates the buttons
create_buttons( words )
# Now we enter to event loop -> the program is running
app.mainloop()
* * *
_**EDIT:_**
Here is the code without the _lambda expressions_ :
import tkinter
app = tkinter.Tk()
# Create a set for all clicked buttons (set prevents duplication)
clicked = set()
# Create a tuple of words (your 180 verb goes here)
words = 'hello', 'world', 'foo', 'bar', 'baz', 'egg', 'spam', 'ham'
# This function will run when pressing the space bar
def on_spacebar_press( event ):
print( 'Clicked words:', *clicked )
# Button creator function
def create_buttons( words ):
# Create a button for each word
for word in words:
# This function will run when a button is clicked
def on_button_click(word=word):
clicked.add( word )
# Add button
button = tkinter.Button( app,
text=word,
command=on_button_click )
# If you have 180 buttons, you should consider using the grid()
# layout instead of pack() but for simplicity I used this one for demo
button.pack()
# Binding function tp space bar event
app.bind('<space>', on_spacebar_press)
# This call creates the buttons
create_buttons( words )
# Now we enter to event loop -> the program is running
app.mainloop()
|
Python: `from x import *` not importing everything
Question: I know that `import *` is bad, but I sometimes use it for quick prototyping
when I feel too lazy to type or remember the imports
I am trying the following code:
from OpenGL.GL import *
shaders.doSomething()
It results in an error: `NameError: global name 'shaders' is not defined'
If I change the imports:
from OpenGL.GL import *
from OpenGL.GL import shaders
shaders.doSomething()
The error disappears. Why does `*` not include `shaders`?
Answer: If `shaders` is a submodule and [it’s not included in
`__all__`](http://docs.python.org/3/tutorial/modules.html#importing-from-a-
package), `from … import *` won’t import it.
[And yes, it is a
submodule.](http://pyopengl.sourceforge.net/documentation/pydoc/OpenGL.GL.shaders.html)
|
PyZMQ Gevent Websocket Connection Error
Question: I am trying pub/sub pattern using python zmq. I am facing a strange problem on
the client side. On the client side I am using pyzmq, gevent-websocket and
bottle as wsgi server. Though it works perfectly for one client, the other
clients are waiting for the first client to disconnect. While working with one
client, if I disconnect and reconnect, I am getting the messages two times or
more for each reconnect.
#!/usr/bin/python
from gevent import monkey; monkey.patch_all()
import zmq
import gevent
from bottle import route, run, request, abort, Bottle ,static_file
from gevent import sleep
from gevent.pywsgi import WSGIServer
import geventwebsocket
from geventwebsocket import WebSocketHandler, WebSocketError
host = "127.0.0.1"
port = 8000
mqport = "8082"
context = zmq.Context()
socket = context.socket(zmq.SUB)
app = Bottle()
@app.route('/v1/streams/device/<id>')
def handle_websocket(id):
socket.setsockopt(zmq.UNSUBSCRIBE, '')
socket.connect ("tcp://localhost:%s" % mqport)
socket.setsockopt(zmq.SUBSCRIBE, id)
wsock = request.environ.get('wsgi.websocket')
if wsock is None:
logger.info("Error creating websocket")
try :
while True:
string = socket.recv()
logger.info("%s" % string)
id, data = string.split(" ")
wsock.send("%s" % data)
sleep(0.1)
except geventwebsocket.WebSocketError, ex:
wsock.close()
sock.close()
server = WSGIServer((host, port), app,
handler_class=WebSocketHandler)
server.serve_forever()
All the examples I have seen use while loop for receiving the messages. I am
not comfortable with this while loop and looking for some call back function
like socket.on_message. For experimental purpose I wrote a node.js version of
the same without the while loop like this but in my project node is ruled out.
The node version is here:
var WebSocketServer = require('websocket').server;
var http = require('http');
global.client = 0;
var server = http.createServer(function(request, response) {
});
server.listen(8000, function() { });
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
console.log("connected client :", global.client++)
var connection = request.accept(null, request.origin);
var url = request.resourceURL.href
var device_id = url.substr(url.lastIndexOf('/') + 1)
var zeromq = require('zmq');
var sock = zeromq.socket('sub');
sock.connect('tcp://127.0.0.1:8082');
sock.subscribe(device_id);
sock.on('message', function(data) {
console.log(data.toString());
var msg = data.toString();
var rjson = msg.split(" ")
connection.send(rjson.pop());
});
connection.on('close', function(connection) {
});
});
Here I dont use the while Loop.
What I am doing wrong on my python code?
Answer: After hitting the wall on several days we find a non-blocking zeromq client
called gevent-zeromq.
Lesson is anybody using gevent-websocket with zmq client don't use pyzmq but
use gevent-zeromq.
Now the gevent-zeromq is merged with pyzmq. Intead of doing `import zmq` do
`from zmq.green import zmq`
|
How to pass dictionary from Jinja2 (using Python) to Javascript?
Question: How to pass dictionary from Jinja2 (using Python) to Javascript ? I have
dictionary in Python and when I render template I need to use that dictionary
with Javascript, I passed from Python
template = JINJA_ENVIRONMENT.get_template('sm.html')
self.response.write(template.render(values=values))
but how to store them in Javascript variable inside html page.
Answer: Use the `json` module to turn the Python data into JSON data; JSON is a subset
of JavaScript and does fine as a JavaScript literal:
import json
js_value = json.dumps(python_value)
and render the `js_value` in the template.
|
Replacing XML tags in Python
Question: I have an XML document with an `<en-media>` tag:
<en-media type="image/png" hash="06c5ec15535babbcd3eef471f51af870"/>
I am trying to change that tag to a HTML `<img>` so it would look like the
following:
<img src="06c5ec15535babbcd3eef471f51af870"/>
This works as the file is named after its hash.
I have been using xml.etree.ElementTree to try to do this and I have been
looking at <http://docs.python.org/2/library/xml.etree.elementtree.html> but I
cant seem to get anything near working.
Can anyone help me with this?
Thanks
Answer: Here is how it can be done with ElementTree.
Input XML (test.xml):
<root>
<en-media type="image/png" hash="06c5ec15535babbcd3eef471f51af870"/>
</root>
Python code:
from xml.etree import ElementTree as ET
root = ET.parse("test.xml").getroot()
# Get the 'en_media' element
en_media = root.find("en-media")
# Add the 'img' element (with 'src' attribute) as a sub-element of 'root'
img = ET.SubElement(root, "img", src=en_media.get("hash"))
# Remove 'en_media'
root.remove(en_media)
print ET.tostring(root)
Output:
<root>
<img src="06c5ec15535babbcd3eef471f51af870" /></root>
|
python - error in tkinter.py line 1470; lambda takes exactly 1; 0 given. when trying to load window
Question: I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
TypeError: <lambda>() takes exactly 1 argument (0 given)
When i call this class
class settingsWindow:
def __init__(self, master, settings):
self.master = master
self.titleLb = tk.Label(self.master, text='MesterMind', font=('Calibri', 22))
self.titleLb.grid(row=0, column=0, sticky='W', columnspan=2)
self.subTitleLb = tk.Label(self.master, text="Settings", font=('Calibri', 18))
self.subTitleLb.grid(row=1, column=0, sticky='W', columnspan=2)
Using this to create instance of the class
def settings(self):
self.settingsWindow = tk.Toplevel(self.master)
self.app = settingsWindow(self.settingsWindow, self.settings)
I have no idea what has caused the error and i don't see any obvious errors in
the code. I am using python 2.7
Any help is appreciated, thanks.
edit: NB, tk is the Tkinter module
edit here is the entire python module, (MasterMind.py). i think all the
relevent parts are above.
'''
Created on 9 Nov 2013
@author: SB960
'''
import Tkinter as tk
def settingsArgs():
'''
stores the settings for the game.
no param = get value
param = assign value | returns true if value assigned, false otherwise.
everything stored here is a constant for the duration of the game
'''
prefDic = {'COLOURS': 3,
'PEGS': 3,
'ROWS': 3,
'PLAYER1': 'COMPUTER',
'PLAYER2': 'COMPUTER'} #Dictionary containing preference values
def colours(int1 = 0):
if int1 == 0:
return prefDic['COLOURS']
elif 3 <= int1 <= 8:
prefDic['COLOURS'] = int1
return True
else:
return False
def pegs(int1 = 0):
if int1 == 0:
return prefDic['PEGS']
elif 3 <= int1 <= 8:
prefDic['PEGS'] = int1
return True
else:
return False
def rows(int1 = 0):
if int1 == 0:
return prefDic['ROWS']
elif 3 <= int1 <= 12:
prefDic['ROWS'] = int1
return True
else:
return False
def player1(string1 = ''):
if string1.isalnum():
prefDic['PLAYER1'] = string1
return True
elif string1 == '':
return prefDic['PLAYER1']
else:
return False
def player2(string1 = ''):
if string1.isalnum():
prefDic['PLAYER2'] = string1
return True
elif string1 == '':
return prefDic['PLAYER2']
else:
return False
def copy(settings):
colours(settings('colours')())
pegs(settings('pegs')())
rows(settings('rows')())
player1(settings('player1')())
player2(settings('player2')())
def importFromFile(fileName = 'SETTINGS'):
'''
imports saved settings from fileName. see exprtTofile
'''
try:
f = open(fileName, 'r')
except:
return False
header = f.readline().strip()
if header == 'MASTERMINDSETTINGS':
settingsStr = f.readline().strip()
settingsLs = settingsStr.split('/')
for i in range(0, len(settingsLs), 2):
prefDic[settingsLs[i]] = int(settingsLs[i+1])
settingsStr = f.readline().strip()
settingsLs = settingsStr.split('/')
for i in range(0, len(settingsLs), 2):
prefDic[settingsLs[i]] = str(settingsLs[i+1])
f.close()
def exportToFile(fileName = 'SETTINGS'):
'''
exports current settings to file
stored of form:
MASTERMINDSETTINGS
attribute1/decimal1/attribute2/decimal2/...
attribute1/string1/...
'''
f = open(fileName, 'w')
f.write('MASTERMINDSETTINGS')
f.write('COLOURS', prefDic['COLOURS'], 'PEGS', prefDic['PEGS'], 'ROWS', prefDic['ROWS'], sep = '/' )
f.write('PLAYER1', prefDic['PLAYER1'], 'PLAYER2', prefDic['PLAYER2'])
f.close()
return (lambda op: {'COLOURS': colours,
'PEGS': pegs,
'ROWS': rows,
'PLAYER1': player1,
'PLAYER2': player2,
'COPY': copy,
'IMPORT': importFromFile}[op.upper()])
def boardArgs():
'''
Stores ongoing data about the current game
'''
data = {'ROW': 0,
'POINTS': 0,#the points of player1; see points function
'CODE': [], #colours stored as a list of ints, 0 = no colour, 1 <= x <= colours is id for colour.
'BOARD': [], #^ditto except nested list for each row
'FEEDBACK': [] #^ditto except 0 <= x <= 2
}
#get data functions:
def currentRow():
return data['ROW']
def points(player = 1):#player = 1 or 2
if player == 1:
return data['POINTS']
elif player == 2:
return ((data['ROUND'] - 1) - data['POINTS'])
else:
return 0
def code():
return data['CODE']
def board(row, peg):
row -= 1 #as in list i starts at 0
peg -= 1 #^ditto
try:
return data['BOARD'][row][peg]
except:
return 0
def feedback(row, peg):
row -= 1 #as in list i starts at 0
peg -= 1 #^ditto
try:
return data['FEEDBACK'][row][peg]
except:
return 0
#assign data functions:
def newGame(settings): #sets dimensions of boards and initial values
data['CODE'] = [0] * settings('PEGS')()
data['BOARD'] = [data['CODE']] * settings('rows')()
data['FEEDBACK'] = [data['CODE']] * (1 + settings('rows')())
data['ROW'] = 0
data['POINTS'] = 0
def makeMove(code1Ls, settings):
code2Ls = data['CODE'][:]#creates duplicate of code
feedback = []#creates feedback list
del feedback[0]#empties feedback list
#compare for colour AND position: remove when found
for i in range(len(code2Ls)):
if code1Ls[i] == code2Ls[i]:
feedback.append(2)
del code1Ls[i]
del code2Ls[i]
#compare for colour: remove from code2 only as element of code1 will not be checked thereafter
for x in code1Ls:
for i in range(len(code2Ls)):
if x == code2Ls[i]:
feedback.append(1)
del code2Ls[i]
#ensure feedback is congruent to elements of data[feedback]:
while len(feedback) < settings('PEGS'): feedback.append(0)
#assign values:
data['FEEDBACK'][data['ROW']] = feedback
data['ROW'] += 1
return (lambda x: {'ROW': currentRow,
'POINTS': points,
'CODE': code,
'BOARD': board,
'FEEDBACK': feedback,
'NEWGAME': newGame,
'MAKEMOVE': makeMove}[x.upper()])
def main():
root = tk.Tk()
app = mainWindow(root)
root.mainloop()
class mainWindow:
def __init__(self, master):
self.settings = settingsArgs()
self.settings('import')()
self.master = master
self.frame = tk.Frame(self.master)
self.master.geometry('+400+200')
self.master.title('MasterMind')
self.title = tk.Label(self.master, text = 'MasterMind', font = ('Calibri', 22))
self.title.pack()
self.newGameBtn = tk.Button(self.frame, text = 'New Game', width = 25, command = self.newGame)
self.newGameBtn.pack()
self.loadGameBtn = tk.Button(self.frame, text = 'Load Game', width = 25, command = self.loadGame)
self.loadGameBtn.pack()
self.settingsBtn = tk.Button(self.frame, text = 'Settings', width = 25, command = self.settings)
self.settingsBtn.pack()
self.frame.pack()
def newGame(self):
self.gameWindow = tk.Toplevel(self.master)
self.app = gameWindow(self.gameWindow, self.settings)
def loadGame(self):
pass
def settings(self):
self.settingsWindow = tk.Toplevel(self.master)
self.app = settingsWindow(self.settingsWindow, self.settings)
class gameWindow:
def __init__(self, master, settings):
self.master = master
self.settings = settingsArgs()
self.settings('copy')(settings)
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
class settingsWindow:
def __init__(self, master, settings):
self.master = master
self.titleLb = tk.Label(self.master, text='MesterMind', font=('Calibri', 22))
self.titleLb.grid(row=0, column=0, sticky='W', columnspan=2)
self.subTitleLb = tk.Label(self.master, text="Settings", font=('Calibri', 18))
self.subTitleLb.grid(row=1, column=0, sticky='W', columnspan=2)
main()
Answer: In `mainwindow` class you have two things with the same name `self.settings`
first: `self.settings = settingsArgs()`
second: `def settings(self):`
Change function name in two place for example to `newsettings`
`def newsetting(self):`
and
`self.settingsBtn = tk.Button(self.frame, text = 'Settings', width = 25,
command = self.newsetting)`
|
how to shuffle a list correctly in python
Question: I have this code that shuffles a list. I first split it into two lists because
I have a interleave function that interleaves 2 lists:
def shuffle(xs, n=1):
il=list()
if len(xs)%2==0:
stop=int(len(xs)//2)
a=xs[:stop]
b=xs[stop:]
print(a)
print(b)
else:
stop=int(len(xs)//2)
a=xs[:stop]
b=xs[stop:]
print(a)
print(b)
if n>0:
for i in range(n):
shuffle=interleave(a,b)
else:
return
return shuffle
and when I test it:
>>> shuffle([1,2,3,4,5,6,7],1)
[1, 2, 3]
[4, 5, 6, 7]
1
[7]
[7, 4]
[1, 4, 2, 5, 3, 6, 7, 4]
What is 4 in the list twice and why is it printing 1, [7], 7,4]??
EDIT:
def interleave(xs,ys):
a=xs
b=ys
minlength=[len(a),len(b)]
extralist= list()
interleave= list()
for i in range((minval(minlength))):
pair=a[i],b[i]
interleave.append(pair)
flat=flatten(interleave)
c=a+b
if len(b)>len(a):
remainder=len(b)-len(a)
for j in range(remainder,-1,-1):
extra=b[-j]
extralist.append(extra)
if len(a)>len(b):
remainder=len(a)-len(b)
for j in range(remainder,-1,-1):
extra=a[-j]
extralist.append(extra)
del extralist[-1]
final=flat+extralist
return final
Answer: Why not just use the standard library?
>>> from random import shuffle
>>> l = list(range(1,20))
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> shuffle(l)
>>> l
[17, 15, 9, 13, 19, 7, 10, 18, 5, 1, 12, 3, 2, 16, 4, 14, 8, 6, 11]
>>>
|
Parsing xml in python - don't understand the DOM
Question: I've been reading up on parsing xml with python all day, but looking at the
site i need to extract data on, i'm not sure if i'm barking up the wrong tree.
Basically i want to get the 13-digit barcodes from a supermarket website
(found in the name of the images). For example:
<http://www.tesco.com/groceries/SpecialOffers/SpecialOfferDetail/Default.aspx?promoId=A31033985>
has 11 items and 11 images, the barcode for the first item is 0000003235676.
However when i look at the page source (i assume this is the best way to
extract all of the barcodes in one go with python, urllib and beautifulsoup)
all of the barcodes are on one line (line 12) however the data doesn't seem to
be structured as i would expect in terms of elements and attributes.
new TESCO.sites.UI.entities.Product({name:"Lb Mens Mattifying Dust 7G",xsiType:"QuantityOnlyProduct",productId:"275303365",baseProductId:"72617958",quantity:1,isPermanentlyUnavailable:true,imageURL:"http://img.tesco.com/Groceries/pi/805/5021320051805/IDShot_90x90.jpg",maxQuantity:99,maxGroupQuantity:0,bulkBuyLimitGroupId:"",increment:1,price:2.5,abbr:"g",unitPrice:3.58,catchWeight:"0",shelfName:"Mens Styling",superdepartment:"Health & Beauty",superdepartmentID:"TO_1448953606"});
new TESCO.sites.UI.entities.Product({name:"Lb Mens Thickening Shampoo 250Ml",xsiType:"QuantityOnlyProduct",productId:"275301223",baseProductId:"72617751",quantity:1,isPermanentlyUnavailable:true,imageURL:"http://img.tesco.com/Groceries/pi/225/5021320051225/IDShot_90x90.jpg",maxQuantity:99,maxGroupQuantity:0,bulkBuyLimitGroupId:"",increment:1,price:2.5,abbr:"ml",unitPrice:1,catchWeight:"0",shelfName:"Mens Shampoo ",superdepartment:"Health & Beauty",superdepartmentID:"TO_1448953606"});
new TESCO.sites.UI.entities.Product({name:"Lb Mens Sculpting Puty 75Ml",xsiType:"QuantityOnlyProduct",productId:"275301557",baseProductId:"72617906",quantity:1,isPermanentlyUnavailable:true,imageURL:"http://img.tesco.com/Groceries/pi/287/5021320051287/IDShot_90x90.jpg",maxQuantity:99,maxGroupQuantity:0,bulkBuyLimitGroupId:"",increment:1,price:2.5,abbr:"ml",unitPrice:3.34,catchWeight:"0",shelfName:"Pastes, Putty, Gums, Pomades",superdepartment:"Health & Beauty",superdepartmentID:"TO_1448953606"});
Maybe something like BeautifulSoup is overkill? I understand the DOM tree is
not the same thing as the raw source, but why are they so different - when i
go to inspect element in firefox the data seems structured as i would expect.
Apologies if this comes across as totally stupid, thanks in advance.
Answer: Unfortunately, the barcode is not given in the HTML as structured data; it
only appears embedded as part of a URL. So we'll need to isolate the URL and
then pick off the barcode with string manipulation:
import urllib2
import bs4 as bs
import re
import urlparse
url = 'http://www.tesco.com/groceries/SpecialOffers/SpecialOfferDetail/Default.aspx?promoId=A31033985'
response = urllib2.urlopen(url)
content = response.read()
# with open('/tmp/test.html', 'w') as f:
# f.write(content)
# Useful for debugging off-line:
# with open('/tmp/test.html', 'r') as f:
# content = f.read()
soup = bs.BeautifulSoup(content)
barcodes = set()
for tag in soup.find_all('img', {'src': re.compile(r'/pi/')}):
href = tag['src']
scheme, netloc, path, query, fragment = urlparse.urlsplit(href)
barcodes.add(path.split('\\')[1])
print(barcodes)
yields
set(['0000003222737', '0000010039670', '0000010036297', '0000010008393', '0000003050453', '0000010062951', '0000003239438', '0000010078402', '0000010016312', '0000003235676', '0000003203132'])
|
Can't get python to write to next line repeatedly. Tried \r initially
Question: I cannot get this program to work.
'''
Tasks are as follows:
1. The code to clean up the raw data and to use this information in the graphics package (R Project)
2. A graph of the month of birth and the number of the Omphaloceles and the number of children with Gastroschisis. (The counts in the file may be given as separate values. Use the sum of these two conditions in your graph.)
3. A graph of the Educational level of the mother versus the birth weight of the infant
4. A graph of the age of the mother and the trimester (not the month) of the start of prenatal care
'''
import re
nat=open('D:\Documents\Project\Nat2010us\VS2010NATL.DETAILUS.PUB', mode='rt')
#lists
Revision=[]
MonthofBirth=[]
MaternalAge=[]
MaternalEducation=[]
MonthofStartofPrenatalCare=[]
BirthWeight=[]
CongenitalAnomalies=[]
OmphaloceleGastroschisis=[]
#encoded lists
enrevision=[]
enmonthofbirth=[]
enmaternalage=[]
enmaternaleducation=[]
enmonthofstartofprenatalcare=[]
enbirthweight=[]
encongenitalanomalies=[]
enomphalocelegastroschisis=[]
#selecting data, S is Unrevised data and A Revised. For Month of Start of Prenatal Care I chose the two columns (246 and 258) that were both found in Unrevised and Revised sets.
for x in nat:
Revision.append(x[6])
MonthofBirth.append(x[18:20])
MaternalAge.append(x[88:90])
if x[6]=="S": MonthofStartofPrenatalCare.append(x[246])
if x[6]=="A": MonthofStartofPrenatalCare.append(x[258])
BirthWeight.append(x[470:472])
CongenitalAnomalies.append(x[512])
OmphaloceleGastroschisis.append(x[760])
if x[6]=="S": MaternalEducation.append(x[155:157])
if x[6]=="A": MaternalEducation.append(x[154])
nat.close()
#encoding the data, using 'en' as noting encoded lists
for x in Revision:
if x=="S": enrevision.append("U")
if x=="A": enrevision.append("R")
for x in MonthofBirth:
if x=="01": enmonthofbirth.append("January")
if x=="02": enmonthofbirth.append("February")
if x=="03": enmonthofbirth.append("March")
if x=="04": enmonthofbirth.append("April")
if x=="05": enmonthofbirth.append("May")
if x=="06": enmonthofbirth.append("June")
if x=="07": enmonthofbirth.append("July")
if x=="08": enmonthofbirth.append("August")
if x=="09": enmonthofbirth.append("September")
if x=="10": enmonthofbirth.append("October")
if x=="11": enmonthofbirth.append("November")
if x=="12": enmonthofbirth.append("December")
for x in MaternalAge:
if x=="12": enmaternalage.append("10-12")
if x=="13": enmaternalage.append("13")
if x=="14": enmaternalage.append("14")
if x=="15": enmaternalage.append("15")
if x=="16": enmaternalage.append("16")
if x=="17": enmaternalage.append("17")
if x=="18": enmaternalage.append("18")
if x=="19": enmaternalage.append("19")
if x=="20": enmaternalage.append("20")
if x=="21": enmaternalage.append("21")
if x=="22": enmaternalage.append("22")
if x=="23": enmaternalage.append("23")
if x=="24": enmaternalage.append("24")
if x=="25": enmaternalage.append("25")
if x=="26": enmaternalage.append("26")
if x=="27": enmaternalage.append("27")
if x=="28": enmaternalage.append("28")
if x=="29": enmaternalage.append("29")
if x=="30": enmaternalage.append("30")
if x=="31": enmaternalage.append("31")
if x=="32": enmaternalage.append("32")
if x=="33": enmaternalage.append("33")
if x=="34": enmaternalage.append("34")
if x=="35": enmaternalage.append("35")
if x=="36": enmaternalage.append("36")
if x=="37": enmaternalage.append("37")
if x=="38": enmaternalage.append("38")
if x=="39": enmaternalage.append("39")
if x=="40": enmaternalage.append("40")
if x=="41": enmaternalage.append("41")
if x=="42": enmaternalage.append("42")
if x=="43": enmaternalage.append("43")
if x=="44": enmaternalage.append("44")
if x=="45": enmaternalage.append("45")
if x=="46": enmaternalage.append("46")
if x=="47": enmaternalage.append("47")
if x=="48": enmaternalage.append("48")
if x=="49": enmaternalage.append("49")
if x=="50": enmaternalage.append("50-54")
for x in MonthofStartofPrenatalCare:
if x=="1": enmonthofstartofprenatalcare.append("1st Trimester")
if x=="2": enmonthofstartofprenatalcare.append("2nd Trimester")
if x=="3": enmonthofstartofprenatalcare.append("3rd Trimester")
if x=="4": enmonthofstartofprenatalcare.append("No Prenatal Care")
if x=="5": enmonthofstartofprenatalcare.append("unknown or not stated")
if x==" ": enmonthofstartofprenatalcare.append("not on certificate")
for x in BirthWeight:
if x=="01": enbirthweight.append("499 or less")
if x=="02": enbirthweight.append("500-999")
if x=="03": enbirthweight.append("1000-1499")
if x=="04": enbirthweight.append("1500-1999")
if x=="05": enbirthweight.append("2000-2499")
if x=="06": enbirthweight.append("2500-2999")
if x=="07": enbirthweight.append("3000-3499")
if x=="08": enbirthweight.append("3500-3999")
if x=="09": enbirthweight.append("4000-4499")
if x=="10": enbirthweight.append("4500-4999")
if x=="11": enbirthweight.append("5000-8165")
if x=="12": enbirthweight.append("not stated")
for x in CongenitalAnomalies:
if x=="1": encongenitalanomalies.append("anomaly reported")
if x=="2": encongenitalanomalies.append("anomaly not reported")
if x=="9": encongenitalanomalies.append("anomaly not classified")
if x==" ": encongenitalanomalies.append("not on certificate")
for x in OmphaloceleGastroschisis:
if x=="0": enomphalocelegastroschisis.append("not reporting")
if x=="1": enomphalocelegastroschisis.append("reporting")
#encoding the two different education codes to be coded the same
for x in range(0, len (MaternalEducation)):
if Revision[x]=="A":
if MaternalEducation[x]=="1": enmaternaleducation.append("8th grade or less")
if MaternalEducation[x]=="2": enmaternaleducation.append("9th through 12th grade no diploma")
if MaternalEducation[x]=="3": enmaternaleducation.append("High school graduate or GED completed")
if MaternalEducation[x]=="4": enmaternaleducation.append("Some college credit but no degree")
if MaternalEducation[x]=="5" or MaternalEducation[x]=="6": enmaternaleducation.append("Associate and/or Bachelor")
if MaternalEducation[x]=="7" or MaternalEducation[x]=="8": enmaternaleducation.append("Master's or Doctorate")
if MaternalEducation[x]=="9": enmaternaleducation.append("not stated")
if MaternalEducation[x]==" ": enmaternaleducation.append("blank")
if Revision[x]=="S":
if MaternalEducation[x]=="00" or MaternalEducation[x]=="01-08": enmaternaleducation.append("8th grade or less")
if MaternalEducation[x]=="09" or MaternalEducation[x]=="10" or MaternalEducation[x]=="11": enmaternaleducation.append("9th through 12th grade no diploma")
if MaternalEducation[x]=="12": enmaternaleducation.append("High school graduate or GED completed")
if MaternalEducation[x]=="13": enmaternaleducation.append("Some college credit but no degree")
if MaternalEducation[x]=="14" or MaternalEducation[x]=="15" or MaternalEducation[x]=="16": enmaternaleducation.append("Associate and/or Bachelor")
if MaternalEducation[x]=="17": enmaternaleducation.append("Master's or Doctorate")
if MaternalEducation[x]=="99": enmaternaleducation.append("not stated")
if MaternalEducation[x]==" ": enmaternaleducation.append("blank")
#open new file for output of data
'''
enmonthofbirth=[]
enmaternalage=[]
enmaternaleducation=[]
enmonthofstartofprenatalcare=[]
enbirthweight=[]
encongenitalanomalies=[]
enomphalocelegastroschisis=[]
'''
#write header and then, for each line, replace values in the Natality file with the encoded values from encoded lists (line by line) in the outputforR file. Matching up values based on commonality they all share - length.
#\n to end line to break to new line
f=open('D:\Documents\Project\outputforR.csv', mode='w')
f.write('month of birth'+','+'maternal age'+','+'maternal education'+','+'month of start of prenatal care'+','+'birth weight'+','+'congenital anomalies'+','+'omphalocele/gastroschisis')
for x in range(0,len(enmonthofbirth)):
f.write(enmonthofbirth[x]+','+enmaternalage[x]+','+enmaternaleducation[x]+','+enmonthofstartofprenatalcare[x]+','+enbirthweight[x]+','+encongenitalanomalies[x]+','+enomphalocelegastroschisis[x]) \n
f.close()
I cannot seem to fix line 170. I've messed around with the \n in different
ways to try to get this file to write so I can move on to putting my data in
R. My headers will write and open up in Excel just fine, but I cannot get
Python to write the values in each list underneath its appropriate header. I'm
told I need \n to make it go to next row, but it will only allow \ by itself,
which doesn't work. Removing \n also doesn't work. \ and nothing leave me with
exactly what is in this link. below.
Below is a link to an image of my excel file once written.
<http://i.imgur.com/GDReiQh.png>
Answer: Remove `\n` from following line:
f.write(enmonthofbirth[x]+','+...) \n
# ^^^
**UPDATE**
If you want to write, write it as follow:
f.write(enmonthofbirth[x]+','+... + '\n')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.