text
stringlengths 226
34.5k
|
---|
POST JSON with python and reading response
Question: I am trying to make a post request in python and I believe I am doing
everything correct. However it is not returning any response. I can't seem to
figure out if there is anything wrong with my request. It seems like there may
be something wrong with the service if I am not getting any response back. Is
there anything inherently wrong with what I've written here?
import json
import urllib2
data = {'first_name': 'John','last_name': 'Smith','email': '[email protected]','phone': '215-555-1212'}
req = urllib2.Request('https://someurl.io/')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
print response.read()
print response.headers
Answer: Honestly, unless you love urllib2, I suggest using
[requests](http://docs.python-requests.org/en/latest/). Here's the same data
code in requests:
import requests
import json
payload = {'first_name': 'John','last_name': 'Smith','email': '[email protected]','phone': '215-555-1212'}
url = 'https://someurl.io/'
r = requests.post(url, json=json.dumps(payload))
print r.content
print r.headers
|
python opencv SIFT doesn't work for 8 bit images (JPEG)
Question: I used SIFT for all my other 24 bit JPEG images without any problems, however,
the 8 bit one always give me this following error.
image is empty or has incorrect depth (!=CV_8U) in function cv::SIFT::operator
()
Does anyone know how to deal with it?
Here is my code:
import cv2
import numpy as np
import os
import glob
import scipy.cluster
os.chdir('\mydirectory')
images = []
for infile in glob.glob('./*.jpg'):
pic = cv2.imread(infile,0)
images.append(pic)
my_set = images
descriptors = np.array([])
feaL=np.array([])
for pic in my_set:
kp, des = cv2.SIFT().detectAndCompute(pic, None)
feaL=np.append(feaL,des.shape[0])
descriptors = np.append(descriptors, des)
Then the error "image is empty or has incorrect depth (!=CV_8U) in function
cv::SIFT::operator ()" pops up.
Answer: **EDIT: After typing this I just saw the grayscale flag on imread. Try
printing the images as they are read in, it sounds like imread may be silently
failing and leaving you with empty Mats.**
cv2.SIFT.detectAndCompute never takes anything other than 8-bit grayscale, so
I'm not sure that you actually did use SIFT on a 24 bit image without
problems.
[cv2.SIFT.detectAndCompute](http://docs.opencv.org/trunk/modules/xfeatures2d/doc/nonfree_features.html?highlight=sift#cv2.SIFT.detectAndCompute)
Python: cv2.SIFT.detectAndCompute(image, mask[, descriptors[, useProvidedKeypoints]]) → keypoints, descriptors
So to change to 8 bit grayscale immediately prior to detection and extraction:
for pic in my_set:
pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
kp, des = cv2.SIFT().detectAndCompute(pic, None)
Of course that is a dumb place to put it, but it's up to you to figure out if
you need to keep the BGR originals or not, etc.
|
python get last 5 elements in list of lists
Question: I have a list of lists like this: `[[1, 2], [4, 5, 6], [], None, [7, 12, 14,
16]]`.
I want to write a function that will return: `[16, 14, 12, 7, 6]`: i.e. the
last 5 elements in the list of lists.
This is the code I have, but it is not very pythonic at all (master_list
contains the list above):
def find_last_five():
last_five = []
limit = 5
for sublist in reversed(master_list):
# have to check that list is not None.
if sublist:
for elem in sublist:
last_five.append(elem)
limit -= 1
if (limit == 0):
return last_five
return last_five
Answer: Given your example; I will assume your items in your list are either an
iterable or `None`;
>>> import itertools
>>> lst = [[1, 2], [4, 5, 6], [], None, [7, 12, 14, 16]]
>>> print list(itertools.chain(*[l for l in lst if l is not None]))[-5:]
[6, 7, 12, 14, 16]
|
Extracting float numbers from file using python
Question: I have .txt file which looks like:
[ -5.44339373e+00 -2.77404404e-01 1.26122094e-01 9.83589873e-01
1.95201179e-01 -4.49866890e-01 -2.06423297e-01 1.04780491e+00]
[ 4.34562117e-01 -1.04469577e-01 2.83633101e-01 1.00452355e-01 -7.12572469e-01 -4.99234705e-01 -1.93152897e-01 1.80787567e-02]
I need to extract all floats from it and put them to list/array
What I've done is this:
A = []
for line in open("general.txt", "r").read().split(" "):
for unit in line.split("]", 3):
A.append(list(map(lambda x: str(x), unit.replace("[", "").replace("]", "").split(" "))))
but `A` contains elements like `['']` or even worse `['3.20973096e-02\n']`.
These are all strings, but I need floats. How to do that?
Answer: Why not use a regular expression?
>>> import re
>>> e = r'(\d+\.\d+e?(?:\+|-)\d{2}?)'
>>> results = re.findall(e, your_string)
['5.44339373e+00',
'2.77404404e-01',
'1.26122094e-01',
'9.83589873e-01',
'1.95201179e-01',
'4.49866890e-01',
'2.06423297e-01',
'1.04780491e+00',
'4.34562117e-01',
'1.04469577e-01',
'2.83633101e-01',
'1.00452355e-01',
'7.12572469e-01',
'4.99234705e-01',
'1.93152897e-01',
'1.80787567e-02']
Now, these are the matched _strings_ , but you can easily convert them to
floats:
>>> map(float, re.findall(e, your_string))
[5.44339373,
0.277404404,
0.126122094,
0.983589873,
0.195201179,
0.44986689,
0.206423297,
1.04780491,
0.434562117,
0.104469577,
0.283633101,
0.100452355,
0.712572469,
0.499234705,
0.193152897,
0.0180787567]
Note, the regular expression might need some tweaking, but its a good start.
|
Detect if Windows workstation is locked in PyQt5 application
Question: I have a PyQt5 application, which I would like to check if the Windows
workstation is in a locked state or not.
At first, I have tried to use snippet [See if my workstation is
locked](http://timgolden.me.uk/python/win32_how_do_i/see_if_my_workstation_is_locked.html).
It did not work at all on my Windows 7 64-bit. It thinks that workstation is
locked all the time.
I have noticed in SO question [How to detect Windows is
locked?](http://stackoverflow.com/questions/8606300/how-to-detect-windows-is-
locked) that the above solution is probably a hack and I should use
`WTSRegisterSessionNotification`. I have found the following snippet [Terminal
Services event monitor for Windows
NT/XP/2003/...](https://gist.github.com/grawity/896881). It works fine used as
is.
I have simplified the code to the following:
import win32con
import win32gui
import win32ts
WM_WTSSESSION_CHANGE = 0x2B1
class WTSMonitor():
className = "WTSMonitor"
wndName = "WTS Event Monitor"
def __init__(self):
wc = win32gui.WNDCLASS()
wc.hInstance = hInst = win32gui.GetModuleHandle(None)
wc.lpszClassName = self.className
wc.lpfnWndProc = self.WndProc
self.classAtom = win32gui.RegisterClass(wc)
style = 0
self.hWnd = win32gui.CreateWindow(self.classAtom, self.wndName,
style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
0, 0, hInst, None)
win32gui.UpdateWindow(self.hWnd)
win32ts.WTSRegisterSessionNotification(self.hWnd, win32ts.NOTIFY_FOR_ALL_SESSIONS)
def start(self):
win32gui.PumpMessages()
def stop(self):
win32gui.PostQuitMessage(0)
def WndProc(self, hWnd, message, wParam, lParam):
if message == WM_WTSSESSION_CHANGE:
self.OnSession(wParam, lParam)
def OnSession(self, event, sessionID):
print(event)
if __name__ == '__main__':
m = WTSMonitor()
m.start()
Now I am trying to merge it with PyQt5 skeleton:
import sys
from PyQt5.QtWidgets import *
class Window(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
However, I am not sure how to do that. Every attempt I have made did not work,
the event does not seem to be registered. Any idea how to make this work?
**Edit:** This is one of the merges I have tried.
import sys
from PyQt5.QtWidgets import *
import win32gui
import win32ts
WM_WTSSESSION_CHANGE = 0x2B1
class WTSMonitor(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.show()
win32ts.WTSRegisterSessionNotification(self.winId(), win32ts.NOTIFY_FOR_ALL_SESSIONS)
def start(self):
win32gui.PumpMessages()
def stop(self):
win32gui.PostQuitMessage(0)
def WndProc(self, hWnd, message, wParam, lParam):
if message == WM_WTSSESSION_CHANGE:
self.OnSession(wParam, lParam)
def OnSession(self, event, sessionID):
print(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = WTSMonitor()
win.start()
sys.exit(app.exec_())
Answer: I have adapted ideas from
[WndProcHookMixin.py](http://wiki.wxpython.org/HookingTheWndProc?action=AttachFile&do=view&target=WndProcHookMixin.py)
posted on [wxPython wiki](http://wiki.wxpython.org/HookingTheWndProc) to PyQt.
It works as expected.
import sys
from PyQt5.QtWidgets import *
import win32api
import win32con
import win32gui
import win32ts
WM_WTSSESSION_CHANGE = 0x2B1
WTS_SESSION_LOCK = 0x7
WTS_SESSION_UNLOCK = 0x8
# http://wiki.wxpython.org/HookingTheWndProc
# http://wiki.wxpython.org/HookingTheWndProc?action=AttachFile&do=view&target=WndProcHookMixin.py
# http://wiki.wxpython.org/HookingTheWndProc?action=AttachFile&do=view&target=WndProcHookMixinCtypes.py
class WndProcHookMixin:
def __init__(self):
self.msgDict = {}
def hookWndProc(self):
self.oldWndProc = win32gui.SetWindowLong(self.winId(), win32con.GWL_WNDPROC, self.localWndProc)
def unhookWndProc(self):
win32api.SetWindowLong(self.winId(), win32con.GWL_WNDPROC, self.oldWndProc)
def addMsgHandler(self, messageNumber, handler):
self.msgDict[messageNumber] = handler
def localWndProc(self, hWnd, msg, wParam, lParam):
if msg in self.msgDict:
if self.msgDict[msg](wParam, lParam) == False:
return
if msg == win32con.WM_DESTROY:
self.unhookWndProc()
return win32gui.CallWindowProc(self.oldWndProc, hWnd, msg, wParam, lParam)
class Window(QWidget, WndProcHookMixin):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.show()
win32ts.WTSRegisterSessionNotification(self.winId(), win32ts.NOTIFY_FOR_ALL_SESSIONS)
self.addMsgHandler(WM_WTSSESSION_CHANGE, self.on_session)
self.hookWndProc()
def on_session(self, wParam, lParam):
event, session_id = wParam, lParam
if event == WTS_SESSION_LOCK:
print("Locked")
if event == WTS_SESSION_UNLOCK:
print("Unlocked")
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
|
Send in async mode data using twisted in python
Question: I want to send data to server in async mode (whenever I type something in
console) not only one time as the below code do. Is there any protocol
function within twisted library that can handle this? In the following find
the code that only send a message where the connection is established. On the
other hand I can receive data in async mode via the function dataReceived. Is
any function that will allow me to send messages in async mode as dataReceived
is for receiving.
from twisted.internet import reactor, protocol
class QuoteProtocol(protocol.Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
self.sendQuote()
def sendQuote(self):
self.message(self.factory.quote)
def dataReceived(self, data):
print "Received quote:", data
#self.transport.loseConnection()
class QuoteClientFactory(protocol.ClientFactory):
def __init__(self, quote):
self.quote = quote
def buildProtocol(self, addr):
return QuoteProtocol(self)
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
message = "hello world"
reactor.connectTCP('127.0.0.1', 5000, QuoteClientFactory())
reactor.run()
Answer: If you want to asynchronously process keystrokes from a terminal, you might
have a look at `TerminalProtocol`:
<http://twistedmatrix.com/documents/9.0.0/api/twisted.conch.insults.insults.TerminalProtocol.html>
|
Mocking __main__
Question: I would like to ensure with tests that: \- the application cannot be imported
\- the application can be started as a real application (i.e: python src.py)
I'm interested about that, why the following is not working:
src.py
class A:
def x(self):
print('this is x')
if __name__ == '__main__':
A().x()
test.py (snippet)
class Test(unittest.TestCase):
@mock.patch('src.A.x')
def test_main(self, mock_x):
import src
mock_x.assert_any_call()
This test fails... why?
Answer: Because the name of the module when imported is `src`, not `__main__`.
The easiest solution would be to move that code into a function:
def main():
A().x()
if __name__ == '__main__':
main()
and in your test, you would invoke `src.main()`
@mock.patch('src.A.x')
def test_main(self, mock_x):
import src
src.main()
mock_x.assert_any_call()
|
How to split a csv file on date using python
Question: I have a csv file that contains a date column formatted as "1929-01-10". I
would like to split this huge file into separate files per year. So for every
year in the date column a separate csv file (ideally with the name of the
year).
I would like to do this in Python
Answer: 1. Get src location where we have to write new files. and main CSV file name
2. Use CSV module to reader and write files.
3. Use collection defaultdict module to set every key value type is list.
4. Reader main file and iterate every row from.
5. split first column of each row by `-` to get year value.
6. Use year value as key and append row in result dictionary.
7. Now we have all information into result dictionary.
8. Iterate every item from the result dictionary.
9. again use CSV module to write CSV file.
10. Use key as name of file.
input: main.csv
1929-01-10,1,a
1929-01-10,2,b
1930-01-10,3,c
1929-01-10,4,d
2015-01-10,5,e
2015-01-10,6,f
1929-01-10,7,g
2014-01-10,8,h
code:
src_path = "/home/vivek/Desktop/Work/stack/"
main_file = "/home/vivek/Desktop/Work/stack/main.csv"
import csv
import collections
import pprint
with open(main_file, "rb") as fp:
root = csv.reader(fp, delimiter=',')
result = collections.defaultdict(list)
for row in root:
year = row[0].split("-")[0]
result[year].append(row)
print "Result:-"
pprint.pprint(result)
for i,j in result.items():
file_path = "%s%s.csv"%(src_path, i)
with open(file_path, 'wb') as fp:
writer = csv.writer(fp, delimiter=',')
writer.writerows(j)
output:
Result:-
defaultdict(<type 'list'>, {'2015': [['2015-01-10', '5', 'e'], ['2015-01-10', '6', 'f']], '1929': [['1929-01-10', '1', 'a'], ['1929-01-10', '2', 'b'], ['1929-01-10', '4', 'd'], ['1929-01-10', '7', 'g']], '1930': [['1930-01-10', '3', 'c']], '2014': [['2014-01-10', '8', 'h']]})
some result file according to input file:
1929.csv
1929-01-10,1,a
1929-01-10,2,b
1929-01-10,4,d
1929-01-10,7,g
2015.csv
2015-01-10,5,e
2015-01-10,6,f
|
Python - creating subpackage without exposing internal imports
Question: I have following structure:
/api
/v0
api_1.py
api_2.py
/v1
api_1.py
api_2.py
I would like to use it like that:
import api
api.v0.api_1.notify_user('1337')
However when I do for example `dir(api.v0.api_1)`, I will get not only the API
methods but all the imports that are performed inside. I feel other developers
should not be bothered of what I use internally.
One of the solutions I am considering is to change all internal imports in
api_1 to something like that:
import collections as _collections
to clearly indicate it's not a part of a public API. However, this seems to be
very strange.
How should I solve this puzzle? Or maybe I should not bother at all and what I
am trying to achieve is an overkill?
Answer: Probably you need to import public stuff in `__init__.py`. File structure
should look so:
/api
/v0
__init__.py # import public stuff here
api_1.py
api_2.py
/v1
__init__.py
api_1.py
api_2.py
In the code:
api.v0.notify_user('1337')
|
Error when trying to import from Database with Pandas and SQLAlchemy
Question: I am using portable python 2.7.6.1 and I want to import a query from an oracle
database into python pandas. I have searched a couple of examples and came up
with the following code:
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('oracle://user:pass@host:port/schema', echo=False)
df = pd.read_sql('select * from databasetable', engine, index_col = index)
print df.describe()
The program stops at the 'pd.read_sql'-statement with this Error Message:
AttributeError: 'module' object has no attribute 'read_sql'
The Database connection is working and according to the examples this code
should work. Can anyone help?
Answer: The pandas module imports read_sql from a submodule; you could try getting it
from the submodule:
df = pd.io.sql.read_sql('select * from databasetable', engine, index_col = index)
You could also print `pd.__dict__` to see what's available in the `pd` module.
Do you get `AttributeError` if you try to use other things from the `pd`
module, for example, `pd.Series()`?
|
Collectstatic configuration error when deploying Django website on to Heroku and S3
Question: I am trying to deploy my Django website onto Heroku and Amazon S3. However,
after I typed `git push heroku master`, I got this:
Counting objects: 3, done.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 298 bytes | 0 bytes/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing dependencies with pip
remote:
remote: -----> Preparing static assets
remote: Collectstatic configuration error. To debug, run:
remote: $ heroku run python ./manage.py collectstatic --noinput**
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing... done, 52.0MB
remote: -----> Launching... done, v9
remote: https://article-django.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/article-django.git
4514a97..070a1af master -> master
I type in `heroku run python ./manage.py collectstatic --noinput` and I get
this log:
Running `python ./manage.py collectstatic --noinput` attached to terminal... up, run.4058
/app/static/
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
settings.INSTALLED_APPS
File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in __getattr__
self._setup(name)
File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 94, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/app/django_test/settings.py", line 142, in <module>
AWS_STORAGE_BUCKET_NAME = os.environ['article-deanna']
File "/app/.heroku/python/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'article-deanna'
'article-deanna' is the name of my `AWS_STORAGE_BUCKET_NAME`, as specified in
this snippet in settings.py:
try:
from local_settings import *
except Exception as e:
print e.message
if not DEBUG:
AWS_STORAGE_BUCKET_NAME = os.environ['article-deanna']
AWS_ACCESS_KEY_ID = os.environ['(censored)']
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
S3_URL = 'http://%s.s3.amazonaws.com/assets/' % article-deanna
STATIC_URL = S3_URL
I also have my Procfile:
web: gunicorn django_test.wsgi
And this snippet of the script `activate`:
# added for S3 deployment
export AWS_STORAGE_BUCKET_NAME=article-deanna
export AWS_ACCESS_KEY_ID=(censored)
export AWS_SECRET_ACCESS_KEY=(censored)
I have the correct `AWS_STORAGE_BUCKET_NAME`, so why doesn't Heroku realize
that?
Answer: I think you has to get the env var from name not from value.
here you set "article-deanna" to the variable **AWS_STORAGE_BUCKET_NAME**
`export AWS_STORAGE_BUCKET_NAME='article-deanna'`
and here you has to get the variable back
`AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']`
|
Seemingly nonsensical runtime increases when switching from pure C to C with Numpy objects
Question: # Introduction
I am trying to realise some number crunching on a one-dimensional array in C
(herafter: _standalone)_ and as a Numpy module written in C (herafter:
_module)_ simultaneously. Since all I need to do with the array is to compare
selected elements, I could use an abstraction layer for the array access and
thus I can use the same code for the _standalone_ or the _module._
Now, I expect the _module_ to be somewhat slower, since comparing elements of
a Numpy array of unknown type using `descr->f->compare` requires extra
function calls and similar and thus is more costly than the analogous
operation for a C array of known type. However, when looking at the output of
a profiler (Valgrind), I found runtime increases in the _module_ for lines
which have no obvious connection to the Python methods. I want to understand
and avoid this, if possible.
# Minimal example
Unfortunately, my minimal example is quite lengthy. Note that the Python
variant is no real module anymore due to example reduction.
# include <stdlib.h>
# include <stdio.h>
# ifdef PYTHON
# include <Python.h>
# include <numpy/arrayobject.h>
// Define Array creation and access routines for Python.
typedef PyArrayObject * Array;
static inline char diff_sign (Array T, int i, int j)
{
return T->descr->f->compare ( PyArray_GETPTR1(T,i), PyArray_GETPTR1(T,j), T );
}
Array create_array (int n)
{
npy_intp dims[1] = {n};
Array T = (Array) PyArray_SimpleNew (1, dims, NPY_DOUBLE);
for (int i=0; i<n; i++)
{* (double *) PyArray_GETPTR1(T,i) = i;} // Line A
return T;
}
#endif
# ifdef STANDALONE
// Define Array creation and access routines for standalone C.
typedef double * Array;
static inline char diff_sign (Array T, int i, int j)
{
return (T[i]>T[j]) - (T[i]<T[j]);
}
Array create_array (int n)
{
Array T = malloc (n*sizeof(double));
for (int i=0; i<n; i++) {T[i] = i;} // Line B
return T;
}
# endif
int main()
{
# ifdef PYTHON
Py_Initialize();
import_array();
# endif
// avoids that the compiler knows the values of certain variables at runtime.
int volatile blur = 0;
int n = 1000;
Array T = create_array (n);
# ifdef PYTHON
for (int i=0; i<n; i++)
{* (double *) PyArray_GETPTR1(T,i) = i;} // Line C
# endif
# ifdef STANDALONE
for (int i=0; i<n; i++) {T[i] = i;} // Line D
#endif
int a = 333 + blur;
int b = 444 + blur;
int c = 555 + blur;
int e = 666 + blur;
int f = 777 + blur;
int g = 1 + blur;
int h = n + blur;
// Line E standa. module
for (int i=h; i>0; i--) // 4000 8998
{
int d = c;
do c = (c+a)%b; // 4000 5000
while (c>n-1); // 2000 2000
if (c==e) f*=2; // 3000 3000
if ( diff_sign(T,c,d)==g ) f++; // 5000 5000
}
printf("%i\n", f);
}
I compiled this with the following two commands:
gcc source.c -o standalone -O3 -g -std=c11 -D STANDALONE
gcc source.c -o module -O3 -g -std=c11 -D PYTHON -lpython2.7 -I/usr/include/python2.7
Changing to `-O2` does not change the following; changing the compiler to
Clang does change the minimal example but not the phenomenon with my actual
code.
# Profiling results
The interesting things happen after Line E and I gave the total runtime spent
in those lines as reported by the profiler as comments in the source code:
Despite having no direct relation to whether I compile as _standalone_ or
_module,_ the runtimes for these lines strongly differ. In particular, in my
actual application, the additional time spent in those lines in the _module_
makes up for one fourth of the _module’s_ total runtime.
What’s even more weird is that if I remove line C (and D) – which is redundant
in the example, as the array’s values are already set (to the same values) in
line A (and B) –, the runtime spent in the loop header is reduced from 8998 to
6002 (the other reported runtimes do not change). The same thing happens, if I
change `int n = 1000;` to `int n = 1000 + blur;`, i.e., if I make `n` unknown
compile time.
This does not make much sense to me and since it has a relevant impact on the
runtime, I would like to avoid it.
# Questions
* Where do these runtime increases come from. I am aware that compilers are not perfect and sometimes work in seemingly mysterious ways, but I would like to understand.
* How can I avoid these runtime increases?
Answer: you have to be very careful when interpreting callgrind profiles. Callgrind
gives you the instruction fetch count, so the number of instructions. This is
not connected to actual performance on modern cpus, as instructions can have
different latencies and throughputs and can be reordered by suitably capable
cpus.
Also you are here matching the instruction fetch to the lines the debug
symbols associate to them. Those do not correspond exactly, e.g. the module
code associates the a register copy and a nop instruction (which are
essentially free in terms of runtime compared to the following division) to
the loop line the source code, while the standalone module associates it to
the line above. You can see that in the machine code tab when using `--dump-
instr=yes` in kcachegrind. This is will have something to do with different
registers being available for the two variants due to the different number of
function calls that imply spilling stuff onto the stack.
Lets look at the modulo loops to see if there is a significant runtime
difference:
module:
400b58: 42 8d 04 3b lea (%rbx,%r15,1),%eax
400b5c: 99 cltd
400b5d: 41 f7 fe idiv %r14d
400b60: 81 fa e7 03 00 00 cmp $0x3e7,%edx
400b66: 89 d3 mov %edx,%ebx
400b68: 7f ee jg 400b58 <main+0x1b8>
standalone:
4005f0: 8d 04 32 lea (%rdx,%rsi,1),%eax
4005f3: 99 cltd
4005f4: f7 f9 idiv %ecx
4005f6: 81 fa e7 03 00 00 cmp $0x3e7,%edx
4005fc: 7f f2 jg 4005f0 <main+0x140>
the difference is one register to register copy `mov %edx,%ebx` (likely again
caused by different register pressure due to earlier function calls) this is
one of the cheapest operations available in a cpu probably around 1-2 cycles
and good throughput, so it should have no measurable effect on the actual wall
time. The `idiv` instruction is the expensive part, it should be around 20
cycles with poor throughput. So the instruction fetch count here is grossly
misleading.
A better tool for such detailed profiling is a sampling profiler like `perf
record/report`. When you run long enough you will be able to single out
instructions that are costing a lot of time, though the actually high sample
counts will also then not match up directly with the slow instructions as the
cpu may execute later independent instructions in parallel with the slow ones.
|
Bizarre looping in python?
Question: I'm new to python, but I come from a basic java background. There are learning
curves to face, and so I'm having troubles. With this loop particularly...
from random import randint;
class simpleAI:
inputMatter = 0;
inputEnergyString = 0;
inputEnergy = 0;
resultMatter = 0;
resultEnergy = 0;
inputMatterMemory = [];
inputEnergyMemory = [];
resultMatterMemory = [];
resultEnergyMemory = [];
searchIndex = 0;
found = 0;
lookin = 0;
lookingEnergy = 0;
def cycle(self):
self.inputMatter = input("Matter: ");
self.inputMatter = int(self.inputMatter, 10);
self.inputMatterMemory.append(self.inputMatter);
self.inputEnergyString = input("Energy: ");
self.inputEnergy = int(self.inputEnergyString, 10);
self.inputEnergyMemory.append(self.inputEnergy);
#Check for an event that resulted in positive energy
while(self.searchIndex < self.resultEnergyMemory.__len__()):
print("we are foring!");
if(self.inputEnergyMemory.__getitem__((self.inputMatterMemory.index(self.inputMatter))) == self.inputEnergy):
print("we are iffy!");
self.resultMatter = self.resultMatterMemory.__getitem__(self.inputMatterMemory.index(self.inputMatter));
self.resultEnergy = self.resultEnergyMemory.__getitem__(self.inputEnergyMemory.index(self.inputEnergy));
self.found = 1;
break;
else:
self.searchIndex = self.searchIndex + 1;
if(self.found == 0):
self.resultMatter = randint(0, 256);
self.resultMatterMemory.append(self.resultMatter);
self.resultEnergy = randint(0, 256);
self.resultEnergyMemory.append(self.resultEnergy);
print("Creating new pair...");
print("Result matter: ", self.resultMatter);
print("Result Energy: ", self.resultEnergy);
elif(self.found == 1):
print("Found positive pair from memory");
print("Result matter: ", self.resultMatter);
print("Result memory: ", self.resultEnergy);
self.inputMatter = 0;
self.inputEnergyString = 0;
self.inputEnergy = 0;
self.resultMatter = 0;
self.searchIndex = 0;
self.found = 0;
It produces the right result the first iteration, but falls back to "creating"
a new pair on other iterations, even when it's supposed to return a pair when
entered in before. What am I doing wrong?
Answer: You made a lot of extra work for yourself. Instead of trying to maintain
multiple parallel arrays, you can simply make a separate class to hold all the
data together and just have a single array of that class to loop through.
from random import randint;
class MatterEnergyData:
def __init__(self, inputMatter, inputEnergy, resultMatter, resultEnergy):
self.inputMatter = inputMatter
self.inputEnergy = inputEnergy
self.resultMatter = resultMatter
self.resultEnergy = resultEnergy
def __str__(self):
return "Result matter: %s\r\nResult energy: %s" % \
self.resultMatter, self.resultEnergy
class simpleAI:
matterEnergyDataPoints = []
def cycle(self):
inputMatter = int(input("Matter: "))
inputEnergy = int(input("Energy: "))
resultObj = None
for obj in self.matterEnergyDataPoints:
if obj.inputEnergy == inputEnergy and obj.inputMatter == inputMatter:
print("Found positive pair from memory")
resultObj = obj
break
if resultObj == None:
print("Creating new pair...")
resultObj = MatterEnergyData(inputMatter, inputEnergy, randint(0, 256), randint(0, 256))
self.matterEnergyDataPoints.append(resultObj)
print resultObj
|
Calculating the totals of odd and even numbers from a file in Python
Question:
def main():
infile = open('numbers.txt','r')
evenTotal = 0
oddTotal = 0
line = infile.readline()
while line != '':
total += int(line)
line = infile.readline()
print('The total for the even numbers is',evenTotal)
print('The total for the odd numbers is',oddTotal)
infile.close()
print('All done!')
main()
I trying to make it so that the program reads the numbers from a file in its
directory and then separates, calculates and displays the total of the two
sets. The thing I am having trouble with is the part in the middle with the
identification of the odds and the evens. I do know that the while loop I have
written in the middle calculates the total but I don't know how to modify it
to make it so it does what I want it to do.
Answer: from itertools you can use the partition recipe to partition into even and odd
and return the sum of those
from itertools import ifilterfalse,imap,ifilter,tee
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return ifilterfalse(pred, t1), ifilter(pred, t2)
def is_odd(x):
return bool(x%2)
list_of_ints = imap(int,filter(lambda x:x.strip().isdigit(),infile))
odds, evens= partition(is_odd,list_of_ints)
print sum(evens),sum(odds)
it will likely be a little bit slower than freddies answer ... but it is a
good pattern to know
or as @JonClements [pointed
out](http://chat.stackoverflow.com/transcript/message/21653318#21653318) in
chat
r = range(11)
d = dict.fromkeys([0, 1], 0)
for i in r: d[i % 2] += i
is a neat way to do it
|
Using django variables in Javascript
Question: My model lop is contains a list of programs which I use for varying purposes.
I want to use the name field as an argument for a javascript function.
I modified some of my lops so the modified versions have a "ver2" at the end
of its name. What the Javascript function does is that it checks for the
suffix "ver2" of the program. The javascript was originally found from
[here](http://stackoverflow.com/questions/280634/endswith-in-javascript).
I read some similar questions and one of them said that [I need to serialize
the object](http://stackoverflow.com/questions/16740546/passing-python-
objects-to-javascript-through-django-template-variable)
EDIT: Expanded view of views.py, Javascript console started working and now is
included.
In my views.py (UPDATED)
from django.core import serializers
.
.
.
.
def loppage(request):
jsondata = serializers.serialize('json', lop.objects.all(),fields=('name'));
## get programs
data = []
types = Type.objects.all()
for type in types:
data.append([type.title, type.script_set.all()])
context = {'lop': Lop.objects.all(), 'cat': data, 'jsondata':jsondata}
## render list
return render(request, 'loppage.html', context)
In my templates file: Javascript/HTML (loppage.html):
<script>
function endsWithsuffix(progname, suffix) {
return progname.indexOf(suffix, progname.length - suffix.length) !== -1;}
</script>
.
.
.
.
{% for lop in type %}
<p id="Options"><i>{{lop.options}}</i></p>
<p id="Id"><a href="/ne/{{lop.id}}/">{{lop.name}}</a></p>
<script type="text/javascript">
if (endsWithsuffix({{jsondata}}, 'ver2')) { //This I've tried with and without quotation marks, and with lop.name with and without quotation marks
document.getElementById('Options').style.visibility = 'visible';
document.getElementById('Id').style.visibility = 'visible';
}
else {
document.getElementById('Options').style.visibility = 'hidden';
document.getElementById('Id').style.visibility = 'hidden';
}
</script>
{% endfor %}
But for whatever reason, the script doesn't seem to load (it loads as if the
script wasn't even though).
As wardk suggested, I have now included my Javascript console which can be
seen here
SyntaxError: invalid property id loppage:56:28
It's a long repetition of this same error on the same line as shown below
Debugger console highlights
if (endsWithsuffix([{"pk": 2, "model": "programs.lop",
I've been working on this way longer than I should but I can't get anywhere
with it. Help.
Answer: You're applying endsWithSuffix on a json representation of lop.objects.all().
Shouldn't you test endsWithSuffix for {{lop.name}} instead?
|
How to merge XML string with XML created by objectify?
Question: I am using python 2.7
I currently have a procedure in place that generates orders in XML from csv
data that works. However everything is hardcoded, and I want to make it a bit
more dynamic as I expand the code to fit more clients.
As it stands, I have a section that adds basic info such as ship to and bill
to address to the order
from lxml import objectify
E = objectify.E
fileElem = E.request(
E.customerID("###"),
E.userID("####"),
E.btNameCompany("BillToCompany"),
E.btAttention("John Snow"),
E.btStreet("123 Any Street"),
E.btAddress2(),
E.btAddress3(),
E.btCity("City"),
E.btState("State"),
E.btZip("12345"),
E.btCountry("USA"),
E.btTelephone(),
E.btEmail(),
E.customerPO(customerPO),
E.stNameCompany(shipToCompany),
E.stAttention(shipToAttn),
E.stStreet(shipToAddr),
E.stAddress2(shipToAddr2),
E.stCity(shipToCity),
E.stState(shipToState),
E.stZip(shipToZip),
E.stCountry(shipToCountry),
E.shipMethod("FedEx Ground"),
E.stTelephone(shipToPhone),
E.shipNotificationEmail(shipToEmail),
E.shipperID("ShipperCompanyID"),
E.messages(),
)
From there I've been appending product info by calling a function that returns
a product built the same way, with hardcoded tags.
def getProductXML(sku, qty):
productList = {"Company Brochure":
E.item(
E.quantity(qty),
E.productID("ID #"),
E.productDesc("Description")
),
"Company Product":
E.item(
E.quantity(qty),
E.productID("ID #"),
E.productDesc("Description")
),}
return productList[sku]
fileElem.append(getProductXML(sku, qty))
I've made some adjustments that allows me to add whatever tags a particular
item needs by setting up an excel file. Each item occupies two rows. One row
is tags, the other row is content, with a sku in the first column as an
identifier.
sku | qty | product ID | random attribu | random attribu2
sku | 1 | thing1 | English | z fold
So I have added a bit of code that runs through the excel document and
generates XML as string. I chose to create a string because running a loop
within objectify caused errors. I was also not able to use variables as the
tags, so if variable = "quantity", `E.variable(qty)` becomes
`<variable>qty</variable>` rather than `<quantity>qty</quantity>`.
from lxml import etree as ET
def GetItemXML(sku,qty)
def HeaderRows(r_sheet, rows, cols ):
headerRows = {}
for row in range(0,rows):
if row%2 == 0:
headerRow = []
for col in range(0,cols):
if col == 0:
thecell=r_sheet.cell(row-1,col)
headerSKU = str(thecell.value)
else:
thecell=r_sheet.cell(row,col)
header = str(thecell.value)
headerRow.append(header)
headerRows[headerSKU] = headerRow
else: continue
return headerRows
def ContentRows(r_sheet, rows, cols ):
contentRows = {}
for row in range(0,rows):
if row%2 == 1:
contentRow = []
for col in range(0,cols):
if col == 0:
thecell=r_sheet.cell(row,col)
contentSKU = str(thecell.value)
else:
thecell=r_sheet.cell(row,col)
content = str(thecell.value)
contentRow.append(content)
contentRows[contentSKU] = contentRow
## print contentSKU
else: continue
return contentRows
def getItemXML(sku, qty, contentRows, headerRows):
skuExists = True
string = ""
##################################### INSERT LOGIC TO ADD PROPER PRICING, QTY, AND SHIPPING WEIGHT BASED ON QTY ENTERED ####################################
try:
columnIndex = 0
for column in headerRows[sku]:
string = string + ET.tostring(E(column, contentRows[sku][columnIndex]))
columnIndex +=1
except: skuExists = False
return string, skuExists
This outputs the following string
'<quantity>1</quantity><numPages>1</numPages><padding>0</padding><versions>0</versions><price>$$.$$</price><productID>ProdID#</productID><productDesc>Product Description</productDesc><device>0</device><inksF>4</inksF><inksB>0</inksB><runW>##.00000</runW><runH>##.00000</runH><cutW>##.00000</cutW><cutH>##.00000</cutH><productType>Inventory</productType><coatingID>0</coatingID><foldingID></foldingID><scoreID>0</scoreID><bindID>0</bindID><proofID>0</proofID><mailID>0</mailID><listID>0</listID><customerDataListID>0</customerDataListID><note></note><memo></memo><weight>16.0</weight><isCanvas></isCanvas><artID>28933</artID><mapingID>0</mapingID><customerApproval>accepted</customerApproval>'
However I cannot turn this string back into XML
>>> root = objectify.fromstring(string)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
root = objectify.fromstring(string)
File "lxml.objectify.pyx", line 1802, in lxml.objectify.fromstring (src/lxml/lxml.objectify.c:22312)
File "lxml.etree.pyx", line 3032, in lxml.etree.fromstring (src/lxml/lxml.etree.c:68292)
File "parser.pxi", line 1786, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:102641)
File "parser.pxi", line 1674, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:101470)
File "parser.pxi", line 1074, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:96652)
File "parser.pxi", line 582, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:91461)
File "parser.pxi", line 683, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:92647)
File "parser.pxi", line 622, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:91943)
XMLSyntaxError: Extra content at the end of the document, line 1, column 14
>>>
OR
>>> ET.XML(string)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
ET.XML(string)
File "lxml.etree.pyx", line 3012, in lxml.etree.XML (src/lxml/lxml.etree.c:68047)
File "parser.pxi", line 1786, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:102641)
File "parser.pxi", line 1674, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:101470)
File "parser.pxi", line 1074, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:96652)
File "parser.pxi", line 582, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:91461)
File "parser.pxi", line 683, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:92647)
File "parser.pxi", line 622, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:91943)
XMLSyntaxError: Extra content at the end of the document, line 1, column 14
Can someone please recommend a way to combine the xml in string form with the
xml I am generating through objectify?
Thank you.
Answer: The output string as you posted above is not a valid XML. XML only allowed to
have one root element, but your string has multiple root elements, something
like :
<quantity>1</quantity>
<numPages>1</numPages>
<padding>0</padding>
.....
.....
One possible way around this is by wrapping the string within single root
element, for example :
valid_xml_string = '<root>' + string + '</root>'
root = objectify.fromstring(valid_xml_string)
|
How to get turtle graphics to not show turtle while its being drawn?
Question: How do I get the final drawing to display without having to show the process
of drawing? I am using Python 3.4, and this project is to create an archery
game. For example, if I use the following code:
import turtle
screen = turtle.Screen()
turtle.circle(10)
A circle with a radius of ten is drawn with an arrow, but I just want a circle
shape without seeing it being drawn.
Answer: You need to hide the turtle:
turtle.hideturtle()
And then set the speed to fastest:
turtle.speed(0)
|
Running Twisted on Azure Websites
Question: Can Azure Websites host Twisted applications? e.g. something like:
from twisted.internet import reactor
from twisted.web import server
site = server.Site(myresource)
reactor.listenTCP(80, site)
reactor.run()
From <http://azure.microsoft.com/en-us/documentation/articles/web-sites-
python-configure/> it sounds like only WSGI apps are supported, but just
wanted to confirm from an Azure Websites expert that there's no way to
directly run something like the above.
\--
This excerpt from discussion with Glyph (Twisted author) in the #twisted.web
IRC channel covers the Twisted half of this question:
16:53:28 glyph: twisted has a WSGI _container_
16:53:34 glyph: twisted _is not_ a WSGI application
16:53:36 glyph: in any part
16:53:43 glyph: so you can't make twisted into a WSGI app
16:53:55 glyph: you can maybe invoke some Twisted code _from_ a WSGI app
16:54:05 glyph: but what that example is doing is speaking HTTP, and WSGI applications have to speak WSGI, they are not allowed to speak HTTP directly.
16:56:47 tos9: crochet?
16:56:56 glyph: tos9: crochet can't eat the inbound HTTP socket
16:56:58 glyph: tos9: so it doesn't help
16:57:11 glyph: you could write a thing that did the _outgoing_ traffic with Twisted, but since you can't handle the inbound request, you're bummed
16:57:37 glyph: basically Twisted's job is doing network I/O and if you're inside a WSGI stack, someone else is already doing the job of doing the network I/O
If there is in fact no way to directly run something like this, it seems like
choosing a language other than Python buys you more flexibility on Azure
Websites. For example, from <http://azure.microsoft.com/en-
us/documentation/articles/web-sites-nodejs-develop-deploy-mac/> it looks like
you can host a Node app on Azure Websites which speaks HTTP directly.
Confirmations or corrections gratefully received.
Answer: Please check [https://social.msdn.microsoft.com/Forums/en-
US/ed1c80c4-4621-4d02-8902-6ecc1166ac8c/running-twisted-on-azure-
websites?forum=windowsazurewebsitesprevie&prof=required](https://social.msdn.microsoft.com/Forums/en-
US/ed1c80c4-4621-4d02-8902-6ecc1166ac8c/running-twisted-on-azure-
websites?forum=windowsazurewebsitesprevie&prof=required) for answer.
As you described in [Running Twisted on Azure
Websites](http://stackoverflow.com/questions/28620060/running-twisted-on-
azure-websites) .
What you said is right. For node.js, you can host a Node app on Azure Websites
which speaks HTTP directly. Please refer to
<http://blogs.msdn.com/b/hanuk/archive/2012/05/05/top-benefits-of-running-
node-js-on-windows-azure.aspx>
For Python, there's no direct way run twiisted code via http.
|
How to perform addition and division in python
Question: I want to get the sum of all numbers within a list. My code is shown below;
however, I am getting an error when I try to run it:
c = [795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
x = x + c1
I am also trying to divide one number by another. However, the result is
always zero:
y=(273591/21247633)*100
Answer: In the first case, you need to define `x` before you use it and use `c1`
instead of `c`:
x = 0
c=[795557,757894,711411,556286,477322,426243,361643,350722]
for c1 in c:
x=x+c1
print x
You can try this code online [here](http://codepad.org/0C0nfi0A).
* * *
In the second case, you need to [use floating point
numbers](http://codepad.org/FfqIghfv) instead of integers:
y=(273591/21247633.0)*100
print y
This is because the result of an integer-integer division in Python 2.x is
_also_ an integer. In this case, `273591 ÷ 21247633 = 0.0128763048571` so the
result is rounded down to `0`.
[This has changed in Python 3.x](https://www.python.org/dev/peps/pep-0238/),
and you can enable the same behavior in Python 2.x as follows:
from __future__ import division
y=(273591/21247633)*100
print y
|
Python - how to refer main app's variable in app's modules
Question: I have following files' structure for Flask app (/env is virtual env):
/env
/env/bin/...
/env/include/...
/env/lib/...
/env/lib64/...
/env/myapp.py
/mymodules/__init__.py
/mymodules/users/__init__.py
/mymodules/users/controller.py
myapp.py has below content:
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request, current_app
from flask.ext.sqlalchemy import SQLAlchemy
import mymodules.users.controller as MyMods
app = Flask(__name__)
db = SQLAlchemy(app)
# [...]
@app.route(u"/test", methods=['GET'])
def test():
return MyMods.mytest()
if __name__ == u"__main__":
app.run()
Content of controller.py
# -*- coding: utf-8 -*-
def mytest():
return "ok"
Question: how can I use `app` and `db` inside controller.py?
I can pass it as param:
MyMods.mytest(app, db)
def mytest(app_ref, db_ref):
but is it the proper way of doing it?
Answer: You can pass it param as you did or could set module level variables:
# controller.py
some_var = None
def mytest():
print(some_var)
# myapp.py
MyMods.some_var = db
...rest of your code...
As long as `some_var` gets set before `mytest()` gets called.
|
Python Class: Global/Local variable name not defined
Question: I have two sets of code, one which I use 'Class' (Second piece of code) to
manage my code, and the other I just define functions, in my second piece of
code I get a NameError: global name '...' is not defined. Both pieces of code
are are for the same purpose.
from Tkinter import *
import ttk
import csv
USER_LOGIN = "user_login.csv"
class Login:
def __init__(self, master):
frame = Frame(master)
frame.pack()
lment1 = StringVar()
lment2 = StringVar()
self.usernameLabel = Label(frame, text="Username:")
self.usernameLabel.grid(row=0, sticky=E)
self.passwordLabel = Label(frame, text="Password:")
self.passwordLabel.grid(row=1, sticky=E)
self.usernameEntry = Entry(frame, textvariable=lment1)
self.usernameEntry.grid(row=0, column=1)
self.passwordEntry = Entry(frame, textvariable=lment2)
self.passwordEntry.grid(row=1, column=1)
self.loginButton = ttk.Button(frame, text="Login", command=self.login_try)
self.loginButton.grid(row=2)
self.cancelButton = ttk.Button(frame, text="Cancel", command=frame.quit)
self.cancelButton.grid(row=2, column=1)
def login_try(self):
ltext1 = lment1.get()
ltext2 = lment2.get()
if in_csv(USER_LOGIN, [ltext1, ltext2]):
login_success()
else:
login_failed()
def in_csv(fname, row, **kwargs):
with open(fname) as inf:
incsv = csv.reader(inf, **kwargs)
return any(r == row for r in incsv)
def login_success():
print 'Login successful'
tkMessageBox.showwarning(title="Login successful", message="Welcome back")
def login_failed():
print 'Failed to login'
tkMessageBox.showwarning(title="Failed login", message="You have entered an invalid Username or Password")
root = Tk()
root.geometry("200x70")
root.title("title")
app = Login(root)
root.mainloop()
That is the second piece of code ^^^
# **** Import modules ****
import csv
from Tkinter import *
import ttk
import tkMessageBox
# **** Declare Classes ****
lGUI = Tk()
lment1 = StringVar()
lment2 = StringVar()
USER_LOGIN = "user_login.csv"
def in_csv(fname, row, **kwargs):
with open(fname) as inf:
incsv = csv.reader(inf, **kwargs)
return any(r==row for r in incsv)
def login_try():
ltext1 = lment1.get()
ltext2 = lment2.get()
if in_csv(USER_LOGIN, [ltext1, ltext2]):
login_success()
else:
login_failed()
def login_success():
print 'Login successful'
tkMessageBox.showwarning(title="Login successful", message="Welcome back")
def login_failed():
print 'Failed to login'
tkMessageBox.showwarning(title="Failed login", message="You have entered an invalid Username or Password")
lGUI.geometry('200x100+500+300')
lGUI.title('PVH')
lButton = Button(lGUI, text="Login", command=login_try)
lButton.grid(row=3)
label_1 = Label(lGUI, text="Username")
label_2 = Label(lGUI, text="Password")
entry_1 = Entry(lGUI, textvariable=lment1)
entry_2 = Entry(lGUI, textvariable=lment2)
label_1.grid(row=0)
label_2.grid(row=1)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
lGUI.mainloop()
And that is the piece of code that works^
I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:/Users/User/Desktop/PVH_work/PVH_program/blu.py", line 33, in login_try
ltext1 = lment1.get()
NameError: global name 'lment1' is not defined
Any help would be appreciated :D
Answer: In your first code piece, you define the variable 'lment1' in the __init __
method, making it local to that single method. When you then try to access the
same variable in the 'login_try', Python doesn't know what it is.
If you wish to access the variable form wherever in the class, you should
define it on the class level, by setting it on 'self'
def __init__(self, master):
[...]
self.lment1 = StringVar()
[...]
That way, you can access it later with:
def login_try(self):
[...]
ltext1 = self.lment1.get()
[...]
The reason it works in your second code sample, is because you defined it
outside of any class - Making it globally available
|
How to get filename and line number of where a function is called?
Question: When working in Python I always have this simple utility function which
returns the file name and line number from where the function is called:
from inspect import getframeinfo, stack
def d():
""" d stands for Debug. It returns the file name and line number from where this function is called."""
caller = getframeinfo(stack()[1][0])
return "%s:%d -" % (caller.filename, caller.lineno)
So in my code I simply put a couple debug lines like this to see how far we
get before some error occurs:
print d()
# Some buggy code here
print d()
# More buggy code here
print d(), 'here is the result of some var: ', someVar
This works really well for me because it really helps debugging quickly.
I'm now looking for the equivalent in Javascript. I was searching around but I
can't find anything useful (maybe I'm looking for the wrong words?).
Does anybody know how I can create a Javascript function which outputs the
file name and line number from where the function is called? All tips are
welcome!
Answer: The only way I've found to get anything relating to line numbers is to trap
the `window.onerror` function, and when there's an error that will get passed
the error message, the file URL and the line number:
window.onerror = function(msg, url, line) {
alert(msg + "\n" + url + ":" + line);
};
This works for me on Chrome - I don't know about other browsers.
|
Python Installation Troubleshooting
Question: I am struggling to install Python. I am running Windows 8.1 . Python used to
run OK on my PC but I refreshed Windows recently and now have to install it
again. I did delete the Python folder before I attempt installation and also
made sure an older version was not installed. When I start the IDLE, about 9
IDLE windows open together with the last one which has a script in it :
try:
import idlelib.PyShell
except ImportError:
# IDLE is not installed, but maybe PyShell is on sys.path:
try:
from . import PyShell
except ImportError:
raise
else:
import os
idledir = os.path.dirname(os.path.abspath(PyShell.__file__))
if idledir != os.getcwd():
# We're not in the IDLE directory, help the subprocess find run.py
pypath = os.environ.get('PYTHONPATH', '')
if pypath:
os.environ['PYTHONPATH'] = pypath + ':' + idledir
else:
os.environ['PYTHONPATH'] = idledir
PyShell.main()
else:
idlelib.PyShell.main()
Any help will be appreciated.
Answer: I would do a complete uninstall of the program and reinstall it. Make sure you
also have all windows updates. Just sounds like a bad/corrupted install.
|
Force pyplot.imshow() to produce image with higher resolution
Question: I have an NxN array that I am plotting in Python using
`matplotlib.pyplot.imshow()`. N will be very large and I want my final image
to have resolution to match. However, in the code that follows, the image
resolution doesn't seem to change with increasing N at all. I think that
`imshow()` (at least how I'm using it) has a fixed minimum pixel size that is
larger than that needed to show my NxN array with full resolution.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
array = np.loadtxt("output.dat",unpack=True)
plt.figsize=(30.0, 30.0)
im = plt.imshow(array,cmap='hot')
plt.colorbar(im)
plt.savefig("mandelbrot.pdf")
As you can see in the code above, I've tried messing with `plt.figsize` to try
and increase resolution but to no avail. I've also tried various output
formats (.pdf, .ps, .eps, .png) but these all produced images with lower
resolution than I wanted. The .ps, .eps, and .pdf images all looked the exact
same.
First, does my problem exist with `imshow()` or is there some other aspect of
my code that needs to be changed to produce higher resolution images?
Second, how do I produce higher resolution images?
Answer: `plt.figsize()` will only change the size of the figure in inches while
keeping the default dpi. You can set the resolution of the figure by passing
the `dpi` keyword argument when you save the figure:
fig.savefig('filename.extension', dpi=XXX)
So if you have a figure size of 4x6 and save it with `dpi=300` you'll end up
with an image with 1200x1800 resolution.
You can also set the default figure size and dpi with
[`matplotlibrc`](http://matplotlib.org/users/customizing.html).
|
Why does vars(response) not show response.text? (using Python Requests module)
Question:
import requests
response = requests.get('http://httpbin.org/get')
print vars(response) # no response.text listed
print response.text # value printed
Why does `vars(response)` not list `response.text` when that value exists?
`dir(response)` does list `response.text`, but that does not print the value
of it.
Answer: For the first question, the reason `text` doesn't show up in `vars` is
[because it's a
property](https://github.com/kennethreitz/requests/blob/master/requests/models.py#L741)
(defined by `@property`) as opposed to a class attribute (which is what ends
up in `__dict__` shown by `vars`).
For the second question, this is because the way `dir` and `vars` work.
From the documentation for `vars`:
> vars([object])
>
> Return the **dict** attribute for a module, class, instance, or any other
> object with a **dict** attribute.
>
> Objects such as modules and instances have an updateable **dict** attribute;
> however, other objects may have write restrictions on their **dict**
> attributes (for example, new-style classes use a dictproxy to prevent direct
> dictionary updates).
>
> Without an argument, vars() acts like locals(). Note, the locals dictionary
> is only useful for reads since updates to the locals dictionary are ignored.
And for `dir`:
> The default dir() mechanism behaves differently with different types of
> objects, as it attempts to produce the most relevant, rather than complete,
> information:
>
> If the object is a module object, the list contains the names of the
> module’s attributes. If the object is a type or class object, the list
> contains the names of its attributes, and recursively of the attributes of
> its bases. Otherwise, the list contains the object’s attributes’ names, the
> names of its class’s attributes, and recursively of the attributes of its
> class’s base classes.
So basically `dir` just prints out the attributes of the passed in argument,
_not_ its corresponding value.
Also, [this answer](http://stackoverflow.com/a/981624/193906) is pretty
comprehensive in explaining the differences.
|
In python, why is this (rather messy) code for my simple test base game not working?
Question: This is part of (emphasis on part of) a simple text based adventure that i am
making right now. For some reason every time i run this and say "no" at either
point it still goes ahead and executes the code for "yes". Feel free also to
suggest any ways to clean up this code. I self teach using the internet and
are very new to python so no hate please :).
if path1 == "1":
while breakhold3 == 0:
if path1 == "1":
poi1 = raw_input ("There is a strange artificial hole in the ground. It is surrounded by yellow bricks and vines cover them. Would you like to investigate?")
if poi1 == "Yes" or "yes" or "ye" or "Ye" or "Y" or "y":
print("You crouch down to look in the hole. When you look in, you find that it goes so deep all you can see is blackness. There is a large rock next to the hole.")
if item == "1":
poic1 = raw_input ("You get out the rope and attatch it to the rock. You throw it down the hole and it is at least 2 seconds before you hear it hit the bottom. Would you like to descend the rope?")
if poic1 == "Yes" or "yes" or "Ye" or "ye" or "Y" or "y":
print ("You slowly descend down the rope. It takes about a minute before you get to the bottom. It is dark here, and you begin to feel around the room with your hands.")
from random import randrange
numberboy = randrange(7,10)
if numberboy == 7:
print ("You unluckily fall into a pit!")
health -= 1
if health == 0:
print ("You drop to your knees and lie, filled with pain in the pit. You drop to the floor. Your quest is over.")
print ("Your health has fallen to " + str(health) + ". ")
if numberboy in (8,9):
print ("You could have fallen into a pit but you luckily didn't!")
print ("You find a path leading of to another room.")
print ("You walk down the path and find a light illuminating an elvish sword!")
print ("You walk out of an escape path and find youself coming out of a secret entrance at the clearing.")
breakhold3 += 1
break
if poic1 == "No" or "no" or "n" or "N":
print ("You decide not to descend down the rope. You continue down the path ahead.")
breakhold3 += 1
if poi1 == "no" or "No" or "n" or "N":
print ("You decide not to investigate. You continue down the path ahead.")
breakhold3 += 1
print ("Check")
import time
NOTE: i did breakhold 3 = 0 earlier on.
Answer: The problem is with this type of boolean expression:
if poi1 == "Yes" or "yes" or "ye" or "Ye" or "Y" or "y":
This is what you were trying to do:
if poi1 == "Yes" or poi1 == "yes" or poi1 == "ye" or poi1 == "Ye" or poi1 == "Y" or poi1 == "y":
The problem was that those strings evaluate to `True` by themselves.
A better solution might be to check if `poi1` is in a list of "yes" values:
if poi1.lower() in ["yes", "ye", "y"]:
Simpler, yet:
if poi1.lower().startswith("y"):
Also, remember that you have those incorrect boolean expressions in several
places in your code that you posted.
|
Calculating factorials with Python
Question: EDIT: I know I can import factorials but I'm doing this as an exercise
Trying to get the factor of a given number with a function in Python.
For example: factorial(4) = 4 * 3 * 2 * 1 = 24
def factorial(x):
n = x
while n >= 0:
x = n * (n - 1)
n -= 1
return x
Answer: try like this: to make your code work
def factorial(x):
n = 1 # this will store the factorial value
while x > 0:
n = n*x
x -= 1
return n
you got many advice on comments follow it
|
How to implement a tree structure in Python using namedtuple
Question: I have a key-word, e.g. friendly. It gives birth to a child-word, e.g. warm,
while descending from a parent-word, e.g. friend.
from collections import namedtuple
keyword = 'friendly'
childword = 'warm'
parentword = 'friend'
connect=namedtuple(keyword,'children parents')
output = connect([childword],[parentword])
As a result, I can use output.children to see what are the children of my
nodeword. However, what I really want to do is to type
friendly.children # instead of output.children
to see the children of the key-word friendly. How can I do this? I am
completely new to Python; I am not even sure if this is doable.
Answer: If you want to define a tree structure, you could use a namedtuple for that:
from collections import namedtuple
TreeNode = namedtuple('TreeNode', ['word', 'children'])
friend = TreeNode(word='friend', children=[])
friendly = TreeNode(word='friendly', children=[])
warm = TreeNode(word='warm', children=[])
friend.children.append(friendly)
friendly.children.append(warm)
print(friendly.children)
which comes up with:
[TreeNode(word='warm', children=[])]
That's a very C-like way of doing things though; you're probably better off
having a single Graph or Tree data structure that stores the edge
relationships, eg:
children = dict()
children['friend'] = ['friendly']
children['friendly'] = ['warm']
def parents(word):
ps = []
for k in children:
if word in children[k]:
ps.append(k)
return ps
print(children['friendly'])
print(parents('friendly'))
which comes up with
['warm']
['friendly']
There's an article on [Implementing Graphs in
Python](https://www.python.org/doc/essays/graphs/) available that you might
find useful.
|
XLRD/Python: Encrypte Excel or make exception
Question: I need to go through the subdirectories of a given directory, search for excel
files and then read their sheet names. A problem occurs when the loop finds an
encrypted file. I tried to read files with xlrd and pandas. But I get an
error:
> _xlrd.XLRDError Workbook is encrypted_
I made an exception with pass method, but if I do so, the loop breaks at this
point and the program stops. What do I have to do to pass that error and move
on to the next file? Is there any method to check if the file is encrypted
before the method xlrd.open_workbook which collapses the program? Or is it
possible to make an exception where I could pass the error and move on?
import codecs
import xlrd
import os
import Tkinter
import tkFileDialog
def pyrexcel(path,file,list):
print 'do now: ' + path + '/' + file
workbook = xlrd.open_workbook(path + '/' + file, encoding_override='windows-1250')
sheet_names = workbook.sheet_names()
for sheet in sheet_names:
list.append(path+"/"+file+"/"+sheet)
def finder(destin,listka,list):
for pliczek in os.listdir(destin):
if os.path.isdir(destin +"/" +pliczek):
finder(destin +"/" +pliczek,listka,list)
elif pliczek[-4:] == ".xls":
pyrexcel(destin,pliczek,list)
elif pliczek[-4:] == ".rar" or pliczek[-4:] == ".zip":
listka.append(destin+pliczek)
root = Tkinter.Tk()
root.withdraw()
listaExcel = []
listaZip = []
dirname = tkFileDialog.askdirectory(parent=root, initialdir="/", title='choose dir to iterate')
print "you choose: " + dirname
try:
finder(dirname,listaZip,listaExcel)
except xlrd.XLRDError as e:
print e.message
pass
plik = codecs.open((dirname + "/listaZIP.txt"), 'w', "utf-8")
for item in listaZip:
plik.write("%s\n" % item)
plik.close()
plik = codecs.open((dirname + "/listaExcel.txt"), 'w', "utf-8")
for item in listaExcel:
plik.write("%s\n" % item)
plik.close()
Answer: `continue` should accomplish what you want as listed here:
"pass simply does nothing, **_while continue goes on with the next loop
iteration_**. In your example, the difference would become apparent if you
added another statement after the if: After executing pass, this further
statement would be executed. After continue, it wouldn't."
Also I found this answer while trying to look for a way to find out if an
Excel file is encrypted via python so thank you! :D
Source: [Is there a different between `continue` and `pass` in a for loop in
python?](http://stackoverflow.com/questions/9483979/is-there-a-different-
between-continue-and-pass-in-a-for-loop-in-python)
Python Docs: <https://docs.python.org/2/reference/simple_stmts.html#continue>
|
Displaying an HTML file with a JS inside an iPython notebook
Question: I have a piece of code in an iPython notebook that programmatically generates
a folder named 'sound' containing the following files: index.html, canvas.js,
graph.js and style.css.
If I open index.html in my browser, I can see exactly the output I want: a
graph with a nice JS animation representing vectors in and out of a process I
am modeling.

However, I would like to display the HTML file from inside the iPython
notebook itself.
For that, I type the following code:
from IPython.display import IFrame
IFrame('/Users/useird/Desktop/sound/index.html', width=700, height=350)
Which returns the following: 
I am not an expert with css or js, but I think that iPython can display js
inside an iframe, so what's wrong here?
Thanks
Answer: To explicitly answer this question, I post my comment here again.
IPython uses the [Tornado](http://www.tornadoweb.org) web server engine to
serve the html pages. Per default, the web server cannot access files above
the start directory. Otherwise, this would be a severe security exposure.
Hence, to make your data available for the web server you have to place it in
the notebook starting directory or in a subdirectory.
This applies not only to html pages, but also to images you want to display
using tags.
|
Detecting memory leaks & dumping statistics in python
Question: I am looking for python memory debugging techniques? Basically I am looking at
tools available for python and see what data we can look at when a python
process is taking lot of memory? I am aiming to isolate such memory eating
process and **dump statistics**.
Answer: Take a look at `guppy`
from guppy import hpy
import networkx as nx
h = hpy()
L=[1,2,3]
h.heap()
> Partition of a set of 89849 objects. Total size = 12530016 bytes.
> Index Count % Size % Cumulative % Kind (class / dict of class)
> 0 40337 45 3638400 29 3638400 29 str
> 1 21681 24 1874216 15 5512616 44 tuple
> 2 1435 2 1262344 10 6774960 54 dict (no owner)
This will go a long way towards telling you where lots of memory is being
used.
Python clears memory when an object is no longer accessible - nothing in the
program points to it. Sometimes you might be wondering what on earth is still
pointing to a particular object. For that you might look at [this
question](http://stackoverflow.com/questions/28403750/understanding-gc-get-
referrers) which tells you how about how to find out what things are still
referring to an object.
|
coefficient plot in python
Question: I am trying to find a nice way to plot the linear model coefficient in python
and I got the following:
import statsmodels.formula.api as sm
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
f = 'change ~ close_r + close_f + close_f1 + close_f2 + gender + age + country_of_citizenship + country_of_origin + religion +ethnicity'
reg_results = sm.ols(f, data=data).fit().summary()
sns.set(style="ticks")
mpl.rc("figure", figsize=(10, 15))
sns.coefplot(f,data,intercept=False);
which produces the following ugly plot (you can't see the x axis labels).

How can I rotate the plot to make it vertical (i.e., the swap the y and x axis
in order to see the labels)? and how can I add custom tick names for the
coefficients (other than the default names from the dataframe)?
I am open to alternative solutions/type of plots as well.
Answer: A solution M Waskow himself gave me when I raised the issue:
` ax = plt.gca() plt.setp(ax.get_xticklabels(), rotation=90) `
See <https://github.com/mwaskom/seaborn/issues/576>
Xaxis tick labels can be set with `plt.gca().set_xlabel(list_of_strings)`
|
Cannot import package - "ImportError: No module named _mechanize"
Question: I am using the Anaconda 2.1.0 distribution of Python on Windows 8.
python --version
Python 3.4.1 :: Anaconda 2.1.0 (64-bit)
I used pip to install the mechanize package. pip (v 6.0.8) installed mechanize
0.2.5 which is the most recent release.
But, while trying to import the package, python throws an error:
>>> import mechanize
Traceback (most recent call last):
File "", line 1, in
File "C:\Anaconda3\lib\site-packages\mechanize\__init__.py", line 122, in
from _mechanize import \
ImportError: No module named '_mechanize'
Similar questions here received replies to check if the installation was done
on the `PYTHONPATH`.
I also checked `sys.path` and there seems to be no problem there.
>>> import sys
>>> sys.path
['',
'C:\\Anaconda3\\Scripts',
'C:\\Anaconda3\\lib\\site-packages\\cssselect-0.9.1-py3.4.egg',
'C:\\Anaconda3',
'C:\\Anaconda3\\python34.zip',
'C:\\Anaconda3\\DLLs',
'C:\\Anaconda3\\lib',
'C:\\Anaconda3\\lib\\site-packages',
'C:\\Anaconda3\\lib\\site-packages\\Sphinx-1.2.3-py3.4.egg',
'C:\\Anaconda3\\lib\\site-packages\\win32',
'C:\\Anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\Anaconda3\\lib\\site-packages\\runipy-0.1.1-py3.4.egg',
'C:\\Anaconda3\\lib\\site-packages\\setuptools-12.2-py3.4.egg',
'C:\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\Kumar Siddharth\\.ipython']
I am able to import other packages residing in the same directory, for e.g.
numpy.
Am I missing something?
Answer: Thanks Joe for pointing that out.
Mechanize is not supported for Python 3.x. For my job, I set up a new Python
2.7 environment through `conda` and switched to it. It addressed the issue.
|
Ubuntu and Ironpython: What paths to add to sys.path AND how to import fcntl module?
Question: I have latest IronPython version built and running in Ubuntu 14.04 through
Mono. Building Ironpython and running with Mono seems trivial but I am not
convinced I have proper sys.paths or permissions for Ironpython to import
modules, especially modules like fcntl.
Running ensurepip runs subprocess, and wants to import "fcntl". There are
numerous posts already out there, but mostly regarding windows.
As I understand, fcntl is part of unix python2.7 standard library. To start
the main problem seems to be that Ironpython has no idea where this is, but I
also suspect that since fcntl seems to be perl or at least not pure python,
that there is more to the story.
So my related sys.path questions are:
1. In Ubuntu, where should I install Ironpython (Ironlanguages folder) to? Are there any permissions I need to set?
2. What paths should I add to the sys.path to get Ironpython's standard library found?'
3. What paths should I add to the sys.path to get Ubuntu's python 2.7 installed modules?
4. What paths should I add to the sys.path or methods to get fcntl to import properly in Ironpython
5. Any clues on how to workaround known issues installing pip through ensurepip using mono ipy.exe X:Frames ensurepip
Thanks!
Answer: As far as I can see, the fcntl module of cPython is a builtin module
(implemented in C) - those modules need to be explicitly implemented for most
alternative Python interpreters like IronPython (in contrast to the modules
implemented in plain Python), as they cannot natively load Python C
extensions.
Additionally, it seems that there currently is no such fcntl implementation in
IronPython.
There is a Fcntl.cs in IronRuby, however, maybe this could be used as a base
for implementing one in IronPython.
|
how to avoid two socket with same port number python
Question: Now here is sample for the server part of socket. I want to have serverSocket
and connectionSocket with different port number, but for now, they are using
same port number.
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((‘’,serverPort))
serverSocket.listen(1)
print (‘The server is ready to receive’)
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
if they are using same port number, would there be some collision?
Answer: There is nothing to avoid, and there is really no easy way to avoid it - this
is how TCP is supposed to work.
In TCP there are 2 kinds of sockets:
* listening server sockets
* connected sockets
The server sockets start listening to incoming connections with `listen`; and
wait for client connections with `accept`. Clients create a socket that is
connected to the server address `(host, port)`. When the server `accept`s a
connection, a **new** connected socket is created between the
`(client_address, client_port)` and `(server_address, server_port)`. The TCP
stack on the server can see from **status bits** easily if the packet is a
connection request, or destined to an already connected socket. If it is a
communication between already connected sockets, then it finds out the file
descriptor that is bound on the local address and local port **and** is
connected with the source address, source port of the remote end.
The connected socket will have the same port as the listening server socket;
both Ende of the socket know 4 things: _local address_ , _local port_ ,
_remote address_ and _remote port_. You can have 1 server socket bound on
`10.20.30.40:12345` at the same time with thousands of sockets connected from
`10.20.30.40:12345` to thousands distinct addresses.
There is really congestion only in the connection attempt phase; the
`server_socket.listen(1)` means that the server will queue just 1 incoming
connection; subsequent connections will be rejected until the incoming
connection is accepted.
From Linux manual pages, `listen(2)` on the `backlog` argument of
`sock.listen`:
> The backlog argument defines the maximum length to which the queue of
> pending connections for sockfd may grow. If a connection request arrives
> when the queue is full, the client may receive an error with an indication
> of `ECONNREFUSED` or, if the underlying protocol supports retransmission,
> the request may be ignored so that a later reattempt at connection succeeds.
|
Quickly determining using Python whether an image is (fuzzily) in a collection
Question: Image that some new image X arrives, and I want to know if X is new or has
already been encountered before. I have code, below, that shrinks the image
and then converts it to a hash code. I can then see via a single hash look-up
if I've already encountered an image with the same hash code, so it's very
fast.
My question is, is there an efficient way for me to see if a _similar_ image,
but one with a different hash code, has already been seen? If was going to
title this question something like "Data structure for determining efficiently
whether a similar, non-identical item is already contained" but decided that
would be an instance of [the XY
problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-
problem).
When I say that this new image is "similar," I'm thinking of one that's
perhaps gone through lossy compression and so looks like the original to the
human eye but is not identical. Normally shrinking the image eliminates the
difference, but not always, and if I shrink the image too much I start getting
false positives.
Here's my current code:
import PIL
seen_images = {} # This would really be a shelf or something
# From http://www.guguncube.com/1656/python-image-similarity-comparison-using-several-techniques
def image_pixel_hash_code(image):
pixels = list(image.getdata())
avg = sum(pixels) / len(pixels)
bits = "".join(map(lambda pixel: '1' if pixel < avg else '0', pixels)) # '00010100...'
hexadecimal = int(bits, 2).__format__('016x').upper()
return hexadecimal
def process_image(filepath):
thumb = PIL.Image.open(filepath).resize((128,128)).convert("L")
code = image_pixel_hash_code(thumb)
previous_image = seen_images.get(code, None)
if code in seen_images:
print "'{}' already seen as '{}'".format(filepath, previous_image)
else:
seen_images[code] = filepath
You can put a path to a bunch of image files into a variable called
`IMAGE_ROOT` and then try my code out with:
import os
for root, dirs, files in os.walk(IMAGE_ROOT):
for filename in files:
filepath = os.path.join(root, filename)
try:
process_image(filepath)
except IOError:
pass
Answer: There are a lot of methods for comparing images, but for your given example I
suspect that simplicity and speed are the key factors (hence why you're trying
to use a hash as a first-pass). Here are some suggestions - in all cases I'd
suggest shrinking and cropping the image to a regular size and shape.
1. Smooth the image (gaussian blur) before shrinking to minimise the influence of artefacts. Then apply the hash or other comparison.
2. Subtract the images from one another (RGB) and check the remainder. Identical images will return zero, compression artefacts will result in small minor variations. You can either threshold, sum, or average the value and compare to a cut-off.
3. Use standard distance algorithsm (see `scipy.spatial.distance`) to calculate 'distance' between the two images. For example `euclidean` distance will give effectively the same as the sum of subtracting, while `cosine` will ignore itensity but match the profile of changes over the image i.e. a darker version of the same image will be considered equivalent. For these you will need to flatten your image to a 1D array.
The last two entail comparing every image to every other image when uploading,
and that is going to get very computationally expensive for large numbers of
images.
|
PyQt4 video player crashes when moving window
Question: I've written a simple PyQt4 GUI that plays an OpenCV `VideoCapture`. This
requires converting frames from numpy arrays to `QImages`. I'm using OpenCV so
that I can detect circles using my `findCircles` method.
However, when I pass my frames to `findCircles`, the program crashes when the
window is moved. This problem does not occur when I don't search for circles.
I don't understand why this is happening, as I'm under the impression that the
work is being done on a different thread than the GUI since I call
`findCircles` from the `run` method of a `QThread`.
Note that I don't receive a normal error message in the console; Python
crashes like such:

[Here](https://onedrive.live.com/redir?resid=C7765FC335ABD69D!20797&authkey=!ABcBXD4-RkP91qk&ithint=video%2cMOV)
is the video file I've been using to test my player. I'm running Python 2.7.6
on Windows 8.1.
import sys
import cv2.cv as cv, cv2
from PyQt4.Qt import *
import time
def numpyArrayToQImage(array):
if array != None:
height, width, bytesPerComponent = array.shape
bytesPerLine = bytesPerComponent * width;
cv2.cvtColor(array, cv.CV_BGR2RGB, array)
return QImage(array.data, width, height, bytesPerLine, QImage.Format_RGB888)
return None
def findCircles(frame):
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurredFrame = cv2.medianBlur(grayFrame, 3)
circles = cv2.HoughCircles(blurredFrame, cv.CV_HOUGH_GRADIENT, 1, 30, param1=50, param2=30, minRadius=30, maxRadius=35)
if circles is not None:
for i in circles[0]:
cv2.circle(frame, (i[0], i[1]), i[2], (255, 0, 0), 1) # Perimeter
cv2.circle(frame, (i[0], i[1]), 3, (0, 255, 0), -1) # Center
class VideoThread(QThread):
frameProcessed = pyqtSignal(QImage)
def __init__(self, video, videoLabel):
QThread.__init__(self)
self.video = video
self.fps = self.video.get(cv.CV_CAP_PROP_FPS)
self.frameCount = self.video.get(cv.CV_CAP_PROP_FRAME_COUNT)
self.startingSecond = 0
self.videoLabel = videoLabel
def run(self):
clockAtStart = time.clock()
while True:
runtime = self.startingSecond + (time.clock() - clockAtStart)
currentFrame = int(runtime * self.fps)
if currentFrame < self.frameCount - 1:
self.video.set(cv.CV_CAP_PROP_POS_FRAMES, currentFrame)
frame = self.video.read()[1]
findCircles(frame) # Removing this line removes the issue
self.frameProcessed.emit(numpyArrayToQImage(frame))
time.sleep(.02)
else:
break
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
@pyqtSlot(QImage)
def updateVideoLabel (self, image):
self.videoLabel.setPixmap(QPixmap.fromImage(image))
self.videoLabel.update()
def initUI(self):
self.setGeometry(300, 300, 500, 375)
self.setMinimumHeight(250)
self.createWidgets()
self.addWidgets()
def startNewVideo(self):
self.video = cv2.VideoCapture(unicode(QFileDialog.getOpenFileName(self, "Open video").toUtf8(), encoding="UTF-8"))
self.videoThread = VideoThread(self.video, self.videoLabel)
self.videoThread.frameProcessed.connect(self.updateVideoLabel)
self.playVideoFrom(0)
def playVideoFrom(self, frame):
self.videoThread.startingSecond = frame / self.videoThread.fps
self.videoThread.start()
def createWidgets(self):
self.populateMenuBar()
self.videoLabel = QLabel()
self.videoLabel.setStyleSheet('background-color : black;');
def populateMenuBar(self):
self.menuBar = self.menuBar()
fileMenu = QMenu('File', self)
openAction = QAction('Open video...', self)
openAction.triggered.connect(self.startNewVideo)
fileMenu.addAction(openAction)
self.menuBar.addMenu(fileMenu)
def addWidgets(self):
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.videoLabel, 1)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
centralWidget.setLayout(mainLayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
player = MainWindow()
player.show()
sys.exit(app.exec_())
Answer: I've tested your program, and it crashes when it finds no circles as indicated
in the error message:
Traceback (most recent call last):
File "test_opencv_tkinter.py", line 53, in run
findCircles(frame) # Removing this line removes the issue
File "test_opencv_tkinter.py", line 26, in findCircles
if len(circles) > 0:
TypeError: object of type 'NoneType' has no len()
I've made some changes in the `findCircles(frame)` function, as follows, and
it runs without error, even when I move the window around on the screen.
def findCircles(frame):
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurredFrame = cv2.medianBlur(grayFrame, 3)
circles = cv2.HoughCircles(grayFrame,cv.CV_HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=0)
if circles == None:
print "no circles found"
return
if len(circles) > 0:
print "found circles ", len(circles[0])
for i in circles[0]:
cv2.circle(frame, (i[0], i[1]), i[2], (255, 0, 0), 1) # Perimeter
cv2.circle(frame, (i[0], i[1]), 3, (0, 255, 0), -1) # Center
|
Managing users authentication in Google App Engine
Question: I am working on a webapp based on google app engine. The application uses the
google authentication apis. Basically every handler extends from this
BaseHandler and as first operation of any get/post the checkAuth is executed.
class BaseHandler(webapp2.RequestHandler):
googleUser = None
userId = None
def checkAuth(self):
user = users.get_current_user()
self.googleUser = user;
if user:
self.userId = user.user_id()
userKey=ndb.Key(PROJECTNAME, 'rootParent', 'Utente', self.userId)
dbuser = MyUser.query(MyUser.key==userKey).get(keys_only=True)
if dbuser:
pass
else:
self.redirect('/')
else:
self.redirect('/')
The idea is that it redirects to / if no user is logged in via Google OR if
there is not a User in my db of users having that google id.
The problem is that I can succesfully log in my web app and make operations.
Then, from gmail, o Logout from any google account BUT if i try to keep using
the web app it works. This means the users.get_current_user() still returns a
valid user (valid but actually OLD). Is that possible?
**IMPORTANT UPDATE** I Do Understand what explained in the Alex Martelli's
Comment: There is a cookie which keeps the former GAE authentication valid.
The problem is that the same web app also exploits the Google Api Client
Library for Python <https://developers.google.com/api-client-library/python/>
to perform operations on Drive and Calendar. In GAE apps such library can be
easily used through decorators implementing the whole OAuth2 Flow
(<https://developers.google.com/api-client-
library/python/guide/google_app_engine>).
I therefore have my Handlers get/post methods decorated with oauth_required
like this
class SomeHandler(BaseHandler):
@DECORATOR.oauth_required
def get(self):
super(SomeHandler,self).checkAuth()
uid = self.googleUser.user_id()
http = DECORATOR.http()
service = build('calendar', 'v3')
calendar_list = service.calendarList().list(pageToken=page_token).execute(http=http)
Where decorator is
from oauth2client.appengine import OAuth2Decorator
DECORATOR = OAuth2Decorator(
client_id='XXXXXX.apps.googleusercontent.com',
client_secret='YYYYYYY',
scope='https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.file'
)
It usually works fine. However (!!) when the app is idle for a long time it
happens that the oauth2 decorator redirects me to the Google authentication
page where, if I change account (I have 2 different accounts) Something WEIRD
happens: The app is still logged as the former account (retrieved through
users.get_current_user()) while the api client library, and thus the oauth2
decorator, returns data (drive, calendar, etc.) belonging to the second
account.
Which is REALLY not appropriate.
Following the example above (SomeHandler class) suppose I am logged as Account
A. The users.get_current_user() always returns A as expected. Now suppose I
stopped using the app, after a long while the oauth_required redirects me to
the Google Account page. I therefore decide (or make a mistake) to log is as
Account B. When accessing the Get method of the SomeHandler class the userId
(retrived through users.get_current_user() is A while the list of calendars
returned through the service object (Google Api client Library) is the list of
calendars belonging to B (the actual currently logged user).
Am I doing something wrong? is Something expected?
**Another Update**
this is after the Martelli's Answer. I have updated the handlers like this:
class SomeHandler(BaseHandler):
@DECORATOR.oauth_aware
def get(self):
if DECORATOR.has_credentials():
super(SomeHandler,self).checkAuth()
uid = self.googleUser.user_id()
try:
http = DECORATOR.http()
service = build('calendar', 'v3')
calendar_list = service.calendarList().list(pageToken=page_token).execute(http=http)
except (AccessTokenRefreshError, appengine.InvalidXsrfTokenError):
self.redirect(users.create_logout_url(
DECORATOR.authorize_url()))
else:
self.redirect(users.create_logout_url(
DECORATOR.authorize_url()))
so basically I now use oauth_aware and, in case of none credentials I logout
the user and redirect it to the DECORATOR.authorize_url()
I have noticed that after a period of inactivity, the handler raises
AccessTokenRefreshError and appengine.InvalidXsrfTokenError exceptions (but
the has_credentials() method returns True). I catch them and (again) redirect
the flow to the logout and authorize_url()
It seems to work and seems to be robust to accounts switch. Is it a reasonable
solution or am I not considering some aspects of the issue?
Answer: I understand the confusion, but the system is "working as designed".
At any point in time a GAE handler can have zero or one "logged-in user" (the
object returned by `users.get_current_user()`, or `None` if no logged-in user)
**and** zero or more "oauth2 authorization tokens" (for whatever users and
scopes have been granted and not revoked).
There is no constraint that forces the oauth2 thingies to match, in any sense,
the "logged-in user, if any".
I would recommend checking out the very simple sample at
<https://code.google.com/p/google-api-python-
client/source/browse/samples/appengine/main.py> (to run it, you'll have to
clone the whole "google-api-python-client" package, then copy into the
`google-api-python-client/source/browse/samples/appengine` directory
directories `apiclient/` and `oauth2client/` from this same package as well as
`httplib2` from <https://github.com/jcgregorio/httplib2> \-- and also
customize the `client_secrets.json` \-- however, you don't need to run it,
just to read and follow the code).
This sample doesn't even **use** `users.get_current_user()` \-- it doesn't
need it nor care about it: it only shows how to use `oauth2`, and there is
_no_ connection between holding an `oauth2`-authorized token, and the `users`
service. (This allows you for example to have cron execute on behalf of one or
more users certain tasks later -- cron doesn't log in, but it doesn't matter
-- if the oauth2 tokens are properly stored and retrieved then it can use
them).
So the code makes a decorator from the client secrets, with
`scope='https://www.googleapis.com/auth/plus.me'`, then uses
`@decorator.oauth_required` on a handler's `get` to ensure authorization, and
with the decorator's authorized `http`, it fetches
user = service.people().get(userId='me').execute(http=http)
with `service` built earlier as `discovery.build("plus", "v1", http=http)`
(with a different non-authorized `http`).
Should you run this locally, it's easy to add a fake login (remember, user
login is faked with dev_appserver) so that `users.get_current_user()` returns
`[email protected]` or whatever other fake email you input at the fake login
screen -- and this in no way inhibits the completely separate `oauth2` flow
from still performing as intended (i.e, exactly the same way as it does
without any such fake login).
If you deploy the modified app (with an extra user login) to production, the
login will have to be a real one -- but it's just as indifferent to, and
separate from, the `oauth2` part of the app.
If your application's logic does require constraining the `oauth2` token to
the specific user who's also logged into your app, you'll have to implement
this yourself -- e.g by setting `scope` to
`'https://www.googleapis.com/auth/plus.login
https://www.googleapis.com/auth/plus.profile.emails.read'` (plus whatever else
you need), you'll get from `service.people().get(userId='me')` a `user` object
with (among many other things) an `emails` attribute in which you can check
that the authorization token is for the user with the email you intended to
authorize (and take remedial action otherwise, e.g via a logout URL &c).
((This can be done more simply and in any case I doubt you really need such
functionality, but, just wanted to mention it)).
|
Django Database engine on Google app engine
Question: I have some problems by trying to change my database engine on my app engine.
right now i use the "google.appengine.ext.django.backends.rdbms" and it works
fine, but it's running slow.
What is the difference in using:
> "google.appengine.ext.django.backends.rdbms" or "django.db.backends.mysql"
i have the following in my settings.py:
DATABASES = {
'default': {
'ENGINE': 'google.appengine.ext.django.backends.rdbms',
'INSTANCE': 'xenon-notch-461:madplanuge',
'NAME': 'madplanuge',
}
}
And when i try to change the database engine to:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/cloudsql/xenon-notch-461:madplanuge',
'NAME': 'madplanuge',
'USER': 'root',
}
}
I get at server error on my appengine and the logs from the appengine says:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/core/handlers/wsgi.py", line 236, in __call__
self.load_middleware()
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/core/handlers/base.py", line 49, in load_middleware
mod = import_module(mw_module)
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/contrib/auth/middleware.py", line 3, in <module>
from django.contrib.auth.backends import RemoteUserBackend
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/contrib/auth/backends.py", line 3, in <module>
from django.contrib.auth.models import Permission
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/contrib/auth/models.py", line 8, in <module>
from django.db import models
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/db/__init__.py", line 40, in <module>
backend = load_backend(connection.settings_dict['ENGINE'])
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/db/__init__.py", line 34, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/db/utils.py", line 93, in __getitem__
backend = load_backend(db['ENGINE'])
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/db/utils.py", line 27, in load_backend
return import_module('.base', backend_name)
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/base/data/home/apps/s~xenon-notch-461/2.382413358316680585/libs/django/db/backends/mysql/base.py", line 17, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
ImproperlyConfigured: Error loading MySQLdb module: this is MySQLdb version (1, 2, 5, 'final', 1), but _mysql is version (1, 2, 4, 'beta', 4)
Answer: When to use either module depends on your environment. You can find more
details on how to use alternate databases for your working environments in App
Engine [documentation](https://cloud.google.com/appengine/docs/python/cloud-
sql/django#development-settings).
Basically, the **django.db.backends.mysql** module enables a Django app
running in production to communicate with a production Google Cloud SQL
instance.
On the other hand the **google.appengine.ext.django.backends.rdbms** backend
is used when running on a developer workstation and accessing a production
Cloud SQL instance.
An excerpt from the above mentioned documentation.
> * Use the standard **django.db.backends.mysql** when running in production
> and accessing a production Google Cloud SQL instance.
> * Use the standard **django.db.backends.mysql** when running on a
> developer workstation and accessing a local MySQL instance. In this case,
> the application uses the system MySQLdb driver.
> * Use the custom backend **google.appengine.ext.django.backends.rdbms**
> when running on a developer workstation and accessing a production Cloud SQL
> instance.
>
And yes, the error seems to have something to do with the incorrect version of
your MySQLdb module.
|
Python blobs.BlobResult module import error
Question: After install blobs package on Debian. am getting the error like
libdc1394 error: Failed to initialize libdc1394
Traceback (most recent call last):
File "1.py", line 8, in <module>
from blobs.BlobResult import CBlobResult
ImportError: No module named blobs.BlobResult
I trying to run [that code](http://andorian.blogspot.com/2013/02/automatic-
number-plate-detection.html). OpenCv and cvBlob already installed. Can anyone
help me to run that code?
Answer: Maybe you forget to install the python wrapper for cvBlob:
<https://github.com/oostendo/cvblob-python>
|
height not working python (3.4)
Question: I'm making my first program with tkinter and height will not work but width is
working.
here is my code:
from tkinter import *
from random import randint
def roll():
text.delete(0.0, END)
text.insert(END, str(randint(1, 6)))
window = Tk()
text = Text(window, width=1 height=1)
button = ButtonA(window, text='Press to roll!'), command=roll)
text.pack()
buttonA.pack()
Answer: Your program works with a few edits. For a 1 char text, width one is okay.
from tkinter import *
from random import randint
def roll():
text.delete("1.0", END) # indent inserted by first editor
text.insert(END, str(randint(1, 6))) # ditto
# but first editor mistakenly added indents below.
window = Tk()
text = Text(window, width=1, height=1) # insert ','
button = Button(window, text='Press to roll!', command=roll) # delete 'A', ')'
text.pack()
button.pack() # replace 'ButtonA' with 'button'
That said, a Label would be more appropriate for read-only display. It also
sizes itself automatically.
from tkinter import *
from random import randint
def roll():
out['text'] = str(randint(1, 6))
window = Tk()
out = Label(window, text = ' ')
button = Button(window, text='Press to roll!', command=roll)
button.pack()
out.pack()
|
python what is the different of size when replacing json.dump by json.load
Question: ### Background:
I am working on python sdk to insert some data to couchbase.
When I tried to insert the data using the `set` method like this:
connection = set(key, document)
I got exception states that the data is unicoded and it is not ascii. I solved
that problem using this:
couchbase.set_json_converters(json.dumps, json.loads)
### My question:
will that solution affects the size of the data that is being inserted to
couchbase?
Plus, could you give me a little explanation about the different of
joson.dumps and json.loads. I tried to search over internet and I found that
json.dump is for encoding while json.loads is for decoding, but i didn't
understand
### After the comment
I did this:
print "First Approach is using JSON loads instead of JSON dumps"
import json
import sys
d = "roma"
sizeBefore = sys.getsizeof(d)
print "size of d = {0}".format(sizeBefore)
dumped = json.dumps(d)
sizeAfter = sys.getsizeof(dumped)
print "size with json.dumps = {0}".format(sizeAfter)
loads = json.loads(dumped)
sizeLoad = sys.getsizeof(loads)
print "size with json.loads = {0}".format(sizeLoad)
print "-------------------------"
print "Second approach is decoding the string as UTF-8"
sizeBeforeDecode = sys.getsizeof(d)
print "Size before applying decode = {0}".format(sizeBeforeDecode)
d=d.decode("utf-8")
sizeAfterDecode = sys.getsizeof(d)
print "Size after applying decode = {0}".format(sizeAfterDecode)
The result is:
First Approach is using JSON loads instead of JSON dumps
size of d = 37
size with json.dumps = 39
size with json.loads = 58
-------------------------
Second approach is decoding the string as UTF-8
Size before applying decode = 37
Size after applying decode = 58
What does that mean please?
Answer: To answer the title question, this is like comparing apples to oranges.
`json.dumps` will convert a Python object to a JSON representation, and
`json.loads` will convert a JSON representation to a Python object. The
`set_json_converters` simply accepts a _pair_ of an encoder and decoder
function (so you basically need to set them both at the same time, even if you
only want to replace one of them).
To address your _real_ issue:
As mentioned in the original post here ([couchbase python sdk ascii
exception](http://stackoverflow.com/questions/28593263/couchbase-python-sdk-
ascii-exception)), the _proper_ solution is to ensure your input (or in this
case, its constituent key/values) are either:
1. 7-Bit ASCII Python `str` objects
2. Python `unicode` objects
_Ideally_ , you should ensure that any data you intend to treat as "Text"
(i.e. non-'binary' data, or data which you intend to encode into non-'binary'
formats (such as JSON)) should be converted into a `unicode` object as _early
as possible_. Unfortunately in Python2 (see below), it is very easy to
accidentally mix up the two -- often resulting in discovering problems deep in
the processing chain, rather than early on.
The `set_json_converters` "solution" is merely just a hack so that your code
can work (sub-optimally) until it is actually fixed. To fix it, you need to
properly sanitize and normalize your input. Currently your input is a
dictionary which has "byte" values which are _not_ Unicode. Yes, the specific
values in your _may_ be interpreted as valid UTF-8 sequences, but Python does
not care about this, and therefore functions which expect valid "Unicode"
inputs will fail.
I _strongly_ suggest you read <http://nedbatchelder.com/text/unipain.html> for
a very thorough, practical, and correct explanation of Unicode handling in
Python.
|
python extract text description from large text file
Question: i have bigg text file, and i need extract description message :
#### **Description**
20_Ways_To_Make_100_Dollars_EVERYDAY !!!
High Quality Guide (PDF File)
Here; I will teach you how to make 100 dollars every, or may be even more!
Buy the guide to get this secret method. ! worth more than you pay!
Good luck to everyone!
#### **Ships To**
Worldwide
start to "**Description** " finish to "#### **Ships To** ", how can i make
this whit python ? i need this output :
20_Ways_To_Make_100_Dollars_EVERYDAY !!!
High Quality Guide (PDF File)
Here; I will teach you how to make 100 dollars every, or may be even more!
Buy the guide to get this secret method. ! worth more than you pay!
Good luck to everyone!
Answer: Assuming that you have more variety in messages after '####' I would suggest
to use stricter format criteria while parsing your file:
import re #regular expressions module
file = open('text_to_process.txt', 'r') #opening your file
text = file.readlines()
file.close()
flag = False #flag to mark start/end of description
for line in text:
if re.match(r"#### \*\*Description\*\*", line):
flag = True
continue
if flag:
if not re.match("####", line):
print(line.strip()) #just printing the line, alternatively you could write it into file or variable
else:
flag = False
|
python list - method instead of string
Question: I am playing a bit with AWS via python and boto. I am trying to get modified
date for keys from AWS bucket. After that I am parsing date to 'regular' date
format and try to add every value to list.
Unfortunately, when I append values to list and try to print it's results I am
getting `datetime` function instead of string with date. Code looks like this:
import boto
s3 = boto.connect_s3()
bucket = s3.get_bucket('mybucket')
keys = bucket.list
keys_latest_modified_date_list = []
for key in keys:
key_latest_modified_date = boto.utils.parse_ts(key.last_modified)
keys_latest_modified_date_list.append(key_latest_modified_date)
print key_latest_modified_date
print keys_latest_modified_date_list
First `print` returns correct date:
2015-02-18 10:11:58
While second `print` gives me something like this:
[datetime.datetime(2015, 2, 18, 10, 11, 58)]
Does anyone know how to print values from list like in first `print` instead
of this what I get from second one?
Answer: You are getting confused by the `str()` output of `datetime` objects and their
representation:
>>> import datetime
>>> dt = datetime.datetime(2015, 2, 18, 10, 11, 58)
>>> dt
datetime.datetime(2015, 2, 18, 10, 11, 58)
>>> str(dt)
'2015-02-18 10:11:58'
>>> repr(dt)
'datetime.datetime(2015, 2, 18, 10, 11, 58)'
`print` calls `str` on the objects you print, but lists and other containers
always show their contents with `repr()`.
You'll have to use some string formatting to process the list:
print ', '.join(map(str, keys_latest_modified_date_list))
would print a comma-separated list of datetime objects converted to strings:
>>> keys_latest_modified_date_list = [dt, dt]
>>> keys_latest_modified_date_list
[datetime.datetime(2015, 2, 18, 10, 11, 58), datetime.datetime(2015, 2, 18, 10, 11, 58)]
>>> ', '.join(map(str, keys_latest_modified_date_list))
'2015-02-18 10:11:58, 2015-02-18 10:11:58'
>>> print ', '.join(map(str, keys_latest_modified_date_list))
2015-02-18 10:11:58, 2015-02-18 10:11:58
|
How to create global lock/semaphore with multiprocessing.pool in Python?
Question: I want limit resource access in children processes. For example - limit **http
downloads** , **disk io** , etc.. How can I achieve it expanding this basic
code?
Please share some basic code examples.
pool = multiprocessing.Pool(multiprocessing.cpu_count())
while job_queue.is_jobs_for_processing():
for job in job_queue.pull_jobs_for_processing:
pool.apply_async(do_job, callback = callback)
pool.close()
pool.join()
Answer: Use the initializer and initargs arguments when creating a pool so as to
define a global in all the child processes.
For instance:
from multiprocessing import Pool, Lock
from time import sleep
def do_job(i):
"The greater i is, the shorter the function waits before returning."
with lock:
sleep(1-(i/10.))
return i
def init_child(lock_):
global lock
lock = lock_
def main():
lock = Lock()
poolsize = 4
with Pool(poolsize, initializer=init_child, initargs=(lock,)) as pool:
results = pool.imap_unordered(do_job, range(poolsize))
print(list(results))
if __name__ == "__main__":
main()
This code will print out the numbers 0-3 in ascending order (the order in
which the jobs were submitted), because it uses the lock. Comment out the
`with lock:` line to see it print out the numbers in descending order.
This solution works both on windows and unix. However, because processes can
fork on unix systems, unix only need to declare global variables at the module
scope. The child process gets a copy of the parent's memory, which includes
the lock object which still works. Thus the initializer isn't strictly needed,
but it can help document how the code is intended to work. When
multiprocessing is able to create processes by forking, then the following
also works.
from multiprocessing import Pool, Lock
from time import sleep
lock = Lock()
def do_job(i):
"The greater i is, the shorter the function waits before returning."
with lock:
sleep(1-(i/10.))
return i
def main():
poolsize = 4
with Pool(poolsize) as pool:
results = pool.imap_unordered(do_job, range(poolsize))
print(list(results))
if __name__ == "__main__":
main()
|
why won't my circle loop work in python
Question:
import turtle
import time
import random
n = int(input("how many circles do you want? "))
radius = int(input("Radius?"))
turtle.forward(radius)
turtle.left(90)
for circle in range(num, 0, -1):90 (num..1)
turtle.begin_fill()
turtle.color(random.random(),random.random(), random.random())
turtle.circle(radius * circle / num)
turtle.end_fill()
turtle.left(90)
turtle.forward(radius / num)
turtle.right(90)
Answer:
for circle in range(num, 0, -1):90 (num..1)
That is not valid Python syntax. Assuming it's meant to be a comment, it would
be:
for circle in range(num, 0, -1): # num..1
However, you'll find yourself a better practitioner of the art if you remember
this: the code tells you _how_ things are done, comments tell you _why_ they
are done.
Anyone looking at Python code should already realise that loop counts down
from `num` (which should possibly be `n` by the way, or the input at the top
should assign to `num`) to `1`, else they shouldn't be _looking_ at the code.
|
Implementing Chain of responsibility pattern in python using coroutines
Question: I am exploring different concepts in python and I happened to read upon an
example of coroutines which can be used for the chain of responsibility design
pattern. I wrote the following code:
from functools import wraps
def coroutine(function):
@wraps(function)
def wrapper(*args, **kwargs):
generator = function(*args, **kwargs)
next(generator)
return generator
return wrapper
@coroutine
def PlatinumCustomer(successor=None):
cust = (yield)
if cust.custtype == 'platinum':
print "Platinum Customer"
elif successor is not None:
successor.send(cust)
@coroutine
def GoldCustomer(successor=None):
cust = (yield)
if cust.custtype == 'gold':
print "Gold Customer"
elif successor is not None:
successor.send(cust)
@coroutine
def SilverCustomer(successor=None):
cust = (yield)
if cust.custtype == 'silver':
print "Silver Customer"
elif successor is not None:
successor.send(cust)
@coroutine
def DiamondCustomer(successor=None):
cust = (yield)
if cust.custtype == 'diamond':
print "Diamond Customer"
elif successor is not None:
successor.send(cust)
class Customer:
pipeline = PlatinumCustomer(GoldCustomer(SilverCustomer(DiamondCustomer())))
def __init__(self,custtype):
self.custtype = custtype
def HandleCustomer(self):
try:
self.pipeline.send(self)
except StopIteration:
pass
if __name__ == '__main__':
platinum = Customer('platinum')
gold = Customer('gold')
silver = Customer('silver')
diamond = Customer('diamond')
undefined = Customer('undefined')
platinum.HandleCustomer()
gold.HandleCustomer()
undefined.HandleCustomer()
What I have tried to do here is try to create a chain of responsibility
pattern solution for handling different types of customers (Platinum, Gold,
Diamond, Silver).
For that Customer has a pipeline where I have mentioned the order in which the
different customers will be handled. Customer().HandleCustomer will send an
instance of itself through the pipeline which will check whether its custtype
matches and then process it accordingly or it will send it across to its
successor (if available)
PROBLEM: The problem is that when I run the above script, it will handle the
first platinum customer but not the gold or the undefined. I am assuming this
is because he has reached the end of the generator. How do I modify the code
so that everytime it is a new instance of a customer, it will go through the
pipeline from its beginning?
Answer: Your coroutines must loop forever in order to handle successive calls, as in:
@coroutine
def PlatinumCustomer(successor=None):
while 1: # <---- this is missing from your coroutines
cust = (yield)
if cust.custtype == 'platinum':
print "Platinum Customer"
elif successor is not None:
successor.send(cust)
And to handle the 'undefined' type, you'll need a final catch-all handler:
@coroutine
def UndefinedCustomer():
while 1:
cust = (yield)
print "No such customer type '%s'" % cust.custtype
and add it to your pipeline:
pipeline = PlatinumCustomer(GoldCustomer(SilverCustomer(DiamondCustomer(UndefinedCustomer()))))
(A terminating UndefinedCustomer handler also will allow you to remove the 'if
there is no successor' code from your coroutines - all will have successors
except for the terminator, which knows that it is the terminator and will not
call a successor.)
With these changes, I get this output from your tests:
Platinum Customer
Gold Customer
No such customer type 'undefined'
Also, why the catch for StopIteration in HandleCustomer? This code should be
sufficient:
def HandleCustomer(self):
self.pipeline.send(self)
|
pyvirtualdisplay on Amazon EC2 instance
Question: I am trying to run selenium on Amazon EC2. I am using pyvirtualdisplay as xvfb
wrapper. I ran the following commands in python.
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(1024, 768))
display.start()
Everything goes fine till now.
But when I do:
driver = webdriver.Firefox()
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/site- packages/selenium/webdriver/firefox/webdriver.py", line 59, in __init__
self.binary, timeout),
File "/usr/lib/python2.6/site-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__
self.binary.launch_browser(self.profile)
File "/usr/lib/python2.6/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 66, in launch_browser
self._wait_until_connectable()
File "/usr/lib/python2.6/site- packages/selenium/webdriver/firefox/firefox_binary.py", line 100, in _wait_until_connectable
raise WebDriverException("The browser appears to have exited "
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
Answer: After spending many hours on the internet searching for solutions and trying
every possible thing out, one thing which worked for me is this.
<http://superuser.com/questions/870702/aws-ec2-linux-headless-firefox-issue-
xvfb-undefined-symbol-pixman-glyph-cache>
As the answer says:
It is trying to load wring pixman so. Delete /usr/local/lib/libpixman-1.so.0
and try again, it will make Xvfb use distribution pixman library which has
this symbol.
|
python script to handle uploaded file via http post
Question: I am working on a django project where i try to upload a file via http post
request.
my upload script is :
url=r'http://MYSITEURL:8000/upload'
files={'file':open('1.png','rb')}
r=requests.post(url,files=files)
my receiving side is in my django site , in views.py:
def upload_image(request):
from py_utils import open_py_shell;open_py_shell.open_py_shell()
when i do request.FILES i can see all the post details, what i want to know is
how to save it in the server side once i got the post request
Answer: What you have in `request.FILES` is `InMemoryUploadedFile`. You just need to
save it somewhere in file system.
This is example method taken from [Django
docs](https://docs.djangoproject.com/en/1.7/topics/http/file-uploads/):
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
|
How to distinguish between multiple shapes in a figure or array?
Question: I have a 2D array in Python containing values of either 0 or 1, arranged to
form various shapes. For my current project I need a method to distinguish
between the shapes in the image.
I am currently attempting to do this by setting the values of the first shape
to 1, the second shape values to 2 and so on. However, this is proving too
difficult for me to code, so I was wondering if anyone knew a good algorithm
to do this, or knew of another method. Thanks.
Answer: I suspect you are looking for [label
features](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.measurements.label.html)
which is available in `scipy.ndimage`. Despite the name, it is not
neccessarily specific to image analysis. Quoting from the documentation "Any
non-zero values in input are counted as features and zero values are
considered the background."
The result will be an array, of the same size, with features numbered. For
example, the following code:
import numpy as np
from scipy.ndimage import measurements
arr = np.array([
[0,0,0,0,0,0],
[0,1,1,0,0,0],
[0,1,1,0,0,1],
[0,0,0,0,1,1],
[0,0,0,0,1,1]
])
labeled_array, number_of_features = measurements.label(arr)
print(labeled_array)
...will produce the following output, with the two features numbered 1 and 2
respectively:
array([[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 0, 2],
[0, 0, 0, 0, 2, 2],
[0, 0, 0, 0, 2, 2]], dtype=int32)
The second return parameter contains the `number_of_features` in the array
(here 2).
|
Plotting graph using matplotlib
Question: I'm trying to plot train and testing learning learning curves using the code
below :
import numpy as np
from sklearn import cross_validation
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer
import sklearn.linear_model as lm
import pandas as pd
from sklearn.learning_curve import learning_curve
def main():
print("loading data..")
train_data = list(np.array(pd.read_table('train.tsv'))[:, 2])
test_data = list(np.array(pd.read_table('test.tsv'))[:, 2])
tr = np.array(pd.read_table('train.tsv'))
tfv = TfidfVectorizer(min_df=3, max_features=None,
strip_accents='unicode',analyzer='word',
token_pattern=r'\w{1,}',ngram_rang(1,2),
use_idf=1, smooth_idf=1, sublinear_tf=1)
rd = lm.LogisticRegression(penalty='l2', dual=True, tol=0.0001,
C=1, fit_intercept=True, intercept_scaling=1.0,
class_weight=None, random_state=None)
y=tr[:,-1].astype(int)
X_all = train_data + test_data
len_train = len(train_data)
print("fitting pipeline")
tfv.fit(X_all)
print("transforming data")
X_all = tfv.transform(X_all)
X = X_all[:len_train]
X_test = X_all[len_train:]
print("20 Fold CV Score: " +
str(np.mean(cross_validation.cross_val_score(rd, X, y, cv=20,
scoring='roc_auc'))))
print("training on full data")
rd.fit(X,y)
pred = rd.predict_proba(X_test)[:, 1]
test_file = pd.read_csv('test.tsv', sep="\t", na_values=['?'],index_col=1)
pred_df = pd.DataFrame(pred, index=test_file.index, columns=['label'])
pred_df.to_csv('benchmark.csv')
print("submission file created..")
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(1,7000,10)):
"""
Generate a simple plot of the test and traning learning curve.
Parameters
----------
estimator : object type that implements the "fit" and "predict" methods
An object of that type which is cloned for each validation.
title : string
Title for the chart.
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape (n_samples) or (n_samples, n_features), optional
Target relative to X for classification or regression;
ylim : tuple, shape (ymin, ymax), optional
Defines minimum and maximum yvalues plotted.
cv : integer, cross-validation generator, optional
n_jobs : integer, optional
Number of jobs to run in parallel (default 1).
"""
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(estimator, X, y,
cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1, color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-
validation score")
plt.legend(loc="best")
return plt
X,Y = y,pred
title = "Learning Curves (tf-idf)"
cv = cross_validation.ShuffleSplit(pred_df, n_iter=100, test_size=0.20,
random_state=0)
estimator = TfidfVectorizer()
plot_learning_curve(estimator, title, X, Y, ylim=(0.1, 1.01), cv=cv,
n_jobs=4)
title = "Learning Curves (lr)"
cv = cross_validation.ShuffleSplit(pred_df, n_iter=10, test_size=0.20,
random_state=0)
estimator = lm()
plot_learning_curve(estimator, title, X, Y, (0.1, 1.01), cv=cv, n_jobs=4)
plt.show()
if __name__ == "__main__":
main()
It gave the following error :
Traceback (most recent call last):
File "<ipython-input-17-fe9e40bbce16>", line 1, in <module>
runfile('C:/Users/Maitri/Documents/Python Scripts/first.py', wdir='C:/Users/Maitri/Documents/Python Scripts')
File "C:\Users\Maitri\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile
execfile(filename, namespace)
File "C:/Users/Maitri/Documents/Python Scripts/first.py", line 136, in <module>
main()
File "C:/Users/Maitri/Documents/Python Scripts/first.py", line 122, in main
cv = cross_validation.ShuffleSplit(pred_df, n_iter=100, test_size=0.20, random_state=0)
File "C:\Users\Maitri\Anaconda\lib\site-packages\sklearn\cross_validation.py", line 771, in __init__
train_size)
File "C:\Users\Maitri\Anaconda\lib\site-packages\sklearn\cross_validation.py", line 922, in _validate_shuffle_split
n_test = ceil(test_size * n)
TypeError: a float is required
Is there a better way to plot graphs for the prediction results?
Answer: The traceback for the error you are receiving shows the source of the problem.
File "C:/Users/Maitri/Documents/Python Scripts/first.py", line 122, in main cv = cross_validation.ShuffleSplit(pred_df, n_iter=100, test_size=0.20, random_state=0)
File "C:\Users\Maitri\Anaconda\lib\site-packages\sklearn\cross_validation.py", line 771, in init train_size)
File "C:\Users\Maitri\Anaconda\lib\site-packages\sklearn\cross_validation.py", line 922, in _validate_shuffle_split n_test = ceil(test_size * n)
TypeError: a float is required
The error is raised in the `sklearn` package, but ultimately originates from
`line 122` in your script. Here you are passing in a Pandas DataFrame
containing your data. The error that is given `TypeError: a float is required`
indicates that the `ShuffleSplit` was expecting a `float` type.
The first step would be to check you are loading your input file correctly, on
the following line:
test_file = pd.read_csv('test.tsv', sep="\t", na_values=['?'],index_col=1)
pred_df = pd.DataFrame(pred, index=test_file.index, columns=['label'])
If the data is loading OK, but the type is _just not a float_ , you can
convert the data to the right type using or `astype` in numpy or `as_dtype`
for Pandas. e.g.
pred_df = pd.DataFrame(pred, index=test_file.index, columns=['label']).as_dtype(np.float)
# ...or...
pred_df = pd.DataFrame(pred.astype(np.float), index=test_file.index, columns=['label'])
|
Barnsley fern in python language
Question: I need help with this Barnsley fern program. I am not getting the leaf picture
at all and getting an error run time message when I run my code I know I am
close but need some help
#! /usr/bin/env python
import matplotlib.pyplot as plt
import random
# starting values
x = 0.5
y = 0.0
for i in range(10000):
rand = (random.randrange(0,1))
if (rand < 0.02):
x = 0.5
y = 0.27*y
if ((0.02 <= rand) and (rand <= 0.17)):
x = -0.139*x + 0.263*y + 0.57
y = 0.246*x + 0.224*y - 0.036
if ((0.17 < rand) and (rand <= 0.3)):
x = 0.17*x - 0.215*y + 0.408
y = 0.222*x + 0.176*y + 0.0893
if ((0.3 < rand) and (rand < 1.0)):
x = 0.781*x + 0.034*y + 0.1075
y = -0.032*x +0.739*y + 0.27
plt.plot(x,y,'.')
plt.show()
Answer: There are two major issues with your code:
1. `random.randrange(0, 1)` always yields `0`. Try using `random.random()` instead.
2. You need to indent the `plot` command in order to have it executed in every iteration.
Furthermore, it might be better to first collect all coordinates in one large
array and then call the plot command. This would probably be more time
efficient because you'd call the rendering engine only once.

|
Python command line using Cygwin: ImportError
Question: My python files are as follows:
/root/D/main.py
/root/T/test.py
/root/T/__init__.py
My `main.py` imports:
from T import test
I executed the `main.py` from command line:
> export PYTHONPATH=/cygdrive/root/T
> cd /root/D
> python main.py
I get error: `ImportError: No module named T.`
How can I execute from command line without error?
Edit: The contents of the `__init__.py` is:
from .test import *
Answer: Resolved it, the problem was Cygwin, I set `PYTHONPATH=/cygdrive/root` and the
proper way is `PYTHONPATH=c:/root`
|
Get system metrics using PowerShell
Question: I have a Python script which prints 1 if it is running under RDP or 0 if it is
not.
from ctypes import *
SM_REMOTESESSION = 0x1000
print(windll.user32.GetSystemMetrics(SM_REMOTESESSION))
I'd like to get the same information using PowerShell. How do I do the
equivalent of `GetSystemMetrics` in PowerShell?
Answer: You can do it the easy way by using the
[TerminalServerSession](https://msdn.microsoft.com/en-
us/library/system.windows.forms.systeminformation.terminalserversession.aspx)
bool-property from .NET Framework:
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SystemInformation]::TerminalServerSession
Output:
False
Or you could do it the manual way (like `TerminalServerSession` does
internally) and use C# and P/Invoke to add load and use `GetSystemMetrics()`
in PowerShell.
$def = @"
//I removed every other enum-value to shorten the sample
public enum SystemMetric
{
SM_REMOTESESSION = 0x1000, // 0x1000
}
[DllImport("user32.dll")]
public static extern int GetSystemMetrics(SystemMetric smIndex);
"@
Add-Type -Namespace NativeMethods -Name User32Dll -MemberDefinition $def
[NativeMethods.User32Dll]::GetSystemMetrics([NativeMethods.User32Dll+SystemMetric]::SM_REMOTESESSION)
Output:
0
|
dictionary to read 3 values from a csv file in python
Question: I'm trying to create a simple dictionary which gets 3 values from a csv file.
my python code can get 2 values easily from the csv file. But I can't get to
display a 3th value.
Heres my csv file :
ERRORCODE,EVENTKEY,COUNT
109,playback_error,2
210,live_channels_metadata_request_failed,1
106,playback_error,19
180,search_error,5
2086,vod_catalog_metadata_request_failed,1
-1001,live_channels_metadata_request_failed,1
380,playback_error,1
400,search_error,2
N/A,crash,218
3803,playback_error,28
JX-0002,search_error,104
385,playback_error,141
386,playback_error,1
387,playback_error,29
0,tbr_error,31
2001,qp_library_failed_to_start,42
2002,qp_library_failed_to_start,147
1512,playback_error,19
2004,live_channels_metadata_request_failed,2
2006,qp_library_failed_to_start,1
2006,live_channels_metadata_request_failed,5
-1001,search_error,2
-1003,search_error,8
BLL-10011,parental_controls_error,42
1517,playback_error,47
,,81
BL-10013,parental_controls_error,3
-1005,search_error,3
BL-10014,parental_controls_error,2
3320,qp_library_failed_reauthentication,2
3710,playback_error,168
-1200,playback_error,2
-1,playback_error,2
3301,playback_error,1311
3304,playback_error,122
3305,playback_error,1
Here's my python dictionary:
#!/usr/bin/python
import csv
with open('csv_err2.log', mode='r') as infile:
reader = csv.reader(infile)
mydict = dict((rows[0],rows[1]) for rows in reader)
print(mydict)
I'm only able to get the following ouput: ERRORCODE, EVENTKEY:
{ '3904': 'playback_error', '3808': 'playback_error', '3902': 'qp_library_failed_to_start'..... }
but i'm missing the value COUNT.. :( How can I display my last value COUNT in
that dictionary?
any help would be greatly appreciated
Answer:
mydict = dict((rows[0],rows[1:]) for rows in reader)
might be what you are looking for ... not really sure
|
I want to modify this python script to output the modification date of the parsed file along with it's title
Question: So the last programmer left me with this script, that grabs all the old
content and writes it's all out as a "partial' file.. which strips out all the
container html and leave's just the html of the article itself. It then write
a manifest as JSON which give the url, the title with the date.
I'd like it to order all the files by the date created, in the manifest, and
in the filenames created. (something like [unix-create-date]-[url].partial]).
Then i can use the manifest file to list the file in the order they were
created, and use the file names themselves as well.
The purpose of all this was to scan the old archives of an old web site and
set the up for insertion into the new web sites template. However the current
list of articles is not by date. I needs to be. Getting the manifest to output
the files by date would do it.
I don't know python at all. So i have no idea how to get the modification date
in there. Seems to be there has got to be a way to open the files in the path
ordered by create date. Thanks for any responses!
Here is the full script.
#!/usr/bin/python
import os
import re
from BeautifulSoup import BeautifulSoup
import simplejson as json
def parse_article(root, filename):
path = os.path.join(root, filename)
abs_path = os.path.abspath(path)
try:
article = open(abs_path, 'rU')
html = article.read()
article.close()
except IOError:
print "Cannot open article: %s" % path
url = "/%s" % path
soup = BeautifulSoup(html)
title = None
fallbacks = ['h1', 'h2', 'h3', 'title']
for fallback in fallbacks:
if title is None:
title = soup.find(fallback)
else:
break
content = u"" if soup.body is None else soup.body.renderContents()
save_file(root, "%s.partial" % filename, content)
title = u"" if title is None else title.renderContents()
return unicode(url), title
def process_folder(path):
files = os.listdir(path)
articles = filter(lambda name: not name.startswith('index.') and (name.endswith('.html') or name.endswith('.htm')), files)
manifest = {}
for article in articles:
url, title = parse_article(path, article)
manifest[url] = title
return manifest
def save_json(root, name, obj):
if len(obj.keys()) == 0:
return
path = os.path.join(root, name)
manifest = open(path, 'w')
json.dump(obj, manifest)
manifest.close()
print "Wrote %s" % path
def save_file(root, name, content):
path = os.path.join(root, name)
manifest = open(path, 'w')
manifest.write(content)
manifest.close()
print "Wrote %s" % path
def process(root):
root = os.path.abspath(root)
root_re = '^%s[/]*' % root
for dirname, dirnames, filenames in os.walk(root):
dirname = re.sub(root_re, '', dirname)
if len(dirname) > 0:
manifest = process_folder(dirname)
abs_path = os.path.abspath(os.path.join(root, dirname))
save_json(abs_path, "manifest.json", manifest)
if __name__ == "__main__":
process('.')
Answer: You can get the modification date of a file by using
[`os.stat`](https://docs.python.org/3/library/os.html#os.stat):
>>> import os, time
>>> result = os.stat("/tmp/z.py")
>>> result
posix.stat_result(st_mode=33188, st_ino=6034492, st_dev=16777220L, st_nlink=1, st_uid=501, st_gid=0, st_size=189, st_atime=1424735724, st_mtime=1424735651, st_ctime=1424735651)
>>> print "Modification date: %s -> %s" % (result.st_mtime, time.ctime(result.st_mtime))
Modification date: 1424735651.0 -> Mon Feb 23 15:54:11 2015
>>> print "Creation date: %s -> %s" % (result.st_ctime, time.ctime(result.st_ctime))
Creation date: 1424735651.0 -> Mon Feb 23 15:54:11 2015
>>> print "Access date: %s -> %s" % (result.st_atime, time.ctime(result.st_atime))
Access date: 1424735724.0 -> Mon Feb 23 15:55:24 2015
So in your code, you'd probably want to store it in the manifest around here:
...
for article in articles:
url, title = parse_article(path, article)
manifest[url] = title
manifest[ctime] = os.stat(path).st_ctime
...
With that information you can then sort the files based on `ctime`, or convert
it to a `datetime` object, etc.
|
From datetime to timestamp python
Question: I need to convert a datetime object with microsecond resolution to a
timestamp, the problem is that I don't get the same timestamp second's
resolution.
For example the timestamp that I pass as an argument is 1424440192 and I get
in return 1424429392.011750, why is this?, I Only changed microsecond value of
the datetime object, so I expect to change only values after the dot. PD: In
this example I'm only simulating one timestamp.
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
return td.total_seconds()
#return (td.microseconds + (td.seconds + td.days * 24 * 3600) *
#10**6) / 1e6
timestamp_pc = 1424440192
tm = datetime.fromtimestamp(timestamp_pc)
new_tm = tm.replace(microsecond = 11750)
print tm
print new_tm
print timestamp_pc
print "%f " %(totimestamp(new_tm))
Answer: I get it. I changed `tm = datetime.fromtimestamp(timestamp_pc)` for `tm =
datetime.utcfromtimestamp(timestamp_pc)`
and now timestamp are identical.
|
Creating a django rest API for my python script
Question: I have a JSON file with data as such :
['dbname' : 'A', 'collection' : 'ACollection', 'fields' : ['name', 'phone_no', 'address']}
['dbname' : 'B', 'collection' : 'BCollection', 'fields' : ['name', 'phone_no', 'address', 'class']}
These are 2 examples amongst many other dictionaries of the same format.
I have a python code that does the following : Accepts 2 inputs from the user
- phone_no and dbname. For example, the user enters phone_no as xxxxxxxxxx and
dbname as A. The python code then reads the JSON file and matches the user
input with the dictionary element having the name of the database as 'A'. It
then opens the database 'A', opens the respective collection 'ACollection' and
prints the respective fields of posts within the collection that have the
phone_no value as xxxxxxxxxx. The databases are implemented with mongoDB.
I need to build a django rest api for this code. The end goal is to access the
code from a browser. The user provides the 2 inputs in the browser and the
code is executed, returning the data, which is displayed on the browser. I
have gone through the django-rest framework documentation but I'm new to this
whole concept and would like some guidance.
How do I implement these functions and create an API? What code should the
models, serializers, views and urls files have related to my program?
models.py
from django.db import models
class App(object):
def __init__(self, phone_no, name, address, categories):
self.phone_no = phone_no
self.name = name
self.address = address
self.categories = categories
This is what I'm working with so far, to get started. The problem, however, is
that the models class should essentially be dynamic. Ex: If 'A' is the
database, the program returns 3 fields but if 'B' is the database, the program
returns 4 values so I'm not sure what the models class would be like.
views.py
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from pymongo import Connection
from models import App
from serializers import AppSerializer
import json
import pymongo
from os import listdir
import re
from django import forms
@csrf_exempt
@api_view(['GET'])
def pgs(request):
#connect to our local mongodb
db = Connection('localhost',27017)
#get a connection to our database
dbconn = db.general
dbCollection = dbconn['data']
if request.method == 'GET':
#get our collection
items = []
for r in dbCollection.find():
post = App(r["phone_no"],r["name"],r["address"],r["categories"])
items.append(post)
serializedList = AppSerializer(items, many=True)
return Response(serializedList.data)
Answer: Let's say you have identical tables in two different databases. We'd start by
creating two db connections in settings.py. Let's say those are called db_a
and db_b. We might model this as so:
class PhoneGenome(models.Model):
phone_no = models.CharField(length=255)
name = models.CharField(length=255)
# and so on...
class Meta:
# if database pre-exists, may want to use managed=False
managed = False
This gives us a model. Now we choose which database to pull from based on user
input. In a view, you might have something like:
db_used = request.GET.get('database')
db_conns = {'a': 'db_a', 'b': 'db_b'}
if db_conns.has_key(db_used):
records = PhoneGenome.objects.using(db_conns[db_used]).filter( user_criteria_here)
The using() method in your queryset is what allows you to select which
database to run the query against.
There's a lot to manage here potentially, so this would be a good time to look
at the docs: <https://docs.djangoproject.com/en/1.7/topics/db/multi-db/>
And if you haven't already, you really should work through the Django tutorial
at the very least before going much further.
|
sending emails with python - subject of message missing
Question: all. I have encountered a bit of a problem while trying to send emails with
python's `email` package along with `smtplib`. I have set up a function that
send an email and it works well, with the exception that the email always
comes without the subject. I am not new to python, but I am new to using it
for internet-related things such as this one. I have set up the following from
several answer in this forum as well as the examples in the
[documentation](https://docs.python.org/2/library/email-examples.html).
import smtplib
from os.path import basename
from email import encoders
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email.mime.audio import MIMEAudio
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def send_mail(send_from, send_to, subject, text, files=None, server="smtp.gmail.com"):
import mimetypes
assert isinstance(send_to, list)
msg = MIMEMultipart(From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True), Subject=subject)
msg.attach(MIMEText(text))
for f in files or []:
print f
ctype,encoding=mimetypes.guess_type(f)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
fp = open(f)
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'image':
fp = open(f, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(f, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(f, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=basename(f))
smtp = smtplib.SMTP(server)
smtp.starttls()
usrname=send_from
pwd=raw_input("Type your password:")
smtp.login(usrname,pwd)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Calling the function as `send_mail('[email protected]',['[email protected]'],'This is
the subject','Hello, World!')` results in an email sent correctly but without
a subject.
The output with or without files is the same. Also, reading the docs also
didn't help me.
I appreciate any help.
Answer: Instead of passing subject as an argument to MIMEMultipart, try assigning the
value to msg:
`msg['Subject'] = subject`
Great examples in the docs: <https://docs.python.org/3/library/email-
examples.html>
|
NumPy analog of R's `filter`
Question: What is analog of R's
[`filter`](https://stat.ethz.ch/R-manual/R-patched/library/stats/html/filter.html)
in NumPy?
I have the following R code:
f <- rep(1/9, 9)
smth_x <- filter(x, f, sides=2)
Where `x` is some 1-D timeseries vector which may contain `nan`'s.
How to perform the same operation using NumPy? (or any other python libs)
Answer: I think the [scipy filter
functions](http://docs.scipy.org/doc/scipy/reference/signal.html) do what you
want, in particular
[lfilter](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html).
Going from [this HOWTO](http://wiki.scipy.org/Cookbook/ApplyFIRFilter):
import numpy, scipy.signal
taps = numpy.repeat(1.0/9, 9)
smoothed_x = scipy.signal.lfilter(taps, 1.0, x)
|
Python's resultant issues
Question: I'm new of Python and i'm stuck on this. I need to check if i can find a
string in a file. I have created the file ContEAN.py
the code:
import sys
for arg in sys.argv:
inputEAN=arg
EAN = open("/home/master/Documenti/Progetti/eanFZ.txt","r")
riga=EAN.readlines()
EAN.close()
print inputEAN
for i in range(len(riga)):
if inputEAN == riga[i]:
print "OK"
From Command line:
> $ python ContEAN.py 455
where "455" will be the value of inputEAN
and this is the content of eanFZ.txt:
7777
777
0000000000156
0000000015
455
9999
85485
656565
the problem is that i never have an ok as ultimate result and i don't know
why...
Answer: First of all, the readlines() method returns an iterable object which can be
iterated over in the loop. Each iteration will use the next line of the file.
Secondly, the lines of the file have a hidden newline character at the end, so
it is not 'equal' to the string from argv. This can be removed with the
rstrip() method.
for i in riga:
if inputEAN == i.rstrip():
print "OK"
(You may also want to check indentation. You need to go to a new indentation
level after each for line and each if line. I have assumed this was due to
copy and paste.)
|
Python 3 with Requests trying to use Tumblr API, I get error 401?
Question: I have Python 3 and I am trying to post to Tumblr via API [link to API
documentation](https://www.tumblr.com/docs/en/api/v2). I keep getting an error
401 despite feeling like I am doing everything correctly. There is an official
API client in Python 2 but that feels a bit hard to follow and all other
mentions of it seem to be in PHP or Java. I also am not sure of the format to
post in after the 401 error because the documentation doesn't give any
explicit examples other than /post. My code:
import requests
from requests_oauthlib import OAuth1
#variables for later
client_key=""
client_secret=""
oauth_token=""
oauth_token_secret=""
#gets the values for the variables
with open("API.txt", 'r') as readAPI:
readAPI.readline()
client_key=readAPI.readline()[23:]
client_secret=readAPI.readline()[23:]
oauth_token=readAPI.readline()[23:]
oauth_token_secret=readAPI.readline()[23:]
readAPI.close()
#prints them to double check they are being read correctly
print(client_key)
print(client_secret)
print(oauth_token)
print(oauth_token_secret)
#sets oauth for the connection
oauth = OAuth1(client_key,
client_secret,
oauth_token,
oauth_token_secret)
#check post that should return various blog stats
r = requests.get("http://api.tumblr.com/v2/user/info" ,auth=oauth)
print(r)
I am 100% sure I am getting the client key, the client secret, oauth token and
oauth token secret correct. I have double checked, the oauth tokens are both
put in the file that is being read manually and they are printed before the
connection attempt. I am 100% sure it is correct. I'm wondering if Tumblr's
API is broken?
Edit: This is with print(repr())
'client_key'
'client_secret'
'oauth_token'
'oauth_token_secret'
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
This is what happens after trying a new code and with Steven's method with
JSON.
b'{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}'
Answer: Instead of doing this:
print(client_key)
What is the output of this?
print(repr(client_key))
You're using `readline`, which includes a newline character at the end of each
line:
$ cat foo.txt
key
secret
blabla
$ python3.4
>>> f = open("foo.txt")
>>> print(repr(f.readline()))
'key\n'
>>> print(repr(f.readline()))
'secret\n'
>>> print(repr(f.readline()))
'blabla\n'
Have you tried stripping the newline character off of each line?
* * *
**Edit** : Updating my post based on @user2853325's comments. Your code works
for me under Python 3.4, requests==2.5.2, and requests-oauthlib==0.4.2.
API.json (redacted the keys/secrets):
{
"client_key": "XXXXXXXXXXXXXXXXXXXXdG7zXIMcDidwQ5pMHuQTbxyhNINrCE",
"client_secret": "XXXXXXXXXXXXXXXXXXXX72A5HQO1axydP5nlOWCTQx4ECfXfyX",
"oauth_token": "XXXXXXXXXXXXXXXXXXXX8WAnqMBWaAdnGhnc4gWhJ4j6cufK1W",
"oauth_token_secret": "XXXXXXXXXXXXXXXXXXXX8Kf82k65JzIcMU7QUp54ssPEzJd7my"
}
tumblr.py:
import json
import requests
from requests_oauthlib import OAuth1
#gets the values for the variables
with open("API.json") as f:
credentials = json.load(f)
#prints them to double check they are being read correctly
print(credentials)
#sets oauth for the connection
oauth = OAuth1(
credentials['client_key'],
credentials['client_secret'],
credentials['oauth_token'],
credentials['oauth_token_secret']
)
#check post that should return various blog stats
r = requests.get("http://api.tumblr.com/v2/user/info", auth=oauth)
print(r)
print(r.content)
Output (redacted the oauth stuff):
$ bin/python tumblr.py
{'oauth_token_secret': 'XXXXXXXXXXXXXXXXXXXX8Kf82k65JzIcMU7QUp54ssPEzJd7my', 'client_secret': 'XXXXXXXXXXXXXXXXXXXX72A5HQO1axydP5nlOWCTQx4ECfXfyX', 'client_key': 'XXXXXXXXXXXXXXXXXXXXdG7zXIMcDidwQ5pMHuQTbxyhNINrCE', 'oauth_token': 'XXXXXXXXXXXXXXXXXXXX8WAnqMBWaAdnGhnc4gWhJ4j6cufK1W'}
<Response [200]>
b'{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"lost-theory","likes":0,"following":2,"default_post_format":"html","blogs":[{"title":"Untitled","name":"lost-theory","posts":0,"url":"http:\\/\\/lost-theory.tumblr.com\\/","updated":0,"description":"","is_nsfw":false,"ask":false,"ask_page_title":"Ask me anything","ask_anon":false,"followed":false,"can_send_fan_mail":true,"share_likes":true,"likes":0,"twitter_enabled":false,"twitter_send":false,"facebook_opengraph_enabled":"N","tweet":"N","facebook":"N","followers":0,"primary":true,"admin":true,"messages":0,"queue":0,"drafts":0,"type":"public"}]}}}'
So now that I've tested your code out for myself:
* How did you get the `oauth_token` and `oauth_token_secret`? I got mine by clicking "Explore API" on the [Applications developer page](https://www.tumblr.com/oauth/apps).
* You don't need to call `readAPI.close()`, as the `with` block automatically closes the file for you (see the [official docs](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects)).
* I used JSON for storing and reading the credentials, that way I'm 100% sure that I'm getting the correct strings. The code is cleaner too. I'm still suspicious about the way you're reading lines from the file and slicing them.
* Try printing `r.content` in your code the same way I am. Does it give you a more descriptive error message than "401 Unauthorized"?
|
how do i get python to print an invoice
Question: parts list array
a =list(["CPU,$150.00","RAM ,$120.00","DVD drive $89.00","Hard Disk Drive,$189.99"])
for letter in a:
print(letter)
this is my parts list I am trying to figure out how to get it to print to a
printer any tips
Answer: From the python windows [print
tutorial:](http://timgolden.me.uk/python/win32_how_do_i/print.html)
import win32api
import win32print
def parts_list():
a = ["CPU,$150.00","RAM ,$120.00","DVD drive $89.00","Hard Disk Drive,$189.99"]
with open('printfile.txt', 'w') as f:
for line in a:
f.write(line)
print_windows('printfile.txt')
def print_windows(filename):
win32api.ShellExecute(0, "print", filename, '/d:"%s"' % winn32print.GetDefaultPrinter (),".", 0)
def main():
parts_list()
if __name__ == '__main__':
main()
|
Python 'in' function , pandas dataframe wrongly populated
Question:
from collections import defaultdict
import csv
from bs4 import BeautifulSoup
import urllib2
import pandas as pd
import re
text = open("/Users/dynajose/Desktop/PlayList.rtf").read()
songDom = BeautifulSoup(text)
data=defaultdict(list)
musicData=defaultdict(list)
f_music = songDom.find_all("div", {"class" : "_gx6 _agv"})
for music in f_music:
try:
Name_title = music.find("a","_gx7")
data['Name'].append(Name_title.text)
except:
data['Name'].append("")
try:
type_title = music.find("div","_1fs8 fsm fwn fcg")
data['Type'].append(type_title.text)
except:
data['Type'].append("")
for link_music in f_music:
variable=link_music.find('a', href=re.compile('^https:'))['href']
data['Link'].append(variable)
for verified_page in f_music:
for page in verified_page:
page_verified = page.find_all('span',{'aria-label':'Verified Page'})
#print page_verified
check= "Verified Page"
for a in page_verified :
if check in a :
musicData['Link'].append(True)
else :
musicData['Link'].append(False)
#if sum([True for a in page_verified if check in a]) > 1:
# musicData['Link'].append(True)
#else :
# musicData['Link'].append(False)
#df = pd.DataFrame(data)
dr= pd.DataFrame(musicData)
#df
dr
* * *

## 
Desired Result - So I want the DataFrame column to be True if the page is
Verified. Wether a page is verified or not is defined by the span tag and
aria-label tag. (DataFrame is Boolean)
My logic- I will append True if the row has "Verified page" in it. else False.
But in this case all rows have "Verified Page" in it yet it goes to the else
part.
Is there any function in Python that helps me do it more efficiently or any
better way to achieve the desired result?
Answer: Looks like your `page_verified` variable is actually a list, that's why your
check returns false.
Example :
l = ['ab']
'a' in l
False
If the list returned is always containing one element, just do
if check in page_verified[0]:
if the returned list can be multi elements, you can try something like
(probably a better way to do it, but it'll work)
if sum([True for a in page_verified if check in a]) > 1:
** edit**
Please provide output of this so we can have more info
for music in f_music:
for verified_page in f_music:
for page in verified_page:
page_verified = page.find_all('span',{'aria-label':'Verified Page'})
print page_verified
check= "Verified Page"
print page_verified[0]
print type(page_verified[0])
print check in page_verified[0]
|
Robot Framework using Python, Key Press without selecting any button or element in the page
Question: I am automating one application using robot framework using Python. In a
certain situation I need to press enter without selecting any button or
element of the page once the page is loaded.
I have tried with the below example but it didn't work as I don't want to
select any specific button or element of the page before press enter on the
page.
Examples:
Press Key text_field q
Press Key login_button \\\13 # ASCII code for enter key
Below Keyword is not recognized by the IDE, most probably because of version:
Press Key Native
So can anyone give me a solution to get rid of this problem ?
Thanks in advance :)
Answer: Robot Framework Selenium library can only send keypresses to an element. If
you want to send actual keypresses, you need to write your own library that
does it. In Windows this can be done using SendKeys module.
Here is a library that defines "Send Enter Key" keyword for Robot Framework. I
tested it quickly on Chrome, it might have problems with PhantomJS.
import SendKeys
def send_enter_key():
"""
Sends ENTER key to application
Works only in Windows
"""
SendKeys.SendKeys("{ENTER}")
|
Use Line2D to plot line in python
Question: I have the data:
x = [10,24,23,23,3]
y = [12,2,3,4,2]
I want to plot it using
[matplotlib.lines.Line2D(xdata,
ydata)](http://matplotlib.org/api/lines_api.html#module-matplotlib.lines)
I use
import matplotlib.lines
matplotlib.lines.Line2D(x, y)
But how do I show the line?
Answer: You should add the line to a plot and then show it:
In [13]: import matplotlib.pyplot as plt
In [15]: from matplotlib.lines import Line2D
In [16]: fig = plt.figure()
In [17]: ax = fig.add_subplot(111)
In [18]: x = [10,24,23,23,3]
In [19]: y = [12,2,3,4,2]
In [20]: line = Line2D(x, y)
In [21]: ax.add_line(line)
Out[21]: <matplotlib.lines.Line2D at 0x7f4c10732f60>
In [22]: ax.set_xlim(min(x), max(x))
Out[22]: (3, 24)
In [23]: ax.set_ylim(min(y), max(y))
Out[23]: (2, 12)
In [24]: plt.show()
The result:

|
Removing duplicate users from a list using set()
Question: Trying to remove duplicate users from list with set in python. The problem is
that it is not removing the duplicate users:
with open ('live.txt') as file:
for line in file.readlines():
word = line.split()
users = (word[word.index('user')+1])
l = users.split()
l = set(l)
l = sorted(l)
print " ".join(l)
Here's the contents of `live.txt`:
Sep 15 04:34:24 li146-252 sshd[13320]: Failed password for invalid user ronda from 212.58.111.170 port 42201 ssh2
Sep 15 04:34:26 li146-252 sshd[13322]: Failed password for invalid user ronda from 212.58.111.170 port 42330 ssh2
Sep 15 04:34:28 li146-252 sshd[13324]: Failed password for invalid user ronda from 212.58.111.170 port 42454 ssh2
Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2
Sep 15 04:34:33 li146-252 sshd[13328]: Failed password for invalid user romero from 212.58.111.170 port 42715 ssh2
Sep 15 04:34:36 li146-252 sshd[13330]: Failed password for invalid user romero from 212.58.111.170 port 42838 ssh2
Answer: You can try a much simpler way as
list(set(<Your user list>))
This will return list with no duplicate. Python has datatype `set` which is
collection of unique element. So just by typecasting your `list` to `set` will
automatically remove the duplicates
Example:
>>> users = ['john', 'mike', 'ross', 'john','obama','mike']
>>> list(set(users))
['mike', 'john', 'obama', 'ross']
>>>
I hope this will solve your problem:
import re
def remove_me():
all_users = []
with open ('live.txt') as file:
for line in file.readlines():
pattern = re.compile('(.*user\s*)([a-zA-Z0-9]*)')
stmt = pattern.match(line)
all_users.append(stmt.groups()[1])
unique_users = list(set(all_users))
print unique_users
if __name__ == "__main__":
remove_me()
|
What's the best way of distinguishing bools from numbers in Python?
Question: I have an application where I need to be able to distinguish between numbers
and bools as quickly as possible. What are the alternatives apart from running
`isinstance(value, bool)` first?
Edit: Thanks for the suggestions. Actually, what I want to be able to do have
a check for numbers that leaves out bools so that I can reorder my checks
(numbers are far more prevalent) and improve my negacalls. `isinstance()`
itself is fast enough. The `x is True or x is False` is intriguing.
Answer: So, Padraic Cunningham suggests, that the following might be a bit faster. My
own quick experiments with `cProfile`-ing it haven't shown any difference:
isbool = value is True or value is False
I assume that's as fast as you can get: Two non-type-coercing comparisons.
**Edit:** I replayed the timing tests from @user 5061 and added my statement.
This is my result:
>>> import timeit
>>> stmt1 = "isinstance(123, bool)"
>>> stmt2 = "123 is True or 123 is False"
>>> t1 = timeit.timeit(stmt1)
>>> t2 = timeit.timeit(stmt2)
>>> print t1
0.172112941742
>>> print t2
0.0690350532532
**Edit 2:** Note, that I'm using Python 2.7 here. @user 5061 might use Python
3 (telling from the `print()` function), so any solution provided here should
be tested by OP before putting in production, for YMMV.
|
pylint says "Unnecessary parens after %r keyword"
Question: After my [first CodeReview
Q](http://codereview.stackexchange.com/questions/61798/mysql-class-to-add-
user-database) \- I got tip in answer:
> Your code appears to be for Python 2.x. To be a bit more ready for a
> possible future migration to Python 3.x, I recommend to start writing your
> print ... statements as print(...)
Thus, in my following code (I'm using Python 2.6 and 2.7 on my boxes) I always
us `()` for `print`:
print('Hello')
Today I first time test my code with PyLint, and it says:
> C: 43, 0: Unnecessary parens after 'print' keyword (superfluous-parens)
Which explained [here](http://pylint-messages.wikidot.com/messages:c0325).
So - does `print(str)` is really incorrect, or I can disregard this PyLint
messages?
Answer: To make pylint aware that you want to use the new print statement and not put
erroneous brackets simply use
from __future__ import print_function
at the beginning of your script. This has also the advantage that you
**always** need to use `print(...)` instead of `print ...`. Accordingly, your
program will throw a `SyntaxError` in case you fall back to the old syntax.
Be aware that this does not work in python 2.5 or older. But since you use 2.6
and 2.7, there should be no problem.
|
Python default logger disabled
Question: For some reason, in a Python application I am trying to modify, the logger is
not logging anything. I traced the error to `logging/__init__.py`
def handle(self, record):
"""
Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied.
"""
if (not self.disabled) and self.filter(record):
self.callHandlers(record)
I am not sure why, but `self.disabled` is `True`. Nowhere in the application
this value is set and I don't think any of the packages is changing it. The
logger is instantiated as usual `logger = logging.getLogger(__name__)`. When I
set `logger.disabled = False` before actually logging anything (before calling
`logger.info()`), the logger prints the expected log text. But if I don't, it
returns in `handle()` without logging anything.
Is there any way I can debug this? Perhaps one can change the `Logger` class
so that some function is called whenever `disabled` gets written to...
Answer: If you need to trace what code might set `handler.disabled` to True (it is 0,
so false, by default), you can replace the attribute it with a property:
import logging
import sys
def get_disabled(self):
return self._disabled
def set_disabled(self, disabled):
frame = sys._getframe(1)
if disabled:
print('{}:{} disabled the {} logger'.format(
frame.f_code.co_filename, frame.f_lineno, self.name))
self._disabled = disabled
logging.Logger.disabled = property(get_disabled, set_disabled)
Demo from the interactive interpreter:
>>> import logging
>>> logging.getLogger('foo.bar').disabled = True
<stdin>:1 disabled the foo.bar logger
|
Python higher order functions usage with str.startswith
Question: I have a file which I want to clean commented lines from. **I'd like to use
python`functools.partial` for the operation**, in something similar to the
following manner:
from functools import partial
f = open(filetoread, "r")
lines = f.readlines()
f.close()
# Filtering the comment lines
f_func = partial(str.startswith, prefix="#")
lines = filter(f_func, lines)
This does not work, apparently because `str.startswith` is a class method.
What is the proper way to use `functools.partial` with `str.startswith` so it
will work?
Answer: You have three problems:
First, `str.startswith` doesn't take keyword arguments, it takes positional
arguments only. It's implemented in C, and uses `PyArg_ParseTuple` to get its
positional arguments. There's nothing to tell Python what names they have,
since the name `prefix` appears only in the docstring. So `prefix=` is no
good. The problem is analogous to this:
>>> str.startswith('#hi', prefix='#')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: startswith() takes no keyword arguments
>>> def foo(self,prefix,start=None,end=None): return str.startswith(self,prefix,start,end)
...
>>> foo('#hi', prefix='#')
True
Second, the first argument of `str.startswith` is not the prefix, it's `self`,
the object in which we're checking whether or not it has the prefix. There's
no inherent problem with it being a method, you'd be fine if there was a
method called `str.isprefixof`, or if this method were implemented in Python.
But there isn't and it isn't.
Finally, `functools.partial` only lets you bind the initial positional
arguments, it doesn't know how to bind the second but not the first. Since the
argument you want to bind isn't the first and isn't accessible by name, you're
out of options.
There's a workaround for this case, though, to write functional-style code.
You just need `operator.methodcaller`, not `functools.partial`:
f_func = operator.methodcaller('startswith', '#')
`operator.methodcaller` binds all arguments _except_ the first.
* * *
Since you ask what's the proper way to use `functools`, I suppose you could do
so with an extra higher-order function to reverse the arguments:
def flip(func):
return lambda x,y: func(y,x)
f_func = partial(flip(str.startswith), '#')
You might consider this "cheating" since it uses a lambda, and if we wanted to
use a lambda we'd have used it like in Daniel's answer. But we're using it to
implement a basic higher-order function that Python doesn't provide, and once
that's out of the way the line to define `f_func` feels nice and functional.
Mind you, I'm not implementing that higher-order function particularly _well_
here in Python terms, since I don't provide any meta-data like `partial` does.
It has a `func` read-only attribute that users might reasonably want `flip` to
provide too.
Alternatively, you could write a Python wrapper to `str.startswith`, like
`foo` above, and apply `partial` to that.
|
How I can convert this matlab code to python?
Question: I would like to write the following operation from matlab to python(numpy).
repmat(sum(data,2),1,20);
Answer: have a look at [What is the equivalent of MATLAB's repmat in
NumPy](http://stackoverflow.com/questions/1721802/what-is-the-equivalent-of-
matlabs-repmat-in-numpy)
I would propose something like
import numpy as np
np.tile(np.sum(data, axis=1), 1, 20)
`axis=1` refers to the dimension along which the sum is taken. as far as I
remember, matlab starts index counting with 1, in python/numpy it starts with
0.
hope this is what you are looking for.
|
python / gspread - How to update a range of cells with a data list?
Question: I have a data list (extracted from CSV) and I'm trying to use Python / GSpread
to update a range of cells on a Google Doc. Here is my code sample:
import gspread
def write_spreadsheet(spreadsheet_name, sheet_id, data, start_row):
gc = gspread.login('[email protected]', 'password')
wks = gc.open(spreadsheet_name).get_worksheet(sheet_index)
start_letter = 'A'
end_letter = string.uppercase[len(data[0]) - 1]
end_row = start_row + len(data) - 1
range = "%s%d:%s%d" % (start_letter, start_row, end_letter, end_row)
print "Range is: " + range
cell_list = wks.range(range)
try:
for i, val in enumerate(data): #gives us a tuple of an index and value
cell_list[i].value = val #use the index on cell_list and the val from cell_values
#Update the whole sheet
wks.update_cells(cell_list)
except:
print "Exception"
this_data_ex = [['data1', 'data1'], ['data2', 'data2']]
write_spreadsheet('python-test', 1, this_data_ex, 1)
This works, but it does not separate the list row entries into the correct
columns. Output on Google sheets looks like this:
A B
['data1', 'data1'] ['data2', 'data2']
How can I fix the "try - for" section to write each data entry to a new cell,
then wrap the row at the correct place? (like this)
A | B
data1 | data1
data2 | data2
Answer: A Double nested for loop; one for the rows, one for the columns, then update
each cell individually. This section seemed to work properly with the desired
outcome:
try:
idx = 0
for (start_row, rowlist) in enumerate(data):
for (colnum, value) in enumerate(rowlist):
cell_list[idx].value = value
idx += 1
if idx >= len(cell_list):
break
# Update the whole sheet
wks.update_cells(cell_list)
|
Global name error when importing a function
Question: Trying to kill two birds with one stone I decided to write a bit of code that
would let me practice python and calculus at the same time. I have two
seperate files, Derivative.py and newton_method.py (I know I should get a bit
better about naming my files correctly). The text from Derivatibe.py is as
follows
def fx(value, function):
x = value
return eval(function)
def function_input(input):
function = str(input)
return function
def derivative_formula(x, h):
return (fx(x - h, input_function) - fx(x + h, input_function)) / (2.0 * h)
def derivative_of_x(x):
error = 0.0001
h = 0.1
V = derivative_formula(x, h)
print V
h = h / 2.0
derivative_estimate = derivative_formula(x, h)
while abs(derivative_estimate - V) < error:
V = derivative_formula(x, h)
h = h / 2.0
derivative_estimate = derivative_formula(x, h)
print derivative_estimate
return derivative_estimate
And the text from newton_method.py is:
from Derivative import *
input_function = function_input(raw_input('enter a function with correct python syntax'))
E = 1 * (10 ** -10)
guessx = float(raw_input('Enter an estimate'))
def newton_method(guessx, E, function):
x1 = guessx
x2 = x1 - (fx(x1, input_function) / derivative_of_x(x1))
while x2 - x1 < E:
x1 = x2
x2 = x1 - (fx(x1, input_function) / derivative_of_x(x1))
return x2
print "The root of that function is %f" % newton_method(guessx, E, input_function)
The error:
Traceback (most recent call last):
File "newton_method.py", line 17, in <module>
print "The root of that function is %f" % newton_method(guessx, E, input_function)
File "newton_method.py", line 11, in newton_method
x2 = x1 - (fx(x1, input_function) / derivative_of_x(x1))
File "C:\Users\159micarn\Desktop\Python\Derivative.py", line 15, in derivative_of_x
V = derivative_formula(x, h)
File "C:\Users\159micarn\Desktop\Python\Derivative.py", line 10, in derivative_formula
return (fx(x - h, input_function) - fx(x + h, input_function)) / (2.0 * h)
NameError: global name 'input_function' is not defined
Do I need to declare input_function in Derivative.py? I would have thought
that declaring it in newton_method.py would have been enough.
Answer: Modules do not have access to the namespaces of the modules that import them.
Imagine 10 modules importing `Derivative.py`. Which `input_function` would it
use? `input_function` is just and another value and should be an additional
input parameter to `derivative_formula`.
|
Python 2.7 - Having trouble outputting a command line percentage bar for large file download (I want output like: 0%...25%...50%...75%...100%)?
Question: Apologies if this seems a basic question, I have been trying to figure out how
to do this for the past hour with no progress. I have this method in Python
for downloading big (10GB+) files:
def downloadChunks(url, destination):
"""Helper to download large files
the file will be downloaded
in chunks and print out how much remains
modified slightly from: https://gist.github.com/gourneau/1430932
"""
baseFile = os.path.basename(url)
#move the file to a more uniq path
os.umask(0002)
try:
file = os.path.join(destination,baseFile)
req = urllib2.urlopen(url)
total_size = int(req.info().getheader('Content-Length').strip())
downloaded = 0
CHUNK = 256 * 10240 # 256 * 10240 == 2560 KB
with open(file, 'wb') as fp:
while True:
chunk = req.read(CHUNK)
downloaded += len(chunk)
#print math.floor( (downloaded / total_size) * 100 ),
if math.floor( (downloaded / total_size) * 100 ) % 100000000 ==0:
#print "downloaded ="+str(downloaded)+" bytes"
#print "total_size ="+str(total_size)+" bytes ("+str( (float(downloaded) / float (total_size)) )+"%)"
#print ""
if not chunk: break
fp.write(chunk)
except urllib2.HTTPError, e:
print "HTTP Error:",e.code , url
return False
except urllib2.URLError, e:
print "URL Error:",e.reason , url
return False
return file
**The problem:**
As this method runs I basically want output like so:
0%...25%...50%...75%...100% or 10%...20%... etc. (As they are big files I want
the granularity to be adjustable by a constant.)
I know to use print(message,end="") but I have been having trouble with the
algorithm.
**What I've tried:**
You can see some of my past experiments commented out, they gave this output,
which is obviously too long for a log file.
downloaded =2621440 bytes
total_size =611886812 bytes (0.00428419104414%)
downloaded =5242880 bytes
total_size =611886812 bytes (0.00856838208829%)
downloaded =7864320 bytes
total_size =611886812 bytes (0.0128525731324%)
downloaded =10485760 bytes
total_size =611886812 bytes (0.0171367641766%)
downloaded =13107200 bytes
total_size =611886812 bytes (0.0214209552207%)
downloaded =15728640 bytes
total_size =611886812 bytes (0.0257051462649%)
downloaded =18350080 bytes
total_size =611886812 bytes (0.029989337309%)
downloaded =20971520 bytes
total_size =611886812 bytes (0.0342735283531%)
downloaded =23592960 bytes
total_size =611886812 bytes (0.0385577193973%)
downloaded =26214400 bytes
total_size =611886812 bytes (0.0428419104414%)
downloaded =28835840 bytes
total_size =611886812 bytes (0.0471261014856%)
downloaded =31457280 bytes
total_size =611886812 bytes (0.0514102925297%)
downloaded =34078720 bytes
total_size =611886812 bytes (0.0556944835739%)
downloaded =36700160 bytes
total_size =611886812 bytes (0.059978674618%)
Just wondering if anyone can help me do this? Thanks very much.
**EDIT:**
I also wrote this small program, which gives incorrect output:
program:
#!/usr/bin/python
import os
import math
scale = 100.0
CHUNK_SIZE=77
FILE_SIZE_TOTAL =611886812
count =0.0
printnum = 25
numIncrememnts = math.floor( scale /printnum)
incrementsize = FILE_SIZE_TOTAL / numIncrememnts
output =0
while True:
if math.floor(count) % math.floor(incrementsize) ==0:
print str(output)+"%"
output= output+printnum
count = count+CHUNK_SIZE
if count >= FILE_SIZE_TOTAL:
break
output:
khennessy@organization-9758:~/Desktop/VM_deployer$ ./test3.py
0%
khennessy@organization-9758:~/Desktop/VM_deployer$
When CHUNK_SIZE ==1 it works fine though. Here is the output for that:
khennessy@organization-9758:~/Desktop/VM_deployer$ ./test3.py
0%
25%
50%
75%
khennessy@organization-9758:~/Desktop/VM_deployer$
**EDIT - My final answer:**
code:
def downloadChunks(url, destination):
"""Helper to download large files
the file will be downloaded
in chunks and print out how much remains
modified slightly from: https://gist.github.com/gourneau/1430932
"""
baseFile = os.path.basename(url)
#move the file to a more uniq path
os.umask(0002)
try:
file = os.path.join(destination,baseFile)
req = urllib2.urlopen(url)
total_size = int(req.info().getheader('Content-Length').strip())
downloaded = 0
CHUNK = 256 * 10240 # 256 * 10240 == 2560 KB
val = -1.0
savedval=0.0
with open(file, 'wb') as fp:
while True:
chunk = req.read(CHUNK)
downloaded += len(chunk)
savedval = val
val = 5 * (20 * downloaded / total_size)
if val != savedval:
printInfo(str(val)+"% downloaded. ("+str(downloaded)+" bytes / "+str(total_size)+" bytes)")
if not chunk: break
fp.write(chunk)
except urllib2.HTTPError, e:
print "HTTP Error:",e.code , url
return False
except urllib2.URLError, e:
print "URL Error:",e.reason , url
return False
return file
output:
[INFO] - 0% downloaded. (2621440 bytes / 611886812 bytes)
[INFO] - 5% downloaded. (31457280 bytes / 611886812 bytes)
[INFO] - 10% downloaded. (62914560 bytes / 611886812 bytes)
Thanks JuniorCompressor!
Answer: It seems you don't multiply your progress by 100 to get a percentage.
Also you can round this percentage like this:
print "total_size =%d bytes (%.0f%%)" % (total_size, 100. * downloaded / total_size)
If you want your percentages to be multiples of 25 you can use the following
code:
print "total_size =%d bytes (%d%%)" % (total_size, 25 * (4 * downloaded / total_size))
`4 * downloaded / total_size` because of the integer division can have `0, 1,
2, 3, 4` as possible values, depending on which range the progress belongs
(0%-25%, 25%-50%, 50%-75%, 75%-100%).
Similarly, you use `10 * (10 * downloaded / total_size)` to get multiples of
10.
|
How to add the OpenCV library to my Python library?
Question: Hey I'm new to python and I have to do a project that requires openCV and
Numpy. I'm currently using both Pycharm and Spyder as my IDE's and Windows as
an operating system. While found a executable for numpy. For the openCV I was
given a folder with about 300mb worth of files from the official site.
I ran the command
"setx -m OPENCV_DIR //MY DIRECTORY"
Like the official website instructed and it was successfully but I still can
use the openCV library. Can someone please tell me what to do with the folder,
the main website is tricky to me. I am still in college undergrad and I humbly
acknowledge my confusion. Even if the answer is simple, please scold me but
let me know what to do.
Answer: if you are using Ubuntu, you can install OpenCV module by typing:
sudo apt-get install python-opencv
you can Import like this
import cv2
|
Get timezone aware datetime
Question: How would I do the following to get a UTC datetime object, so django doesn't
complain about `/Library/Python/2.7/site-
packages/django/db/models/fields/__init__.py:808: RuntimeWarning:
DateTimeField received a naive datetime (2015-02-11 00:00:00) while time zone
support is active. ` ?
>>> from django.utils import timezone
>>> timezone.date(2014,1,1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'date'
Answer: Taking your example, you should use `datetime` and specify the tzinfo
argument:
timezone.datetime(2014, 1, 1, tzinfo=timezone.UTC())
You may also be interested in Django's `make_aware` function:
<https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.timezone.make_aware>
|
How to connect to localhost using Python's paramiko?
Question: I am totally new to implementing client-server communication and am trying to
get started with a very basic example using Python's paramiko module. All I
want to do is to send a simple string to my machine's localhost from one
terminal window and retrieve it from there in another terminal window.
This is what I have so far:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='localhost', username='myun', password='mypwd')
stdin, stdout, stderr = ssh.exec_command('echo "Hello"')
print stdout
ssh.close()
What is get is this:
Traceback (most recent call last):
File "./ssh.py", line 13, in <module>
ssh.connect(hostname='localhost', username='myun', password='mypwd')
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 251, in connect
retry_on_signal(lambda: sock.connect(addr))
File "/usr/local/lib/python2.7/site-packages/paramiko/util.py", line 270, in retry_on_signal
return function()
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 251, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 61] Connection refused
Can anybody please advise where I am going wrong here? Why can't I connect to
localhost using my correct username and password?
Answer: This should connect properly if SSH is accepting connections on localhost.
OpenSSH does by default. Check /etc/ssh/sshd_config and your firewall. Another
possibility is that "localhost" isn't configured properly in /etc/hosts. Try
with 127.0.0.1 or ::1.
Note that to get the actual stdout, use:
print stdout.read()
|
Simple development http-proxy for multiple source servers
Question: I developed till now with different webapp-servers (Tornado, Django, ...) and
am encountering the same problem again and again:
I want a simple web proxy (reverse proxy) that allows me, that I can combine
different source entities from other web-servers (that could be static files,
dynamic content from an app server or other content) to one set of served
files. That means, the browser should see them as if they come from one
source.
I know, that I can do that with nginx, but I am searching for an even simpler
tool for development. I want something, that can be started on command line
and does not need to run as root. Changing the configuration (routing of the
requests) should be as simple as possible.
In development, I just want to be able to mashup different sources. For
example: On my production server runs something, that I don't want to copy,
but I want to connect with static files on a different server and also a new
application on my development system.
Speed of the proxy is not the issue, just flexibility and speed of
development!
Preferred would be a Python or other scripting solution. I found also a big
list of Python proxys, but after scanning the list, I found that all are
lacking. Most of them just connect to one destination server and no way to
have multiple servers (the proxy has to decide which to take by analysis of
the local url).
I am just wondering, that nobody else has this need ...
Answer: You do not need to start nginx as root as long as you do not let it serve on
port 80. If you want it to run on port 80 as a normal user, [use
setcap](http://stackoverflow.com/questions/413807/is-there-a-way-for-non-root-
processes-to-bind-to-privileged-ports-1024-on-l). In combination with a script
that converts between an nginx configuration file and a route specification
for your reverse proxy, this should give you the most reliable solution.
If you want something simpler/smaller, it should be pretty straight-forward to
write a script using Python's `BaseHTTPServer` and `urllib`. Here's an example
that only implements `GET`, you'd have to extend it at least to `POST` and add
some exception handling:
#!/usr/bin/env python
# encoding: utf-8
import BaseHTTPServer
import SocketServer
import urllib
import re
FORWARD_LIST = {
'/google/(.*)': r'http://www.google.com/%s',
'/so/(.*)': r'http://www.stackoverflow.com/%s',
}
class HTTPServer(BaseHTTPServer.HTTPServer, SocketServer.ThreadingMixIn):
pass
class ProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
for pattern, url in FORWARD_LIST.items():
match = re.search(pattern, self.path)
if match:
url = url % match.groups()
break
else:
self.send_error(404)
return
dataobj = urllib.urlopen(url)
data = dataobj.read()
self.send_response(200)
self.send_header("Content-Length", len(data))
for key, value in dataobj.info().items():
self.send_header(key, value)
self.end_headers()
self.wfile.write(data)
HTTPServer(("", 1234), ProxyHandler).serve_forever()
|
AttributeError: object has no attribute 'runTest'
Question: I'm am new to `unittest` and I am not sure why I am getting this error:
runTest (__main__.TestTimeInterval)
No test ... Traceback (most recent call last):
File "/Users/bli1/Development/Trinity/qa-trinity/python_lib/qe/tests/test_timestamp_interval.py", line 122, in <module>
sys.exit(main(sys.argv))
File "/Users/bli1/Development/Trinity/qa-trinity/python_lib/qe/tests/test_timestamp_interval.py", line 110, in main
result_set = runner.run(suite)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/runner.py", line 168, in run
test(result)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/suite.py", line 87, in __call__
return self.run(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/suite.py", line 125, in run
test(result)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 625, in __call__
return self.run(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 555, in run
testMethod = getattr(self, self._testMethodName)
AttributeError: 'TestTimeInterval' object has no attribute 'runTest'
I wanted to create a simple test to see if everything is working properly but
I got the error above. I added the test to the suite and then ran it with
`.run()`
class TestTimeInterval(unittest.TestCase):
def __init__(self, log, runtag, interval, path_file):
super(TestTimeInterval, self).__init__()
self.interval = interval
self.path_file = path_file
self.log = log
self.runtag = runtag
def test_record(self):
self.assertTrue(1 > 0)
##############################################################################
def main(argv):
exit_code = 0
global me; me = os.path.basename(argv[0]) # name of this program
global mydir; mydir = os.path.dirname(os.path.abspath(__file__))
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument("file", metavar="FILE",
help="File filled with hdfs paths separated by newlines")
parser.add_argument("runtag", metavar="RUNTAG", help="tag for the test run")
parser.add_argument("-t", "--time", default="10", dest="interval",
help="Time interval (minutes) between server_timestamp and interval given by HDFS folder name")
args = parser.parse_args(args=argv[1:])
log = logging.getLogger(me)
logfile = args.runtag + ".log"
if os.path.exists(logfile):
os.remove(logfile)
log.addHandler(logging.FileHandler(logfile))
console = logging.StreamHandler(sys.stderr); console.setLevel(logging.WARNING); log.addHandler(console)
if exit_code == 0:
runner = unittest.TextTestRunner(stream=sys.stdout, descriptions=True, verbosity=2)
suite = unittest.TestSuite()
print(args)
suite.addTest(TestTimeInterval(log, args.runtag, args.interval, args.file))
try:
log.info("{0}: START: {1}".format(me, datetime.datetime.now().ctime()))
result_set = runner.run(suite)
except KeyboardInterrupt as e:
log.info("{0}: exit on keyboard interrupt".format(me))
exit_code = 1
else:
exit_code = len(result_set.errors) + len(result_set.failures)
finally:
log.info("{0}: FINISH: {1}".format(me, datetime.datetime.now().ctime()))
return exit_code
##############################################################################
# The following code calls main only if this program is invoked standalone
if __name__ == "__main__":
sys.exit(main(sys.argv))
Answer: You almost never need to create TestSuites and TestRunners yourself. Normally,
you'd do something like:
# my_test.py
import unittest
class Something(object):
def __init__(self):
self.foo = 1
class TestSomething(unittest.TestCase):
def setUp(self):
super(TestSomething, self).setUp()
self.something = Something()
def test_record(self):
self.assertTrue(1 > 0)
def test_something_foo_equals_1(self):
self.assertEqual(self.something.foo, 1)
if __name__ == '__main__':
unittest.main()
now, to run your test, you just execute your script.
python my_test.py
|
FieldStorage input removes some characters
Question: Putting "c++" in a input box, my Python script just receives "c".
Here's the HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
<input id="inputtxt" type="text">
<a onclick="window.location='escapetest.py?q='+document.getElementById('inputtxt').value;">Go!</a>
</body>
</html>
And the python script which receives the request:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cgitb; cgitb.enable()
from cgi import FieldStorage
inputstr = FieldStorage()["q"]
print "Content-Type: text/html; charset=utf-8"
print
print inputstr.value
The output is:
> c
Running Python 2.7 (x64) and using Firefox.
Answer: You are not properly escaping your value; the `+` character in a [URL-encoded
query value](https://en.wikipedia.org/wiki/Percent-
encoding#The_application.2Fx-www-form-urlencoded_type) is the encoded value
for a _space_ , so really you are printing:
"c "
A `c` with two spaces. Use the [`encodeURIComponent()`
function](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) to
properly escape the input value, where spaces will be replaced by `+` and `+`
will be replaced by `%2B`, so that Python can decode that back to `+`:
<a onclick="window.location='escapetest.py?q='+encodeURIComponent(document.getElementById('inputtxt').value);">Go!</a>
|
How to emulate Firefox "Save File" -> OK in Python
Question: My following code:
#!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
# Define firefox profile
download_dir = "/Users/pdubois/Desktop/TargetMine_Output/"
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", download_dir)
#fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
driver = webdriver.Firefox(fp)
driver.implicitly_wait(20)
genes = "Eif2ak2,Pcgf5,Vps25,Prmt6,Tcerg1,Dnttip2,Preb,Polr1b,Gabpb1,Prdm1,Fosl2,Zfp143,Psip1,Kat6a,Tgif1,Txn1,Irf8,Cnot6l,Zfp451,Foxk2,Lpxn,Etv6,Khsrp,Lmo4,Nkrf,Mafk,Mbd1,Cited2,Elp5,Jdp2,Bzw1,Rbm15b,Klf9,Gtf2e2,Dynll1,Klf6,Stat1,Srrt,Gtf2f1,Adnp2,Ikbkg,Mybbp1a,Nup62,Brd2,Chd1,Kctd1,Sap30,Cebpd,Mtf1,Gtf2h2,Fubp1,Tcea1,Irf2bp2,Ezh2,Hnrpdl,Pml,Cebpz,Med7"
targetmine_url = "http://targetmine.nibio.go.jp/targetmine/begin.do"
driver.get(targetmine_url)
# Define type of list to be submitted
gene_select = Select(driver.find_element_by_name("type"))
gene_select.select_by_visible_text(u"Gene")
# Enter list and submit
gene_input = driver.find_element_by_id("listInput")
gene_input.send_keys(genes)
submit = driver.find_element_by_css_selector("input.button.light").click()
# Choose name for list
driver.find_element_by_id("newBagName").clear()
driver.find_element_by_id("newBagName").send_keys("ADX.06.ID.Clust1")
driver.switch_to_frame("__pomme::0")
# Add All
driver.find_element_by_css_selector("span.small.success.add-all.button").click()
# Save all genes
driver.find_element_by_css_selector("a.success.button.save").click()
# Select M. Musculus
driver.find_element_by_xpath("//ul[@id='customConverter']/li[2]/a[1]").click()
# Gene enrchment part
go_xpath = "//div[@id='gene_go_enrichment-widget']/div[@class='inner']/div[1]/div[@class='form']/form[@style='margin:0']/div[2]/select[1]"
#driver.find_element_by_xpath(go_xpath).click()
go_select = Select(driver.find_element_by_xpath(go_xpath))
go_select.select_by_visible_text(u"1.00")
# Download
#driver.find_element_by_css_selector("a.btn.btn-small.export").click()
Works fine. Which end with this instances:

One last thing I want to achieve then is to _Save the file automatically_.
Despite I've already set the Firefox profile at the top of the code, it
doesn't do as I hoped. What's the right way to do it?
**Update:**
The solution by alecxe works. Except I tried this, it doesn't save the file.
go_download_xpath = "//div[@id='gene_go_enrichment-widget']/div[@class='inner']/div[1]/div[2]/a[@class='btn btn-small export']"
driver.find_element_by_xpath(go_download_xpath).click()
# it saved the specific desired file.
# using
#driver.find_element_by_css_selector("a.btn.btn-small.export").click()
#save the wrong file.
Answer: This particular dialog _cannot be controlled via selenium_ \- this is a
browser popup, not a javascript popup (which can be automated with
`swith_to.alert`).
In this case, you need to avoid the popup being shown in the first place and
make Firefox download the file automatically by tweaking browser's _desired
capabilities_ (aka profile preferences). Firefox can download files
automatically depending on the _mime-type_ of the file being downloaded. In
your case it is `text/plain`:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.dir", download_dir)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
driver = webdriver.Firefox(firefox_profile=fp)
* * *
FYI, I've downloaded the file manually and used [`magic`
module](https://github.com/ahupp/python-magic) to [detect the mime-
type](http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-
file-in-python):
In [1]: import magic
In [2]: mime = magic.Magic(mime=True)
In [3]: mime.from_file("result.tsv")
Out[3]: 'text/plain'
|
Python CSV library returning 1 item instead of a list of items
Question: Im trying to use the CSV library to do some excel processing, but when I use
the code posted below, row returns the entirety of data as 1 item, so row[0]
returns the entire file and row[1] returns index out of range. Is there a way
to make each row a list with each cell being an item? Making the final product
a list of lists. I was thinking of using split everytime ther was a close
bracket ']' . If needed I can post the excel file
Heres a sample of what some of the output looks like. This is all one item in
the list:
['3600035671,"$13,668",8/11/2008,8/11/2013,,,2,4A,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,']
['3910435005,"$34,872",4/1/2010,10/8/2016,,,2,4A,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,']
['5720636344,"$1,726",8/30/2010,9/5/2011,,,3,6C,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,']
['15260473510,"-$1,026,580",7/22/2005,3/5/2008,,,6,1C2A,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,']
import csv
csvfile = open('Invictus.csv', 'rU')
data = csv.reader(csvfile, dialect=csv.excel_tab)
for char in data:
char = filter(None, char)
print char
Answer: Assuming you are giving examples of your data above the line `import csv`, it
looks like your data is comma delimited but you are setting up your CSV reader
to expect tab delimited data (`dialect=csv.excel_tab`).
What happens if you change that line to:
data = csv.reader(csvfile, dialect=csv.excel)
|
share datastore python between modules in google app engine
Question: Im studying about GAE, Im trying to build a app with 2 module: default module
and count module. Count module increaces value of Count object in datastore by
1 every min. default module access Count object and show its current value.
I setup default module as index.py in root directory.
Count object in Global.py in /global/
Count-module as count.py in /count/
I can access Count object form index.py through:
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "global"))
from Global import Count
But I cannot access Count object from count.py in count-module:
sys.path.append(os.path.join(os.path.dirname(__file__),
"..",
"global")
)
from Global import Count
\--> ImportError: No module named Global Someone help me?
Answer: You don't need folders, but if you do use empty `__init__.py` inside of each
to make them python modules. Your project structure can be:
index.py
count.py
global.py
Then you will be able to import files from each module without changing
`sys.path`. If you want folders then read this answer [What is __init__.py
for?](http://stackoverflow.com/questions/448271/what-is-init-py-for).
**Upd.** By the way, use `global` for module name is bad idea. It is reserved
word.
|
Dictionaries and files in python
Question: Hey guys first time question here.
I'm trying to figure out how to create a dictionary containing keys as ID's,
and values as another dictionary containing scores for homework essays and
exam's for that individuals ID.
Example:
{"173-25-6389":
{
"hw":[94,89,92,73],
"quiz":[45,36,42,50,22,27,40,41],
"exam":[135,127]
},
.....
}
These numbers are being pulled from separate files representing the categories
and are each matched with their corresponding ID.
I have 4 files to work with and one of them just contains the IDs which I
think I will apply to the keys in the larger dictionary.
My main issue is that inside of the files, each line is written like:
> 173-25-6389 61
So it's the `id` plus a `space` and then the `score`. I'm not sure how to run
through the file and search for the other scores that have the same ID.
I'm just a bit confused as to how to find a list of the scores, and then add
that to a dictionary as the value for the larger dictionary containing the
ID's. Any insight as to how to precede would really be amazing and if you need
me to elaborate more let me know.
I have only been coding for about a year so go easy on me. Thanks
Answer: So let's assume you already know how to open the file and read it line-by-
line. For each line you have an id and a score, but you don't know if the
score already exists in your result dict. Frankly, you'd rather not care.
Enter
[defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict).
It guarantees you a useful value even if the particular key doesn't exist.
from collections import defaultdict
…
result = defaultdict(dict) # an undefined key will map an empty dict
for line in scorefile:
id, score = line.split()
result[id]['hw'] = score
But wait, that will overwrite our 'hw' key with a single score! We wanted a
list!
Let's double down on this defaultdict.
# an undefined key will map a defaultdict
# whose undefined keys will map an empty list
result = defaultdict(lambda: defaultdict(list))
for line in scorefile:
id, score = line.split()
result[id]['hw'].append(score)
Now, you didn't say how we were to tell homework from exam scores, so I'll
leave that bit up to you…
|
Python subclassing process with parameter
Question: I'm trying to create an object but as a new process. I'm following [this
guide](http://pymotw.com/2/multiprocessing/basics.html#subclassing-process)
and came up with this code.
import multiprocessing as mp
import time
class My_class(mp.Process):
def run(self):
print self.name, "created"
time.sleep(10)
print self.name, "exiting"
self.x()
def x(self):
print self.name, "X"
if __name__ == '__main__':
print 'main started'
p1=My_class()
p2=My_class()
p1.start()
p2.start()
print 'main exited'
But here I'm unable to pass arguments to the object. I searched but found
none. It's not like a normal multiprocess where we'd be doing something like:
p1 = multiprocessing.Process(target=My_class, args=('p1',10,))
to pass the arguments to the new process. But the multiprocessing for a class
instance is different. For now I'm passing it the hard way like below.
import multiprocessing as mp
import time
class My_class(mp.Process):
my_vars={'name':'', 'num':0}
def run(self):
self.name=My_class.my_vars['name']
self.num=My_class.my_vars['num']
print self.name, "created and waiting for", str(self.num), "seconds"
time.sleep(self.num)
print self.name, "exiting"
self.x()
def x(self):
print self.name, "X"
if __name__ == '__main__':
print 'main started'
p1=My_class()
p2=My_class()
My_class.my_vars['name']='p1'
My_class.my_vars['num']=20
p1.start()
My_class.my_vars['name']='p2'
My_class.my_vars['num']=10
p2.start()
print 'main exited'
Which is working fine. But I guess it may fail for complex arguments like a
large list or object or something like that.
Is there any other method to pass the arguments??
Answer: You can just implement an `__init__` method for `My_class`, which takes the
two parameters you want to provide:
import multiprocessing as mp
import time
class My_class(mp.Process):
def __init__(self, name, num):
super(My_class, self).__init__()
self.name = name
self.num = num
def run(self):
print self.name, "created and waiting for", str(self.num), "seconds"
time.sleep(self.num)
print self.name, "exiting"
self.x()
def x(self):
print self.name, "X"
if __name__ == '__main__':
print 'main started'
p1=My_class('p1', 20)
p2=My_class('p2', 10)
p1.start()
p2.start()
print 'main exited'
You just need to be sure to call `super(My_class, self).__init__()` in your
`__init__` method, so that your class is properly initialized as a `Process`
subclass.
|
Sorting by value in a python dictionary?
Question: I have an assignment in which a series of items and the amount a store carries
of that item is given which I then have to put into a dictionary and display
with the highest amount of stock to the lowest amount of stock. The dictionary
looks a bit like this:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
and the output would look like this:
keyboards: 56
hammers: 33
socks: 10
After getting the dictionary set up, I'm having difficulty with the second
part... does anyone know how I could sort by value?
Answer: It's easy to make a sorted list of (key, value) pairs:
import operator
slop = sorted(thelist.items(), key=operator.itemgetter(1), reverse=True)
and then you can loop over it to display it, e.g in Python 2:
for k, v in slop:
print '{}: {}'.format(k, v),
print
|
Print string left aligned with fixed width and suffix
Question: Using Pythons string formatting, is there a nice way to add a suffix to a left
aligned string that is padded to a fixed size?
I want to print a list of key-value-pairs in the following formatting:
a_key: 23
another_key: 42
...
The problem is the ':'. The best solution I found so far is to append the ':'
to the key name:
print "{:<20} {}".format(key+':', value)
But I think this is a rather ugly solution, as it diminishes the separation of
formatting and values. Is it possible to achieve this directly in the format
specification?
What I am looking for is something like this:
print "{do something here} {}".format(key, value)
Answer: You cannot change `"".format()` as it is a built-in but if it is acceptable to
provide the string and parameters to a method:
print(kf.format("{:t{}} {}", key, ':', value))
you can do so by subclassing `string.Formatter` to allow empty format fields
and provide a special type handler `t`:
from string import Formatter
import sys
if sys.version_info < (3,):
int_type = (int, long)
else:
int_type = (int)
class TrailingFormatter(Formatter):
def vformat(self, *args):
self._automatic = None
return super(TrailingFormatter, self).vformat(*args)
def get_value(self, key, args, kwargs):
if key == '':
if self._automatic is None:
self._automatic = 0
elif self._automatic == -1:
raise ValueError("cannot switch from manual field specification "
"to automatic field numbering")
key = self._automatic
self._automatic += 1
elif isinstance(key, int_type):
if self._automatic is None:
self._automatic = -1
elif self._automatic != -1:
raise ValueError("cannot switch from automatic field numbering "
"to manual field specification")
return super(TrailingFormatter, self).get_value(key, args, kwargs)
def format_field(self, value, spec):
if len(spec) > 1 and spec[0] == 't':
value = str(value) + spec[1] # append the extra character
spec = spec[2:]
return super(TrailingFormatter, self).format_field(value, spec)
kf = TrailingFormatter()
w = 20
ch = ':'
x = dict(a_key=23, another_key=42)
for k in sorted(x):
v = x[k]
print(kf.format('{:t{}<{}} {}', k, ch, w, v))
gives you:
a_key: 23
another_key: 42
You can of course hardcode the `ch`, and `w` values:
print(kf.format('{:t:<20} {}', k, v))
for better readability, but less flexibility.
* * *
A backport of the Python 3.4 string.Formatter() that includes a bugfix for
versions (at least) up to 3.5.0rc1, that includes this code is now available
on [PyPI](https://pypi.python.org/pypi/string_formatter)
|
Matplotlib lines do not join smoothly, Python
Question: I am using matplotlib to draw the outline of a cylindrical body, however the
lines do not want to join up smoothly, as seen in the range x[40,60].

It is really subtle in this image I know, but it is unfortunately not
acceptable for my purposes. I hope it is visible for you to see.
Using more data points does not seem to make a difference.
Is there a way to get curved lines to join up more smoothly in matplotlib?
Original code:
import numpy as np
import matplotlib.pylab as plt
length = 100.
a = 40
b = 20
n = 2.
alpha = np.radians(25.)
d = 18.
x_nose = np.linspace(0,a,1000)
r_nose = (0.5*d*(1 - ((x_nose-a)/a)**2)**(1/n))
x_mid = np.linspace(x_nose[-1],a+b,2)
r_mid = np.array([r_nose[-1],r_nose[-1]])
x_tail = np.linspace(x_mid[-1],length,1000)
l_tail = length-a-b
r_tail = (0.5*d - ((3*d)/(2*l_tail**2) - np.tan(alpha)/l_tail)*(x_tail-a-b)**2 + (d/l_tail**3 - np.tan(alpha)/l_tail**2)*(x_tail-a-b)**3)
fig = plt.figure()
plt.plot(x_nose,r_nose,'k',linewidth=2,antialiased=True)
plt.plot(x_mid,r_mid,'k',linewidth=2,antialiased=True)
plt.plot(x_tail,r_tail,'k',linewidth=2,antialiased=True)
plt.axis('equal')
plt.show()
You can see the effect more easily when zoomed in:

Answer: I'm not sure why this is happening, but you may be able to mitigate by
constructing a single `x` and `r` array with the full line to draw.
x = np.append(x_nose, x_mid)
x = np.append(x, x_tail )
r = np.append(r_nose, r_mid)
r = np.append(r, r_tail )
plt.plot(x,r,'k',linewidth=2,antialiased=True)
This obviously prevents you altering line styles of individual elements, but
it looks like you don't want to do that. This works for me:

|
pysqlcipher installation - SyntaxError: Missing parentheses in call to 'print'
Question: I have Python 3.4.2, and I try to install **pysqlcipher** on my PC with
windows 8. After having entered the code below in my command prompt:
git clone https://github.com/leapcode/pysqlcipher/
cd pysqlcipher
python setup.py build_sqlcipher
I’m getting the following error:
File "setup.py", line 64
print "CFLAGS", os.environ['CFLAGS']
^
SyntaxError: Missing parentheses in call to 'print'
It seems to be a problem with print. I have _Python 3.4.2_ , and the print
syntax used here corresponds to _Python 2.X_. I have done lot of searching but
I haven’t found any solution.
**Does someone know how to install pysqlcipher with Python 3.4.2?**
Thank you for your help!
**PS:** I have already followed this
[tutorial](http://www.jerryrw.com/howtocompile.php) and all things indicated
have been accomplished.
Answer: It looks like the code is written for Python 2. Python 3 contains several
changes that can make some Python 2 incompatible with Python 3.
[Differences between python 2 and python
3](https://wiki.python.org/moin/Python2orPython3)
You can use the included 2to3 tool to convert the `setup.py` and
`cross_bdist_wininst.py` into python 3 compatible code.
Just run `2to3 -w setup.py` and `2to3 -w cross_bdist_wininst.py` to convert
the python code. The automatic convert works quite well but it does miss out
one conversion that is necessary. Change line 209 in `setup.py`
-- if sources is None or type(sources) not in (ListType, TupleType):
++ if sources is None or type(sources) not in (List, Tuple):
and remove line 30:
-- from types import ListType, TupleType
This should then allow you to compile the using `python setup.py
build_sqlcipher`
|
python serial error raspberry-pi gps module
Question: I am trying to use python serial (for python 2.7) to read data from a gps
device (ublox EVK-7P). I am using the following code:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import time
import serial
ser = serial.Serial('/dev/ttyUSB7', 9600, timeout = 5)
ser.open()
while True:
print ser.readline()
The following error comes up when I try to run the program-
File "./gps2.py", line 7, in <module>
ser = serial.Serial('/dev/ttyUSB7',9600,timeout = 5)
File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 260, in __init__
self.open()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 276, in open
raise SerialException("could not open port %s: %s" % (self._port, msg))
serial.serialutil.SerialException: could not open port /dev/ttyUSB7: [Errno 2] No such file or directory: '/dev/ttyUSB7'
Out of curiosity I used 'sudo lsusb' in the terminal. I got the following:
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 004: ID 05e3:0608 Genesys Logic, Inc. USB-2.0 4-Port HUB
Bus 001 Device 005: ID 062a:0201 Creative Labs Defender Office Keyboard (K7310) S Zodiak KM-9010
Bus 001 Device 006: ID 093a:2510 Pixart Imaging, Inc. Optical Mouse
Bus 001 Device 007: ID 1546:01a7 U-Blox AG
Could anyone please help me out? Please tell me what am I doing wrong. I'm
using an external mouse and keyboard and plugged another usb drive into the pi
(all done using a 4-to-1 usb connector plugged to the pi).
Thanks
Answer: Using `dmsg` after plugging you HW will give you the correct /dev device to
use. You can check that it exists : `ls -lsah /dev/ttyUSB*` and that your user
has the correct permission to use it.
|
Issue installing Theano in my virtualenv
Question: I'm trying to install Theano in a virtualenv:
(dnouri_tut)[xxx@xxx virtualenvs]$ pip install Theano
but I get the following error:
Installing collected packages: scipy, numpy, Theano
Running setup.py install for scipy
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-JcZ_Qe/scipy/setup.py", line 249, in <module>
setup_package()
File "/tmp/pip-build-JcZ_Qe/scipy/setup.py", line 237, in setup_package
from numpy.distutils.core import setup
ImportError: No module named numpy.distutils.core
Complete output from command /home/xxx/virtualenvs/dnouri_tut/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-JcZ_Qe/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-T3NhHj-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/xxx/virtualenvs/dnouri_tut/include/site/python2.6:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-JcZ_Qe/scipy/setup.py", line 249, in <module>
setup_package()
File "/tmp/pip-build-JcZ_Qe/scipy/setup.py", line 237, in setup_package
from numpy.distutils.core import setup
ImportError: No module named numpy.distutils.core
----------------------------------------
Command "/home/xxx/virtualenvs/dnouri_tut/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-JcZ_Qe/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-T3NhHj-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/xxx/virtualenvs/dnouri_tut/include/site/python2.6" failed with error code 1 in /tmp/pip-build-JcZ_Qe/scipy
I would like not to depend on any system package, so I didn't use the option "
--system-site-packages" to create my virtualenv.
Anybody can help?
Answer: As pointed out by user1615070, I just had to install numpy and scipy in my
virtualenv before installing Theano (to not use the system versions).
|
Explanation of Python doc argument syntax
Question: Is anyone able to help me to understand the syntax of arguments being passed
to some methods in the Python doc?
Examples of the type of things that are confusing me would be from the iter()
function
iter(o[, sentinel])
From my understanding this is equivalent to
iter(o, sentinel)
but as to why I really don't understand.
Answer: `function(mandatory_argument[, optional_argument]` represents an optional
argument that will alter the function if provided. In the [`iter()`
documentation](https://docs.python.org/3.4/library/functions.html#iter):
> The first argument is interpreted very differently depending on the presence
> of the second argument.
In what way optional arguments alters the function should be described in the
documentation to it.
Optional arguments can be nested, so you may see something like
([source](https://docs.python.org/3.4/library/functions.html#bytearray)):
bytearray([source[, encoding[, errors]]])
That means that each of the arguments are optional, but builtin upon the
previous ones. So the following are all valid calls:
bytearray(source)
bytearray(source, encoding)
bytearray(source, encoding, errors)
But this is not:
bytearray(source, errors=errors)
There is a second way to indicate that arguments are optional:
__import__(name, globals=None, locals=None, fromlist=(), level=0)
This tells us that all these arguments (but name) are optional and also tells
us the default for when we do not provide arguments for them.
On the code site in pure python you can get optional arguments by:
def iter(o, sentinel=None):
[do something]
But this would not be documented the way above, as we can see in the example
of
[`__import__`](https://docs.python.org/3.3/library/functions.html#__import__):
__import__(name, globals=None, locals=None, fromlist=(), level=0)
To see why `iter` is different read the section at the end of my post.
Also note that in the example of the `iter()` builtin you can **not** provide
sentinel as keyword argument and trying will raise a TypeError:
>>> iter([], sentinel=None)
Traceback (most recent call last):
File '<stdin>', line1, in <module>
TypeError: iter() takes no keyword arguments
in other cases though it may be possible:
>>> bytearray('', encoding='UTF-8')
bytearray(b'')
It is still true that providing a later argument without the previous ones
will raise an error.
>>> bytearray('', errors='')
Traceback (most recent call last):
File '<stdin>', line 1, in <module>
TypeError: string argument without an encoding
The "keyword like syntax" is the "normal" way to document optional arguments
in python. Why is `iter` different? `iter` is a builtin and not implemented in
python but in C. If we look at the [source code](https://github.com/python-
git/python/blob/master/Python/bltinmodule.c#L1274) of it we see that it treats
the arguments as a tuple that may have one or two arguments.
builtin_iter(PyObject *self, PyObject *args)
{
PyObject *v, *w = NULL;
if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
return NULL;
if (w == NULL)
return PyObject_GetIter(v);
if (!PyCallable_Check(v)) {
PyErr_SetString(PyExc_TypeError,
"iter(v, w): v must be callable");
return NULL;
}
return PyCallIter_New(v, w);
}
This might explain the "list-like syntax". It seems that the
`[optional_argument]` notation is only used in modules that are programmed in
C. For the normal user it makes no difference if there is
function([optional_argument])
or
function(optional_argument=True)
|
Python - FileNotFoundError when dealing with DMZ
Question: I created a python script to copy files from a source folder to a destination
folder, the script runs fine in my local machine.
However, when I tried to change the source to a path located in a server
installed in a DMZ and the destination to a folder in a local servers I got
the following error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: '\reports'
And Here is the script:
import sys, os, shutil
import glob
import os.path, time
fob= open(r"C:\Log.txt","a")
dir_src = r"\reports"
dir_dst = r"C:\Dest"
dir_bkp = r"C:\Bkp"
for w in list(set(os.listdir(dir_src)) - set(os.listdir(dir_bkp))):
if w.endswith('.nessus'):
pathname = os.path.join(dir_src, w)
Date_File="%s" %time.ctime(os.path.getmtime(pathname))
print (Date_File)
if os.path.isfile(pathname):
shutil.copy2(pathname, dir_dst)
shutil.copy2(pathname, dir_bkp)
fob.write("File Name: %s" % os.path.basename(pathname))
fob.write(" Last modified Date: %s" % time.ctime(os.path.getmtime(pathname)))
fob.write(" Copied On: %s" % time.strftime("%c"))
fob.write("\n")
fob.close()
os.system("PAUSE")
Answer: Okay, we first need to see what kind of remote folder you have.
1. If your remote folder is shared windows network folder, try mapping it as a network drive: <http://windows.microsoft.com/en-us/windows/create-shortcut-map-network-drive#1TC=windows-7> Then you can just use something like Z:\reports to access your files.
2. If your remote folder is actually a unix server, you could use paramiko to access it and copy files from it:
import paramiko, sys, os, posixpath, re
def copyFilesFromServer(server, user, password, remotedir, localdir, filenameRegex = '*', autoTrust=True):
# Setup ssh connection for checking directory
sshClient = paramiko.SSHClient()
if autoTrust:
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #No trust issues! (yes this could potentially be abused by someone malicious with access to the internal network)
sshClient.connect(server,user,password)
# Setup sftp connection for copying files
t = paramiko.Transport((server, 22))
t.connect(user, password)
sftpClient = paramiko.SFTPClient.from_transport(t)
fileList = executeCommand(sshclient,'cd {0}; ls | grep {1}'.format(remotedir, filenameRegex)).split('\n')
#TODO: filter out empties!
for filename in fileList:
try:
sftpClient.get(posixpath.join(remotedir, filename), os.path.join(localdir, filename), callback=None) #callback for showing number of bytes transferred so far
except IOError as e:
print 'Failed to download file <{0}> from <{1}> to <{2}>'.format(filename, remotedir, localdir)
`
3. If your remote folder is something served with the webdav protocol, I'm just as interested in an answer as you are.
4. If your remote folder is something else still, please explain. I have not yet found a solution that treats all equally, but I'm very interested in one.
|
ValueError: too many values to unpack Tkinter Listbox
Question: When writing a simple program to output the values and keys in a dictionary to
a listbox in python using Tkinter I get the following error:
for key, value in mydict.itervalues():
ValueError: too many values to unpack
Please see my code below:
#!/usr/bin/python
import Tkinter as tk
mydict = {"0x00063":"6F 7D 9E 0E FF FF FF FF",
"0x00061":"FF FF FF FF FF FF FF FF",
"0x00062":"AA AA AA AA AA AA AA AA",
"0x00064":"00 00 00 00 00 00 00 00"}
guiMain = tk.Tk()
recvDisplay = tk.Listbox(guiMain)
for key, value in mydict.itervalues():
recvDisplay.insert(key, value)
recvButton = tk.Button(guiMain, text="Start Receive")
tranDisplay = tk.Listbox(guiMain)
tranButton = tk.Button(guiMain, text="Start Transmit")
recvDisplay.pack()
recvButton.pack()
tranDisplay.pack()
tranButton.pack()
guiMain.mainloop()
I need to be able to output the values and keys within to dictionary to the
listbox `recvDisplay`, but I need the listbox to automatically refresh so it
displays any changes to the dict.
Answer: [`mydict.itervalues()`](https://docs.python.org/2/library/stdtypes.html#dict.itervalues)
is an iterator over the values in `mydict`. If you want both the keys and the
values, use
[`mydict.iteritems()`](https://docs.python.org/2/library/stdtypes.html#dict.iteritems):
for key, value in mydict.iteritems():
recvDisplay.insert(tk.END, '{}, {}'.format(key, value))
Note: A Listbox only has one column. If you want multiple columns to display
the key and value separately, you will need a different widget, such as a
[treectrl.MultiListbox](http://stackoverflow.com/q/5286093/190597), or put two
`Listboxes` side-by-side.
|
Python ta-lib with pandas.io.data: candlestick not plotting but other charts are ok
Question: iPython 2.3.1, OS-X Yosemite 10.10.2
Python print (sys.version):
2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)]
The following code works for data pulled for US stock data e.g. make the
security id "INTC" for Intel. However when I access data for European stocks,
the candlestick function fails even though all the OHLC data is there in the
dataframe. Have put the full code in here to show that the other tech analysis
charts plot just fine for the European stock data.
import pandas.io.data as web
import pandas as pd
import numpy as np
import talib as ta
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
from matplotlib.finance import candlestick
import datetime
ticker = 'DNO.L'
# Download sample data
sec_id = web.get_data_yahoo(ticker, '2014-06-01')
# Data for matplotlib finance plot
sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index),
'1':sec_id.Open,
'2':sec_id.Close,
'3':sec_id.High,
'4':sec_id.Low}))
# Technical Analysis
SMA_FAST = 50
SMA_SLOW = 200
RSI_PERIOD = 14
RSI_AVG_PERIOD = 15
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
STOCH_K = 14
STOCH_D = 3
SIGNAL_TOL = 3
Y_AXIS_SIZE = 12
analysis = pd.DataFrame(index = sec_id.index)
analysis['sma_f'] = pd.rolling_mean(sec_id.Close, SMA_FAST)
analysis['sma_s'] = pd.rolling_mean(sec_id.Close, SMA_SLOW)
analysis['rsi'] = ta.RSI(sec_id.Close.as_matrix(), RSI_PERIOD)
analysis['sma_r'] = pd.rolling_mean(analysis.rsi, RSI_AVG_PERIOD) # check shift
analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = \
ta.MACD(sec_id.Close.as_matrix(), fastperiod=MACD_FAST, slowperiod=MACD_SLOW, signalperiod=MACD_SIGNAL)
analysis['stoch_k'], analysis['stoch_d'] = \
ta.STOCH(sec_id.High.as_matrix(), sec_id.Low.as_matrix(), sec_id.Close.as_matrix(), slowk_period=STOCH_K, slowd_period=STOCH_D)
analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)
analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1, 0)
analysis['stoch_k_test'] = np.where((analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0)
analysis['rsi_test'] = np.where((analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)
# Prepare plot
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
ax1.set_ylabel(ticker, size=20)
#size plot
fig.set_size_inches(15,30)
# Plot candles
candlestick(ax1, sec_id_ochl, width=0.5, colorup='g', colordown='r', alpha=1)
# Draw Moving Averages
analysis.sma_f.plot(ax=ax1, c='r')
analysis.sma_s.plot(ax=ax1, c='g')
#RSI
ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
analysis.rsi.plot(ax = ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
analysis.sma_r.plot(ax = ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
ax2.axhline(y=30, c='b')
ax2.axhline(y=50, c='black')
ax2.axhline(y=70, c='b')
ax2.set_ylim([0,100])
handles, labels = ax2.get_legend_handles_labels()
ax2.legend(handles, labels)
# Draw MACD computed with Talib
ax3.set_ylabel('MACD: '+ str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' + str(MACD_SIGNAL), size=Y_AXIS_SIZE)
analysis.macd.plot(ax=ax3, color='b', label='Macd')
analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
ax3.axhline(0, lw=2, color='0')
handles, labels = ax3.get_legend_handles_labels()
ax3.legend(handles, labels)
# Stochastic plot
ax4.set_ylabel('Stoch (k,d)', size=Y_AXIS_SIZE)
analysis.stoch_k.plot(ax=ax4, label='stoch_k:'+ str(STOCH_K), color='r')
analysis.stoch_d.plot(ax=ax4, label='stoch_d:'+ str(STOCH_D), color='g')
handles, labels = ax4.get_legend_handles_labels()
ax4.legend(handles, labels)
ax4.axhline(y=20, c='b')
ax4.axhline(y=50, c='black')
ax4.axhline(y=80, c='b')
plt.show()

Answer: pandas data.index needs to convert datetype.
import matplotlib.dates as mdates
...
In your code, before sec_id_ochl:
# Data for matplotlib finance plot
sec_id.index = mdates.date2num(sec_id.index.to_pydatetime())
|
How to calculate word frequency of a string phrase in a column of a csv file using python?
Question: So my problem is that I have a csv file is structured something like this:
"L.Name", "F. Name", "Gender", "School Type", "Subjects"
"Doe", "John", "M", "University", "Chem I, statistics, English, Anatomy"
"Tan", "Betty", "F", "High School", "Algebra I, chem I, English 101"
"Han", "Anna", "F", "University", "PHY 3, Calc 2, anatomy I, spanish 101"
"Hawk", "Alan", "M", "University", "English 101, chem I,"
What I need to do is count the amount of times a subject is being taken. For
example, I need to be able to check that "Spanish 101"/"spanish 101" is being
taken 1 time, and that "Chem I"/"chem I" is being taken 3 times. However, I'm
running into a lot of problems while trying to doing it in python. I'm a
beginning programmer and just started programming in python this week, so I'm
not really sure what's the best way to approach this problem. I first tried to
do this:
import csv
count = 0
stringToCheck = "Enter Subject here"
with open("Students.csv") as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for col in f_csv:
if(col[4]):
if stringToCheck in col[4]:
print('Found', stringToCheck, 'in' col[4])
count += 1
else: print('Not found in', col[4])
print(count)
However, that does not work.... for example, the first line is something like
"Concurrent programming, blah, blah blah", where the phrase "concurrent
programming" only shows up in that one line, once. When I search for either
"Concurrent programming" or "concurrent programming" i get that it returns
"Not Found in..." from rows 10 through the end.
Furthermore, I tried this:
import csv
import re
from collections import Counter
with open("Students.csv") as f:
f_csv = csv.reader(f)
for col in f_csv
words = re.findall(r'\w+', col[4])
two_words = [''.join(ws) for ws in zip(words,words[1:])]
wordscount = {w:f for w, s in Counter(two_words).most_common() if s > 1}
print (wordscount)
but that was majorly wrong.... and I understand, that it doesn't do the
purpose of searching and counting for a specific phrase, but I don't know how
to turn it into that either. I sort of just looked that up online, and I
didn't completely understand how to use it anyway....
But yeah, I've been working on this for hours and its due today, any help
please??? I'm just a bit confused, and knowing what would be the right
direction would be helpful, thanks.
Answer: So there are a few weird things in your csv file (like an extra comma in the
subjects field of the last row), but I think the following should work for
you.
import csv
with open('Students.csv','r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',', skipinitialspace=True)
subjectcount={}
for row in reader:
for subject in row['Subjects'].lower().split(','):
if subject.strip() not in subjectcount:
subjectcount[subject.strip()] = 1
else:
subjectcount[subject.strip()] += 1
for k,v in subjectcount.items():
print k, v
|
Find and replace symbols with regex python
Question: I have such sample:
sample = 'TEXT/xx_271802_1A'
p = re.compile("(/[a-z]{2})")
print p.match(sample)
in position of xx may be any from [a-z] in quantity of 2:
TEXT/qq_271802_1A TEXT/sg_271802_1A TEXT/ut_271802_1A
How can I find this xx and f.e. replace it with 'WW':
TEXT/WW_271802_1A TEXT/WW_271802_1A TEXT/WW_271802_1A
my code returns `None`
Answer: You can try the following Regular expression :
>>> sample = 'TEXT/xx_271802_1A'
>>> import re
>>> re.findall(r'([a-z])\1',sample)
['x']
>>> re.sub(r'([a-z])\1','WW',sample)
'TEXT/WW_271802_1A'
>>> sample = 'TEXT/WW_271802_1A TEXT/WW_271802_1A TEXT/WW_271802_1A'
>>> re.sub(r'([a-z])\1','WW',sample)
'TEXT/WW_271802_1A TEXT/WW_271802_1A TEXT/WW_271802_1A'
The RegEx `([a-z])\1` searches for 1 letter and then matches it if it repeats
immediately.
|
Finding all roots of an equation in Python
Question: I have a function that I want to find its roots. I could write a program to
figure out its roots but the point is, each time that I want to find the other
root I should give it an initial value manually which I do not want to do
that. I want to have all the roots in a list since I want to do some
operations on the roots after finding them. This is my code:
import math
import scipy
import scipy.optimize
c = 5
alambda = 1
rho = 0.8
b = rho * c / alambda
def f(zeta):
y = ((zeta**c)*(math.exp((alambda*b)*(1-zeta)))) - 1
return y
print scipy.optimize.newton(f, -1)
Answer: For integer `c`, the roots of the function are given by the Lambert W
function, <https://en.wikipedia.org/wiki/Lambert_W_function>
from numpy import exp, pi
from scipy.special import lambertw
c = 3
alambda = 1.234
rho = 0.8
b = rho * c / alambda
def f(zeta):
y = ((zeta**c)*(exp((alambda*b)*(1-zeta)))) - 1
return y
def zeta_root(k, n):
a = alambda
return -c/(a*b) * lambertw(-a*b/c * exp(-(a*b+2j*pi*n)/c), k=k)
for k in range(-20, 20):
# also n can be any integer; probably reproduces the same root set
# as varying k
zeta = zeta_root(k, 3)
print("k={0}, zeta={1}, error={2}".format(k, zeta, abs(f(zeta))))
The equation has an infinite number of complex-valued roots. The `k=0` and
`k=-1` roots which correspond to real branches of the Lambert W function may
be real-valued.
For non-integer `c` the situation seems a bit more complicated due to the
extra branch cut, although at least the real-valued positive roots should be
captured.
|
What is the pure Python equivalent to the IPython magic function call %matplotlib inline?
Question: In IPython Notebook, I defined a function that contains a call to the magic
function `%matplotlib`, like this:
def foo(x):
%matplotlib inline
# ... some useful stuff happens in between here
imshow(np.asarray(img))
I'd like to put that function into a Python module so that I can just import
and call it.
However, to do this, I'd need to remove the `%matplotlib inline` from my code
and replace it with its pure-Python equivalent.
What is the pure-Python equivalent?
Answer: `%matplotlib inline` directly hook into IPython instance. You can get the
equivalent by using `%hist -t` that show you the processed input as pure
python, which show that `%matplotlib inline` is equivalent to
`get_ipython().magic('matplotlib inline')` in which `get_ipython()` return the
current ipython shell object. It is pure python but will work only in an
IPython kernel.
For more in depth explanation, `%matplolib xxx` just set matplotlib backend to
xxx, the case od inline is a bit different and requires first a backend which
is shipped with IPython and not matplotlib. Even if this backend was in
matplotlib itself, it needs hooks in IPython itself to trigger the display and
GC of matplotlib figures after each cell execution.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.