text
stringlengths 226
34.5k
|
---|
Logging script data with Node child_process
Question: I am working with a python script that runs on a loop and outputs a new value
every second, and can only be stopped by pressing `enter` on the keyboard. For
various reasons, the python code should not be altered.
**Ask:** How do I capture the first ten values of the looping script then kill
the script from Node?
I wrote the below Node script that will kick off an external program and log
the output; however, this only works for scripts that aren't running in loops.
var exec = require('child_process').exec;
var scriptCommand = "sudo python script.py"
exec(scriptCommand, function cb(error, stdout, stderr){
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null){
console.log('exec error: ' + error);
}
});
Answer: You're going to want to use spawn and capture the standard output of the
python child process. Once you have reached ten values, you can kill the
python process.
Unfortunately you're going to have to modify the python program to flush
stout. There is no way around this. If you do not manually flush stdout,
python will, but only after the internal buffer fills up (which in my sample
code will take awhile).
Here is a fully working example (captures first three values and then kills
the python process):
**pyscript.py**
#!/usr/bin/env python
# python 2.7.4
import time
import sys
i = 0
while(True):
time.sleep(1)
print("hello " + str(i))
# Important! This will flush the stdout buffer so node can use it
# immediately. If you do not use this, node will see the data only after
# python decides to flush it on it's own.
sys.stdout.flush()
i += 1
**script.js**
#!/usr/bin/env node
"use strict";
// node version 0.10.26
var spawn = require('child_process').spawn
, path = require('path')
, split = require('split');
// start the pyscript program
var pyscript = spawn('python', [ path.join(__dirname, 'pyscript.py') ]);
var pythonData = [];
// Will get called every time the python program outputs a new line.
// I'm using the split module (npm) to get back the results
// on a line-by-line basis
pyscript.stdout.pipe(split()).on('data', function(lineChunk) {
// Kill the python process after we have three results (in our case, lines)
if (pythonData.length >= 3) {
return pyscript.kill();
}
console.log('python data:', lineChunk.toString());
pythonData.push(lineChunk.toString());
});
// Will be called when the python process ends, or is killed
pyscript.on('close', function(code) {
console.log(pythonData);
});
Put them both in the same directory, and make sure to grab the
[split](https://www.npmjs.org/package/split) module for the demo to work.
|
python to search within pdf file
Question: here is part of pdf structure:
5 0 obj
<< /Length 56 >>
stream
BT /F1 12 Tf 100 700 Td 15 TL (JavaScript example) Tj ET
endstream
endobj
6 0 obj
<<
/Type /Font
/Subtype /Type1
/Name /F1
/BaseFont /Helvetica
/Encoding /MacRomanEncoding
>>
endobj
7 0 obj
<<
/Type /Action
/S /JavaScript
I want to search for "javascript" if its there or not. the problem with it
that javascript can be represented by its hex as a whole or part ot it
"javascript or Jav#61Script or J#61v#61Script and so on"
so how could I find out if javascript is exist with all of this possibilities
????
Answer: Read it in a character at a time and translate any hex you find to characters
as you go, also translating to lowercase. Compare the result to "javascript".
Here's an idea:
import string
import os
import re
def pdf_find_str(pdfname, str):
f = open(pdfname, "rb")
# read the file CHUNK_SIZE chars at a time, keeping last KEEP_SIZE chars
CHUNK_SIZE = 2*1024*1024
KEEP_SIZE = 3 * len(str) # each char might be in #ff form
hexvals = "0123456789abcdef"
ichunk = removed = 0
chunk = f.read(CHUNK_SIZE)
while len(chunk) > 0:
# Loop to find all #'s and replace them with the character they represent.
hpos = chunk.find('#')
while hpos != -1:
if len(chunk)-hpos >= 3 and chunk[hpos+1] in hexvals and chunk[hpos+2] in hexvals:
hex = int(chunk[hpos+1:hpos+3], 16) # next two characters are int value
ch = chr(hex).lower()
if ch in str: # avoid doing this if ch is not in str
chunk = chunk[:hpos] + ch + chunk[hpos+3:]
removed += 2
hpos = chunk.find('#', hpos+1)
m = re.search(str, chunk, re.I)
if m:
return ichunk * (CHUNK_SIZE-KEEP_SIZE) + m.start()
# Transfer last KEEP_SIZE characters to beginning for next round of
# testing since our string may span chunks.
next_chunk = f.read(CHUNK_SIZE - KEEP_SIZE)
if len(next_chunk) == 0: break
chunk = chunk[-KEEP_SIZE:] + next_chunk
ichunk += 1
f.close()
return -1
# On one file:
#if pdf_find_str("Consciousness Explained.pdf", "javascript") != -1:
# print 'Contains "javascript"'
# Recursively on a directory:
for root, dirs, files in os.walk("Books"):
for file in files:
if file.endswith(".pdf"):
position = pdf_find_str(root + "/" + file, "javascript")
if position != -1:
print file, "(", position, ")"
# Note: position returned by pdf_find_str does not account for removed
# characters from #ff representations (if any).
|
How to open a text file with python
Question: I would like to open a file that contains text. I would like the text file to
open up with a program called gedit, and the filename is entry3. Gedit is just
a type of text editor.
Answer:
import subprocess
subprocess.call(("gedit", "entry3"))
|
python utc time minus 5 minutes
Question: How to round down a time 5 minutes in Python?
I have this script, but i think this can be easyer, and the full hours the
calculation goes wrong. When its 22:03 it returns 21:95 instead of 21:55.
import datetime
from datetime import date
import time
utc_datetime = datetime.datetime.utcnow()
jaar = date.today().year
maand = time.strftime("%m")
dag = time.strftime("%d")
uurutc = utc_datetime.strftime("%H")
autc = utc_datetime.strftime("%M")
minuututc = int(5 * round(float(autc)/5)-5)
uur = time.strftime("%H")
a = time.strftime("%M")
minuut = int(5 * round(float(a)/5)-5)
timestamp = ''.join(str(x) for x in [jaar, maand, dag, uurutc, minuututc])
print timestamp
What the code should actually do:
Our local time is UTC+2, but i only need the UTC time, so the output must be
in UTC. Second, the time needs to be 5 min before current time and then round
down. The output format of the string should be: YYYYMMDDHHMM.
Example:
local time: 12:53 > output script: 10:45
local time: 17:07 > output script: 15:00
local time: 08:24 > output script: 06:15
Who can help me with this out?
Thank you!
Answer: Use
[datetime.timedelta](https://docs.python.org/2/library/datetime.html#available-
types):
from datetime import datetime, timedelta
now = datetime.utcnow()
rounded = now - timedelta(minutes=now.minute % 5 + 5,
seconds=now.second,
microseconds=now.microsecond)
print rounded
# -> 2014-04-12 00:05:00
|
interp function in python like matlab
Question: Could someone explain how to use an interpolation function on an existing
array, in python as the one exists in matlab ?
example:
x =
1
2
3
4
5
6
7
8
9
10
> > interp(x,2)
ans =
1.0000
1.4996
2.0000
2.4993
3.0000
3.4990
4.0000
4.4987
5.0000
5.4984
6.0000
6.4982
7.0000
7.4979
8.0000
8.4976
9.0000
9.4973
10.0000
10.4970
I'd like a function in python which does exactly this, i.e. adds more points
keeping the original intact.
Answer: A couple of issues need to be raised:
* Are you just looking at linear interpolation (ie "connect the dots" with straight line segments)? That's simple but kind of nasty. You can get nicer results with higher-order curves (ie bicubic splines) but for that you need to provide more information to nail down a unique solution (ie endpoint first-derivatives).
* Do you want to smooth the curve at the same time, or do you expect it to go exactly through your given points?
* Are your input points uniformly spaced (ie along the x axis)?
* Your data shows not just interpolation but also extrapolation (ie your last point is off the end of your data) - is this actually what you want?
[Matlab documentation](http://www.mathworks.com/help/signal/ref/interp.html)
says "`interp` inserts 0s into the original signal and then applies a lowpass
interpolating filter to the expanded sequence".
* * *
**Edit:** I think the closest equivalent is `scipy.interpolate.interp1d` \-
see
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d>
You could make a wrapper like so:
import numpy as np
from scipy.interpolate import interp1d
def interp(ys, mul):
# linear extrapolation for last (mul - 1) points
ys = list(ys)
ys.append(2*ys[-1] - ys[-2])
# make interpolation function
xs = np.arange(len(ys))
fn = interp1d(xs, ys, kind="cubic")
# call it on desired data points
new_xs = np.arange(len(ys) - 1, step=1./mul)
return fn(new_xs)
which then works like
>>> interp([1,2,3,4,5,6,7,8,9,10], 2)
array([ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ,
5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5,
10. , 10.5])
|
How to detect what output is and do if statement from it?
Question: Basically I am writing a script in Python that will check for me the status of
my servers. I need it to ping five different IPs and then detect what the
output is. I will then need an if statement for example:
import.os
Server1 = os.system('ping 123.123.123.123')
if Server1 == 'Request timed out':
print('Server 1 is down.')
else:
print('Server 1 is up.')
I am not exactly sure how to go about this. Let me know.
Thanks.
Answer: You posted big X/Y here. You want do do X. You don't know how to do X. You
think Y is the best way to do X and are asking about Y. If you want to know
about X, see [Ivc's
comment](http://stackoverflow.com/questions/2953462/pinging-servers-in-
python).
I'm going to answer Y but letting you know that Y is not the best way to do
it.
import subprocess
import locale
encoding = locale.getdefaultlocale()[1]
proc = subprocess.Popen(["ping", "123.123.123.123"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
if 'Request timed out' in out.decode(encoding):
print 'the host is down'
else:
print 'the host is up'
Then you would need to decide exactly what to do when the host is down and
when the host is up.
|
online web form access using python
Question: I am trying to access websites that require login information. For practice I
tried getting into Hotmail just to see if it would work. I have no idea if
this code is right. With trial and error I have the code "running", but it
isn't working still.. Can someone help me out?
Thanks, Brandon
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
import urllib.request
import webbrowser
url = 'http://hotmail.com'
data = urllib.parse.urlencode({'idDiv_PWD_UsernameExample' : 'email','idDiv_PWD_PasswordExample' : 'password'})
binary_data = data.encode('utf8')
results = urllib.request.urlopen(url, binary_data)
html = results.geturl()
print (html)
Answer: # General Considerations
**Cookies** will possibly be used during the whole login process. Then the
following steps can become necessary:
1. Load the login page to get the initial cookie.
2. Load the login page again, sending login data and the cookie from step 1.
3. Follow redirections after successful login.
But thanks to "batteries included", it's not that hard, I just tried the
following example with the Horde Groupware:
import urllib.request
import http.cookiejar
import urllib.parse
cookiejar = http.cookiejar.CookieJar()
loginpage = "https://example.com/login.php"
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar))
data = {'user': 'username', 'pw': 'password'} # + what else might be required
binData = urllib.parse.urlencode(data).encode('utf-8')
result = opener.open(loginpage) # without credentials, to get cookie
result.read()
for c in cookiejar: # just debugging to see if we got a cookie
print(c)
result = opener.open(loginpage, binData) # now send the crendentials
page = result.read().decode() # read() will read after redirects!
f = open("out.html", "w") # store output in a file
f.write(page) # if everything worked, this should look
f.close() # like the landing page
Please also note that most sites require **Javascript** , and Python can't
handle that. I suggest that you disable Javascript in your Browser, clear all
cookies from the site you try to access, and then carefully step through the
process using [Firebug](https://getfirebug.com/) and see which information
(cookies, GET/POST-parameters, redirects, etc.) gets passed around for a login
process. Then you can try to recreate this using python.
# Hotmail specific
Hotmail.com seems to be a suboptimal starting point to work with login forms.
If you look at the source (I highly suggest [Firebug](https://getfirebug.com/)
if you use Firefox), you can see that the "real" input field is not the
`<div>` that you seem to try to use, but this one:
<input type="email" lang="en" name="login" id="i0116" maxlength="113"
class="ltr_override" aria-labelledby="idLbl_PWD_Username">
and the password is contained in this one
<input type="password" name="passwd" id="i0118" autocomplete="off"
aria-labelledby="idDiv_PWD_PasswordExample">
If you enter dummy (or your real) information in the input fields and try to
login, you can see in Firebug's "Network" tab that some more information is
sent:
LoginOptions 3
NewUser 1
PPFT {very long encoded string}
PPSX Pas
i1 0
i12 1
i13 0
i14 226
i15 2270
i17 0
i18 __Login_Strings|1,__Login_Core|1,
i2 1
i3 92877
i4 0
i7 0
idsbho 1
login [email protected]
passwd password456
sso 0
type 11
It is possible that `login` and `password` are sufficient, but since I don't
have a Hotmail account, I can't do further testing. Your general approach
using urllib.request seems to be OK (except that `geturl` does exactly that,
it gets an URL, so you should rename the variable html to something better).
|
Match any word in string except those preceded by a curly brace in python
Question: I have a string like
line = u'I need to match the whole line except for {thisword for example'
I have a difficulty doing this. What I've tried and it doesn't work:
# in general case there will be Unicode characters in the pattern
matchobj = re.search(ur'[^\{].+', line)
matchobj = re.search(ur'(?!\{).+', line)
Could you please help me figure out what's wrong and how to do it right?
P.S. I don't think I need to substitute `"{thisword"` with empty string
Answer: I am not exactly clear what you need. From your question title It looks you
wants to find "All words in a string e.g 'line' those doesn't starts with {",
but you are using re.search() function that confuses me.
### `re.search()` and `re.findall()`
The function
[`re.search()`](https://docs.python.org/2/library/re.html#re.RegexObject.search)
return _a_ corresponding MatchObject instance, re.serach is usually used to
match and return a patter in a long string. _It doesn't return all possible
matches_. See below a simple example:
>>> re.search('a', 'aaa').group(0) # only first match
'a'
>>> re.search('a', 'aaa').group(1) # there is no second matched
Traceback (most recent call last):
File "<console>", line 1, in <module>
IndexError: no such group
With regex `'a'` search returns _only one_ patters `'a'` in string `'aaa'`, it
doesn't returns all possible matches.
If your objective to find – "all words in a string those doesn't starts with
`{`". You should use
[`re.findall()`](https://docs.python.org/2/library/re.html#re.findall)
function:- that matches all occurrences of a pattern, not just the first one
as re.search() does. See example:
>>> re.findall('a', 'aaa')
['a', 'a', 'a']
**Edit:** On the basis of comment adding one more example to demonstrate use
of re.search and re.findall:
>>> re.search('a+', 'not itnot baaal laaaaaaall ').group()
'aaa' # returns ^^^ ^^^^^ doesn't
>>> re.findall('a+', 'not itnot baaal laaaaaaall ')
['aaa', 'aaaaaaa'] # ^^^ ^^^^^^^ match both
Here is a good tutorial for Python re module: [re – Regular
Expressions](http://pymotw.com/2/re/index.html#module-re)
Additionally, there is concept of group in Python-regex – "a matching pattern
within parenthesis". If more than one groups are present in your regex patter
then re.findall() return a list of groups; this will be a list of tuples if
the pattern has more than one group. see below:
>>> re.findall('(a(b))', 'abab') # 2 groups according to 2 pair of ( )
[('ab', 'b'), ('ab', 'b')] # list of tuples of groups captured
In Python regex `(a(b))` contains two groups; as two pairs of parenthesis
(this is unlike regular expression in formal languages – regex are not exactly
same as regular expression in formal languages but that is different matter).
* * *
**Answer** : The words in sentence `line` are separated by spaces (other
either at starts of string) regex should be:
ur"(^|\s)(\w+)
Regex description:
1. `(^|\s+)` means: either word at start or start after some spaces.
2. `\w*`: Matches an alphanumeric character, including "_".
On applying regex `r` to your line:
>>> import pprint # for pretty-print, you can ignore thesis two lines
>>> pp = pprint.PrettyPrinter(indent=4)
>>> r = ur"(^|\s)(\w+)"
>>> L = re.findall(r, line)
>>> pp.pprint(L)
[ (u'', u'I'),
(u' ', u'need'),
(u' ', u'to'),
(u' ', u'match'),
(u' ', u'the'),
(u' ', u'whole'),
(u' ', u'line'),
(u' ', u'except'),
(u' ', u'for'), # notice 'for' after 'for'
(u' ', u'for'), # '{thisword' is not included
(u' ', u'example')]
>>>
To find all words in a single line use:
>>> [t[1] for t in re.findall(r, line)]
Note: it will avoid { or any other special char from line because \w only pass
alphanumeric and '_' chars.
* * *
If you specifically only avoid `{` if it appears at start of a word (in middle
it is allowed) then use regex: `r = ur"(^|\s+)(?P<word>[^{]\S*)"`.
To understand diffidence between this regex and other is check this example:
>>> r = ur"(^|\s+)(?P<word>[^{]\S*)"
>>> [t[1] for t in re.findall(r, "I am {not yes{ what")]
['I', 'am', 'yes{', 'what']
* * *
**Without Regex:**
You could achieve same thing simply without any regex as follows:
>>> [w for w in line.split() if w[0] != '{']
* * *
**re.sub() to replace pattern**
If you wants to just replace one (or more) words starts with `{` you should
use [`re.sub()`](https://docs.python.org/2/library/re.html#re.sub) to replace
patterns start with `{` by emplty string `""` check following code:
>>> r = ur"{\w+"
>>> re.findall(r, line)
[u'{thisword']
>>> re.sub(r, "", line)
u'I need to match the whole line except for for example'
* * *
**Edit** Adding Comment's reply:
The `(?P<name>...)` is Python's Regex extension: (it has meaning in Python) -
`(?P<name>...)` is similar to regular parentheses - create a group (a named
group). The group is accessible via the symbolic group name. Group names must
be valid Python identifiers, and each group name must be defined only once
within a regular expression. example-1:
>>> r = "(?P<capture_all_A>A+)"
>>> mo = re.search(r, "aaaAAAAAAbbbaaaaa")
>>> mo.group('capture_all_A')
'AAAAAA'
example-2: suppose you wants to filter name from a name-line that may contain
title also e.g mr use regex: `name_re = "(?P<title>(mr|ms)\.?)? ?(?P<name>[a-z
]*)"`
we can read name in input string using `group('name')`:
>>> re.search(name_re, "mr grijesh chauhan").group('name')
'grijesh chauhan'
>>> re.search(name_re, "grijesh chauhan").group('name')
'grijesh chauhan'
>>> re.search(name_re, "ms. xyz").group('name')
'xyz'
|
How to convert a '\u5f71\u89c6\...' in to its real meaning?(python)
Question: I want to convert
'[["[FK\u5f71\u89c6\u51fa\u54c1]\u7576\u65fa\u7238\u7238-17.\u7ca4\u8bed\u5b57\u5e55.TV-RMVB.rmvb", "205.53 MB"]]'
to
'[["[[FK影视出品]當旺爸爸-17.粤语字幕.TV-RMVB.rmvb", "205.53 MB"]]'
Because I make a mistake that I use `json.dumps(file_list)` convert a list
object to str, and save the result to db.I find this mistabke until using
sphinx to index these data...
I have tried use data.decode('utf-8'), but it seems not work.
Answer: Just decode from JSON again:
>>> import json
>>> json.loads('[["[FK\u5f71\u89c6\u51fa\u54c1]\u7576\u65fa\u7238\u7238-17.\u7ca4\u8bed\u5b57\u5e55.TV-RMVB.rmvb", "205.53 MB"]]')
[['[FK影视出品]當旺爸爸-17.粤语字幕.TV-RMVB.rmvb', '205.53 MB']]
You don't _have_ UTF-8 encoded data, you have JSON-encoded data, which uses
`\uhhhh` escape sequences to represent Unicode codepoints.
|
Distributed lock manager for Python
Question: I have a bunch of servers with multiple instances accessing a resource that
has a hard limit on requests per second.
I need a mechanism to lock the access on this resource for all servers and
instances that are running.
There is a restful distributed lock manager I found on github:
<https://github.com/thefab/restful-distributed-lock-manager>
Unfortunately there seems to be a min. lock time of 1 second and it's
relatively unreliable. In several tests it took between 1 and 3 seconds to
unlock a 1 second lock.
Is there something well tested with a python interface I can use for this
purpose?
Edit: I need something that auto unlocks in under 1 second. The lock will
never be released in my code.
Answer: My first idea was using Redis. But there are more great tools and some are
even lighter, so my solution builds on zmq. For this reason you do not have to
run Redis, it is enough to run small Python script.
# Requirements Review
Let me review your requirements before describing solution.
* limit number of request to some resource to a number of requests within fixed period of time.
* auto unlocking
* resource (auto) unlocking shall happen in time shorter than 1 second.
* it shall be distributed. I will assume, you mean that multiple distributed servers consuming some resource shall be able and it is fine to have just one locker service (more on it at Conclusions)
# Concept
## Limit number of requests within timeslot
Timeslot can be a second, more seconds, or shorter time. The only limitation
is precision of time measurement in Python.
If your resource has hard limit defined per second, you shall use timeslot 1.0
## Monitoring number of requests per timeslot until next one starts
With first request for accessing your resource, set up start time for next
timeslot and initialize request counter.
With each request, increase request counter (for current time slot) and allow
the request unless you have reached max number of allowed requests in current
time slot.
## Serve using zmq with REQ/REP
Your consuming servers could be spread across more computers. To provide
access to LockerServer, you will use zmq.
# Sample code
zmqlocker.py:
import time
import zmq
class Locker():
def __init__(self, max_requests=1, in_seconds=1.0):
self.max_requests = max_requests
self.in_seconds = in_seconds
self.requests = 0
now = time.time()
self.next_slot = now + in_seconds
def __iter__(self):
return self
def next(self):
now = time.time()
if now > self.next_slot:
self.requests = 0
self.next_slot = now + self.in_seconds
if self.requests < self.max_requests:
self.requests += 1
return "go"
else:
return "sorry"
class LockerServer():
def __init__(self, max_requests=1, in_seconds=1.0, url="tcp://*:7777"):
locker=Locker(max_requests, in_seconds)
cnt = zmq.Context()
sck = cnt.socket(zmq.REP)
sck.bind(url)
while True:
msg = sck.recv()
sck.send(locker.next())
class LockerClient():
def __init__(self, url="tcp://localhost:7777"):
cnt = zmq.Context()
self.sck = cnt.socket(zmq.REQ)
self.sck.connect(url)
def next(self):
self.sck.send("let me go")
return self.sck.recv()
## Run your server:
run_server.py:
from zmqlocker import LockerServer
svr = LockerServer(max_requests=5, in_seconds=0.8)
From command line:
$ python run_server.py
This will start serving locker service on default port 7777 on localhost.
## Run your clients
run_client.py:
from zmqlocker import LockerClient
import time
locker_cli = LockerClient()
for i in xrange(100):
print time.time(), locker_cli.next()
time.sleep(0.1)
From command line:
$ python run_client.py
You shall see "go", "go", "sorry"... responses printed.
Try running more clients.
## A bit of stress testing
You may start clients first and server later on. Clients will block until the
server is up, and then will happily run.
# Conclusions
* described requirements are fulfilled
* number of requests is limited
* no need to unlock, it allows more requests as soon as there is next time slot available
* LockerService is available over network or local sockets.
* it shall be reliable, zmq is mature solution, python code is rather simple
* it does not require time synchronization across all participants
* performance will be very good
On the other hand, you may find, that limits of your resource are not so
predictable as you assume, so be prepared to play with parameters to find
proper balance and be always prepared for exceptions from this side.
There is also some space for optimization of providing "locks" - e.g. if
locker runs out of allowed requests, but current timeslot is already almost
completed, you might consider waiting a bit with your "sorry" and after a
fraction of second provide "go".
## Extending it to real distributed lock manager
By "distributed" we might also understand multiple locker servers running
together. This is more difficult to do, but is also possible. zmq allows very
easy connection to multiple urls, so clients could really easily connect to
multiple locker servers. There is a question, how to coordinate locker servers
not to allow too many request to your resource. zmq allows inter-server
communication. One model could be, that each locker server would publish each
provided "go" on PUB/SUB. All other locker servers would be subscribed, and
used each "go" to increase their local request counter (with a bit modified
logic).
|
Accessing python list in javascript as an array
Question: I have this in my flask views.py
def showpage():
...
test = [1,2,3,4,5,6]
return render_template("sample.html",test=test)
I have this in my sample .html
<script> var counts = {{test}}; </script>
This gives me a empty counts variable. How can I get the counts same as the
test list in python?
Answer: 1. When you insert variable to template `{{ test }}` it take object representation. For list of int `[1,2,3,4,5,6]` it will be rendered as `[1, 2, 3, 4, 5, 6]`, so it is valid javascript array, but this method not safe complex objects without javascript-like representation, for example, test = [1,2,3,4,5,any] will rendered as `[1, 2, 3, 4, 5, <built-in function any>]`, however this is just example and will never work.
2. To implicitly cast to javascript object in flask exist [`tojson`](http://flask.pocoo.org/docs/templating/#standard-filters) filter:
<script> var counts = {{ test|tojson }}; </script>
So if the object is JSON serializable, then all will be rendered, otherwise
the template engine will raise an exception.
3. You also can send javascript code to your template:
from flask import json
return render_template("sample.html",test=json.dumps(test))
but it is not a good approach and it's better use `tojson` filter that is also
HTML markup safe.
4. I prefer to not mix any javascript code within templates and split templates, javascript and javascript data with ajax. If this approach is hard I would prefer to use `tojson` filter.
|
Using files in Hadoop Streaming with Python
Question: I am completely new to Hadoop and MapReduce and am trying to work my way
through it. I am trying to develop a mapreduce application in python, in which
I use data from 2 .CSV files. I am just reading the two files in mapper and
then printing the key value pair from the files to the sys.stdout
The program runs fine when I use it on a single machine, but with the Hadoop
Streaming, I get an error. I think I am making some mistake in reading files
in the mapper on Hadoop. Please help me out with the code, and tell me how to
use file-handling in Hadoop Streaming. The mapper.py code is as below. (You
can understand the code from the comments):
#!/usr/bin/env python
import sys
from numpy import genfromtxt
def read_input(inVal):
for line in inVal:
# split the line into words
yield line.strip()
def main(separator='\t'):
# input comes from STDIN (standard input)
labels=[]
data=[]
incoming = read_input(sys.stdin)
for vals in incoming:
# write the results to STDOUT (standard output);
# what we output here will be the input for the
# Reduce step, i.e. the input for reducer.py
#
# tab-delimited;
if len(vals) > 10:
data.append(vals)
else:
labels.append(vals)
for i in range(0,len(labels)):
print "%s%s%s\n" % (labels[i], separator, data[i])
if __name__ == "__main__":
main()
There are 60000 records which are entered to this mapper from two .csv files
as follows (on single machine, not hadoop cluster):
cat mnist_train_labels.csv mnist_train_data.csv | ./mapper.py
Answer: I was able to resolve the issue after searching a solution for like 3 days.
The problem is with the newer version of Hadoop (2.2.0 in my case). The mapper
code, when reading values from files was giving an exit code of non-zero at
some point (maybe because it was reading a huge list of values(784) at a
time). There is a setting in the Hadoop 2.2.0, which tells the Hadoop System
to give a general error (subprocess failed with code 1). This setting is set
to True by default. I just had to set the value of this property to False, and
it made my code run without any errors.
Setting is: **stream.non.zero.exit.is.failure**. Just set it to false when
streaming. So the streaming command would be somewhat like:
**hadoop jar ... -D stream.non.zero.exit.is.failure=false ...**
Hope it helps someone, and saves 3 days... ;)
|
Python datastructures into js datastructures using jinja2 template (lists and dicts)
Question: I have a very similar problem to this question, [Python datastructures into js
datastructures using Django templates (lists and
dicts)](http://stackoverflow.com/questions/9547185/python-datastructures-into-
js-datastructures-using-django-templates-lists-and-d) but with the next step -
how do the variable names in python that are strings become javascript
objects?
So in python I have this:
data = [{'year': 2006, 'books': 54, 'author': 'fred'},
{'year': 2007, 'books': 43, 'author': 'sue'},
{'year': 2008, 'books': 41, 'author': 'bill'},
{'year': 2009, 'books': 44, 'author': 'alex'},
{'year': 2010, 'books': 35, 'author': 'fred'}]
which I can output into my javascript via {{ data | safe }}
but I would like my javascript to look like this:
var data = [{year: 2006, books: 54, author: 'fred'},
{year: 2007, books: 43, author: 'sue'},
{year: 2008, books: 41, author: 'bill'},
{year: 2009, books: 44, author: 'alex'},
{year: 2010, books: 35, author: 'fred'}];
whereas it comes out at the moment like this:
var data = [{'year': 2006, 'books': 54, 'author': 'fred'},
{'year': 2007, 'books': 43, 'author': 'sue'},
{'year': 2008, 'books': 41, 'author': 'bill'},
{'year': 2009, 'books': 44, 'author': 'alex'},
{'year': 2010, 'books': 35, 'author': 'fred'}];
Is there anyway to do this?
Many thanks, Mark
Answer: The [`tojson`
filter](https://flask.readthedocs.org/en/latest/templating/#standard-filters)
included with Flask takes care of producing a valid Javascript subset that is
also HTML safe:
var data = {{ data|tojson|safe }};
If you are not using Flask, then [register a custom
filter](http://jinja.pocoo.org/docs/api/#writing-filters) like:
import json
def tojson(obj):
"""Produce HTML-safe JSON"""
return (json.dumps(obj)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
|
TypError when save function of Pillow called. Too many arguments
Question: Attempting to call the save function results in a TypeError. As a side note:
qrcode requires the importing of PIL as PilImage.
It's also worth mentioning that I did not have this error when using the
Python Imaging Library. It only occurred after switching (by recommendation)
to Pillow.
from qrcode import *
import PIL as PilImage
from PIL import Image
import qrcode
qr = qrcode.QRCode (
version = 1,
error_correction = qrcode.constants.ERROR_CORRECT_L,
box_size = 10,
border = 2
)
qr.add_data('Hello World')
qr.make(fit=True)
img = qr.make_image()
img.format = 'PNG'
img.save('test.png')
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
img.save('test.png')
File "build\bdist.win32\egg\qrcode\image\pil.py", line 29, in save
self._img.save(stream, kind)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1467, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\site-packages\PIL\PngImagePlugin.py", line 605, in _save
ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 452, in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 395, in _getencoder
return encoder(mode, *args + extra)
TypeError: function takes at most 4 arguments (6 given)
Answer: As a last stitch effort I did a re-install of the Pillow module. This
miraculously solved my problem and `img.save()` now works exactly as intended.
I'm not sure how, but something must've gone awry during initial installation.
Thank you for all of your help, though. This experience has been hell. If
you'd like to know what this conflict was in pursuit of here is my git-
repository: <https://github.com/NamesJ/qr-tickets>
|
uWSGI unique timer python decorator
Question: I would like to run a cron-like command with python decorators that needs to
be unique (so that if the previous process is still running it doesn't start a
new process) with uwsgi.
taking a look at the documentation (<http://uwsgi-
docs.readthedocs.org/en/latest/PythonDecorators.html>) i saw that i can do
something like this
task.py
from uwsgidecorators import *
@timer(600) #every 10 minutes
def myfunction(signum):
pass
uwsgi.ini
[uwsgi]
...
import=task
...
but this way it is not unique like if i do something like this (following the
documentation <http://uwsgi-docs.readthedocs.org/en/latest/Cron.html>)
task.py
...
all_my_tasks
...
uwsgi.ini
[uwsgi]
...
cron2 = minute=-10,unique=1 python path/to/task.py
...
Isn't there a way to do this using uwsgi's decorators and timer instead of
cron?
Answer: Use the uWSGI locking api:
from uwsgidecorators import *
@timer(600) #every 10 minutes
def myfunction(signum):
if uwsgi.is_locked(): return
uwsgi.lock()
....
uwsgi.unlock()
<http://uwsgi-docs.readthedocs.org/en/latest/Locks.html>
|
how to send email attachement using python 2.7
Question: I am getting error when using this code to send email using localhost ip, any
suggestion how to solve the socket error?
def SendTMail(self):
# Import the email modules we'll need
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
#try:
fp = open('testint.txt', 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
testfile = 'TESTING REPORT'
fp.close()
me = '[email protected]'
you = '[email protected]'
msg['Subject'] = 'The contents of %s' % testfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('192.168.1.3')
s.sendmail(me, [you], msg.as_string())
s.quit()
the error is shown below:
File "x:\example.py", line 6, in SendTMail s = smtplib.SMTP('192.168.1.3')
File "x:\Python27\lib\smtplib.py", line 251, in init (code, msg) = self.connect(host, port)
File "x:\Python27\lib\smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout)
File "x:\Python27\lib\smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout)
File "x:\Python27\lib\socket.py", line 571, in create_connection raise err –
error: [Errno 10051] A socket operation was attempted to an unreachable network
Answer: Before posting raw code, I'd like to add an small explanation as per the
conversation that took place in the comments to your
[question](http://stackoverflow.com/q/23046140/289011).
[smtplib](https://docs.python.org/2/library/smtplib.html) connects to an
existing SMTP server. You can see it more like an Outlook Express. Outlook is
a client (or a [Mail User
Agent](http://en.wikipedia.org/wiki/Mail_user_agent), if you wanna get fancy).
It doesn't send emails by itself. It connects to whatever SMTP server it has
configured among its accounts and tells that server _"Hey, I'm user
[email protected] (and here's my password to prove it). Could you send this for
me?"_
If you wanted to, having your own SMTP server is doable (for instance, in
Linux, an easily configurable SMTP server would be Postfix, and I'm sure there
are many for Windows) Once you set one up, it'll start listening for incoming
connections in its port 25 (usually) and, if whatever bytes come through that
port follow the [SMTP
protocol](http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol), it'll
send it to its destination. IMHO, this isn't such a great idea (nowadays). The
reason is that now, every (decent) email provider will consider emails coming
from unverified SMTP servers as spam. If you want to send emails, is much
better relying in a well known SMTP server (such as the one at
`smtp.live.com`, the ones hotmail uses), authenticate against it with your
username and password, and send your email relying (as in [SMTP
Relay](http://www.xeams.com/smtprelay.htm)) on it.
So this said, here's some code that sends an HTML text with an attachment
`borrajax.jpeg` to an email account relying on `smtp.live.com`.
You'll need to edit the code below to set your hotmail's password (maybe your
hotmail's username as well, if it's not `[email protected]` as shown in your
question) and email recipients. I removed mines from the code after my tests
for obvious security reasons... for me **:-D** and I put back the ones I saw
in your question. Also, this scripts assumes it'll find a `.jpeg` picture
called `borrajax.jpeg` in the same directory where the Python script is being
run:
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_mail():
test_str="This is a test"
me="[email protected]"
me_password="XXX" # Put YOUR hotmail password here
you="[email protected]"
msg = MIMEMultipart()
msg['Subject'] = test_str
msg['From'] = me
msg['To'] = you
msg.preamble = test_str
msg_txt = ("<html>"
"<head></head>"
"<body>"
"<h1>Yey!!</h1>"
"<p>%s</p>"
"</body>"
"</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg") as f:
msg.attach(MIMEImage(f.read()))
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"
smtp_conn.starttls()
smtp_conn.ehlo_or_helo_if_needed()
smtp_conn.login(me, me_password)
smtp_conn.sendmail(me, you, msg.as_string())
smtp_conn.quit()
if __name__ == "__main__":
send_mail()
When I run the example (as I said, I edited the recipient and the sender) it
sent an email to a Gmail account using my (old) hotmail account. This is what
I received in my Gmail:

There's a lot of stuff you can do with the
[email](https://docs.python.org/2/library/email.html) Python module. Have
fun!!
**EDIT:**
Gorramit!! Your comment about attaching a text file wouldn't let me relax!!
**:-D** I had to see it myself. Following what was detailed [in this
question](http://stackoverflow.com/questions/9541837/attach-a-txt-file-in-
python-smtplib), I added some code to add a text file as an attachment.
msg_txt = ("<html>"
"<head></head>"
"<body>"
"<h1>Yey!!</h1>"
"<p>%s</p>"
"</body>"
"</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg", "r") as f:
msg.attach(MIMEImage(f.read()))
#
# Start new stuff
#
with open("foo.txt", "r") as f:
txt_attachment = MIMEText(f.read())
txt_attachment.add_header('Content-Disposition',
'attachment',
filename=f.name)
msg.attach(txt_attachment)
#
# End new stuff
#
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"
And yep, it works... I have a `foo.txt` file in the same directory where the
script is run and it sends it properly as an attachment.
|
rrdscript won't plot anything
Question: Hey guys (and off course Ladys) ,
i have this little script which should show me some nice rrd graphs. But i
seems like i cant find a way to bring it to work to show me some stats. This
is my Script:
# Function: Simple ping plotter for rrd
import rrdtool,tempfile,commands,time,sys
from model import hosts
sys.path.append('/home/dirk/devel/python/stattool/stattool/lib')
import nurrd
from nurrd import RRDplot
class rrdPing(RRDplot):
def __init__(self):
self.DAY = 86400
self.YEAR = 365 * self.DAY
self.rrdfile = 'hostname.rrd'
self.interval = 300
self.probes = 5
self.rrdList = []
def create_rrd(self, interval):
ret = rrdtool.create("%s" % self.rrdfile, "--step", "%s" % self.interval,
"DS:packets:COUNTER:600:U:U",
"RRA:AVERAGE:0.5:1:288",
"RRA:AVERAGE:0.5:1:336")
def getHosts(self, userID):
myHosts = hosts.query.filter_by(uid=userID).all()
return myHosts.pop(0)
def _doPing(self,host):
for x in xrange(0, self.probes):
ans,unans = commands.getstatusoutput("ping -c 3 -w 6 %s| grep rtt| awk -F '/' '{ print $5 }'" % host)
print x
self.probes -=1
self.rrdList.append(unans)
return self.rrdList
def plotRRD(self):
self.create_rrd(self.interval)
times = self._doPing(self.getHosts(3))
for x in xrange(0,len(times)):
loc = times.pop(0)
rrdtool.update(self.rrdfile, '%d:%d' % (int(time.time()), int(float(loc))))
print '%d:%d' % (int(time.time()), int(float(loc)))
time.sleep(5)
self.graph(60)
def graph(self, mins):
ret = rrdtool.graph( "%s.png" % self.rrdfile, "--start", "-1", "--end" , "+1","--step","300",
"--vertical-label=Bytes/s",
"DEF:inoctets=%s:packets:AVERAGE" % self.rrdfile ,
"AREA:inoctets#7113D6:In traffic",
"CDEF:inbits=inoctets,8,*",
"COMMENT:\\n",
"GPRINT:inbits:AVERAGE:Avg In traffic\: %6.2lf \\r",
"COMMENT: ",
"GPRINT:inbits:MAX:Max In traffic\: %6.2lf")
if __name__ == "__main__":
ping = rrdPing()
ping.plotRRD()
info = rrdtool.info('hostname.rrd')
print info['last_update']
Could somebody please give me some advice or some tips how to solve this?
(Sorry code is a litte mess)
Thanks in advance
Kind regards,
Dirk
Answer: Several issues.
Firstly, you appear to only be collecting a single data sample and storing it
before you try to generate a graph. You will need at least two samples,
separated by about 300s, before you can get a single Primary Data Point and
therefore something to graph.
Secondly, you do not post nay information as to what data you are actually
storing. Are you sure your rrdPing function is returning valid data to store?
You are not testing the error status of the write either.
Thirdly, the data you are collecting seems to be ping times or similar, which
is a GAUGE type value. Yet, your RRD DS definition uses a COUNTER type and
your graph call is treating it as network traffic data. A COUNTER type assumes
increasing values and converts to a rate of change, so if you give it ping RTT
data you'll get either unknowns or zeroes stored, which will not show up on a
graph.
Fourthly, your call to RRDGraph is specifying a start of -1 and and end of +1.
From 1 second in the past to 1 second in the future? Since your step is 300s
this is an odd graph. Maybe you should have`--end 'now-1' --start 'end-1day'`
or similar?
You should make your code test the return values for any error messages
produced by the RRDTool library -- this is good practice anyway. When testing,
print out the values you are updating with to be sure you are giving valid
values. With RRDTool, you should collect several data samples at the step
interval and store them before expecting to see a line on the graph. Also,
make sure you are using the correct data type, GAUGE or COUNTER.
|
UTF-8 "inconsistency" when storing unicode key/values from CSV file into dict
Question: I always get very confused when dealing with Unicode and UTF-8 characters and
encodings in Python. There's probably a simple explanation to what I'm going
to detail below, but, so far, I can't wrap my head around it.
Let's say I have a very very simple `.csv` file that contains non-ascii
characters:
`tildes.csv`:
Año,Valor
2001,Café
2002,León
I want to read that file using a
[csv.DictReader](https://docs.python.org/2/library/csv.html#csv.DictReader)
object and store its key/values as `unicode` strings, with tildes and such
handled properly (unescaped) in a python dict. I've seen Tornado and Django
handling unicode key/value sets properly, so I said to myself _Yep, I can do
that too!!_... But nopes... it looks like I can't.
import csv
with open('tildes.csv', 'r') as csv_f:
reader = csv.DictReader(csv_f)
for dct in reader:
print "dct (original): %s" % dct
for k, v in dct.items():
print '%s: %s' % (unicode(k, 'utf-8'), unicode(v, 'utf-8'))
utf_dct = dict((unicode(k, 'utf-8'), unicode(v, 'utf-8')) \
for k, v in dct.items())
print utf_dct
So, I thought: _Ok, I read a`dict` from the file (Its keys being `Año` and
`Valor`) which will be loaded **ascii** with escaped characters, but then I
can encode those into unicode values and use them as keys..._ Wrong!
This is what I see when I run the code above:
dct (original): {'A\xc3\xb1o': '2001', 'Valor': 'Caf\xc3\xa9'}
Año: 2001
Valor: Café
{u'A\xf1o': u'2001', u'Valor': u'Caf\xe9'}
dct (original): {'A\xc3\xb1o': '2002', 'Valor': 'Le\xc3\xb3n'}
Año: 2002
Valor: León
{u'A\xf1o': u'2002', u'Valor': u'Le\xf3n'}
So the first line shows the dictionary 'as it is' (escaped). Good, nothing odd
here. Then I `print` all the key/values parsed to unicode. It shows the
characters the way I want it. Good too. But then, using the exact same
instruction I used to re-encode the strings when I printed them, I try to
create a `dict` (the `utf_dct` variable) and when I print it, I get the values
escaped again.
* * *
**EDIT 1** :
Actually, I don't think I even need a csv file to show what I mean. I just
tried this in my console:
>>> print "Año"
Año # Yeey!! There's hope!
>>> print {"Año": 2001}
{'A\xc3\xb1o': 2001} # 2 chars --> Ascii, I think I get this part
>>> print {u"Año": 2001}
{u'A\xf1o': 2001} # What happened here?
# Why am I seeing the 0x00F1 UTF-8 code
# from the Latin-1 Supplement (wiki:
# http://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)
# instead of an ñ?
Why can't I just print a dict showing `{u'Año': 2001}`? My terminal clearly
accepts it. What's happening here?
Answer: When you print the string itself, it is printed "nicely", using its `str()`
representation. When you print a dictionary, its contents are printed using
their `repr()` representation, which always escapes. The contents of the
string are the same in both cases, it's just that Python displays them
differently. It is the same reason that no quote marks are printed around
`Año` in the first case, but quote marks are printed around `'A\xc3\xb1o'` in
the second case. It's just two different display formats.
Here is an even simpler example that may help illustrate the situation:
>>> import unicodedata
>>> unicodedata.name('\u00f1') # 00F1 is unicode code point for this character
'LATIN SMALL LETTER N WITH TILDE'
>>> print(str(u'\u00f1')) # str() gives a displayable character
ñ
>>> print repr(u'\u00f1') # repr() gives an escaped representation
u'\xf1'
>>> print repr(str(u'\u00f1')) # repr() of the str() shows the two characters in the UTF-8 encoding -- this is what happens when showing a dict
'\xc3\xb1'
>>> len(str(u'\u00f1')) # the str() is two bytes long (UTF-8 encoded)
2
>>> len(repr(u'\u00f1')) # the repr() is 7 bytes long (`u`, `'`, `\`, `x`, `f`, `1`, `'`)
7
There is a [related bug report](http://bugs.python.org/issue2630) suggesting
to change this behavior so that `repr` doesn't escape non-ASCII characters.
According to that bug report, this change was made in Python 3, so tools that
you have seen doing this may be using Python 3.
It's also possible for individual tools to display anything however they like.
A tool doesn't have to just call `str(someDict)` and display the result; if it
wants, it can "manually" call `str` on the contents of the dict instead and
build up its own displayable version from that.
|
How to fit a model to my testing set in statsmodels (python)
Question: I am working on a logistic regression model and I am having trouble
understanding how to take the model fit from my training set onto my testing
set. Sorry, I am new to python and VERY new to statsmodels..
import pandas as pd
import statsmodels.api as sm
from sklearn import cross_validation
independent_vars = phy_train.columns[3:]
X_train, X_test, y_train, y_test = cross_validation.train_test_split(phy_train[independent_vars], phy_train['target'], test_size=0.3, random_state=0)
X_train = pd.DataFrame(X_train)
X_train.columns = independent_vars
X_test = pd.DataFrame(X_test)
X_test.columns = independent_vars
y_train = pd.DataFrame(y_train)
y_train.columns = ['target']
y_test = pd.DataFrame(y_test)
y_test.columns = ['target']
logit = sm.Logit(y_train,X_train[subset],missing='drop')
result = logit.fit()
print result.summary()
y_pred = logit.predict(X_test[subset])
From the last line, I get this error:
> > > y_pred = logit.predict(X_test[subset]) Traceback (most recent call
> last): File "", line 1, in File
> "C:\Users\eMachine\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-
> packages\statsmodels\discrete\discrete_model.py", line 378, in predict
> return self.cdf(np.dot(exog, params)) ValueError: matrices are not aligned
My training and testing data set have the same number of variables so I am
sure I am misunderstanding what the logit.predict() is actually doing.
Answer: There are two predict methods.
`logit` in your example is the **model instance**. The model instance doesn't
know about the estimation results. The model predict has a different signature
because it needs the parameters also `logit.predict(params, exog)`. This is
mainly interesting for internal usage.
What you want is the predict method of the **results instance**. In your
example
`y_pred = result.predict(X_test[subset])`
should give the correct results. It uses the estimated parameters in the
prediction with your new test data of explanatory variables, X_test.
Calling `model.fit()` returns an instance of a results class that provides
access to additional post-estimation statistics and analysis, and to
prediction.
|
Is there a way to map GAE user object and Google+ userid
Question: As mentioned
[here](https://developers.google.com/appengine/docs/python/users/loginurls),
for default authentication using python users API an object will be returned
based on user's email. When `user_id()` is called over the object a unique id
is returned, which is of course not a Google+ user id.
import webapp2
from google.appengine.api import users
class MainPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
if users.is_current_user_admin():
utype = "Admin"
else:
utype = "Normal"
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('Hello, ' + user.nickname() + ' Userid: ' + user.user_id() + ' User Type: ' + utype)
else:
self.redirect(users.create_login_url(self.request.uri))
app = webapp2.WSGIApplication([
('/', MainPage)
], debug=False)
Basically, I need the plus id to retrieve some user details. (via [HTTP
GET](https://developers.google.com/+/api/latest/people/get))
Is there any available package in AppEngine API that can provide me with
google plus id for a logged in user's email?
Or should I move on to OAuth 2 for authentication purpose?
I have already completed 50% based on users API, so any help regarding the
same will be appreciated.
Answer: Yes, using their user.email()
To access properties of their Google+ profile you will need to use the Google
APIs Client Library for Python <https://developers.google.com/api-client-
library/python/start/installation>
|
Execute a python separate application in a java application
Question: I have a small java project which do several activities including a database
update and i have a separate python(.py) application which update the same
database after a data mining process. In my Java application i need to
open(execute) my python application which update the same database. i tried
several ways but the code is not working. below i paste the initial code
without calling the .py file.
if (getDB("BP") != 0.0 && getDB("BT") != 0.0 &&
getDB("SO2") != 0.0 && getDB("HR") != 0.0) {
if(analyzeData(inputLine)) {
setDB(inputLine);
//<python(.py) file should execute independently in this section, after setDB(inputLine)>
} }
else {
setNormalBio(inputLine);
}
Answer: I do not see anything related to spawning a new process from your java code.
Did you really investigate this topic? If not: Do not expect the following
code to be the top-notch solution. Maybe dig deeper in
<http://docs.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html> and
the python docs, as I remember, when I did this from PHP, I ran into some
problems with the python code itself.
Python (deadparrot.py):
from os import chdir, name as osname
from os.path import dirname, abspath
def voom():
if osname == 'posix':
chdir(dirname(abspath(__file__)))
return "Testing! This is your nine o'clock alarm call!"
if __name__ == '__main__':
print voom()
exit(0)
I am not sure with the chdir-call. Once got a project, in which I needed to
call python in a linux webserver environment with php (hence the 'posix'), and
doing stuff with relative pathes in the python-script. IIRC I didn't need it
while testing on my local windows-environment.
Edit 1: I tested it in Windows 7. It looks like neither pb.directory(...) or
chdir(...) is needed, to call relativ pathes from the python script. IDK about
linux.
About the '**__main__** ' condition. I am using this, because this way I still
can call the script from the java-app (exit(0) returns an ok in unix-
terminology) and in addition use the voom() function from another python-
script, like so:
from deadparrot import voom
voom()
Java:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestJavaAppClean {
public static void main(String[] args) {
ProcessBuilder pb = null;
Process p = null;
BufferedReader br = null;
try {
String top = "C:\\Users\\MaxMueller\\Documents\\test\\";
String cmd = "C:\\Python27\\python.exe";
String arg = "deadparrot.py";
pb = new ProcessBuilder(new String[]{cmd, top + arg});
pb.directory(new File(top));
p = pb.start();
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
}
if (p != null) {
p.destroy();
}
}
}
}
|
Applying variable transparency to an image in java
Question: I'm wondering how to apply a variable mask to an image's transparency in Java
(presumably using buffered image). So, for instance, I want to apply a mask
such as the following:

To the an image such as the following:

In order to get:

It's important that the transparency is changed by the gradient, not just the
color, because I want to be able to to this kind of thing:

I've found an incredibly slow way of achieving this by going through and
setting the transparency value of every single pixel manually, but as I said,
it's super slow. What should I be looking at to try to accomplish this? Or
should I even be doing it in Java? I've been getting to know python recently,
so if anyone thinks it's better to try this sort of thing with a particular
python module, that would be useful information as well.
Thank in advance!
Answer: Here is one way to get a transparent mask.
GradientMask.java:
import Utilities.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class GradientMask {
public static void main(String[] args) throws Exception{
JFrame Main = new JFrame("Gradient Mask");
JLabel imageLayer = new JLabel();
JLabel maskLayer = new JLabel();
BufferedImage image = ImageIO.read(new File("C:\\Users\\"+System.getenv("username")+"\\Desktop\\Cat Image.jpg"));
BufferedImage gradientMask = new GradientImage(image.getWidth(), image.getHeight(), new Color[]{new Color(255, 255, 255, 125), Color.BLACK}, GradientImage.RADIAL_FROM_CENTER).getImage();
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main.setBounds(100, 50, image.getWidth(), image.getHeight());
imageLayer.setBounds(0, 0, Main.getWidth(), Main.getHeight());
maskLayer.setBounds(0, 0, Main.getWidth(), Main.getHeight());
imageLayer.setIcon(new ImageIcon((Image) image));
maskLayer.setIcon(new ImageIcon((Image) gradientMask));
Main.getContentPane().add(imageLayer);
imageLayer.add(maskLayer);
Main.setVisible(true);
}
}
GradientImage.java:
package Utilities;
import java.awt.*;
import java.awt.image.*;
public class GradientImage {
public final static int LINEAR_LEFT_TO_RIGHT = 1;
public final static int LINEAR_RIGHT_TO_LEFT = 2;
public final static int LINEAR_TOP_TO_BOTTOM = 3;
public final static int LINEAR_BOTTOM_TO_TOP = 4;
public final static int LINEAR_DIAGONAL_UP = 5;
public final static int LINEAR_DIAGONAL_DOWN = 6;
public final static int RADIAL_FROM_TOP_LEFT_CORNER = 7;
public final static int RADIAL_FROM_BOTTOM_LEFT_CORNER = 8;
public final static int RADIAL_FROM_TOP_RIGHT_CORNER = 9;
public final static int RADIAL_FROM_BOTTOM_RIGHT_CORNER = 10;
public final static int RADIAL_FROM_CENTER = 11;
public final static int RADIAL_FROM_CORNERS = 12;
public final static int PATH_FROM_CENTER = 13;
public final static int PATH_FROM_TOP_LEFT_CORNER = 14;
public final static int PATH_FROM_TOP_RIGHT_CORNER = 15;
public final static int PATH_FROM_BOTTOM_LEFT_CORNER = 16;
public final static int PATH_FROM_BOTTOM_RIGHT_CORNER = 17;
public final static int LINEAR_FROM_TOP_RIGHT_CORNER = 18;
public final static int LINEAR_FROM_TOP_LEFT_CORNER = 19;
public final static int LINEAR_FROM_BOTTOM_RIGHT_CORNER = 20;
public final static int LINEAR_FROM_BOTTOM_LEFT_CORNER = 21;
public final static int LINEAR_FROM_CENTER = 22;
public final static int LINEAR_FROM_CORNERS = 23;
public final static int PATH_FROM_CORNERS = 24;
private BufferedImage image = null;
private BufferedImage circleImage = null;
private int[] pixels;
private int[] circlePixels;
private int[] positions;
private Color[] colors;
private int[] rgbs;
private int alignment;
private int width;
private int height;
public GradientImage(int width, int height, Color[] colors, int alignment){
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
this.alignment = alignment;
this.width = width;
this.height = height;
this.colors = colors;
rgbs = new int[colors.length];
for (int i=0;i<rgbs.length;i++){
rgbs[i] = colors[i].getRGB();
}
try{
renderImage();
}catch(Exception error){error.printStackTrace();}
}
public GradientImage(int width, int height, Color[] colors, int[] positions, int alignment){
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
this.alignment = alignment;
this.width = width;
this.height = height;
this.colors = colors;
this.positions = positions;
rgbs = new int[colors.length];
for (int i=0;i<rgbs.length;i++){
rgbs[i] = colors[i].getRGB();
}
try{
renderImage();
}catch(Exception error){error.printStackTrace();}
}
public BufferedImage getImage(){
return image;
}
public BufferedImage getImageAsCircle(){
if (circleImage==null){
circleImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
circlePixels = ((DataBufferInt) circleImage.getRaster().getDataBuffer()).getData();
int radius = Math.min(width, height)>>1;
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
if (Math.sqrt((Math.max(width>>1, x)-Math.min(width>>1, x))*(Math.max(width>>1, x)-Math.min(width>>1, x))+(Math.max(height>>1, y)-Math.min(height>>1, y))*(Math.max(height>>1, y)-Math.min(height>>1, y)))<=radius){
circlePixels[x+y*width] = pixels[x+y*width];
}
}
}
}
return circleImage;
}
private void renderImage() throws Exception{
if (alignment==LINEAR_LEFT_TO_RIGHT){
int[] rgbRange = loadRGBRange(width, rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+y*width] = rgbRange[x];
}
}
}else if (alignment==LINEAR_RIGHT_TO_LEFT){
int[] rgbRange = loadRGBRange(width, rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+y*width] = rgbRange[width-x-1];
}
}
}else if (alignment==LINEAR_BOTTOM_TO_TOP){
int[] rgbRange = loadRGBRange(height, rgbs, positions);
for (int y=0;y<height;y++){
for (int x=0;x<width;x++){
pixels[x+y*width] = rgbRange[height-y-1];
}
}
}else if (alignment==LINEAR_TOP_TO_BOTTOM){
int[] rgbRange = loadRGBRange(height, rgbs, positions);
for (int y=0;y<height;y++){
for (int x=0;x<width;x++){
pixels[x+y*width] = rgbRange[y];
}
}
}else if (alignment==RADIAL_FROM_TOP_LEFT_CORNER){
int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+y*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
}
}
}else if (alignment==RADIAL_FROM_BOTTOM_LEFT_CORNER){
int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+(height-y-1)*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
}
}
}else if (alignment==RADIAL_FROM_TOP_RIGHT_CORNER){
int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[(width-x-1)+y*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
}
}
}else if (alignment==RADIAL_FROM_BOTTOM_RIGHT_CORNER){
int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[(width-x-1)+(height-y-1)*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
}
}
}else if (alignment==RADIAL_FROM_CENTER){
int[] divArray = divideArray(positions, 2);
BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_RIGHT_CORNER).getImage();
BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_LEFT_CORNER).getImage();
BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_RIGHT_CORNER).getImage();
BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_LEFT_CORNER).getImage();
Graphics2D g = image.createGraphics();
g.drawImage(quad1, 0, 0, null);
g.drawImage(quad2, width>>1, 0, null);
g.drawImage(quad3, 0, height>>1, null);
g.drawImage(quad4, width>>1, height>>1, null);
g.dispose();
}else if (alignment==RADIAL_FROM_CORNERS){
int[] divArray = divideArray(positions, 2);
BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_LEFT_CORNER).getImage();
BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_RIGHT_CORNER).getImage();
BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_LEFT_CORNER).getImage();
BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_RIGHT_CORNER).getImage();
Graphics2D g = image.createGraphics();
g.drawImage(quad1, 0, 0, null);
g.drawImage(quad2, width>>1, 0, null);
g.drawImage(quad3, 0, height>>1, null);
g.drawImage(quad4, width>>1, height>>1, null);
g.dispose();
}else if (alignment==LINEAR_DIAGONAL_UP){
int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+(height-y-1)*width] = rgbRange[Math.max(y-x, x-y)];
}
}
}else if (alignment==LINEAR_DIAGONAL_DOWN){
int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+y*width] = rgbRange[Math.max(y-x, x-y)];
}
}
}else if (alignment==LINEAR_FROM_TOP_RIGHT_CORNER){
int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+(height-y-1)*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
}
}
}else if (alignment==LINEAR_FROM_TOP_LEFT_CORNER){
int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[(width-x-1)+(height-y-1)*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
}
}
}else if (alignment==LINEAR_FROM_BOTTOM_RIGHT_CORNER){
int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+y*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
}
}
}else if (alignment==LINEAR_FROM_BOTTOM_LEFT_CORNER){
int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[(width-x-1)+y*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
}
}
}else if (alignment==LINEAR_FROM_CENTER){
int[] divArray = divideArray(positions, 2);
BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_RIGHT_CORNER).getImage();
BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_LEFT_CORNER).getImage();
BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_RIGHT_CORNER).getImage();
BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_LEFT_CORNER).getImage();
Graphics2D g = image.createGraphics();
g.drawImage(quad1, 0, 0, null);
g.drawImage(quad2, width>>1, 0, null);
g.drawImage(quad3, 0, height>>1, null);
g.drawImage(quad4, width>>1, height>>1, null);
g.dispose();
}else if (alignment==LINEAR_FROM_CORNERS){
int[] divArray = divideArray(positions, 2);
BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_LEFT_CORNER).getImage();
BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_RIGHT_CORNER).getImage();
BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_LEFT_CORNER).getImage();
BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_RIGHT_CORNER).getImage();
Graphics2D g = image.createGraphics();
g.drawImage(quad1, 0, 0, null);
g.drawImage(quad2, width>>1, 0, null);
g.drawImage(quad3, 0, height>>1, null);
g.drawImage(quad4, width>>1, height>>1, null);
g.dispose();
}else if (alignment==PATH_FROM_TOP_LEFT_CORNER){
int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+y*width] = rgbRange[Math.max(x, y)];
}
}
}else if (alignment==PATH_FROM_TOP_RIGHT_CORNER){
int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[(width-x-1)+y*width] = rgbRange[Math.max(x, y)];
}
}
}else if (alignment==PATH_FROM_BOTTOM_LEFT_CORNER){
int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[x+(height-y-1)*width] = rgbRange[Math.max(x, y)];
}
}
}else if (alignment==PATH_FROM_BOTTOM_RIGHT_CORNER){
int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
for (int x=0;x<width;x++){
for (int y=0;y<height;y++){
pixels[(width-x-1)+(height-y-1)*width] = rgbRange[Math.max(x, y)];
}
}
}else if (alignment==PATH_FROM_CENTER){
int[] divArray = divideArray(positions, 2);
BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_RIGHT_CORNER).getImage();
BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_LEFT_CORNER).getImage();
BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_RIGHT_CORNER).getImage();
BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_LEFT_CORNER).getImage();
Graphics2D g = image.createGraphics();
g.drawImage(quad1, 0, 0, null);
g.drawImage(quad2, width>>1, 0, null);
g.drawImage(quad3, 0, height>>1, null);
g.drawImage(quad4, width>>1, height>>1, null);
g.dispose();
}else if (alignment==PATH_FROM_CORNERS){
int[] divArray = divideArray(positions, 2);
BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_LEFT_CORNER).getImage();
BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_RIGHT_CORNER).getImage();
BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_LEFT_CORNER).getImage();
BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_RIGHT_CORNER).getImage();
Graphics2D g = image.createGraphics();
g.drawImage(quad1, 0, 0, null);
g.drawImage(quad2, width>>1, 0, null);
g.drawImage(quad3, 0, height>>1, null);
g.drawImage(quad4, width>>1, height>>1, null);
g.dispose();
}
}
public int[] divideArray(int[] array, int div){
if (array==null){
return null;
}
int[] arr = new int[array.length];
if (div==2){
for (int i=0;i<arr.length;i++){
arr[i] = array[i]>>1;
}
}else{
for (int i=0;i<arr.length;i++){
arr[i] = array[i]/div;
}
}
return arr;
}
public int[] loadRGBRange(int length, int[] rgbs) throws Exception {
if (rgbs==null){
throw new Exception("RGB[]'s cannot be null");
}
if (length==0){
throw new Exception("Length cannot be 0");
}
if (rgbs.length==0){
throw new Exception("RGB[]'s length cannot be 0");
}
int[] rgbRange = new int[length];
if (rgbs.length==1){
for (int i=0;i<rgbRange.length;i++){
rgbRange[i] = rgbs[0];
}
return rgbRange;
}
int[] positions = new int[rgbs.length];
double pos = 0;
double block = (double) length/(rgbs.length-1);
for (int i=0;i<positions.length;i++){
positions[i] = (int) pos;
pos+=block;
}
int[] as = new int[rgbs.length];
int[] rs = new int[rgbs.length];
int[] gs = new int[rgbs.length];
int[] bs = new int[rgbs.length];
for (int i=0;i<rgbs.length;i++){
as[i] = (rgbs[i]>>24) & 0xff;
rs[i] = (rgbs[i]>>16) & 0xff;
gs[i] = (rgbs[i]>>8) & 0xff;
bs[i] = (rgbs[i]) & 0xff;
}
int[] adifs = new int[rgbs.length-1];
int[] rdifs = new int[rgbs.length-1];
int[] gdifs = new int[rgbs.length-1];
int[] bdifs = new int[rgbs.length-1];
for (int i=0;i<rgbs.length-1;i++){
adifs[i] = as[i]-as[i+1];
rdifs[i] = rs[i]-rs[i+1];
gdifs[i] = gs[i]-gs[i+1];
bdifs[i] = bs[i]-bs[i+1];
}
double[] ab = new double[rgbs.length-1];
double[] rb = new double[rgbs.length-1];
double[] gb = new double[rgbs.length-1];
double[] bb = new double[rgbs.length-1];
for (int i=0;i<rgbs.length-1;i++){
int l = positions[i+1]-positions[i];
ab[i] = (double) adifs[i]/l;
rb[i] = (double) rdifs[i]/l;
gb[i] = (double) gdifs[i]/l;
bb[i] = (double) bdifs[i]/l;
}
double a = as[0];
double r = rs[0];
double g = gs[0];
double b = bs[0];
int color = 0;
for (int i=0;i<rgbRange.length;i++){
rgbRange[i] = ((int)a<<24)|((int)r<<16)|((int)g<<8)|((int)b);
if (i+1>positions[0] && i+1<positions[positions.length-1]){
if (i==positions[color+1]){
color++;
a = as[color];
r = rs[color];
g = gs[color];
b = bs[color];
}else{
a-=ab[color];
r-=rb[color];
g-=gb[color];
b-=bb[color];
}
}
}
return rgbRange;
}
public int[] loadRGBRange(int length, int[] rgbs, int[] positions) throws Exception {
if (positions==null){
return loadRGBRange(length, rgbs);
}
if (rgbs==null){
throw new Exception("RGB[]'s cannot be null");
}
if (length==0){
throw new Exception("Length cannot be 0");
}
if (rgbs.length==0 || positions.length==0){
return null;
}
if (positions.length!=rgbs.length){
throw new Exception("The length of Positions[] must equals the length of RGB[]'s");
}
for (int i=0;i<positions.length;i++){
if (positions[i]>length){
throw new Exception("Any positions cannot be greater than the length");
}
}
int[] rgbRange = new int[length];
if (rgbs.length==1){
for (int i=0;i<rgbRange.length;i++){
rgbRange[i] = rgbs[0];
}
return rgbRange;
}
int[] as = new int[rgbs.length];
int[] rs = new int[rgbs.length];
int[] gs = new int[rgbs.length];
int[] bs = new int[rgbs.length];
for (int i=0;i<rgbs.length;i++){
as[i] = (rgbs[i]>>24) & 0xff;
rs[i] = (rgbs[i]>>16) & 0xff;
gs[i] = (rgbs[i]>>8) & 0xff;
bs[i] = (rgbs[i]) & 0xff;
}
int[] adifs = new int[rgbs.length-1];
int[] rdifs = new int[rgbs.length-1];
int[] gdifs = new int[rgbs.length-1];
int[] bdifs = new int[rgbs.length-1];
for (int i=0;i<rgbs.length-1;i++){
adifs[i] = as[i]-as[i+1];
rdifs[i] = rs[i]-rs[i+1];
gdifs[i] = gs[i]-gs[i+1];
bdifs[i] = bs[i]-bs[i+1];
}
double[] ab = new double[rgbs.length-1];
double[] rb = new double[rgbs.length-1];
double[] gb = new double[rgbs.length-1];
double[] bb = new double[rgbs.length-1];
for (int i=0;i<rgbs.length-1;i++){
int l = positions[i+1]-positions[i];
ab[i] = (double) adifs[i]/l;
rb[i] = (double) rdifs[i]/l;
gb[i] = (double) gdifs[i]/l;
bb[i] = (double) bdifs[i]/l;
}
double a = as[0];
double r = rs[0];
double g = gs[0];
double b = bs[0];
int color = 0;
for (int i=0;i<rgbRange.length;i++){
rgbRange[i] = ((int)a<<24)|((int)r<<16)|((int)g<<8)|((int)b);
if (i+1>positions[0] && i+1<positions[positions.length-1]){
if (i==positions[color+1]){
color++;
a = as[color];
r = rs[color];
g = gs[color];
b = bs[color];
}else{
a-=ab[color];
r-=rb[color];
g-=gb[color];
b-=bb[color];
}
}
}
return rgbRange;
}
}
|
Does the SVM in sklearn support incremental (online) learning?
Question: I am currently in the process of designing a recommender system for text
articles (a binary case of 'interesting' or 'not interesting'). One of my
specifications is that it should continuously update to changing trends.
From what I can tell, the best way to do this is to make use of machine
learning algorithm that supports incremental/[online
learning](http://en.wikipedia.org/wiki/Online%5fmachine%5flearning).
Algorithms like the Perceptron and Winnow support online learning but I am not
completely certain about Support Vector Machines. Does the scikit-learn python
library support online learning and if so, is a support vector machine one of
the algorithms that can make use of it?
I am obviously not completely tied down to using support vector machines, but
they are usually the go to algorithm for binary classification due to their
all round performance. I would be willing to change to whatever fits best in
the end.
Answer: While online algorithms for SVMs do exist, it has become important to specify
if you want kernel or linear SVMs, as many efficient algorithms have been
developed for the special case of linear SVMs.
For the linear case, if you use the [SGD classifier in scikit-
learn](http://scikit-learn.org/stable/modules/sgd.html#sgd) with the hinge
loss and L2 regularization you will get an SVM that can be updated
online/incrementall. You can combine this with [feature transforms that
approximate a kernel](http://scikit-
learn.org/stable/modules/kernel_approximation.html) to get similar to an
online kernel SVM.
> One of my specifications is that it should continuously update to changing
> trends.
This is referred to as _concept drift,_ and will not be handled well by a
simple online SVM. Using the PassiveAggresive classifier will likely give you
better results, as it's learning rate does not decrease over time.
Assuming you get feedback while training / running, you can attempt to detect
decreases in accuracy over time and begin training a new model when the
accuracy starts to decrease (and switch to the new one when you believe that
it has become more accurate). [JSAT](https://code.google.com/p/java-
statistical-analysis-tool/) has 2 drift detection methods (see
[jsat.driftdetectors](https://code.google.com/p/java-statistical-analysis-
tool/source/browse/#svn/trunk/JSAT/src/jsat/driftdetectors)) that can be used
to track accuracy and alert you when it has changed.
It also has more online linear and kernel methods.
(bias note: I'm the author of JSAT).
|
installing lxml in OSX 10.9
Question: I have a problem installing the `lxml` in my mavericks machine.
I tried all possibilities by installing the prebuild binaries using
* normal pip
* pip with `static deps`
and Building
* Current version in normal model
* Current version with static deps
* Older version in normal mode
* Older version with static deps
and always end up in this error.
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1
here the detailed message
copying /Users/mangoreader/work/lxml-3.3.4/build/tmp/libxml2/include/libxslt/xsltutils.h -> build/lib.macosx-10.9-intel-2.7/lxml/includes/libxslt
running build_ext
building 'lxml.etree' extension
cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -I/Users/mangoreader/work/lxml-3.3.4/build/tmp/libxml2/include -I/Users/mangoreader/work/lxml-3.3.4/build/tmp/libxml2/include/libxml2 -I/Users/mangoreader/work/lxml-3.3.4/build/tmp/libxml2/include/libxslt -I/Users/mangoreader/work/lxml-3.3.4/build/tmp/libxml2/include/libexslt -I/Users/mangoreader/work/lxml-3.3.4/src/lxml/includes -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/lxml/lxml.etree.c -o build/temp.macosx-10.9-intel-2.7/src/lxml/lxml.etree.o -w -flat_namespace
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1
Also when i tried installing `cython` , i am getting the same error
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1
detailed log here
cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c /private/var/folders/1z/7lv1qq457qxbhkgpt1fk9sdc0000gn/T/pip_build_mangoreader/cython/Cython/Plex/Scanners.c -o build/temp.macosx-10.9-intel-2.7/private/var/folders/1z/7lv1qq457qxbhkgpt1fk9sdc0000gn/T/pip_build_mangoreader/cython/Cython/Plex/Scanners.o
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1
----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/1z/7lv1qq457qxbhkgpt1fk9sdc0000gn/T/pip_build_mangoreader/cython/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/1z/7lv1qq457qxbhkgpt1fk9sdc0000gn/T/pip-0akrMB-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/1z/7lv1qq457qxbhkgpt1fk9sdc0000gn/T/pip_build_mangoreader/cython
Storing debug log for failure in /Users/mangoreader/Library/Logs/pip.log
I am totally struck here. It seems this is something to do with the version
conflict with gcc or libxml. But i could't figure out what. Any help much
appreciated.
**SOLVED**
As per this SO post [clang error: unknown argument: '-mno-fused-madd' (python
package installation
failure)](http://stackoverflow.com/questions/22313407/clang-error-unknown-
argument-mno-fused-madd-python-package-installation-fa?rq=1), this can be
fixed by setting up this following env variables
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
Answer: I am sure that by that that you sorted it out, but in case someone else needs
it, install XCode and command line tools and just run
pip install lxml
It will work, may take a little time.
|
Does python make a copy of opened files in memory?
Question: So I would like to search for filenames with os.walk() and write the resulting
list of names to a file. I would like to know what is more efficient : opening
the file and then writing each result as I find them or storing everything in
a list and then writing the whole list. That list could be big so I wonder if
the second solution would work.
Answer: See this example:
import os
fil = open('/tmp/stuff', 'w')
fil.write('aaa')
os.system('cat /tmp/stuff')
You may expect to see `aaa`, but instead you get nothing. This is because
Python has an internal buffer. Writing to disk is expensive, as it has to:
* Tell the OS to write it.
* Actually transfer the data to the disk (on a hard disk it may involve spinning it up, waiting for IO time, etc.).
* Wait for the OS to report success on the writing.
If you want to write any small things, it can add up to quite some time.
Instead, what Python does is to keep a buffer and only _actually_ write from
time to time. You don't have to worry about the memory growth, as it will be
kept at a low value. From the
[docs](https://docs.python.org/2/library/functions.html#open):
"0 means unbuffered, 1 means line buffered, any other positive value means use
a buffer of (approximately) that size (in bytes). A negative buffering means
to use the system default, which is usually line buffered for tty devices and
fully buffered for other files. If omitted, the system default is used."
When you are done, make sure you do a `fil.close()`, or `fil.flush()` at any
point during the execution, or use the keyword `buffering=0` to disable
buffering.
Another thing to consider is what happens if, for some reason, the program
exits in the middle of the process. If you store everything in memory, it will
be lost. What you have on disk, will remain there (but unless you flush, there
is no guarantee of how much was actually saved).
|
plotting dynamic data using matplotlib
Question: I'm writing an application do display data that changes dynamically (the data
being read from a socket).
As a dummy case, I try to draw a sine with an amplitude multiplied by 1.1 each
second:
import numpy as np
import matplotlib.pyplot as plt
import time
x = np.arange(0, 10, 0.1);
y = np.sin(x)
for i in xrange(100):
plt.plot(x, y)
time.sleep(1)
y=y*1.1
This obviously not the way do it, but it shows my intentions.
How can it be done correctly?
**EDIT:** The following is the traceback output of the code suggested in
@mskimm answer:
plt.show() #Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
File "<ipython-input-5-ed773f8e3e84>", line 7, in update
plt.draw()
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 466, in draw
get_current_fig_manager().canvas.draw()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 240, in draw
tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/tkagg.py", line 12, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
RuntimeError: main thread is not in main loop
**EDIT 2:**
it turns out that same code works when run in qtconsole... (any idea why?) How
ever, each print rescaling to plot, so the "animation effect" is missing. I
try to use `plt.autoscale_view(False,False,False)` but that just caused no
plot at all.
Answer: There are better ways to do this using the [matplotlib animation
API](http://matplotlib.org/1.3.1/examples/animation/simple_anim.html), but
here's a quick and dirty approach:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.ion()
ax = plt.gca()
ax.set_autoscale_on(True)
line, = ax.plot(x, y)
for i in xrange(100):
line.set_ydata(y)
ax.relim()
ax.autoscale_view(True,True,True)
plt.draw()
y=y*1.1
plt.pause(0.1)
The key steps are:
1. Turn on interactive mode with `plt.ion()`.
2. Keep track of the line(s) you want to update, and overwrite their data instead of calling `plot` again.
3. Give Python some time to update the plot window by calling `plt.pause`.
I included the code to autoscale the viewport, but that's not strictly
necessary.
|
JSON to CSV in python convert issue
Question: I am trying to convert a nested JSON object file into CSV. Here is the sample
of JSON
{
"total_hosts" : [
{
"TYPE" : "AGENT",
"COUNT" : 6
}
],
"installed" : [
{
"ID" : "admin-4.0",
"VERSION" : 4,
"ADDON_NAME" : "Administration"
},
{
"ID" : "admin-2.0",
"VERSION" : 2,
"ADDON_NAME" : "Administration"
},
{
"ID" : "ch-5.0",
"VERSION" : "5",
"ADDON_NAME" : "Control Host"
}
],
"virtual_machine" : [
{
"COUNT" : 4,
"TYPE" : "VM"
}
TYPE,COUNT,ID,VERSION like these are columns but the problem is not each
object have values in it some have 1 object with these values or some have
more so,I write in row , so i am trying to write blank space when there is no
value for that column.
the code to write it into CSV
json_input = open('all.json')
try:
decoded = json.load(json_input)
# tell computer where to put CSV
outfile_path='Path to CSV'
# open it up, the w means we will write to it
writer = csv.writer(open(outfile_path,'w'))
for index in range(len(decoded['installed'])):
row = []
if decoded['total_hosts'][index]['TYPE'] is None:
row.append(str(''))
else:
row.append(str(decoded['total_hosts'][index]['TYPE']))
if decoded['total_hosts'][index]['COUNT'] is None:
row.append(str(''))
else:
row.append(str(decoded['total_hosts'][index]['COUNT']))
writer.writerow(row)
I am getting `Index out of range` error , I even tried `True`/`False`
condition for `if`.
Can anyone help me with this?
Updated : Expected Output :
TYPE,COUNT,ID,VERSION,ADDON_NAME,COUNT,TYPE
AGENT,6,admin-4.0,4,Administration,4,VM
, ,admin-2.0,2,Administration, ,
, ,cd-5.0,5,Control Host, ,
So basically i need blank spaces when there is no value for that column.
Quesion Modified : OUTPUT :
AGENT,6,,,
, ,admin-4.0,4,Administration
, ,admin-2.0,2,Administration
, ,ch-5.0,5,Control Host
Expected OUTPUT :
AGENT,6,admin-4.0,4,Administration
, ,admin-2.0,2,Administration
, ,ch-5.0,5,Control Host
Updated : I even tried
row.append(str(entry.get('TYPE', '')))
row.append(str(entry.get('COUNT', '')))
row.append(str(entry.get('ID', '')))
row.append(str(entry.get('VERSION', '')))
row.append(str(entry.get('ADDON_NAME', '')))
writer.writerow(row)
Still got the same output as above. :(
Answer: There are two mistakes here:
1. You use the length of `decoded['installed']` to generate an index you then use for the `decoded['total_hosts']` list. This will generate index errors because `decoded['total_hosts']` doesn't have as many entries.
2. Accessing a key that doesn't exist will throw a `KeyError`; use the [`dict.get()` method](https://docs.python.org/2/library/stdtypes.html#dict.get) instead to retrieve a value or a default.
It's much simpler to just loop _directly_ over a list, no need to generate an
index:
for host in decoded['total_hosts']:
row = [host.get('TYPE', ''), host.get('COUNT', '')]
writer.writerow(row)
You can extend this to handle more than one key:
for key in ('total_hosts', 'installed', 'virtual_machine'):
for entry in decoded[key]:
row = [entry.get('TYPE', ''), entry.get('COUNT', '')]
writer.writerow(row)
If you needed to _combine_ the output of two entries, use
[`itertools.izip_longest()`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest)
to pair up the lists, using a default value for when the shorter list runs
out:
from itertools import izip_longest
for t, i, v in izip_longest(decoded['total_hosts'], decoded['installed'], decoded['version'], fillvalue={}):
row = [t.get('TYPE', ''), t.get('COUNT', ''),
i('ID', ''), i('VERSION', ''), i.get('ADDON_NAME', ''),
v.get('COUNT', ''), v.get('TYPE', '')]
writer.writerow(row)
This allows for any one of the three lists to be shorter than the others.
For Python versions before 2.6 (which added `itertools.izip_longest`) you'd
have to assume that `installed` was always longest, and then use:
for i, installed in decoded['installed']:
t = decoded['types'][i] if i < len(decoded['types']) else {}
v = decoded['version'][i] if i < len(decoded['version']) else {}
row = [t.get('TYPE', ''), t.get('COUNT', ''),
installed['ID'], installed['VERSION'], installed['ADDON_NAME'],
v.get('COUNT', ''), v.get('TYPE', '')]
writer.writerow(row)
|
Apache Benchmark horror results with a simple Gevent app
Question: I have a simple Python code to run Gevent.
Tested with Apache Benchmark with 10000 users and 5 concurrent but it's damn
slow..nearly 2 seconds per request (1.419 ms) which is bad..
My code is
from gevent import wsgi, monkey
class WebServer(object):
def application(self, environ, start_response):
start_response("200 OK", [])
return ["Hello world!"]
if __name__ == "__main__":
monkey.patch_all()
app = WebServer()
wsgi.WSGIServer(('', 8888), app.application, log=None).serve_forever()
and the results are pretty horrible
Server Software:
Server Hostname: 127.0.0.1
Server Port: 8888
Document Path: /
Document Length: 12 bytes
Concurrency Level: 5
Time taken for tests: 28.379 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 10700000 bytes
HTML transferred: 1200000 bytes
Requests per second: 3523.73 [#/sec] (mean)
Time per request: 1.419 [ms] (mean)
Time per request: 0.284 [ms] (mean, across all concurrent requests)
Transfer rate: 368.20 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.0 0 4
Processing: 0 1 0.1 1 10
Waiting: 0 1 0.1 1 10
Total: 0 1 0.1 1 10
Percentage of the requests served within a certain time (ms)
50% 1
66% 1
75% 1
80% 1
90% 1
95% 1
98% 2
99% 2
100% 10 (longest request)
why is that?? this guy got way better results than mine, with the same code
<http://blindvic.blogspot.it/2013/04/hello-world-gevent-vs-nodejs.html>
Tell me if I'm missing something here..
I searched to see if there are any tuning to do but can't find anything.
Answer: Americans use "." as the decimal point, not as a separator between thousands
and hundreds. "1.419" is more than 1 and less than 2, not over 1,000.
|
How do I show a Test_Question (String) per page?? (PyQt/Python)
Question: I am creating a PyQt application which creates and sets tests for the user.
However, when setting the test questions i wanted 1 question to be viewed per
page. For example, if the user was to start a test, then a question would
appear. Once they have answered that question, then they click a button
`'Proceed'` which presents the next page showing only the 2nd question and so
on... However, in my case, i am unaware as to how many questions there are in
each test, so the number of pages will vary. I am using switching layouts as i
would rather switch layouts as opposed to open new windows but that means that
i have to create a class per question and because questions per test vary, i
am unsure as to how i will present the questions????
I am not going to copy out my entire application code but will provide a basic
example below:
import sys
from PyQt4 import QtCore, QtGui
class StartTest(QtGui.QMainWindow):
def __init__(self, parent=None):
super(StartTest, self).__init__(parent)
self.central_widget = QtGui.QStackedWidget()
self.setCentralWidget(self.central_widget)
question1 = Question1(self)
self.central_widget.addWidget(question1)
self.central_widget.setCurrentWidget(question1)
question1.proceed.clicked.connect(self.question2)
def question2(self):
question2 = Question2(self)
self.central_widget.addWidget(question2)
self.central_widget.setCurrentWidget(question2)
class Question1(QtGui.QWidget):
def __init__(self, parent=None):
super(Question1, self).__init__(parent)
question = QtGui.QLabel('What is 5+5?')
self.proceed = QtGui.QPushButton("Proceed")
self.Answer = QtGui.QLineEdit(self)
layout = QtGui.QFormLayout()
layout.addRow(question, self.Answer)
layout2 = QtGui.QVBoxLayout()
layout2.addLayout(layout)
layout2.addWidget(self.proceed)
self.setLayout(layout2)
class Question2(QtGui.QWidget):
def __init__(self, parent=None):
super(Question2, self).__init__(parent)
question = QtGui.QLabel('What is 45+10?')
self.proceed = QtGui.QPushButton("Proceed")
self.Answer = QtGui.QLineEdit(self)
layout = QtGui.QFormLayout()
layout.addRow(question, self.Answer)
layout2 = QtGui.QVBoxLayout()
layout2.addLayout(layout)
layout2.addWidget(self.proceed)
self.setLayout(layout2)
#....
if __name__ == '__main__':
User = ''
app = QtGui.QApplication([])
window = StartTest()
window.showFullScreen()
app.exec_()
Answer: Just have a single `Question` class that can be parameterized. For the example
code in the question, this would be as simple as passing the label text as an
argument, since this is the only thing that is different:
class Question(QtGui.QWidget):
def __init__(self, label, parent=None):
super(Question, self).__init__(parent)
question = QtGui.QLabel(label)
...
question1 = Question('What is 5+5?', self)
question2 = Question('What is 45+10?', self)
If some question types have a different structure, you could create subclasses
for each type:
class ComplexQuestion(Question):
def __init__(self, label, parent=None):
super(ComplexQuestion, self).__init__(parent)
# do additional initialization...
Or if you wanted to avoid subclassing, you could simply add methods to the
`Question` class that enabled/disabled certain features.
|
what is a way to ask in python if a number actually exists and is not masked in python
Question: I have an numpy array with 13 invalid (logs of zeros) numbers that I have
masked and 3 valid numbers:
[[-- -- -- --]
[-- -- 0.0 0.3010299956639812]
[-- -- -- 0.0]
[-- -- -- --]]
I want to print out something like
numlist=[]
for item in array:
numlist.append(num)
for i in numlist:
if i is not masked:
print i
any suggestions?
Answer: You could use the
[MaskedArray.compressed](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.MaskedArray.compressed.html#numpy.ma.MaskedArray.compressed)
method to return all the non-masked data:
print(arr.compressed())
To print one value per line:
for val in arr.compressed():
print(val)
* * *
If you wish to save space (instead of time), you could use `ravel` (as @DSM
points out). To iterate over the non-masked entries, you could use IT.izip to
loop over the values and the mask at the same time. For example,
import itertools as IT
import numpy as np
arr = np.ma.masked_invalid(np.log(np.random.random((4,4))-0.5))
arr1d = arr.ravel()
for val, mask in IT.izip(arr1d, arr1d.mask):
if not mask:
print(val)
|
Python Subprocess Finishes, but Output File Not Available
Question: My python code is using a subprocess to call "ifconfig" through the shell and
uses ">" to write the output to a text file. When the subprocess finishes, and
returns success, I read the output file. I do this at fixed intervals to
monitor the network status, but occasionally I'm unable to open the output
file. I was just reading that Popen has optional arguments for stdout and
stderr, which may be safer/better supported, but I'm curious to why my current
version fails. My code is below. There are a few objects and macros from my
library included without explanation, but I think the code is still clear
enough for this question.
Why does opening the output file occasionally fail? Is it possible the file is
not ready when the subprocess returns? What would be a way to guarantee it's
ready to open?
# Build command line expression.
expr = 'ifconfig' + ' >' + outputFile + ' 2>&1'
try:
# Execute command line expression.
p = subprocess.Popen(expr, shell=True)
except:
Error("Unable to open subprocess.")
if(p is None):
Error("Unable to create subprocess.")
# Wait until command line expression has been executed.
wait = Wait.Wait(Constants.MIN_TIME_TO_QUERY_NETWORK_INFO, Constants.MAX_TIME_TO_QUERY_NETWORK_INFO)
#Execute command then wait for timeout.
if (wait.StopUntilCondition(operator.ne, (p.poll,), None, True)):
p.kill()
Error("Get subnet mask subprocess timed out.")
if(not p.poll() == 0):
Error("Failed to get network information from operating system.")
Warning("About to read output file from get subnet mask...")
# Read temporary output file.
f = open(outputFile, "r")
networkInfo = f.read()
f.close()
Answer: To avoid the corrupted/missing output, you should call `p.wait()` before
trying to read the file. You don't need to use a file in this case:
from subprocess import check_output, STDOUT
network_info = check_output('ifconfig', stderr=STDOUT)
If you want to interrupt `ifconfig` before it is done _and_ read its output;
see [Stop reading process output in Python without
hang?](http://stackoverflow.com/q/4417962/4279)
|
Super basic uwsgi configuration
Question: I've tried some uwsgi tutorials but can't get a simple python script to run in
my browser. Ive read through this (<http://uwsgi-
docs.readthedocs.org/en/latest/WSGIquickstart.html>) and this
(<https://www.digitalocean.com/community/articles/how-to-deploy-python-wsgi-
applications-using-uwsgi-web-server-with-nginx>) and others, but for some
reason can't get a simple uwsgi app running. I am currently not going through
a web server, just uwsgi by itself.
I have the following wsgi.py:
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return ["Hello!"]
and I run:
uwsgi --socket 127.0.0.1:8080 --chdir /my/program/path --pp .. -w wsgi
which produces the following output (looks promising):
*** Starting uWSGI 2.0.3 (64bit) on [Mon Apr 14 12:51:32 2014] ***
compiled with version: 4.6.3 20120306 (Red Hat 4.6.3-2) on 14 April 2014 12:01:33
os: Linux-3.1.0-7.fc16.x86_64 #1 SMP Tue Nov 1 21:10:48 UTC 2011
nodename: ip-10-252-98-215
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /usr/oai/icscada/www
detected binary path: /usr/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 1024
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address 127.0.0.1:8080 fd 3
Python version: 2.7.3 (default, Jul 24 2012, 11:41:40) [GCC 4.6.3 20120306 (Red Hat 4.6.3-2)]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x2504ee0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72752 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
added ../ to pythonpath.
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x2504ee0 pid: 21702 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 21702, cores: 1)
but when I go to port 8080 from my browser I get a "could not connect" error.
Port 8080 is open and has been tested.
* * *
I've also tried the following wsgi.py:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
exactly the same results
Answer: If you want to run uWSGI without a web server in front of it, use `http`
option instead of `socket`. See [Native HTTP support](http://uwsgi-
docs.readthedocs.org/en/latest/HTTP.html).
Also, use 0.0.0.0:80 as an address if you are accessing from a remote machine.
|
Python MySQL insert and retrieve a list in Blob
Question: I'm trying to insert a list of element into a MySQL database (into a Blob
column). This is an example of my code is:
myList = [1345,22,3,4,5]
myListString = str(myList)
myQuery = 'INSERT INTO table (blobData) VALUES (%s)'
cursor.execute(query, myListString)
Everything works fine and I have my list stored in my database. But, when I
want to retrieve my list, because it's now a string I have no idea how to get
a real integer list instead of a string.
For example, if now i do :
myQuery = 'SELECT blobData FROM db.table'
cursor.execute(myQuery)
myRetrievedList = cursor.fetch_all()
print myRetrievedList[0]
I ll get :
[
instead of :
1345
Is there any way to transform my string [1345,22,3,4,5] into a list ?
Answer: Edit, as per the OP, he (she?) has a list of lists being entered as the blob
field. In that case, the JSON seems a better way to go.
import json
...
...
myRetrievedList = cursor.fetch_all()
jsonOfBlob = json.loads(myRetrievedList)
integerListOfLists = []
for oneList in jsonOfBlob:
listOfInts = [int(x) for x in oneList]
integerListOfLists.append(listOfInts)
return integerListOfLists #or print, or whatever
|
Installing Swampy for Python 2.7 Help Please
Question: I've been trying to do this for 3 hours. I have windows. I'm using [this
official guide](http://www.greenteapress.com/thinkpython/swampy/install.html):
So for step 2 for the windows installation for Python 2: it says: "To see if
you have Tkinter, launch python; then at the Python prompt, type
>>> import Tkinter
When I do this from the python shell, it says `ImportError: No module named
'Tkinter'`. But when I type in Python in the command prompt, and I type
`import Tkinter`, nothing happens. So which one do I look at? The instructions
aren't clear.
Okay so going on, step 2 "install Swampy" is what i'm having trouble with too.
To download pip, you have to go to [this link](http://www.pip-
installer.org/en/latest/installing.html). But when you get there, it says to
download off the link that says "get-pip.py." What in the world? It's just a
long wall of text. It doesn't even ask me if I want to download anything. How
are we supposed to download this???
Also the instructions say " If you still don't have pip, you can download the
Swampy zip file from the Cheese shop. Unzip it, then cd into the directory it
creates and run:
`python setup.py install`
What does `cd into the directory it creates and run...` mean??? I am so lost
and would be eternally grateful if someone helps. Thanks.
Answer: Right-click the [download
link](https://raw.github.com/pypa/pip/master/contrib/get-pip.py) and choose
"Save Link As" (Firefox) or "Save target as" (Internet Explorer). Open a
command prompt and run get-pip.py by entering the full path to python.exe and
get-pip.py. For example:
> `C:\Python27\python.exe "C:\Users\UserName\Downloads\get-pip.py"`
I recommend using the full path to python.exe in case it's either not on the
search `PATH` or the wrong version would be found. Double quotes are required
for a path that contains spaces. If the above command fails with an "Access
denied" error, retry the installation in a command prompt that has
administrator privileges enabled, i.e. right-click and choose "Run as
administrator".
Install Swampy from the same command prompt:
> `C:\Python27\python.exe -m pip install swampy`
`-m pip` runs the pip module as a script. There's also pip.exe in the Scripts
subdirectory.
Personally, I'd use [GnuWin32](http://getgnuwin32.sourceforge.net) wget.exe
(w/ Mozilla [certdata.txt](http://mxr.mozilla.org/mozilla-
release/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1)) to download
the install script and run it with the [py
launcher](https://bitbucket.org/vinay.sajip/pylauncher/raw/tip/Doc/launcher.rst):
> `wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py`
> `py -2.7 get-pip.py`
> `py -2.7 -m pip install swampy`
* * *
As to [`cd`](http://ss64.com/nt/cd.html), that's an internal command in the
cmd.exe shell (command prompt) that [c]hanges the current [d]irectory on a
drive (`chdir` is a synonym). If the new directory isn't an absolute path,
it's resolved relative to the current directory on the current drive, or the
drive specified in the command (e.g. `cd D:Downloads` changes the directory on
drive D: to the Downloads subdirectory of its current directory). The `/D`
switch makes `cd` change the current drive as well.
If the new directory is on the current drive (or `/D` was used), the `cd`
command also changes the current working directory of the shell process, which
will be inherited by an executed program. Otherwise it just sets one of the
cmd shell's hidden environment variables for the drive path*.
Entering just `cd` will print the current directory on the current drive.
Entering `cd D:` will print the current directory on drive D:.
I generally prefer [`pushd`](http://ss64.com/nt/pushd.html), since it always
changes the current drive; maps a temp drive for a UNC path; and enables
returning to the previous directory with `popd`. Entering just `pushd` will
print the stack of pushed directories.
For more information on the available commands, enter `help` in the command
prompt. Here's an [index of commands](http://ss64.com/nt). Commands that are
internal to the cmd shell are marked with a bullet (•).
* For example, `=C:`, `=D:`, and so on. A Windows process has only a single current working directory, so cmd.exe has to use this trick to emulate the DOS per-drive working directory. Due to a bug in cmd, you can see these 'hidden' environment variables by entering `set ""`.
|
Pie chart labels are overlapping for same values.
Question: Here I'm trying to create a pie chart using **matplotlib** python library. But
the dates are overlapping if the values are same "0.0" multiple times.
My question is how I can display them separately.
Thanks.

This is what I tried:
from pylab import *
labels = [ "05-02-2014", "23-02-2014","07-02-2014","08-02-2014"]
values = [0, 0, 2, 10]
fig = plt.figure(figsize=(9.0, 6.10))
plt.pie(values, labels=labels, autopct='%1.1f%%', shadow=True)
plt.axis('equal')
show()
Answer: You can adjust the label positions manually, although that results in a bit
more code you would want to for such a simple request. You can detect groups
of duplicate labels by examining the positions at which there are placed.
Here is an example with some random data replicating the occurrence of
overlapping labels:
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
import datetime
# number slices of pie
num = 10
# generate some labels
dates = [datetime.datetime(2014,1,1) + datetime.timedelta(days=np.random.randint(1,20)) for i in range(num)]
labels = [d.strftime('%d-%m-%Y') for d in dates]
# generate some values
values = np.random.randint(2,10, num)
# force half of them to be zero
mask = np.random.choice(num, num // 2, replace=False)
values[mask] = 0
# pick some colors
colors = plt.cm.Blues(np.linspace(0,1,num))
fig, ax = plt.subplots(figsize=(9.0, 6.10), subplot_kw={'aspect': 1})
wedges, labels, pcts = ax.pie(values, colors=colors, labels=labels, autopct='%1.1f%%')
# find duplicate labels and the amount of duplicates
c = Counter([l.get_position() for l in labels])
dups = {key: val for key, val in c.items() if val > 1}
# degrees of spacing between duplicate labels
offset = np.deg2rad(3.)
# loop over any duplicate 'position'
for pos, n in dups.items():
# select all labels with that position
dup_labels = [l for l in labels if l.get_position() == pos]
# calculate the angle with respect to the center of the pie
theta = np.arctan2(pos[1], pos[0])
# get the offsets
offsets = np.linspace(-(n-1) * offset, (n-1) * offset, n)
# loop over the duplicate labels
for l, off in zip(dup_labels, offsets):
lbl_radius = 1.3
# calculate the new label positions
newx = lbl_radius * np.cos(theta + off)
newy = lbl_radius * np.sin(theta + off)
l.set_position((newx, newy))
# rotate the label
rot = np.rad2deg(theta + off)
# adjust the rotation so its
# never upside-down
if rot > 90:
rot += 180
elif rot < -90:
rot += 180
# rotate and highlight the adjusted labels
l.set_rotation(rot)
l.set_ha('center')
l.set_color('#aa0000')
I purposely only modified the overlapping labels to highlight the effect, but
you could alter all labels in a similar way to create a uniform styling. The
rotation makes it easier to automatically space them, but you could try
alternate ways of placement.
Note that it only detect truly equal placements, if you would have values of
`[0, 0.00001, 2, 10]`, they would probably still overlap.

|
when I initiate second button click -> AttributeError: Application instance has no attribute 'readfile'
Question:
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid() #put it on the grid
self.create_widgets()
#widget
def create_widgets(self):
self.button1 = Button(self)
self.button1.grid(row = 3, column = 5, columnspan = 2, stick = E)
self.button1["text"] = "Browse"
self.button1["command"] = self.update_count
self.pack()
#here
self.text1 = Text(self)
self.text1 = Text(self, width = 41, height = 1, wrap = WORD)
self.text1.grid(row = 3, column = 1, columnspan = 2, stick = W)
# here
self.button2 = Button(self)
self.button2.grid(row = 5, column = 5, columnspan = 2, stick = E)
self.pack()
self.button2["text"] = "OK"
self.button2["command"] = self.readfile
# select list box
self.listbox1 = Listbox(self, selectmode = EXTENDED)
self.listbox1 = Listbox(self, width = 51, height = 5)
self.listbox1.grid(row = 5, column = 1, columnspan = 2, stick = W)
self.label1 = Label(self)
self.label1.grid(row = 1, column = 1, columnspan = 2, sticky = W)
self.label1["text"] = "Choose the data log file folder ..."
self.label2 = Label(self)
self.label2.grid(row = 4, column = 1, columnspan = 2, sticky = W)
self.label2["text"] = "Choose the data log file ..."
#on click
def update_count(self):
path_string = tkFileDialog.askdirectory()
self.text1.delete(0.0, END)
self.text1.insert(0.0, path_string)
# read files
onlyfiles = [ f for f in listdir(path_string) if isfile(join(path_string,f)) ]
with open("output.txt", "w") as a:
for path, subdirs, files in os.walk(path_string):
for filename in files:
ffnames = os.path.join(filename)
self.listbox1.insert(END, ffnames)
a.write(str(ffnames) + os.linesep)
#on click
def readfile(self):
global listEx
items = map(int, listbox1.curselection())
result = listEx[items[0]]
print result
# main loop
root = Tk()
root.title("Test Window")
root.geometry("900x700")
app = Application(root)
root.mainloop() #main loop
Thanks in advance,
Can anyone help me to fix this error, I have got two button, first button
works, now I need to read a file name from the listbox so have declared a
constructor to do the work, eventually I got an AttributeError, don't know
why?
I am new to Python, as a beginner struggling to fix, please help me.
Ramas
Answer: The error is telling you exactly the problem -- your class has no method named
`readfile`. It looks like you have indented the method incorrectly, causing it
to be private to the `update_count` method. The solution is to remove one
level of indentation to the function definition, so that it is in the proper
scope.
|
python struct pack speed up inside function
Question: I'm testing python's struct pack/unpack performance and notice it'll speed up
if put inside a function:
import time
import struct
from io import BytesIO
def pack(b):
for i in range(10000000):
b.write(struct.pack('!i', i))
b = BytesIO()
start = time.time()
pack(b)
end = time.time()
print(end - start)
b2 = BytesIO()
start = time.time()
for i in range(10000000):
b2.write(struct.pack('!i', i))
end = time.time()
print(end - start)
Running this gives
2.639040946960449
3.0683419704437256
The codes are the same, while the function is faster.
Why is this?
Answer: A loop inside a function is faster than the same loop at the global level:
from timeit import default_timer as timer
N = 10000000
def f():
for i in range(N):
pass
start = timer()
for i in range(N):
pass
print("global %.2f" % (timer() - start,))
start = timer()
f()
print("function %.2f" % (timer() - start,))
Output:
global 0.71
function 0.40
It may be explained by the difference in the speed of global vs. local
namespace access in CPython.
|
import from views.py does not work from app
Question: I'm working with django and I'm trying to get a simple app functional.
The app is supposed to deliver a simple 'Hello world'-view but my_app/urls.py
fails to import methods from my_app/views.py.
my app is named SocialUrl
Here is my-project/urls.py.
from django.conf.urls import patterns, include, url
# from SocialUrl.views import test
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^/su/', include('SocialUrl.urls')),
# url(r'^$', test),
)
Here is my-app/urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^test$', views.test()),
)
Here is my-app/views.py
from django.shortcuts import render
from django.template import RequestContext
def test(request):
return render(request, 'test.html', RequestContext(request, {}))
Note that the testlines in my-project/urls.py works correctly.
My folder structure looks like this: my-project my-project my-app
I've added this in my-project/settings.py
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/'),
os.path.join(BASE_DIR, 'SocialUrl', 'templates').replace('\\', '/'),
)
I get the following error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.6.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'SocialUrl')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\core\handlers\base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\core\urlresolvers.py" in resolve
318. for pattern in self.url_patterns:
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\core\urlresolvers.py" in url_patterns
346. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\core\urlresolvers.py" in urlconf_module
341. self._urlconf_module = import_module(self.urlconf_name)
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\utils\importlib.py" in import_module
40. __import__(name)
File "C:\Users\Sverker\Dropbox\Coomba\SbrgCoomba\SbrgCoomba\urls.py" in <module>
13. url(r'^/su/', include('SocialUrl.urls')),
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\conf\urls\__init__.py" in include
26. urlconf_module = import_module(urlconf_module)
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site-packages\django\utils\importlib.py" in import_module
40. __import__(name)
File "C:\Users\Sverker\Dropbox\Coomba\SbrgCoomba\SocialUrl\urls.py" in <module>
7. url(r'^$', test),
Exception Type: NameError at /
Exception Value: name 'test' is not defined
I have tried various combinations of the 'from . import views'-line in my-
app/urls.py eg. 'from views import test'
Edit:
still disfunctional my-app/urls.py
from django.conf.urls import patterns, url
from views import test
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', test),
)
Answer: The problem is that you really have this line in your app `urls.py`:
url(r'^$', test)
The error says that `test` is not defined. Just define (import) it:
from views import test
|
Python mechanize saying existing control does not exist
Question: I am trying to scrape a password protected website in python. My code is as
follows:
import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Chrome')]
br.open('https://monitor1.returnpath.net/login.php')
for f in br.forms():
print f
br.select_form(nr=1)
br.form['email'] = 'email'
br.form['password'] = 'password'
The for loop returns this:
>
> <form1 POST https://monitor1.returnpath.net/login.php application/x-www-
> form-urlencoded
> <TextControl(email=)>
> <PasswordControl(password=)>
> <CheckboxControl(remember=[1])>
> <SubmitControl(Submit=Sign In) (readonly)>>
> <GET http://now.eloqua.com/e/f2.aspx application/x-www-form-urlencoded
> <TextControl(e=)>
> <HiddenControl(lang=NA) (readonly)>
> <HiddenControl(elqSiteID=841) (readonly)>
> <HiddenControl(elqFormName=nLRegFooter-1347904420246) (readonly)>
> <SubmitControl(<None>=Sign Me Up) (readonly)>
> <SubmitButtonControl(<None>=) (readonly)>>
> <POST https://monitor1.returnpath.net/send_feedback.php
> application/x-www-form-urlencoded
> <HiddenControl(size=) (readonly)>
> <HiddenControl(nps=) (readonly)>
> <TextareaControl(desc=)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>
> <IgnoreControl(<None>=<None>)>>
>
And this error:
> mechanize._form.ControlNotFoundError: no control matching name 'email'
The output states that 'email' is found so I'm not sure why it says there is
no control matching it?
Answer: Its zero-indexed. try the code below:
br.select_form(nr=0)
|
check if a number ends up with either XX,5 or is an integer in python
Question: I can solve it using multiple ifs and right function... but was wondering if
there were a nicer solution...
as an example
10,5 would return true
10 would return true
9,3 would return false
9,5 would return true
Any ideas?
Answer: Use regex:
import re
def int_or_comma_5(n):
return re.match('\d+(,5)?$',n)
|
How do you iterate through a gzipped carriage-return file using python 2.7?
Question: I have to use python 2.7 because I'm using the boto library and boto3 is
experimental. I need to read a file that is gzipped and lines are terminated
by carriage returns. Using [python
3.3](https://docs.python.org/3.3/library/gzip.html#gzip.open) It seems you can
just specify the newline variable in gzip.open. What would be the cleanest and
still efficient way to do this in python 2.7.
Answer: You could try `io` module to read the gzipped file as text line by line with
universal newlines support:
import gzip
import io
with io.TextIOWrapper(io.BufferedReader(gzip.open(filename))) as file:
for line in file:
print line,
|
Trying to parse JSON data with python
Question: I am having no luck trying to parse this json data, i only care about a small
amount of it.
json data
{
"timestamp" : 1397555135361,
"sets" : {
"worldguard.markerset" : {
"areas" : {
"world_region_name" : {
"markup" : false,
"desc" : "What I really want.",
"weight" : 3,
"color" : "#FF0000",
"fillopacity" : 0.35,
"opacity" : 0.8,
"label" : "Region_name",
"ytop" : 65.0,
"fillcolor" : "#FF0000",
"z" : [846.0, 847.0, 847.0, 846.0],
"ybottom" : 65.0,
"x" : [773.0, 773.0, 774.0, 774.0]
}
}
}
}
}
I hope I copied it correctly, it a very large file, and I only care about the
region info that it has.
there are other parts of this json file, that I don't care about, so I haven't
included them. but there are many items under 'areas' that I do care about. I
just cant work out how to parse them all
import json
from pprint import pprint
json_data=open('marker_world.json')
data = json.load(json_data)
for item in data["sets"]["worldguard.markerset"]["areas"]:
print item
the items that i care about from each region is; desc, label, z, & x .
It doesn't seem to print out the everything under that region like I would
expect all I get is a screen of "u'w'"
I haven't even started to try and select only the bits out of each region I
care about. A push in the right direction would be great if you can workout
what I am doing wrong.
Answer: Here's what you can start with.
Define a list of keys you need from an area, then iterate over `areas`, for
each area get the values of the keys you've defined:
keys = ['desc', 'label', 'x', 'z']
for area_key, area_items in data["sets"]["worldguard.markerset"]["areas"].iteritems():
print area_key
for key in keys:
print '%s: %s' % (key, area_items[key])
prints:
world_region_name
desc: What I really want.
label: Region_name
x: [773.0, 773.0, 774.0, 774.0]
z: [846.0, 847.0, 847.0, 846.0]
|
Opening/reading a list of unknown files using I/O methods
Question: So I'm a newb :) Python question
I have a list of files and I'm looking to open/read these files using an I/O
method
I understand if I explicitly go through each test file I've created and
opening them one by one would be fine but how about if I have an unknown file
and I tell it to be open/read, how would this be done?
Logically thinking, it sounds like I need to create a variable and assign it
to a list of files and from there tell it open all the files in the list. So a
for loop perhaps?
Answer: You can do it as follows:
import os
for fl in os.listdir(os.getcwd()):
with open(fl) as f:
#do stuff
Alternatively, if your files are not in the same directory as your script, you
can do:
for fl in os.listdir('custom/path/to/files'):
|
matplotlib says it needs libpng15, but I have libpng16
Question: The problem is likely a configuration issue, because getting the installation
correct on Macs seems to be tricky. I'm running Mavericks and matplotlib
1.4.x, yet when I open a Python 2.7.5 shell and `import pylib`, I get this
error:
>>> import pylab
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/pylab.py", line 230, in <module>
import matplotlib.finance
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/finance.py", line 38, in <module>
from matplotlib.collections import LineCollection, PolyCollection
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/collections.py", line 27, in <module>
import matplotlib.backend_bases as backend_bases
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/backend_bases.py", line 55, in <module>
import matplotlib.textpath as textpath
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/textpath.py", line 22, in <module>
from matplotlib.mathtext import MathTextParser
File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/mathtext.py", line 64, in <module>
import matplotlib._png as _png
ImportError: dlopen(/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/_png.so, 2): Library not loaded: /usr/local/lib/libpng15.15.dylib
Referenced from: /Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/_png.so
Reason: image not found
I have `libpng16` installed, but not `libpng15`.
Answer: I saw a hardcoded reference to libpng15 in _png.so.
Uninstall and install of matplotlib fixed the issue for me.
|
Data extraction and transform efficiency
Question: I've got a Python script that connects to a MySQL database and executes a
number of nested SELECT queries. It's basically a giant for loop. The database
is structured such that Businesses have Menus, Menus have Sections, and
Sections have Items. The script queries all the Businesses, and for each
Business, it queries all of its Menus, and so on. It builds a big dictionary
along the way that it then spits out as JSON.
It looks something like this:
#!/usr/bin/env python
from bottle import route, run
import mysql.connector
import json
import collections
import datetime
def getBusinesses():
conn = mysql.connector.connect(user="APIUser", password="abc123", host="12.34.56.78", port="54321", database="businesses")
cursor = conn.cursor()
objects = {}
businessesQuery = ("SELECT * FROM business")
cursor.execute(businessesQuery)
businessRows = cursor.fetchall()
businessObjects = []
for businessRow in businessRows:
print businessRow[0]
businessDict = collections.OrderedDict()
businessDict['id'] = businessRow[0]
businessDict['business_name'] = businessRow[1]
businessDict['business_address1'] = businessRow[2]
businessDict['business_address2'] = businessRow[3]
businessDict['business_city'] = businessRow[4]
businessDict['business_state'] = businessRow[5]
businessDict['business_zip'] = businessRow[6]
businessObjects.append(businessDict)
menuQuery = ("SELECT * FROM menu WHERE business_id = %s" % businessRow[0])
cursor.execute(menuQuery)
menuRows = cursor.fetchall()
menuObjects = []
for menuRow in menuRows:
menuDict = collections.OrderedDict()
menuDict['id'] = menuRow[0]
menuDict['menu_name'] = menuRow[1]
menuDict['menu_description'] = menuRow[2]
menuDict['menu_note'] = menuRow[3]
menuDict['business_id'] = menuRow[4]
menuObjects.append(menuDict)
businessDict['menus'] = menuObjects
for menuIdx, menuRow in enumerate(menuRows):
sectionQuery = ("SELECT * FROM menu_section WHERE menu_id = %s" % menuRow[0])
cursor.execute(sectionQuery)
sectionRows = cursor.fetchall()
sectionObjects = []
for sectionIdx, sectionRow in enumerate(sectionRows):
sectionDict = collections.OrderedDict()
sectionDict['id'] = sectionRow[0]
sectionDict['section_name'] = sectionRow[1]
sectionDict['section_note'] = sectionRow[2]
sectionDict['section_description'] = sectionRow[3]
sectionDict['menu_id'] = sectionRow[4]
sectionObjects.append(sectionDict)
businessDict['menus'][menuIdx]['sections'] = sectionObjects
itemQuery = ("SELECT * FROM menu_item WHERE section_id = %s" % sectionRow[0])
cursor.execute(itemQuery)
itemRows = cursor.fetchall()
itemObjects = []
for itemIdx, itemRow in enumerate(itemRows):
itemDict = collections.OrderedDict()
itemDict['id'] = itemRow[0]
itemDict['item_name'] = itemRow[1]
itemDict['item_description'] = itemRow[2]
itemDict['item_note'] = itemRow[3]
itemDict['item_price'] = itemRow[4]
itemDict['section_id'] = itemRow[5]
itemObjects.append(itemDict)
businessDict['menus'][menuIdx]['sections'][sectionIdx]['items'] = itemObjects
objects['businesses'] = businessObjects
return objects
@route('/test')
def index():
return json.dumps(getBusinesses())
run(host='192.168.1.70', port=7070)
I want to know if this is an efficient way of doing things. When I deployed my
database remotely (WebFaction) and ran the Bottle server locally, it took
almost 40 seconds to return a few hundred rows. So it seems like something is
amiss. I have a gut feeling that there could be a better way of doing this.
Just not sure what that way is!
Answer: if I had to venture a guess: notice the rough structure of your code is:
def getBusinesses():
businessesQuery = ("SELECT * FROM business")
businessRows = cursor.fetchall()
businessObjects = []
for businessRow in businessRows:
menuQuery = ("SELECT * FROM menu WHERE business_id = %s" % businessRow[0])
menuRows = cursor.fetchall()
for menuIdx, menuRow in enumerate(menuRows):
sectionQuery = ("SELECT * FROM menu_section WHERE menu_id = %s" % menuRow[0])
cursor.execute(sectionQuery)
sectionRows = cursor.fetchall()
sectionObjects = []
for sectionIdx, sectionRow in enumerate(sectionRows):
itemQuery = ("SELECT * FROM menu_item WHERE section_id = %s" % sectionRow[0])
itemRows = cursor.fetchall()
That is, you execute nearly identical queries in a loop for `menu`,
`menu_section` and especially `menu_item`. Also, you're using `fetchall()` to
return the full contents of the result set but examine each element only once,
in a loop, where you create _another_ list of objects.
what you might want instead is something more like:
businesses = []
cursor.execute("select * from business")
row = cursor.fetchone()
while row is not None:
business.append(...(row))
row = cursor.fetchone()
cursor.execute("select * from menu")
row = cursor.fetchone()
while row is not None:
business[row['business_id']].menus.append(...(row))
row = cursor.fetchone()
cursor.execute("select menu.business_id, menu_section.*"
" from menu_section"
" join menu on menu.id = menu_section.menu_id")
row = cursor.fetchone()
while row is not None:
business[row['business_id']][row['menu_id']].sections.append(...(row))
row = cursor.fetchone()
cursor.execute("select menu.business_id, menu_section.menu_id, menu_item.*"
" from menu_item"
" join menu_section on menu_section.id = menu_item.section_id"
" join menu on menu.id = menu_section.menu_id")
row = cursor.fetchone()
while row is not None:
business[row['business_id']][row['menu_id']][row['section_id'].items.append(...(row))
row = cursor.fetchone()
so that you're issuing a much smaller number of queries, and only loading the
amount of data you can process in one go.
|
Add meta tag using BeautifulSoup
Question: How to add a meta tag just after title tag in a HTML page by using Beautiful
Soup(library). I am using python language for coding and unable to do this.
Answer: Use `soup.create_tag()` to create a new `<meta>` tag, set attributes on that
and add it to your document `<head>`.
metatag = soup.new_tag('meta')
metatag.attrs['http-equiv'] = 'Content-Type'
metatag.attrs['content'] = 'text/html'
soup.head.append(metatag)
Demo:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <html><head><title>Hello World!</title>
... </head><body>Foo bar</body></html>
... ''')
>>> metatag = soup.new_tag('meta')
>>> metatag.attrs['http-equiv'] = 'Content-Type'
>>> metatag.attrs['content'] = 'text/html'
>>> soup.head.append(metatag)
>>> print soup.prettify()
<html>
<head>
<title>
Hello World!
</title>
<meta content="text/html" http-equiv="Content-Type"/>
</head>
<body>
Foo bar
</body>
</html>
|
Solve seemingly (but not actually!) overdetermined sparse linear system in Python
Question: I have a sparse matrix A (using scipy.sparse) and a vector b, and want to
solve Ax = b for x. A has more rows than columns, so it appears to be
overdetermined; however, the rows of A are linearly dependent, so that in
actuality the row rank of A is equal to the number of columns. For example, A
could be
A = np.array([[1., 1.], [-1., -1.], [1., 0.]])
while b is
b = np.array([0., 0., 1.])
The solution is then x = [1., -1.]. I'm wondering how to solve this system in
Python, using the functions available in scipy.sparse.linalg. Thanks!
Answer: Is your system possibly _underdetermined_? If it is not, and there is actually
a solution, then the least squares solution will be that solution, so you can
try
from scipy.sparse.linalg import lsqr
return_values = lsqr(A, b)
x = return_values[0]
If your system is actually underdetermined, this should find you the minimum
L2 norm solution. If it doesn't work, set the parameter `damp` to something
very small (e.g. `1e-5`).
If your system is _exactly_ determined (i.e. `A` is of full rank) and has a
solution, and your matrix `A` is tall, as you describe it, then you can find
an equivalent system in the normal equations:
A.T.dot(A).dot(x) == A.T.dot(b)
has a unique solution in `x`. This is a square linear system and is thus
solvable using linear system solvers such as `scipy.sparse.linalg.spsolve`
|
Measuring runtime of CUDA through an script in python
Question: I am trying to use some profiling tools on CUDA with so many different inputs
to see the the differences among different inputs. For this purpose I wrote a
python script to compile the code on CUDA, run the profiler with different
inputs and write the results into a CSV file. Some of these runs take so much
time ( about 3 days ! ) and I want to kill that specific run if it takes more
than a threshold ( for example 30 minutes ) but I do no know how to do it.
Here is a part of python script that I wrote :
import subprocess ,sys, string, os
{START TIME}
p = subprocess.Popen([CUDA PROFILER COMMAND], stdout=subprocess.PIPE)
s, err = p.communicate()
{END TIME}
I want to measure START TIME and END TIME and kill this run if it takes more
than 30 minutes. The script would run line by line and if the CUDA PROFILER
command takes more than 30 minutes, it never gets to {END TIME} line and I
cannot measure the elapsed time of the CUDA PROFILER command. Any suggestion
would be so much appreciated.
Answer: There are many answers in [subprocess with
timeout](http://stackoverflow.com/q/1191374/4279) question that you've linked
in the comments. I've chosen a couple that are both simple and portable. [In
Python 3.3+](http://stackoverflow.com/a/12698328/4279):
from subprocess import check_output
s = check_output(['cuda', 'profiler', 'command'], timeout=30*60)
[On older versions](http://stackoverflow.com/a/10012262/4279):
from subprocess import Popen, PIPE
from threading import Timer
p = Popen(['cuda', 'profiler', 'command'], stdout=PIPE)
t = Timer(30*60, p.kill) # kill process in 30 minutes
t.start()
s = p.communicate()[0]
t.cancel() # cancel the hit
|
Python constants
Question: I am in the middle of a development in Django and we got some doubts about if
we should use or not constants in the project. Exactly the situation is to use
constants everywhere or not (we know constants in Django are not really read-
only).
There are 2 scenarios and I would like to get your opinion about which one is
better for you and why:
# Scenario 1 (using constants)
## constants.py
class CONST():
def NAME(): return "name"
def SURNAME(): return "surname"
def ZIPCODE(): return "zipcode"
def CITY(): return "city"
def CREATED(): return "created"
## admin.py
from constants import CONST
class RegisterAdmin(admin.ModelAdmin):
list_display = (CONST.NAME(),CONST.SURNAME(),CONS.ZIPCODE())
list_filter = [CONST.ZIPCODE(),CONST.CITY()]
search_fields = [CONST.NAME(), CONST.SURNAME()]
date_hierarchy = CONST.CREATED()
## models.py
from constants import CONST
class Register(models.Model):
name = models.CharField(CONST.NAME(), max_length=25)
surname = models.CharField(CONST.SURNAME(), max_length=25)
zipcode = models.IntegerField(CONST.ZIPCODE())
city = models.CharField(CONST.CITY(),max_length=20)
_... and any view etc where you use text will be using contants ..._
# Scenario 2 (without constants)
## admin.py
class RegisterAdmin(admin.ModelAdmin):
list_display = ("name","surname","zipcode")
list_filter = ["zipcode","city"]
search_fields = ["name","surname"]
## models.py
class Register(models.Model):
name = models.CharField("name", max_length=25)
surname = models.CharField("surname", max_length=25)
zipcode = models.IntegerField("zipcode")
city = models.CharField("city",max_length=20)
I like the most the second scenario (I have been programming python from
2004), for me it looks more efficient, clear and easy to understand. The first
scenario (proposed from Java/PHP programmers that now writes Python code) has
the advantage that it helps the developer to detect that it made a mistake
writing the "constant" so it is easier to detect errors and also it makes
easier and quicker "massive changes" on this kind of texts without
refactorizing the source code.
I would like to know which source code you would write or use and why.
Thank you,
Answer: Scenario 1 is awful. Unfortunately I know all too well the problems of working
with Java/PHP developers who are learning python.
Perhaps you can compromise with those guys by proposing the use of [python
enums](http://legacy.python.org/dev/peps/pep-0435/) to address their concern.
These are built-in in python 3.4+, and have been
[backported](https://pypi.python.org/pypi/enum34) as far back as 2.4.
from enum import Enum
class Constant(Enum):
name = "name"
surname = "surname"
zipcode = "zipcode"
city = "city"
created = "created"
Now you can change the "values", say for example changing zipcode to be
"potato" in the enum definition, whilst still using the name
`Constant.zipcode.value` everywhere else in source code.
|
Pandas DataFrame stored list as string: How to convert back to list?
Question: I have an _n_ -by-_m_ Pandas DataFrame `df` defined as follows. (I know this
is not the best way to do it. It makes sense for what I'm trying to do in my
actual code, but that would be TMI for this post so just take my word that
this approach works in my particular scenario.)
>>> df = DataFrame(columns=['col1'])
>>> df.append(Series([None]), ignore_index=True)
>>> df
Empty DataFrame
Columns: [col1]
Index: []
I stored lists in the cells of this DataFrame as follows.
>>> df['column1'][0] = [1.23, 2.34]
>>> df
col1
0 [1, 2]
For some reason, the DataFrame stored this list as a string instead of a list.
>>> df['column1'][0]
'[1.23, 2.34]'
I have 2 questions for you.
1. **Why does the DataFrame store a list as a string and is there a way around this behavior?**
2. **If not, then is there a Pythonic way to convert this string into a list?**
* * *
**Update**
The DataFrame I was using had been saved and loaded from a CSV format. _This
format, rather than the DataFrame itself, converted the list from a string to
a literal._
Answer: As you pointed out, this can commonly happen when saving and loading pandas
DataFrames as `.csv` files, which is a text format.
In your case this happened because list objects have a string representation,
allowing them to be stored as `.csv` files. Loading the `.csv` will then yield
that string representation.
If you want to store the actual objects, you should you use
`DataFrame.to_pickle()` (note: objects must be picklable!).
To answer your second question, you can convert it back with
[`ast.literal_eval`](https://docs.python.org/3.4/library/ast.html#ast.literal_eval):
>>> from ast import literal_eval
>>> literal_eval('[1.23, 2.34]')
[1.23, 2.34]
|
Single mouse click within While loop (PsychoPy)
Question: I am using PsychoPy and I would like to print the position of my mouse when it
has been clicked.
The actual printing of the position needs to be placed inside a while loop.
Using the code below, when I click I get more than one output lines, which
print the same positions. I would like to have only one output printing for
each click.
This is the code I am using:
#!/usr/bin/env python2
from psychopy import visual, core, event
from pyglet.gl import *
width = 600
height = 600
myWin = visual.Window([width,height], color='white',units='pix',monitor='testMonitor')
#This will set the windows units (pixels) to GL units
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_BLEND)
glBlendFunc(GL_ZERO, GL_SRC_COLOR)
myMouse = event.Mouse() # will use myWin by default
while True:
#Triangle left
glColor3f(1.0, 0.0, 0.0)
glBegin(GL_TRIANGLES)
glVertex3f(150, 550, 1)
glVertex3f(50, 350, 1)
glVertex3f(250, 350, -1)
glEnd()
if myMouse.getPressed()[0]:
myMouse.clickReset()
print myMouse.getPos()
myWin.flip()
core.quit()
Is there something wrong I am doing? Should the 'frame rate' of the while loop
be changed?
Answer: ~~I've not used the module, but it seems like mouse events are thrown for
mouse _raises_ as well.~~
You'll need to
* Store the mouse state for next time
* Each iteration, test whether the mouse state for button 0 has gone up → down
The mouse state is returned by `myMouse.getPressed`.
So something like:
oldMouseIsDown = False
while True:
...
mouseIsDown = myMouse.getPressed()[0]
myMouse.clickReset()
if mouseIsDown and not oldMouseIsDown:
print myMouse.getPos()
oldMouseIsDown = mouseIsDown
|
Adding a timestamp to a file, python subprocess linux
Question: I’m trying to take a picture with my `Raspicam` on my raspberry and adding a
`timestamp` too each picture. The code that I use doesn’t however work. It
gives me a syntax error at `.."+%H...` I have mucked around in the code and
was able too do it once, then tough the picture file didn’t receive any
`timestamp` on it.
Does any one have any clue what im doing wrong?
#!/usr/bin/python
import RPi.GPIO as GPIO, time, os, subprocess, random
gpout = subprocess.check_output("stamp=$(date "+%H%M%S")", stderr=subprocess.STDOUT,shell=True)
gpout = subprocess.check_output("raspistill -t 1 --output /home/pi/photobooth_images/Test${stamp}.jpg", stderr=subprocess.STDOUT, shell=True)
Answer: There are at least two issues:
* to use double quotes inside a Python string literal, you should escape them or use single quotes for the string literal:
'stamp=$(date "+%H%M%S")'
* it is pointless to set `stamp` shell variable because `check_output()` call spawns its own shell i.e., `stamp` won't be defined in the second command where you are trying to use it
You could emulate `date "+%H%M%S"` in Python:
import time
from subprocess import check_output, STDOUT
timestamp = time.strftime('%H%M%S')
path = '/home/pi/photobooth_images/Test{stamp}.jpg'.format(stamp=timestamp)
gpout = check_output(["raspistill", "-t", "1", "--output", path], stderr=STDOUT)
Note: `shell=True` is not used.
You could also format an existing datetime object:
from datetime import datetime
path = '/path/to/Test{now:%H%M%S}.jpg'.format(now=datetime.now())
|
Start daemon process within BaseHTTPServer
Question: In order to allow helpdesk to restart an Oracle Instance, we are trying to
implement a small python webserver that would start a shell script that starts
the Oracle instance.
The code is done and it starts the instance but there is a problem: the
instance is connected to the webserver, so the buffer to the browser is not
closed until the instance has been stopped, and there is a `ora_pmon_INSTANCE`
process listening on the webserver port.
I tried to launch the script with:
process = os.system("/home/oracle/scripts/webservice/prueba.sh TFINAN")
and
process = subprocess.Popen(["/home/oracle/scripts/webservice/prueba.sh", "TFINAN"], shell=False, stdout=subprocess.PIPE)`
but it happens the same.
I also tried to launch a script with daemon (using daemon function from
redhat's init scripts). The script starts the Oracle instance with the same
result.
This is my code:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
import argparse, urlparse
import re
import cgi, sys, time
import os, subprocess
class HTTPRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(403)
self.send_header('Content-Type', 'text/html')
self.end_headers()
return
def do_GET(self):
ko = False
respuesta = ""
params = {}
myProc = -1
parsed_path = urlparse.urlparse(self.path)
try:
params = dict([p.split('=') for p in parsed_path[4].split('&')])
except:
params = {}
elif None != re.search('/prueba/*', self.path):
self.send_response(200)
respuesta = "Hola Mundo! -->" + str( params['database'] )
elif None != re.search('/startup/*', self.path):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
cmd = """ <html>
<body><H2> Iniciando instancia oracle: """ + str( params["database"]) + '. Espere un momento, por favor ...</H2>'
self.wfile.write(cmd)
#process = os.system("/home/oracle/scripts/webservice/prueba.sh INSTANCE")
process = subprocess.Popen(["/home/oracle/scripts/webservice/prueba.sh", "INSTANCE"], shell=False, stdout=subprocess.PIPE)
# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode
if errcode == 0:
self.wfile.write("""<H1> Instancia iniciada correctamente
</H1>
</body> </html>""")
self.wfile.close()
else:
respuestaok = "Error inicializando la instancia: " + str( params['database']) + " Intentelo de nuevo pasados unos minutos y si vuelve a fallar escale la incidencia al siguiente nivel de soporte"
else:
self.send_response(403, 'Bad Request: pagina no existe')
respuesta = "Solicitud no autorizada"
if respuesta != "":
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(respuesta)
self.wfile.close()
if ko:
server.stop()
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
allow_reuse_address = True
def shutdown(self):
self.socket.close()
sys.exit(0)
class SimpleHttpServer(object):
def __init__(self, ip, port):
self.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler)
def start(self):
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
self.server_thread.start()
def waitForThread(self):
self.server_thread.join()
def stop(self):
self.server.shutdown()
if __name__=='__main__':
parser = argparse.ArgumentParser(description='HTTP Server')
parser.add_argument('port', type=int, help='Listening port for HTTP Server')
parser.add_argument('ip', help='HTTP Server IP')
args = parser.parse_args()
server = SimpleHttpServer(args.ip, args.port)
print 'HTTP Server Running...........'
server.start()
server.waitForThread()
Can any of you help me?
Answer: Your problem is not related much to HTTP server. You seem to have general
problem to control Oracle daemon from Python code.
Try first writing a simple python script, which does what you need.
My guess is, that your attempts are having problems with reading output from
daemon control script.
See also
[Popen.communicate()](https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate)
for reading output from the command. Other option could be to call
subrocess.call()
There are many tutorials for calling system command from Python, e.g. [this
one](http://www.pythonforbeginners.com/os/subprocess-for-system-
administrators)
Apart of purely Python related problems you may run into problems with
permission - if your user, running the script/HTTP server is not allowed to
call oracle control script, you have another problem (which might have a
solution, on Linux adding that user into sudoers).
After you resolve problems with calling the script, it shall be easy to make
it working inside of your HTTP server.
|
How to identify a specific switch in Mininet when connected to a pox controller
Question: I have a custom topology running on Mininet and it has 2 switches s1, and s2.
I am using pox as the controller. I have written a python code to identify the
switches, is this the correct way to do it? Are there any other better methods
that i can use? could any body suggest other alternatives?
Code:
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.util import dpidToStr
log = core.getLogger()
s1_dpid=0
s2_dpid=0
def _handle_ConnectionUp (event):
global s1_dpid, s2_dpid
print "ConnectionUp: ",
dpidToStr(event.connection.dpid)
#remember the connection dpid for switch
for m in event.connection.features.ports:
if m.name == "s1-eth1":
s1_dpid = event.connection.dpid
print "s1_dpid=", s1_dpid
elif m.name == "s2-eth1":
s2_dpid = event.connection.dpid
print "s2_dpid=", s2_dpid
Answer: This link <http://squarey.me/cloud-virtualization/pox-controller-learning-
four.html> provides examples of POX component that listens to ConnectionUp
events from all switches and get the dpid
**1\. Use the component script "connectionDown.py" inside POX directory:**
#!/usr/bin/python
from pox.core import core
from pox.lib.util import dpid_to_str
from pox.lib.revent import *
log = core.getLogger()
class ConnectionUp(Event):
def __init__(self,connection,ofp):
Event.__init__(self)
self.connection = connection
self.dpid = connection.dpid
self.ofp = ofp
class ConnectionDown(Event):
def __init__(self,connection,ofp):
Event.__init__(self)
self.connection = connection
self.dpid = connection.dpid
class MyComponent(object):
def __init__(self):
core.openflow.addListeners(self)
def _handle_ConnectionUp(self,event):
ConnectionUp(event.connection,event.ofp)
log.info("Switch %s has come up.",dpid_to_str(event.dpid))
def _handle_ConnectionDown(self,event):
ConnectionDown(event.connection,event.dpid)
log.info("Switch %s has shutdown.",dpid_to_str(event.dpid))
def launch():
core.registerNew(MyComponent)
**2- (POX controller xterm) Start the POX controller with custom component**
mininet@mininet-vm:~/pox$ ./pox.py connectionDown
POX 0.1.0 (betta) / Copyright 2011-2013 James McCauley, et al.
INFO:core:POX 0.1.0 (betta) is up.
**3- (mininet xterm) start mininet topology with multiple switches**
mininet@mininet-vm:~$ sudo mn --topo linear --mac --controller remote --switch ovsk
*** Creating network
*** Adding controller
*** Adding hosts:
h1 h2
*** Adding switches:
s1 s2
*** Adding links:
(h1, s1) (h2, s2) (s1, s2)
*** Configuring hosts
h1 h2
*** Starting controller
*** Starting 2 switches
s1 s2
*** Starting CLI:
mininet>
**4- Back to POX controller xterm, here is what observe in POX xterm:**
./pox.py connectionDown
POX 0.1.0 (betta) / Copyright 2011-2013 James McCauley, et al.
INFO:core:POX 0.1.0 (betta) is up.
INFO:openflow.of_01:[00-00-00-00-00-02 2] connected
INFO:connectionDown:Switch 00-00-00-00-00-02 has come up.
INFO:openflow.of_01:[00-00-00-00-00-01 1] connected
INFO:connectionDown:Switch 00-00-00-00-00-01 has come up.
**5- S#POX should react to any changes to rhe switches:**
mininet> py s1.stop()
mininet> py s1.start([c0])
mininet>
**4- Back to POX controller xterm:**
mininet@mininet-vm:~/pox$ ./pox.py connectionDown
POX 0.1.0 (betta) / Copyright 2011-2013 James McCauley, et al.
INFO:core:POX 0.1.0 (betta) is up.
INFO:openflow.of_01:[00-00-00-00-00-02 2] connected
INFO:connectionDown:Switch 00-00-00-00-00-02 has come up.
INFO:openflow.of_01:[00-00-00-00-00-01 1] connected
INFO:connectionDown:Switch 00-00-00-00-00-01 has come up.
>
> INFO:openflow.of_01:[00-00-00-00-00-01 1] closed
> INFO:connectionDown:Switch 00-00-00-00-00-01 has shutdown.
> INFO:openflow.of_01:[00-00-00-00-00-01 3] connected
> INFO:connectionDown:Switch 00-00-00-00-00-01 has come up.
>
|
Algorithm to find the least difference between lists
Question: I have been trying to understand the algorithm used
[here](https://github.com/stefankoegl/python-json-
patch/blob/master/jsonpatch.py#L611) to compare two lists, implemented in this
[commit](https://github.com/stefankoegl/python-json-
patch/commit/cc7bda313ec4a8353f9e00d088fc4f64b9ff1ea9). The intention, as I
understood, is to find the least amount of changes to create `dst` from `src`.
These changes are later listed as sequence of `patch` commands. I am not a
python developer, and learned `generators` to understand the flow and how
recursion is done. but, now I can't make much sense out of the output
generated by the `_split_by_common_seq` method. I fed a few different lists,
and the output is shown below. Can you please help me to understand why the
output is like it is in these cases.
in the reference case,
src [0, 1, 2, 3]
dst [1, 2, 4, 5]
[[(0, 1), None], [(3, 4), (2, 4)]]
I cannot see how it is related to the the
[picture](https://github.com/stefankoegl/python-json-
patch/blob/master/jsonpatch.py#L579) in the doc. Why `(3,4)` and `(2,4)` on
the right? Is it a standard algorithm?
## test cases
src [1, 2, 3]
dst [1, 2, 3, 4, 5, 6, 7, 8]
[[None, None], [None, (3, 8)]]
src [1, 2, 3, 4, 5]
dst [1, 2, 3, 4, 5, 6, 7, 8]
[[None, None], [None, (5, 8)]]
src [4, 5]
dst [1, 2, 3, 4, 5, 6, 7, 8]
[[None, (0, 3)], [None, (5, 8)]]
src [0, 1, 2, 3]
dst [1, 2, 4, 5]
[[(0, 1), None], [(3, 4), (2, 4)]]
src [0, 1, 2, 3]
dst [1, 2, 3, 4, 5]
[[(0, 1), None], [None, (3, 5)]]
src [0, 1, 3]
dst [1, 2, 4, 5]
[[(0, 1), None], [(2, 3), (1, 4)]]
For future reference, here's the code (taken from the aforementioned
repository):
import itertools
def _longest_common_subseq(src, dst):
"""Returns pair of ranges of longest common subsequence for the `src`
and `dst` lists.
>>> src = [1, 2, 3, 4]
>>> dst = [0, 1, 2, 3, 5]
>>> # The longest common subsequence for these lists is [1, 2, 3]
... # which is located at (0, 3) index range for src list and (1, 4) for
... # dst one. Tuple of these ranges we should get back.
... assert ((0, 3), (1, 4)) == _longest_common_subseq(src, dst)
"""
lsrc, ldst = len(src), len(dst)
drange = list(range(ldst))
matrix = [[0] * ldst for _ in range(lsrc)]
z = 0 # length of the longest subsequence
range_src, range_dst = None, None
for i, j in itertools.product(range(lsrc), drange):
if src[i] == dst[j]:
if i == 0 or j == 0:
matrix[i][j] = 1
else:
matrix[i][j] = matrix[i-1][j-1] + 1
if matrix[i][j] > z:
z = matrix[i][j]
if matrix[i][j] == z:
range_src = (i-z+1, i+1)
range_dst = (j-z+1, j+1)
else:
matrix[i][j] = 0
return range_src, range_dst
def split_by_common_seq(src, dst, bx=(0, -1), by=(0, -1)):
"""Recursively splits the `dst` list onto two parts: left and right.
The left part contains differences on left from common subsequence,
same as the right part by for other side.
To easily understand the process let's take two lists: [0, 1, 2, 3] as
`src` and [1, 2, 4, 5] for `dst`. If we've tried to generate the binary tree
where nodes are common subsequence for both lists, leaves on the left
side are subsequence for `src` list and leaves on the right one for `dst`,
our tree would looks like::
[1, 2]
/ \
[0] []
/ \
[3] [4, 5]
This function generate the similar structure as flat tree, but without
nodes with common subsequences - since we're don't need them - only with
left and right leaves::
[]
/ \
[0] []
/ \
[3] [4, 5]
The `bx` is the absolute range for currently processed subsequence of
`src` list. The `by` means the same, but for the `dst` list.
"""
# Prevent useless comparisons in future
bx = bx if bx[0] != bx[1] else None
by = by if by[0] != by[1] else None
if not src:
return [None, by]
elif not dst:
return [bx, None]
# note that these ranges are relative for processed sublists
x, y = _longest_common_subseq(src, dst)
if x is None or y is None: # no more any common subsequence
return [bx, by]
return [split_by_common_seq(src[:x[0]], dst[:y[0]],
(bx[0], bx[0] + x[0]),
(by[0], by[0] + y[0])),
split_by_common_seq(src[x[1]:], dst[y[1]:],
(bx[0] + x[1], bx[0] + len(src)),
(bx[0] + y[1], bx[0] + len(dst)))]
Answer: It is a cute algorithm, but I don't think it's a "known" one. It's a clever
way of comparing lists, and probably not the first time that someone thought
of it, but I had never seen it before.
Basically, the output is telling you the ranges that look different in `src`
and `dst`.
The function always returns a list with 2 lists. The first list refers to the
elements in `src` and `dst` that are on the left side of the longest common
subsequence between `src` and `dst`; the second refers to the elements that
are on the right side of the longest common subsequence. Each of these lists
holds a pair of tuples. Tuples represent a range in the list - `(x, y)`
denotes the elements you would get if you performed `lst[x:y]`. From this pair
of tuples, the first tuple is the range from `src`, the second tuple is the
range from `dst`.
At each step, the algorithm computes the ranges of `src` and `dst` that are to
the left of the longest common subsequence and to the right of the longest
common subsequence between `src` and `dst`.
Let's look at your first example to clear things up:
src [0, 1, 2, 3]
dst [1, 2, 4, 5]
The longest common subsequence between `src` and `dst` is `[1, 2]`. In `src`,
the range `(0, 1)` defines the elements that are immediately to the left of
`[1, 2]`; in `dst`, that range is empty, because there is nothing before `[1,
2]`. So, the first list will be `[(0, 1), None]`.
To the right of `[1, 2]`, in `src`, we have the elements in the range `(3,
4)`, and in `dst` we have 4 and 5, which are represented by the range `(2,
4)`. So the second list will be `[(3, 4), (2, 4)]`.
And there you go:
[[(0, 1), None], [(3, 4), (2, 4)]]
**How does this relate to the tree in the comments?**
The leafs in the tree are using a different notation: instead of a tuple
describing a range, the actual elements on that range are shown. In fact,
`[0]` is the only element in the range `(0, 1)` in `src`. The same applies for
the rest.
Once you get this, the other examples you posted should be pretty easy to
follow. But note that the output can become more complex if there is more than
one common subsequence: the algorithm finds every common subsequences in
nonincreasing order; since each invocation returns a list with 2 elements,
this means that you will get nested lists in cases like these. Consider:
src = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
dst = [46, 1, 2, 3, 4, 5, 99, 98, 97, 5, 6, 7, 30, 31, 32, 11, 12, 956]
This outputs:
[[(0, 1), (0, 1)], [[[None, (6, 10)], [(8, 11), (12, 15)]], [(13, 14), (17, 18)]]]
The second list is nested because there was more than one recursion level
(your previous examples immediately fell on a base case).
The explanation shown before applies recursively to each list: the second list
in `[[(0, 1), (0, 1)], [[[None, (6, 10)], [(8, 11), (12, 15)]], [(13, 14),
(17, 18)]]]` shows the differences in the lists to the right of the longest
common subsequence.
The longest common subsequence is `[1, 2, 3, 4, 5]`. To the left of `[1, 2, 3,
4, 5]`, both lists are different in the first element (the ranges are equal
and easy to check).
Now, the procedure applies recursively. For the right side, there is a new
recursive call, and `src` and `dst` become:
src = [6, 7, 8, 9, 10, 11, 12, 13]
dst = [99, 98, 97, 5, 6, 7, 30, 31, 32, 11, 12, 956]
# LCS = [6, 7]; Call on the left
src = []
dst = [99, 98, 97, 5]
# LCS = [6, 7]; Call on the right
src = [8, 9, 10, 11, 12, 13]
dst = [30, 31, 32, 11, 12, 956]
# LCS = [11, 12]; Call on the left
src = [8, 9, 10]
dst = [30, 31, 32]
# LCS = [11, 12]; Call on the right
src = [13]
dst = [956]
The longest common subsequence is `[6, 7]`. Then you will have another
recursive call on the left, for `src = []` and `dst = [99, 98, 97, 5]`, now
there is no longest common subsequence and the recursion on this side stops
(just follow the picture).
Each nested list recursively represents the differences on the sub-list with
which the procedure was invoked, but note that the indices always refer to
positions in the original list (due to the way arguments for `bx` and `by` are
passed - note that they always accumulate since the beginning).
The key point here is that you will get nested lists linearly proportional to
the depth of the recursion, and in fact, you can actually tell how many common
subsequences exist in the original lists just by looking at the nesting level.
|
How to use MFDataset to read multiple files in OPeNDAP dataset with Python NetCDF4 module?
Question: I have an opendap thredds link to a directory holding many oceanographic model
output files from the Delaware Operational Forecast System (DBOFS). Historical
data are stored in separate hourly files and even some files spanning multiple
hours. I'd like to look at the files as if they were one long time series. I
came across another question asking something similar here: [Loop through
netcdf files and run calculations - Python or
R](http://stackoverflow.com/questions/18665078/loop-through-netcdf-files-and-
run-calculations-python-or-r)
Searching with a wildcard character returned the following error:
import netCDF4
f = netCDF4.MFDataset('http://opendap.co-ops.nos.noaa.gov/thredds/dodsC/NOAA/DBOFS/MODELS/201401/nos.dbofs.fields.n001.20140130.*.nc')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-a44e21cddbe9> in <module>()
----> 1 f = netCDF4.MFDataset('http://opendap.co-ops.nos.noaa.gov/thredds/dodsC/NOAA/DBOFS/MODELS/201401/nos.dbofs.fields.n001.20140130.*.nc')
C:\Users\cenglert\AppData\Local\Enthought\Canopy32\User\lib\site-packages\netCDF4.pyd in netCDF4.MFDataset.__init__ (netCDF4.c:6458)()
ValueError: cannot using file globbing for remote (OPeNDAP) datasets
Answer: Like the error says, you can't use globbing (using `*` for wildcard) on remote
datasets, but you _can_ build a python list of dataset URLs and pass them to
`MFDataset`. Like this:
import netCDF4
base = 'http://opendap.co-ops.nos.noaa.gov/thredds/dodsC/\
NOAA/DBOFS/MODELS/201401/nos.dbofs.fields.n001.20140130.t%2.2dz.nc'
files = [base % d for d in range(0,24,6)]
nc = netCDF4.MFDataset(files)
print nc.variables['salt']
which produces:
<class 'netCDF4._Variable'>
float64 salt('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
long_name: salinity
time: ocean_time
coordinates: lat_rho lon_rho
field: salinity, scalar, series
unlimited dimensions = ('ocean_time',)
current size = (4, 10, 732, 119)
and shows that in fact, the four values at 0,6,12, and 18 hours have been
virtually aggregated by `MFDataset`.
|
How do I properly construct an UPDATE statement that references an attached database table?
Question: this question pertains to Python3's sqlite3 module (DB-API 2.0 interface for
SQLite databases).
I am trying to update a sqlite3 database column where there are equivalent
values in an attached database table. I fail to understand why my sqlite
statement fails with the error message "no such column". I posted a minimal
example below. My goal is to update the "number" column in table_b for rows
where the "word" column matches the "string" column of table_a from the
attached database "db1".
Any help would be greatly appreciated. TIA for your time.
import sqlite3
conn = sqlite3.connect('db1.dat')
c = conn.cursor()
c.execute('''CREATE TABLE table_a (string TEXT)''')
c.execute('''INSERT INTO table_a VALUES ('Lorem')''')
c.execute('''INSERT INTO table_a VALUES ('ipsum')''')
c.execute('''INSERT INTO table_a VALUES ('dolor')''')
conn.commit()
c.close
conn = sqlite3.connect('db2.dat')
c = conn.cursor()
c.execute('''CREATE TABLE table_b (word TEXT, number INTEGER)''')
c.execute('''INSERT INTO table_b VALUES ('sit', 0)''')
c.execute('''INSERT INTO table_b VALUES ('amet', 0)''')
c.execute('''INSERT INTO table_b VALUES ('dolor', 0)''')
conn.commit()
c.execute('''ATTACH 'db1.dat' AS db1''')
c.execute('''UPDATE table_b SET number = 1 WHERE table_b.word = table_a.string''')
-----------------------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/home/newb/sandbox/<ipython-input-1-3659f61710d7> in <module>()
17 c.execute('''PRAGMA database_list''')
18 c.fetchall()
---> 19 c.execute('''UPDATE table_b SET number = 1 WHERE table_b.word = table_a.string''')
OperationalError: no such column: table_a.string
Answer: Nevermind, I figured it out. The update statement that I was looking for is:
c.execute('''UPDATE table_b SET number = 1 WHERE table_b.word IN (SELECT string FROM table_a)''')
I found guidance here:
<http://www.tutorialspoint.com/sqlite/sqlite_sub_queries.htm>
|
Python to Ruby: How do I open a file, parse the data and multithread with it?
Question: I need to translate this into Ruby:
ids = [i.strip() for i in open('ids.txt','r')]
proxies = [i.strip() for i in open('socks.txt','r')]
for (i,j) in izip(ids,proxies):
i = parseID(i)
j = j.split(':')
threading.Thread(target=raider,args=(i,j)).start()
This is just showing you what's happening with it:
def parseID(auser3):
auser3 = auser3.split('&')
userid = auser3[1].split('=')[1]
k1 = auser3[2].split('=')[1]
k2 = auser3[3].split('=')[1]
return [userid,k1,k2]
return l5
def raider(a3,p):
global ip
global port
try:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, p[0], int(p[1]))
socket.test = socks.socksocket
xat = socket.test(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP)
xat.connect((ip,int(port)))
xat.send('<y r="'+str(info[2])+'" />\0')
bypass = xat.recv(1024)
print "\nRecv --> "+bypass+"\n"
rcv = tree.fromstring(bypass.strip("\0"))
if 'i' not in rcv.attrib:
raise Exception("YUP")
import pprint
pprint.pprint(a3)
print p[0]+":"+p[1]+"\n\n"
uid = a3[0]
k = a3[1]
Y = getY(rcv.attrib["au"], rcv.attrib["p"].split("_")[0],rcv.attrib["p"].split("_")[1],rcv.attrib["p"].split("_")[2],rcv.attrib["p"].split("_")[3], rcv.attrib["i"])
j2 = str('<j2 cb="'+rcv.attrib["c"]+'" Y="'+str(Y[0])+'" l5="'+str(Y[1]).strip()+'" l4="583" l3="463" l2="0" q="1" y="'+rcv.attrib['i']+'" k="'+k+'" k3="0" p="0" c="'+str(info[2])+'" f="0" u="'+str(uid)+'" d0="0" n=" " a="0" h="" v="0" />\0')
xat.send(j2)
print "\nSend --> "+j2+"\n"
while 1:
text = xat.recv(4069)
if 'logout' in text or 'idle' in text or 'dup' in text:
raider(a3, p)
else:
time.sleep(1)
xat.send('<m t=" " u="'+uid+'" />\0')
except:
raider(a3, p)
I made an attempt but it failed:
def raid()
$proxies = []
$ids = []
IO.foreach('ids.txt') do |line| # Foreach id as a line
$ids << line #ine.scan(/&Userid=(.*?)&k1=(.*?)&k2=([0-9]+)/i) # parse id
end
IO.foreach('socks.txt') do |line|
$proxies << line
end
$test = $ids.zip($proxies)
end
It reads the data from the two files, matches each ID with a Proxy, and sends
it to a function.
Answer: I'd write it like:
def raid()
ids = File.readlines('ids.txt')
proxies = File.readlines('socks.txt')
ids.zip(proxies).map{ |a| a.map(&:chomp) }
end
Starting with two files:
* socks.txt:
127.0.0.1
127.0.0.2
* ids.txt:
foo
bar
Calling the above method returns:
raid() # => [["foo", "127.0.0.1"], ["bar", "127.0.0.2"]]
> "...sends it to a function"
I'm not sure where in your code you tried to call a function, so I can't
replicate that.
|
Accessing ndarray and discarding invalid positions - Python
Question: I have one question about accessing a matrix position that in fact does not
exists.
First, I have an matrix with **rows** rows and **cols** columns. From this
matrix, I have to get sets of **n** x **n** sub matrices. For example, to get
3 x 3 sub matrices, I do the following:
for x, y in product(range(1, matrix.rows-1), range(1, matrix.cols-1)):
bootstrap_3x3 = npr.choice(matrix.data[x-1:x+2, y-1:y+2].flatten(), size=(3, 3), replace=True)
But, as can be seen, I'm not considering the extremes, and I have to. For x =
0 and y = 0, for example, I should consider `matrix.data[x:x+2, y:y+2]` (the
center should be the current x and y), returning a `3 x 3` with the first
row/column = 0.
I know that I can achieve this with some **if** statements. But I guess Python
should have a clever way to do this properly.
Thank you in advance.
Answer: I would make a new matrix, padded with `(n-1)/2` zeros around it:
import numpy as np
rows, cols = 4, 6
n = 3
d = (n-1)/2
data = np.arange(rows*cols).reshape(rows, cols)
padded = np.pad(data, d, mode='constant')
for x, y in np.indices(data.shape).reshape(2, -1).T:
sub = padded[x:x+n, y:y+n]
print sub
bootstrap_nxn = np.random.choice(sub.ravel(), (n, n))
This assumes `n` is odd, and that the submatrix _center_ is always within the
the original `data` matrix. If `n` is even, the _center_ of the submatrix
isn't well defined.
If you actually want to have the submatrix overlap with the data matrix with
only one row, then you'd need to pad with `n-1` zeros (and in that case even
vs odd `n` won't matter).
|
How to get data from MongoDB on client side using javascript/jQuery
Question: I have written a code in bottle in python which gets data from mongodb and
when the user request the url `http://localhost:8080/index/test` from bottle
it will return the json result from mongoDB. it works fine when I point my
browser to that url, I can see all the result on the browser.
However when I try to send a request from jQuery ajax I always get error, and
the request never succeeds.
Has anyone ever done anything similar who can share their approach with me?
MY general question is, what the best way to get data from MongoDB from client
side, when using bottle as the server. I have seen some example in Node.js but
I want to use python as the server.
I have used this code.
$.ajax({
type: "POST",
url: "http://localhost:8080/hello/test",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("success");
},
error: function (response){
console.log("failed");
}
});*/
And I have also tried this :
$.post( "http://localhost:8080/hello/test", d)
.done(function( response ) {
console.log("success");
});
no luck with any of these. I have also tried GET instead of post, but no luck.
This is kind of what I have in python side :
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return {'status':'online', 'something':'blah blah'}
run(host='localhost', port=8080)
Many thanks in advance.
Answer: First of all 'GET' is the better alternative since you are not passing any
params to your DB.
Secondly on which port is your application running? You are adding 8080 to
your request which lets me assume your app is running under a different port.
JS is based on the [Same Origin
Policy](http://en.wikipedia.org/wiki/Same_origin_policy) that means if you
want to access data from a different URL (different port = different url) it
won't give you any repsponse data.
To make this work either make sure the python script is passing the
information to your application directly or you have to implement [Cross
Origin Ressource Sharing](http://en.wikipedia.org/wiki/Cross-
origin_resource_sharing). To do this you have to add a header to the response
of your python (port 8080) script with the following content
> Access-Control-Allow-Origin: localhost:XXXX //replace XXXX with your
> application port
EDIT: If you need to know how to activate COR check out this thread on
stackoverflow: [PY Bottle enable
COR](http://stackoverflow.com/questions/17262170/bottle-py-enabling-cors-for-
jquery-ajax-requests)
|
How can we remove all distinct words of length 16 letters or more using python
Question: How can we remove all distinct words of length 16 letters or more. Reduce the
size of these words to fifteen letters while keeping them distinct. (hint
removing postfix, suffix, and or infix)
so far i have done the following code:
fo = open("anyFile.txt","wb")
words = set(w.lower() for w in open('distinct_words_only.txt').read().split())
for item in english_words:
if len(item) > 15:
fo.write(item)
fo.close()
Answer: Well I gave a quick shot to your question. I shall explain how I accomplished
this task. There could be a better approach too. As far as what I understood
from your question is:
> Your major concern is to keep the length of a word to 15 and also to keep
> them distinct.
The code snippet below does that exactly. I first read the file `anyFile.txt`
which shall contain all the words having 15 letters or more only. I assume
from your question that you have already created this kind of file. I kept the
contents of this file into `english_words`.
Then I declared a `charList = ['a','b','c','d','e','f']`. Well in my code I am
simply using these `6` letters for creating distinct words. You can use more
if you like. More is better.
Then I loop over every word using a for loop. In loop first I strip the word
to keep its length up to 15 letters. Then I call my `checker()` to do the
heavy stuff.
The `checker()` will first check if the word is already present in
`oldWordList` if yes then it will generate a new distinct word. I used
recursion to double check if the newly created word is distinct or not. If the
word is not in the `oldWordList` then I simply append it to a `newWorldList`.
This `newWorldList` will contain all the distinct words at last.
How are distinct words being generated? Well the code is simple. First I am
converting the word which is a string to a List `tempList = list(item)`, so
that I can modify it. Then here `tempList[randomIndex] = charList[randomChar]`
I am selecting a random letter from `charList = ['a','b','c','d','e','f']` and
then assigning it to a random position in the `tempList`.
Code snippet: _Please see: The code snippet is quick and dirty feel free to
improve it further._
import random
fo = open("anyFile.txt","wb")
english_words = set(w.lower() for w in open('distinct_words_only.txt').read().split())
for item in english_words:
if len(item) > 15:
fo.write(item+'\n')
fo.close()
def checker(item):
randomIndex = random.randrange(0,15)#Random number to decide which position in word
randomChar = random.randrange(0,6)#Random number to pick a letter from charList
if item in oldWordList:
print 'Yes %s is present already'%item
tempList = list(item)#Convert string to list
tempList[randomIndex] = charList[randomChar]#Generate random word
item = "".join(tempList)#Covert list back to string
checker(item)#Recursion to double check
print 'Newly created word %s'%item
else:
print '%s is distinct'%item
newWordList.append(item)
english_words = set(w.lower() for w in open('anyFile.txt').read().split())
charList = ['a','b','c','d','e','f']
oldWordList = []
newWordList = []
for item in english_words:
item = item[0:15]
print 'Append item to oldWordList %s '%item
checker(item)
oldWordList.append(item)
print oldWordList#Will contain the original 15 letters words
print newWordList#Will contain distinct 15 letteres words
**Testing the code:** Create a file named as `'distinct_words_only.txt'` with
the following content and execute the script code:
averybigblackdogwithdots
averysmallwhitecatwithatail
averytinygreymousewithanose
averytinygreymousewithabignose
averybigblackdogwithdots
averybigblackdogwithdotts
averysmallwhitecatwithalongtail
averytinygreymousewithanosee
aaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaabbbbb
When the script is executed you shall see the `print newWordList` will show
you a list of distinct words with length of 15 letters in console.
**Limitation:** I just wanted to point out that there is a limitation in
creating distinct words too using replacement method like what I did. Eg:
Consider a word of 2 letters and if you are allowed to use 2 letters for
creating all the possible words then you can only generate 4 different words.
**Eg:** Word = IN, replacement letters are A,B
Distinct words could only be: IA, IB, AN, BN. Because in replacement method we
can only replace a letter without changing their position. We can only replace
I or N with A or B. We can't do something like NA, NB, AI, BI etc. using
replacement method.
I hope this was a bit helpful.
|
Unhandled exception at multiarray.pyd the 2nd time the program runs
Question: I'm making a .dll plug-in in c++ and embedding python 2.7 in it.
Everything worked fine with simple .py programs until I imported a large
program. The strangest thing is that the program runs with no problem the
first time, but the second time an exception is raised:
Unhandled exception at 0x6731ADA1 (multiarray.pyd) in EuroScope.exe: 0xC0000005: Access violation writing location 0x00000001.
(The Lib/Dll folders and modules are all copied to the .exe folder)
I've searched the web and there are a couple of persons with the same error
but the solutions that worked for them don't for me. For example
[here](https://code.google.com/p/ironclad/issues/detail?id=32)
I know this is a very specific error but I'm hoping that someone out there has
already managed to work past it. I won't post the code here because i think
it's irrelevant for this bug and also because it's way too long
Edit: I managed to see the problem is specifically in `import numpy`
Answer: I managed to work past this problem. It seems that some modules have problems
when their initialization routines are called more than once, and `numpy`is
one of those. The solution is to call `Py_Finalize()` only once at the very
end of the program. `Py_Initialize()` can be called as many times as you want,
as if Python is already initialized, `Py_Initialize()` is a non-op ...
And also, discovered that this solution turns the application faster since
python doesn't need to restart every time there's a call to some of its
function.
More information about it
[here](http://stackoverflow.com/questions/7676314/py-initialize-py-finalize-
not-working-twice-with-numpy)
|
Why is Julia slow when decoding GZIP and parsing JSON?
Question: The following script reads the gzip file line-by-line and decodes JSON object
Pkg.add("GZip")
Pkg.add("JSON")
using GZip
using JSON
stream = GZip.gzopen(Base.ARGS[1])
_started = time()
i = 0
for line in eachline(stream)
_j = JSON.parse(line)
if i % 10000 == 0
println(time()-_started)
end
i += 1
try
key_id = _j["some_id"]
except
pass
end
end
output:
0.7071459293365479
20.09155511856079
37.8870849609375
compare to Python:
import os
import sys
import gzip
import datetime
import ujson as json
_started = datetime.datetime.now()
fh = gzip.open(sys.argv[1])
for i, line in enumerate(fh):
if i % 10000 == 0:
print datetime.datetime.now() - _started
line = json.loads(line)
try:
k = line['some_id']
except:
pass
output:
0:00:00.028951
0:00:01.934277
0:00:03.821954
0:00:05.713572
Yes, I know, I used ujson which is really fast - but shouldn't Julia be faster
anyway? Instead, it's much slower =(
P.S. Tried many times so it's not related to the OS cache or whatever.
P.P.S. Mac OS 10.7.3, Julia 0.2.1
Answer: Isolating the JSON and GZIP operations is a good suggestion. My guess (only a
guess!) is that most of the time is in JSON parsing; ujson is indeed very
fast. There's no way to guarantee that everything that happens in a language
is fast. PyPy, for example, will generally speed up python code a lot, but in
some cases is still slow, or slower than C extensions.
|
Is twitter-text-python thread-safe?
Question: I'm using [twitter-text-python](https://github.com/ianozsvald/twitter-text-
python)
Is it thread-safe to create an instance of Parser:
from ttp import ttp
parser = ttp.Parser()
and then use it in various threads?
Answer: I took a quick look at the source code, and it looks like the Parser object's
state could easily get trashed if two threads are running parser.parse() at
the same time. Here is what Parser.parse looks like:
def parse(self, text, html=True):
'''Parse the text and return a ParseResult instance.'''
self._urls = []
self._users = []
self._lists = []
self._tags = []
reply = REPLY_REGEX.match(text)
reply = reply.groups(0)[0] if reply is not None else None
parsed_html = self._html(text) if html else self._text(text)
return ParseResult(self._urls, self._users, reply,
self._lists, self._tags, parsed_html)
The first thing the method does is clear a bunch of internal lists that
contain parsed results. If you were to call parse() in one thread, and half-
way through that being complete (so a few of those internal lists are
populated, but work is still being done), you call self.parse() in another
thread, all those lists will get cleared, which would trash the first thread's
results. You'd end up with a mix of results from each thread being returned to
both the first and second thread.
I think you'll need to create a Parser() instance for each thread.
|
WARNING:base_connection:Unknown state on disconnect: 0 Pika/Celery/Rabbitmq
Question: I'm trying to run the hello world version of using celery/rabbitmq (from
rabbitmq site).
When I run `python send.py` it outputs this and throws an error:
python send.py
[x] Sent 'Hello World!'
WARNING:pika.adapters.base_connection:Unknown state on disconnect: 0
WARNING:pika.adapters.base_connection:Unknown state on disconnect: 0
Here is my `send.py` :
#!/usr/bin/env python
import pika
import logging
logging.basicConfig()
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='xx.xxx.xx.xxx'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
here is `receive.py`
#!/usr/bin/env python
import pika
import logging
logging.basicConfig()
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='xx.xxx.xx.xxx'))
channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
**EDIT (FIX):** To not receive this warning of
`WARNING:pika.adapters.base_connection:Unknown state on disconnect: 0`
Remove the `connection.close()` used in either send.py or receive.py files.
Answer: I'm not sure how celery is coming into play here, since you're just doing the
RabbitMQ "Hello, world" tutorial, which has nothing to do with celery. But I
believe those warnings are actually just caused by a bug in pika. It's not
anything you're doing wrong with your example. See the bug report here:
<https://github.com/pika/pika/pull/346>
Note that they're just warnings; they're being printed when connection.close()
is called, and won't affect the behavior of the program at all.
|
wxPython Reload a grid in a panel
Question: I've got several classes so I prefer not to paste any code here (if that's
possible :P)
The problem: I've created a class which creates a frame, and this frame
contains a panel. In another class I've stored all my settings.
On the panel are several sizers and among other attributes, it has a grid.
This grid is build from sequence 1 on the x axis and sequence y on the y axis.
To create my panel, I've divided my code into sections (like buildLeft()
buildRight() buildTopRight() and so on which are linked to a main sizer in the
buildFrame() method).
My grid is created in the buildTopRight() section of this class. It creates
the grid by retrieving the values for sequence1 and sequence2 from the
settings object and creates a grid of the length of this sequence accordingly.
After this is done, the grid is bound to the sizer for the topRight section.
I also have a dropdown list (wx.Choice). If i select another option from this
list, I want to remove an item from my sequence 1 and sequence 2. The code to
do this already works, and the data in my settings object changes accordingly.
However, I'm not able to reload the matrix, since if i call the
buildTopRight() method again, the matrix is recreated and cropped to the
topleft side of my screen, while leaving the old matrix in place.
Please help.
On request, this is the code for building my panel:
# import modules
import wx
import wx.grid
import matrixSettings as ms
# Panel class
class ResultatenPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id, style=wx.BORDER_SUNKEN)
# link settings object
self.matSet = self.GetGrandParent().ms
# build the main sizers
self.sizerMain = wx.BoxSizer(wx.HORIZONTAL)
self.sizerMenu = wx.BoxSizer(wx.VERTICAL)
self.sizerRight = wx.BoxSizer(wx.VERTICAL)
self.sizerTopRight = wx.BoxSizer(wx.HORIZONTAL)
self.sizerBotRight = wx.BoxSizer(wx.HORIZONTAL)
# make individual parts
self.buildMenu()
self.buildTopRight()
self.buildBotRight()
self.buildRight()
# build total frame
self.buildFrame()
build right code (includes top and bottom right bits):
def buildRight(self):
self.sizerRight.Add(self.sizerTopRight, 5)
self.sizerRight.Add(self.sizerBotRight, 2)
the code to build the frame:
def buildFrame(self):
self.sizerMain.Add(self.sizerMenu, 1)
self.sizerMain.Add(self.sizerRight, 5, wx.EXPAND)
self.SetSizer(self.sizerMain)
top right code:
def buildTopRight(self):
self.grid = wx.grid.Grid(self)
print "buildTopRight called"
if self.matSet.getAlgoritme() == "Needleman-Wunsch":
self.matSet.setSeq1("-" + self.matSet.getSeq1())
self.matSet.setSeq2("-" + self.matSet.getSeq2())
# set grid
self.grid.CreateGrid(len(self.matSet.getSeq2()), len(self.matSet.getSeq1()))
self.grid.SetRowLabelSize(25)
self.grid.DisableDragColSize()
self.grid.DisableDragRowSize()
# set the grid proportions accurately
for x in range(0, len(self.matSet.getSeq1())):
# set the grid proportions accurately
for y in range(0, len(self.matSet.getSeq2())):
self.grid.SetRowSize(y, 25)
self.grid.SetRowLabelValue(y, self.matSet.getSeq2()[y].upper())
self.grid.SetCellValue(y, x, "0")
self.grid.SetReadOnly(y, x, True)
self.grid.SetColSize(x, 25)
self.grid.SetColLabelValue(x, self.matSet.getSeq1()[x].upper())
newly added:
self.sizerTopRight.Clear()
self.sizerTopRight.Add(self.grid, 1)
self.Update()
self.Layout()
Answer: I know this is a not very memory friendly solution. You should hide the
current grid and create a new one:
self.sizerTopRight.Hide(self.grid)
self.sizerTopRight.Add(self.new_grid, 1)
self.sizerTopRight.Show(self.new_grid)
self.Layout()
|
Having trouble trying to pull data from a url into python using an API
Question: I'm trying to pull data from a chart on a site in csv format. I've tried
different combinations of code but can't seem to figure it out. I keep getting
the following errors depending on the code I write:
TypeError: 'set' object is not subscriptable TypeError: a float is required
My latest attempt looked like this:
import urllib
import urllib2
import csv
import StringIO
url = "https://api.rjmetrics.com/0.1/chart/chartid/export"
headers = {"X-RJM-API-Key": "myapikey"}
data = {"format=csv"}
response = urllib2.Request(url, data, headers)
re = urllib2.urlopen(response)
spamreader = csv.reader(re, delimiter=',', quotechar='|')
for row in spamreader:
print row
The working CURL version looks like this:
curl -d "format=csv" -H "X-RJM-API-Key: myapikey" https://api.rjmetrics.com/0.1/chart/chartid/export
but I don't know how to work with curl.
Thank you!
Answer: `data` should be a url encoded string, you are passing it a set --
{"format=csv"} is a set literal. Try this:
data = urllib.urlencode(dict(format='csv'))
|
Inserting JSON Data into SQL Server with Python
Question: I have a python script that makes a call to an API, submits a request, and
then is supposed to insert the result into a Sql Server 2012 table. When it
goes to execute the insert into SQL, it breaks. I am currently importing json,
requests, and pyodbc into the file. Here is the location where it is breaking:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER={localServer};DATABASE={localDB}')
cursor = conn.cursor()
for record in response:
print(json.dumps(record))
cursor.execute("Insert Into Ticket_Info values ?", json.dumps(record))
cursor.commit()
cursor.close()
conn.close()
It is at the cursor.execute() line where the breakage occurs. This is the
error I got when I attempted to run this.
> pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server
> Driver][SQL Server]Incorrect syntax near '@P1'. (102) (SQLExecDirectW);
> [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could
> not be prepared. (8180)"
Any help I could get I would appreciate. I have searched and tried several
different methods at this point, the only thing that changes is the error.
Answer: The second argument to `cursor.execute()` must be a _sequence_ of values to
interpolate, one for each SQL parameter in your statement.
You gave ODBC a string instead, which is _also_ a sequence, but one that
contains (many) more elements (characters) than your query requires.
Use a single-element tuple here:
cursor.execute("Insert Into Ticket_Info values (?)", (json.dumps(record),))
I also put parenthesis around the values section, as per the [SQL Server
`INSERT` syntax](http://technet.microsoft.com/en-us/library/ms174335.aspx):
> `VALUES`
> Introduces the list or lists of data values to be inserted. There must be
> one data value for each column in column_list, if specified, or in the
> table. **The value list must be enclosed in parentheses.**
Unless `Ticket_Info` has only _one_ column per row (unlikely, you'd have a
primary key column at least), you probably need to specify what column you are
inserting your value into:
cursor.execute("Insert Into Ticket_Info (<columnname>) values (?)", (json.dumps(record),))
where you need to replace `<columnname>` with the actual column name in your
table.
|
Matplotlib interactive mode not working on win 7
Question: This file should work, but it doesn't:
from matplotlib import pyplot
pyplot.ion()
pyplot.plot(range(10))
raw_input('Press return to close')
The plot window appears, the inside is white and the hourglass cursor is
shown. The text is printed in the shell, and hitting return closes the empty
plot window.
I can plot from ipython, but this has to run from a file. Exactly the same
problem as [Using ion() from pylab causes matplotlib to
hang](http://stackoverflow.com/questions/12827969/using-ion-from-pylab-causes-
matplotlib-to-hang) , but the solution doesn't help me.
I am using Qt4Agg, by default. I haven't changed any settings, it is a fresh
Anaconda install.
I don't think this is Anaconda specific, I had exactly the same problem some
time ago with a normal Python install, but I don't remember the solution.
I recently upgraded Matplotlib to 1.3.1 np18py27_1
Current conda install:
platform : win-32
conda version : 3.0.6
python version : 2.7.6.final.0
root environment : C:\Anaconda (writable)
default environment : C:\Anaconda
envs directories : C:\Anaconda\envs
package cache : C:\Anaconda\pkgs
channel URLs : http://repo.continuum.io/pkgs/free/win-32/
http://repo.continuum.io/pkgs/pro/win-32/
config file : None
is foreign system : False
Answer: If it fixed your problem to call a different back-end, you can make this a
permanent change by changing the `matplotlibrc` file.
Unfortunately, I'm not sure where this file would be in windows.
When you do find it, line 32 sets the back-end used:
#### CONFIGURATION BEGINS HERE
# the default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg FltkAgg MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS
# PDF SVG Template
# You can also deploy your own backend outside of matplotlib by
# referring to the module name (which must be in the PYTHONPATH) as
# 'module://my_backend'
backend : <Whatever works for you>
This will allow you to run it from a file - outside of ipython
|
Cython+NumPy - compiler not using numpy.pyd
Question: I have a code that uses numpy and I want to compile it using Cython. I added
the cimport directive:
import numpy as np
cimport numpy as np
I am on Windows 7, compiling using distutils with gcc (MinGW) as the compiler.
It yields an error when I try to compile it. This is the error:
ssepMC.c:346:31: fatal error: numpy/arrayobject.h: No such file or directory
#include "numpy/arrayobject.h"
^
compilation terminated.
error: command 'gcc' failed with exit status 1
I believe this error occurs because the compiler is trying to compile the
numpy package. But this is an unnecessary step because a compiled version of
numpy exists in Cython under
C:\Python27\Lib\site-packages\Cython\Includes\numpy\numpy.pxd
So the question is: How do I make the compiler use the compiled version of
numpy?
Thanks in advance.
Answer: As mentioned elsewhere, you need to point `gcc` to `numpy/arrayobject.h` which
you can do by setting `include_dirs` to `[np.get_include()]`.
Note - this is not 'recompiling' numpy, this is using the directives in the
numpy arrayheader file to instruct `gcc` how to compile your code.
from Cython.Build import cythonize
import numpy as np
ext_modules = [Extension("hello", ["hello.pyx"], include_dirs=[np.get_include()])]
setup(
ext_modules = cythonize(extensions)
)
|
formatting strings in list of lists
Question: I have this list of list
a = [['c', '1.3e-8', '4.5e-8'], ['h', '3.4e-5', '2.3e-7', '2.3e-5']]
I want to format the 'e' strings only as
a = [[ 'c', '0.000000013', '0.000000045'], ['h', '0.000034', '0.00000023', '0.000023']]
How can I do this in Python? Thanks!
Answer: If you sure only first element is not a float.
from decimal import Decimal
a = [['c', '1.3e-8', '4.5e-8'], ['h', '3.4e-5', '2.3e-7', '2.3e-5']]
for inx, rec in enumerate(a):
a[inx] = [rec[0]] + ['{:.{precise}f}'.format(Decimal(val),
precise=int(val[-1])+1) for val in rec[1:]]
print(a)
Output:
[['c', '0.000000013', '0.000000045'], ['h', '0.000034', '0.00000023', '0.000023']]
|
Could not extract TIF.gz file
Question: The TIF.gz file downloaded from the link below can be successfully extracted
by WinRAR GUI mode manually.
<ftp://ftp.glcf.umd.edu/glcf/QuickBird/02AUG15032744-X2AS_R1C1-000000185959_01_P005-Indonesia-
Ujong/02AUG15032744-M2AS_R1C1-000000185959_01_P005.TIF.gz>
However, it could not extract using programming mode using Python. But the
similiar method below can extract other tar.gz files:
import subprocess
win_rar = 'C:\\Program Files\\WinRAR\\UnRAR.exe'
tif_gz_file = 'D:\\source\\02AUG15032744-M2AS_R1C1-000000185959_01_P005.TIF.gz'
subprocess.call([win_rar, 'x', tif_gz_file, 'D:\\target\\'])
Any idea would be highly appreciated. I also tried the similiar procesure
using 7-Zip, it also did not. I want to extract it using a program. Please
help me.
Answer: You need to change this:
win_rar = 'C:\\Program Files\\WinRAR\\UnRAR.exe'
to this:
win_rar = 'C:\\Program Files\\WinRAR\\WinRAR.exe'
I ran your code successfully with this change (after reproducing your error).
|
Python: tkinter, adding entry to listbox doesn't response
Question: For some reason, it doesn't add the element to the listbox. I guess it's
because of the program order, but i'm not sure how should I properly put the
code in the right order
Here is the code:
from tkinter import *
class App(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.parent = parent
self.grid()
self.lb = Listbox()
self.lb.grid(column=0, row=1, columnspan=5, rowspan=4,padx=5,sticky=E+W+S+N)
self.e = Entry()
self.e.grid( column=0, row=0, padx=5)
self.badd = Button(text="Add", command=self.addtolistbox())
self.badd.grid( column=1, row=0, padx=5, pady=5)
self.brmv = Button(text="Remove")
self.brmv.grid(column=2, row=0, padx=5, pady=5)
def addtolistbox(self):
self.lb.insert(0, self.e.get())
App = App(Tk())
App.mainloop()
Answer: Change this line
self.badd = Button(text="Add", command=self.addtolistbox())
to this
self.badd = Button(text="Add", command=self.addtolistbox)
The problem is that instead of binding the callback function to the button,
you _execute_ the function once (adding an empty string to the list) and then
bind the result of the function call to the button, i.e. `None`.
|
Read the data of a single channel from a stereo wave file in Python
Question: I have to read the data from just one channel in a stereo wave file in Python.
For this I tried it with scipy.io:
import scipy.io.wavfile as wf
import numpy
def read(path):
data = wf.read(path)
for frame in data[1]:
data = numpy.append(data, frame[0])
return data
But this code is very slow, especially if I have to work with longer files. So
does anybody know a faster way to do this? I thought about the standard _wave_
module by using _wave.readframes()_ , but how are the frames stored there?
Answer: [`scipy.io.wavfile.read`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.read.html)
returns the tuple `(rate, data)`. If the file is stereo, `data` is a numpy
array with shape `(nsamples, 2)`. To get a specific channel, use a
[slice](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) of
`data`. For example,
rate, data = wavfile.read(path)
# data0 is the data from channel 0.
data0 = data[:, 0]
|
TypeError: super(type, obj) when running pyprocessing script interactively
Question: Python 2.7.3:
Create the simplest possible
[`pyprocessing`](http://code.google.com/p/pyprocessing/) file and save it as
`foo.py`:
from pyprocessing import *
def setup():
size(100,100)
def draw():
rect(10,10,10,10)
run()
Now in python:
>>> execfile('foo.py')
The file runs as expected. Close the `pyprocessing` window to return to the
prompt and type:
>>> execfile('foo.py')
and you're greeted with:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo.py", line 9, in <module>
run()
File "/usr/local/lib/python2.7/dist-packages/pyprocessing-0.1.3.22-py2.7.egg/pyprocessing/__init__.py", line 417, in run
__main__.setup()
File "foo.py", line 4, in setup
size(100,100)
File "/usr/local/lib/python2.7/dist-packages/pyprocessing-0.1.3.22-py2.7.egg/pyprocessing/__init__.py", line 335, in size
config=canvas.config, caption=caption, visible = isVisible)
File "/usr/local/lib/python2.7/dist-packages/pyprocessing-0.1.3.22-py2.7.egg/pyprocessing/flippolicy.py", line 142, in __init__
super(BackupWindow, self).__init__(*args, **keyargs)
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/window/xlib/__init__.py", line 474, in __init__
super(XlibWindow, self).__init__(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/window/__init__.py", line 690, in __init__
self.set_visible(True)
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/window/xlib/__init__.py", line 878, in set_visible
self._map()
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/window/xlib/__init__.py", line 710, in _map
self.dispatch_event('on_resize', self._width, self._height)
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/window/__init__.py", line 1219, in dispatch_event
EventDispatcher.dispatch_event(self, *args)
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/event.py", line 352, in dispatch_event
event_type, args, getattr(self, event_type))
File "/usr/local/lib/python2.7/dist-packages/pyglet-1.1.4-py2.7.egg/pyglet/event.py", line 349, in dispatch_event
return getattr(self, event_type)(*args)
File "/usr/local/lib/python2.7/dist-packages/pyprocessing-0.1.3.22-py2.7.egg/pyprocessing/flippolicy.py", line 168, in on_resize
super (FBOWindow, self).on_resize(w,h)
TypeError: super(type, obj): obj must be an instance or subtype of type
What is happening here? Is this a bug are am I using `pyprocessing` wrong?
Answer: This works as
[subprocess](https://docs.python.org/2/library/subprocess.html#subprocess.call)
spawns a separate process each time:
from subprocess import call
call([sys.executable, 'foo.py'])
See [this SO question](http://stackoverflow.com/questions/1196074/starting-a-
background-process-in-python) for a fuller discussion of `subprocess.call`.
|
Set DJANGO_SETTINGS_MODULE as an Enviroment Variable in Windows permanently
Question: I have searched Web and Stack to this solution.
How can i permanently set the environmental variable `DJANGO_SETTINGS_MODULE`
on `WINDOWS` on a permanent basis and be done with it.
I mean
1. `Win Button` \+ `Pause/Break Button`
2. This leads to `Control Panel\System and Security\System`
3. Click `Advanced System Settings`
4. Click `Environment Variables`
5. There are two boxes the first is titled `User variables` and the second `System variables`
6. On the `System variables` click the `New Button`
7. For variable name put in `DJANGO_IMPORT_SETTINGS`
**XXX-->** **WHAT DO I PUT IN VARIABLE VALUE TO SET IT ONCE AND FOR ALL?**
* * *
In the Django Site on this
[issue](https://docs.djangoproject.com/en/dev/topics/settings/) it states:
_DJANGO_SETTINGS_MODULE_
_When you use Django, you have to tell it which settings you’re using. Do this
by using an environment variable, DJANGO_SETTINGS_MODULE._
_The value of DJANGO_SETTINGS_MODULE should be in Python path syntax,e.g.
mysite.settings. Note that the settings module should be on the Python import
search path._
* * *
What on earth does it mean **_...should be in Python path syntax e.g.
mysite.settings..._** ?
* I have a certain directory where my `Python` is located: `C:\Python27`
* I have a certain directory where my `Django` is located: `C:\Python27\Lib\site-packages\django`
What does this `mysite` means. What directory is it meanning
`C:\Something......`
Can you put this variable once and for all or you have to constantly change it
for every project(Holly Moses I hope not!)
And what does this suspiciously line means **_Note that the settings module
should be on the Python import search path._**
**All i want it to set the DJANGO_SETTINGS_MODULE environmental variable and
be done once and for all from this hassle**
They should really make tutorials for coding enthusiasts too, not only
experienced hardened professionals!
Thank you.
**EDIT**
_In order to work, Django just has to be pointed at a valid settings file, and
by default it looks for an environment variable named DJANGO_SETTINGS_MODULE
to tell it where to find the settings. The value of this variable should be
the Python import path of the settings file, such as cms.settings._
\--> What king of directory is this: `cms.settings`? In windows every
directory starts with a hard drive as **C:\Something.....**. How can you start
a directory like this in Windows?
**EDIT_2**
Excerpt from a book
_PROBLEM_ _Environment variable DJANGO_SETTINGS_MODULE is undefined._
_SOLUTION_ _Run the command`python manage.py shell` rather than `python`._
**MY QUESTION** \--> ON WHAT DIRECTORY?///CAN YOU SET IT FOR ONCE OR IS IT
DIFFERENT PER PROJECT?
MY PROJECT IS STRUCTURED LIKE THIS
C:\Python27\pysec-master(file)
|__local_settings.py
|__manage.py
|__settings.py
|__C:\Python27\pysec(file)
|__ __init__.py
|__example.py
|__models.py
|__xbrl.py
|__xbrl_fundamentals.py
I am trying to run `models.py` and i have a `settings.py` in the
`C:\Python27\pysec-master` You can find an exact copy
[here](https://github.com/lukerosiak/pysec).
**MAYBE_IMPORTANT_EDIT**
Guys I have a file called `manage.py` in my project which has these contents
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Does this has to do anything on setting the variable? Do i need to set here
here inside the loop?
EDIT
For the command in the IDLE `from django.db import settings` do i need to set
a directory for the `PYTHON_MODULE_SETTINGS` like `C:\Python27\Lib\site-
packages\django\db` ?
THANK YOU
Answer: Okay, don't be so frustrated. Let's look at this step by step:
* **Python path syntax:**
In Python, when you split your code base across modules, you qualify the name
of the import with the name of the module. Let's say your project is
structured like this:
my_project
|__utils
| |____init__.py
| |__file_utils.py
|__my_module
|____init__.py
|__main.py
In your `main.py` if you want to access methods you have defined in
`file_utils.py` you add an import statement in your `main.py` like this:
import utils.file_utils.read_file
assuming `read_file` is the method you want to import into `main.py`. This way
of importing modules where you have a `.` separating every module is referred
as python path syntax.
* **PYTHONPATH:**
In the above example, the import statement would work only if the Python
interpreter knows where to look for the first module namely the `utils`. Only
when it finds `utils` can it find `file_utils` and `read_file`. You specify
the list of all the paths you want the interpreter to look into in the
environment variable `PYTHONPATH`. So in order to have an import statement
like above in your code, you have to make sure that the full path to your
project `my_project` is in `PYTHONPATH`. Assuming `my_project` is in
`C:\AMAZEBALLS_CODE\my_project` you should have `C:\AMAZEBALLS_CODE` in your
`PYTHONPATH`
* **DJANGO_SETTINGS_MODULE:**
Now let's suppose your `my_project` is actually a Django application. A Django
application needs a settings file where you specify a [whole bunch of
things](https://docs.djangoproject.com/en/dev/topics/settings/). In order to
instruct Django which settings file to look into you specify it in
`DJANGO_SETTINGS_MODULE`. Assuming this is your project structure:
my_project
|__utils/
| |____init__.py
| |__file_utils.py
|__my_module/
| |____init__.py
| |__main.py
|__site_settings/
|__dev_settings.py
|__production_settings.py
`myroject.site_settings` is the module Django has to look into for the
settings file. And `myroject.site_settings.dev_settings` is the value you need
to be setting to the `DJANGO_SETTINGS_MODULE` in the above case. When
documentation says `cms.settings` or `mysite.settings` they mean `cms` or
`mysite` is the name of your project and `settings.py` is the name of your
settings file.
Now let's look at your question:
Can you permanently set it in the environment variables of Windows? Sure.
Is it the right way? No.
Because if you want to create another application tomorrow in another
location, you will have to edit this in the environment variables section of
Windows. Also, it is a practice to use a different settings file for
development environment and another one for production. So setting it at one
place with one value makes it inflexible. But if you are aware of all of the
above and sure you are gonna be using just the one settings file set
`DJANGO_SETTINGS_MODULE` to `myproject.site_settings.dev_settings` in the env
variables section.
Hope this helps!
**EDIT:**
Looks like you are putting your `pysec-master` project in `C:\Python27`. Do
not put your projects in the python installation. Create a `settings.py` file
in your project and set `DJANGO_SETTINGS_MODULE` to `pysec-master.settings`
|
How can I get all the plain text from a website with Scrapy?
Question: I would like to have all the text visible from a website, after the HTML is
rendered. I'm working in Python with Scrapy framework. With
`xpath('//body//text()')` I'm able to get it, but with the HTML tags, and I
only want the text. Any solution for this? Thanks !
Answer: The easiest option would be to
[`extract`](http://doc.scrapy.org/en/latest/topics/selectors.html#scrapy.selector.Selector.extract)
`//body//text()` and
[`join`](https://docs.python.org/2/library/string.html#string.join) everything
found:
''.join(sel.select("//body//text()").extract()).strip()
where `sel` is a
[`Selector`](http://doc.scrapy.org/en/latest/topics/selectors.html#scrapy.selector.Selector)
instance.
Another option is to use [`nltk`](https://pypi.python.org/pypi/nltk)'s
`clean_html()`:
>>> import nltk
>>> html = """
... <div class="post-text" itemprop="description">
...
... <p>I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
... With <code>xpath('//body//text()')</code> I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !</p>
...
... </div>"""
>>> nltk.clean_html(html)
"I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.\nWith xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !"
Another option is to use
[`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-
text)'s `get_text()`:
> `get_text()`
>
> If you only want the text part of a document or tag, you can use the
> `get_text()` method. It returns all the text in a document or beneath a tag,
> as a single Unicode string.
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.get_text().strip()
I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !
Another option is to use [`lxml.html`](http://lxml.de/lxmlhtml.html)'s
`text_content()`:
> `.text_content()`
>
> Returns the text content of the element, including the text content of its
> children, with no markup.
>>> import lxml.html
>>> tree = lxml.html.fromstring(html)
>>> print tree.text_content().strip()
I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !
|
Username and password using expect in python
Question: write a piece of code that ask the user to set a password \- queries the user
for his/her user name \- queries the user for his/her password twice, making
sure the user enters the same password twice \- Allow Only 3 attempts to get a
correct password
the rules for the password are \- at least one number \- at least one lower
cap letter \- at least one upper cap letter \- allowed characters: numbers,
letters, "_", "-" and "."
The above task should be done using expect concept. Since am new to python
language can anyone help me in solving this task.
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
I have tried till thid and donn't know how to proceed.
Answer: How about
child.sendline(raw_input('Password:'))
It prints `Password:` and asks the user for the password.
|
convert string numpy array to a ascii numpy matrix
Question: I have been looking for an efficient way for converting a string numpy array
to a two dimensional ASCII matrix in python. So for this is the best that I
could come up with
def charArrayToAsciiMatrix(strNumpyArray):
for i in range(strNumpyArray):
if(i==0):
AsciiMatrix=numpy.matrix(ord[[c for c in strNumpyArray[i]]])
else:
AsciiMatrix=numpy.vstack(AsciiMatrix,ord[[c for c in strNumpyArray[i]]])
is there a efficient way of doing this?
Answer: How is this?
import numpy as np
def add_word_as_ordinal(arr, word):
arr.extend([ord(ch) for ch in word])
return arr
def char_array_to_ascii_matrix(char_array):
result = np.matrix(reduce(add_word_as_ordinal, char_array, []))
result.shape = len(char_array), len(char_array[0])
return result
my_array = np.array("JustA Flesh Wound".split())
my_matrix = char_array_to_ascii_matrix(my_array)
|
Display a range of dates based on current date, in Python
Question:
import datetime
print datetime.datetime.now().strftime("Week of %m/%d")
#returns "Week of 04/18"
I want it to print "Week of 4/11 to 4/18" (with 4/13 being exactly one week
beforehand) and it would need to account for if the week ended on 4/3, then it
would be "Week of 3/27 to 4/3"
Is there an easy way to do this?
Answer: [`dateutil.relativedelta`](http://labix.org/python-dateutil#head-
ba5ffd4df8111d1b83fc194b97ebecf837add454) will do what you want:
import datetime
from dateutil.relativedelta import *
march27 = datetime.datetime(2014, 3, 27)
print (march27 + relativedelta(weeks=+1)).strftime("Week of %m/%d")
#prints "Week of 04/03"
|
Accessing Data from .mat (version 8.1) structure in Python
Question: I have a Matlab (.mat, version >7.3) file that contains a structure (data)
that itself contains many fields. Each field is a single column array. Each
field represents an individual sensor and the array is the time series data. I
am trying to open this file in Python to do some more analysis. I am using
PyTables to read the data in:
import tables
impdat = tables.openFile('data_file.mat')
This reads the file in and I can enter the fileObject and get the names of
each field by using:
impdat.root.data.__members__
This prints a list of the fields:
> ['rdg', 'freqlabels', 'freqbinsctr',... ]
Now, what I would like is a method to take each field in data and make a
python variable (perhaps dictionary) with the field name as the key (if it is
a dictionary) and the corresponding array as its value. I can see the size of
the array by doing, for example:
impdat.root.data.rdg
which returns this:
/data/rdg (EArray(1, 1286920), zlib(3))
atom := Int32Atom(shape=(), dflt=0)
maindim := 0
flavor := 'numpy'
byteorder := 'little'
chunkshape := (1, 16290)
My question is how do I access some of the data stored in that large array (1,
1286920). How can I read that array into another Python variable (list,
dictionary, numpy array, etc.)? Any thoughts or guidance would be appreciated.
Answer: I have come up with a working solution. It is not very elegant as it requires
an eval. So I first create a new variable (alldata) to the data I want to
access, and then I create an empty dictionary datastruct, then I loop over all
the members of data and assign the arrays to the appropriate key in the
dictionary:
alldata = impdat.root.data
datastruct = {}
for names in impdat.rood.data.__members___:
datastruct[names] = eval('alldata.' + names + '[0][:]')
The '[0]' could be superfluous depending on the structure of the data trying
to access. In my case the data is stored in an array of an array and I just
want the first one. If you come up with a better solution please feel free to
share.
|
How to get every single permutation of a string?
Question: I know how to get the permutations of just the plain string in python:
>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> print perms
...
But how would I get the permutations of `'stac'`, `'stak'`, `'sack'`,
`'stck'`, `'stc'`, `'st'`, and so forth? My desired output is:
>>> permutations('pet')
['pet', 'pte', 'ept', 'etp', 'tpe', 'tep', 'pe', 'ep', 'p', 'e', 't', 'pt', 'tp', 'et', 'te']
What I have so far:
def permutate(values, size):
return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
def permutate_positions(n, size):
if (n==1):
return [[n]]
unique = []
for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
if p not in unique:
unique.append(p)
return unique
def perm(word):
all = []
for k in range(1, len(word)+1):
all.append(permutate([' ']+list(word), k))
return all
This runs as:
>>> perm('pet')
[[['t'], ['e'], ['p']], [['t', 'e'], ['e', 't'], ['e', 'p'], ['t', 'p'], ['p', 't'], ['p', 'e'], ['p', 'p']], [['t', 'e', 'p'], ['e', 't', 'p'], ['e', 'p', 't'], ['e', 'p', 'p'], ['t', 'p', 'e'], ['p', 't', 'e'], ['p', 'e', 't'], ['p', 'e', 'p'], ['t', 'p', 'p'], ['p', 't', 'p'], ['p', 'p', 't'], ['p', 'p', 'e']]]
>>>
However, it has a bunch of list of lists, and with values like ['p', 'p',
't']!
How do I do this? ANy help is appreciated.
Answer: This is one way of doing it with
[itertools.permutations](https://docs.python.org/2.7/library/itertools.html#itertools.permutations):
from itertools import permutations
s = 'pet'
print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]
Output:
['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp', 'te', 'pet', 'pte', 'ept', 'etp', 'tpe', 'tep']
|
How do i open a class from within another class by selecting an item on ToolBar?? Python/PyQt
Question: I am trying to run class AddTQuestions from a def in class AddTest but it wont
work!! It opens the window AddTQuestions for a split-second then closes it
straight away?!
The code is shown here:
import sys
from PyQt4 import QtCore, QtGui
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
RunClassAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
RunClassAction.triggered.connect(self.run)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(RunClassAction)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Why Wont this Woooorkkkkk')
self.show()
def run(self):
AddQuestion = AddTQuestions()
AddQuestion.show()
class AddTQuestions(QtGui.QMainWindow):
def __init__(self, parent=None):
super(AddTQuestions, self).__init__(parent)
self.welldone = QtGui.QLabel('WellDone')
self.button = QtGui.QPushButton('Press Me')
layout = QtGui.QVBoxLayout()
layout.addWidget(self.welldone)
layout.addWidget(self.button)
self.setLayout(layout)
print("hello")
if __name__ == '__main__':
app = QtGui.QApplication([])
window = Example()
window.show()
app.exec_()
Answer: The object get's garbage collected, since you don't hold any reference to it
when the function ends.
add them as class variables like this and the window stays open.
self.AddQuestion = AddTQuestions()
self.AddQuestion.show()
|
Django with mod_wsgi how to set PYTHONHASHSEED env variable?
Question: How to run django with mod_wsgi with PYTHONHASHSEED environment variable set
to random? Is it a good approach to set it in django settings like this?
os.environ['PYTHONHASHSEED'] = 'random'
Answer: mod_wsgi 4.1.0 introduces an option for this
(<http://modwsgi.readthedocs.org/en/latest/release-notes/version-4.1.0.html>);
you would add to your Apache config:
WSGIPythonHashSeed random
If you can't run that version, you have to set the variable in the startup
environment of the Apache process, which will be OS-specific. For Fedora or
RHEL 7, you can create /etc/systemd/system/httpd.service:
.include /lib/systemd/system/httpd.service
[Service]
Environment=PYTHONHASHSEED=random
then `systemctl daemon-reload; systemctl restart httpd.service`. For pre-
systemd Red Hats, you can edit /etc/sysconfig/httpd. For Debian, it's
/etc/apache2/envvars.
Here's a WSGI file to test if it's working (based on the example in the
mod_wsgi docs):
import sys
def application(environ, start_response):
status = '200 OK'
try:
hr = sys.flags.hash_randomization
if hr == 0:
output = 'Hash randomization disabled'
elif hr == 1:
output = 'Hash randomization enabled'
else:
output = 'Unknown hash randomization: ' + str(hr)
except AttributeError:
output = 'Hash randomization not supported'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
|
Python: re module to replace value in dictionary
Question: I started looking at the handy `re` module available in Python today, and
hoping I could get help with `re.sub`
My file:
avid "Av.Id
fated "fEIt.Id
leaded "lEd.Id
wicked "wIk.Id
I want to sub if match `"(v|t|d|k)\.Id"` then change to `"\.(v|t|d|k)Id"` so
that output looks like:
avid "A.vId
fated "fEI.tId
leaded "lE.dId
wicked "wI.kId
I could match my string fine with `re.search` however I'm stuck at how I can
do the actual replacement when the letter is different every time (v, t, d, k,
etc). Thanks for any help.
Answer: Use [`re.sub()`](https://docs.python.org/2/library/re.html#re.sub) and
reference the saved group `(v|t|d|k)` using `\g<1>` syntax:
import re
PATTERN = re.compile('(v|t|d|k)\.Id')
with open('input.txt') as f:
for line in f:
print PATTERN.sub(".\g<1>Id", line)
It prints:
avid "A.vId
fated "fEI.tId
leaded "lE.dId
wicked "wI.kId
|
Error when installing from requirements.txt of web project with pip
Question: This is the error message I received
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-xGZuOG-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/Pillow
The full terminal output from sudo pip install -r requirements.txt is
<http://pastebin.com/CAvW67f2>
The content of requirements:
Django==1.6.1
EasyProcess==0.1.6
Pillow==2.3.0
South==0.8.4
Whoosh==2.6.0
bottle==0.11.6
dj-database-url==0.2.2
dj-static==0.0.5
django-bootstrap3==2.6.1
django-toolbelt==0.0.1
gunicorn==18.0
httplib2==0.8
pyscreenshot==0.3.2
pystache==0.5.3
python-instagram==0.8.0
simplejson==3.3.2
static==1.0.2
wsgiref==0.1.2
yolk==0.4.3
I'm completely lost - thanks for any help on this
Answer: Try running this in your bash before installing:
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
[Source](http://stackoverflow.com/questions/22697440/cc-failed-with-exit-
status-1-error-when-install-python-library)
|
Disable wxMenuBar
Question: So I'm looking to disable and enable a wxMenuBar in wxPython. Basically, grey
out the whole thing.
If you look at the documentation:
<http://docs.wxwidgets.org/trunk/classwx_menu_bar.html> ... you can see that
the enable function takes a parameter for the menu item. As in, it doesn't
disable/enable the whole menu, just a certain item.
Better yet, there's an `EnableTop(size_t pos, bool enable)` function to
disable a whole menu, but not the whole bar.
Do I have to disable each item or menu individually? There's no function for
doing the whole bar?
I made a function to do this manually but there must be a better way?
def enableMenuBar(action): #true or false
for index in range(frame.menuBar.GetMenuCount()):
frame.menuBar.EnableTop(index, action)
Thanks
Answer: You can disable the whole Menu by using
[EnableTop()](http://wxpython.org/Phoenix/docs/html/MenuBar.html#MenuBar.EnableTop)
**Code sample:**
import wx
class gui(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, None, id, title, style=wx.DEFAULT_FRAME_STYLE)
menuBar = wx.MenuBar()
file = wx.Menu()
quit = wx.MenuItem(file, 101, '&Quit\tCtrl+Q', 'Quit the Application')
about = wx.MenuItem(file, 102, '&About\tCtrl+A', 'About the Application')
help = wx.MenuItem(file, 103, '&Help\tCtrl+H', 'Help related to the Application')
file.AppendItem(help)
file.AppendSeparator()
file.AppendItem(about)
file.AppendSeparator()
file.AppendItem(quit)
file.AppendSeparator()
menuBar.Append(file, '&File')
self.SetMenuBar(menuBar)
menuBar.EnableTop(0, False)#Comment out this to enable the menu
#self.SetMenuBar(None)#Uncomment this to hide the menu bar
if __name__ == '__main__':
app = wx.App()
frame = gui(parent=None, id=-1, title="My-App")
frame.Show()
app.MainLoop()

Also if you use `self.SetMenuBar(None)` the whole menu bar is gone as shown
below. You can toggle the showing/hiding of the menu bar using this quick and
dirty way. To show the menu bar again just set it again like
`self.SetMenuBar(menuBar)` then the menu bar will be visible again. There
could be a better approach too.

I hope it was helpful.
|
python CSV edit elements in the diagonal of a matrix
Question: I have a CSV file containing an n * n distance matrix, and here's a part of
view,

I want to use python to edit this CSV, making elements in the diagonal of the
matrix replaced by 1, how should I do?
I am using python 2.7.4 under Windows 8.1 x64.
Answer: probably best to create a new csv from the old one. (untested)
import csv
newlines = []
with open('csvfilename.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
i=0
for row in reader:
newlines.append(row[:i] + [1] + row[i+1:])
i+=1
with open('newcsvfilename.csv','wb') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(newlines)
|
Random number function python that includes 1?
Question: I am new to Python and am trying to create a program for a project- firstly, I
need to generate a point between the numbers 0-1.0, including 0 and 1.0 ([0,
1.0]). I searched the python library for functions
(<https://docs.python.org/2/library/random.html>) and I found this function:
random.random()
This will return the next random floating point number in the range [0.0,
1.0). This is a problem, since it does not include 1. Although the chances of
actually generating a 1 are very slim anyway, it is still important because
this is a scientific program that will be used in a larger data collection.
I also found this function:
rand.randint
This will return an integer, which is also a problem.
I researched on the website and previously asked questions and found that this
function:
random.uniform(a, b)
will only return a number that is greater than or equal to a and less than b.
Does anyone know how to create a random function on python that will include
[0, 1.0]?
Please correct me if I was mistaken on any of this information. Thank you.
*The random numbers represent the x value of a three dimensional point on a sphere.
Answer: Consider the following function built on top of `random.uniform`. I believe
that the re-sampling approach should cause all numbers in the desired interval
to appear with equal probability, because the probability of returning
`candidate > b` is `0`, and originally all numbers should be equally likely.
import sys
import random
def myRandom(a, b):
candidate = uniform.random(a, b + sys.float_info.epsilon)
while candidate > b:
candidate = uniform.random(a, b + sys.float_info.epsilon)
return candidate
As gnibbler mentioned below, for the general case, it may make more sense to
change both the calls to the following. Note that this will only work
correctly if `b > 0`.
candidate = uniform.random(a, b*1.000001)
|
Python "open" file got 'TypeError: function takes at least 2 arguments (1 given)'
Question: I've had a piece of code which basically read a txt file from directory.
def img2vector(filename):
returnVect=zeros((1,1024))
fr=open(filename)
for i in range(32):
lineStr=fr.readline()
for j in range(32):
returnVect[0,32*i+j]=int(lineStr[j])
return returnVect
When I run img2vector(PATHTOMYFILE) I've got the error message:
fr=open(filename)
TypeError: function takes at least 2 arguments (1 given)
But, when I try: ` fr=open(PATHTOMYFILE) ` it's correct without any problem.
Answer: The most likely cause is that you define (or import) a function called
`open()` that shadows the [built-
in](https://docs.python.org/2/library/functions.html#open).
|
Writing and reading lists to text files in Python: Is there a more efficient way?
Question: Below is a program which asks the user to enter a recipe and stores their
ingredients in a set of lists. The program then stores the list data into a
text file. If option 2 is chosen it will retrieve the stored data from the
text file and load it back into the program for processing and to be displayed
to the user.
The text file doesn't need to store data in a human readable format but after
retrieval it must be in a format where each list item can be identifiable and
the quantities values need to be able to undergo a calculation.
My method was to dump the lists into a text document easily. When retrieving
the data it first adds each line to a variable, removes the square brackets,
speech marks etc and then splits it back into a list.
These seems to be a rather long winded and inefficient way of doing it. Surely
there is an easier way to store list data into a file and then retrieve
straight back into a list?
So, is there an easier more efficient way? Or, is there an alternative method
which is again more simple / efficient?
while True:
print("1: Enter a Recipe")
print("2: Calculate Your Quantities")
option = input()
option = int(option)
if option == 1:
name = input("What is the name of your meal?: ")
numing = input("How many ingredients are there in this recipe?: ")
numing = int(numing)
orignumpep = input("How many people is this recipe for?: ")
ingredient=[]
quantity=[]
units=[]
for x in range (0,numing):
ingr = input("Type in your ingredient: ")
ingredient.append(ingr)
quant = input("Type in the quantity for this ingredient: ")
quantity.append(quant)
uni = input("Type in the units for this ingredient: ")
units.append(uni)
numing = str(numing)
ingredient = str(ingredient)
quantity = str(quantity)
units = str(units)
recipefile = open("Recipe.txt","w")
recipefile.write(name)
recipefile.write("\n")
recipefile.write(numing)
recipefile.write("\n")
recipefile.write(orignumpep)
recipefile.write("\n")
recipefile.write(ingredient)
recipefile.write("\n")
recipefile.write(quantity)
recipefile.write("\n")
recipefile.write(units)
recipefile.close()
elif option == 2:
recipefile = open("Recipe.txt")
lines = recipefile.readlines()
name = lines[0]
numing = lines[1]
numing = int(numing)
orignumpep = lines[2]
orignumpep = int(orignumpep)
ingredients = lines[3].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
quantitys = lines[4].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
unitss = lines[5].replace("/n", "").replace("[", "").replace("]","").replace("'", "").replace(",", "")
ingredient=[]
quantity=[]
units=[]
ingredient = ingredients.split()
quantity = quantitys.split()
units = unitss.split()
for x in range (0,numing):
quantity[x] = int(quantity[x])
numberpep = input("How many people is the meal for?")
numberpep = int(numberpep)
print("New Ingredients are as follows...")
for x in range (0,numing):
print(ingredient[x], " ", quantity[x]/orignumpep*numberpep, units[x])
input()
Many thanks!
Answer: You could use a serialisation format; Python offers several.
For a list or dictionary containing string information, I'd use JSON, via the
[`json` module](https://docs.python.org/2/library/json.html), as it is a
format reasonably readable:
import json
# writing
with open("Recipe.txt","w") as recipefile:
json.dump({
'name': name, 'numing': numing, 'orignumpep': orignumpep,
'ingredient': ingredient, 'quantity': quantity, 'units': units},
recipefile, sort_keys=True, indent=4, separators=(',', ': '))
# reading
with open("Recipe.txt") as recipefile:
recipedata = json.load(recipefile)
# optional, but your code requires it right now
name = recipedata['name']
numing = recipedata['numing']
orignumpep = recipedata['orignumpep']
ingredient = recipedata['ingredient']
quantity = recipedata['quantity']
units = recipedata['units']
The `json.dump()` configuration will produce very readable data, and most of
all, you don't have to convert anything back to integers or lists; that is all
preserved for you.
|
How do I send an email with a .csv attachment using Python
Question: Okay, I know there is a few questions out there addressing this, but I cannot
find a way to make it work properly. I would assume it is as simple as the
below code, but this does not attach my file. Any help would be greatly
appreciated. I am also very new to Python. Is there a mail module that I
should be importing to make the function work?
import smtplib
fromaddr = "[email protected]
toaddrs = "[email protected]
msg = "help I cannot send an attachment to save my life"
attach = ("csvonDesktp.csv")
username = user
password = password
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg, attach)
server.quit()
Answer: Send a multipart email with the appropriate MIME types.
<https://docs.python.org/2/library/email-examples.html>
So possible something like this (I tested this):
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
emailfrom = "[email protected]"
emailto = "[email protected]"
fileToSend = "hi.csv"
username = "user"
password = "password"
msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "help I cannot send an attachment to save my life"
msg.preamble = "help I cannot send an attachment to save my life"
ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
if maintype == "text":
fp = open(fileToSend)
# Note: we should handle calculating the charset
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "image":
fp = open(fileToSend, "rb")
attachment = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "audio":
fp = open(fileToSend, "rb")
attachment = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(fileToSend, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)
server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
|
Python: Processing each row independently using map function
Question: Assuming the list:
[[2,4,0,8],[0,2,4,8],[8,0,2,4],[8,2,0,4]]
Hi guys, how do I use map function to process each element inside the row of
the list?
For e.g. if I want to add the pairs of each list:
[[6,0,8,0],[2,0,12,0],[8,0,6,0],[10,0,4,0]]
Basically I don't know how to use the map function very well, never find very
useful article about mapping. Appreciate if I can get some links. Thanks!!!
Answer: It depends what is your function actually.
**First:** If the function say `f` accepts "list as complete row" then you can
use:
m = [[6, 0, 8, 0], [2, 0, 12, 0], [8, 0, 6, 0], [10, 0, 4, 0]]
map(f, m)
**Second:** If function `f` accepts each element then you need to call nested
`map()`, something like as below:
map(lambda r: map(f, r), m)
For this, you could also use list compression:
[map(f, r) for r in m] # I prefer this
There are other tricks also, like you can use
[`functools.partial`](https://docs.python.org/2.7/library/functools.html#functools.partial)
Check this [example](http://ideone.com/dvi16G).
from functools import partial
newf = partial(map, f)
map(newf, m)
**Edit** as response to comment:
> Actually main thing is I want to know how to manipulate the elements in
> rows. Which mean I can also add all the element in for e.g. `[2, 4, 0, 8]`
> making it into `[14, 0, 0, 0]`.
First, I have doubt why you wants to convert a list `[2, 4, 0, 8]` into `[14,
0, 0, 0]`, why not to output just `14` -- the sum, check if you can improve
your algorithm/design of your program.
Anyways, in Python we have sum() function, read documentation [`sum(iterable[,
start])`](https://docs.python.org/2/library/functions.html#sum), example (read
comments):
>>> row = [2,4,0,8]
>>> sum(row) # just outputs sum of all elements, in rows
14
So if you wants to pass "a list of lists" like `m` (you posted in question)
then you can use `map(sum, m)` see below:
>>> m = [[6, 0, 8, 0], [2, 0, 12, 0], [8, 0, 6, 0], [10, 0, 4, 0]]
>>> map(sum, m) # call sum for each row (a list) in `m`
[14, 14, 14, 14] # sum of all individual list's elements
But if you wants to make a list like you asked then you can use `+` (list
concatenate) operator with sum as below:
>>> row = [2, 4, 0, 8]
>>> [sum(row)] + [0,] * (len(row) -1 )
[14, 0, 0, 0]
>>>
To understand this code piece:
1. `[sum(row)]` means list of single element that is sum of row -- `[14]`.
2. `[0,] * (len(row) -1 )` makes a list of zeros of length one less then number of elements in row, check below code example:
>>> row = [2, 4, 0, 8] # 4 elements
>>> [0,] * (len(row) -1 )
[0, 0, 0] # 3 zeros
>>>
The * operator similarly can be applied to tuple, string also.
3. So from above, I make two separate lists and add + both finally as below:
>>> row = [2, 4, 0, 8]
>>> [sum(row)] + [0,] * (len(row) -1 )
[14, 0, 0, 0] # that is what you wants
Now, you wants to execute `[sum(row)] + [0,] * (len(row) -1 )` expression for
each rowi ∈ m, then you can use lambda expression with `map()` as below:
>>> map(lambda row: [sum(row)] + [0,] * (len(row) -1 ), m)
[[14, 0, 0, 0], [14, 0, 0, 0], [14, 0, 0, 0], [14, 0, 0, 0]]
Better is to lambda expression a name:
>>> f = lambda r: [sum(r)] + [0,] * (len(r) -1 )
>>> f(row)
[14, 0, 0, 0]
then use `map()`:
>>> map(f, m)
[[14, 0, 0, 0], [14, 0, 0, 0], [14, 0, 0, 0], [14, 0, 0, 0]]
Just as I suggested in first few lines in my answer. Again you can use list
compression here in place of calling map() as:
>>> [f(r) for r in m]
|
Failed to screen scrap ASP.Net website while posting data
Question: Getting Invalid postback or callback argument error while trying to screen
scrap a website which has build on ASP.NET.
Fist request of landing page has no issue. It's raising exception when I posts
form data after changing one of drop-down field value.
"""
Invalid postback or callback argument. Event validation is enabled using
<pages enableEventValidation="true"/> in configuration or <%@ Page
EnableEventValidation="true" %> in a page. For security purposes, this feature
verifies that arguments to postback or callback events originate from the server
control that originally rendered them. If the data is valid and expected, use
the ClientScriptManager.RegisterForEventValidation method in order to register
the postback or callback data for validation.
"""
## Here's my try:
#!/bin/env python
import sys
import requests
from bs4 import BeautifulSoup
HOST = 'forms.toyotabharat.com'
URL = 'http://%s/pricelist-dealer.aspx' % HOST
HEADERS = {
'Host': HOST,
'Origin': 'http://%s' % HOST,
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive'
}
session = requests.Session()
r = session.get(URL, headers=HEADERS)
if r.status_code != requests.codes.ok:
sys.exit()
soup = BeautifulSoup(r.content)
# ASP validation and session fields
view_state = soup.select("#__VIEWSTATE")[0]['value']
view_state_generator = soup.select("#__VIEWSTATEGENERATOR")[0]['value']
event_validation = soup.select("#__EVENTVALIDATION")[0]['value']
FORM_FIELDS = {
'__EVENTTARGET': 'cboState',
'__EVENTARGUMENT': '',
'__LASTFOCUS': '',
'__VIEWSTATE': view_state,
'__VIEWSTATEGENERATOR': view_state_generator,
'__EVENTVALIDATION': event_validation,
'cboState': '3',
'cboCity': '-1',
'hdDealerMaps': 'True',
}
# POST form fields
r = session.post(URL, data=FORM_FIELDS, headers=HEADERS, cookies=r.cookies.get_dict())
if r.status_code != requests.codes.ok:
print "Failed with status_code %d" % r.status_code
sys.exit()
soup = BeautifulSoup(r.content)
Answer: You where basically on the right track. I got it running with a few changes.
> Invalid postback or callback argument.
The error message is really helpful. If you read the [msdn
page](https://msdn.microsoft.com/en-
us/library/system.web.ui.page.enableeventvalidation%28v=vs.110%29.aspx) of it
there is a hint.
Summarized as: don't post parameters or values which are not in the form which
you get with `GET`
In your case means that that if you select a State it should be one of the
values from `cboState` select element. (For example 2 is not a valid value)
But this is right in your example so the second point is not to have
parameters in your post request which are not valid. Meaning in this example
you shouldn't add `cboCity` when you post to `__EVENTTARGET` cboState.
Long story short you need to use this form fields:
FORM_FIELDS = {
'__EVENTTARGET': 'cboState',
'__EVENTARGUMENT': '',
'__LASTFOCUS': '',
'__VIEWSTATE': view_state,
'__VIEWSTATEGENERATOR': view_state_generator,
'__EVENTVALIDATION': event_validation,
'cboState': '3',
'hdDealerMaps': 'True',
}
The updated version of the script:
<https://gist.github.com/fliiiix/ea365b96f5ab4ec4d345>
|
python apscheduler, an easier way to run jobs?
Question: I have jobs scheduled thru `apscheduler`. I have 3 jobs so far, but soon will
have many more. i'm looking for a way to scale my code.
Currently, each job is its own `.py` file, and in the file, I have turned the
script into a function with `run()` as the function name. Here is my code.
from apscheduler.scheduler import Scheduler
import logging
import job1
import job2
import job3
logging.basicConfig()
sched = Scheduler()
@sched.cron_schedule(day_of_week='mon-sun', hour=7)
def runjobs():
job1.run()
job2.run()
job3.run()
sched.start()
This works, right now the code is just stupid, but it gets the job done. But
when I have 50 jobs, the code will be stupid long. How do I scale it?
note: the actual names of the jobs are arbitrary and doesn't follow a pattern.
The name of the file is `scheduler.py` and I run it using
`execfile('scheduler.py')` in python shell.
Answer:
import urllib
import threading
import datetime
pages = ['http://google.com', 'http://yahoo.com', 'http://msn.com']
#------------------------------------------------------------------------------
# Getting the pages WITHOUT threads
#------------------------------------------------------------------------------
def job(url):
response = urllib.urlopen(url)
html = response.read()
def runjobs():
for page in pages:
job(page)
start = datetime.datetime.now()
runjobs()
end = datetime.datetime.now()
print "jobs run in {} microseconds WITHOUT threads" \
.format((end - start).microseconds)
#------------------------------------------------------------------------------
# Getting the pages WITH threads
#------------------------------------------------------------------------------
def job(url):
response = urllib.urlopen(url)
html = response.read()
def runjobs():
threads = []
for page in pages:
t = threading.Thread(target=job, args=(page,))
t.start()
threads.append(t)
for t in threads:
t.join()
start = datetime.datetime.now()
runjobs()
end = datetime.datetime.now()
print "jobs run in {} microsecond WITH threads" \
.format((end - start).microseconds)
|
Are True, False, None keywords or built-ins in Python 3?
Question: So, in Python 2 it was clear. But in Python 3 I'm a little bit confused.
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>> import keyword
>>> dir(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
_True_ , _False_ and _None_ are present in both the _builtins_ module and the
_keywords_ module. Then how should I treat them? As a builtin classes or as a
keywords?
Answer: They are reserved words _and_ built-in values. From the [Python 3 What's
New](https://docs.python.org/3/whatsnew/3.0.html#changed-syntax):
> `True`, `False`, and `None` are reserved words. (2.6 partially enforced the
> restrictions on `None` already.)
This means you cannot use them as names, assigning a different value to them.
This prevents accidentally masking the built-in singleton values:
>>> True = False
File "<stdin>", line 1
SyntaxError: can't assign to keyword
Also see [Guido van Rossum's history lesson on `None`, `True` and
`False`](http://python-history.blogspot.co.uk/2013/11/story-of-none-true-
false.html):
> I still forgot to answer whether None/True/False are literals or keywords.
> My answer is that they are both. They are keywords because that's how the
> parser recognizes them. They are literals because that's their role in
> expressions and because they stand for constant values.
With `True`, `False` and `None` classified as keywords, the Python compiler
can actually optimize their use, since you cannot (directly) rebind these
names Python can look them up as constants instead of globals, which is
faster.
Until Python 3.4 there were still some corner cases where the compiler would
issue a global lookup for these objects, see [issue
16619](http://bugs.python.org/issue16619). From Python 3.4 onwards the Python
parser has been extended to produce a new AST node `NameConstant` to ensure
that they are treated as constants everywhere.
|
Turn a string with nested parenthesis into a nested list, python
Question: There are other questions referring to this on Stack Overflow such as [how-to-
parse-a-string-and-return-a-nested-
array?](http://stackoverflow.com/questions/17140850/how-to-parse-a-string-and-
return-a-nested-array?lq=1)
But they all refer to lists in the format of `((abc)de(fg)))`. going to the
form:`[['a','b','c']'d','e'['f','g',]]]` I have a list of the form:
((wordOneWord2)OtherWord(FinalWord)))
By using the methods I learnt from the other questions by nested list was of
the form:
[['w','o','r','d','O','n','e','W','o','r','d','2']'O','t','h','e','r','W','o','r','d',['F','i','n','a','l','W','o','r','d']]]
rather than the desired
[['wordOneWord2'], 'OtherWord', ['FinalWord']]
I can achieve the desired result by parsing the list letter by letter and then
concatenating the items within each list back together but it takes more code
than I think necessary, is there a faster way of doing this?
Answer: Based on this [solution by
falsetru](http://stackoverflow.com/a/17141899/190597):
import re
def parse_nested(text, left=r'[(]', right=r'[)]', sep=r','):
""" Based on http://stackoverflow.com/a/17141899/190597 (falsetru) """
pat = r'({}|{}|{})'.format(left, right, sep)
tokens = re.split(pat, text)
stack = [[]]
for x in tokens:
if not x or re.match(sep, x): continue
if re.match(left, x):
stack[-1].append([])
stack.append(stack[-1][-1])
elif re.match(right, x):
stack.pop()
if not stack:
raise ValueError('error: opening bracket is missing')
else:
stack[-1].append(x)
if len(stack) > 1:
print(stack)
raise ValueError('error: closing bracket is missing')
return stack.pop()
text = '((wordOneWord2)OtherWord(FinalWord))'
print(parse_nested(text))
# [[['wordOneWord2'], 'OtherWord', ['FinalWord']]]
|
Make a Progress Counter in Concurrent Python
Question:
from multiprocessing import Process, Pool
from bs4 import BeautifulSoup
alreadyProcessedFile = 0.0
processLength = 0.0
def convertedFile(filePath):
fileName = os.path.basename(filePath).split('.')[0]
print("Total: "+str(processLength)+", current: "+str(alreadyProcessedFile)
+ ", percentage: "+ str((alreadyProcessedFile+1.0)/(processLength+1)))
#business logic
print("One file is saved at the location: "+r'E:\xxx\SECProject\ProcessedSEC10KFiles\2012QTR1/'+fileName+'-finalDoc.txt')
def getFilePath(path):
return glob.glob(os.path.join(path, '*.txt'))
if __name__ == '__main__':
s = r"E:\xxx\SECProject\SEC10KFiles\2012QTR1"
fileList = getFilePath(s)
processLength = len(fileList)
p = Pool(40)
p.map(convertedFile, fileList)
This is basically a shortened version of the python program. I don't have a
wrapper class outside and I want to have a counter inside to keep track of the
progress (so I know when the program will stop). However the program (`def
covertedFile()` have a problem accessing the changed variables:
`alreadyProcessedFile` and `processLength`)
I know concurrency might have problems with shared state, but how can you
accomplish a counter without some degree of shared state?? And why can't the
concurrent function access the variable outside of it?
* * *
Also as weird as it may sound, this concurrent version program can't process
all files (about 5000 of them) under one directory. I wonder if the program is
shut down while some processes are still running. Is this a possibility?
Answer: `multiprocessing` creates a _copy_ of the memory for each process at the time
you start the new processes. Sharing state via module-level globals doesn't
work because every process gets it's own "snapshot" of the globals at the time
you fork the process. Changing one processes' globals doesn't magically
propagate to other processes.
If you need to share state between processes, you need to use one of the tools
that `multiprocessing` gives to you. You can share c types via `Value` or
`Array`, or use `Manager` to share arbitrary data types. See [sharing state
between
processes](https://docs.python.org/2/library/multiprocessing.html#sharing-
state-between-processes) in the docs for details and examples.
|
Print out array items greater than a specific Value in Python
Question: I am trying to print out values greater than 100000 on an array MSLP But I
keep on getting this error :The truth value of an array with more than one
element is ambiguous. Use a.any() or a.all()
Here is my code:
import numpy as np
import netCDF4
from numpy import *
from netCDF4 import Dataset
ncfile= Dataset('test.nc','r')
lat =ncfile.variables['lat'][:]
lon =ncfile.variables['lon'][:]
time =ncfile.variables['time'][:]
MSLP =ncfile.variables['PSL'][:]
for item in MSLP:
if item>100000:
print item
Answer: The error gives the answer:
> The truth value of an array with more than one element is ambiguous
When you do `if item>100000:`, `item` is an array of truth values--not a
single element.
If you want the values, you can use
[`numpy.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html):
MSLP[numpy.where(MSLP > 100000)]
Remember: prefer the numpy functions over iterating through arrays whenever
possible.
|
How can i move python functions into different .py file?
Question: i want to move functions because of lot of files, into separate python files.
But if i do it, it dont work.
I tried:
File: server.py:
import os, cherrypy, json
from customers.py import *
class application(object):
def get_webpage(self):
....
def get_data(self):
....
File: customers.py:
import os, cherrypy, json
def get_customer_data(self):
....
I use the python as server, the data in the function: get_customer_data is in
this case not processed, get a 404 Not Found, means the function is not
included in main file (server.py)
Answer: I removed the self from get_webpages() because it was not indented, which
means it was not part of the class.
application.py:
class application(object):
def __init__(self):
pass
def get_webpage():
print('From application')
customers.py:
from application import *
get_webpage() # From application
You could indent get_webpages() and make it part of the class. The way you
call it would change. (I put the self back and capitalized the name of the
class.)
application.py:
class Application(object):
def __init__(self):
pass
def get_webpage(self):
print('From application')
customers.py:
from application import *
a = Application()
a.get_webpage() # From application
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.