text
stringlengths 226
34.5k
|
---|
No module named bumpy
Question: i am new mac user and new to python.
i just install python 2.7 and matplotlib and try to run this demo code:
"""
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
when i click Run -> Run Module i get this error:
Traceback (most recent call last):
File "/Users/mehmetalinadigulec/Desktop/subplot_demo.py", line 4, in <module>
import numpy as np
ImportError: No module named numpy
i searched for hours but can`t fix it.
i edit my ~/.bash_profile
# Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PYTHONPATH="/Library/Python/2.7/site-packages:${PYTHONPATH}"
export PYTHONPATH
and result
echo $PYHTONPATH
/Library/Python/2.7/site-packages:
Answer: The simply answer would seem to be to install numpy via
<http://www.scipy.org/install.html>
|
remove widgets from grid in tkinter
Question: I have a grid in a tkinter frame which displays query results. It has a date
field that is changed manually and then date is used as a parameter on the
query for those results. every time the date is changed, obviously the results
change, giving a different amount of rows. The problem is that if you get less
rows the second time you do it, you will still have results from the first
query underneath those and will be very confusing.
My question is, how can i remove all rows from the frame that have a row
number greater than 6 (regardless of what's in it)?
By the way, I'm running Python 3.3.3. Thanks in advance!
Answer: Calling the method `grid_forget` on the widget will remove it from the window
- this example uses the call `grid_slaves` on the parent to findout all
widgets mapped to the grid, and then the `grid_info` call to learn about each
widget's position:
>>> import tkinter
# create:
>>> a = tkinter.Tk()
>>> for i in range(10):
... label = tkinter.Label(a, text=str(i))
... label.grid(column=0, row=i)
# remove from screen:
>>> for label in a.grid_slaves():
... if int(label.grid_info()["row"]) > 6:
... label.grid_forget()
|
Python filling a 2D list with recusion
Question: I need to create a program that will recursively fill a 2D list. The list
forms a grid like
I - I - I - - -
I I - - - - - -
I I I I - - - -
Then the user input column and row numbers. The program then fills that
section of "-" with "@". So if row = 1 and column = 4 it would look like:
I - I @ I @ @ @
I I @ @ @ @ @ @
I I I I @ @ @ @
I have to do this with recursion. The only thing I could get it to do was
partially fill a row. Please help me.
Answer: The program is pretty simple if you start from bottom right of the grid and
recurse backwards till (0, 0). Let's walk through the logic step by step:
* We start from bottom right, in your case (2, 7). And you need to fill everything that is greater than your bounds, in your case (0, 3). These are the parameters we will need for the recursive method.
recur_fill(input_list, a, b, i, j)
* We begin with the boundary conditions. Your program needs to execute only while the co-ordinates are greater than zero. i.e., if `i < 0` or `j < 0` we have to stop. This translates to:
if i < 0 or j < 0:
return
* Now, we need to take care of the paint bounds, namely a and b. As long as our co-ordinates are greater than your bounds, we need to check if the cell has `-` and fill it with `@`. Which translates to:
if i >= a and j >= b:
if input_list[i][j] == '-':
input_list[i][j] = '@'
* Now, we need to fill the cells recursively till all the cells that fall within our conditions are filled. i.e.,
recur_fill(input_list, a, b, i - 1, j)
recur_fill(input_list, a, b, i, j - 1)
Summing these, we have:
from pprint import pprint
def recur_fill(input_list, a, b, i, j):
if i < 0 or j < 0:
return
if i >= a and j >= b:
if input_list[i][j] == '-':
input_list[i][j] = '@'
recur_fill(input_list, a, b, i - 1, j)
recur_fill(input_list, a, b, i, j - 1)
def main():
input_list = [['I', '-', 'I', '-', 'I', '-', '-', '-' ],
['I', 'I', '-', '-', '-', '-', '-', '-' ],
['I', 'I', 'I', 'I', '-', '-', '-', '-' ]]
recur_fill(input_list, 0, 2, 2, 7)
pprint(input_list)
if __name__ == '__main__':
main()
|
Python CSV Comparison
Question: This script compares two csv files...with two columns plz help me to modify
this script if sample1.csv and sample2.csv has more than 2 columns or 1
column.
f1_in = open("sample1.csv","r")
next(f1_in,None)
f1_dict = {}
for line in f1_in:
l = line.split(',')
f1_dict[l[0]. strip()] = l[1]. strip()
l.sort()
f1_in.close()
f2_in = open("sample2.csv","r")
next(f2_in,None)
f2_dict = {}
for line in f2_in:
l = line.split(',')
f2_dict[l[0]. strip()] = l[1]. strip()
l.sort()
f2_in.close()
f_same = open("same.txt","w")
f_different = open("different.txt","w")
for k1 in f1_dict.keys():
if k1 in f2_dict.keys() \
and f2_dict[k1] == f1_dict[k1]:
f_same.write("{0}, {1}\n". format(str(k1)+" "+str(f1_dict[k1]),
str(k1)+" "+str(f2_dict[k1])))
elif not k1 in f2_dict.keys():
f_different.write("{0}, {1}\n". format(str(k1)+" "+str(f1_dict[k1]),
"------"))
elif not f2_dict[k1] == f1_dict[k1]:
f_different.write("{0}, {1}\n". format(str(k1)+" "+str(f1_dict[k1]),
str(k1)+" "+str(f2_dict[k1])))
f_same.close()
f_different.close()
for eg:if my source file has Name and Salary as headers with values A 20000 B
15000 C 10000 D 10000 and target file also with Name and Salary has headers
with values A 40000 D 10000 B 15000 C 10000 E 8000...my output should be
Different lines:A 20000 A 40000 D 10000 -----(no file in target) -----(no file
in source) E 8000 and common lines as B 15000 B 15000, C 10000 C 10000
Answer: It is no wonder you cannot expand the code to more than two colums if you are
regarding your columns as key/value pairs in a dictionary.
You have to see them as "elements in a set". I understand this is why you are
not using the `csv` module or the `difflib` module: because you do not care
whether the lines appear in (nearly) same order in either file, but whether
they appear at all.
Here is an example:
import itertools
def compare(first_filename, second_filename):
lines1 = set()
lines2 = set()
with open(first_filename, 'r') as file1, \
open(second_filename, 'r') as file2:
for line1, line2 in itertools.izip_longest(file1, file2):
if line1:
lines1.add(line1)
if line2:
lines2.add(line2)
print "Different lines"
for line in lines1 ^ lines2:
print line,
print "---"
print "Common lines"
for line in lines1 & lines2:
print line,
Notice that this code will find differences on both files, not just things
that exist on f1 but not on f2, as your example does. However, it is not able
to tell where do differences come from (since this does not seem a requirement
of the question).
### Check that it works
In [40]: !cat sample1.csv
bacon, eggs, mortar
whatever, however, whenever
spam, spam, spam
In [41]: !cat sample2.csv
guido, van, rossum
spam, spam, spam
In [42]: compare("sample1.csv", "sample2.csv")
Different lines
whatever, however, whenever
guido, van, rossum
bacon, eggs, mortar
---
Common lines
spam, spam, spam
|
Sending different files from Client to Server in Python
Question: I am trying to send files from client to server in python. It is sending but
the problem is that I'm not getting same file name as it is. **Suppose
filename is File1.txt. When I send it to server, I receive it as file_.txt**.
The code I've wrote for this is :
**Client Code**
import socket, os, shutil
from stat import ST_SIZE
HOST=raw_input("Please enter IP-address : ")
PORT=int(raw_input("Please enter PORT Number : "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
if s.recv(8)!='READY':
raw_input('Unable to connect \n\n Press any key to exit ...')
s.close()
exit()
path=raw_input("Please enter the complete PATH of your file : ")
f=open(path,'rb')
fsize=os.stat(f.name)[ST_SIZE]
s.sendall(str(fsize).zfill(8))
sfile = s.makefile("wb")
shutil.copyfileobj(f, sfile)
sfile.close()
s.close()
f.close()
**Server Code**
import socket
import shutil
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = ''
PORT = 31400
s.bind((HOST, PORT))
s.listen(3)
conn, addr = s.accept()
print 'conn at address',addr
conn.sendall('READY')
i=1
f = open(r'file_'+ str(i)+".txt",'wb')
i=i+1
fsize=int(conn.recv(8))
print 'File size',fsize
sfile = conn.makefile("rb")
shutil.copyfileobj(sfile, f)
sfile.close()
f.write(conn.recv(fsize))
f.close()
conn.close()
s.close()
How to get same file name...and what if I've to receive any type of file like
.pdf, .txt, .jpeg etc. Please help me I'm new in python.
Answer: You either need to use a library such as
[ftputil](https://pypi.python.org/pypi/ftputil/2.2.3) or encode the file in
some way such as such as
[UUENCODE](https://docs.python.org/2/library/uu.html).
Alternatively you will have to implement your own protocol with separate
transactions to send the file name and size then the contents. i.e.
* Client gets the file path then checks the size plus splits off the basename.
* Client sends the file base name and size in a pre-formatted manner.
* Server receives and interprets the above information then opens the file called _base name_ for write.
* Client sends the binary data.
* Server writes binary data to open file.
* Both compute the MD5, or similar, for the file and exchange information to make sure it matches.
_Note that the above does not cover handling problems such as lost data, ASCII
only links, corruption, sending as blocks, etc. Bear in mind that FTP has been
in active use and development since 1971 with fundamental change suggested as
late as 1998._
|
Delay between for loop iteration (python)
Question: Is [this](http://stackoverflow.com/questions/11946232/how-to-add-some-delay-
between-each-iteration-of-for-loop-in-c "Delay iterations") possible in
Python? I wrote a great loop/script in Python and I’d like to add this delay
to it if at all possible.
map(firefox.open, ['http://www.bing.com/search?q=' + str(i) for i in range(x))], [2] * x)
Where shall I put the `sleep(6)` in this?
Answer: You can do that using `time.sleep(some_seconds)`.
from time import sleep
for i in range(10):
print i
sleep(0.5) #in seconds
### Implementation
Here is a cool little implementation of that: (Paste it in a .py file and run
it)
from time import sleep
for i in range(101):
print '\r'+str(i)+'% completed',
time.sleep(0.1)
map(firefox.open, ['<http://www.bing.com/search?q=>' + str(i) for i in
range(x))], [2] * x)
|
Python Enclosing Words With Quotes In A String
Question: For Python I'm opening a csv file that appears like:
jamie,london,uk,600087
matt,paris,fr,80092
john,newyork,ny,80071
How do I enclose the words with quotes in the csv file so it appears like:
"jamie","london","uk","600087"
etc...
What I have right now is just the basic stuff:
filemame = "data.csv"
file = open(filename, "r")
Not sure what I would do next.
Answer: If you are just trying to convert the file, use the `QUOTE_ALL` constant from
the [`csv` module](https://docs.python.org/2/library/csv.html#csv.QUOTE_ALL),
like this:
import csv
with open('data.csv') as input, open('out.csv','w') as output:
reader = csv.reader(input)
writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL)
for line in reader:
writer.writerow(line)
|
Python How to post form with request
Question: I want use request to post the form with python and request This is form with
2 value user and pass to submit them
## can you help me pls .
<form method="post" action="/maxverif/0" name="loginf" id="connect">
<p class="title">
Connect
</p>
<div class="before">
<div class="ques">
<div class="name">Mail :</div>
<div class="input"><input type="text" name="user"/></div>
</div>
<div class="question">
<div class="name">Pass</div>
<div class="input"><input type="password" name="pass" /></div>
</div></div>
<div>
<div class="button">
<input type="submit" value="trens" id="connect" />
</div>
python :
import requests
url = 'https://www.domains.com/store/verify/'
parameters2 = {'user': '[email protected]',
'pass': '123456'
}
params = urllib.urlencode(parameters2)
req = urllib2.Request(url, params)
response = urllib2.urlopen(req)
data=response.read()
html= etree.HTML(data)
print html
And when I make Print html and i see the form is not posted . Tks
Answer: Hi i found a solution and i make this
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'user': '[email protected]', 'pass': '123456'})
opener.open('https://www.domains.com/store/verify/', login_data)
hh = opener.open('https://www.domains.com/store/verify/', login_data)
print hh.read()
Tks
|
ponyORM: trouble with query
Question: I have query with dynamic conditions,i.e.
select (lambda obj:obj.A = 'a' and obj.B = 'b' and ...)
So i write code for this:
def search(self,**kwargs):
q = unicode('lambda obj:', 'utf-8')
for field,value in kwargs.iteritems():
value = unicode(value, 'utf-8')
field = unicode(field, 'utf-8')
q+=u" obj.%s == '%s' and" % (field,value
q = q[0:q.rfind('and')]
res = select(q.encode('utf-8'))[:]
But i have this error during execution of function:
tasks.search(title='Задача 1',url='test.com')
res = select(q.encode('utf-8'))[:]
File "<string>", line 2, in select
File ".../local/lib/python2.7/site-packages/pony/utils.py", line 96, in cut_traceback
return func(*args, **kwargs)
File ".../local/lib/python2.7/site-packages/pony/orm/core.py", line 3844, in select
if not isinstance(tree, ast.GenExpr): throw(TypeError)
File "...local/lib/python2.7/site-packages/pony/utils.py", line 123, in throw
raise exc
TypeError
Answer: While it is possible to use strings in order to apply conditions to a query,
it can be unsafe, because of the risk of SQL injection. The better way for
applying conditions to a query is using the `filter()` method. You can take
the latest version of Pony ORM from <https://github.com/ponyorm/pony>
repository and try a couple of examples provided below.
First we define entities and create a couple of objects:
from decimal import Decimal
from pony.orm import *
db = Database('sqlite', ':memory:')
class Product(db.Entity):
name = Required(unicode)
description = Required(unicode)
price = Required(Decimal)
quantity = Required(int, default=0)
db.generate_mapping(create_tables=True)
with db_session:
Product(name='iPad', description='Air, 16GB', price=Decimal('478.99'), quantity=10)
Product(name='iPad', description='Mini, 16GB', price=Decimal('284.95'), quantity=15)
Product(name='iPad', description='16GB', price=Decimal('299.00'), quantity=10)
Now we'll apply filters passing them as keyword arguments:
def find_by_kwargs(**kwargs):
q = select(p for p in Product)
q = q.filter(**kwargs)
return list(q)
with db_session:
products = find_by_kwargs(name='iPad', quantity=10)
for p in products:
print p.name, p.description, p.price, p.quantity
Another option is to use lambdas in order to specify the conditions:
def find_by_params(name=None, min_price=None, max_price=None):
q = select(p for p in Product)
if name is not None:
q = q.filter(lambda p: p.name.startswith(name))
if min_price is not None:
q = q.filter(lambda p: p.price >= min_price)
if max_price is not None:
q = q.filter(lambda p: p.price <= max_price)
return list(q)
with db_session:
products = find_by_params(name='iPad', max_price=400)
for p in products:
print p.name, p.description, p.price, p.quantity
As you can see filters can be applied dynamically. You can find more
information about using filters following by this link:
<http://doc.ponyorm.com/queries.html#Query.filter>
|
Using a python program to rename all XML files within a linux directory
Question: Currently, my code uses the name of an XML file as a parameter in order to
take that file, parse some of its content and use it to rename said file, what
I mean to do is actually run my program once and that program will search for
every XML file (even if its inside a zip) inside the directory and rename it
using the same parameters which is what I am having problems with.
#encoding:utf-8
import os, re
from sys import argv
script, nombre_de_archivo = argv
regexFecha = r'\d{4}-\d{2}-\d{2}'
regexLocalidad = r'localidad=\"[\w\s.,-_]*\"'
regexNombre = r'nombre=\"[\w\s.,-_]*\"'
regexTotal = r'total=\"\d+.?\d+\"'
fechas = []; localidades = []; nombres = []; totales = []
archivo = open(nombre_de_archivo)
for linea in archivo.readlines():
fechas.append(re.findall(regexFecha, linea))
localidades.append(re.findall(regexLocalidad, linea))
nombres.append(re.findall(regexNombre, linea))
totales.append(re.findall(regexTotal, linea))
fecha = str(fechas[1][0])
localidad = str(localidades[1][0]).strip('localidad=\"')
nombre = str(nombres[1][0]).strip('nombre=\"')
total = str(totales[1][0]).strip('total=\"')
nombre_nuevo_archivo = fecha+"_"+localidad+"_"+nombre+"_"+total+".xml"
os.rename(nombre_de_archivo, nombre_nuevo_archivo)
EDIT: an example of this would be.
directory contains only 3 files as well as the program.
silly.xml amusing.zip feisty.txt
So, you run the program and it ignores feisty as it is a .txt file and it
reads silly.xml, ti then parses "fechas, localidad, nombre, total" concatenate
or append or whatever and use that as the new file for silly.xml, then the
program checks if zip has an xml file, if it does then it does the same thing.
so in the end we would have
20141211_sonora_walmart_2033.xml 20141008_sonora_starbucks_102.xml feisty txt
amusing.zip
Answer: Your question is not clear, and the code you posted is too broad.
I can't debug regular expressions with the power of my sight, but there's a
number of things you can do to simplify the code. Simple code means less
errors, and an easier time debugging.
To locate your target files, use
[`glob.glob`](https://docs.python.org/2/library/glob.html):
files = glob.glob('dir/*.xml')
To parse them, ditch regular expressions and use the
[`ElementTree`](https://docs.python.org/2/library/xml.etree.elementtree.html)
API.
import xml.etree.ElementTree as ET
tree = ET.parse('target.xml')
root = tree.getroot()
There's also modules to navigate XML files with CSS notation and XPATH.
Extracting fields form the filename using regex is okay, but check out [named
groups](https://docs.python.org/2/library/re.html).
|
Apache django not saving image with image field in form
Question: I have a form which is working fine if I don't add any image, but it gives
template not found error as per the apache log if I try to upload image. The
problem here is that my form with image is working fine on my local server
(django) but not uploading the image when I start apache and run the project
in it.
This is my .conf file
<VirtualHost *:80>
WSGIScriptAlias / /home/anmol/suvidha.wsgi
ServerName suvidha.com
Alias /static /var/www/suvidha/register/static/
<Directory /var/www/suvidha/>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
My .wsgi file
import os
import sys
sys.path = ['/var/www/suvidha'] + sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = 'suvidha.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
My .settings file
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = join(BASE_DIR, 'register/static')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/static/images/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
My directories listing
/var
/www
/suvidha
/register
/static
Log file
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] mod_wsgi (pid=15679):Exception occurred processing WSGI script '/home/byld/suvidha.wsgi'.
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] Traceback (most recent call last):
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] response = self.get_response(request)
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 153, in get_response
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 228, in handle_uncaught_exception
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] return callback(request, **param_dict)
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py", line 91, in _wrapped_view
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] response = view_func(request, *args, **kwargs)
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/views/defaults.py", line 32, in server_error
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] t = loader.get_template(template_name) # You need to create a 500.html template.
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 145, in get_template
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] template, origin = find_template(template_name)
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 138, in find_template
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] raise TemplateDoesNotExist(name)
[Tue Apr 22 00:23:53 2014] [error] [client 192.168.58.196] TemplateDoesNotExist: 500.html
It would be great if someone can help, I am stuck on this and can't find any
answer.
Answer: What this is telling you is that you have an exception somewhere triggered by
the image upload, which would normally result in a 500 error response - but
you have no 500.html template to use to display the response. Create the
relevant template, and you'll be able to see the real bug.
|
Drawing decision boundary of two multivariate gaussian in Python
Question: I will borrow the image from the following stack overflow question to help me
describing my problem: [Drawing decision boundary of two multivariate
gaussian](http://stackoverflow.com/questions/19576761/drawing-decision-
boundary-of-two-multivariate-gaussian)

I have 2 classes with 2D points, and what I am interested in is the decision
boundary (or discriminant).
I have written the functions that return the result for the discriminant
functions (a float value) that allowed me to classify the samples into those 2
patterns.
if a sample point is e.g., x_i = [x, y]
I can call the functions and
if `g1(x,y) > g2(x,y)` it's class 1, and vice versa if
`g1(x,y) <= g2(x,y)` it's class 2
So the decision boundary should be at `g1(x,y) == g2(x,y)`
* * *
**EDIT:**
Hope that an example is helpful:
1) Let's assume I take 1 sample `x = [1, 2]` from the dataset
2) Then I will call e.g.
`g1(1,2)` \--> returns `0.345`
`g2(1,2)` \--> returns `0.453`
\--> sample x belongs to class 2, since `g2(1,2) > g1(1,2)`
3) Now for the decision boundary, I have `g2(x,y) == g1(x,y)`,
or
`g1(x,y) - g2(x,y)` == 0
4) I generate a range of `x` values, e.g., `1,2,3,4,5`, and now I want to find
the corresponding `y` values that yield `g1(x,y) - g2(x,y) == 0`
5) then I can use these `x,y` pairs to plot the decision boundary
* * *
In the StackOverflow post that I linked above, the suggestion would be to
> you can simply plot the contour line of f(x,y) := pdf1(x,y) > pdf2(x,y). So
> you define function f to be 1 iff pdf1(x,y)>pdf2(x,y). This way the only
> contour will be placed along the curve where pdf1(x,y)==pdf2(x,y) which is
> the decision boundary (discriminant). If you wish to define "nice" function
> you can do it simply by setting f(x,y) = sgn( pdf1(x,y) - pdf2(x,y) ), and
> plotting its contour plot will result in exact same discriminant.
But how would I do it in Python and matplotlib, I am really lost setting up
the code to do that. I am grateful for any help!
EDIT:
A little bit more about the function `g()` itself:
def discr_func(x, y, cov_mat, mu_vec):
"""
Calculates the value of the discriminant function for a dx1 dimensional
sample given covariance matrix and mean vector.
Keyword arguments:
x_vec: A dx1 dimensional numpy array representing the sample.
cov_mat: dxd numpy array of the covariance matrix.
mu_vec: dx1 dimensional numpy array of the sample mean.
Returns a float value as result of the discriminant function.
"""
x_vec = np.array([[x],[y]])
W_i = (-1/2) * np.linalg.inv(cov_mat)
assert(W_i.shape[0] > 1 and W_i.shape[1] > 1), 'W_i must be a matrix'
w_i = np.linalg.inv(cov_mat).dot(mu_vec)
assert(w_i.shape[0] > 1 and w_i.shape[1] == 1), 'w_i must be a column vector'
omega_i_p1 = (((-1/2) * (mu_vec).T).dot(np.linalg.inv(cov_mat))).dot(mu_vec)
omega_i_p2 = (-1/2) * np.log(np.linalg.det(cov_mat))
omega_i = omega_i_p1 - omega_i_p2
assert(omega_i.shape == (1, 1)), 'omega_i must be a scalar'
g = ((x_vec.T).dot(W_i)).dot(x_vec) + (w_i.T).dot(x_vec) + omega_i
return float(g)
And when I execute it, it would return a float, e.g.,
`discr_func(1, 2, cov_mat=cov_est_1, mu_vec=mu_est_1)`
`-3.726426544537969`
if I didn't make a mistake, it should be this equation: 
Thank you a lot for the suggestion with the contour, however, I have problems
implementing it:
import pylab as pl
X, Y = np.mgrid[-6:6:100j, -6:6:100j]
x = X.ravel()
y = Y.ravel()
p = (discr_func(x, y, cov_mat=cov_est_1, mu_vec=mu_est_1) -\
discr_func(x, y, cov_mat=cov_est_2, mu_vec=mu_est_2)).reshape(X.shape)
#pl.scatter(X_train[:, 0], X_train[:, 1])
pl.contour(X, Y, p, levels=[0])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-192-28c1c8787237> in <module>()
5 y = Y.ravel()
6
----> 7 p = (discr_func(x, y, cov_mat=cov_est_1, mu_vec=mu_est_1) - discr_func(x, y, cov_mat=cov_est_2, mu_vec=mu_est_2)).reshape(X.shape)
8
9 #pl.scatter(X_train[:, 0], X_train[:, 1])
<ipython-input-184-fd2f8b7fad82> in discr_func(x, y, cov_mat, mu_vec)
25 assert(omega_i.shape == (1, 1)), 'omega_i must be a scalar'
26
---> 27 g = ((x_vec.T).dot(W_i)).dot(x_vec) + (w_i.T).dot(x_vec) + omega_i
28 return float(g)
ValueError: objects are not aligned
My feeling is that the passing of the `.ravel()` list doesn't work well with
how I set up this function... any suggestions?
Answer: calculate the `g1(x, y) - g2(x, y)` on a `mgrid[]` and then draw the line by
`contour(..., levels=[0])`, here is an example. Since you did not post any
sample data and code, I use sklearn to generate the sample data. You only need
the code after `#plot code from here`:
import numpy as np
import pylab as pl
from sklearn import mixture
np.random.seed(0)
C1 = np.array([[3, -2.7], [1.5, 2.7]])
C2 = np.array([[1, 2.0], [-1.5, 1.7]])
X_train = np.r_[
np.random.multivariate_normal((-5, -5), C1, size=100),
np.random.multivariate_normal((5, 5), C2, size=100),
]
clf = mixture.GMM(n_components=2, covariance_type='full')
clf.fit(X_train)
#define g1(x, y) and g2(x, y)
def g1(x, y):
return clf.predict_proba(np.column_stack((x, y)))[:, 0]
def g2(x, y):
return clf.predict_proba(np.column_stack((x, y)))[:, 1]
#plot code from here
X, Y = np.mgrid[-15:15:100j, -15:15:100j]
x = X.ravel()
y = Y.ravel()
p = (g1(x, y) - g2(x, y)).reshape(X.shape)
pl.scatter(X_train[:, 0], X_train[:, 1])
pl.contour(X, Y, p, levels=[0])
here is the output:

|
Python play song from point
Question: I would like to play a song with python, but all the libraries I've tried, had
problems on starting the song from a precise second.
I mean, I want to start a song from second 10, for example. I've tried pygame,
but I have issues with the play function.
The issue is: The music is supposed to start at second 89, but it starts from
the beginning and after 1 sec. skips at 89.
Could anyone help me? Thanks
import pygame
pygame.init()
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load("C:\\Users\\Leonardo\\Desktop\\Projo\\music.mp3")
pygame.mixer.music.play(0,89)
clock = pygame.time.Clock()
clock.tick(10)
while pygame.mixer.music.get_busy():
pygame.event.poll()
clock.tick(10)
Answer: As per your issue:
> The issue is: The music is supposed to start at second 89, but it starts
> from the beginning and after 1 sec. skips at 83.
This line in your code `pygame.mixer.music.play(0,83)` should be
pygame.mixer.music.play(0,89)
because
[pygame.mixer.music.play()](http://www.pygame.org/docs/ref/music.html#pygame_mixer_music_play)
takes two parameters first one is for the looping the music and second one is
the starting point of the music file. In your case the starting point should
be 89 not 83, as you mentioned in your question.
|
Regular expression help in Python. Looking for an expression for RGB values
Question: Looks like I need a little help with a regular expression to match RGB values.
I've built the following expression but it doesn't find a match. It is also
insufficient because I need to expand it to check for three digits and only a
0-255 value should exist.
For example. The following are all valid values I need to match against:
0,0,0
0, 0, 0
255,255,255
255, 255, 255
Here is what I have so far:
expression = re.compile(r'(\\d+),(,),(\\d+),(,),(\\d+)')
expression.match(text)
Answer: You _can_ insure that the numbers are between 0 and 255 with a regex, but I
highly recommend against it. An easier method here is to capture the numbers
with a regex and check that they are between 0 and 255 by simply casting to an
int and comparing:
>>> import re
>>> r = r"(\d+),\s*(\d+),\s*(\d+)"
>>> re.match(r, "0, 254,10").groups()
('0', '254', '10')
>>> all(0 <= int(group) <= 255 for group in re.match(r, "0, 254,10").groups())
True
>>> all(0 <= int(group) <= 255 for group in re.match(r, "0,256, 190").groups())
False
|
Python 3.3 how to get all methods (including all parents' methods) of a class in its metaclass?
Question: For example:
class Meta(type):
def __new__(cls, name, parents, attrs):
new_attrs={}
for k,v in attrs.items():
# Here attrs only has methods defined in "name", this is not I want.
print(k,v)
new_attrs[k] = v
return type.__new__(cls, name, parents, new_attrs)
class meta(metaclass=Meta):
pass
class a(object):
def a1(self):
return self.a2()
def a2(self):
print('a2 voked')
class b(a):
def b1(self):
return self.b2()
def b2(self):
return self.a1()
class c(b):
def c1(self):
return self.b1()
class d(c,meta):
def d1(self):
return self.c1()
x=d()
x.d1()
The result is:
>>>
__qualname__ meta
__module__ __main__
__qualname__ d
d1 <function d.d1 at 0x0000000002A7B950>
__module__ __main__
a2 voked
As you can see, in `__new__` of `Meta`, except special methods, only `d1` is
accessible. But I want to get all its parents' methods as well(.i.e a1 a2 b1
b2 and c1 objects) so I can do something useful when class `d` is creating via
metaclass, such as add a decorator to all its methods. so how ?
I know one similar way to get this, but it is a little complicated and in
fact, it is _after_ class `d` is created.:
import inspect
class Print(object):
@classmethod
def printize(cls,):
for name,attr in inspect.getmembers(cls):
# here all methods are accessible
# you can do something like:
# setattr(cls,name, f(attr))
class d(c,Print):
def d1(self):
return self.c1()
d.printize()
Answer:
x=d()
p = type(x)
while p != object:
print(p.__bases__)
p = p.__bases__[0]
_Gives:_
(<class '__main__.c'>, <class '__main__.meta'>)
(<class '__main__.b'>,)
(<class '__main__.a'>,)
(<class 'object'>,)
Or you can do:
import inspect
print(inspect.getmro(type(x)))
_To get:_
(<class '__main__.d'>, <class '__main__.c'>, <class '__main__.b'>,
<class '__main__.a'>, <class '__main__.meta'>, <class 'object'>)
|
Splitting a String Python within a list
Question: I have a list such as
a=['john(is,great),paul,school','robert,jack,john']
then I am building an empty list to append the split
b=[]
then I do this
for i in a:
b.append(i.split(','))
but list be is appearing like this
[['john(is', 'great)', 'paul', 'school'], ['robert', 'jack', 'john']]
Its doing this because its splitting at the comma but is there another way to
split this so this `john(is', 'great)` appears as one string like
`john(is,great)`
Answer: You can use `list.extend()` to add elements individually:
for i in a:
b.extend(i.split(','))
To split text on commas _not inside parenthesis_ you could use the following
regular expression:
re.split(r',(?=[^()]*(?:\(|$))', i)
This splits on a comma only if it is not followed by text containing any
parentheses (opening or closing) until the next opening parenthesis. This
expression falls down when you have nested parenthesis, but works for your
simple case:
>>> import re
>>> i = 'john(is,great),paul,school'
>>> re.split(r',+(?=[^()]*(?:\(|$))', i)
['john(is,great)', 'paul', 'school']
For more complex splits, use a full-blown parser.
|
Append child in the middle
Question: I would like to add an element to an XML file using minidom from python. Let's
assume i have the following xml file
<node-a>
<node-1/>
<node-2/>
<node-3/>
<node-a/>
in this case i can easily append an element "node-4" as follow
node4 = designDOM.createElement('node-4')
nodea.appendChild(node4)
resulting with the following xml:
<node-a>
<node-1/>
<node-2/>
<node-3/>
<node-4/>
<node-a/>
my questrion is: if I would like to force the insertion of an element in a
specific position instead of in the end... what should i do? for instance if i
want an element "2-a" as in the following xml what shold i do?
<node-a>
<node-1/>
<node-2/>
<node-2a/>
<node-3/>
<node-4/>
<node-a/>
Answer: You can use
[`insertBefore()`](https://docs.python.org/2.7/library/xml.dom.html#xml.dom.Node.insertBefore):
import xml.dom.minidom
data = """<node-a>
<node-1/>
<node-2/>
<node-3/>
</node-a>"""
dom = xml.dom.minidom.parseString(data)
node_a = dom.getElementsByTagName('node-a')[0]
node_4 = dom.createElement('node-4')
node_a.appendChild(node_4)
node_3 = dom.getElementsByTagName('node-3')[0]
node2_a = dom.createElement('node-2a')
node_a.insertBefore(node2_a, node_3)
print dom.toprettyxml()
prints:
<node-a>
<node-1/>
<node-2/>
<node-2a/>
<node-3/>
<node-4/>
</node-a>
|
How to force OS to free port with python
Question:
I use a port in my python program and close it,now I want to use it again.Just
that port not another port.
Is there any way to force OS to free port with python?
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.close
ss = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
ss.bind((host, portt))
s.close
but the output is:
Traceback (most recent call last):
File "client.py", line 17, in <module>
ss.bind((host, portt))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
Answer: You'll never be able to force the OS (with any sort of reasonable effort) to
release a socket.
Instead you just want to say you don't care with
[`setsockopt`](https://docs.python.org/2/library/socket.html#socket.socket.setsockopt)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
This means that the option takes place at the **S** ocket **O** bject **L**
evel SOCKET (as opposed to the TCP or something else) and you're setting the
**S** ocket **O** ption REUSEADDR (you're telling the OS that it's OK, you
really do want to listen here). And finally, you're turning the option on with
`1`, rather than off (with `0`).
|
how to display HSV image - tkinter, python 2.7
Question: I'm converting an RGB image to HSV, and trying to display the same in a Label.
But I'm getting error.
My code snippet is:
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
imgthresh=Image.open(imgthresh)
re_hsv=imhsv.resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(windo, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
And my error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "E:\python\track\guinew.py", line 215, in hsv_img
imhsv=Image.open(imgthresh)
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\System\lib\site-packages\PIL\Image.py", line 1956, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'
So how to display the HSV image, is there any other way then what i have
tried? Any suggestions are welcome!
Thanks in advance!
Answer: The error is thrown when you call `Image.open(imgthresh)`, because
`Image.open` [expects a file-like
object](http://effbot.org/imagingbook/image.htm), but `imgthresh` is a Numpy
array.
Try removing that line altogether.
**EDIT** : Here's a complete version that works (on my machine):
from PIL import Image, ImageTk
from Tkinter import Tk, Label, SOLID
import cv2
import numpy as np
img = np.array(Image.open('some-file.png'))
window = Tk()
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
re_hsv=Image.fromarray(imghsv).resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(window, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
hsv_img()
window.mainloop()
I had to rename some things, as well as add a call to `Image.fromarray` when
you resize to 360x360.
It seems like most of the confusion stems from different
numpy/PIL/OpenCV/Tkinter image formats. You might find [this conversion
guide](http://www.comp.nus.edu.sg/~cs4243/conversion.html) useful, though it's
slightly out of date.
|
How can you make \b accept words that start with '+' using regex in python?
Question:
re.search(r"\b\+359\b","Is your phone number +359 887438?")
Why is this regex not finding `+359` and how can i make `\b` consider words
starting with `+`?
Answer: You can't alter `\b`'s behaviour. You'd have to use a different anchor; like
`\B`, which matches anywhere _not_ at the start or end of a word; it is the
inverse of `\b`:
\B\+359\b
This again matches if there is no word character preceding `+`, which itself
is a non-word character. Where `\b` can only match between a word and nonword
character (so `WORD\bNONWORD` or `NONWORD\bWORD`), `\B` needs two nonword or
two word characters to match (so `WORD\BWORD` or `NONWORD\BNONWORD`). As `+`
is a nonword character, whatever comes before `+` must _also_ be a non-word
character.
Alternatively, you can use a negative look-behind:
(?<!\w)\+359\b
The `(?<!\w)` negative look-behind assertion only matches a position where
there is no word character preceding the position.
Demo:
>>> import re
>>> re.search(r"\b\+359\b","Is your phone number +359 887438?")
>>> re.search(r"\B\+359\b","Is your phone number +359 887438?")
<_sre.SRE_Match object at 0x10cf03850>
>>> re.search(r"(?<!\w)\+359\b","Is your phone number +359 887438?")
<_sre.SRE_Match object at 0x10cf03d30>
|
Python SQL connect to wrong ip adress
Question: I'm trying to connect to my sql server using a simple python script.
import MySQLdb
db = MySQLdb.connect(host="192.168.0.156", user="root",
passwd="Imnottellingyoumypassword", db="mydatabase") # name of the data base
cur = db.cursor()
cur.execute("SELECT * FROM customers")
for row in cur.fetchall() :
print row[0]
But when I run my script something goes wrong:
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user
'root'@'192.168.0.107' (using password: YES)")
Why is he trying to connect to my ip address of my laptop instead of the sql
server?
Answer: That message is from the MySQL server and not the MySQL driver. What the
server is telling you is that connections as root from the IP of your laptop
aren't allowed.
|
python cannot kill process using process.terminate
Question: I have a python code as following:
import threading
import time
import subprocess, os, sys, psutil, signal
from signal import SIGKILL
def processing():
global p_2
global subp_2
.
.
.
if condition1: #loop again
threading.Timer(10,processing).start()
if condition2:
signal.signal(signal.SIGINT, signal_handler)
#signal.signal(signal.SIGTERM, signal_handler)
subp_2.terminate()
#os.kill(subp_2.pid, 0)
#subp_2.kill()
print " Status p_2: ", p_2.status
def signal_handler(signal, frame):
print('Exiting')
sys.exit(0)
def function():
global p_1
global subp_1
.
.
.
if condition1: #loop again
threading.Timer(5,function).start()
if condition2:
signal.signal(signal.SIGINT, signal_handler)
#signal.signal(signal.SIGTERM, signal_handler)
subp_1.terminate()
#os.kill(subp_1.pid, 0)
#subp_1.kill()
print " Status p_1: ", p_1.status
threading.Timer(10,processing).start()
subp_2 = subprocess.Popen('./myScript2.sh %s %s' % (arg0, arg1), shell=True)
p_2 = psutil.Process(subp_2.pid)
if __name__ == '__main__':
global p_1
global subp_1
.
.
.
subp_1 = subprocess.Popen(["/.../myScript1.sh"], shell=True)
p_1 = psutil.Process(subp_1.pid)
threading.Timer(5,function).start()
I could not kill the processe subp_1 and subp_2. Whatever I tried:
.terminate(), .kill() or os.kill() I am still getting process status running.
Could anyone tell me please what am I missing ? Any hint is appreciated.
Answer: When you use `shell=True`, first a subprocess is spawned which runs the shell.
Then the shell spawns a subprocess which runs `myScript2.sh`. The subprocess
running the shell can be terminated without terminating the `myScript2.sh`
subprocess.
If you can avoid using `shell=True`, then that would be one way to avoid this
problem. If using user input to form the command, `shell=True` should
definitely be avoided, since it is a [security
risk](https://docs.python.org/2/library/subprocess.html#subprocess.call).
On Unix, by default, the subprocess spawned by `subprocess.Popen` is _not_ a
[session leader](http://unix.stackexchange.com/q/18166/3330). When you send a
signal to a session leader, it is propagated to all processes with the same
session id. So to have the shell pass the `SIGTERM` to `myScript2.sh`, make
the shell a session leader.
For Python versions < 3.2 on Unix, that can be done by having the shell
process run `os.setsid()`:
import os
subp_2 = subprocess.Popen('./myScript2.sh %s %s' % (arg0, arg1),
shell=True,
preexec_fn=os.setsid)
# To send SIGTERM to the process group:
os.killpg(subp_2.pid, signal.SIGTERM)
For Python versions >= 3.2 on Unix, pass `start_new_session=True` to `Popen`.
For Windows, see [J.F. Sebastian's
solution](http://stackoverflow.com/a/13256908/190597).
|
How to use python readlines method in random order
Question: How can one use the `readlines()` method to read a file in a random shuffled
manner i.e. `random.shuffle()`
file = open(filename)
data = file.readlines()
file_length = len(data)
Answer: Get them into a list with `lines = file.readlines()`, and then
`random.shuffle(lines)` that list (import `random` module).
|
Limiting number of processes in multiprocessing python
Question: My requirement is to generate `hundreds of HTTP POST requests per second`. I
am doing it using `urllib2`.
def send():
req = urllib2.Request(url)
req.add_data(data)
response = urllib2.urlopen(req)
while datetime.datetime.now() <= ftime:
p=Process(target=send, args=[])
p.start()
time.sleep(0.001)
The problem is this code `sometimes for some iterations` throws either of
following exceptions:
HTTP 503 Service Unavailable.
URLError: <urlopen error [Errno -2] Name or service not known>
I have tried using `requests(HTTP for humans)` as well but I am having some
proxy issues with that module. Seems like `requests` is sending http packets
to proxy server even when target machine is within same LAN. I don't want
packets to go to proxy server.
Answer: The simplest way to limit number of concurrent connections is to use a thread
pool:
#!/usr/bin/env python
from itertools import izip, repeat
from multiprocessing.dummy import Pool # use threads for I/O bound tasks
from urllib2 import urlopen
def fetch(url_data):
try:
return url_data[0], urlopen(*url_data).read(), None
except EnvironmentError as e:
return url_data[0], None, str(e)
if __name__=="__main__":
pool = Pool(20) # use 20 concurrent connections
params = izip(urls, repeat(data)) # use the same data for all urls
for url, content, error in pool.imap_unorderred(fetch, params):
if error is None:
print("done: %s: %d" % (url, len(content)))
else:
print("error: %s: %s" % (url, error))
`503 Service Unavailable` is a server error. It might fail to handle the load.
`Name or service not known` is a dns error. If you need make many requests;
install/enable a local caching dns server.
|
splitext in write is not giving the basename
Question: I am trying to split text to the basename as:
#!/usr/bin/python3
import os.path
out.write(atoms[q]+" ")
out.write(str(os.path.splitext(atoms[q][0]))+" ")
which is yielding:
Mn7.pot ('M', '')
where obviously the full text is `Mn7.pot` as shown by the first one, and by
splitext, I want the `'Mn7'`, (even better, if I can have without the
enclosing `''`).
If I do this in terminal, using print, I am getting the correct result(almost)
as:
$python3
Python 3.3.2 (default, Mar 5 2014, 08:21:05)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> file="Mn7.pot"
>>> os.path.splitext(file)
('Mn7', '.pot')
please show me how I can achieve this is `write` function as well.
Answer: If `atoms[q]` is `Mn7.pot` then `atoms[q][0]` is `M`.
You don't need the `str()` call and you don't need the `[0]`.
|
Split Cloud Endpoint API over multiple classes and multiple files
Question: I've started working on a Cloud Endpoint API as a first-time Python programmer
(with experience in Java and PHP).
I would like to keep everything together in one API but split different
resource calls over different files. The documentation gives this as an
example:
an_api = endpoints.api(name='library', version='v1.0')
@an_api.api_class(resource_name='shelves')
class Shelves(remote.Service):
...
@an_api.api_class(resource_name='books', path='books')
class Books(remote.Service):
...
endpoints.api_server([an_api])
What I would like to do is put the `Shelves` and `Book` classes in different
files since they're both going to get quite long. I've tried just moving them,
but that results in an empty API discovery document because the files probably
aren't loaded/run/interpreted when the API is started.
How can I fix this? I have a feeling it's going to be something with `import`
but I can't figure it out...
Thanks!
Answer: Yes, you have to sure that the api classes are properly imported, but if there
was a problem with this you'd be getting some runtime exception rather than an
empty discovery document.
The problem I can see is you're creating the api server with the `an_api`
object which you use to decorate your actual API classes. You should do the
following instead:
an_api = endpoints.api(name='library', version='v1.0')
@an_api.api_class(resource_name='shelves')
class Shelves(remote.Service):
...
@an_api.api_class(resource_name='books', path='books')
class Books(remote.Service):
...
endpoints.api_server([Shelves, Books])
To then go from this to a multi-module API, you'll easily run into a circular
dependency situation (something that Python cannot deal with). You then need a
common module where you define `an_api`; a set of API modules that implement a
part of the API, all of which `import` the common module; and then you'll need
a main module that calls `endpoints.api_server`.
A note: in the Python world it's not uncommon for a single module (file) to be
quite long indeed and have very many classes in it; this may seem very odd
coming from Java or well-structured PHP.
|
Invalid characters (&) in "where" request to Eve
Question: I found this problem in my development system and have reproduced it in the
Eve demo found [here](https://github.com/nicolaiarocci/eve-
demo/blob/master/README.rst)
This the code I run.
import requests
import json
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
name = "max and me"
data = {"lastname":id_generator(), "firstname":name}
print data
res = requests.post("http://127.0.0.1:5000/people", data = data)
print res.text
data = 'where={"firstname":"%s"}' % (name)
res = requests.get("http://127.0.0.1:5000/people", params = data)
print res.text
first I make a POST including the variable , and the I do a GET with a where
on the same variable . First I set the variable to "max and me" and all runs
fine Then I run the with set to "max & me" and eve throws up all over me:
127.0.0.1 - - [23/Apr/2014 20:22:07] "GET /people?where=%7B%22firstname%22:%22max%20&%20me%22%7D HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/endpoints.py", line 53, in collections_endpoint
response = get(resource, lookup)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/methods/common.py", line 226, in rate_limited
return f(*args, **kwargs)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/auth.py", line 45, in decorated
return f(*args, **kwargs)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/methods/common.py", line 429, in decorated
r = f(*args, **kwargs)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/methods/get.py", line 104, in get
cursor = app.data.find(resource, req, lookup)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/io/mongo/mongo.py", line 145, in find
spec = parse(req.where)
File "/Users/hingem/Documents/python/venv/lib/python2.7/site-packages/eve/io/mongo/parser.py", line 26, in parse
v.visit(ast.parse(expression))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
{"firstname":"max
^
SyntaxError: EOL while scanning string literal
It's probably me not handling the <&> symbol probably - but I feel that I have
tried all sorts of encoding...And I get stuck....every time
Answer: Try replacing `&` with its escaped version:`%26`. I just tried this GET to a
Eve-powered API
`?where={"name": "You %26 me"}`
and it worked just fine.
|
Can't insert tuple to mssql db
Question: I am using `pymssql` in Python 3.3 to communicate with my Mssql db. And I am
trying to save the data from a user in a tuple to the database, but I keep
getting this weird error:
pymssql.ProgrammingError: (102, b"Incorrect syntax near '\\'.DB-Lib error message 102, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
My method, the error is showing in the last line:
user.password = user.password.encode('utf_8')
user.password = encrypt_RSA(user.password)
cursor.execute('INSERT INTO Usertable VALUES(%i, \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')' % user.get_usertuple())
I suspect it has something to do with the encoding and encrypting:
def encrypt_RSA(message, public_key_loc = "pubkey.pem"):
'''
param: public_key_loc Path to public key
param: message String to be encrypted
return encoded encrypted string
'''
key = open(public_key_loc, "r").read()
rsakey = RSA.importKey(key)
rsakey = PKCS1_OAEP.new(rsakey)
encrypted = rsakey.encrypt(message)
return encrypted
Can anyone tell what I am doing wrong here? And how to fix it?
EDIT: My query now looks like this:
cursor.execute('INSERT INTO Usertable VALUES(%i, %s, %s, %s, %s, %s, %s)' % user.get_usertuple())
But that gives me another error: pymssql.OperationalError: (103, b"The identifier that starts with (LONG TEXT) is too long. Maximum length is 128.DB-Lib error message 103, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 102, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
Answer: use bind variables. it is safer, it is kinder to the DB.
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
your strings will be automatically and properly wrapped in quotes.
|
Having trouble with pythonic style and list comprehension
Question: I spent yesterday writing a small script in Python, which is not my primary
language, and it left me with some questions on how to do things in proper
'pythonic' style. The task is fairly simple, I have two arrays `fieldnames`
and `values`. Imagine their contents are
fieldnames = ['apples','oranges','pears','bananas']
values = [None,2,None,5]
I need to create an array of fieldnames that only consists of indices that
correspond with values that are not None. Currently I am doing it like this:
#print fieldnames
usedFieldnames = []
for idx,val in enumerate(values):
if val is not None:
usedFieldnames.append(fieldnames[idx])
I could be wrong, but this seems very non-pythonic to me, and I was wondering
if there was a more python-appropriate way to do this with a list
comprehension. Any help would be appreciated.
Answer: You can use [`zip()`](https://docs.python.org/2/library/functions.html#zip):
>>> fieldnames = ['apples','oranges','pears','bananas']
>>> values = [None,2,None,5]
>>> [field for field, value in zip(fieldnames, values) if value is not None]
['oranges', 'bananas']
If you are using python2.x, instead of `zip()`, which creates a new list with
zipped lists, you can take an "iterative" approach and use
[`itertools.izip()`](https://docs.python.org/2/library/itertools.html#itertools.izip):
>>> from itertools import izip
>>> [field for field, value in izip(fieldnames, values) if value is not None]
['oranges', 'bananas']
In case of python3.x, `zip()` returns an iterator, not a list.
|
pyside: QFileDialog returns an empty list
Question: When I run the script below, I am able to select several files in the file
dialog, but the value returned for the var "filenames" is: "[ ]", which
appears to be an empty list.
I think the solution must be somewhere on this page, but I can't figure out
what it is: <http://srinikom.github.io/pyside-
docs/PySide/QtGui/QFileDialog.html>
Any suggestions would be much appreciated. I'm a python and pyside newbie.
#!/usr/bin/python
# -*- coding: utf-8 -*-
# http://srinikom.github.io/pyside-docs/PySide/QtGui/QFileDialog.html
from PySide import QtGui
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.ExistingFiles)
#dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly, False)
fileNames = dialog.selectedFiles()
print str(fileNames)
dialog.exec_()
Answer: There won't be any selected files before you actually run the dialog.
if dialog.exec_():
fileNames = dialog.selectedFiles()
print str(fileNames)
else:
print "Canceled"
|
How to handle cgi form with Python requests
Question: I'm trying to use the requests module in Python to handle a cgi and can't work
out what I've done wrong.
I've tried to use Google Dev Tools in Chrome to provide the right params and
data but I've not quite fixed it.
The site I'm trying to get data from is:
<http://staffordshirebmd.org.uk/cgi/birthind.cgi>
Here's my code
import requests
headers = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding":"gzip,deflate,sdch",
"Accept-Language":"en-US,en;q=0.8",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
"Content-Length":"124",
"Content-Type":"application/x-www-form-urlencoded",
"DNT":"1",
"Host":"staffordshirebmd.org.uk",
"Origin":"http://staffordshirebmd.org.uk",
"Pragma":"no-cache",
"Referer":"http://staffordshirebmd.org.uk/cgi/birthind.cgi?county=staffordshire",
"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"}
payload = {"county":"staffordshire",
"lang": "",
"year_date":"1837",
"search_region":"All",
"sort_by":"alpha",
"csv_or_list":"screen",
"letter":"A",
"submit":"Display Indexes"}
f = requests.put(path, data=payload, headers=headers)
f.text
This provides the response:
u'<html>\n<body>\n<div>\n<p>\nThe Bookmark you have used to reach this page is not valid.\n</p>\n<p>\nPlease click <a href="http://staffordshirebmd.org.uk/">here</a> to return to the main page and reset your\nbookmark to that page.\n</p>\n</div>\n</body>\n</html>\n\n'
What am I doing wrong?
Answer: The URL you used in your `Referrer` header has a form that uses `POST`, not
`PUT`.
You rarely should hardcode the `Content-Length` header; do leave that up to
`requests` to calculate for you and set. Different browsers can easily use
subtly different content lengths, a script that only works with a fixed
`Content-Length` would not last long.
Removing the `Content-Length` header and changing `.put()` to `.post()` gives
me results, in any case.
|
Retrieve block of text from a file, using key-words as start-point in Python 2.7?
Question: I'm trying to read a paragraph of text from a file based on the paragraph's
title (first line). For example, let's say the file is as so:
Paragraph 1:1
This paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This
paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This paragraph
1. This paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This
paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This paragraph
Paragraph 1:2
This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph
2. This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph
2. This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph
2. This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph 2
I have my code so that I can choose a title at random:
def get_paragraph():
f = open('file.txt','r')
n = [str(x) for x in range(3)]
paragraph_list = []
for line in f:
for numbers in n: # I know the following code isn't very pretty...
if (number in line) and (':' in line) and (len(line) < 20):
paragraph_list.append(line)
selection = random.choice(paragraph_list)
print(selection)
get_paragraph()
Now, I want to be able to read the rest of the paragraph associated with that
first line, ending at the blank line - so that the output will be a randomly
selected paragraph from the file.
Any suggestions or help would be greatly appreciated!
Answer: I would approach this differently
from collections import defaultdict
def get_paragraph(file_path)
myString = open(file_path.read()
paragraphList = myString.split('\n\n') # split by adjacent newlines
paragraphList = [paragraph.split('\n') for paragraph in paragraphList]
paragrpahDictionary = defaultdict(list)
for paragraph in paragraphList:
paragraphNumber = int(paragraph[0].split(:)[-1])
paragraphBody = paragraph[1:]
paragraphDictionary[paragraphNumber] = paragraphBody
choices = paragraphDictionary.keys()
theParagraph=random.choice(choices)
for line in paragraphDictionary[theParagraph]
print line + '\n'
|
Save Outfile with Python Loop in SPSS
Question: Ok so I've been playing with python and spss to achieve almost what I want. I
am able to open the file and make the changes, however I am having trouble
saving the files (and those changes). What I have (using only one school in
the `schoollist`):
begin program.
import spss, spssaux
import os
schoollist = ['brow']
for x in schoollist:
school = 'brow'
school2 = school + '06.sav'
filename = os.path.join("Y:\...\Data", school2) #In this instance, Y:\...\Data\brow06.sav
spssaux.OpenDataFile(filename)
#--This block are the changes and not particularly relevant to the question--#
cur=spss.Cursor(accessType='w')
cur.SetVarNameAndType(['name'],[8])
cur.CommitDictionary()
for i in range(cur.GetCaseCount()):
cur.fetchone()
cur.SetValueChar('name', school)
cur.CommitCase()
cur.close()
#-- What am I doing wrong here? --#
spss.Submit("save outfile = filename".)
end program.
Any suggestions on how to get the `save outfile` to work with the loop?
Thanks. Cheers
Answer: In your save call, you are not resolving filename to its actual value. It
should be something like this: spss.Submit("""save outfile="%s".""" %
filename)
|
How to mock Python static methods and class methods
Question: How do I mock a class that has unbound methods? For example, this class has a
`@classmethod` and a `@staticmethod`:
class Calculator(object):
def __init__(self, multiplier):
self._multiplier = multiplier
def multiply(self, n):
return self._multiplier * n
@classmethod
def increment(cls, n):
return n + 1
@staticmethod
def decrement(n):
return n - 1
calculator = Calculator(2)
assert calculator.multiply(3) == 6
assert calculator.increment(3) == 4
assert calculator.decrement(3) == 2
assert Calculator.increment(3) == 4
assert Calculator.decrement(3) == 2
The above pretty much describes my question. The following is a working
example that demonstrates the things I have tried.
Class `Machine` contains an instance of `Calculator`. I will be testing
`Machine` with a mock of `Calculator`. To demonstrate my issue, `Machine`
calls the unbound methods via an instance of `Calculator` and via the
`Calculator` class:
class Machine(object):
def __init__(self, calculator):
self._calculator = calculator
def mult(self, n):
return self._calculator.multiply(n)
def incr_bound(self, n):
return self._calculator.increment(n)
def decr_bound(self, n):
return self._calculator.decrement(n)
def incr_unbound(self, n):
return Calculator.increment(n)
def decr_unbound(self, n):
return Calculator.decrement(n)
machine = Machine(Calculator(3))
assert machine.mult(3) == 9
assert machine.incr_bound(3) == 4
assert machine.incr_unbound(3) == 4
assert machine.decr_bound(3) == 2
assert machine.decr_unbound(3) == 2
All the functional code above works fine. Next is the part that does not work.
I create a mock of `Calculator` to use in testing `Machine`:
from mock import Mock
def MockCalculator(multiplier):
mock = Mock(spec=Calculator, name='MockCalculator')
def multiply_proxy(n):
'''Multiply by 2*multiplier instead so we can see the difference'''
return 2 * multiplier * n
mock.multiply = multiply_proxy
def increment_proxy(n):
'''Increment by 2 instead of 1 so we can see the difference'''
return n + 2
mock.increment = increment_proxy
def decrement_proxy(n):
'''Decrement by 2 instead of 1 so we can see the difference'''
return n - 2
mock.decrement = decrement_proxy
return mock
In the unit test below, the bound methods use `MockCalculator` as I had hoped.
However, the calls to `Calculator.increment()` and `Calculator.decrement()`
still use `Calculator`:
import unittest
class TestMachine(unittest.TestCase):
def test_bound(self):
'''The bound methods of Calculator are replaced with MockCalculator'''
machine = Machine(MockCalculator(3))
self.assertEqual(machine.mult(3), 18)
self.assertEqual(machine.incr_bound(3), 5)
self.assertEqual(machine.decr_bound(3), 1)
def test_unbound(self):
'''Machine.incr_unbound() and Machine.decr_unbound() are still using
Calculator.increment() and Calculator.decrement(n), which is wrong.
'''
machine = Machine(MockCalculator(3))
self.assertEqual(machine.incr_unbound(3), 4) # I wish this was 5
self.assertEqual(machine.decr_unbound(3), 2) # I wish this was 1
So I try to patch `Calculator.increment()` and `Calculator.decrement()`:
def MockCalculatorImproved(multiplier):
mock = Mock(spec=Calculator, name='MockCalculatorImproved')
def multiply_proxy(n):
'''Multiply by 2*multiplier instead of multiplier so we can see the difference'''
return 2 * multiplier * n
mock.multiply = multiply_proxy
return mock
def increment_proxy(n):
'''Increment by 2 instead of 1 so we can see the difference'''
return n + 2
def decrement_proxy(n):
'''Decrement by 2 instead of 1 so we can see the difference'''
return n - 2
from mock import patch
@patch.object(Calculator, 'increment', increment_proxy)
@patch.object(Calculator, 'decrement', decrement_proxy)
class TestMachineImproved(unittest.TestCase):
def test_bound(self):
'''The bound methods of Calculator are replaced with MockCalculator'''
machine = Machine(MockCalculatorImproved(3))
self.assertEqual(machine.mult(3), 18)
self.assertEqual(machine.incr_bound(3), 5)
self.assertEqual(machine.decr_bound(3), 1)
def test_unbound(self):
'''machine.incr_unbound() and Machine.decr_unbound() should use
increment_proxy() and decrement_proxy(n).
'''
machine = Machine(MockCalculatorImproved(3))
self.assertEqual(machine.incr_unbound(3), 5)
self.assertEqual(machine.decr_unbound(3), 1)
Even after patching, the unbound methods want an instance of `Calculator` as
an argument:
> TypeError: unbound method increment_proxy() must be called with Calculator
> instance as first argument (got int instance instead)
How do I mock out class method `Calculator.increment()` and static method
`Calculator.decrement()`?
Answer: You were patching the wrong object. You must patch the `Calculator` from the
`Machine` class, not the general `Calculator` class. Read about it
[here](http://alexmarandon.com/articles/python_mock_gotchas/).
from mock import patch
import unittest
from calculator import Calculator
from machine import Machine
class TestMachine(unittest.TestCase):
def my_mocked_mult(self, multiplier):
return 2 * multiplier * 3
def test_bound(self):
'''The bound methods of Calculator are replaced with MockCalculator'''
machine = Machine(Calculator(3))
with patch.object(machine, "mult") as mocked_mult:
mocked_mult.side_effect = self.my_mocked_mult
self.assertEqual(machine.mult(3), 18)
self.assertEqual(machine.incr_bound(3), 5)
self.assertEqual(machine.decr_bound(3), 1)
def test_unbound(self):
'''Machine.incr_unbound() and Machine.decr_unbound() are still using
Calculator.increment() and Calculator.decrement(n), which is wrong.
'''
machine = Machine(Calculator(3))
self.assertEqual(machine.incr_unbound(3), 4) # I wish this was 5
self.assertEqual(machine.decr_unbound(3), 2) # I wish this was 1
|
Ipython notebook align Latex equations in Ipython.Display module
Question: I am using ipython notebook to write latex equations with the following
modules
from IPython.display import display, Math, Latex
a simple example code might look like:
display(Math('a = \\frac{1}{2}'))
display(Math('b = \\frac{1}{3}'))
display(Math('c = \\frac{1}{4}'))
Which would output:
a = 1/2
b = 1/3
c = 1/4
in a pretty print format. Is there a way that I can somehow align this in
columns like:
a = 1/2 b = 1/3 c = 1/4
? I know that the markup allows HTML usage, but this markup is entered into
the input for a code-based cell. Any help/advice is greatly appreciated!!
Answer: I'm not sure how familiar you are with LaTeX, but the notebook does allow you
to use things like `\begin{align}`, allowing you to organize things into
columns by separating them with `&` symbols. For example, this works if you
enter it into a Markdown cell:
$$
\begin{align}
a = \frac{1}{2} && b = \frac{1}{3} && c = \frac{1}{4} \\
a && b && c
\end{align}
$$
This also works using `display(Math())`, e.g.:
display(Math(
r"""
\begin{align}
a = \frac{1}{2} && b = \frac{1}{3} && c = \frac{1}{4} \\
a && b && c \\
1 && 2 && 3
\end{align}
"""))
Giving you this output:

|
subprocess.call() fails on Mac and Linux
Question: I'm running into a weird issue with subprocess.call() function. I am trying to
execute Java's 'jar' command using subprocess.call(). Here's the code:
import os
import subprocess
def read_war():
war_file_path = "jackrabbit-webapp-2.6.5.war"
java_home = os.environ['JAVA_HOME']
jar_path = os.path.join(java_home, 'bin', 'jar')
jar_cmd = jar_path + ' tvf ' + war_file_path
print "command to be executed is : " + jar_cmd
subprocess.call(jar_cmd)
read_war()
I'm using Python v2.7.3 on both Windows and Linux (Oracle Enterprise Linux).
On Windows 7, I see the contents of the war file being displayed. On Linux,
however, I see a 'no such file or directory' error.:
$ python example.py
command to be executed is : /usr/local/tools/jdk1.7.0_15/bin/jar tvf jackrabbit-webapp-2.6.5.war
Traceback (most recent call last):
File "example.py", line 24, in <module>
read_war()
File "example.py", line 23, in read_war
subprocess.call(jar_cmd)
File "/usr/local/tools/Python-2.7.3/Lib/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/local/tools/Python-2.7.3/Lib/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/local/tools/Python-2.7.3/Lib/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
$
I've tried the command '/usr/local/tools/jdk1.7.0_15/bin/jar tvf jackrabbit-
webapp-2.6.5.war' from command prompt and it works fine. So, nothing's wrong
with the command. I've tried various combinations of subprocess.call() -
passing a string, passing a list etc. None of them worked. Any help at all
would be appreciated.
Answer: Add shell=True to the call. On windows, the CreateProcess command does string
parsing to separate the command and its various arguments. On linux, you only
get string processing if you specifically tell subprocess to call the shell.
Otherwise, it treats that entire string you handed in as the command and you
don't get very far.
subprocess.call(jar_cmd, shell=True)
|
Python - splitting a string twice
Question: I have some data that looks like
"string,string,string:otherstring,otherstring,otherstring".
I want to manipulate the first set of "string"s one at a time. If I split the
input and delimit it based off a colon, I will then end up with a list. I then
cannot split this again because "'list' object has no attribute 'split'".
Alternatively, if I decide to delimit based off a comma, then that will return
everything (including stuff after the comma, which I don't want to
manipulate). rsplit has the same problem. Now even with a list, I could still
manipulate the first entries by using [0], [1] etc. except for the fact that
the number of "string"s is always changing, so I am not able to hardcode the
numbers in place. Any ideas on how to get around this list limitation?
Answer: Try this:
import re
s = 'string,string,string:otherstring,otherstring,otherstring'
re.split(r'[,:]', s)
=> ['string', 'string', 'string', 'otherstring', 'otherstring', 'other string']
We're using regular expressions and the
[`split()`](https://docs.python.org/2/library/re.html#re.split) method for
splitting a string with more than one delimiter. Or if you want to manipulate
the first group of strings in a separate way from the second group, we can
create two lists, each one with the strings in each group:
[x.split(',') for x in s.split(':')]
=> [['string', 'string', 'string'], ['otherstring', 'otherstring', 'otherstring']]
… Or if you just want to retrieve the strings in the first group, simply do
this:
s.split(':')[0].split(',')
=> ['string', 'string', 'string']
|
cant import netsnmp in python on centos 6.5
Question: I am trying to use netsnmp in python but it is unable to import after
following all suggestions related to netsnmp in python. I installed netsnmp
using below commands
yum install net-snmp net-snmp-utils
easy_install ipython
snmpd service is running. It still throws this error
ImportError: No module named netsnmp
I am using Cent os 6.5 and Python version 2.6.6 Kindly help if installation is
incorrect or any other configuration is missing.
Answer: To import netsnmp in python only _net-snmp-python_ is required both _net-snmp
net-snmp-utils_ can be removed. so just
yum install net-snmp-python
will do for importing netsnmp library into python on Cent os 6.5
yum install net-snmp net-snmp-utils
will enable SNMP queries from Linux terminal. Both can work independently.
|
Calculate time difference between entries in a file using python
Question: I have csv file with the data formatted like this `date,time,event,user,net` .
I need to go through each line of this file, and if event == start, continue
till it reach the line with event == end for the same user and net, then
calculate the time difference between the two events. I have this code:
import csv
import datetime
import time
with open('dates.csv', 'rb') as csv_file:
csv_read = csv.reader(csv_file)
for row in csv_read:
if row[2]=="start":
n1=datetime.datetime.strptime(row[1], '%H:%M:%S')
for row2 in csv_read:
if (row2[2]=="End" and row[3]==row2[3] and row[4]==row2[4]):
n2=datetime.datetime.strptime(row2[1], '%H:%M:%S')
print row[2],row[1], row2[2], row2[1]
diff = n2 - n1
print "time difference = ", diff.seconds
break
But the problem with this code is that when it find a match "End" and
calculate the time, it will start searching from the line after the with the
match "End", ignoring the lines before it. as an example
May,20,9:02:22,2010,start,user1,net-3
May,20,9:02:23,2010,start,user1,net-3
May,20,9:02:55,2010,start,user1,net-2
May,20,9:02:55,2010,End,user1,net-3
May,20,9:03:43,2010,End,user1,net-2
May,20,9:02:55,2010,End,user1,net-3
May,20,9:03:43,2010,End,user1,net-2
May,20,9:03:44,2010,start,user1,net-2
May,20,9:03:49,2010,End,user1,net-2
will only produce the following output:
Connect 9:02:22 Disconnect 9:02:55
time difference = 33
Connect 9:03:44 Disconnect 9:03:49
time difference = 5
So does anyone have an idea how to solve this problem, please? Also is it
possible to add the time difference as an extra column to the existing data?
thanks
I've updated the code, but now I'm facing a new problem, my file contains
35734 rows, but the output file contain only 350 rows, I'm confused as to why
this happens, and I would appreciate any help, thanks Updated Code:
l1=[] ## empty list
l2=[] ## empty list
csv_file=open('dates_read.csv', 'r+')
csv_wfile=open('dates_write.csv', 'w+')
csv_read = csv.reader(csv_file)
csv_read1 = csv_read
csv_write = csv.writer(csv_wfile)
for row in csv_read:
s=csv_read.line_num
if (row[4]=="start" and (s not in l1)):
n1=datetime.datetime.strptime(row[2], '%H:%M:%S')
l1.append(s)
month = str(row[0])
day = int(row[1])
time = str(row[2])
year = int(row[3])
user = str(row[5])
net = str(row[6])
dwell_time = str(row[7])
for row2 in csv_read1:
e=csv_read1.line_num
if (row2[4]=="End" and row[5]==row2[5] and row[6]==row2[6] and (csv_read1.line_num not in l2)and s<e):
n2=datetime.datetime.strptime(row2[2], '%H:%M:%S')
diff = n2 - n1
dwell_time= diff
print("time difference = ", diff.seconds,"\n")
csv_write.writerow([month, day, time, year, user, net, dwell_time])
l2.append(e)
break
print (s) #prints 818
print (e) #prints 35734
Answer: The only problem with your code is that you are traversing the lines for
**END** keyword right after it encounters the first **START** . Instead it
should traverse the line of the file from the beginning. With that we also had
to take into consideration that same line doesn't get traversed again. For
that we can use a list, that can hold the line number of the line been
traversed.
Instead of writing a new code i made changes to your code only.
>>> l=[] ## empty list
>>> csv_file=open('dates.csv')
>>> csv_read = csv.reader(csv_file)
>>> for row in csv_read:
if row[0].split()[4]=="start":
n1=datetime.datetime.strptime(row[0].split()[2], '%H:%M:%S')
s=csv_read.line_num
csv_file1=open('/Python34/Workspace/Stoverflow/dates.csv')
csv_read1 = csv.reader(csv_file1)
for row2 in csv_read1:
e=csv_read1.line_num
## Inside if iam adding to more checks that verify that the same line is not traversed again and the END flag is always encountered after START flag
if (row2[0].split()[4]=="End" and row[0].split()[6]==row2[0].split()[6] and row[0].split()[5]==row2[0].split()[5] and (csv_read1.line_num not in l) and s<csv_read1.line_num):
n2=datetime.datetime.strptime(row2[0].split()[2], '%H:%M:%S')
print("Connect : ",row[0].split()[2]," Disconnect :",row2[0].split()[2])
diff = n2 - n1
print("time difference = ", diff.seconds,"\n")
l.append(csv_read1.line_num)
del csv_read1
break
del csv_file1
|
Python Exceptions Logging
Question: Im currently logging the exceptions of a program via...
def log_message(text):
log_file = "/var/log/logfile.txt"
try:
if os.path.isfile(log_file):
mode = "a"
else:
mode = "w"
with open(log_file, mode) as myfile:
myfile.write("%s\n" % (text))
return True
except Exception as e:
print "error : ",e
return False
try:
... some code
except Exception as e:
log_message("error : %s" % (e))
However im my log I get "TypeError: argument of type 'NoneType' is not
iterable" Is there a way to also log the other info from the exception like
below. Such as the line number the module file etc etc ?
>>> post_builder_ghost(abc).generate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "post_builder.py", line 34, in generate
if 'youtube' in self.video:
TypeError: argument of type 'NoneType' is not iterable
>>>
Thanks,
Answer: To answer your question directly: look at
[traceback.print_exc](https://docs.python.org/2/library/traceback.html?highlight=traceback#traceback.print_exc)
**BUT...**
You should have a look at [standard
logging](https://docs.python.org/2/library/logging.html)
([tutorial](https://docs.python.org/2/howto/logging.html)). Your code would
become (in it's simplest form):
import logging
logging.basicConfig(stream=open("/var/log/logfile.txt", "a+"))
LOG = logging.getLogger(__name__)
try:
... some code
except Exception as e:
LOG.exception("human readable explanation of what you did")
As mentioned, this is the simplest form of logging. You can got much further
than this! Personally, I would advise _against_ `basicConfig`. But to get you
going quickly it will do just fine.
Diving into the logging config you will be able to do much more useful things,
like writing debug info in one file, and error messages into another file (or
stream like stderr, stdout).
It also supports what you asked, like logging module name, filename and line
number, but this is disabled by default. You can enable it, by specifying your
own message format (see [LogRecord
objects](https://docs.python.org/2/library/logging.html#logrecord-objects) for
a reference of the fields):
logging.basicConfig(stream=open("/var/log/logfile.txt", "a+"),
format="%(levelname)s:%(name)s:%(pathname)s:%(lineno)s:%(message)s")
The `LOG.exception` method I used above will include the stack trace (which is
what you wanted). You have other methods (`.debug`, `.info`, `.warning`,
`.error`, `.critical`) which will only emit the message.
As a rule of thumb, you want to configure the logging system _as soon as
possible_ in your application, but don't do it at the module level to avoid
interfering with other libraries if possible. If it's a console application,
"entry points" will help (or protect it with an `if __name__ == '__main__'`
block.
After configured (either manually, or using `basicConfig`), you can then put
this in each of your modules:
import logging
LOG = logging.getLogger(__name__)
Which will give a logger (`LOG`) dedicated to that module and enables you to
configure logging (increase/decrease verbosity for example) per module later
on (even at run-time).
|
replacing strings in files from list in python
Question: So I need to find all files with certain extension in this case `.txt`. Then I
must open all these files and change certain string with another string... and
here i'm stuck.
here is my code:
import os, os.path
find_files=[]
for root, dirs, files in os.walk("C:\\Users\\Kevin\\Desktop\\python programi"):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.txt':
find_files.append(fullpath)
for i in find_files:
file = open(i,'r+')
contents = file.write()
replaced_contents = contents.replace('xy', 'djla')
print i
ERROR mesage:
line 12, in <module>
contents = file.write()
TypeError: function takes exactly 1 argument (0 given)
i know that there is misssing an argument but which argument should I use? i
think it would be better if i change the code from `for i in find files:` down
any advice?
Answer: I think you mean to use `file.read()` rather than `file.write()`
|
Python parallel execution - how to debug efficiently?
Question: Below is a Python problem, that demonstrates how to iterate a function `func`
in parallel using `multiprocessing.Pool`. The are `Np` number of elements to
iterate. The function `func` merely returns `Np` minus the index of the
iterable. As seen I use a queue to return the values from the function, when
running in parallel mode.
If I set `runParallel=False` the program can be executed in serial mode.
The program runs fine, for `runParallel=False` and `runParallel=True`, but now
comes the essential problem I have: As you might see below, if setting
`problemIndex` a bit lower than `Np` (e.g. `problemIndex=7`), then I make a
floating point exception. I divide by zero - stupid me :-)
If running `runParallel=False` then I can see the source line number of the
bug and I catch the bug directly.
$ python map.py
Traceback (most recent call last):
File "map.py", line 63, in <module>
a = func(argList[p])
File "map.py", line 22, in func
ret = 1/(args["index"]-args["problemIndex"])
ZeroDivisionError: integer division or modulo by zero
Nice!
However for `runParallel=True` I just end up in the "Bummer" print-section
with no indication of the source of the bug. Annoying!
My question is: For `runParallel=True`, how can I efficiently debug this and
get the line number of the buggy code-line back from the `Pool()`?
#!/usr/bin/python
# map.py
import time
import multiprocessing
import sys
import random
# Toggle whether we run parallel or not
runParallel = True
# Problematic index - if less than Np we create an exception
problemIndex = 13
# Number of compute problems
Np = 10
def func(args):
# Emulate that the function might be fast or slow
time.sleep(random.randint(1,4))
ret = args["Np"] - args["index"]
# Emulate a bug
if args["index"]==args["problemIndex"]:
ret = 1/(args["index"]-args["problemIndex"])
# Return data
if args["runParallel"]:
# We use a queue thus ordering may not be protected
args["q"].put((args["index"],ret))
else:
return ret
# Return queue used when running parallel
manager = multiprocessing.Manager()
q = manager.Queue()
# Build argument lists
argList = []
for i in range(Np):
args={}
args["index"] = i # index
args["Np"] = Np # Number of problems
args["q"] = q # return queue for parallel execution mode
args["problemIndex"] = problemIndex # if index == problemIndex then func will malfunction
args["runParallel"] = runParallel # should we run parallel
argList.append(args)
#should we run parallel
if runParallel:
# Run 10 processes in parallel
p = multiprocessing.Pool(processes=10)
ret = p.map_async(func, argList)
ret.wait()
qLen = q.qsize()
p.close()
if not qLen == Np:
print "Bummer - one of more worker threads broke down",Np,qLen
sys.exit(0)
resultVector = [None]*Np
for p in range(Np):
if runParallel:
(i,a) = q.get(timeout=0.1)
else:
i = p
a = func(argList[p])
resultVector[i] = a
for i in range(Np):
print "Index", i, "gives",resultVector[i]
Answer: It's not very elegant, but how about:
def func(args):
try:
# Emulate that the function might be fast or slow
time.sleep(random.randint(1,4))
ret = args["Np"] - args["index"]
# Emulate a bug
if args["index"]==args["problemIndex"]:
ret = 1/(args["index"]-args["problemIndex"])
# Return data
if args["runParallel"]:
# We use a queue thus ordering may not be protected
args["q"].put((args["index"],ret))
else:
return ret
except Exception as e:
logging.exception(e)
raise
output should look like this(for problemIndex=9):
ERROR:root:integer division or modulo by zero
Traceback (most recent call last):
File "/home/rciorba/test.py", line 26, in func
ret = 1/(args["index"]-args["problemIndex"])
ZeroDivisionError: integer division or modulo by zero
Bummer - one of more worker threads broke down 10 9
|
Combining multiple text files belonging to different groups using Python
Question: In my directory the following files (1_xxx.txt, 2_xxx.txt, 1_yyy.txt,
2_yyy.txt, 1_zzz.txt, 2_zzz.txt) exists. The contents of those files are shown
below:
1_xxx.txt:
-114.265646442 34.0360392257
-112.977603537 31.6338662268
-117.239800991 36.1408246787
-114.716762067 32.958308901
-116.710069802 36.2660863375
-115.412539137 34.5790101356
-117.173651349 36.1032456689
-115.254332318 33.8689615728
-115.225643473 32.8079130497
-113.757416909 32.6491579487
2_xxx.txt:
-121.527298571 38.3074782763
-119.241009725 35.2597437123
-111.993090251 33.1087011262
-119.328464365 35.8944690935
-114.819870325 32.7076471384
-120.041889447 36.4080463723
-121.249592001 38.3951295581
-121.078565259 37.6730108558
-120.523147893 37.2889578323
-119.2383536 35.9028202963
1_yyy.txt:
-109.690156887 34.2072891001
-119.780672722 38.7665894396
-118.557741892 35.6314002547
-118.483411917 36.3579432166
-123.472136838 39.1714120111
-123.485136802 40.0894616596
-109.185105643 33.8647845733
-120.046426359 38.4660843951
-122.929234616 40.1186699391
-123.300682512 39.2757431576
2_yyy.txt:
-120.915282551 37.0468246029
-118.168309521 37.606220824
-111.172152572 35.5687631188
-110.999951025 34.8671827527
-120.375558342 37.7773687622
-121.028079242 36.5374775742
-118.53486589 36.7879815762
-115.771046166 39.1046390941
-117.618352132 39.3133019115
-110.163871705 34.6500104537
1_zzz.txt:
-117.442417987 34.0694542108
-118.624320171 34.3117074054
-111.915932786 33.6893480358
-118.214145399 34.0360392257
-122.189710383 37.6396159347
-122.413202409 37.9443375576
-115.524007077 32.9541312874
-117.735266836 33.9107314118
-110.840774505 32.3734158543
-122.399926026 37.7898915865
2_zzz.txt:
-106.544451063 31.5126888716
-112.728165588 32.3232796291
-117.793575105 34.8128904057
-116.464953895 32.3441697714
-116.206850112 34.2448798952
-121.758363934 37.9819048821
-113.317063698 33.5306154403
-115.999423067 31.4750816387
-115.257632657 37.8817248156
-117.558324417 37.4684639908
I want to combine those files matching xxx, yyy, and zzz, and write one
separate file for each group:
files = glob.glob('*.txt')
my_classes = ['xxx', 'yyy', 'zzz']
files_dict ={}
for c in my_classes:
files_dict[c] = [f for f in files if c in f]
all_lons, all_lats ={}, {}
for e, f in files_dict.iteritems():
all_lons[e], all_lats[e] = [], []
for x in f:
fi = open(x, 'r')
lines = fi.read().splitlines()
lons = [l.split(' ')[0] for l in lines]
lats = [l.split(' ')[1] for l in lines]
all_lons[e].apend(lons)
all_lats[e].apend(lats)
for g, h in all_lons.iteritems():
for i, j in all_lats.iteritems():
with open(g + '_final.txt', 'w') as fo:
fo.write(str(h) + str(j) + '\n' )
Because of my limited knowledge of Python I could not do it. I am waiting to
know best practices of solving it. The number of text files corresponding to
each of my class(i.e., xxx, yyy, zzz) are more than two than shown in this
example.
Answer: Since you are under windows, the shell option _might_ not work for you unless
you are working with a POSIX-like shell, so here is a similar way to it in
python.
import glob
files = glob.glob('*.txt')
my_classes = ['xxx', 'yyy', 'zzz']
for cls in my_classes:
files = glob.glob('*{}*.txt'.format(cls))
if files:
with open(cls, 'w') as fout:
for file_name in files:
with open(file_name, 'r') as fin:
fout.write(fin.read())
This is based on the fact that you really don't need to do any processing on
the contents of each file other than putting them all together based on some
keyword in the file name.
|
Ubuntu: Can't setup virtualenv for python
Question: I'm using Ubuntu. I tried to follow the [Deploying a Django on Amazon Elastic
Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Python_django.html).
Rather than using `yum`, i used `apt-get` instead.
I followed every ahead steps well.
root@james-MacBookPro:/home/james# virtualenv --version
1.7.2
root@james-MacBookPro:/home/james# python --version
Python 2.7.6
root@james-MacBookPro:/home/james# apt-get install python-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
root@james-MacBookPro:/home/james# apt-get install python2.7-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
python2.7-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
But when i tried to create a virtual environment for django development, some
things wrong. I typed `virtualenv -p python2.6 /tmp/djangodev`
root@james-MacBookPro:/home/james# virtualenv -p python2.7 /tmp/djangodev
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /tmp/djangodev/bin/python2.7
Not overwriting existing python script /tmp/djangodev/bin/python (you must use /tmp/djangodev/bin/python2.7)
Installing setuptools...................................
Complete output from command /tmp/djangodev/bin/python2.7 -c "#!python
\"\"\"Bootstra...sys.argv[1:])
" /usr/local/lib/pytho...ols-0.6c11-py2.7.egg:
Traceback (most recent call last):
File "<string>", line 279, in <module>
File "<string>", line 240, in main
File "/usr/local/lib/python2.7/dist-packages/virtualenv_support/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1712, in main
File "/usr/local/lib/python2.7/dist-packages/virtualenv_support/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1700, in with_ei_usage
File "/usr/local/lib/python2.7/dist-packages/virtualenv_support/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1716, in <lambda>
File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 971, in run_command
cmd_obj.ensure_finalized()
File "/usr/lib/python2.7/distutils/cmd.py", line 109, in ensure_finalized
self.finalize_options()
File "/usr/local/lib/python2.7/dist-packages/virtualenv_support/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 125, in finalize_options
File "/usr/local/lib/python2.7/dist-packages/virtualenv_support/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1121, in _expand
File "/usr/lib/python2.7/distutils/cmd.py", line 312, in get_finalized_command
cmd_obj.ensure_finalized()
File "/usr/lib/python2.7/distutils/cmd.py", line 109, in ensure_finalized
self.finalize_options()
File "/usr/local/lib/python2.7/dist-packages/virtualenv_support/setuptools-0.6c11-py2.7.egg/setuptools/command/install.py", line 32, in finalize_options
File "/usr/lib/python2.7/distutils/command/install.py", line 321, in finalize_options
(prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
File "/tmp/djangodev/lib/python2.7/distutils/__init__.py", line 85, in sysconfig_get_config_vars
real_vars = old_get_config_vars(*args)
File "/usr/lib/python2.7/distutils/sysconfig.py", line 495, in get_config_vars
func()
File "/usr/lib/python2.7/distutils/sysconfig.py", line 439, in _init_posix
from _sysconfigdata import build_time_vars
File "/usr/lib/python2.7/_sysconfigdata.py", line 6, in <module>
from _sysconfigdata_nd import *
ImportError: No module named _sysconfigdata_nd
----------------------------------------
...Installing setuptools...done.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 2429, in <module>
main()
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 942, in main
never_download=options.never_download)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1052, create_environment
search_dirs=search_dirs, never_download=never_download)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 598, in install_setuptools
search_dirs=search_dirs, never_download=never_download)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 570, in _install_req
cwd=cwd)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1020, in call_subprocess
% (cmd_desc, proc.returncode))
OSError: Command /tmp/djangodev/bin/python2.7 -c "#!python
\"\"\"Bootstra...sys.argv[1:])
" /usr/local/lib/pytho...ols-0.6c11-py2.7.egg failed with error code 1
Can someone tell me what's wrong and how to fix it?
Answer: This is caused by a known
[bug](https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/1115466) in
Ubuntu.
Fix this creating a softlink of module `_sysconfigdata_nd.py` in `python2.7`
dir:
cd /usr/lib/python2.7
sudo ln -s plat-x86_64-linux-gnu/_sysconfigdata_nd.py .
(or use
sudo ln -s plat-i386-linux-gnu/_sysconfigdata_nd.py .
if you are on an i386 system)
|
How can I get and process a new S3 file for every iteration of an mrjob mapper?
Question: I have a log file of status_changes, each one of which has a driver_id,
timestamp, and duration. Using driver_id and timestamp, I want to fetch the
appropriate GPS log from S3. These GPS logs are stored in an S3 bucket in the
form bucket_name/yyyy/mm/dd/driver_id.log.
from mrjob.job import MRJob
class Mileage(MRJob):
def get_s3_gpslog_path(self, driver_id, occurred_at, status):
s3_path = "s3://gps_logs/{yyyy}/{mm}/{dd}/{driver_id}.log"
s3_path = s3_path.format(yyyy=occurred_at.year,
mm=occurred_at.month,
dd=occurred_at.day,
driver_id=driver_id)
return s3_path
def mapper(self, _, line):
line = ast.literal_eval(line)
driver_id = line['driverId']
occurred_at = line['timestamp']
status = line['status']
s3_path = self.get_s3_gpslog_path(driver_id, occurred_at, status)
# ^^ How do I fetch this file and read it?
distance = calculate_distance_from_gps_log(s3_path, occurred_at, status)
yield status, distance
if __name__ == '__main__':
Mileage.run()
And from the command line I run it with the status_change log file as input: $
python mileage.py status_changes.log
My question is: How do I actually fetch that GPS log, given the S3 URI string
I have constructed?
Answer: You can use [S3Filesystem](https://pythonhosted.org/mrjob/runners-
emr.html#s3-utilities) that is part of mrjob. You may also use
[boto](http://docs.pythonboto.org/en/latest/)'s S3 utility within your script.
You will likely need to hardcode (or parse from Hadoop configuration in each
node) the (secret) access key. However, what the mapper is doing may be a bit
too much, potentially making excessive requests to get S3 resources. You might
be able to rewrite the MapReduce algorithm to do the join in a less resource-
intensive way by streaming in the GPS logs along with the other logs.
|
Errors while installing matplotlib on OS X 10.8
Question: I am trying to install matplotlib on my machine with OS X 10.8 and XCode
5.0.2. I get these weird errors of which I am not able to make sense. I used
`pip install matplotlib` to install the package, but then it returns the
following errors at the end. I am clueless on what to do. Please help me
proceed. I tried to install scipy through the same process and the same error
stream prevails.
building 'rootfind' library
compiling C sources
C compiler: clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe
creating build/temp.macosx-10.8-intel-2.7/scipy/optimize/Zeros
compile options: '-I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -c'
clang: scipy/optimize/Zeros/bisect.c
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: Command "clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -c scipy/optimize/Zeros/bisect.c -o build/temp.macosx-10.8-intel-2.7/scipy/optimize/Zeros/bisect.o" failed with exit status 1
----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/v3/xf03tznj5hn9mj7j_4jbkvw40000gn/T/pip_build_Siva/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/v3/xf03tznj5hn9mj7j_4jbkvw40000gn/T/pip-u0HK_Y-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/v3/xf03tznj5hn9mj7j_4jbkvw40000gn/T/pip_build_Siva/scipy
After this I set the `ARCHFLAGS` variable to the following
export ARCHFLAGS='-Wno-error=unused-command-line-argument-hard-error-in-future'
Although the installatoion proceeds a bit further, I get an error stream at a
different point now.
running build_ext
building 'matplotlib.ft2font' extension
creating build/temp.macosx-10.8-intel-2.7
creating build/temp.macosx-10.8-intel-2.7/src
creating build/temp.macosx-10.8-intel-2.7/CXX
clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -DPY_ARRAY_UNIQUE_SYMBOL=MPL_matplotlib_ft2font_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -I/usr/local/include -I/usr/include -I. -I/usr/local/Cellar/freetype/2.5.3_1/include/freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/ft2font.cpp -o build/temp.macosx-10.8-intel-2.7/src/ft2font.o
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'clang' failed with exit status 1
----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/matplotlib/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ZU81yE-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/matplotlib
Answer: That's a common problem, the last macos updates make clang generate errors
instead of warnings for unknown compiler options. As a temporary workaround
you could set ARCHFLAGS environment variable, before running pip:
export ARCHFLAGS='-Wno-error=unused-command-line-argument-hard-error-in-future'
|
Get variables from the GUI in program
Question: first, sorry for my english - im still learning. I´m a student from Germany
and i learn Python.
I have a program which needs a lot of paramters for running so i build a gui
by wxGlade. Now i want to get this paramters in my application. I saw some
things. They used the GUI for editing a INI- File. And the application gets
the paramters from these INI. But this is not what i want. I want to controll
my application with the GUI. And it is very Important that i can save my
Values in the GUI (so that the User should not do everything again).
Hope you understand what i mean. Here is my Code for the Gui (not ready but it
is enough for doing the first steps)
Here is my GUI Code:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.6.8 (standalone edition) on Thu Apr 24 12:36:34 2014
#
import wx
# begin wxGlade: dependencies
import gettext
# end wxGlade
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
# Menu Bar
self.frame_3_menubar = wx.MenuBar()
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(wx.ID_ANY, _("Beenden"), "", wx.ITEM_NORMAL)
self.frame_3_menubar.Append(wxglade_tmp_menu, _("Datei"))
wxglade_tmp_menu = wx.Menu()
self.frame_3_menubar.Append(wxglade_tmp_menu, _("Bearbeiten"))
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(wx.ID_ANY, _("Dokumenationen"), "", wx.ITEM_NORMAL)
self.frame_3_menubar.Append(wxglade_tmp_menu, _("Hilfe"))
self.SetMenuBar(self.frame_3_menubar)
# Menu Bar end
self.frame_3_statusbarr = self.CreateStatusBar(1, 0)
self.kartei = wx.Notebook(self, wx.ID_ANY, style=0)
self.pane_all_settings = wx.Panel(self.kartei, wx.ID_ANY)
self.label_5 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Laufzeiteinstellungen"))
self.label_6 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Abrechnungsjahr"))
self.abr_jahr = wx.SpinCtrl(self.pane_all_settings, wx.ID_ANY, "", min=2000, max=2099, style=wx.SP_ARROW_KEYS | wx.TE_AUTO_URL)
self.label_7 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Abrechnungmonat"))
self.abr_monat = wx.SpinCtrl(self.pane_all_settings, wx.ID_ANY, "", min=1, max=12)
self.label_8 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Payroll"))
self.payroll = wx.ComboBox(self.pane_all_settings, wx.ID_ANY, choices=[_("Loga"), _("Sage"), _("SAP"), _("KidiCap"), _("fidelis Personal")], style=wx.CB_DROPDOWN)
self.label_1 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Mandant"))
self.mandant = wx.SpinCtrl(self.pane_all_settings, wx.ID_ANY, "1", min=0, max=999, style=wx.SP_ARROW_KEYS | wx.TE_AUTO_URL)
self.zuschlag = wx.CheckBox(self.pane_all_settings, wx.ID_ANY, _(u"Zuschl\xe4ge"))
self.fehlzeit = wx.CheckBox(self.pane_all_settings, wx.ID_ANY, _("Fehlzeiten"))
self.urlaub = wx.CheckBox(self.pane_all_settings, wx.ID_ANY, _(u"Urlaubsanspr\xfcche"))
self.soll = wx.CheckBox(self.pane_all_settings, wx.ID_ANY, _("Sollstunden"))
self.label_8_copy_1 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("ImpVar"))
self.dir_impvar = wx.TextCtrl(self.pane_all_settings, wx.ID_ANY, "")
self.label_8_copy_2 = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("ImpUbr"))
self.dir_impubr = wx.TextCtrl(self.pane_all_settings, wx.ID_ANY, "")
self.label_8_copy_1_copy = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Pfad zur ImpVar"))
self.dir_impvar_copy = wx.TextCtrl(self.pane_all_settings, wx.ID_ANY, "")
self.label_8_copy_1_copy_copy = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Pfad zur ImpUbr"))
self.dir_impvar_copy_1 = wx.TextCtrl(self.pane_all_settings, wx.ID_ANY, "")
self.label_8_copy_1_copy_copy_copy = wx.StaticText(self.pane_all_settings, wx.ID_ANY, _("Ausgabeverzeichnis"))
self.dir_impvar_copy_2 = wx.TextCtrl(self.pane_all_settings, wx.ID_ANY, "")
self.button_1 = wx.Button(self.pane_all_settings, wx.ID_ANY, _("Exportieren"))
self.button_1_copy = wx.Button(self.pane_all_settings, wx.ID_ANY, _("Abbrechen"))
self.pan_loga = wx.Panel(self.kartei, wx.ID_ANY)
self.label_5_copy = wx.StaticText(self.pan_loga, wx.ID_ANY, _("Exportieren nach Loga"))
self.label_6_copy = wx.StaticText(self.pan_loga, wx.ID_ANY, _("Loga-Mandant"))
self.loga_mandant = wx.SpinCtrl(self.pan_loga, wx.ID_ANY, "1", min=0, max=1000000, style=wx.SP_ARROW_KEYS | wx.TE_AUTO_URL)
self.label_7_copy = wx.StaticText(self.pan_loga, wx.ID_ANY, _("Loga-Abrechnungskreis"))
self.loga_al = wx.SpinCtrl(self.pan_loga, wx.ID_ANY, "", min=0, max=100)
self.label_8_copy = wx.StaticText(self.pan_loga, wx.ID_ANY, _("Empty"))
self.combo_box_1_copy = wx.ComboBox(self.pan_loga, wx.ID_ANY, choices=[], style=wx.CB_DROPDOWN)
self.label_1_copy = wx.StaticText(self.pan_loga, wx.ID_ANY, _(u"Personalnummer f\xfcllen"))
self.loga_fill_pnr = wx.SpinCtrl(self.pan_loga, wx.ID_ANY, "1", min=0, max=999, style=wx.SP_ARROW_KEYS | wx.TE_AUTO_URL)
self.konv_loa = wx.CheckBox(self.pan_loga, wx.ID_ANY, _("Konvertierungslohnart"))
self.konv_fehl = wx.CheckBox(self.pan_loga, wx.ID_ANY, _("Konvertierungsfehlzeiten"))
self.zeitraum_fehl = wx.CheckBox(self.pan_loga, wx.ID_ANY, _("Zeitraum Fehlzeit"))
self.vertragsnummer = wx.CheckBox(self.pan_loga, wx.ID_ANY, _(u"Vertragsnummer ber\xfccksichtigen"))
self.notebook_2_pane_3 = wx.Panel(self.kartei, wx.ID_ANY)
self.notebook_2_pane_4 = wx.Panel(self.kartei, wx.ID_ANY)
self.notebook_2_pane_5 = wx.Panel(self.kartei, wx.ID_ANY)
self.notebook_2_pane_6 = wx.Panel(self.kartei, wx.ID_ANY)
self.notebook_2_pane_7 = wx.Panel(self.kartei, wx.ID_ANY)
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_MENU, self.stopExport, id=wx.ID_ANY)
self.Bind(wx.EVT_BUTTON, self.startExport, self.button_1)
self.Bind(wx.EVT_BUTTON, self.stopExport, self.button_1_copy)
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle(_("TDA Export Manager 0.12"))
self.frame_3_statusbarr.SetStatusWidths([-1])
# statusbar fields
frame_3_statusbarr_fields = [_("(C) TDA-HR-Software Entwicklungs GmbH")]
for i in range(len(frame_3_statusbarr_fields)):
self.frame_3_statusbarr.SetStatusText(frame_3_statusbarr_fields[i], i)
self.payroll.SetSelection(-1)
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
grid_sizer_2_copy = wx.FlexGridSizer(10, 4, 0, 0)
grid_sizer_2 = wx.FlexGridSizer(10, 4, 0, 0)
grid_sizer_2.Add(self.label_5, 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_6, 0, wx.ALL, 10)
grid_sizer_2.Add(self.abr_jahr, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_7, 0, wx.ALL, 10)
grid_sizer_2.Add(self.abr_monat, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_8, 0, wx.ALL, 10)
grid_sizer_2.Add(self.payroll, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_1, 0, wx.ALL, 10)
grid_sizer_2.Add(self.mandant, 0, wx.ALL, 10)
grid_sizer_2.Add(self.zuschlag, 0, wx.ALL, 10)
grid_sizer_2.Add(self.fehlzeit, 0, wx.ALL, 10)
grid_sizer_2.Add(self.urlaub, 0, wx.ALL, 10)
grid_sizer_2.Add(self.soll, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_8_copy_1, 0, wx.ALL, 10)
grid_sizer_2.Add(self.dir_impvar, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_8_copy_2, 0, wx.ALL, 10)
grid_sizer_2.Add(self.dir_impubr, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_8_copy_1_copy, 0, wx.ALL, 10)
grid_sizer_2.Add(self.dir_impvar_copy, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_8_copy_1_copy_copy, 0, wx.ALL, 10)
grid_sizer_2.Add(self.dir_impvar_copy_1, 0, wx.ALL, 10)
grid_sizer_2.Add(self.label_8_copy_1_copy_copy_copy, 0, wx.ALL, 10)
grid_sizer_2.Add(self.dir_impvar_copy_2, 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2.Add(self.button_1, 0, wx.ALL, 10)
grid_sizer_2.Add(self.button_1_copy, 0, wx.ALL, 10)
self.pane_all_settings.SetSizer(grid_sizer_2)
grid_sizer_2_copy.Add(self.label_5_copy, 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.label_6_copy, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.loga_mandant, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.label_7_copy, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.loga_al, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.label_8_copy, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.combo_box_1_copy, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.label_1_copy, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.loga_fill_pnr, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.konv_loa, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.konv_fehl, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.zeitraum_fehl, 0, wx.ALL, 10)
grid_sizer_2_copy.Add(self.vertragsnummer, 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
grid_sizer_2_copy.Add((20, 20), 0, wx.ALL, 10)
self.pan_loga.SetSizer(grid_sizer_2_copy)
self.kartei.AddPage(self.pane_all_settings, _("Allgemeine Einstellungen"))
self.kartei.AddPage(self.pan_loga, _("Loga"))
self.kartei.AddPage(self.notebook_2_pane_3, _("Sage"))
self.kartei.AddPage(self.notebook_2_pane_4, _("SAP"))
self.kartei.AddPage(self.notebook_2_pane_5, _("KidiCap"))
self.kartei.AddPage(self.notebook_2_pane_6, _("fidelis Personal"))
self.kartei.AddPage(self.notebook_2_pane_7, _("Konvertierungsfehlzeiten"))
sizer_2.Add(self.kartei, 1, wx.EXPAND, 0)
self.SetSizer(sizer_2)
sizer_2.Fit(self)
self.Layout()
# end wxGlade
def startExport(self, event): # wxGlade: MyFrame.<event_handler>
abrjahr = self.abr_jahr.GetValue()
print abrjahr
def stopExport(self, event): # wxGlade: MyFrame.<event_handler>
self.Close()
# end of class MyFrame
if __name__ == "__main__":
gettext.install("app") # replace with the appropriate catalog name
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_3 = MyFrame(None, wx.ID_ANY, "")
app.SetTopWindow(frame_3)
frame_3.Show()
app.MainLoop()
Answer: I would suggest you do the following:
* Use a dictionary to receive all the initial values. Let the names in the dictionary map to the names of your variables.
* Allow other modules to subscribe to this GUI using the [Observer Pattern](https://en.wikipedia.org/wiki/Observer_pattern).
* When anything changes, or when the buttons are pressed, create a dictionary with the changes and notify all subscribers of the change.
This keeps the GUI cleanly separated from the rest of the program.
|
Guessing the date format python
Question: I am writing a method in a Python module which tries to make live easier to
the users. This method implements the creation of events in that calendar.
def update_event(start_datetime=None, end_datetime=None, description=None):
'''
Args:
start_date: string datetime in the format YYYY-MM-DD or in RFC 3339
end_date: string datetime in the format YYYY-MM-DD or in RFC 3339
description: string with description (\n are transforrmed into new lines)
'''
If the user specifies the start_date or the end_date a check up should be made
in order to determine if the date is in YYYY-MM-DD format or in the datetime
RFC 3339 format.
if (start_date is not None):
# Check whether we have an date or datetime value
# Whole day events are represented as YYYY-MM-DD
# Other events are represented as 2014-04-25T10:47:00.000-07:00
whole_day_event = False
try:
new_start_time = datetime.datetime.strptime(start_date,'YYYY-MM-DD')
# Here the event date is updated
try:
new_start_time = datetime.datetime.strptime(start_date,'%Y-%m-%dT%H:%M:%S%z')
#Here the event date is updated
except ValueError:
return (ErrorCodeWhatever)
except ValueError:
return (ErrorCodeWhatever)
Is this a good way of doing this? Can I check what kind of date I am receiving
in a nicer way? Thanks!
Answer: [`dateutil.parser.parse`](https://labix.org/python-dateutil) can be used to
attempt to parse strings into `datetime` objects for you.
from dateutil.parser import parse
def update_event(start_datetime=None, end_datetime=None, description=None):
if start_datetime is not None:
new_start_time = parse(start_datetime)
return new_start_time
d = ['23/04/2014', '24-04-2013', '25th April 2014']
new = [update_event(i) for i in d]
for date in new:
print(date)
# 2014-04-23 00:00:00
# 2013-04-24 00:00:00
# 2014-04-25 00:00:00
|
Loopback ('What u hear') recording in Python using PyAudio
Question: Good day,
I'm trying to record my speaker output with Python using PyAudio. Currently,
I'm able to record my microphone input and send this over to the 'listener'.
What I'm trying to do now is create a loopback, so it will record the output
from my speakers. I was able to do this with the 'Stereo Mix' from windows,
but since this needs to be cross platform, there should be another way to do
this.
Does anyone has some advice on how I could achieve this?
Here is my current code for recording an input stream.
import socket
import pyaudio
import wave
#record
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 40
HOST = '192.168.0.122' # The remote host
PORT = 50007 # The same port as used by the server
recording = True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
p = pyaudio.PyAudio()
for i in range(0, p.get_device_count()):
print(i, p.get_device_info_by_index(i)['name'])
device_index = int(input('Device index: '))
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=device_index)
print("*recording")
frames = []
while recording:
data = stream.read(CHUNK)
frames.append(data)
s.sendall(data)
print("*done recording")
stream.stop_stream()
stream.close()
p.terminate()
s.close()
print("*closed")
Any help would be greatly appreciated!
Answer: EDIT: I didn't see the cross-platform thing. Leaving this as a reference to
the loopback device for Windows.
Install a virtual loopback device like [1] and select the adapter as your
input device. That works for me very well.
You can check that with pyAudio like so:
>>> print p.get_device_count()
8
>>> print p.get_device_info_by_index(1)["name"]
Line 1 (Virtual Audio Cable)
So, I use 1 as my device_index.
[1] <http://virtual-audio-cable.en.softonic.com/>
|
Averaging out sections of a multiple row array in Python
Question: I've got a 2-row array called C like this:
from numpy import *
A = [1,2,3,4,5]
B = [50,40,30,20,10]
C = vstack((A,B))
I want to take all the columns in C where the value in the first row falls
between i and i+2, and average them. I can do this with just A no problem:
i = 0
A_avg = []
while(i<6):
selection = A[logical_and(A >= i, A < i+2)]
A_avg.append(mean(selection))
i += 2
then A_avg is:
[1.0,2.5,4.5]
I want to carry out the same process with my two-row array C, but I want to
take the average of each row separately, while doing it in a way that's
dictated by the first row. For example, for C, I want to end up with a 2 x 3
array that looks like:
[[1.0,2.5,4.5],
[50,35,15]]
Where the first row is A averaged in blocks between i and i+2 as before, and
the second row is B averaged in the same blocks as A, regardless of the values
it has. So the first entry is unchanged, the next two get averaged together,
and the next two get averaged together, for each row separately. Anyone know
of a clever way to do this? Many thanks!
Answer: I hope this is not too clever. TIL boolean indexing does not broadcast, so I
had to manually do the broadcasting. Let me know if anything is unclear.
import numpy as np
A = [1,2,3,4,5]
B = [50,40,30,20,10]
C = np.vstack((A,B)) # float so that I can use np.nan
i = np.arange(0, 6, 2)[:, None]
selections = np.logical_and(A >= i, A < i+2)[None]
D, selections = np.broadcast_arrays(C[:, None], selections)
D = D.astype(float) # allows use of nan, and makes a copy to prevent repeated behavior
D[~selections] = np.nan # exclude these elements from mean
D = np.nanmean(D, axis=-1)
Then,
>>> D
array([[ 1. , 2.5, 4.5],
[ 50. , 35. , 15. ]])
Another way, using `np.histogram` to bin your data. This may be faster for
large arrays, but is only useful for few rows, since a hist must be done with
different weights for each row:
bins = np.arange(0, 7, 2) # include the end
n = np.histogram(A, bins)[0] # number of columns in each bin
a_mean = np.histogram(A, bins, weights=A)[0]/n
b_mean = np.histogram(A, bins, weights=B)[0]/n
D = np.vstack([a_mean, b_mean])
|
Google App engine python writing csv in arabic
Question: I am trying to write a CSV in Arabic script. I have encoded the string to
utf-8 and wrote it in the csv.
The problem is if I open the file in csv it shows strange characters like
`آلز سندويتش كاÙيه` however if I open the file in notepad++ it
shows the expected arabic text.
i checked notepad ++ and converted the encoding to utf-8 instead of utf-8
without BOM , now its working fine in csv reader(excel) too. so what should i
do to set encoding to "utf-8 with BOM" in app engine
i am using unicodecsv.writer to write the csv
writer = unicodecsv.writer(self.response.out)
row = []
row.append(transaction.name.encode('utf8'))
writer.writerow(row)
the data to be written is taken from the datastore
Answer: To write a CSV with UTF-8 BOM, simply write the BOM first; you can use
[`codecs.BOM_UTF8`](https://docs.python.org/2/library/codecs.html#codecs.BOM_UTF8)
for that:
import codecs
self.response.out.write(codecs.BOM_UTF8)
writer = csv.writer(self.response.out)
row = []
row.append(transaction.name.encode('utf8'))
writer.writerow(row)
[Excel 2007 and newer](http://stackoverflow.com/questions/155097/microsoft-
excel-mangles-diacritics-in-csv-files) pick up on the BOM and correctly open
such a CSV file with UTF-8. Silly Microsoft!
|
Bool object is not callable in python connect for game ( is in the return line of def isWinner(bo, le):)
Question: # Tic Tac Toe
this is the beginning of the code for reference possibly this is the board
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print"| "+board[1]+" | "+board[2]+" | "+board[3]+" | "+board[4]+" | "+board[5]+" | "+board[6]+" | "+board[7]+" | "
print"|___|___|___|___|___|___|___|"
print"| "+board[8]+" | "+board[9]+" | "+board[10]+" | "+board[11]+" | "+board[12]+" | "+board[13]+" | "+board[14]+" | "
print"|___|___|___|___|___|___|___|"
print"| "+board[15]+" | "+board[16]+" | "+board[17]+" | "+board[18]+" | "+board[19]+" | "+board[20]+" | "+board[21]+" | "
print"|___|___|___|___|___|___|___|"
print"| "+board[22]+" | "+board[23]+" | "+board[24]+" | "+board[25]+" | "+board[26]+" | "+board[27]+" | "+board[28]+" | "
print"|___|___|___|___|___|___|___|"
print"| "+board[29]+" | "+board[30]+" | "+board[31]+" | "+board[32]+" | "+board[33]+" | "+board[34]+" | "+board[35]+" | "
print"|___|___|___|___|___|___|___|"
print"| "+board[36]+" | "+board[37]+" | "+board[38]+" | "+board[39]+" | "+board[40]+" | "+board[41]+" | "+board[42]+" | "
print"|___|___|___|___|___|___|___|"
inputs for X or O
def inputPlayerLetter():
# Let's the player type which letter they want to be.
# Returns a list with the player's letter as the first item, and the computer's letter as the second.
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input('Do you want to be X or O?').upper()
gives computer other letter
# the first element in the tuple is the player's letter, the second is the computer's letter.
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
randomly chooses who goes first.
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
play again
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input('Do you want to play again? (yes or no)').lower().startswith('y')
def makeMove(board, letter, move):
board[move] = letter
right here is the problem on the return line this is used to match up 4
winning spaces along the board made earlier
def isWinner(bo, le):
# Given a board and a player's letter, this function returns True if that player has won.
# We use bo instead of board and le instead of letter so we don't have to type as much.
return ((bo[1] == le and bo[2] == le and bo[3] == le and bo[4] == le) or # top row 1
(bo[2] == le and bo[3] == le and bo[4] == le and bo[5] == le) or # top row 2
(bo[3] == le and bo[4] == le and bo[5] == le and bo[6] == le) or # top row 3
(bo[4] == le and bo[5] == le and bo[6] == le and bo[7] == le) or # top row 4
(bo[8] == le and bo[9] == le and bo[10] == le and bo[11] == le) or # 2nd row 1
(bo[9] == le and bo[10] == le and bo[11] == le and bo[12] == le) or # 2nd row 2
(bo[10] == le and bo[11] == le and bo[12] == le and bo[13] == le) or # 2nd row 3
(bo[11] == le and bo[12] == le and bo[13] == le and bo[14] == le) # 2nd row 4
(bo[15] == le and bo[16] == le and bo[17] == le and bo[18] == le) or # 3rd row 1
(bo[16] == le and bo[17] == le and bo[18] == le and bo[19] == le) or # 3rd row 2
(bo[17] == le and bo[18] == le and bo[19] == le and bo[20] == le) or # 3rd row 3
(bo[18] == le and bo[19] == le and bo[20] == le and bo[21] == le) or # 3rd row 4
(bo[22] == le and bo[23] == le and bo[24] == le and bo[25] == le) or # 4th row 1
(bo[23] == le and bo[24] == le and bo[25] == le and bo[26] == le) or # 4th row 2
(bo[24] == le and bo[25] == le and bo[26] == le and bo[27] == le) or # 4th row 3
(bo[25] == le and bo[26] == le and bo[27] == le and bo[28] == le) or # 4th row 4
(bo[29] == le and bo[30] == le and bo[31] == le and bo[32] == le) or # 5th row 1
(bo[30] == le and bo[31] == le and bo[32] == le and bo[33] == le) or # 5th row 2
(bo[31] == le and bo[32] == le and bo[33] == le and bo[34] == le) or # 5th row 3
(bo[32] == le and bo[33] == le and bo[34] == le and bo[35] == le) or # 5th row 4
(bo[36] == le and bo[37] == le and bo[38] == le and bo[39] == le) or # 6th row 1
(bo[37] == le and bo[38] == le and bo[39] == le and bo[40] == le) or # 6th row 2
(bo[38] == le and bo[39] == le and bo[40] == le and bo[41] == le) or # 6th row 3
(bo[39] == le and bo[40] == le and bo[41] == le and bo[42] == le) or # 6th row 4
(bo[1] == le and bo[8] == le and bo[15] == le and bo[22] == le) or # 1st row 1
(bo[8] == le and bo[15] == le and bo[22] == le and bo[29] == le) or # 1st row 2
(bo[15] == le and bo[22] == le and bo[29] == le and bo[36] == le) or # 1st row 3
(bo[2] == le and bo[9] == le and bo[16] == le and bo[23] == le) or # 2st row 1
(bo[9] == le and bo[16] == le and bo[23] == le and bo[28] == le) or # 2st row 2
(bo[16] == le and bo[23] == le and bo[28] == le and bo[35] == le) or # 2st row 3
(bo[3] == le and bo[10] == le and bo[17] == le and bo[24] == le) or # 3th row 1
(bo[10] == le and bo[17] == le and bo[24] == le and bo[31] == le) or # 3th row 2
(bo[17] == le and bo[24] == le and bo[31] == le and bo[38] == le) or # 3th row 3
(bo[4] == le and bo[11] == le and bo[18] == le and bo[25] == le) or # 4th row 1
(bo[11] == le and bo[18] == le and bo[25] == le and bo[32] == le) or # 4th row 2
(bo[18] == le and bo[25] == le and bo[32] == le and bo[39] == le) or # 4th row 3
(bo[5] == le and bo[12] == le and bo[19] == le and bo[26] == le) or # 5th row 1
(bo[12] == le and bo[19] == le and bo[26] == le and bo[33] == le) or # 5th row 2
(bo[19] == le and bo[26] == le and bo[33] == le and bo[40] == le) or # 5th row 3
(bo[6] == le and bo[13] == le and bo[20] == le and bo[27] == le) or # 6th row 1
(bo[13] == le and bo[20] == le and bo[27] == le and bo[34] == le) or # 6th row 2
(bo[20] == le and bo[27] == le and bo[34] == le and bo[41] == le) or # 6th row 3
(bo[7] == le and bo[14] == le and bo[21] == le and bo[28] == le) or # 7th row 1
(bo[14] == le and bo[21] == le and bo[28] == le and bo[35] == le) or # 7th row 2
(bo[21] == le and bo[28] == le and bo[35] == le and bo[42] == le) or # 7th row 3
(bo[1] == le and bo[9] == le and bo[17] == le and bo[25] == le) or # diagonal 1 (1)(9)(17)(25)
(bo[8] == le and bo[16] == le and bo[24] == le and bo[32] == le) or # diagonal 2 (8)(16)(24)(32)
(bo[15] == le and bo[23] == le and bo[31] == le and bo[39] == le) or # diagonal 3 (15)(23)(31)(39)
(bo[2] == le and bo[10] == le and bo[18] == le and bo[26] == le) or # diagonal 4 (2)(10)(18)(26)
(bo[9] == le and bo[17] == le and bo[25] == le and bo[33] == le) or # diagonal 5 (9)(17)(25)(33)
(bo[16] == le and bo[24] == le and bo[32] == le and bo[40] == le) or # diagonal 6 (16)(24)(32)(40)
(bo[3] == le and bo[11] == le and bo[19] == le and bo[27] == le) or # diagonal 7 (3)(11)(19)(27)
(bo[10] == le and bo[18] == le and bo[26] == le and bo[34] == le) or # diagonal 8 (10)(18)(26)(34)
(bo[17] == le and bo[25] == le and bo[33] == le and bo[41] == le) or # diagonal 9 (17)(25)(33)(41)
(bo[4] == le and bo[12] == le and bo[20] == le and bo[28] == le) or # diagonal 10 (4)(12)(20)(28)
(bo[11] == le and bo[19] == le and bo[27] == le and bo[35] == le) or # diagonal 11 (11)(19)(27)(35)
(bo[18] == le and bo[26] == le and bo[34] == le and bo[42] == le) or # diagonal 12 (18)(26)(34)(42)
(bo[7] == le and bo[13] == le and bo[19] == le and bo[25] == le) or # diagonal 13 (7)(13)(19)(25)
(bo[14] == le and bo[20] == le and bo[26] == le and bo[32] == le) or # diagonal 14 (14)(20)(26)(32)
(bo[21] == le and bo[27] == le and bo[33] == le and bo[39] == le) or # diagonal 15 (21)(27)(33)(39)
(bo[6] == le and bo[12] == le and bo[18] == le and bo[26] == le) or # diagonal 16 (6)(12)(18)(26)
(bo[13] == le and bo[19] == le and bo[25] == le and bo[31] == le) or # diagonal 17 (13)(19)(25)(31)
(bo[20] == le and bo[26] == le and bo[32] == le and bo[38] == le) or # diagonal 18 (20)(26)(32)(38)
(bo[5] == le and bo[11] == le and bo[17] == le and bo[23] == le) or # diagonal 19 (5)(11)(17)(23)
(bo[12] == le and bo[18] == le and bo[24] == le and bo[30] == le) or # diagonal 20 (12)(18)(24)(30)
(bo[19] == le and bo[25] == le and bo[31] == le and bo[37] == le) or # diagonal 21 (19)(25)(31)(37)
(bo[4] == le and bo[10] == le and bo[16] == le and bo[22] == le) or # diagonal 22 (4)(10)(16)(22)
(bo[11] == le and bo[17] == le and bo[23] == le and bo[29] == le) or # diagonal 23 (11)(17)(23)(29)
(bo[18] == le and bo[24] == le and bo[30] == le and bo[36] == le)) # diagonal 24 (18)(24)(30)(36)
#
Answer:
(bo[11] == le and bo[12] == le and bo[13] == le and bo[14] == le) # 2nd row 4
You missed an `or` at the end of this line.
|
Django: syncdb not able to add any model in data base
Question: I'm new with Django and I'm not able to add any model to my DB?? Ok,this is
the Portfolio model :
from django.db import models
from core.models import Unit
# Create your models here.
class Portfolio(models.Model):
"""
Generic class to portfolios
"""
name = models.CharField(_('Name'), max_length=255)
youtube_id = models.CharField(_('Youtube_id'), max_length=255)
url_doc = models.CharField(_('Url_doc'), max_length=255)
data = models.TextField()
unit = models.ForeignKey(Unit, verbose_name=_('Unit'), null=True, blank=True, related_name='portfolios')
comment = models.TextField(_('Comment'), blank=True)
class Meta:
verbose_name = _('Portfolio')
verbose_name_plural = _('Portfolios')
ordering = [('id')]
abstract = True
def __unicode__(self):
return u'%s' % (self.name)
and this is the result of **python manage.py syncdb** :
Syncing...
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
all is alright but the table isn't created !!!!
and this is the setting.py file :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'timtec.sqlite', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '',
# Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '',
# Set to empty string for default.
}
}
INSTALLED_APPS = (
'django_extensions',
'south',
'pipeline',
'suit',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'rest_framework',
'rosetta',
'autoslug',
'core',
'accounts',
'activities',
'administration',
'forum',
'course_material',
'notes',
'reports',
'portfolio',
'metron',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'django_markdown',
# raven has to be the last one
'raven.contrib.django.raven_compat',
)
thanks :)
Answer: Django won't generate database tables for models which are Abstract. You
should inherit from abstract class or simply remove `abstract = True` line in
Meta class.
|
Importing module functions from python packages
Question: I saw the command listed as below for `sklearn.tree.tree`
from ._tree import Criterion, Splitter, Tree
from . import _tree
Yet in the same tree folder I cannot find any file or class named `_tree`. Can
anyone tell me where exactly I can find this class?
Answer: The module you are looking for is written in Cython. The corresponding file is
called `_tree.pyx`. It can be found in `.../scikit-
learn/sklearn/tree/_tree.pyx`, if you have the scikit learn sources, e.g. in
form of the git repo, on your computer.
Cython is translated to C code, which can be found in `_tree.c`.
The compiled C code is what is imported in the lines you found, and the
corresponding file is called `_tree.so`. In a typical scikit-learn
installation, this may be the only file you find. It is not human-readable, so
if you are interested in the source, check it out
[here](https://github.com/scikit-learn/scikit-
learn/blob/master/sklearn/tree/_tree.pyx)
|
optional python arguments without dashes but with additional parameters?
Question: what I'd like to do in Python is accept arguments of the following format:
script.py START | STOP | STATUS | MOVEABS <x> <y> | MOVEREL <x> <y>
So in other words,
1. I don't want to deal with hyphens;
2. I have multiple possibilities, ONE of which is required;
3. Each is mutually exclusive;
4. Some of the commands (E.G. moveabs and moverel) have additional required arguments, but these args and should not be present with any other argument.
Can this be done in python and would I use argparse or something else? Thanks.
Answer: Using `docopt` you can do this quite easily.
# Install `docopt` first:
$ pip install docopt
# Write the `script.py`:
"""
Usage:
script.py (start | stop | status | moveabs <x> <y> | moverel <x> <y>)
"""
from docopt import docopt
if __name__ == "__main__":
args = docopt(__doc__)
print args
# and run it:
first showing basic help:
$ python script.py
Usage:
script.py (start | stop | status | moveabs <x> <y> | moverel <x> <y>)
then try subcommands:
start
$ python script.py start
{'<x>': None,
'<y>': None,
'moveabs': False,
'moverel': False,
'start': True,
'status': False,
'stop': False}
stop
$ python script.py stop
{'<x>': None,
'<y>': None,
'moveabs': False,
'moverel': False,
'start': False,
'status': False,
'stop': True}
moveabs
$ python script.py moveabs 11 22
{'<x>': '11',
'<y>': '22',
'moveabs': True,
'moverel': False,
'start': False,
'status': False,
'stop': False}
moverel
$ python script.py moverel 11 22
{'<x>': '11',
'<y>': '22',
'moveabs': False,
'moverel': True,
'start': False,
'status': False,
'stop': False}
|
Do Python functions copy the input parameters to the function?
Question: I have the following example in Python:
import numpy as np
import timeit
# array size
m = 3000
# square array
a = np.random.rand(m, m)
# column vector
b = np.random.rand(m)
# solve
ti = timeit.default_timer()
x = np.linalg.solve(a, b)
tf = timeit.default_timer()
# solve function
def solver(a, b):
x = np.linalg.solve(a, b)
return x
tii = timeit.default_timer()
x = solver(a, b)
tff = timeit.default_timer()
print('time1 ', tf-ti)
print('time2 ', tff-tii)
The time comparison for not using a function (time1) vs using a function
(time2) is:
time1 0.6199771239989786
time2 0.5945519460001378
There seems to be a slight difference between in the two approaches. How are
the input parameters handled for the function `solver`, are they copied or are
they just passed to the internals of the function?
Answer: The speed difference is likely due to some memory caching of the contents of
`a` and `b` that the second call to `linalg.solve` takes advantage of.
And to answer the question, objects in python are passed by reference, so the
only differencein the cost of passing arguments is that you are doing it twice
in the 2nd example. But that is probably a tiny fraction of the solve cost.
|
asyncio - How can coroutines be used in signal handlers?
Question: I am developing an application that uses asyncio from python3.4 for
networking. When this application shuts down cleanly, a node needs to
"disconnect" from the hub. This disconnect is an active process that requires
a network connection so the loop needs to wait for this to complete before
shutting down.
My issue is that using a coroutine as a signal handler will result in the
application not shutting down. Please consider the following example:
import asyncio
import functools
import os
import signal
@asyncio.coroutine
def ask_exit(signame):
print("got signal %s: exit" % signame)
yield from asyncio.sleep(10.0)
loop.stop()
loop = asyncio.get_event_loop()
for signame in ('SIGINT', 'SIGTERM'):
loop.add_signal_handler(getattr(signal, signame),
functools.partial(ask_exit, signame))
print("Event loop running forever, press CTRL+c to interrupt.")
print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
loop.run_forever()
If you run this example and then press Ctrl+C, nothing will happen. The
question is, how do I make this behavior happen with siganls and coroutines?
Answer:
loop = asyncio.get_event_loop()
for signame in ('SIGINT', 'SIGTERM'):
loop.add_signal_handler(getattr(signal, signame),
asyncio.async, ask_exit(signame))
That way the signal causes your ask_exit to get scheduled in a task.
|
Changing of pixel values after writing the same image using imwrite opencv python function
Question:
import cv2
import numpy as np
im=cv2.imread('test.jpg')
cv2.imwrite('result.jpg',im)
Here test.jpg have size 19 KB and result.jpg have 41 KB even though they are
same images.
I observed that there is change in the pixel values of these two images.
How to prevent this one ?
Answer: Re-writing or 'saving' an image in any library or tool will always create a
new file or 'new pixel values'. This happens because the image is being
processed for saving at a certain quality. The saved image quality and size
depends on the library doing the save. So default values, depth, compression,
etc. need to be provided.
If you just want to create a copy of the image in a new file, either copy the
file directly via `sys` or binary read the whole file and write it to a new
one - without using any image processing libs.
|
Is print the only way to display something in .py file
Question: In the python command line, I can do
>>> a
array([ 0, 1, 3, 10, 1, 0, 0, 3, 6])
>>> print a
[ 0 1 3 10 1 0 0 3 6]
But in a .py file, I can only do print, but not directly 'a'. What if I want
to see the whole `array([ 0, 1, 3, 10, 1, 0, 0, 3, 6])`?
Answer: The interpreter usually shows what
[`repr(object)`](https://docs.python.org/library/functions.html#func-repr)
returns, so:
print repr(a)
Example:
In [1]: import numpy as np
In [2]: a = np.array([ 0, 1, 3, 10, 1, 0, 0, 3, 6])
In [3]: repr(a)
Out[3]: 'array([ 0, 1, 3, 10, 1, 0, 0, 3, 6])'
|
python matplotlib legend shows first entry of a list only
Question: I could not get all the legends to appear in matplotlib.
My Labels array is:
lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']
I use the below code to add the legend:
ax.legend(lab,loc="best")
Am seeing only 'Google' in top right corner. How to show all labels? 
Full code:
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle, islice
menMeans = (8092, 812, 2221, 1000, 562)
N = len(menMeans)
lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, N))
rects1 = ax.bar(ind, menMeans, width, color=my_colors,label=lab)
# add some
ax.set_ylabel('Count')
ax.set_title('Trending words and their counts')
ax.set_xticks(ind+width)
ax.legend(lab,loc="best")
plt.show()
Answer: Your problem is that you're only plotting once with a single `ax.bar` and as
such your legend can only have one item (for that one plot). One way to get
around this, for your plotting script, is to change the xticks and xticklabels
as shown below.
When you create a legend you create an entry for each `matplotlib.artist`
object that you have created through plotting. These objects could be a set of
data points, or a line, or a set of bars in a bar chart. It doesn't matter if
you have 5 or 10 bars in your bar chart as **you've still only plotted one bar
chart**. This means you will end up only having one entry in your legend.
I have used `ax.set_xticks(ind+width/2)` to place the tick positions directly
underneath your bars, I have then set these labels using your `lab` list with
`ax.set_xticklabels(lab)`.
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle, islice
import matplotlib.ticker as mtick
menMeans = (8092, 812, 2221, 1000, 562)
N = len(menMeans)
lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, N))
rects1 = ax.bar(ind, menMeans, width, color=my_colors,label=lab)
ax.set_ylabel('Count')
ax.set_title('Trending words and their counts')
plt.xticks(rotation=90)
ax.set_xticks(ind+width/2)
ax.set_xticklabels(lab)
plt.show()

|
2D-Array to tiled map PyGame, Python
Question: I have looked for similar questions, but I haven't found anything concrete
enough to actually apply to my situation.
Ok, so I've come up with something that will display the right amount of
images, in the right places, except for the Y axis. Basically, if I have
array:
[1,1,1,1,
0,0,0,0]
I would want it to display as something like:
####
@@@@
However, it display as this:
####@@@@
How do I iterate down in the rows, much more importantly, how do I detect a
row-continuation?
Answer: Posting on behalf of the OP who is new to the site and found the answer on
their own.
tileX = 0
tileY = 0
tile_dict = {0: pygame.image.load("C:\Users\Software Development\Desktop\Tile00.png"), 1: pygame.image.load("C:\Users\Software Development\Desktop\Tile01.png")}
map00 = [[0,0,0,0],
[1,1,1,1], [1,0,1,0]]
for x in map00:
for x in x:
if x == 0:
screen.blit(tile_dict[0], (tileX, tileY))
tileX = tileX+16
if x == 1:
screen.blit(tile_dict[1], (tileX, tileY))
tileX = tileX+16
tileX = 0
tileY += 16
|
Module Name Error
Question:
>>> import EpicMatrix
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import EpicMatrix
ImportError: No module named EpicMatrix
>>>
I have created this module and saved it as .py file but still python is not
able to recognise it
Answer: You need to add the path to the directory containing this file to the
PYTHONPATH environment variable.
PYTHONPATH is a list of directories to look at to load modules from. If the
module isn't in one of the directories in PYTHONPATH then python won't be able
to find it. That is what's happening here.
|
Fastest way to find nearest triangle number?
Question: In python I need a function that takes an integer and returns the absolute
value of n minus the nearest [triangle
number](http://en.wikipedia.org/wiki/Triangular_number) to n. The way I'm
doing it now is by generating a list of all the triangle numbers up to n. Then
using:
def closest(myList, myNumber):
c = min(myList, key=lambda x:abs(x-myNumber))
To find the closest triangle number.
The end result list should look like:
[0, 0, 1 , 0 , 1 ,1 , 0 , 1, 2 , 1, 0 , 1, 2, 2, 1, 0, etc.]
If you have another method of generating the same result that's faster go for
it.
Answer: A little bit of math will bring a more analytical solution:
from math import sqrt
def close_triangle2(n):
m=int(0.5*(-1+sqrt(1+8*n))) #solve it for the explicit formula
tan0=(m*m+m)/2 #the closest one is either this
tan1=(m*m+3*m+2)/2 #or this
if (n-tan0)>(tan1-n):
return tan1-n
else:
return n-tan0
It will become slightly faster than the loop version from @perreal when the
number is large:
In [87]:
%timeit close_triangle(111111111)
100000 loops, best of 3: 5 µs per loop
In [86]:
%timeit close_triangle2(111111111)
100000 loops, best of 3: 4.13 µs per loop
If you wonders:
In [94]:
close_triangle2((30**10 * (30**10+1)) / 2 + 100)
Out[94]:
100L
In [95]:
close_triangle((30**10 * (30**10+1)) / 2 + 100)
Out[95]:
100L
In [102]:
%timeit close_triangle((30**10 * (30**10+1)) / 2 + 100)
10000 loops, best of 3: 17.9 µs per loop
In [103]:
%timeit close_triangle2((30**10 * (30**10+1)) / 2 + 100)
100000 loops, best of 3: 12 µs per loop
|
Best way to have a python script copy itself?
Question: I am using python for scientific applications. I run simulations with various
parameters, my script outputs the data to an appropriate directory for that
parameter set. Later I use that data. However sometimes I edit my script; in
order to be able to reproduce my results if needed I would like to have a copy
of whatever version of the script was used to generate the data live right in
the directory with the data. So basically I would like to have my python
script copy itself to the data directory. What's the best way to do this?
Thanks!
Answer: Copying the script can be done with `shutil.copy()`.
But you should consider keeping your script under revision control. That
enables you to retain a revision history.
E.g. I keep my scripts under revision control with `git`. In Python files I
tend to keep a version string like this;
__version__ = '$Revision: a42ef58 $'[11:-2]
This version string is updated with the git short hash tag every time the file
in question is changed. (this is done by running a script called `update-
modified-keywords.py` from git's `post-commit` hook.)
If you have a version string like this, you can embed that in the output, so
you always know which version has produced the output.
**Edit** :
The update-modified-keywords script is shown below;
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Author: R.F. Smith <[email protected]>
# $Date: 2013-11-24 22:20:54 +0100 $
# $Revision: 3d4f750 $
#
# To the extent possible under law, Roland Smith has waived all copyright and
# related or neighboring rights to update-modified-keywords.py. This work is
# published from the Netherlands.
# See http://creativecommons.org/publicdomain/zero/1.0/
"""Remove and check out those files that that contain keywords and have
changed since in the last commit in the current working directory."""
from __future__ import print_function, division
import os
import mmap
import sys
import subprocess
def checkfor(args):
"""Make sure that a program necessary for using this script is
available.
Arguments:
args -- string or list of strings of commands. A single string may
not contain spaces.
"""
if isinstance(args, str):
if ' ' in args:
raise ValueError('No spaces in single command allowed.')
args = [args]
try:
with open(os.devnull, 'w') as bb:
subprocess.check_call(args, stdout=bb, stderr=bb)
except subprocess.CalledProcessError:
print("Required program '{}' not found! exiting.".format(args[0]))
sys.exit(1)
def modifiedfiles():
"""Find files that have been modified in the last commit.
:returns: A list of filenames.
"""
fnl = []
try:
args = ['git', 'diff-tree', 'HEAD~1', 'HEAD', '--name-only', '-r',
'--diff-filter=ACMRT']
with open(os.devnull, 'w') as bb:
fnl = subprocess.check_output(args, stderr=bb).splitlines()
# Deal with unmodified repositories
if len(fnl) == 1 and fnl[0] is 'clean':
return []
except subprocess.CalledProcessError as e:
if e.returncode == 128: # new repository
args = ['git', 'ls-files']
with open(os.devnull, 'w') as bb:
fnl = subprocess.check_output(args, stderr=bb).splitlines()
# Only return regular files.
fnl = [i for i in fnl if os.path.isfile(i)]
return fnl
def keywordfiles(fns):
"""Filter those files that have keywords in them
:fns: A list of filenames
:returns: A list for filenames for files that contain keywords.
"""
# These lines are encoded otherwise they would be mangled if this file
# is checked in my git repo!
datekw = 'JERhdGU='.decode('base64')
revkw = 'JFJldmlzaW9u'.decode('base64')
rv = []
for fn in fns:
with open(fn, 'rb') as f:
try:
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if mm.find(datekw) > -1 or mm.find(revkw) > -1:
rv.append(fn)
mm.close()
except ValueError:
pass
return rv
def main(args):
"""Main program.
:args: command line arguments
"""
# Check if git is available.
checkfor(['git', '--version'])
# Check if .git exists
if not os.access('.git', os.F_OK):
print('No .git directory found!')
sys.exit(1)
print('{}: Updating modified files.'.format(args[0]))
# Get modified files
files = modifiedfiles()
if not files:
print('{}: Nothing to do.'.format(args[0]))
sys.exit(0)
files.sort()
# Find files that have keywords in them
kwfn = keywordfiles(files)
for fn in kwfn:
os.remove(fn)
args = ['git', 'checkout', '-f'] + kwfn
subprocess.call(args)
if __name__ == '__main__':
main(sys.argv)
If you don't want keyword expansion to clutter up your git history, you can
use the _smudge_ and _clean_ filters. I have the following set in my
`~/.gitconfig`;
[filter "kw"]
clean = kwclean
smudge = kwset
Both kwclean and kwset are Python scripts.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: R.F. Smith <[email protected]>
# $Date: 2013-11-24 22:20:54 +0100 $
#
# To the extent possible under law, Roland Smith has waived all copyright and
# related or neighboring rights to kwset.py. This work is published from
# the Netherlands. See http://creativecommons.org/publicdomain/zero/1.0/
"""Fill the Date and Revision keywords from the latest git commit and tag and
subtitutes them in the standard input."""
import os
import sys
import subprocess
import re
def gitdate():
"""Get the date from the latest commit in ISO8601 format.
"""
args = ['git', 'log', '-1', '--date=iso']
dline = [l for l in subprocess.check_output(args).splitlines()
if l.startswith('Date')]
try:
dat = dline[0][5:].strip()
return ''.join(['$', 'Date: ', dat, ' $'])
except IndexError:
raise ValueError('Date not found in git output')
def gitrev():
"""Get the latest tag and use it as the revision number. This presumes the
habit of using numerical tags. Use the short hash if no tag available.
"""
args = ['git', 'describe', '--tags', '--always']
try:
with open(os.devnull, 'w') as bb:
r = subprocess.check_output(args, stderr=bb)[:-1]
except subprocess.CalledProcessError:
return ''.join(['$', 'Revision', '$'])
return ''.join(['$', 'Revision: ', r, ' $'])
def main():
"""Main program.
"""
dre = re.compile(''.join([r'\$', r'Date:?\$']))
rre = re.compile(''.join([r'\$', r'Revision:?\$']))
currp = os.getcwd()
if not os.path.exists(currp+'/.git'):
print >> sys.stderr, 'This directory is not controlled by git!'
sys.exit(1)
date = gitdate()
rev = gitrev()
for line in sys.stdin:
line = dre.sub(date, line)
print rre.sub(rev, line),
if __name__ == '__main__':
main()
and
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: R.F. Smith <[email protected]>
# $Date: 2013-11-24 22:20:54 +0100 $
#
# To the extent possible under law, Roland Smith has waived all copyright and
# related or neighboring rights to kwclean.py. This work is published from the
# Netherlands. See http://creativecommons.org/publicdomain/zero/1.0/
"""Remove the Date and Revision keyword contents from the standard input."""
import sys
import re
## This is the main program ##
if __name__ == '__main__':
dre = re.compile(''.join([r'\$', r'Date.*\$']))
drep = ''.join(['$', 'Date', '$'])
rre = re.compile(''.join([r'\$', r'Revision.*\$']))
rrep = ''.join(['$', 'Revision', '$'])
for line in sys.stdin:
line = dre.sub(drep, line)
print rre.sub(rrep, line),
Both of these scripts are installed (without an extension at the end of the
filename, as usual for executables) in a directory that is in my `$PATH`, and
have their executable bit set.
In the `.gitattributes` file of my repository I choose for which files I want
keyword expansion. So for e.g. Python files;
*.py filter=kw
|
Detecting collision in python and tkinter
Question: I have following setup: I have an archer who can shoot arrows, which are
always new instances of the class arrow and I have an instance of the class
blackMonster. My Question is whether it is even possible or not to detect
whether one of my arrow instances had a collision with this black monster
instance ? And when it is possible how is it made ? I used to think so often
and much about it, but I couldn't find a solution yet and it is getting really
frustrating. Here is my code... Please don't judge it too hard I am about to
work on it.
from Tkinter import *
from PIL import ImageTk, Image
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master, height=400, width=400)
self.master = master
self.master.bind('<Shift_L>', self.createArrow)
self.charImg = ImageTk.PhotoImage(Image.open("./Archer.gif"))
self.charLabel = Label(self, image = self.charImg)
self.charLabel.pack()
self.down = False
self.right = False
self.left = False
self.up = False
self.x_coord = 200
self.y_coord = 200
self.pack_propagate(0)
self.pack()
self.monster = blackMonster(self)
self.monster.createMonster(self.monster, 300, 300)
def createArrow(self, event):
self.arrow = Arrow(self)
self.arrow.moveArrow(self.arrow, self.x_coord, self.y_coord + 15)
def moveableImage(self):
self.charLabel.place(y=self.y_coord, x=self.x_coord)
def keyPressed(self, event):
if event.keysym == 'Down':
self.down = True
elif event.keysym == 'Right':
self.right = True
elif event.keysym == 'Left':
self.left = True
elif event.keysym == 'Up':
self.up = True
def keyReleased(self, event):
if event.keysym == 'Down':
self.down = False
elif event.keysym == 'Right':
self.right = False
elif event.keysym == 'Left':
self.left = False
elif event.keysym == 'Up':
self.up = False
def task(self):
if self.down and self.y_coord < 360:
self.y_coord += 10
elif self.right and self.x_coord < 370:
self.x_coord += 10
elif self.left and self.x_coord > 10:
self.x_coord -= 10
elif self.up and self.y_coord > 10:
self.y_coord -= 10
root.after(20,self.task)
self.moveableImage()
class Arrow(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.arrowImage = ImageTk.PhotoImage(Image.open("./arrow.gif"))
Label(self, image=self.arrowImage).pack()
self.damage = 20
def moveArrow(self, arrow, xCoord, yCoord):
arrow.place_forget()
arrow.place(x = xCoord, y = yCoord)
self.after(10, self.moveArrow, arrow, xCoord+5, yCoord)
class blackMonster(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.monsterImage = ImageTk.PhotoImage(Image.open("./monster.gif"))
Label(self, image=self.monsterImage).pack()
self.health = 100
def createMonster(self, monster, x_Coord, y_Coord):
monster.place(x = x_Coord, y = y_Coord)
root = Tk()
root.title("Frametitel")
app = App(master=root)
root.bind_all('<Key>', app.keyPressed)
root.bind_all('<KeyRelease>', app.keyReleased)
root.after(20, app.task)
app.mainloop()
Answer: You're using labels and place to represent the monster and arrow? The coding
would be much easier if you used a canvas rather than labels. The canvas has
methods to easily get the coordinates of objects that have been draw. Then
it's it's nothing more than a little math. You get the current coordinates of
the arrow, and you get the coordinates of the monster, then check if the
coordinate of the tip of the arrow is inside the space taken up by the
monster. You can get the coordinates of ana object using the
[bbox](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.bbox-method)
method.
|
Python Tkinter: Loop The Computer's Turn A Certain Amount of Times
Question: I'm writing a program for a dice game (Pig). In the game, the player will roll
a d6 until they decide to hold their score (passing to the computer) or until
they roll a 1, which will automatically make it the computer's turn.
The issue I'm having is that I need the function for the computer's turn to
loop ten times. I want the computer to roll the die ten times, where it will
either roll a one and pass back to the player or it will hold after ten rolls.
How do I get the computer to roll the die ten times without using a loop
inside of Tk?
Here's the code:
from Tkinter import *
from random import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.headerFont = ("courier new", "16", "bold")
self.title("Pig, The Dice Game")
self.headers()
self.rollDie()
def headers(self):
Label(self, text = "Instructions", font = self.headerFont).grid(columnspan = 4)
Label(self, text = "Text", font = self.headerFont).grid(row = 1, columnspan = 4)
Label(self).grid(row = 1, columnspan = 4)
Label(self, text = "The Game of Pig", font = self.headerFont).grid(row = 2, columnspan = 4)
def rollDie(self):
self.btnRoll = Button(self, text = "Roll The Die")
self.btnRoll["state"] = 'active'
self.btnRoll.grid(row = 3, columnspan = 4)
self.btnRoll["command"] = self.playerTurn
self.btnHold = Button(self, text = "Hold")
self.btnHold["state"]= 'active'
self.btnHold.grid(row = 4, columnspan = 4)
self.btnHold["command"] = self.compTurn
self.btnPass = Button(self, text = "Pass")
self.btnPass.grid(row = 5, columnspan = 4)
self.btnPass["command"] = self.compTurn
Label(self, text = "You Rolled:").grid(row = 6, column = 0)
self.lblYouRolled = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblYouRolled.grid(row = 6, column = 1, columnspan = 1, sticky = "we")
Label(self, text = "Options:").grid(row = 7, column = 0)
self.lblOptions = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblOptions.grid(row = 7, column = 1, sticky = "we")
Label(self, text = "Player One Turn Score:").grid(row = 8, column = 0)
self.lblPlayerOneTurnScore = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblPlayerOneTurnScore.grid(row = 8, column = 1, sticky = "we")
def playerTurn(self):
self.oneTurnTotal = [0]
self.oneRoll = randint(1,6)
self.btnHold["state"] = 'active'
self.lblYouRolled["text"] = self.oneRoll
if self.oneRoll != 1:
self.oneTurnTotal.append(self.oneRoll)
self.lblOptions["text"] = "Roll again, or hold and pass the dice to Player Two."
else:
self.lblOptions["text"] = "You rolled a 1! Click 'Pass' to pass your turn to the computer."
self.oneTurnTotal = [0]
self.btnRoll["state"] = 'disabled'
self.btnHold["state"] = 'disabled'
def calculatePlayerOneTurnScore(self):
turnScore = sum(self.oneTurnTotal)
self.lblPlayerOneTurnScore["text"] = turnScore
def compTurn(self):
self.compTurnTotal = [0]
self.compRoll = randint(1,6)
self.lblYouRolled["text"] = self.compRoll
if self.compRoll != 1:
self.compTurnTotal.append(self.compRoll)
self.lblOptions["text"] = "The computer will roll again."
else:
self.lblOptions["text"] = "The computer rolled a 1! Its turn has ended."
self.compTurnTotal = [0]
self.btnRoll["state"] = 'active'
def calculatePlayerTwoTurnScore(self):
turnScore = sum(self.twoTurnTotal)
self.lblPlayerTwoTurnScore["text"] = turnScore
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
Answer: You could make the dicerolling a toplevel widget and then have your root
"wait_window" for the rolling widget to complete. Create a function inside the
toplevel widget that generates the roll and call it ten times
EXAMPLE
from Tkinter import *
yourscorevalue=12
cpuscorevalue=10
class dice:
def __init__(self,parent):
rollcount=0
top=self.top=Toplevel(parent)
while 1:
roll=self.diceroll()
rollcount+=1
if rollcount==10 or roll==1:
break
def diceroll(self):
#Random Dice Roll code
class dicegame:
def __init__(self):
self.root=Tk()
self.root.title('Dicerolling Game')
Label(self.root, text='Your Score').grid(column=0,row=0,sticky='ew')
Label(self.root, text=yourscorevalue, background='black',foreground='red').grid(column=1,row=0,sticky='ew')
Label(self.root, text='Computer Score').grid(column=0,row=1,sticky='ew')
Label(self.root, text=cpuscorevalue, background='black',foreground='red').grid(column=1,row=1,sticky='ew')
b=Button(self.root, text='Roll The Dice', command=self.roll).grid(column=0,row=2,sticky='ew')
c=Button(self.root, text="Done", command=self.root.destroy).grid(column=1,row=2,sticky='ew')
mainloop()
def roll(self):
d=dice(self.root)
self.root.wait_window(d.top)
|
Is there any suggestions or standards of module dependency design of Python?
Question: Suppose all that need to be considered are only user defined functions and
system modules.
I've created 2 modules based on it's logical structure, then I'm not sure
what's next.
Say I put 10 functions in `fm1.py` and 8 functions in `fm2.py`. Functions in
both `fm1.py` and `fm2.py` would need some system modules `m1` and `m2`, as
long as some other user defined functions `f1()`, `f2()`.
What I do now is create another file `i1.py`, it imports system modules `m1`
and `m2` and the definition of `f1()` and `f2()` are also included in this
file. Then both `fm1.py` and `fm2.py` import `i1.py1` and finally a `main.py`
imports `fm1.py` and `fm2.py`.
I ran `main.py` and no error occurred, however, I wonder the way I designed
the dependency may not be the suggested way.
So, is there any suggestions or standards of module dependency design?
Answer: The correct way to do this would be to **pass** the functions `f1()` and
`f2()` to whatever function needs them in `fm1.py` and `fm2.py`. For example,
if you originally had something like
def length(a,b):
return metric(a,b)
where you defined `metric()` in `i1.py`. You could instead do it like
def length(a,b,metric):
return metric(a,b)
Then, if someone wanted to use the function they could import your module and
call it like this:
from foo import length
def metric(a,b):
return a[0]*b[0] - sum(x*y for x, y in zip(a[1:],b[1:]))
norm = length(a,b,metric)
|
Curl works but urllib doesn't
Question: Whenever I curl
[this](http://www.economist.com/blogs/schumpeter/2014/04/alstom-block), I'm
able to get the entire webpage. However, when I use the `urllib` or even
mechanize library in Python, I get a `403 error`. Any reason why?
Answer: You can user the requests lib:
import requests
print requests.get('http://www.economist.com/blogs/schumpeter/2014/04/alstom-block').text
|
socket.gethostbyaddr() returns error on some computers and not for others
Question: I've looked for any other threads related to this topic, but after an
extensive search i was not able to find an answer that relates to my question.
Using Python, I'm trying to use socket.gethostbyaddr("ip here") to determine
the hostname of an ip address in a local network:
import socket
def gethostname(ip):
hostname = socket.gethostbyaddr(ip)
return hostname
For some computers (such as the server) this returns the triplet of hostname,
alias and other IP's, but for others it does not. Instead, i get the following
error:
socket.herror: [Errno 4] No address associated with name
What exactly does this error imply? What could it be that causes it? Is there
any service or instane that should be running on the target computer in order
for this to work? The computers i'm trying to get the hostname of run Debian.
If this question has already been asked then i am sorry, but i could not find
it.
If it has something to do with reverse dns lookups, how would i solve this?
Answer: It means exactly what it says, there is no address associated. Not all IP
addresses have a reverse-lookup address.
|
Pythonic way to group items in a list
Question: Consider a list of dicts:
items = [
{'a': 1, 'b': 9, 'c': 8},
{'a': 1, 'b': 5, 'c': 4},
{'a': 2, 'b': 3, 'c': 1},
{'a': 2, 'b': 7, 'c': 9},
{'a': 3, 'b': 8, 'c': 2}
]
Is there a pythonic way to extract and group these items by their `a` field,
such that:
result = {
1 : [{'b': 9, 'c': 8}, {'b': 5, 'c': 4}]
2 : [{'b': 3, 'c': 1}, {'b': 7, 'c': 9}]
3 : [{'b': 8, 'c': 2}]
}
References to any similar Pythonic constructs are appreciated.
Answer: Use
[`itertools.groupby`](https://docs.python.org/2/library/itertools.html#itertools.groupby):
>>> from itertools import groupby
>>> from operator import itemgetter
>>> {k: list(g) for k, g in groupby(items, itemgetter('a'))}
{1: [{'a': 1, 'c': 8, 'b': 9},
{'a': 1, 'c': 4, 'b': 5}],
2: [{'a': 2, 'c': 1, 'b': 3},
{'a': 2, 'c': 9, 'b': 7}],
3: [{'a': 3, 'c': 2, 'b': 8}]}
If item are not in sorted order then you can either sort them and then use
`groupby` or you can use `collections.OrderedDict`(if order matters) or
`collections.defaultdict` to do it in O(N) time:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> for item in items:
... d.setdefault(item['a'], []).append(item)
...
>>> dict(d.items())
{1: [{'a': 1, 'c': 8, 'b': 9},
{'a': 1, 'c': 4, 'b': 5}],
2: [{'a': 2, 'c': 1, 'b': 3},
{'a': 2, 'c': 9, 'b': 7}],
3: [{'a': 3, 'c': 2, 'b': 8}]}
**Update:**
I see that you only want the those keys to be returned that we didn't use for
grouping, for that you'll need to do something like this:
>>> group_keys = {'a'}
>>> {k:[{k:d[k] for k in d.viewkeys() - group_keys} for d in g]
for k, g in groupby(items, itemgetter(*group_keys))}
{1: [{'c': 8, 'b': 9},
{'c': 4, 'b': 5}],
2: [{'c': 1, 'b': 3},
{'c': 9, 'b': 7}],
3: [{'c': 2, 'b': 8}]}
|
Am I using classes and implementing functionality correctly?
Question: I have to create a listening server that will receive HTTP POST / XML alert
traffic from a network sensor and parse out the received XML. Being a beginner
to Python, and having a tough time understanding classes, I wanted to get
advice on if I'm implementing the classes and functionality I'm trying to
achieve correctly, and if there's a better or "more Pythonic" way of doing it.
I'm forcing myself to use classes in hopes that I better grasp the concept, I
know I can just use regular functions.
The script so far:
I'm using the BaseHTTPServer and SocketServer module to create a threaded HTTP
server, and xml.dom.minidom class for parsing the XML data. So far I have two
classes set up - one to setup the threading (ThreadedHTTPServer) and another
with everything else (ThreadedHTTPRequestHandler). The "everything else" class
is currently managing the sessions and manipulating the data. I'm thinking I
need three classes, breaking out the data manipulation into the third and
leaving the second just to managing the inbound connections. Would this be
correct? How would I pass the connection data from the
ThreadedHTTPRequestHandler class to the new class that will be parsing and
manipulating the XML data?
Any help for this newbie would be appreciated. Code is below, and it's
currently working. All it does at this time is accept incoming connections and
prints the XML of a specific tag I'm interested in.
import cgi
from xml.dom.minidom import parseString
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
# Server settings
HOST = ''
PORT = 5000
BUFF = 2048
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""
This class sets up multi-threading for the server
"""
pass
class ThreadedHTTPRequestHandler(BaseHTTPRequestHandler):
'''
This class is the overall request handler.
This class contains functions to manage client connections and manipulate data.
'''
def do_POST(self):
'''
This method handles the inbound HTTP POST data
'''
print 'Connection from: ', self.client_address[0], self.client_address[1]
ctype = self.headers.getheader('content-type')
content_len = int(self.headers.getheader('content-length'))
if ctype == 'multipart/form-data':
self.post_body = cgi.parse_multipart(self.rfile)
elif ctype == 'application/x-www-form-urlencoded':
self.post_body = self.rfile.read(content_len)
else:
self.post_body = ""
self.done(200)
self.handleXML()
def done(self, code):
'''
Send back an HTTP 200 OK and close the connection
'''
try:
self.send_response(code)
self.end_headers()
except:
pass
print 'Connection from: ', self.client_address[0], self.client_address[1], ' closed.'
#class XMLHandler():
def handleXML(self):
'''
This method parses and manipulates the XML alert data
'''
xml_dom = parseString(self.post_body)
xmlTag = xml_dom.getElementsByTagName('malware')[0].toxml()
#print out the xml tag and data in this format: <tag>data</tag>
print xmlTag
if __name__ == "__main__":
try:
server = ThreadedHTTPServer((HOST, PORT), ThreadedHTTPRequestHandler).serve_forever()
print
except KeyboardInterrupt:
pass
Answer: You don't necessarily need a third class. What you need is a freestanding
function,
def handle_xml(post_body):
# work
so that you no longer need to store the `post_body` on the
`ThreadedHTTPRequestHandler`.
Class hierarchies are a good fit for some problems, and a bad fit for most.
Don't use them if you don't need to, they'll just complicate your code.
|
Writing an Element to a file
Question: I am using `ElementTree` to create, parse and modify XML files and object. I
am creating the tree like this:
import xml.etree.ElementTree as etree
foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })
then, I want to write this to a file. According to the
[documentation](https://docs.python.org/3.3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write),
I should use an `ElementTree` object for that, but how to create that from the
`Element`?
I tried
e = etree.ElementTree(foo)
e.write(filename)
but that doesn't work:
> TypeError: must be str, not bytes
Answer: Your opened file should be opened with `b` (binary) flag:
import xml.etree.ElementTree as etree
foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })
e = etree.ElementTree(foo)
with open('test.xml', 'wb') as f:
e.write(f)
or just pass a filename/path to `write()`:
e.write('test.xml')
|
Can't get the url function to work with a specific syntax in django
Question: I've visited the documenation at
[https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#std:templatetag-
url](https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#std%3atemplatetag-
url) several times and i cant seem to get this syntax to work anywhere:
{% url 'view' obj.id %}
I have a view that takes one parameter so this should work but im only getting
NoReverseMatch exception for some strange reason.
When doing it like this:
{% url 'view' obj.id as test %}
<a href="{{ test }}">test</a>
..im getting the correct url returned back and the link address displays
correctly, but when using the above mentioned syntax without setting is as a
variable it doesnt work, when i for example use it directly in an element.
When trying to do this which im trying to do:
{% url 'view' obj.id as test %}
<input type="hidden" value="{{ test }}">
im not getting any error but it doesnt seem like im getting any value in the
value field because if there were a value in the field the code would do
something, and when replacing the variable with a hard-coded string it does
work.
When doing this:
{% url 'view' obj.id as test %}
{{ test }}
just to try to print the value it doesnt return anything which i find strange
because when using it with the a element in html as shown at the first code
line above it displays the correct url.
So basically, im only getting the {% url 'view' obj.id %} syntax to work with
the a element of html and only if i define it as a variable.
I would like to use the {% url 'view' obj.id %} syntax in order to have a DRY
code. According to the documenation this should work, does anyone have a clue
about why this isnt working ? If you need more information then please let me
know and i will update the question with the necessary information.
UPDATE: I'm currently using django 1.6. The typo in the second snippet has
been corrected. The exact line from urls.py is (im at this page, using the
comment system at /comment/ which should do a reverse to the display_story
view (it works without problems when hardcoding the value attribute of the
input html tag but not with the url function):
url(r'^story/display/(?P<specific_story>\d+)/$', 'base.views.display_story', name='display_story'),
url(r'^comments/', include("django.contrib.comments.urls"))
I have also tried the url function just on the application i have created
without going through the comments application but i get the same problem.
This is the error message:
NoReverseMatch at /story/display/1/
Reverse for 'display_story' with arguments '(1,)' and keyword arguments '{}' not found.
Even though i know that the view exists and takes one argument.
This is the html code:
<input type="hidden" name="next" value="{% url 'display_story' story_details.id %}">
I have named views with the name argument and i apply the namespace when
necessary.
The django docs says: exception NoReverseMatch The NoReverseMatch exception is
raised by django.core.urlresolvers when a matching URL in your URLconf cannot
be identified based on the parameters supplied.
but that doesnt seem to be the case.
This urls.py:
url(r'^story/display/(?P<specific_story>\d+)/$', 'base.views.display_story', name='display_story')
should match this view code:
def display_story(request, specific_story):
""" Display details for a specific story. """
story_details = Story.objects.get(id=specific_story)
return render(request, "base/story/display_story.html", {
'story_details': story_details,
})
but for some reason django doesnt think the parameter sent is the the one the
function receives when it clearly is stated so in the code.
Update 2: When giving a keyword argument instead of a positional argument i
get this error:
NoReverseMatch at /story/display/1/
Reverse for 'display_story' with arguments '()' and keyword arguments '{u'specific_story': 1}' not found.
This code is used:
{% url 'display_story' specific_story=story_details.id %}
Update 3: I will update the question with the values of the local vars for the
reverse function.
To add some additional infor i ran some code in the python shell:
>>> import base.views
>>> from django.core.urlresolvers import reverse
>>>
>>> test=1
>>> reverse("display_story", kwargs={'test': test})
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 496, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 416, in _reverse_with_prefix
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'display_story' with arguments '()' and keyword arguments '{'test': 1}' not found.
>>>
>>>
>>> reverse("display_story", args=[1])
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 496, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 416, in _reverse_with_prefix
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'display_story' with arguments '(1,)' and keyword arguments '{}' not found.
Answer: Unless your view is named 'view' in the urlconf, you should use the full
python dotted import path in the tag. For example:
{% url 'my_app.views.my_view' obj.id %}
If you want to test it properly, you can also use the django shell
python manage.py shell
and try the 'reverse' function:
from django.core.urlresolvers import reverse
reverse('my_app.views.my_view' args=[1])
>> '/my/awesome/url/1'
edit: also make sure that you didn't namespace your urls, if you did, you
should include the namespace in the url tag:
{% url 'namespace:view' obj.id %}
another edit, because I have a feeling this might be it. I apologise for
abusing the answer system instead of comments, but since I'm only starting out
my reputation is too low.
Can you post the full urlconfig from your root urls.py up until the
'misbehaving' url? I have had cases where an url captured a group (say, an ID)
and then included a bunch of other urls, leading to two required arguments for
the reverse function.
|
Pyramid web framework hello world not working
Question: I'm trying to run the ["hello world"
application](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/firstapp.html)
for the Pyramid web framework but getting the following error. Can someone
please tell me what I need to install. Thanks
C:\Python27>python pyramid_hello.py
Traceback (most recent call last):
File "pyramid_hello.py", line 2, in <module>
from pyramid.config import Configurator
File "C:\Python27\lib\site-packages\pyramid-1.5-py2.7.egg\pyramid\config\__init__.py", line 11, in <module>
from pyramid.interfaces import (
File "C:\Python27\lib\site-packages\pyramid-1.5-py2.7.egg\pyramid\interfaces.py", line 1, in <module>
from zope.deprecation import deprecated
ImportError: No module named deprecation
C:\Python27>pip install zope
Downloading/unpacking zope
Could not find any downloads that satisfy the requirement zope
No distributions at all found for zope
Storing complete log in C:\Users\Tracy\pip\pip.log
C:\Python27>pip install zope.deprecation
Requirement already satisfied (use --upgrade to upgrade): zope.deprecation in c:\python27\lib\site-packages\zope.deprecation-4.1.1-py2.7.egg
Requirement already satisfied (use --upgrade to upgrade): distribute in c:\python27\lib\site-packages\distribute-0.6.26-py2.7.egg (from zope.deprecation)
Cleaning up...
C:\Python27>pip install zope.deprecation --upgrade
Requirement already up-to-date: zope.deprecation in c:\python27\lib\site-packages\zope.deprecation-4.1.1-py2.7.egg
Downloading/unpacking distribute from https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a (from zope.deprecation)
Downloading distribute-0.7.3.zip (145kB): 145kB downloaded
Running setup.py egg_info for package distribute
Downloading/unpacking setuptools>=0.7 (from distribute->zope.deprecation)
Downloading setuptools-3.4.4.tar.gz (794kB): 794kB downloaded
Running setup.py egg_info for package setuptools
Installing collected packages: distribute, setuptools
Found existing installation: distribute 0.6.26
Uninstalling distribute:
Successfully uninstalled distribute
Running setup.py install for distribute
Found existing installation: distribute 0.6.26
Can't uninstall 'distribute'. No files were found to uninstall.
Running setup.py install for setuptools
Installing easy_install-script.py script to C:\Python27\Scripts
Installing easy_install.exe script to C:\Python27\Scripts
Installing easy_install.exe.manifest script to C:\Python27\Scripts
Installing easy_install-2.7-script.py script to C:\Python27\Scripts
Installing easy_install-2.7.exe script to C:\Python27\Scripts
Installing easy_install-2.7.exe.manifest script to C:\Python27\Scripts
Successfully installed distribute setuptools
Cleaning up...
C:\Python27>python pyramid_hello.py
Traceback (most recent call last):
File "pyramid_hello.py", line 2, in <module>
from pyramid.config import Configurator
File "C:\Python27\lib\site-packages\pyramid-1.5-py2.7.egg\pyramid\config\__init__.py", line 11, in <module>
from pyramid.interfaces import (
File "C:\Python27\lib\site-packages\pyramid-1.5-py2.7.egg\pyramid\interfaces.py", line 1, in <module>
from zope.deprecation import deprecated
ImportError: No module named deprecation
C:\Python27>pip install deprecation
Downloading/unpacking deprecation
Could not find any downloads that satisfy the requirement deprecation
No distributions at all found for deprecation
Storing complete log in C:\Users\Tracy\pip\pip.log
Using virtualenv:
C:\Python27>easy_install virtualenv
Searching for virtualenv
Reading https://pypi.python.org/simple/virtualenv/
Best match: virtualenv 1.11.4
Downloading https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.11.4.tar.gz#md5=9accc2d3f0ec1da479ce2c3d1fdff06e
Processing virtualenv-1.11.4.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-o3mttl\virtualenv-1.11.4\setup.cfg
Running virtualenv-1.11.4\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-o3mttl\virtualenv-1.11.4\egg-dist-tmp-qi3l26
warning: no previously-included files matching '*' found under directory 'docs\_templates'
warning: no previously-included files matching '*' found under directory 'docs\_build'
Adding virtualenv 1.11.4 to easy-install.pth file
Installing virtualenv-script.py script to C:\Python27\Scripts
Installing virtualenv.exe script to C:\Python27\Scripts
Installing virtualenv.exe.manifest script to C:\Python27\Scripts
Installing virtualenv-2.7-script.py script to C:\Python27\Scripts
Installing virtualenv-2.7.exe script to C:\Python27\Scripts
Installing virtualenv-2.7.exe.manifest script to C:\Python27\Scripts
Installed c:\python27\lib\site-packages\virtualenv-1.11.4-py2.7.egg
Processing dependencies for virtualenv
Finished processing dependencies for virtualenv
C:\Python27>set VENV=c:\env
C:\Python27>c:\Python27\Scripts\virtualenv %VENV%
New python executable in c:\env\Scripts\python.exe
Installing setuptools, pip...done.
C:\Python27>cd\
C:\>cd env
C:\env>%VENV%\Scripts\easy_install "pyramid==1.5"
Searching for pyramid==1.5
Reading https://pypi.python.org/simple/pyramid/
Best match: pyramid 1.5
Downloading https://pypi.python.org/packages/source/p/pyramid/pyramid-1.5.tar.gz#md5=8747658dcbab709a9c491e43d3b0d58b
Processing pyramid-1.5.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-_ci7js\pyramid-1.5\setup.cfg
Running pyramid-1.5\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-_ci7js\pyramid-1.5\egg-dist-tmp-3di1fa
Adding pyramid 1.5 to easy-install.pth file
Installing ptweens-script.py script to c:\env\Scripts
Installing ptweens.exe script to c:\env\Scripts
Installing ptweens.exe.manifest script to c:\env\Scripts
Installing pdistreport-script.py script to c:\env\Scripts
Installing pdistreport.exe script to c:\env\Scripts
Installing pdistreport.exe.manifest script to c:\env\Scripts
Installing proutes-script.py script to c:\env\Scripts
Installing proutes.exe script to c:\env\Scripts
Installing proutes.exe.manifest script to c:\env\Scripts
Installing pshell-script.py script to c:\env\Scripts
Installing pshell.exe script to c:\env\Scripts
Installing pshell.exe.manifest script to c:\env\Scripts
Installing prequest-script.py script to c:\env\Scripts
Installing prequest.exe script to c:\env\Scripts
Installing prequest.exe.manifest script to c:\env\Scripts
Installing pviews-script.py script to c:\env\Scripts
Installing pviews.exe script to c:\env\Scripts
Installing pviews.exe.manifest script to c:\env\Scripts
Installing pcreate-script.py script to c:\env\Scripts
Installing pcreate.exe script to c:\env\Scripts
Installing pcreate.exe.manifest script to c:\env\Scripts
Installing pserve-script.py script to c:\env\Scripts
Installing pserve.exe script to c:\env\Scripts
Installing pserve.exe.manifest script to c:\env\Scripts
Installed c:\env\lib\site-packages\pyramid-1.5-py2.7.egg
Processing dependencies for pyramid==1.5
Searching for PasteDeploy>=1.5.0
Reading https://pypi.python.org/simple/PasteDeploy/
Best match: PasteDeploy 1.5.2
Downloading https://pypi.python.org/packages/source/P/PasteDeploy/PasteDeploy-1.5.2.tar.gz#md5=352b7205c78c8de4987578d19431af3b
Processing PasteDeploy-1.5.2.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-cfzau8\PasteDeploy-1.5.2\setup.cfg
Running PasteDeploy-1.5.2\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-cfzau8\PasteDeploy-1.5.2\egg-dist-tmp-f7vrej
Adding pastedeploy 1.5.2 to easy-install.pth file
Installed c:\env\lib\site-packages\pastedeploy-1.5.2-py2.7.egg
Searching for translationstring>=0.4
Reading https://pypi.python.org/simple/translationstring/
Best match: translationstring 1.1
Downloading https://pypi.python.org/packages/source/t/translationstring/translationstring-1.1.tar.gz#md5=0979b46d8f0f852810c8ec4be5c26cf2
Processing translationstring-1.1.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-ekrgr1\translationstring-1.1\setup.cfg
Running translationstring-1.1\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-ekrgr1\translationstring-1.1\egg-dist-tmp-o3xqh2
no previously-included directories found matching 'docs\_build'
Adding translationstring 1.1 to easy-install.pth file
Installed c:\env\lib\site-packages\translationstring-1.1-py2.7.egg
Searching for venusian>=1.0a3
Reading https://pypi.python.org/simple/venusian/
Best match: venusian 1.0a8
Downloading https://pypi.python.org/packages/source/v/venusian/venusian-1.0a8.tar.gz#md5=a1a72166fd7cccf0f30e3305e09ce5cf
Processing venusian-1.0a8.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-otkbse\venusian-1.0a8\setup.cfg
Running venusian-1.0a8\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-otkbse\venusian-1.0a8\egg-dist-tmp-wxnee2
Adding venusian 1.0a8 to easy-install.pth file
Installed c:\env\lib\site-packages\venusian-1.0a8-py2.7.egg
Searching for zope.deprecation>=3.5.0
Reading https://pypi.python.org/simple/zope.deprecation/
Best match: zope.deprecation 4.1.1
Downloading https://pypi.python.org/packages/source/z/zope.deprecation/zope.deprecation-4.1.1.tar.gz#md5=ce261b9384066f7e13b63525778430cb
Processing zope.deprecation-4.1.1.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-vv7_t0\zope.deprecation-4.1.1\setup.cfg
Running zope.deprecation-4.1.1\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-vv7_t0\zope.deprecation-4.1.1\egg-dist-tmp-g86gig
warning: no previously-included files matching '*.dll' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.pyo' found anywhere in distribution
warning: no previously-included files matching '*.so' found anywhere in distribution
Adding zope.deprecation 4.1.1 to easy-install.pth file
Installed c:\env\lib\site-packages\zope.deprecation-4.1.1-py2.7.egg
Searching for zope.interface>=3.8.0
Reading https://pypi.python.org/simple/zope.interface/
Best match: zope.interface 4.1.1
Downloading https://pypi.python.org/packages/2.7/z/zope.interface/zope.interface-4.1.1-py2.7-win32.egg#md5=97fc757b020bb25b829f9c566d87c8c3
Processing zope.interface-4.1.1-py2.7-win32.egg
creating c:\env\lib\site-packages\zope.interface-4.1.1-py2.7-win32.egg
Extracting zope.interface-4.1.1-py2.7-win32.egg to c:\env\lib\site-packages
Adding zope.interface 4.1.1 to easy-install.pth file
Installed c:\env\lib\site-packages\zope.interface-4.1.1-py2.7-win32.egg
Searching for repoze.lru>=0.4
Reading https://pypi.python.org/simple/repoze.lru/
Best match: repoze.lru 0.6
Downloading https://pypi.python.org/packages/source/r/repoze.lru/repoze.lru-0.6.tar.gz#md5=2c3b64b17a8e18b405f55d46173e14dd
Processing repoze.lru-0.6.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-sbw6vu\repoze.lru-0.6\setup.cfg
Running repoze.lru-0.6\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-sbw6vu\repoze.lru-0.6\egg-dist-tmp-o5ek4v
Adding repoze.lru 0.6 to easy-install.pth file
Installed c:\env\lib\site-packages\repoze.lru-0.6-py2.7.egg
Searching for WebOb>=1.3.1
Reading https://pypi.python.org/simple/WebOb/
Best match: WebOb 1.3.1
Downloading https://pypi.python.org/packages/source/W/WebOb/WebOb-1.3.1.tar.gz#md5=20918251c5726956ba8fef22d1556177
Processing WebOb-1.3.1.tar.gz
Writing c:\users\tracy\appdata\local\temp\easy_install-8x1ebc\WebOb-1.3.1\setup.cfg
Running WebOb-1.3.1\setup.py -q bdist_egg --dist-dir c:\users\tracy\appdata\local\temp\easy_install-8x1ebc\WebOb-1.3.1\egg-dist-tmp-dgnzem
no previously-included directories found matching '*.pyc'
no previously-included directories found matching '*.pyo'
Adding webob 1.3.1 to easy-install.pth file
Installed c:\env\lib\site-packages\webob-1.3.1-py2.7.egg
Finished processing dependencies for pyramid==1.5
C:\env>python pyramid_hello.py
Traceback (most recent call last):
File "pyramid_hello.py", line 2, in <module>
from pyramid.config import Configurator
File "C:\Python27\lib\site-packages\pyramid-1.5-py2.7.egg\pyramid\config\__init__.py", line 11, in <module>
from pyramid.interfaces import (
File "C:\Python27\lib\site-packages\pyramid-1.5-py2.7.egg\pyramid\interfaces.py", line 1, in <module>
from zope.deprecation import deprecated
ImportError: No module named deprecation
C:\env>
Answer: Your last command uses system-wide python in `C:\Python27` that is available
using %PATH% variable.
Just change your last command to use
C:\env>.\Scripts\python pyramid_hello.py
or from any directory containing your scripts use an absolute path to run it
with your %VENV% python interpreter.
c:\scripts>%VENV%\Scripts\python pyramid_hello.py
May be you will find it more convenient to activate/deactivate your
virtualenv. Experienced users tend to have it explicit and the pyramid docs
usually do not use virtualenv activation. For pyramid beginners it may be a
good idea for their first steps. Just a matter of taste.
|
SYN Port Scanner Script: "Mac address to reach destination not found. Using Broadcast" error
Question: Im writing a SYN Port Scanner in Python with Scapy. There are no syntax errors
involved but when I run the script Im unable to send any packets to any
destination.

This the code
#!/usr/bin/python
#Port Scanner using SYN Scanning (Half Open TCP Scanning)
from scapy.all import *
import sys, argparse
#the 'argparse' module makes it easy to write user-freindly command-line interfaces.
#it also automatically generates help and usage messages and issues errors on invalid arguments
argParser = argparse.ArgumentParser(description='TCP SYN Scanner for a single host.')
argParser.add_argument('--version','-v',action='version', version = '%(prog)s is at version 1.0.0')
argParser.add_argument('host',metavar = 'host', type=str, help='The hostname or IP to scan.')
argParser.add_argument('-p', metavar='port', nargs=2, type=str, help='port range scan eg 80 443')
argParser.add_argument('-t', metavar = 'timeout', type=float, help = 'The time to wait for ACKs.', default=1)
arguments = argParser.parse_args()
print 'Scanning host %s' % (arguments.host)
startPort = 1
endPort = 65535
if arguments.p != None: #if we have arguments
startPort = int(arguments.p[0])
endPort = int(arguments.p[1])
for port in xrange (startPort, endPort +1):
packet=sr1(IP(dst=arguments.host)/TCP(dport=port,flags='S'),verbose=0,timeout=arguments.t) //ERROR
if packet:
print ('Port %d is open!' % port)

NOTE: The other question with the same error has a completely different
script. Please dont mark as duplicate.
Answer: Im an idiot. You cannot put a public IP address, as PAT isn't applicable - it
has to be private Class A, B or C. It said that on the first sentence of the
GITHUB info paragraph where I took the script from
|
Unable to find file or directory Python subprocess
Question: I'm trying to call a Python module but get the following error "test.sh not
found"
but this file is found in the directory.
process = subprocess.Popen("test.sh",shell=True)
The script and the sh file are located in the same directory.
Answer: By default the current directory is not in PATH therefore just `"test.sh"` is
not found, the minimal change is to use `"./tests.sh"`.
To run a shell script, make sure you have a valid shebang e.g., `#!/bin/sh`
and the file has executable permissions (`chmod u+x test.sh`).
If you are running Python script from a different directory then you also need
to provide the full path:
#!/usr/bin/env python
import os
import sys
from subprocess import check_call
script_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
check_call(os.path.join(script_dir, "test.sh"))
Note: there is no `shell=True` that starts the additional unnecessary shell
process here. `realpath` resolve symlinks, you could use `abspath` instead if
you want the path relative script's symlink instead of the script file itself.
|
While is this function still executing after?
Question: I made a simple choice game much like Rock, Paper, Scissors using Python. The
problem is that after you have won, and put in the winner's name, the while
loop still executes one more time. This is unacceptable! I've looked over it,
and looked over it again. With my knowledge, I can't seem to work out the
problem. This is a good learning moment.
Link to
[File](https://drive.google.com/file/d/0BwiB337z3HPrd043bUt0ekFhZjA/edit?usp=sharing)
# Imports modules
import random
import math
# Welcome message
def main():
print("//////////////////////////////////////")
print("//////////////////////////////////////")
print("// Welcome Ninja, Pirate, or Zombie //")
print("//////////////////////////////////////")
print("//////////////////////////////////////")
print("\n\n")
choose()
# Prompts user to choose class
def choose():
choice = str(input("Make a choice! (Ninja, Pirate, or Zombie) "))
choice = choice.lower()
if choice == "ninja" or choice == "pirate" or choice == "zombie":
enemy(choice)
else:
choose()
# Randomly selects opposing enemy
def enemy(choice):
enemyRandom = random.randint(1,3)
if enemyRandom == 1:
enemy = "ninja"
elif enemyRandom == 2:
enemy = "pirate"
elif enemyRandom == 3:
enemy = "zombie"
else:
print("Something went wrong!")
hit_factor(choice, enemy)
# Determines the hit factor. Certain class are weak or strong when fighting certain
# other classes
def hit_factor(choice, enemy):
if choice == "ninja" and enemy == "ninja":
hitFactor = 1
elif choice == "ninja" and enemy == "pirate":
hitFactor = 1.2
elif choice == "ninja" and enemy == "zombie":
hitFactor = 0.8
elif choice == "pirate" and enemy == "ninja":
hitFactor = 0.8
elif choice == "pirate" and enemy == "pirate":
hitFactor = 1
elif choice == "pirate" and enemy == "zombie":
hitFactor = 1.2
elif choice == "zombie" and enemy == "ninja":
hitFactor = 1.2
elif choice == "zombie" and enemy == "pirate":
hitFactor = 0.8
elif choice == "zombie" and enemy == "zombie":
hitFactor = 1
else:
print("Something went horribly wrong.")
enemy_hit_factor(choice, enemy, hitFactor)
# Determines the enemy's hit factor
def enemy_hit_factor(choice, enemy, hitFactor):
if enemy == "ninja" and choice == "ninja":
enemyHitFactor = 1
elif enemy == "ninja" and choice == "pirate":
enemyHitFactor = 1.2
elif enemy == "ninja" and choice == "zombie":
enemyHitFactor = 0.8
elif enemy == "pirate" and choice == "ninja":
enemyHitFactor = 0.8
elif enemy == "pirate" and choice == "pirate":
enemyHitFactor = 1
elif enemy == "pirate" and choice == "zombie":
enemyHitFactor = 1.2
elif enemy == "zombie" and choice == "ninja":
enemyHitFactor = 1.2
elif enemy == "zombie" and choice == "pirate":
enemyHitFactor = 0.8
elif enemy == "zombie" and choice == "zombie":
enemyHitFactor = 1
else:
print("Something went horribly wrong.")
combat(choice, enemy, hitFactor, enemyHitFactor)
# Initiates combat
def combat(choice, enemy, hitFactor, enemyHitFactor):
yourHP = 1000
enemyHP = 1000
print("Your HP: ", yourHP)
print("Enemy's HP: ", enemyHP)
over = False
while over != True:
isHitCalc = random.randint(1,10)
if isHitCalc > 3:
isHit = True
else:
isHit = False
print("You missed!")
if isHit == True:
randomHIT = random.randint(1,100)
randomHitDamage = math.ceil(randomHIT * hitFactor)
enemyHP -= randomHitDamage
if enemyHP < 0:
enemyHP = 0
print("You hit the enemy for ", randomHitDamage," damage.",sep='')
print("Enemy's HP: ", enemyHP)
if enemyHP == 0:
file = open("wonMessage.txt", "r")
content = file.read()
print(content)
over = True
winner()
isHitCalc2 = random.randint(1,10)
if isHitCalc2 > 3:
isHitMe = True
else:
isHitMe = False
print("Your enemy missed!")
if isHitMe == True:
randomHitMe = random.randint(1,100)
randomHitDamageMe = math.ceil(randomHitMe * enemyHitFactor)
yourHP -= randomHitDamageMe
if yourHP < 0:
yourHP = 0
print("The enemy hit you for ", randomHitDamageMe, " damage.", sep='')
print("Your HP: ", yourHP)
if yourHP == 0:
file = open("lostMessage.txt", "r")
content = file.read()
print(content)
over = True
# Writes winner's name to text file
def winner():
winner = str(input("Please enter your name: "))
infile = open("winner.txt", "w")
infile.write("Latest winnner's name: ")
infile.write(winner)
# Calls main
main()
Answer: It is probably because after you call `winner()` in
if enemyHP == 0:
file = open("wonMessage.txt", "r")
content = file.read()
print(content)
over = True
winner()
you don't `break` out of the loop immediately.
Instead, you still proceed to process the logic below before doing the `while`
loop check (`over != True`) :
isHitCalc2 = random.randint(1,10)
if isHitCalc2 > 3:
isHitMe = True
else:
isHitMe = False
print("Your enemy missed!")
if isHitMe == True:
randomHitMe = random.randint(1,100)
randomHitDamageMe = math.ceil(randomHitMe * enemyHitFactor)
yourHP -= randomHitDamageMe
if yourHP < 0:
yourHP = 0
print("The enemy hit you for ", randomHitDamageMe, " damage.", sep='')
print("Your HP: ", yourHP)
if yourHP == 0:
file = open("lostMessage.txt", "r")
content = file.read()
print(content)
over = True
You can fix this specific case by adding:
if enemyHP == 0:
file = open("wonMessage.txt", "r")
content = file.read()
print(content)
over = True
winner()
break
|
POST data to CGI file using XMLHttpRequest causes BadHeader
Question: When I try posting data to my CGI file, my CGI file says the actual post data
is invalid. I am using HTML/JavaScript for the front end and Python for the
backend.
Works:
<form name="login" action="/cgi-bin/register.py" method="POST">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
Confirm password:<input type="password" name="confirmpassword"><br>
</form>
However, this causes the page to refresh. I am trying to avoid this and have
text display within the same page(without reloading). Hence, I have chosen to
use an XMLHTTPRequest to asynchronously process this event.
This is what I want to achieve:
<script>
function validateLogin()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username.length <= 0 || password.length <= 0)
{
document.alert("The username or password cannot be blank");
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("resultText").innerHTML=xmlhttp.responseText;
}else if (xmlhttp.readyState==4) {
document.write(xmlhttp.status + xmlhttp.statusText);
}
}
xmlhttp.open("POST","/cgi-bin/login.cgi",true);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8')
xmlhttp.send("username=" + username + "&password=" + password);
}
</script>
CGI File:
#!/usr/bin/python
import cgi
from dbmanager import openConnection
from passlib.hash import sha256_crypt
s = "Content-type: text/html\n\n\n"
form = cgi.FieldStorage()
username = form["username"].value
password = form["password"].value
message = None
I am getting an error in python stating `Bad header=FieldStorage(None, None,`
I don't get this error when I do it the first way, but the second way is
giving me this error. I **need** it to work the second way.
Answer: For echo Server :
# HTML :
<html>
<head>
<script>
function validateLogin()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username.length <= 0 || password.length <= 0)
{
document.alert("The username or password cannot be blank");
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("resultText").innerHTML=xmlhttp.responseText;
}else if (xmlhttp.readyState==4) {
document.write(xmlhttp.status + xmlhttp.statusText);
}
}
xmlhttp.open("POST","../post_test.py",true);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8')
xmlhttp.send("username=" + username + "&password=" + password);
}
</script>
</head>
<body>
<form name="login" >
Username:<input type="text" id="username"><br>
Password:<input type="text" id="password"><br>
Confirm password:<input type="text" id="repassword"><br>
</form>
<button onclick="validateLogin()">Login</button>
<span id="resultText"></span>
</body>
</html>
# CGI-SCRIPT:
#!/usr/bin/python2.7
import cgi
form = cgi.FieldStorage()
print "Content-Type: text/html;charset=utf-8"
print "Access-Control-Allow-Origin:*"
print
print form
Replace input type `password` to `text` because got security bugs !
Yo got wrong answer on cgi script. Who know service is live ? So need some
type, status, header, content..
Check post address : `..//` mean `currient_uri + new_path + target`
On javascript: Call by ID but where ID parameter ?
|
Django error in filtering datetime field by date : Join on field X not permitted
Question: I saw another post suggests that datetime field can be filtered by time, by
using `__date`. However when I tried on my machine it never worked.
This is my `models.py`
class Record (models.Model):
time = models.DateTimeField(null=True,blank=True)
user = ForeignKey to the user table
content = models.CharField(max_length=36,null=True,blank=True,unique=True)
In `python manage.py.runserver`
>>> from datetime import datetime
>>> from appname.models import Record
>>> u = User.objects.filter(username = 'user')
>>> r = Record.objects.filter(time__date = datetime.today().date())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 163, in filter
return self.get_queryset().filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 590, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 608, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1198, in add_q
clause = self._add_q(where_part, used_aliases)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1234, in _add_q
current_negated=current_negated)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1100, in build_filter
allow_explicit_fk=True)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1357, in setup_joins
names, opts, allow_many, allow_explicit_fk)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1320, in names_to_path
"the lookup type?" % (name, names[pos + 1]))
FieldError: Join on field 'timeIn' not permitted. Did you misspell 'date' for the lookup type?
I am on windows 7 running python 2.7, django 1.6
Any help is greatly appreciated!
Answer: Use __contains instead of __date:
r = Record.objects.filter(time__contains = datetime.today().date())
**UPDATE**
Since that __startswith (LIKE 'value%') is more faster than __contains (LIKE
'%value%'), the best choice is:
r = Record.objects.filter(time__startswith = datetime.today().date())
|
How do I import a file type .1.tar.gz into Python?
Question: I am attempting to complete a computational project were I can duplicate
sentiment analysis, and find a correlation to parts of speech usage in a data
set saved in a tar.gz file. The file is currently saved in my user directory
on my University server. Access to the directory is not a problem. The problem
that I have is importing the file into Python so that I may run the Counter
script. I am very new to the NTLK platform. Can someone please explain how to
overcome this obstacle?
Answer: [`tar`](http://unixhelp.ed.ac.uk/CGI/man-cgi?tar) is an archiving tool. You're
file is a gzipped tar archive. You'll have to unpack that file:
tar -xvzf file.1.tar.gz
After which you can easily manipulate the unpacked files in python with
regular file operations. You can also use certain python modules for unpacking
the archive but I don't see any extra value in that.
|
Run a python image processing script in an android app
Question: I am using a python script to detect circles using Hough transfrom which
imports "opencv2" and "math" libraries.Can I run this script in an android
app?How can this be done?The following application is the one I want to run in
an android app.`import cv2 import math
def resizeImage(img):
dst=cv2.resize(img,None,fx=1,fy=1,interpolation=cv2.INTER_LINEAR)
return dst
img=cv2.imread('20140318_174800.jpg')
grey=cv2.imread('20140318_174800.jpg',0)
ret,thresh = cv2.threshold(grey,50,255,cv2.THRESH_BINARY)
circles = cv2.HoughCircles(thresh,cv2.cv.CV_HOUGH_GRADIENT,1,75,param1=50,param2=13,minRadius=0,maxRadius=400)
for i in circles[0,:]:
#draw the outer circle
cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)
#draw the centre of the circle
cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
##Determine co-ordinates for centre of circle
x1 = circles[0][0][0]
y1 = circles[0][0][1]
#x2 = circles[0][1][0]
#y2 = circles[0][1][1]
##Angle betwen two circles
#theta = math.degrees(math.atan((y2-y1)/(x2-x1)))
##print information
print "x1 = ",x1
print "y1 = ",y1
#print "x2 = ",x2
#print "y2 = ",y2
#print theta
print circles
##Resize image
img = resizeImage(img)
thresh = resizeImage(thresh)
##Show Images
cv2.imshow("thresh",thresh)
cv2.imshow("img",img)
cv2.waitKey(0)
`
Answer: atm, you can't.
you would have to recompile the cv2 module for android first, in a similar way
python4android does it(redirecting system calls to java rmi), tough job.
|
Adding values to dictionary in Python
Question: The code below:
rect_pos = {}
rect_pos_single = [[0,0], [50, 0], [50, 100], [0, 100]]
i = 0
while (i<3):
for j in range(4):
rect_pos_single[j][0] += 50
print rect_pos_single
rect_pos[i] = rect_pos_single
i += 1
print rect_pos
The code prints subsequent iterations of the variable "rect_pos_single". Next,
I add them to dictionary "rect_pos". Keys change, but value is always the same
- last iteration. I do not understand why?
Answer: This line
rect_pos_single[j][0] += 50
modifies the list in-place; that is, `rect_pos_single` always refers to the
same list object, but you change the contents of that list.
This line
rect_pos[i] = rect_pos_single
assigns a reference to the list referenced by `rect_pos_single` to
`rect_pos[i]`. Each element of `rect_pos` refers to the same list.
The simplest change is to assign a _copy_ of the list to the dictionary with
rect_pos[i] = copy.deepcopy(rect_pos_single) # Make sure you import the copy module
A deep copy is needed because `rect_pos_single` is a list of lists, and doing
a shallow copy with `rect_pos_single` would simply create a new list with
references to the same lists that are actually modified with
`rect_pos_single[j][0] += 50`.
|
Shell script to update DB via flask
Question: I got started with [flask](http://flask.pocoo.org/docs/quickstart/#quickstart)
and I tried out the
[Flaskr](https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/)
example. On the execution of a certain python script, I would like to update
one row of my database.
I am a newbie here and would like to understand: am I going to update the DB
from inside that python script or I am going to wait for a signal from the
flask WSGI script: I have referred to this
[thread](http://stackoverflow.com/questions/11292612/flask-sqlalchemy-how-to-
update-insert-row-in-db) but am not sure how I am going to interact with the
external script. Any help or hints are appreciated.
Answer: WSGI handles HTTP requests/responses. A script won't be issuing those.
Instead, import your Flask app in the script and make an application context:
from my_project import my_app
ctx = my_app.app_context()
ctx.push()
# ... my code
db.session.commit()
ctx.pop()
Relevant docs: <http://flask.pocoo.org/docs/appcontext/>,
<http://flask.pocoo.org/docs/shell/>
Or consider using [Flask-Script](http://flask-
script.readthedocs.org/en/latest/) to add command line functions to your
application, if the function doesn't need to be a separate script.
|
Python: Resize Image to a fixed size, ignoring the initial aspect ratio
Question: I am trying to scale an incoming image which can be of (any type, any size) to
a fixed grayscale image (eg 14x14). What I do is:
from PIL import Image
...
img = Image.open(args.picture).convert('L')
img.thumbnail( (14,14), Image.ANTIALIAS) #img.resize returns Non-Type
but this returns a 12x14 instead of 14x14, due to the original aspect ratio
apparently.
How would I achieve a 14x14, for any possible input?
Answer: The `thumbnail` entry from the [PIL
docs](http://effbot.org/imagingbook/image.htm) specifically says it maintains
the aspect ratio of the original. Try using `resize` instead, it doesn't
appear to maintain aspect ratio, at least from what I see.
|
How do i generate a documentation for a 1-file python project (script, no module) with sphinx?
Question: I have a python project which is stored in one file, it's a command line tool.
I've managed to generate a documentation with sphinx allready, but how do i
determine that my file is a script and _not_ a module?
Answer: There are multiple options for documenting command line tool written in
Python:
* helpstring shown directly by the command
* README.rst written in reStructuredText and converted to html by `rst2html`
* Sphinx documentation
(I do not claim, this list is complete)
# helpstring printed from command line
This is by far the most accessible form of documentation as everyone, who
installs the program can show it up.
I highly recommend using `docopt` for parsing command line, as it brings you
best of all - having docstring in your source code (as module docstring) and
at the same time on command line.
You can see my post in SO <http://stackoverflow.com/a/23304876/346478> or here
you see sample from project itself:
"""Usage:
quick_example.py tcp <host> <port> [--timeout=<seconds>]
quick_example.py serial <port> [--baud=9600] [--timeout=<seconds>]
quick_example.py -h | --help | --version
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1.1rc')
print(arguments)
When running from command line:
$ python quick_example.py -h
Usage:
quick_example.py tcp <host> <port> [--timeout=<seconds>]
quick_example.py serial <port> [--baud=9600] [--timeout=<seconds>]
quick_example.py -h | --help | --version
There are other argument parsers, like `plac` or `argparse`. Personally I like
the most `docopt`.
# README.rst written in reStructuredText and converted to html by `rst2html`
Writting README.rst is very easy and has advantage, that on github and
bitbucket, you get great readable introduction to your project as it gets
rendered automatically.
It is also much simpler than Sphinx project, you do not have to use multiple
files, have just one.
When you install docutils:
$ pip install docutils
you get bunch of commands, which let you convert README.rst into something
nice. The only command I use from this set is `rst2html` (on Windows it goes
as `rst2html.py` and you have to play a bit to make it working, but it is
definitely worth).
Creation of html for of your `README.rst`:
$ rst2html README.rst README.html
I do it from my `vim` editor, where it goes even simpler `:!rst2html % %.html`
what produces `README.rst.html` file.
# Sphinx documentation
I consider Sphinx great extension of reStructuredText and have authored couple
of technical booklets with that - it offers great cross referencing syntax, I
like it.
But for command line tool I would consider it overkill.
For description how to use Sphinx, refer to their great documentation.
# Conclusion
Sphinx is great, but seems to be overkill for command line tool.
reStructuredText README.rst shall be obligatory part of any Python project
regardless of the size, put there all what you think is handy when you forget
everything about the project.
On the other hand, I have provided set of pages to my users in html and I am
not sure, how often they really read it. People are lazy.
Documentation over help option on command line seems to work best for me. At
the moment, you need the help (typing on command line), you have it there. And
with packages like `docopt` it can be perfectly in-line with docstring inside
your source code.
And if you want to invest into your users, teach them `less` (or `more`)
command with those few hot keys to search `/` for a string, jump to the next
occurrence `n`, back one occurrence `N`, to the top `gg` or bottom `G`. `h` or
`H` be your friend and `q` your security break.
Enjoy living on command line.
|
My calculator program in Python allows character inputs
Question: I have created a Calculator program in Python using Tkinter and it is working
fully; but when I run it you can click on the Entry box at the top of my
Calculator and enter characters. I have written code so that when this happens
an Error occurs but these characters still appear. I would appreciate any help
on whether I can disallow this from happening.
import tkinter as tk
root=tk.Tk()
root.geometry("198x125")
root.title("Calculator")
display= tk.Entry(root, width=33, bg="pink")
display.grid(row=1, column=0, columnspan=5)
def click(key):
if key =='=':
str1="123456789"
if display.get() [0] not in str1:
display.insert(tk.END, "First character is not valid")
try:
result=eval(display.get())
display.insert(tk.END, "="+str(result))
except:
display.insert(tk.END, "--> ERROR")
elif key== 'C':
display.delete(0, tk.END)
if '=' in display.get():
entry.display(0, tk.END)
else:
if '=' in display.get():
display.get(0, tk.END)
display.insert(tk.END, key)
button_list = [
'7','8','9','/',
'4','5','6','*',
'1','2','3','-',
'0','+','C','=',]
r = 2
c = 0
for t in button_list:
cmd=lambda x=t: click(x)
tk.Button(root, text=t, width=5, command=cmd).grid(row=r, column=c)
c +=1
if c > 3:
c = 0
r +=1
root.mainloop()
Answer: Use the `state=DISABLED` option to disable the Entry while it's idle, and if
you want to retain the color, just use the `disabledbackground` option:
display= tk.Entry(root, width=33, bg="pink", disabledbackground="pink", state=tk.DISABLED)
Then access its state and change it to normal at the start of the click
function, and back to disabled at the end.
Refer to: <http://effbot.org/tkinterbook/entry.htm#Tkinter.Entry.config-
method>
|
Python error check bug?
Question: I have the following script:
from multiprocessing import Lock, Pool
def worker():
r = other.work()
return r
def main():
pool = Pool(4)
result = pool.apply_sync(worker,())
result.wait()
In **worker()** , I call function **work()** from another module '**other** ',
However, I forget to import the module '**other** '. But when I ran this
python script, python didn't report any Exception. Is this a bug ?
Answer: Any errors that are raised in the spawned processes will remain silent until
you actually retrieve the result.
from multiprocessing import Lock, Pool
def worker():
r = other.work()
return r
def main():
pool = Pool(4)
# note: this is apply_async, not apply_sync
result = pool.apply_async(worker,())
result.wait()
# See here
actual_result = result.get()
This will raise:
NameError: global name 'other' is not defined
What you have named `result` is a `multiprocessing.pool.ApplyResult` object
which is more like the promise of a return value, than a return value itself.
|
Converting a list from a .txt file into a dictionary
Question: Ok, I've tried all the methods in [Python: List to
Dictionary](http://stackoverflow.com/questions/4576115/python-list-to-
dictionary), but I can't seem to get this to work right. I'm trying to convert
a list that I've made from a .txt file into a dictionary. So far my code is:
import os.path
from tkinter import *
from tkinter.filedialog import askopenfilename
import csv
window = Tk()
window.title("Please Choose a .txt File")
fileName = askopenfilename()
classInfoList = []
classRoster = {}
with open(fileName, newline = '') as listClasses:
for line in csv.reader(listClasses):
classInfoList.append(line)
The .txt file is in the format: professor class students
An example would be: Professor White Chem 101 Jesse Pinkman, Brandon Walsh,
Skinny Pete
The output I desire would be a dictionary with professors as the keys, and
then the class and list of students for the values.
OUTPUT:
{"Professor White": ["Chem 101", [Jesse Pinkman, Brandon Walsh, Skinny Pete]]}
However, when I tried the things in the above post, I kept getting errors.
What can I do here?
Thanks
Answer: Since the data making up your dictionary is on consecutive lines, you will
have to process three lines at once. You can use the `next()` method on the
file handle like this:
output = {}
input_file = open('file1')
for line in input_file:
key = line.strip()
value = [next(input_file).strip()]
value.append(next(input_file).split(','))
output[key] = value
input_file.close()
This would give you:
{'Professor White': ['Chem 101',
['Jesse Pinkman, Brandon Walsh, Skinny Pete']]}
|
Python & requests | ImportError: No module named util
Question: I just installed the package requests on a new computer. I'm getting this
error when I try to import that module. Any ideas what's causing the issue w/
the util module?
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/__init__.py", line 58, in <module>
from . import utils
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/utils.py", line 25, in <module>
from .compat import parse_http_list as _parse_list_header
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/compat.py", line 7, in <module>
from .packages import chardet
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/__init__.py", line 3, in <module>
from . import urllib3
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/__init__.py", line 16, in <module>
from .connectionpool import (
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/connectionpool.py", line 36, in <module>
from .connection import (
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/connection.py", line 43, in <module>
from .util import (
ImportError: No module named util
Answer: on pypi.python.org I see, that latest version of `requests` is 2.2.1
Your listing shows, you have installed version 2.3.0, so it is likely, you are
using development version which is not yet really completed.
Uninstal it:
$ pip uninstall requests
And install production quality one:
$ pip install requests
In case, it would still mess up with version 2.3.0, install explicitly the
2.2.1
$ pip install requests==2.2.1
|
Python & SQLite3 Selecting from two tables
Question: I have written this code in python, which I basically opens up my SQLite3
database and looks at each row in the table 'contact' and then takes each 'id'
number and then looks at the matching 'id' in the table 'Users'. My problem is
that it only outputs the first one and does not loop through all the rows.
import sqlite3
conn = sqlite3.connect('sqlite3.db')
cursor = conn.cursor()
cursor2 = conn.cursor()
cursor3 = conn.cursor()
text_file = open("Output.txt", "w");
try:
cursor.execute("SELECT Id, address FROM contact;") # Get address details by ID
for row in cursor:
ID = row[0]
address= row[1]
cursor2.execute("SELECT name FROM Users WHERE id= " + str(ID) + ";") # Get users's name by ID
row2 = cursor2.fetchone()
sendername = row2[0]
text_file.write(firstname, lastname, address);
finally:
conn.close()
Any suggestions, I'm very new to python.
Answer: You can ask the database to do a join instead:
cursor.execute("""\
SELECT u.name, c.address
FROM contact c
INNER JOIN Users u ON u.id = c.Id
""")
with open('Output.txt', 'w') as outfh:
for name, address in cursor:
outfh.write('{} {}\n'.format(name, address)
The `INNER JOIN` tells SQLite to only pick rows for which there is an actual
match on the `id` columns. If you marked the `id` column as a foreign key in
the `contact` table, you could use a `NATURAL INNER JOIN` as well, and omit
the `ON` clause.
|
how to post multiple value with same key in python requests?
Question:
requests.post(url, data={'interests':'football','interests':'basketball'})
but,is not working,how to post `football` and `basketball` in `interests`
field?
Answer: Dictionary keys _must_ be unique, you can't repeat them. You'd use a sequence
of key-value tuples instead, and pass this to `data`:
requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])
Demo POST to <http://httpbin.org>:
>>> import requests
>>> url = 'http://httpbin.org/post'
>>> r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])
>>> r.json()['form']
{u'interests': [u'football', u'basketball']}
|
Connect OpenERP with mysql using cr?
Question: I would like to get some data from mysql in OpenERP.
In one way I can do it like that:
#!/usr/bin/python
import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="appuser", passwd="",
db="onco")
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT * FROM LOCATION")
# commit your changes
db.commit()
# get the number of rows in the resultset
numrows = int(cursor.rowcount)
# get and display one row at a time.
for x in range(0,numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
from [How do I connect to a MySQL Database in
Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-
mysql-database-in-python)
But is it maybe smarter way to do it? To use cr like standard OpenERP object?
Answer: Your way is ok, but:
1. You don't need `db.commit()` after `SELECT`. It's necessary only if you change something in database.
2. Instead of getting the number of rows and `for x in range(0, numrows)` you can use `for x in cursor.fetchall():`. To get only `n` elements you can use `cursor.fetchmany(n)`.
|
Threading and interpreter shutdown
Question: I have this piece of python code:
def __init__(self):
self.ip_list=[]
self.queue=Queue()
for i in range(5):
worker=threading.Thread(target=self.__executeCmd, name="executeCmd("+str(i)+")")
worker.setDaemon(True)
worker.start()
self.queue.put(["wget", "-qO-", "http://ipecho.net/plain"])
self.queue.put(["curl", "http://www.networksecuritytoolkit.org/nst/cgi-bin/ip.cgi"])
self.queue.put(["curl", "v4.ident.me"])
self.queue.put(["curl", "ipv4.icanhazip.com"])
self.queue.put(["curl", "ipv4.ipogre.com"])
def __executeCmd(self):
cmd=self.queue.get()
try:
rc=subprocess.check_output(cmd, stderr=open(os.devnull, 'w')).strip()
except:
self.queue.task_done()
return
if self.is_valid_ip(rc)==True:
self.ip_list.append(rc)
self.queue.task_done()
def waitForIP(self, wait_in_sec):
cnt=wait_in_sec*10
while self.ip_list==[]:
time.sleep(0.1)
cnt-=1
if cnt<=0:
return("")
return(self.ip_list[0])
Its for querying the external IP address from five URLs and get the response
from that one that was delivered first.
But sometimes I get this (and I get it via email because the job was started
via crontab):
Exception in thread executeCmd(0) (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
File "/usr/lib/python2.7/threading.py", line 505, in run
File "/home/dede/bin/tunnel_watchdog.py", line 115, in __executeCmd
File "/usr/lib/python2.7/Queue.py", line 65, in task_done
File "/usr/lib/python2.7/threading.py", line 296, in notifyAll
<type 'exceptions.TypeError'>: 'NoneType' object is not callable
I think its because the script has ended but a thread was still running and
then came out of subprocess.check_output().
Is there a way to avoid this (without waiting for all five URLs delivered
their data) ?
Answer: The project is much simpler than it looks. Here's one implementation using the
`multiprocessing` module.
The function `imap_unordered` runs the jobs in parallel, and returns the
first-completed one first. The outer level function checks the result. If the
result is okay, it's printed, then the pool is terminated and the entire
program exits. It doesn't wait for the other jobs to complete.
import multiprocessing, re, subprocess, sys
CMD_LIST = [
["wget", "-qO-", "http://ipecho.net/plain"],
["curl", '-s', "http://www.networksecuritytoolkit.org/nst/cgi-bin/ip.cgi"],
["curl", '-s', "v4.ident.me"],
["curl", '-s', "ipv4.icanhazip.com"],
["curl", '-s', "ipv4.ipogre.com"],
]
ip_pat = re.compile('[0-9.]{7,}')
pool = multiprocessing.Pool(5)
for output in pool.imap_unordered(subprocess.check_output, CMD_LIST):
print 'output:',output
m = ip_pat.search(output)
if m:
print 'GOT IP:', m.group(0)
pool.terminate()
sys.exit(0)
print 'no IP found'
|
logging in multiple classes with module name in log
Question: I want to use the logging module instead of printing for debug information and
documentation. The goal is to print on the console with DEBUG level and log to
a file with INFO level.
I read through a lot of documentation, the cookbook and other tutorials on the
logging module but couldn't figure out, how I can use it the way I want it.
(I'm on python25)
I want to have the names of the modules in which the logs are written in my
logfile.
The documentation says I should use `logger = logging.getLogger(__name__)` but
how do I declare the loggers used in classes in other modules / packages, so
they use the same handlers like the main logger? To recognize the 'parent' I
can use `logger = logging.getLogger(parent.child)` but where do I know, who
has called the class/method?`
The example below shows my problem, if I run this, the output will only have
the `__main__` logs in and ignore the logs in `Class`
This is my **Mainfile:**
# main.py
import logging
from module import Class
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create file handler which logs info messages
fh = logging.FileHandler('foo.log', 'w', 'utf-8')
fh.setLevel(logging.INFO)
# create console handler with a debug log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# creating a formatter
formatter = logging.Formatter('- %(name)s - %(levelname)-8s: %(message)s')
# setting handler format
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
if __name__ == '__main__':
logger.info('Script starts')
logger.info('calling class Class')
c = Class()
logger.info('calling c.do_something()')
c.do_something()
logger.info('calling c.try_something()')
c.try_something()
**Module:**
# module.py
imnport logging
class Class:
def __init__(self):
self.logger = logging.getLogger(__name__) # What do I have to enter here?
self.logger.info('creating an instance of Class')
self.dict = {'a':'A'}
def do_something(self):
self.logger.debug('doing something')
a = 1 + 1
self.logger.debug('done doing something')
def try_something(self):
try:
logging.debug(self.dict['b'])
except KeyError, e:
logging.exception(e)
Output in **console:**
- __main__ - INFO : Script starts
- __main__ - INFO : calling class Class
- __main__ - INFO : calling c.do_something()
- __main__ - INFO : calling c.try_something()
No handlers could be found for logger "module"
Besides: Is there a way to get the module names were the logs ocurred in my
logfile, without declaring a new logger in each class like above? Also like
this way I have to go for `self.logger.info()` each time I want to log
something. I would prefer to use `logging.info()` or `logger.info()` in my
whole code.
Is a global logger perhaps the right answer for this? But then I won't get the
modules where the errors occur in the logs...
And my last question: Is this pythonic? Or is there a better recommendation to
do such things right.
Answer: You should have one global logger with your handlers:
logger= logging.getLogger("myapp")
#configure handlers
Then, on each module:
`logger= logging.getLogger("myapp."+__name__)`
Whether you need per-class loggers is up to you - most projects I've seen have
(at most) one logger per module. My advice is, if you don't need different
handlers for different classes, stick with one logger per module, or even one
logger per project - if the project is small.
If you need more context on your logs, note you can print the current function
name using `%(funcName)s` on the formatter
|
Can Python's comprehensions make groups?
Question: I have a list that looks like
[(1,2,5),(2,10,13),(5,24,56),(1,8,10),(2,3,11)]
How can I produce a dictionary by grouping by first element of tuples and
finding `min` element in second elements and `max` element in third elements:
{1:(2,10),2:(3,13),5:{24,56}]
Answer: You can, if you first _sort_ on the grouping element, then use
[`itertools.groupby()`](https://docs.python.org/2/library/itertools.html#itertools.groupby)
to group your elements and test for minimum and maximum values. Because the
groups are generators, you need to jump through an extra hoop to turn that
into a list you can reuse for the `min()` and `max()` functions:
from itertools import groupby
from operator import itemgetter
result = {k: (min(item[1] for item in gv), max(item[2] for item in gv))
for k, g in groupby(sorted(inputlist, key=itemgetter(0)), itemgetter(0))
for gv in (list(g),)}
Note that this sorts (O(NlogN)) then loops over each group twice to find the
minimum and maximum of each group, adding another 2N to the total.
The additional `for gv in (list(g),)` loop assigns a list to `gv` containing
all elements from the `g` group.
The simple loop version would be:
result = {}
for key, v1, v2 in inputlist:
minimum, maximum = result.get(key, (float('inf'), float('-inf')))
if v1 < minimum:
minimum = v1
if v2 > maximum:
maximum = v2
result[key] = (minimum, maximum)
This is a straightforward O(N) loop, and more readable to boot.
Demo of the two approaches:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> inputlist = [(1,2,5),(2,10,13),(5,24,56),(1,8,10),(2,3,11)]
>>> {k: (min(item[1] for item in gv), max(item[2] for item in gv))
... for k, g in groupby(sorted(inputlist, key=itemgetter(0)), itemgetter(0))
... for gv in (list(g),)}
{1: (2, 10), 2: (3, 13), 5: (24, 56)}
and
>>> result = {}
>>> for key, v1, v2 in inputlist:
... minimum, maximum = result.get(key, (float('inf'), float('-inf')))
... if v1 < minimum:
... minimum = v1
... if v2 > maximum:
... maximum = v2
... result[key] = (minimum, maximum)
...
>>> result
{1: (2, 10), 2: (3, 13), 5: (24, 56)}
|
Python Storing and Retrieving Date into Sqlite3 database
Question: I am aware of this [similar question on
SO](http://stackoverflow.com/questions/1829872/read-datetime-back-from-sqlite-
as-a-datetime-in-python) which is basically asking about the same thing.
However, I seems to be getting an error message. Let me explain.
In order to test the idea of Storing and Retrieving Python Date object with
Sqlite3 database, I have created this small test script:
import sqlite3
import datetime
conn = sqlite3.connect("test.db")
conn.execute('''CREATE TABLE TEST
(
ID TEXT PRIMARY KEY NOT NULL,
DATE TIMESTAMP
);''')
conn.commit()
mydate = datetime.date(2014,4,28)
myid = 'test'
conn.execute("INSERT INTO TEST (ID,DATE)\
VALUES(?,?)",[myid,mydate])
conn.commit()
conn.close()
conn = sqlite3.connect("test.db")
cursor = conn.execute("SELECT ID,DATE from TEST")
for row in cursor:
retrievedDate = row[1]
print retrievedDate,type(retrievedDate)
conn.close()
The code works but the retrieved date is in `unicode`.
I found out from the above link that without the
`detect_types=sqlite3.PARSE_DECLTYPES` parameters sqlite will return unicode.
So, I have changed the code like this:
...
conn = sqlite3.connect("test.db",detect_types=sqlite3.PARSE_DECLTYPES)
cursor = conn.execute("SELECT ID,DATE from TEST")
for row in cursor:
retrievedDate = row[1]
print retrievedDate,type(retrievedDate)
...
But now it's giving me this error message:
File "C:\Python27\lib\sqlite3\dbapi2.py", line 66, in convert_timestamp
datepart, timepart = val.split(" ")
ValueError: need more than 1 value to unpack
What is causing the problem?
Answer: You declared the column to be a timestamp:
conn.execute('''CREATE TABLE TEST
(
ID TEXT PRIMARY KEY NOT NULL,
DATE TIMESTAMP
);''')
Make it type `DATE` instead; Python picks a converter based on the column type
and `TIMESTAMP` triggers the wrong converter here.
Demo:
>>> import sqlite3
>>> import datetime
>>> conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
>>> conn.execute('''CREATE TABLE TEST (ID TEXT PRIMARY KEY NOT NULL, DATE DATE)''')
<sqlite3.Cursor object at 0x104a5adc0>
>>> conn.commit()
>>> conn.execute("INSERT INTO TEST (ID,DATE) VALUES (?, ?)",
... ('foo', datetime.date(2014,4,28)))
<sqlite3.Cursor object at 0x104a5ae30>
>>> conn.commit()
>>> cursor = conn.execute("SELECT ID,DATE from TEST")
>>> for row in cursor:
... print row
...
(u'foo', datetime.date(2014, 4, 28))
Alternatively, include the type name in the `SELECT` query in square brackets:
cur.execute('SELECT ID, DATE [date] from TEST')
|
Python CSV take square root of data in the field
Question: I have a CSV file containing numbers in the fields,

I write a script, trying to take square root of numbers in every field in this
CSV file,
import sys, os
import csv, math
import tempfile
import shutil
element = []
filename = 'test.csv'
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
writer = csv.writer(g, delimiter = ',')
for row in csv.reader(f):
element = element in row
row = math.sqrt(element)
writer.writerow([row])
shutil.move(g.name, filename)
But the output is not what I want,

What should I edit my script?
Answer: I think you're overcomplicating things. Try something like:
import numpy as np
data = np.loadtxt('input.csv', delimiter=',')
data = np.sqrt(data)
data = np.where(np.isnan(data), 0, data)
np.savetxt('output.csv', data, delimiter=',')
Note: This assumes you're not reading in irregularly structured data.
|
Tornado Url Not Match with ? ("Interrogation") Sign
Question: I'm using tornado to create a web service. I learn many ways to handle URLs
but i can't find a way to handle this URLS:
> Main-Dns:xxxx(port)/{System}(this is static)/{word}?q={word}
My code:
import tornado.ioloop
import tornado.web
import psycopg2
import json
import collections
import datetime
import decimal
application = tornado.web.Application([
(r"/system/(\w+)[?][q]=[\w+]",MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
I tried many regex only when i erase the '?' it works
for example for this URLs get the uri:
uri:/system/4?q=
handler:r"/system/(\d)[?]q=",MainHandler
uri:/system/word_word?q=
handler:r"/system/(\w+)[?][q]=",MainHandler
The parameter is optional i only put the "()" to test sending parameter.
I used Python regex tester web, and find that i worked but in Tornado i think
it's not the same thing.
Thanks in advance.
Edit: more examples
Handle:/system/(\w+)[?]q=(\w+)
URL examples : /system/(any_word)?q=(any_word) like
/system/word_word?q=word
/system/wo5d_w5rd?q=w5ord
Edit: This is the console output:
WARNING:tornado.access:404 GET/system/test?q=test
I can do without the '?' but i need to do it with the '?'.
Edit: With method get_argument(), it's something like this posible:
Uri:/system/word?{last_name='Jackson_Smith'}
to get this parameters: "word" , "last_name" , "'Jackson_Smith'"
Answer: You don't want to try to capture the "?q=.." in the regular expression. You
capture that in the `RequestHandler` itself, using the `get_argument` method.
Here's a small example that I think captures what you're trying to do:
#!/usr/bin/python
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self, word=None):
self.write("word is %s\n" % word)
self.write("uri is %s\n" % self.request.uri)
self.write("q is %s\n" % self.get_argument("q"))
application = tornado.web.Application([
(r"/system/(.+)",MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Here's sample output:
dan@dan:~$ curl localhost:8888/system/4?q=44d
word is 4
uri is /system/4?q=44d
q is 44d
dan@dan:~$ curl localhost:8888/system/word_word?q=word
word is word_word
uri is /system/word_word?q=word
q is word
dan@dan:~$ curl localhost:8888/system/wo5d_w5rd?q=w5ord
word is wo5d_w5rd
uri is /system/wo5d_w5rd?q=w5ord
q is w5ord
|
How do you make a database using sqlite3 in python
Question: I'm trying to make a .db file which as a 1 to many realntionshp in it and it
will not work.
from sqlite3 import *
$sqlite3 testDB.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
CREATE TABLE BOOKS(
ISBN TEXT PRIMARY KEY NOT NULL,
TITLE TEXT NOT NULL,
ATHOUR TEXT NOT NULL,
NUMBEROFCOPIES INT NOT NULL,
OUTNUMBER INT NOT NULL);
CREATE TABLE LOANS(
ORDERNUMBER TEXT PRIMATY KEY NOT NULL,
FOREIGN KEY (ISBN) REFERENCES BOOKS
TILLE TEXT NOT NULL,
AUTHOR TEXT NOT NULL,
PERSON TEXT NOT NULL,
DUEDATE TEXT NOT NULL);
Answer: You can take a look at pySQLite. It's a package that will allow you to dev
databases within Python use sqlite, but from what I'm seeing, it isn't as
widely available.
If I were you, I'd take a good look at using MySQL and then wrapping it with
mysql-python.
<https://wiki.python.org/moin/MySQL>
and
<http://code.google.com/p/pyodbc/>
Will be great places to start. The getting started page on the Google link has
some great examples of pulling in a database to Python.
I hope this helps!
|
Python For In Loop Matrix for User Input
Question: So I have been searching on Overflow for a few days now for a problem that I
am working on. I understand the communities efforts to curb the homework
questions, but I am stumped and would like to learn this concept and move on
to learn more programming.
In Python I am developing a Matrices or 2D Array.
Here are the Array's Programming requirements from the user and comparing the
value to the arrays value:
Then ask the user to enter both the first name and last name of one of the
users in the matrix, then print the corresponding information (entire row) for
that person if found; if not found, print 'User Not Found!'
Here's what I have so far on that array.
rows = 5
cols = 7
names_matrix = ([['lname', 'fname', 'city', 'state', 'zipcode'],
['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',
'Alfonso'],
['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',
'Denver','Gastonia'],
['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])
print names_matrix
#Create a Boolean variable flag.
found = False
#Create a variable to use as a loop counter.
index = 0
#Get the strings to search for.
for in names_matrix: #Having problems here with what goes here in For In Loop
userFirstName = raw_input('What is the user first name?')
userLastName = raw_input('What is the user last name?')
if userFirstName == names_matrix [1] and userLastName == names_matrix [0]:
print('')
#I want to print the Matrix value from the user input
else
print('User Not Found!')
# nested find columns
# http://stackoverflow.com/questions/7845165/how-to-take-input-in-an-array-python
I'm new to python and programming and have seen in the book how they made this
with a While Loop with the false and index. I was having difficulty understand
pass by values and references I think as well.
# Get the string to search for.
searchValue = raw_input('Enter a name to search for in the list: ')
# Step through the list searching for the
# specified name.
while found == False and index < len(names):
if names[index] == searchValue:
found = True
else:
index = index + 1
# Display the search results.
if found:
print 'That name was found in element ' + str(index + 1)
else:
print 'That name was not found in the list.'
I was wondering how to do this with a For In Range Loop. It might be a Nested
Loop and those are a bit more tricky.
I don't believe I need the boolean flag or index part at the beginning of my
coding for a For In range loop. I was just showing my progress so far and was
trying to get this program to work better.
I researched the following helpful links for For In Range but was getting
stumped.
[For In input in an Array](http://stackoverflow.com/questions/7845165/how-to-
take-input-in-an-array-python)
[Array For In ](http://stackoverflow.com/questions/22441259/finding-several-
regions-of-interest-in-an-array)
[Testing User Input in
Array](http://stackoverflow.com/questions/3944655/testing-user-input-against-
a-list-in-python)
[Python If Else Nested
Statements](http://stackoverflow.com/questions/16449634/python-nested-if-else-
statements)
We haven't gone over Class and Objects and did see how to do that, and we also
haven't gone over numpy and tried using import numpy and was having some
problems with that as I'm new to numpy as well. I am reading Think Like a CS
with Python as additional help with the class as well as Learn Python the Hard
Way.
Thanks for your time.
Answer: The correct syntax for a `for` loop iteration is:
for x in iterable_object:
# do something with each x
In english, take each item in your `iterable_object`, call it `x`, and perform
some code involving x.
for `range` objects:
for i in range(0,10,1):
print i
This will print the numbers from `0-9`, i.e. `i` will have the value `0` and
is incremented by the third argument `1` until it is of value `10` and will
not reenter the loop which means the last printed value will be `9`.
Python allows for some shorthand calls for this:
for i in range(10):
print i
does the same thing. When one argument is provided is it interpreted as the
upper limit.
ref: [range()](https://docs.python.org/2.7/library/functions.html#range)
In your case you have this data:
names_matrix = ([['lname', 'fname', 'city', 'state', 'zipcode'],
['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',
'Alfonso'],
['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',
'Denver','Gastonia'],
['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])
You probably want information by column correct and ignoring the headers?
iteration 1 - Zdolfalos, Fred, Charlotte, NC, 28210
iteration 2 - Johnson, Malcom, Monroe, NC, 28337
etc ...
This means you want to iterate across the size of your `names_matrix[1]`, the
second object in your list.
L = len(names_matrix[1])
print names_matrix[0][0],names_matrix[0][2],names_matrix[0][2],names_matrix[0][3],names_matrix[0][4]
for i in range(L):
print names_matrix[1][i],names_matrix[2][i],names_matrix[3][i],names_matrix[4][i],names_matrix[5][i]
will give you:
lname fname city state zipcode
Zdolfalos Fred Charlotte NC 28210
Johnson Malcom Monroe NC 28337
Terrell Monkey Broken Pine SC 28974
Wilson Wilson Hogwart VA 27457
Key LeDoor Spot in Road AL 36827
Smith Jim Bob Denver NC 28037
Alfonso Ralph Gastonia NC 28559
It looks like you are trying to perform a search for someone in your data. I
would say to perform the user input before the loop, and then compare as you
have done with the slight change to the indexing performed above.
One note here, I find your data to be arranged in a rather strange manner. I
like it would make more sense to structure it as:
names_matrix = (
[['lname', 'fname', 'city', 'state', 'zipcode'],
['Zdolfalos', 'Fred', 'Charlotte','NC','28210'],
['Malcom', 'Johnson', 'Monroe', 'NC', '28337',],
['Monkey', 'Terrell', 'Broken Pine', 'SC','28974',],
# ...etc...
]
Making the iterations rather simple to iterate through your entries:
for user in names_matrix[1:]: # [1:] means take the list from the 1st element to the end, noted by the lack of a number after the colon (on a 0 based index)
print user
python being the awesomeness that it is, provides very quick and easy
operations for such transformations:
names_matrix = zip(*names_matrix[1:])
The [`zip`](https://docs.python.org/2.7/library/functions.html#zip) function
in this case tells python to take the matrix, excluding the first entry which
are your headers.
([['lname', 'fname', 'city', 'state', 'zipcode'],
['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',
'Alfonso'],
['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',
'Denver','Gastonia'],
['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])
upzip it by each entry, which are your categories
zip( ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith','Alfonso'],
['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road','Denver','Gastonia'],
['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
['28210', '28337', '28974', '27457', '36827', '28037', '28559'] )
and pair across each of these lists by their indexes into `tuple`s:
[ ('Zdolfalos', 'Fred', 'Charlotte', 'NC', '28210'),
('Johnson', 'Malcom', 'Monroe', 'NC', '28337'),
('Terrell', 'Monkey', 'Broken Pine', 'SC', '28974'),
# ... etc ...
]
Now you can iterate across the user and not have to deal with the more complex
indexing that you would need with your current setup.
This can be done as a temporary step for ease of use if you would rather keep
the original data in the format you have it in currently.
Of course you can still do it if you prefer not to alter the data.
userFirstName = raw_input('What is the user first name?')
userLastName = raw_input('What is the user last name?')
L = len(names_matrix[1])
for i in range(L):
if userFirstName == names_matrix[0][i] and userLastName == names_matrix[1][i]:
print('Found!')
else
print('User Not Found!')
This format could perhaps give you some ideas for how to implement what you
are asking
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.