text
stringlengths 226
34.5k
|
---|
In Python is there a history of the function that i ran?
Question: After writing for a long time tons of stuff i've deleted a certain function...
CTRL + y couldn't save me. basically i had:
def foo(todo):
print 'how why where'
in a .py file, i have deleted function and its is not traceable from the file.
Since ipython ran the function, and interpreter is still live, is there a way
to watch the history of the interpreter running the function? I managed to
find the function name by the command:
history
also from [Export Python interpreter history to a
file?](http://stackoverflow.com/questions/8421097/export-python-interpreter-
history-to-a-file):
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
but it also the same as plain history The real question is where is the
history, or trace, from which python can relaunch a function even if the file
was deleted as long as the session of the interpreter is alive. I can run the
function again & again, because it is complied somewhere.
Thanks!
Answer: All you have available at this point is the compiled code. You can disassemble
that into a readable byte code listing, and that may help you to reconstruct
the original source. It will be hard work, because the byte codes are quite
low level, but it may be better than nothing.
import dis
dis.disassemble(foo.__code__)
The result looks like this:
2 0 LOAD_CONST 1 ('how why where')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
|
python csv writer is adding quotes when not needed
Question: I am having issues with writing json objects to a file using csv writer, the
json objects seem to have multiple double quotes around them thus causing the
json objects to become invalid, here is the result:
"{""user.CustomAttribute.ISOLanguageCode"": ""en"", ""user.Email"": ""[email protected]""
what I want is
{"user.CustomAttribute.ISOLanguageCode": "en", "user.Email"": "[email protected]"}
here is how I open the file, perhaps there is an argument I can pass to
prevent this from happening?
file = csv.writer(open(localResultPath + ".txt",'ab'),delimiter = '|')
here is how I write to the file, the last append adds the json as a string
list.append(pk)
list.append(email)
list.append(json)
file.writerow(list)
Answer: Switch off auto-quoting with `quoting=csv.QUOTE_NONE`, and set `quotechar` to
the empty string:
file = csv.writer(open(localResultPath + ".txt",'ab'),
delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
Even with `csv.QUOTE_NONE` the `csv.writer()` will still want to quote the
`quotechar` if left set to anything but an empty string, if present in the
value. The default quote character is `"` and JSON values are full of those.
Demo:
>>> from cStringIO import StringIO
>>> import csv
>>> f = StringIO()
>>> writer = csv.writer(f, delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
>>> writer.writerow(['{"user.CustomAttribute.ISOLanguageCode": "en"}'])
>>> f.getvalue()
'{"user.CustomAttribute.ISOLanguageCode": "en"}\r\n'
|
What is the most appropriate way to pass objects between modules in python?
Question: I have to access an object in a module from another module:
module_1.py:
import module_2
class A():
def __init__():
do_sth()
class B():
def __init__():
do_sth()
self.x = some_object()
do_sth_else(x)
def show():
show_gui()
def start():
y = B()
y.show()
if __name__ == "__main__":
start()
module_2.py:
def run_it(arg):
run_run_run()
I need `self.x` object from `module_1` so that I can pass it as an argument to
`run_it()` function in `module_2`. Note that `module_1` also imports
`module_2`.
Is there a conventional method to access objects in other modules?
Answer: Now with your corrections, it looks like you want something like this:
from module_1 import B
run_it(B().x)
Which raises a question: If `x` is the same for all objects of `B`, why not
make it a class member instead of an instance member. Something like:
class B:
x = some_object()
def __init__(self):
do_sth()
do_sth_else(B.x)
def show(self):
show_gui()
And in the other module
run_it(B.x)
* * *
Addressing your comment: `y` is local to `start`. You will need to return it:
def start():
y = B()
y.show()
return y
And then
run_it(start())
* * *
Also `y.show()` will fail horribly as `show` doesn't accept parameters and
will get passed `y` as `self`.
|
Python: Trying to shift data in CSV but not seeing desired results
Question: I'm having trouble with a relatively simple problem.. I have some data like so
in CSV:
period, reading
1, 3
2, 4
3, 5
4, 2
5, 2
I simply want the second column to shift up by one, while the first column
stays the same. After the second column shifts up by one, I would like the
last value to be replaced with a random value in the range -5, 5 (hopefully
you can see this from my script).
import csv
import random
directory = r"C:/Program Files (x86)/CM/data.csv"
with open(directory, 'r') as csvfile:
s = csvfile.readlines()
dataCSV = []
for i, point in enumerate(s[1:]):
seperatedPoint = point.strip("\n").split(",")
if len(seperatedPoint) == 2:
dataCSV.append([int(dataPoint) for dataPoint in seperatedPoint])
l = len(dataCSV)
for i in range(l-1):
dataCSV[i][1] = dataCSV[i+1][1]
dataCSV[l-1][1] += random.randint(-5,5)
with open(directory, 'w') as csvfile: #opens the file for writing
output = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
output.writerow(["period", "reading"])
header = (["period", "reading"])
print( ", ".join( str(e) for e in header ) )
print ""
for point in dataCSV:
output.writerow(point)
print( ", ".join( str(e) for e in point ) )
print ""
However instead of shifting up by one, this is just spitting out a the same
value a ton of times in the second column.. It will then change values and
spit out a ton of those repeated values as well, until I get to the end of my
range. I can't figure out what I'm doing wrong. Any help is appreciated, thank
you.
Answer:
import pandas as pd
import random
random.seed(time.time())
df = pd.read_csv(filename)
df[col] = df[col].shift(-1)
df.iloc[-1][col] = random.randint(-5, 5)
df.to_csv(outfile)
|
Recovering memory scipy interpolation
Question: I am using scipy's LinearNDInterpolator from the interpolate module, and I'm
losing memory somewhere. It would be great if someone could tell me how to
recover it. I'm doing something like the following (where I've tracked memory
usage on the side):
import numpy as np
from scipy import interpolate as irp # mem: 14.7 MB
X = np.random.random_sample( (2**18,2) ) # mem: 18.7 MB
Y = np.random.random_sample( (2**18,1) ) # mem: 20.7 MB
f = irp.LinearNDInterpolator( X, Y ) # mem: 85.9 MB
del f # mem: 57.9 MB
The interpolation I'm doing is much smaller but many times leading to an
eventual crash. Can anyone say where this extra memory is hanging out and how
I can recover it?
# Edit 1:
output of [memory_profiler](https://pypi.python.org/pypi/memory_profiler):
Line # Mem usage Increment Line Contents
================================================
4 15.684 MiB 0.000 MiB @profile
5 def wrapper():
6 19.684 MiB 4.000 MiB X = np.random.random_sample( (2**18,2) )
7 21.684 MiB 2.000 MiB Y = np.random.random_sample( (2**18,1) )
8 86.699 MiB 65.016 MiB f = irp.LinearNDInterpolator( X, Y )
9 58.703 MiB -27.996 MiB del f
# Edit 2:
The actual code I'm running is below. Each xtr is (2*w^2,w^2) uint8. It works
until I get to w=61, but only if I run each w separately (so r_[21] ... r_[51]
and running each). Strangely, each less than 61 still hogs all the memory, but
its not until 61 that it bottoms out.
from numpy import *
from scipy import interpolate as irp
for w in r_[ 21:72:10 ]:
print w
t = linspace(-1,1,w)
xx,yy = meshgrid(t,t)
xx,yy = xx.flatten(), yy.flatten()
P = c_[sign(xx)*abs(xx)**0.65, sign(yy)*abs(yy)**0.65]
del t
x = load('../../windows/%d/raw/xtr.npy'%w)
xo = zeros(x.shape,dtype=uint8)
for i in range(x.shape[0]):
f = irp.LinearNDInterpolator( P, x[i,:] )
out = f( xx, yy )
xo[i,:] = out
del f, out
save('../../windows/%d/lens/xtr.npy'%w,xo)
del x, xo
It errors on 61 with this message:
Python(10783) malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
File "make_lens.py", line 16, in <module>
f = irp.LinearNDInterpolator( P, x[i,:] )
File "interpnd.pyx", line 204, in scipy.interpolate.interpnd.LinearNDInterpolator.__init__ (scipy/interpolate/interpnd.c:3794)
File "qhull.pyx", line 1703, in scipy.spatial.qhull.Delaunay.__init__ (scipy/spatial/qhull.c:13267)
File "qhull.pyx", line 1432, in scipy.spatial.qhull._QhullUser.__init__ (scipy/spatial/qhull.c:11989)
File "qhull.pyx", line 1712, in scipy.spatial.qhull.Delaunay._update (scipy/spatial/qhull.c:13470)
File "qhull.pyx", line 526, in scipy.spatial.qhull._Qhull.get_simplex_facet_array (scipy/spatial/qhull.c:5453)
File "qhull.pyx", line 594, in scipy.spatial.qhull._Qhull._get_simplex_facet_array (scipy/spatial/qhull.c:6010)
MemoryError
# Edit 3:
A link to code like identical to above, but independent of my data:
<http://pastebin.com/BKYzVVTS>
I receive the same error as above. I'm on a intel core 2 duo macbook with 2GB
of RAM. The read x, and write xo combine only to ~53MB, yet memory usage
crawls far beyond what is needed as the loop progresses.
Answer: This issue was fixed in a later version of SciPy which I was not using:
<https://github.com/scipy/scipy/issues/3471>
|
Python parsing set-cookie header
Question: In PHP I send one cookie with secure and http only flags, and other without
setcookie("c2","value");
setcookie("c1","value", 0, "/", "", true, true);
It produces header
Set-Cookie: c2=value, c1=value; path=/; secure; httponly
In firebug I can see, this is OK (c1 secure flag is True, c2 is False)
I want to get which one of them is not using secure flag My python code:
cookies = Cookie.SimpleCookie()
cookies.load(headers['set-cookie'])
print cookies
Output:
Set-Cookie: c1=value; Path=/\\r\\nSet-Cookie: c2=value
headers['set-cookie'] **does** contain original set-cookie header, it's ok
According to python documentation printing(handling as string) SimpleCookie
instance should create set-cookie header. Point is, that something is missing
after parsing original header. Morsels also contains wrong values (secure and
http only).
Is this some kind of misconfiguration or it's a bug in python library ? Thanks
:)
Answer: This might be a bit late but saw your question and thought you may still need
help. The code I use to read a cookie is:
import Cookie,os
def getCookieData():
try:
cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
session = cookie['usrSession'].value
return session
except (Cookie.CookieError, KeyError):
return None
My cookie string its something along the lines of:
Cookie: usrSession=12345
Hope this helps
|
Console column output in python3
Question: I am trying to create to create a column output for a few lists that differ in
lengths, e.g:
list1 = ['hello', 'hello', 'hello', 'hello', 'hello', 'goodbye']
list2 = ['hello', 'hello', 'hello']
list3 = ['hello', 'hello', 'hello', 'hello']
desired output:
hello hello hello
hello hello hello
hello hello hello
hello hello
hello
goodbye
The individual lists can be quite long, and the lists are linked in a way as
we are doing matching of items in the lists and printing matches etc. Hence
the need to do it in column format.
I've worked out how to do everything else, apart from printing the desired
output.
I have played around with zip, but from my limited experience it does not seem
to like lists of different lengths, but I could be doing it all wrong of
course. ;-)
Basically I'm stuck. :-(
Answer: Indeed, zip only pairs items up to the shortest iterator. What you are looking
for is
itertools.zip_longest
That would pair elements from different iterators and use a fillvalue for when
the iterators fall short.
For instance:
from itertools import zip_longest
for elems in zip_longest(list1, list2, list3):
for e in elems:
print(e or '\t', end=" ")
print()
|
Failed testing on Ubuntu 12.04
Question: After installing the scikit-learn from source code of version 0.14.1 by 'sodu
python setup.py install', I tested the package by 'nosetests sklearn --exe',
and received the following information:
==================================================================================
/home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/feature_selection/selector_mixin.py:7: DeprecationWarning: sklearn.feature_selection.selector_mixin.SelectorMixin has been renamed sklearn.feature_selection.from_model._LearntSelectorMixin, and this alias will be removed in version 0.16
DeprecationWarning)
/home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/pls.py:7: DeprecationWarning: This module has been moved to cross_decomposition and will be removed in 0.16
"removed in 0.16", DeprecationWarning)
.......S................../home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/cluster/hierarchical.py:746: DeprecationWarning: The Ward class is deprecated since 0.14 and will be removed in 0.17. Use the AgglomerativeClustering instead.
"instead.", DeprecationWarning)
.........../usr/lib/python2.7/dist-packages/numpy/distutils/system_info.py:1423: UserWarning:
Atlas (http://math-atlas.sourceforge.net/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [atlas]) or by setting
the ATLAS environment variable.
warnings.warn(AtlasNotFoundError.__doc__)
.............................................../home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/manifold/spectral_embedding_.py:226: UserWarning: Graph is not fully connected, spectral embedding may not work as expected.
warnings.warn("Graph is not fully connected, spectral embedding"
..................................SS..............S.................................................../home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/utils/extmath.py:83: NonBLASDotWarning: Data must be of same type. Supported types are 32 and 64 bit float. Falling back to np.dot.
'Falling back to np.dot.', NonBLASDotWarning)
....................../home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/decomposition/fastica_.py:271: UserWarning: Ignoring n_components with whiten=False.
warnings.warn('Ignoring n_components with whiten=False.')
..................../home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/utils/extmath.py:83: NonBLASDotWarning: Data must be of same type. Supported types are 32 and 64 bit float. Falling back to np.dot.
'Falling back to np.dot.', NonBLASDotWarning)
....................................S................................../home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/externals/joblib/test/test_func_inspect.py:134: UserWarning: Cannot inspect object <functools.partial object at 0xbdebf04>, ignore list will not work.
nose.tools.assert_equal(filter_args(ff, ['y'], (1, )),
FAIL: Check that gini is equivalent to mse for binary output variable
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/elkan/Downloads/MS2PIP/scikit-learn/sklearn/tree/tests/test_tree.py", line 301, in test_importances_gini_equal_mse
assert_almost_equal(clf.feature_importances_, reg.feature_importances_)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 452, in assert_almost_equal
return assert_array_almost_equal(actual, desired, decimal, err_msg)
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 800, in assert_array_almost_equal
header=('Arrays are not almost equal to %d decimals' % decimal))
File "/usr/lib/python2.7/dist-packages/numpy/testing/utils.py", line 636, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not almost equal to 7 decimals
(mismatch 70.0%)
x: array([ 0.2925143 , 0.27676187, 0.18835709, 0.04181255, 0.03699054,
0.01668818, 0.03661717, 0.03439216, 0.04422749, 0.03163866])
y: array([ 0.29599052, 0.27676187, 0.19146823, 0.03837769, 0.03699054,
0.01811955, 0.0362238 , 0.03439216, 0.04137032, 0.03030531])
>> raise AssertionError('\nArrays are not almost equal to 7 decimals\n\n(mismatch 70.0%)\n x: array([ 0.2925143 , 0.27676187, 0.18835709, 0.04181255, 0.03699054,\n 0.01668818, 0.03661717, 0.03439216, 0.04422749, 0.03163866])\n y: array([ 0.29599052, 0.27676187, 0.19146823, 0.03837769, 0.03699054,\n 0.01811955, 0.0362238 , 0.03439216, 0.04137032, 0.03030531])')
----------------------------------------------------------------------
Ran 3950 tests in 150.890s
FAILED (SKIP=19, failures=1)
==================================================================================
The python version is 2.7.3, OS is 32 bit. So, what the problem might be?
Thanks.
Answer: It's a numerical precision discrepancy on 32 bit platforms. You can safely
ignore it as the failing test is checking the values of the attribute
`clf.feature_importances_` of a random forest which usually do not need to be
precise to be useful (interpretation of the most important features
contributing to the RF model).
|
Pillow keeps throwing cannot identify image file on Window in Python2.7.6
Question: I'm using Python2.7.6 and Pillow 2.3.0 on 32 bits Windows. And I do **not**
have PIL installed on my machine.
My problem is when I do following I get _"cannot identify image file"_ error.
>>> from PIL import Image
>>> file = open(r"C:\\a.jpg", 'r')
>>> image = Image.open(file)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\pillow-2.3.0-py2.7-win32.egg\PIL\Image.py", line 2025, in open
IOError: cannot identify image file
But this works if I don't _"Open"_ the file before opening it with
`Image.Open`:
>>> image2 = Image.open(r"C:\\a.jpg", 'r')
NOTE: I cannot omit the _"Open"_ statement.
Does anyone know what may be causing this strange behavior?
Thanks, in advance!
Answer: Don't do `image = Image.open(file)` , you already opened the file.
Try `image = Image.open("C:\\a.jpg")`
Here is the Image module: <http://effbot.org/imagingbook/image.htm>
**EDIT:**
**Use 'rb' instea of 'r'** when opening the file
|
Using id (Primary Key) of a Model as ForeignKey when creating new model instances in Django through shell
Question: For illustration purposes, just two plain models:
class PrimaryModel(models.Model):
foo = models.CharField(max_length=50, unique=True)
class SecondaryModel(models.Model):
bar = models.ForeignKey(PrimaryModel)
Now trying to create instances in shell:
>>> import testapp.models
>>> a=testapp.models.PrimaryModel(foo="Test1")
>>> a.save()
>>> b=testapp.models.SecondaryModel(bar=1)
... and of course the error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/pkaramol/Workspace/django-env/lib/python3.3/site-packages/django/db/models/base.py", line 405, in __init__
setattr(self, field.name, rel_obj)
File "/home/pkaramol/Workspace/django-env/lib/python3.3/site-packages/django/db/models/fields/related.py", line 337, in __set__
self.field.name, self.field.rel.to._meta.object_name))
ValueError: Cannot assign "1": "SecondaryModel.bar" must be a "PrimaryModel" instance.
The question is why can't we use the id of the PrimaryModel (as in the
erroneous example above) and we have to use an instance? Have also tried to
use the `to_field` field as in
class SecondaryModel(models.Model):
bar = models.ForeignKey(PrimaryModel, to_field='foo')
but that did not change the situation.
Answer: If you want to use id of a PrimaryModel you should do it like this:
b=testapp.models.SecondaryModel(bar_id=1)
|
Multiple Instantiation of Programs interacting with one another (Python2.7 & Tkinter)
Question: I currently have a restaurant simulation program, GUI by Tkinter and I was
finding a way to allow multiple instantiation of the programs to interact with
one another in the sense of updating its key variables. (Sorry for my poor
English)
Let's say:
* Five Users have opened this program at the same time using same PC. (Hypothetical)
* There are three functions in the program, namely `Order`, `See Inventory` ,and `See Sales`
* Assume that all five have made an order
Now, the restaurant must keep track of the orders made, and the inventory to
cook the food.
I tried coding the program by using `txt` file import and export to keep track
of the data but it was just now that I realized the `txt` file can be edited
by programs ONE AT THE TIME. (Cannot edit single `txt` file at once)
Q: What is the better approach in saving the values of the variables used in
the program so that multiple users can use the program with real-time updated
values of the variables?
* Someone told me that I could try using `Global` variables. But how could I possible assign values to them and keep them updated? (Local variables get initialized everytime when the program ran)
Thank you for reading my Question!
Answer: You could use the `sqlite3` module to create a light-weight database. This
does not need a server program; the database manager is in the Python standard
library. Multiple instances would read/write to the same file database and
sqlite would take care of ensuring consistency.
However, please note that there is a [5-second global lock on most sqlite
implementations](http://beets.radbox.org/blog/sqlite-nightmare.html), so any
of your multiple instances _must_ complete its read/write in less than that
time or it will cause a 'database locked' exception in the other instances.
Here you have an example:
import sqlite3 as lite
import time
con = lite.connect('common.db')
cur = con.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS restaurant (orderId INT primary key, inventory TEXT, sales INT);")
for i in range(5):
print "About to insert on ID: %s" % i
cur.execute("INSERT INTO restaurant VALUES(%d, 'burger', 1)" % i)
time.sleep(1)
con.close()
If you execute this code on two terminals at the same time, you will notice:
1. a 'common.db' file is created
2. one of both executions advances freely; the other advances to the point "About to insert on ID: 0" and then gets locked until the first one is completed.
|
GridSpec with shared axes in Python
Question: [This solution](http://stackoverflow.com/a/19627237/283296) to another thread
suggests using `gridspec.GridSpec` instead of `plt.subplots`. However, when I
share axes between subplots, I usually use a syntax like the following
fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))
How can I specify `sharex` and `sharey` when I use `GridSpec` ?
Answer: First off, there's an easier workaround for your original problem, as long as
you're okay with being slightly imprecise. Just reset the top extent of the
subplots to the default _after_ calling `tight_layout`:
fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall title', size=20)
fig.tight_layout()
fig.subplots_adjust(top=0.9)
plt.show()

* * *
However, to answer your question, you'll need to create the subplots at a
slightly lower level to use gridspec. If you want to replicate the hiding of
shared axes like `subplots` does, you'll need to do that manually, by using
the `sharey` argument to
[`Figure.add_subplot`](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.add_subplot)
and hiding the duplicated ticks with `plt.setp(ax.get_yticklabels(),
visible=False)`.
As an example:
import matplotlib.pyplot as plt
from matplotlib import gridspec
fig = plt.figure()
gs = gridspec.GridSpec(1,2)
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharey=ax1)
plt.setp(ax2.get_yticklabels(), visible=False)
plt.setp([ax1, ax2], title='Test')
fig.suptitle('An overall title', size=20)
gs.tight_layout(fig, rect=[0, 0, 1, 0.97])
plt.show()

|
How do i interpret inline javascript code in python on GAE?
Question: I'm in use python based on GAE (Google App Engine) and want to interpret
inline javascript code.
like as a SpiderMonkey(<https://code.google.com/p/python-spidermonkey>),
> from spidermonkey import Runtime
> rt = Runtime()
> cx = rt.new_context() cx.eval_script("1 + 2") + 3
>
> class Foo:
>
>> def hello(self):
> print "Hello, Javascript world!"
>
> cx.bind_class(Foo, bind_constructor=True)
> cx.eval_script("var f = new Foo(); f.hello();")
>
> f = cx.eval_script("f;")
> f.hello()
>
> # Hello, Javascript world!
how can i do it? or Is it possible to install a spidermonkey on GAE?
Thanks in advice!
Answer: You can't use it in appengine. If you look at the installation docs it says
"At present, you'll need a C compiler on your system to install this
extension, as well as the Pyrex package."
This sort of thing is not supported on appengine in the python SDK. It can
only have dependencies on supported 3rd party libraries and pure python code
that you supply.
Have a read of the python runtime on appengine docs
<https://developers.google.com/appengine/docs/python/#Python_The_sandbox>
and the 3rd party libs docs
<https://developers.google.com/appengine/docs/python/tools/libraries27>
Oh and this sort of question has been asked hundreds of times here. Whilst not
specific to the library in question SpiderMonkey, all ask the same thing, so
some searching in SO might save you some time.
|
How to solve a binary linear program with cvxopt? Python
Question: I know how to solve a linear program with cvxopt, but I don't know how to make
it when the variables are all 0 or 1 (binary problem). Here is my attempt
code:
#/usr/bin/env python3
# -*- coding: utf-8 -*-
from cvxopt.modeling import variable, op, solvers
import matplotlib.pyplot as plt
import numpy as np
x1 = variable()
x2 = variable()
x3 = variable()
x4 = variable()
c1 = (x1+x2+x3+x4 <= 2)
c2 = (-x1-x2+x3 <= 0)
c3 = (55*x1+40*x2+76*x3+68*x4 <= 200)
c4 = (x3+x4 <= 1)
#here is the problem.
c5 = (x1 == 0 or x1 == 1)
c6 = (x2 == 0 or x2 == 1)
c7 = (x3 == 0 or x3 == 1)
c8 = (x4 == 0 or x4 == 1)
lp1 = op(70*x1-60*x2-90*x3-80*x4, [c1, c2, c3, c4, c5, c6, c7, c8])
lp1.solve()
print('\nEstado: {}'.format(lp1.status))
print('Valor óptimo: {}'.format(-round(lp1.objective.value()[0])))
print('Óptimo x1: {}'.format(round(x1.value[0])))
print('Óptimo x2: {}'.format(round(x2.value[0])))
print('Óptimo x3: {}'.format(round(x3.value[0])))
print('Óptimo x4: {}'.format(round(x4.value[0])))
print('Mult óptimo primera restricción: {}'.format(c1.multiplier.value[0]))
print('Mult óptimo segunda restricción: {}'.format(c2.multiplier.value[0]))
print('Mult óptimo tercera restricción: {}'.format(c3.multiplier.value[0]))
print('Mult óptimo cuarta restricción: {}\n'.format(c4.multiplier.value[0]))
The result is:
pcost dcost gap pres dres k/t
0: -3.0102e-09 -2.0300e+02 2e+02 1e-02 8e-01 1e+00
1: -3.5175e-11 -2.4529e+00 2e+00 1e-04 1e-02 1e-02
2: 1.9739e-12 -2.4513e-02 2e-02 1e-06 1e-04 1e-04
3: 5.0716e-13 -2.4512e-04 2e-04 1e-08 1e-06 1e-06
4: -7.9906e-13 -2.4512e-06 2e-06 1e-10 1e-08 1e-08
Terminated (singular KKT matrix).
Estado: unknown
Valor óptimo: 0
Óptimo x1: 0
Óptimo x2: 0
Óptimo x3: 0
Óptimo x4: 0
Mult óptimo primera restricción: 1.1431670510974203e-07
Mult óptimo segunda restricción: 0.9855547161745738
Mult óptimo tercera restricción: 9.855074750509187e-09
Mult óptimo cuarta restricción: 2.5159510552878724e-07
I've read the cvxopt doc, but i don't find anything about binary linear
problems.
Answer: cvxopt cannot solve binary linear programs. Given the size of your problem you
could try writing your own little branch and bound algorithm:
1) Solve the linear program
2) pick a fractional solution variable x_f and create two new problem "leafs"
2a) problem 1) with additional constraint x_f <= 0
2b) problem 1) with additional constraint x_f >= 1
Repeat...
(or use Excel solver)
|
keeping "global" variables in flask blueprints
Question: Let's say I have a fairly basic main app then a series of Blueprints which
lead to other pages. I then have modules that will read a csv and use the data
to do the functions
from py_csv_entry import entry
class python_csv:
def __init__(self, csv_location):
self.data = []
self.read_csv(csv_location)
def read_csv(self):
with open(csv_location + 'python_csv.csv') as csv_data:
read = csv.reader(csv_data):
for row in read:
self.data.append(entry(*row))
I want to use this module in my blueprint to contain the data.
on an app, I would usually do:
app.config['python'] = python_csv('/path/to/file')
when I try to do this with the Blueprint, it raises the following error:
AttributeError: 'Blueprint' object has no attribute 'config'
in the terms of a blueprint, how would you bind a global variable?
Answer: If this is unchanging data that is just generally 'global', just keep it
global. Just put it in your module, read the CSV when the module loads, and
use that data.
Blueprints otherwise take their configuration from the app object;
configuration is stuff that changes from one application (site) from the next,
but lets you reuse your blueprints. As such configuration is tied to
applications, and blueprints merely read that configuration.
Blueprints are just groups of views, associated signal handlers
(`before_request`, `after_request`, etc.), letting you reuse that group or
easily disable the group of views as one. They still operate in the context of
a Flask application, so they will always have access to the application
configuration.
As such, if you want the path to the CSV module to be configurable, set _that_
in your application configuraton, and use the [`Blueprint.record_once()`
hook](https://flask.readthedocs.org/en/latest/api/#flask.Blueprint.record_once)
to read the CSV file based on the application configuration.
|
cpython vs cython vs numpy array performance
Question: I am doing some performance test on a variant of the prime numbers generator
from <http://docs.cython.org/src/tutorial/numpy.html>. The below performance
measures are with kmax=1000
Pure Python implementation, running in CPython: 0.15s
Pure Python implementation, running in Cython: 0.07s
def primes(kmax):
p = []
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
if i == k:
p.append(n)
k = k + 1
n = n + 1
return p
Pure Python+Numpy implementation, running in CPython: 1.25s
import numpy
def primes(kmax):
p = numpy.empty(kmax, dtype=int)
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
n = n + 1
return p
Cython implementation using int*: 0.003s
from libc.stdlib cimport malloc, free
def primes(int kmax):
cdef int n, k, i
cdef int *p = <int *>malloc(kmax * sizeof(int))
result = []
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
result.append(n)
n = n + 1
free(p)
return result
The above performs great but looks horrible, as it holds two copies of the
data... so I tried reimplementing it:
Cython + Numpy: 1.01s
import numpy as np
cimport numpy as np
cimport cython
DTYPE = np.int
ctypedef np.int_t DTYPE_t
@cython.boundscheck(False)
def primes(DTYPE_t kmax):
cdef DTYPE_t n, k, i
cdef np.ndarray p = np.empty(kmax, dtype=DTYPE)
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
n = n + 1
return p
Questions:
1. why is the numpy array so incredibly slower than a python list, when running on CPython?
2. what did I do wrong in the Cython+Numpy implementation? cython is obviously NOT treating the numpy array as an int[] as it should.
3. how do I cast a numpy array to a int*? The below doesn't work
cdef numpy.nparray a = numpy.zeros(100, dtype=int)
cdef int * p = <int *>a.data
Answer:
cdef DTYPE_t [:] p_view = p
Using this instead of p in the calculations. reduced the runtime from **580
ms** down to **2.8 ms** for me. About the exact same runtime as the
implementation using *int. And that's about the max you can expect from this.
DTYPE = np.int
ctypedef np.int_t DTYPE_t
@cython.boundscheck(False)
def primes(DTYPE_t kmax):
cdef DTYPE_t n, k, i
cdef np.ndarray p = np.empty(kmax, dtype=DTYPE)
cdef DTYPE_t [:] p_view = p
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p_view[i] != 0:
i = i + 1
if i == k:
p_view[k] = n
k = k + 1
n = n + 1
return p
|
Python - Adding a state to a program
Question: I have this program that's supposed to take a user's lowercase sentence and
capitalize it. There's currently two states, one that takes in the message
(which I think is referred to as sockCanSend) and the other that capitalizes
it (sockCanReceive). The problem is that I'm supposed to add another
method/state so that the program is only in the send state if the buffer is
completely empty and only goes to the receive state if the buffer is
completely full. The intermediate state should be accessed if the buffer is
only partially full. I think this intermediate state is supposed to continue
accepting input up until the buffer is completely full, at which point it
changes state to the send state. Meanwhile, I think it's supposed to keep
capitalizing the user's message so long as a message is received. If you're in
this state and the buffer is empty, there's some sort of problem and the
connection should terminate. The instructor for this course (it's a network
course) didn't explain any of this very well and I've tried talking to him
about it but his explanation still didn't make any sense. I figured that in
order to reach this new state I'd need a new method (sockCanSendOrRecv) but
that's about all I know. How can I add this new state?
from socket import *
from select import select
import sys # for exit
# select sets used to map sock#->function to call
rmap, wmap, xmap = {}, {}, {} # read, write, except.
stop = 0 # set to true when should stop (on socket failure)
# setup server socket
serverSock = socket(AF_INET, SOCK_STREAM) # ipv4, tcp
serverSock.bind(('', 2000)) # bind to port 2000
serverSock.listen(3) # up to 3 pending accepts
serverSock.setblocking(False) # non-blocking (readable means accept will succeed)
# constants for connection state
readState = 0 # when interested in reading
writeState = 1 # when interested in writing
readOrWriteState = 2 # when buffer is partially full
class connection:
def __init__(self, sock): # constructor
sock.setblocking(False)
print "new connection on fd %d" % sock.fileno()
self.sock = sock
self.buf = bytearray(1024)
self.fd = fd = sock.fileno()
self.state = readState
xmap[fd] = lambda : self.sockError() # call sockError on sock error
self.setSelect()
def sockCanReceive(self):
"called when socket is ready for pending read"
fd, buf = self.fd, self.buf
self.start = 0
self.nbytes = nbytes = self.sock.recv_into(buf, 1024)
print "rec'd %d bytes on fd %d: <%s>" % (self.nbytes, fd, buf[0:nbytes])
if nbytes != 0: # read succeeded
buf[0:nbytes] = str(buf[0:nbytes]).upper() # convert to uppercase
self.state = writeState
self.setSelect()
else: # socket closed
print "zero length read from %d. Assuming that other end is closed." % fd
self.close()
def sockCanSend(self):
"called when socket is ready for pending write"
fd = self.fd
start = self.start # first unsent
toSend = self.nbytes - start # number of bytes to send
sent = self.sock.send(self.buf[start:toSend])
self.start += sent
print "sent %d bytes of %d on fd %d" % (sent, toSend, fd)
if sent == toSend: # all sent, switching to receive
self.state = readState
self.setSelect()
def sockCanSendOrRecv(self):
"called when buffer is partially full"
def sockError(self):
"called when socket is in error condition"
fd = self.fd
print "socket error for %d. Shutting down."
self.close()
def close(self):
"close down this connection"
fd = self.fd
print "closing connection on fd %d" % fd
for x in rmap, wmap, xmap: # remove from select sets
if x.has_key(fd): del x[fd]
try:
self.sock.close()
except:
pass
def setSelect(self):
"set select read/write sensitivity based on connection state"
fd = self.fd
if self.state == readState:
rmap[fd] = lambda : self.sockCanReceive() # interested in reading
if wmap.has_key(fd): del wmap[fd] # not interested in writing
else: # writeState
wmap[fd] = lambda : self.sockCanSend() # interested in writing
if rmap.has_key(fd): del rmap[fd] # not interested in reading
def ssockAccept():
"called when a client has connected to server sock"
connSock, addr = serverSock.accept()
print "accepted connection on fd %d from %s" % (connSock.fileno(), addr)
connection(connSock)
def ssockPanic():
"called when the server socket has failed"
print "Panic: listener socket failed. Aborting."
sys.exit(1)
rmap[serverSock.fileno()] = ssockAccept # call ssockAccept() when client connects
xmap[serverSock.fileno()] = ssockPanic # call ssockPanic() if socket fails
# this is the main select loop
while not stop:
print "select(r=%s, w=%s, x=%s, 5s)" % (rmap.keys(), wmap.keys(), xmap.keys())
r,w,x = select(rmap.keys(), wmap.keys(), xmap.keys(), 5)
print "=======> returned: r=%s, w=%s, x=%s" % (r,w,x)
for fd in r:
rmap[fd]() # call read handler
for fd in w:
wmap[fd]() # call write handler
for fd in x:
xmap[fd]() # call eXception handler
Answer: > I figured that in order to reach this new state I'd need a new method
> (sockCanSendOrRecv) but that's about all I know.
You don't need a new method for the new state `readOrWriteState`; just extend
`setSelect` to handle the state - e. g.
def setSelect(self):
"set select read/write sensitivity based on connection state"
fd = self.fd
if self.state == readState:
rmap[fd] = lambda : self.sockCanReceive() # interested in reading
if wmap.has_key(fd): del wmap[fd] # not interested in writing
elif self.state == readOrWriteState:
rmap[fd] = lambda : self.sockCanReceive() # interested in reading
wmap[fd] = lambda : self.sockCanSend() # interested in writing
else: # writeState
wmap[fd] = lambda : self.sockCanSend() # interested in writing
if rmap.has_key(fd): del rmap[fd] # not interested in reading
\- and adapt `sockCanReceive` to set `state` to `readOrWriteState` as long as
the buffer is not full, `sockCanSend` to set `state` to `readOrWriteState` as
long as the buffer is not empty, and both `sockCanReceive` and `sockCanSend`
to be able to handle a partially full buffer.
|
BoxSizer in Frame and Panel
Question: When i create a BoxSizer like this:
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"App",size=(800,600),style= wx.SYSTEM_MENU | wx.CAPTION | wx.MINIMIZE_BOX | wx.CLOSE_BOX)
self.panel=wx.Panel(self,size=(800,600))
# create BoxSizer and fill it with elements
it works. But when I do this:
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"App",size=(800,600),style= wx.SYSTEM_MENU | wx.CAPTION | wx.MINIMIZE_BOX | wx.CLOSE_BOX)
panelThree(self)
class panelThree(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent,size=(800,600))
self.panel=wx.Panel(self,size=(800,600))
# create BoxSizer and fill it with elements
then something goes wrong: all elements are located in the top left corner and
they overlap each other. How do I have to use BoxSizer when I want to use it
in my class _panelThree_ ? I just took the example from here:
<http://wiki.wxpython.org/BoxSizerTutorial>
Answer: The problem is most likely that you are not adding the following widget to the
sizer: self.panel. If you do not add it to the sizer, then it's going to mess
up your layout. Personally, I don't think you even need a panel inside a
panel. Removing that line will fix the issue:
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
"App",size=(800,600),style= wx.SYSTEM_MENU | wx.CAPTION | wx.MINIMIZE_BOX | wx.CLOSE_BOX)
panelThree(self)
class panelThree(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent,size=(800,600))
self.panel=wx.Panel(self,size=(800,600))
# create BoxSizer and fill it with elements
sizer = wx.BoxSizer(wx.VERTICAL)
for item in range(10):
btn = wx.Button(self, label="Button %s" % item)
sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
self.SetSizer(sizer)
#----------------------------------------------------------------------
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
|
foreman start no module named myapp
Question: I'm following the heroku quick start guide here:
<https://devcenter.heroku.com/articles/getting-started-with-python>
and I'm stuck on the foreman start part. This is what my directory looks. I'm
just running a basic web app. No frameworks or anything.
soapbar/
Procfile.txt
soapbar/
soapbar.py
venv/
Include/
Lib/
Scripts/
This is the stack trace:
16:00:13 web.1 | started with pid 34135
16:00:13 web.1 | 2014-03-19 16:00:13 [34135] [INFO] Starting gunicorn 18.0
16:00:13 web.1 | 2014-03-19 16:00:13 [34135] [INFO] Listening at: http://0.0.0.0:5000 (34135)
16:00:13 web.1 | 2014-03-19 16:00:13 [34135] [INFO] Using worker: sync
16:00:13 web.1 | 2014-03-19 16:00:13 [34138] [INFO] Booting worker with pid: 34138
16:00:13 web.1 | 2014-03-19 16:00:13 [34138] [ERROR] Exception in worker process:
16:00:13 web.1 | Traceback (most recent call last):
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker
16:00:13 web.1 | worker.init_process()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process
16:00:13 web.1 | self.wsgi = self.app.wsgi()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi
16:00:13 web.1 | self.callable = self.load()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load
16:00:13 web.1 | return self.load_wsgiapp()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp
16:00:13 web.1 | return util.import_app(self.app_uri)
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app
16:00:13 web.1 | __import__(module)
16:00:13 web.1 | ImportError: No module named soapbar
16:00:13 web.1 | Traceback (most recent call last):
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker
16:00:13 web.1 | worker.init_process()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process
16:00:13 web.1 | self.wsgi = self.app.wsgi()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi
16:00:13 web.1 | self.callable = self.load()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load
16:00:13 web.1 | return self.load_wsgiapp()
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp
16:00:13 web.1 | return util.import_app(self.app_uri)
16:00:13 web.1 | File "/Users/ranuka/soapbar/venv/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app
16:00:13 web.1 | __import__(module)
16:00:13 web.1 | ImportError: No module named soapbar
16:00:13 web.1 | 2014-03-19 16:00:13 [34138] [INFO] Worker exiting (pid: 34138)
16:00:13 web.1 | 2014-03-19 16:00:13 [34135] [INFO] Shutting down: Master
16:00:13 web.1 | 2014-03-19 16:00:13 [34135] [INFO] Reason: Worker failed to boot.
16:00:13 web.1 | exited with code 3
16:00:13 system | sending SIGTERM to all processes
SIGTERM received
Any ideas?
Answer: Add a file named `__init__.py` to the `soapbar/` folder. Leave it empty.
> The `__init__.py` files are required to make Python treat the directories as
> containing packages; this is done to prevent directories with a common name,
> such as string, from unintentionally hiding valid modules that occur later
> on the module search path. In the simplest case, `__init__.py` can just be
> an empty file, but it can also execute initialization code for the package
> or set the `__all__` variable.
Source: <http://docs.python.org/2/tutorial/modules.html>
|
In Python: saving Unicode letters with newlines into a .txt so that it works fine while opening both using Excel and a text editor
Question: I want to save some unicode data into a .txt file, so that it looks OK while
opening the same file both in text editor and using Excel. Tried to
codecs.open() the txt file using different encodings, but this "codecs"
library does not show newlines, what is not OK while opening the txt file in
file explorer, however when I open it in Excel I can see newlines. But I also
need to see my unicode letters. I cannot manage to have both (unicode symbols
and newlines) in both ways of opening the txt file..
Answer: `codecs.open()` doesn't convert `'\n'` (newline) to `os.linesep` (`'\r\n'` on
Windows). You could try `io.open()` instead:
import io
with io.open(r'c:\path\to\output.txt', 'w', encoding='utf-8-sig') as file:
file.write(u"abc\n")
file.write(u"\u2744\n")
|
Django gives "GET /static/css/style.css HTTP/1.1" 304 0
Question: ok so My
Index.html is
<!DOCTYPE html>
<html>
<head>
<title>Kodeworms</title>
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" />
</head>
<body class="logged-out">
</body>
</html>
style.css
.logged-out {
background-image: href=("{{ STATIC_URL }}img/landing.jpg") no-repeat center 30px;
background-size: 90%;
}
Now my index.html is stored in ***project_name/project_name/templates*** and
my style.css is stored in ***project_name/assets/css*** and the image is
stored in ***project_name/assets/img***
my setting.py is
# Django settings for BE.
import os
import dj_database_url
here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
PROJECT_ROOT = here("..")
root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': dj_database_url.config()
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['http://serene-schubland-8864.herokuapp.com']
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Calcutta'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = root("..","..", "uploads")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = root("..","..", "static" )
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
root("..","assets"),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'j%ox@teo++vyzqfjfr@4trs&cx&2q52)ss$+ds*u=(u+!k#b@i'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'BE.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'BE.wsgi.application'
TEMPLATE_DIRS = (
root("templates"),
)
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'south',
)
LOCAL_APPS = (
'course',
)
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
What Should I do to get the image load in background from css ?
Answer: An HTTP 304 response means "I don't need to fetch it again, since it hasn't
changed since I got it last". So if that's the response code you got, you may
not have a problem at all. Or did you mean 404 (not found)?
In any event, you normally don't serve static files with Django directly; you
do it through your front-end server. On Heroku, they have a special app and
setup to help with that. You can read about it at:
<https://devcenter.heroku.com/articles/django-assets>.
Also: you accidentally posted your SECRET_KEY in your message here. Please
change that value to something else before you deploy or your site could have
a serious security vulnerability. Keep that secret key a secret.
|
Creating a threshold-coded ROC plot in Python
Question: R's [ROCR package](http://rocr.bioinf.mpi-sb.mpg.de) provides options for ROC
curve plotting that will color code and label threshold values along the
curve:

The closest I can get with Python is something like
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(qualityTrain.PoorCare, qualityTrain.Pred1)
plt.plot(fpr, tpr, label='ROC curve', color='b')
plt.axes().set_aspect('equal')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
which gives

Are there packages that provide functionality equivalent to R's ability to
label (using `print.cutoffs.at`) and color code (using `colorize`) thresholds?
Presumably this information is in `thresholds`, returned by
[`sklearn.metrics.roc_curve`](http://scikit-
learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html), but I
can't figure out how to use it to color code and label the figure.
Answer: Look at this gist:
<https://gist.github.com/podshumok/c1d1c9394335d86255b8>
roc_data = sklearn.metrics.roc_curve(...)
plot_roc(*roc_data, label_every=5)
|
How to get POST/GET data in python
Question: I'm trying to get POST/GET data in my python script. I'm using the web.py
framework and below is my code:
import web
form = web.input()
mydata = form.mydata
This is the error output im getting:
File "script.py", line 22, in <module>
form = web.input()
File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/webapi.py", line 330, in input
out = rawinput(_method)
File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/webapi.py", line 291, in rawinput
e = ctx.env.copy()
AttributeError: 'ThreadedDict' object has no attribute 'env'
(I'm used to getting these variables in PHP and am not sure why im having a
hard time with python)
Answer: In web.py you have to define a class for the URL and functions for GET and
POST within it. So then in the POST function of the URL class you can set form
= web.input(). Below is a quick example of this structure.
class Index:
def GET(self):
#Your GET code here...
def POST(self):
input = web.input()
|
urlopen with timeout fails behind proxy
Question: python 2.7.3 under linux: getting strange behaviour when trying to use the
timeout parameter
from urllib2 import urlopen, Request, HTTPError, URLError
url = "http://speedtest.website-solution.net/speedtest/random350x350.jpg"
try:
#f = urlopen(url, timeout=30) #never works - always times out
f = urlopen(url) #always works fine, returns after < 2 secs
print("opened")
f.close()
print("closed")
except IOError as e:
print(e)
pass
EDIT:
Digging into this more, it seems lower level.. the following code has the same
issue:
s = socket.socket()
s.settimeout(30)
s.connect(("speedtest.website-solution.net", 80)) #times out
print("opened socket")
s.close()
It's running behind a socks proxy. Running using `tsocks python test.py`.
Wonder if that can be screwing up the socket timeout for some reason? Seems
strange that `timeout=None` works fine though.
Answer: OK.. figured it out. This is indeed related to the proxy. No idea why, but the
following code seems to fix it:
Source: <https://code.google.com/p/socksipy-branch/>
Put this at the start of the code:
import urllib2
from urllib2 import urlopen, Request, HTTPError, URLError
import httplib
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.56.1", 101)
socks.wrapmodule(urllib2)
Now everything works fine..
|
How to deal with a lot variables access in different function/class in python
Question: The code which I wanna improved now looks something like below,
which f0 and f1(or more than 2 function) need the same variables.
I have to code about 50 lines to describe the variable setting at each
function. how can I do this more pythontic?
\--f0.py
import csv
def gen(csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# do sth in f0
xx = a + b
...
str = ...
return str
\--f1.py
import csv
def gen(csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
a = 1
b = 2
...
# do sth in f1
xx = a*b + b
...
str = ...
return str
\--genstr.py
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
* * *
(I don't really know how to use class, but I found this could help my problem
just describe maybe it will help understanding my question )
I try to do it with class, so i can access by inherit conf.
I know I can access by 'self.a', but is there any way I can direct use 'a' in
the function?
\--conf.py
class conf:
def __init__(self, csv_f):
# var define
for row in csv.DictReader(open(csv_f)):
c += row['x']
...
self.a = 1
self.b = 2
...
\--f0.py
import conf
class f0(conf):
def __init__(self):
config.__init__(self, csv_f) #this line is not correct
def gen():
# var set
c = self.c
a = self.a
b = self.b
# do sth in f0
xx = a + b
...
str = ...
return str
\--f1.py
import conf
class f1(conf):
def __init__(self):
config.__init__(self, csv_f) #this line is not correct
def gen():
# var set
c = self.c
a = self.a
b = self.b
# do sth in f1
xx = a + b
...
str = ...
return str
\--genstr.py
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0.gen(1)+f1.gen(1))
f.close()
Answer: The code is slightly confusing and i'm not sure what exactly you are trying,
but here are some general help.
This code:
for row in csv.DictReader(open(csv_f)):
c += row['x']
Will append the content of coloumn `x` to `c`.
import conf
class f0(conf):
def __init__(self, csv_f):
super(f0,self).__init__(self) # Fixed
self.csv_f = csv_f
def gen(self):
# var set
c = self.c #
a = self.a
b = self.b
# do sth in f0
xx = a + b
Instead of `c = self.c` you can use `self.c` where ever you need `c`.
from f0 import *
from f1 import *
f = open('xxx.x','w')
f.write(f0(filename).gen()+f1(filename).gen())
f.close()
|
OOP python program
Question:
from collections import Counter
class Runlength:
def __init__(self):
self.str = 0
def returner(self,str):
self.str = str
self.__str = ','.join(str(n) for n in self.__str)
self.__str = self.__str[::-1]
self.__str = self.__str.replace(',', '')
return self.__str
def final(self,num):
self.num = num
k = []
c = Counter(self.num).most_common()
for x in c:
k += x
return k
math = Runlength()
def Main():
a = "aabbcc"
b = math.returner(a)
c = math.final(b)
print(c)
Main()
The program takes a word as input and gives the occurrence of each repeating
character and outputs that number along with a single character of the
repeating sequence.
I cant figure it out, why this doesn't work. I get this error:
NameError: global name 'returner' is not defined
Answer: The problem is that in `Main()` you are not accessing the global (outside the
scope of the `Main()` method) `math` variable. Instead try initializing your
`math` inside the `Main()` function
This lets the method know that it should use the global `math` variable
instead of trying to look for a non-existent local one.
|
Jython Shutil (different behaviour between Windows, Linux, J/Python)!
Question: I'm using Jython, through Topspin (NMR Software running on Java) to run the
following code:
home = "C:/Bruker/TopSpin3.2"
ep_zges_outdir = os.path.abspath(home + "/data/Testshutil/nmr/zges/")
data = ["EP_Saliva_140131_raw", "1", "1", "C:/Bruker/TopSpin3.2/data/Testshutil/nmr"]
ep_zges_list = [["EP_Saliva_140131_raw",25,334],...]
for sample in ep_zges_list:
if data[0] == sample[0] and data[1] == str(sample[1]):
src = os.path.abspath(data[3] + "/" + data[0] + "/" + data[1])
dst = os.path.abspath(ep_zges_outdir + "/" + str(sample[2]))
shutil.copytree(src, dst)
Proper imports were done and, when it works, no os.path.abspath is necessary.
This works perfectly in Windows/Linux python and through the same Software
that runs Jython in CentOS. It does not run in the Software/Jython in Windows
7 and the following error is produced:
Traceback (most recent call last):
File "C:/Bruker/TopSpin3.2/exp/stan/nmr/py/user/JF_test_code_8.py", line 41, in <module>
shutil.copytree(os.path.abspath(data[3] + "/" + data[0] + "/" + data[1]), os.path.abspath(ep_zges_outdir + "/" + str(sample[2])))
File "C:\Bruker\TopSpin3.2\jython\Lib\shutil.py", line 145, in copytree
raise Error, errors
shutil.Error: [u'C:\\Bruker\\TopSpin3.2\\data\\Testshutil\\nmr\\EP_Saliva_140310_raw\\1\\pdata\\1',
u'C:\\Bruker\\TopSpin3.2\\data\\Testshutil\\nmr\\zges\\334\\pdata\\1',
"[Errno 5] Input/output error: u'C:\\\\Bruker\\\\TopSpin3.2\\\\data\\\\Testshutil\\\\nmr\\\\zges\\\\334\\\\pdata\\\\1'",
u'C:\\Bruker\\TopSpin3.2\\data\\Testshutil\\nmr\\EP_Saliva_140310_raw\\1\\pdata',
u'C:\\Bruker\\TopSpin3.2\\data\\Testshutil\\nmr\\zges\\334\\pdata',
"[Errno 5] Input/output error: u'C:\\\\Bruker\\\\TopSpin3.2\\\\data\\\\Testshutil\\\\nmr\\\\zges\\\\334\\\\pdata'",
u'C:\\Bruker\\TopSpin3.2\\data\\Testshutil\\nmr\\EP_Saliva_140310_raw\\1',
u'C:\\Bruker\\TopSpin3.2\\data\\Testshutil\\nmr\\zges\\334',
"[Errno 5] Input/output error: u'C:\\\\Bruker\\\\TopSpin3.2\\\\data\\\\Testshutil\\\\nmr\\\\zges\\\\334'"]
Software versions: Windows 7 SP1 64bit. Python 2.7 32bit. Jython 2.5.3 running
on Topspin 3.2 and Java 1.7.0_51.
CentOS 6.5 32Bit Jython 2.5.3 running on Topspin 3.2 and Java 1.7.0_45
Answer: I think this is a Jython bug (a very annoying one). See
<http://bugs.jython.org/issue1872>
|
Run Python script importing xmlrpclib on Windows?
Question: I have been using Linux to programm Python scripts, but now I have to make one
of them work on Windows XP, and here I am a beginner. I have installed Python
3.4 in C:\Python34, and I have my Python script in E:\solidworks_xmlrpc. This
script works perfectly on Linux, but on Windows I get this error message:
import xmlrpclib
ImportError: No module named "xmlrpclib"
I checked if there was an xmlrpc folder in C:\Python34\Lib and there is. I
also defined PYTHONPATH and PYTHONHOME in system variables.
Anyone knows how to solve this, please?
Thank you so much.
**EDIT**
I deleted the content of the programm only a moment to proof:
import sys
print(sys.path)
And the cmd returned this:
['E:\\solidworks_xmlrpc', 'C:\\WINDOWS\\system32\\python34.zip', 'C:\\Python34\\
DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
Answer: This is the real answer to the question:
Python 3.4 brings the library xmlrpc, which replaces old xmlrpclib.
So, if you have installed Python 3.4 on Windows and you want to use xmlrpclib
(probably as a client side), don't write anymore this:
import xmlrpclib
Replace that with this line:
from xmlrpc import client
And replace every match of _xmlrpc_ in the rest of your code with _client_.
|
Parsing big text files with python specific syntax
Question: I'm trying to parse big text files with python.
These files have a syntax like this:
<option1> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}
<option2> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}
...
...
<optionN> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}
And I want to get for instance `<optionK>[<variableT>]` value.
Is there an optimal way to do this by using a fileparser?
Answer: Consider your above example (ugly solution) you can use
<http://docs.python.org/2/library/htmlparser.html> as follow:
test = """
<option1> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}
<option2> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}
...
...
<optionN> {
<variable1>=<value1>; //<comment>
<variable2>=<value2>;
..
<variableN>=<valueN>; //<comment>
}
"""
from HTMLParser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
option = ""
key = ""
value = ""
r = {}
def handle_starttag(self, tag, attrs):
self.currentTag = tag
print "Encountered a start tag:", tag
if "option" in tag:
#self.r = {}
self.option = tag
self.r[self.option] = {}
elif "{" in self.currentData or "=" not in self.currentData and "//" not in self.currentData:
self.key = tag
self.r[self.option][self.key] = ""
elif "=" in self.currentData:
self.value = tag
self.r[self.option][self.key] = self.value
#print self.r
def handle_endtag(self, tag):
self.currentData = None
print "Encountered an end tag :", tag
def handle_data(self, data):
self.currentData = data
print "Encountered some data :", data
#find a condition to yield result here "}" ?
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed(test)
print parser.r
|
No module psutil.error
Question: I have the following error:
File "/usr/local/lib/python2.7/dist-packages/a8/terminals.py", line 11, in <module>
import psutil, psutil.error
ImportError: No module named error
psutil is installed.
Answer: `psutil` has `NoSuchProcess`, `AccessDenied` and `TimeoutExpired` exceptions.
There is class `Process` in `psutil` but `error` is not valid attribute for
`psutil`.
|
No module named setuptools
Question: I want to install setup file of twilio. When I install it through given
command it is given me an error "No module named setuptools".
Could you please let me know what should I do?
I am using python 2.7.
Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation.
All rights reserved.
C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
from setuptools import setup, find_packages
ImportError: No module named setuptools
Answer: Install
setuptools
<https://pypi.python.org/pypi/setuptools>
and try again
|
Python ImportError: cannot import name datafunc [PyML]
Question: I have installed [PyML](http://pyml.sourceforge.net/tutorial.html) package in
order to use some machine learning algorithms, and according to the tutorial,
my installation is successful.
I try to run a python script which includes the following line to import
modules from PyML
> from PyML import datafunc,svm,assess,modelSelection,ker
However I get the error message above saying
> File `<stdin>`, line 1, in `<module>` ImportError: cannot import name
> datafunc
cannot import name datafunc`. From terminal I check every module by saying
> from PyML import datafunc, from PyML import svm, from PyML import ker
I only get error message for `datafunc`. The PyML library is under the `site-
packages` folder of Python 2.7.
I check this question here [Python error: ImportError: cannot import name
Akismet](http://stackoverflow.com/questions/2351919/python-error-importerror-
cannot-import-name-akismet), but I could't see how it will help my problem.
Do you have any idea why Python imports some modules but does not import this
one?
Answer: In PyML-0.7.13.3, the `datafunc` module exists in `PyML/containers` directory.
So it seems that you can import the module as follows:
from PyML.containers import datafunc
Howerver, it raises an error beacuse the `datafunc` module uses undefined
classes `BaseVectorDataSet` and `SparseDataSet`.
Thus you need to modify the source of PyML in order to use `datafunc` module.
First, prepend the following two lines to `PyML/containers/datafunc.py` and
re-install the PyML library.
from PyML.containers.baseDatasets import BaseVectorDataSet
from PyML.containers.vectorDatasets import SparseDataSet
Then you can import the modules as follows:
from PyML import svm, modelSelection, ker
from from PyML.containers import datafunc
from from PyML.evaluators import assess
BTW, I recommend that you use more documented and tested machine learning
library, such as [scikit-learn](http://scikit-learn.org/stable/).
|
Django tests - fixture User matching query does not exist
Question: I'm trying to run a test that loads a fixture. One the models has
`GenericForeign` key to `ContentType` and a Foreign key to `auth.Users`. It
associates users with content they create. I created fixture with `--natural`
key (as per below) and can foreign keys resolved to names.
python manage.py dumpdata mtm --natural --indent=4
When running my tests I get the following error:
DeserializationError: Problem installing fixture 'fix.json': User matching query does not exist.
Sample database object as dumped by manage.py:
{
"pk": 7,
"model": "xx.vendor",
"fields": {
"phone_number": "777777777777777",
"alternative_phone_number": "",
"object_id": 1,
"contact_email": "",
"user": [
"john"
],
"content_type": [
"xx",
"axe"
],
"contact_person": "jimmy"
}
},
Full traceback:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 178, in __call__
self._pre_setup()
File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 749, in _pre_setup
self._fixture_setup()
File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 881, in _fixture_setup
'skip_validation': True,
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 159, in call_command
return klass.execute(*args, **defaults)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 55, in handle
self.loaddata(fixture_labels)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 84, in loaddata
self.load_label(fixture_label)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 134, in load_label
for obj in objects:
File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/json.py", line 76, in Deserializer
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/json.py", line 70, in Deserializer
for obj in PythonDeserializer(objects, **options):
File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/python.py", line 124, in Deserializer
obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(*field_value)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 167, in get_by_natural_key
return self.get(**{self.model.USERNAME_FIELD: username})
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 307, in get
self.model._meta.object_name)
EDIT:
I have confirmed that all users referenced by vendor model exist in the db.
UPDATE 1:
My prpject uses GenericForeign key to ContentType and a Foreign key to
auth.Users. I dumped the data using the --natural option but this lead to the
problem described above. Now I removed the --natural option and instead dumped
data for all 3 apps myApp, auth, contenttypes. When I'm running the test I get
"Could not load contenttypes.ContentType(pk=50): columns app_label, model are
not unique". I think this is due to the contenttypes being created dynamically
when models are imported. What's the way around this?
Answer: They may exists in "the db". But do they exist in your test database? When you
run tests, Django creates a [test
database](https://docs.djangoproject.com/en/dev/topics/testing/overview/#the-
test-database). So you'll have to dump the Users from you db and load them as
fixtures too.
Fixtures are a nightmare to maintain. I advise you to use something like
[model mommy](https://github.com/vandersonmota/model_mommy) or [factory
boy](https://github.com/rbarrois/factory_boy) to create your fixtures at test
time. Personally I like the model mommy API best, but your taste may differ.
|
wxPython- "no module named Panel" error
Question: I am writing a GUI application using wxPython . But every time i am getting
"no module named Panel" error. Can anyone suggest why.. My code is this
class Player1(wx.Frame):
def _init_(self, parent, id, title):
wx.Frame._init_(self, parent, id, title, size=(350,300))
self.panel =wx.Panel(self)
I am using Python 2.7. I tried uninstalling and then re-installing wxPython
twice but it doesn't work.
Answer: Try to execute the code below, if any error occurs do let me know:
**Code:**
import wx
class Player1(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, style=wx.DEFAULT_FRAME_STYLE)
myPanel = wx.Panel(self,-1)
myButton = wx.Button(myPanel, -1, 'Download', size=(100,50), pos=(20,20))
self.Show(True)
app = wx.App()
frame = Player1(None, wx.ID_ANY, 'Image')
app.MainLoop()
|
How to send Autobahn/Twisted WAMP message from outside of protocol?
Question: I am following the basic wamp pubsub examples in [the github
code](https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/wamp/basic/pubsub/basic):
This example publishes messages from within the class:
class Component(ApplicationSession):
"""
An application component that publishes an event every second.
"""
def __init__(self, realm = "realm1"):
ApplicationSession.__init__(self)
self._realm = realm
def onConnect(self):
self.join(self._realm)
@inlineCallbacks
def onJoin(self, details):
counter = 0
while True:
self.publish('com.myapp.topic1', counter)
counter += 1
yield sleep(1)
I want to create a reference so that I can publish messages over this
connection from elsewhere in the code, i.e.
`myobject.myconnection.publish('com.myapp.topic1', 'My message')`
From this similar
[question](https://stackoverflow.com/questions/15163550/calling-publish-from-
outside-a-custom-autobahn-wampclientprotocol "question") the answer seems to
be that upon connection, I need to set something like
`self.factory.myconnection = self`. I have tried multiple permutations of this
without success.
The factory setup portion is below:
## create a WAMP application session factory
##
from autobahn.twisted.wamp import ApplicationSessionFactory
session_factory = ApplicationSessionFactory()
## .. and set the session class on the factory
##
session_factory.session = Component
## create a WAMP-over-WebSocket transport client factory
##
from autobahn.twisted.websocket import WampWebSocketClientFactory
transport_factory = WampWebSocketClientFactory(session_factory, args.wsurl, debug = args.debug)
transport_factory.setProtocolOptions(failByDrop = False)
## start a WebSocket client from an endpoint
##
client = clientFromString(reactor, args.websocket)
client.connect(transport_factory)
Where would any reference that I set from within the class be attached? to
`client`? to `transport_factory`? to `session_factory`?
Answer: Upon your app session joining the WAMP realm, it sets a reference to itself on
the app session factory:
class MyAppComponent(ApplicationSession):
... snip
def onJoin(self, details):
if not self.factory._myAppSession:
self.factory._myAppSession = self
You then can access this session from elsewhere in your code, e.g.
@inlineCallbacks
def pub():
counter = 0
while True:
## here we can access the app session that was created ..
##
if session_factory._myAppSession:
session_factory._myAppSession.publish('com.myapp.topic123', counter)
print("published event", counter)
else:
print("no session")
counter += 1
yield sleep(1)
pub()
|
How to create a test script in Python for a registration page?
Question: I have a website made in PHP.
To increase number of data sets in my database, I need to create a python
script such that I need not add 500 registrations manually.
There are several tools available but I need to create script of my own.
Can any one help me with this ?
PS: I have knowledge of PHP, Python and ASP.NET as well.
Answer: # [MySQL](https://pypi.python.org/pypi/MySQL-python/)
import MySQLdb
db = MySQLdb.connect(host="localhost", user="john", passwd="megajonhy", db="jonhydb")
cursor = db.cursor()
for i in range(0,500):
cursor.execute("INSERT INTO MyTable VALUES('Some string', 1337);")
# [PostgreSQL](http://python.projects.pgfoundry.org/)
import postgresql
db = postgresql.open("pq://postgres:[email protected]/testdb")
prepstatement = db.prepare("INSERT INTO MyTable VALUES($1, $2, $3);")
with db.xact():
for i in range(0, 500):
prepstatement('Some string', 1337, ["a", "list"])
# [MsSQL](https://code.google.com/p/pyodbc/)
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=user;PWD=pass')
cursor = cnxn.cursor()
for i in range(0, 500):
cursor.execute("INSERT INTO MyTable VALUES('Some string', 1337);")
# [SQLAlchemy](http://www.sqlalchemy.org/)
Note that this is a library that will do a lot of magic for you, hence you'd
might not learn as much from it or desire all it's functionality.
from sqlalchemy import create_engine
db = create_engine("mssql://me:pass@localhost/testdb")
for i in range(0, 500):
db.execute("INSERT INTO MyTable VALUES('Some string', 1337);"):
# How get get POST/GET data
And finally, we have no clue as to how you run the script.
But you mentioned web development and well, assuming you run the script as
CGI, here's how to get the POST/GET data:
import cgi
form = cgi.FieldStorage()
print form["username"]
# Let me Google this for you
* [How are POST and GET variables handled in Python?](http://stackoverflow.com/questions/464040/how-are-post-and-get-variables-handled-in-python)
* [How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python)
* [How to insert array of data into mysql using php](http://stackoverflow.com/questions/15013211/how-to-insert-array-of-data-into-mysql-using-php)
* [MSSQL in python 2.7](http://stackoverflow.com/questions/7317195/mssql-in-python-2-7)
|
Delete particular string while reading CSV data
Question: I'm new in python , and I'm writing a code to read data from a CSV file.
The data looks like this:
10944750,13451,0,6��4��
10944750,21110,0,6��7��
10944750,1131,0,7��23��
10944750,8689,0,5��2��
The last column represents date , for example in first row : June 4th . But
there are two Chinese charter in it . So I have to decode it and get the month
and day.
My code :
import codecs
raw_file=open('Documents/t_alibaba_data.csv')
result=open('Documents/result.txt','w')
for line in raw_file.readlines():
entry=line.split(",")
deco=entry[3].decode("gbk")
month=deco[0]
if len(deco)==5:
day=int(deco[2])*10+int(deco[3])
else:
day=int(deco[2])
result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
print result
There is no alert or error in my IDE, but there is nothing in my result
either.
Answer: First of all: you haven't told Python that you want to read from the file.
(add 'r' to raw_file.open().
And, when running your program, after decoding the last column, element nr 3
(deco[2]) is a chinese symbol, not the nr of day.
I adjusted your program a little, and when it looks like this, it works (at
least if I understood your question correctly):
import codecs
raw_file=open('Documents/t_alibaba_data.csv', 'r')
result=open('Documents/result.txt','w')
for line in raw_file.readlines():
entry=line.split(",")
deco=entry[3].decode("gbk").strip()
month=deco[0]
if len(deco)==5:
day=int(deco[2])*10+int(deco[3])
else:
day=int(deco[4])
result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
result.close()
Also, len(deco) is never 5, and the if test will never be true. The length is
_always_ longer than 5. Try printing out the length of the different decos to
see what the actual length is. It could be wise to use the strip function on
deco, in case there are spaces at the end of the string. When I print the
length of the decos you gave as examples, the length was 8 or 9, depending on
the line that were being processed.
|
Flask: 'Response' object is not iterable with response-producing exceptions
Question: I can't seem to generate responses from exceptions anymore in Flask 0.10.1
(the same happened with 0.9). This code:
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
import flask, werkzeug
print 'Flask version: %s' % flask.__version__
print 'Werkzeug version: %s' % werkzeug.__version__
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
class JSONException(HTTPException):
response = None
def get_body(self, environ):
return jsonify(a=1)
def get_headers(self, environ):
return [('Content-Type', 'application/json')]
@app.route('/x')
def x():
return jsonify(a=1)
@app.route('/y')
def y():
raise JSONException()
c = app.test_client()
r = c.get('x')
print r.data
r = c.get('y')
print r.data
prints
Flask version: 0.10.1
Werkzeug version: 0.9.4
{
"a": 1
}
Traceback (most recent call last):
File "flask_error.py", line 33, in <module>
print r.data
File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 881, in get_data
self._ensure_sequence()
File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 938, in _ensure_sequence
self.make_sequence()
File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 953, in make_sequence
self.response = list(self.iter_encoded())
File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
for item in iterable:
File "/home/path/lib/python2.7/site-packages/werkzeug/wsgi.py", line 682, in __next__
return self._next()
File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
for item in iterable:
File "/home/path/lib/python2.7/site-packages/werkzeug/wsgi.py", line 682, in __next__
return self._next()
File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
for item in iterable:
TypeError: 'Response' object is not iterable
The traceback is unexpected.
Answer: `jsonify()` produces a _full response object_ , not a response body, so use
[`HTTPException.get_response()`](http://werkzeug.pocoo.org/docs/exceptions/#werkzeug.exceptions.HTTPException.get_response),
not `.get_body()`:
class JSONException(HTTPException):
def get_response(self, environ):
return jsonify(a=1)
The alternative is to just use `json.dumps()` to produce a body here:
class JSONException(HTTPException):
def get_body(self, environ):
return json.dumps({a: 1})
def get_headers(self, environ):
return [('Content-Type', 'application/json')]
|
Wrong freqs & amplitudes with numpy.fft, furthermore odd drawing of spectra
Question: To understand the usage of ffts, I've just implemented a low-pass filter for a
discrete signal in python.
The resulting filtered signal is pretty much what I wanted to get, but
unfortunately, the spectra are not what I had expected. They seem OK on the
first look, but as you can see, both the amplitudes and frequences are not
correct.
The frequencys should be 0Hz, 220Hz, 660Hz and the amplitudes 3, 2, 1; but it
comes out as shown in the plot below. Please note that the amplitudes in that
plot are not correct due I wrote `abs(F)/N` instead of `2*abs(F)/N` on the
plot command. But when I do so, the DC value doubles to 6, which is wrong I
think.

And also the drawing of the spectrum seems a little odd to me, please have a
look at this:

I have no idea what I am doing wrong and would very much appreciate some help
on this.
import numpy as np
import matplotlib.pyplot as plt
from math import pi
N = 2048
w0 = 2*pi*220
t = np.linspace(0, 0.1, N)
signal = lambda x: 3 + 2*np.sin(w0*x) + np.sin(3*w0*x)
f = np.array(signal(t))
F = np.fft.fft(f)
Fo = F.copy() # just for printing the unfiltered spectrum
freq = np.fft.fftfreq(len(f), 1/N)
# That's the filter, all parts over the frequency of fg should be damped.
fg = 50
for i in range(0, len(f)):
F[i] *= (1 if abs(freq[i]) < fg else 0)
ff = np.fft.ifft(F)
plt.subplot(3, 1, 1)
plt.plot(t, f, label='f original')
plt.plot(t, ff, label='f filtered')
plt.axis(xmin=0, xmax=16e-3)
plt.legend()
plt.subplot(3, 1, 2)
plt.plot(freq, abs(Fo)/N, label='spec original')
plt.axis(xmin=-200, xmax=200)
plt.legend()
plt.subplot(3, 1, 3)
plt.plot(freq, abs(F)/N, label='spec filtered')
plt.axis(xmin=-200, xmax=200)
plt.legend()
plt.show()
Answer: There are two questions here:
1) Your `freq` axis is off by a factor of 10 since `fftfreq` wants the sample
spacing (_eg_ , in seconds), which should be `total_time/N` (or, `0.1/N` in
your case), not `1/N` as you're using.
2) The funny looking plot is because the returned values from the fft are not
ordered by increasing values of the frequency, and it happens that the last
frequency in the returned values are at the middle frequency in the plot, so
that line just ends there. Try instead: just plotting points (rather than
points connected by a line) and it will look reasonable; or use
[`fftshift`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftshift.html).
|
Fast algorithm to compute Adamic-Adar
Question: I'm working on graph analysis. I want to compute an N by N similarity matrix
that contains the Adamic Adar similarity between every two vertices. To give
an overview of Adamic Adar let me start with this introduction:
Given the adjacency matrix `A` of an undirected graph `G`. `CN` is the set of
all common neighbors of two vertices `x`, `y`. A common neighbor of two
vertices is one where both vertices have an edge/link to, i.e. both vertices
will have a 1 for the corresponding common neighbor node in `A`. `k_n` is the
degree of node `n`.
Adamic-Adar is defined as the following: 
My attempt to compute it is to fetch both rows of the `x` and `y` nodes from
`A` and then sum them. Then look for the elements that has `2` as the value
and then gets their degrees and apply the equation. However computing that
takes really really a long of time. I tried with a graph that contains 1032
vertices and it took a lot of time to compute. It started with 7 minutes and
then I cancelled the computations. So my question: is there a better algorithm
to compute it?
Here's my code in python:
def aa(graph):
"""
Calculates the Adamic-Adar index.
"""
N = graph.num_vertices()
A = gts.adjacency(graph)
S = np.zeros((N,N))
degrees = get_degrees_dic(graph)
for i in xrange(N):
A_i = A[i]
for j in xrange(N):
if j != i:
A_j = A[j]
intersection = A_i + A_j
common_ns_degs = list()
for index in xrange(N):
if intersection[index] == 2:
cn_deg = degrees[index]
common_ns_degs.append(1.0/np.log10(cn_deg))
S[i,j] = np.sum(common_ns_degs)
return S
Answer: I believe you are using rather slow approach. It would better to revert it -
\- initialize AA (Adamic-Adar) matrix by zeros
\- for every node k get it's degree k_deg
\- calc `d = log(1.0/k_deg)` (why log10 - is it important or not?)
\- add d to all AAij, where i,j - all pairs of 1s in kth row of adjacency
matrix
**Edit:**
\- for sparse graphs it is useful to extract positions of all 1s in kth row to
the list to reach O(V*(V+E)) complexity instead of O(V^3)
AA = np.zeros((N,N))
for k = 0 to N - 1 do
AdjList = []
for j = 0 to N - 1 do
if A[k, j] = 1 then
AdjList.Add(j)
k_deg = AdjList.Length
d = log(1/k_deg)
for j = 0 to AdjList.Length - 2 do
for i = j+1 to AdjList.Length - 1 do
AA[AdjList[i],AdjList[j]] = AA[AdjList[i],AdjList[j]] + d
//half of matrix filled, it is symmetric for undirected graph
|
How to start a waveform from a python script, if a component is run on two different architectures?
Question: I had asked an earlier question on how to create and run the same component on
different architecture, [Same component run on 2 different
GPPs](http://stackoverflow.com/questions/22390340/same-component-
on-2-different-gpps). The IDE can create a component that can run on two
different architectures via the implementation tab. When you launch the
waveform, you have the option to specify a particular GPP for a component
instance.
How would you do the same thing when you are not launching the waveform from
the IDE? I currently launch waveforms from a python script.
Answer: You can accomplish this by passing a `DeviceAssignmentSequence` as the third
argument to the `ApplicationFactory::create()` call.
Each member of the sequence is a `DeviceAssignmentType` that takes two string
parameters. The first is the Component's `usagename` as it appears in the SAD
file. The second is the identifier for the Device that you would like to
deploy your Component to.
An example:
from ossie.utils import redhawk
from ossie.cf import CF
dom = redhawk.attach("REDHAWK_DEV")
# Find the devices
for devMgr in dom.devMgrs:
# Check the name of Device Manager
if devMgr.name == 'DEV_MGR1':
# Find the GPP
for dev in devMgr.devs:
if dev.name == 'GPP'
dev1 = dev
elif devMgr.name == 'DEV_MGR2':
# Find the GPP
for dev in devMgr.devs:
if dev.name == 'GPP'
dev2 = dev
# Create the deployment requirements
# First variable is comp name as it appears in the SAD file, second is device ID
assignment1 = CF.DeviceAssignmentType('comp_1', dev1._get_identifier())
assignment2 = CF.DeviceAssignmentType('comp_2', dev2._get_identifier())
# Install the Application Factory
dom.installApplicationFactory('/waveforms/app_name/app_name.sad.xml')
# Get the Application Factory
facs = dom._get_applicationFactories()
# If using multiple, different Applications, this list needs to be iterated
# to get the correct factory
app_fac = facs[0]
# Create the Application
app = app_fac.create(app_fac._get_name(), [], [assignment1, assignment2])
# Uninstall the Application Factory
dom.uninstallApplication(app_fac._get_identifier())
|
Variables defined in a function - Python
Question: I am running this code: <https://dpaste.de/RiAP>
As you see, the variable `linespecificpayload` is used only within this
function, but if I check the ID, its the same in every function call.
I can't seem to figure out how to flush its value with each call. Both the
call for `id(linespecificpayload)` return the same value. Any suggestions
would be welcome.
Also the code is something I wrote in an hour or two. So may not be the most
efficient one.
Answer: The reason is that you are assigning a global object to `linespecificpayload`,
thus the reference stays the same.
If you would like to create a copy of the `filespecificpayload` dict you can
either:
* use `filespecificpayload.copy()`. This will create a copy of the dict, but the values that existed before copying will be shared so that `id(filespecificpayload[key]) == id(filespecificpayload.copy()[key])`
* use `copy.deepcopy()`:
>>> from copy import deepcopy
>>> d = deepcopy(filespecificpayload)
>>> id(d[key]) == id(filespecificpayload[key])
False
|
In Python how to encode/decode unicode characters such as ö
Question: Using Python 2.6.6 on CentOS 6.4
import json
import urllib2
url = 'http://www.google.com.hk/complete/search?output=toolbar&hl=en&q=how%20to%20pronounce%20e'
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
opener.addheaders = [('Accept-Charset', 'utf-8')]
response = opener.open(url)
page = response.read()
print page
Result:
...<suggestion data="how to pronounce eyjafjallaj
at which Python dies with no error message.
I think it dies because the next character is `ö`:
<toplevel>
<CompleteSuggestion>
<suggestion data="how to pronounce edinburgh"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce elle"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce edith"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce et al"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce eunice"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce english names"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce edamame"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce erudite"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce eyjafjallajökull"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="how to pronounce either"/>
</CompleteSuggestion>
</toplevel>
[http://www.google.com.hk/complete/search?output=toolbar&hl=en&q=how%20to%20pronounce%20e](http://www.google.com.hk/complete/search?output=toolbar&hl=en&q=how%20to%20pronounce%20e)
This appears to be a unicode issue, I have tried encode('utf-8') and
decode('utf-8') in many ways, but it still dies. Any ideas?
PS It seems I need to stay with urllib2 not urllib as urllib ignores cookies
that causes other problems.
Answer: `response.read()` returns a bytestring. Python shouldn't die while printing a
bytestring because no character conversion occurs, bytes are printed as is.
You could try to print Unicode instead:
text = page.decode(response.info().getparam('charset') or 'utf-8')
print text
|
TypeError: expected string or buffer while using regular expression in python
Question: I wrote this code to remove the tags that match like this
`<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>`
**CODE:**
import mechanize
import urllib2
from bs4 import BeautifulSoup
import re
med = 'paracetamol'
listiterator = []
listiterator[:] = range(2,16)
br = mechanize.Browser()
br.set_handle_robots(False)
r=br.open("http://www.drugs.com/search-wildcard-phonetic.html")
br.select_form(nr=0)
br.form['searchterm'] = med
br.submit()
url = br.response().geturl()
print url
mainurl = urllib2.urlopen(url).read()
subpages = re.findall("<a href=\"(.*?).html\">[^>]*>", mainurl)
for sub in subpages:
if sub.startswith("http:"):
soup = BeautifulSoup(urllib2.urlopen(sub).read())
m = soup.find_all("div", {"class":"contentBox"})
head = m[0].find_all(["h2","p"])
for i in head:
m = re.match("<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>").group()
if not m:
print i
break
I got this error:
m = re.match("<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>",i).group()
File "/usr/lib/python2.7/re.py", line 137, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
Answer: You get that error because the type of the variable `i` is `<class
'bs4.element.Tag'>`, and `match` needs a buffer or string. Secondly, if the
pattern doesn't match, then the `.match` call will return `None`, so your
`.group` will be a null pointer exception.
Here's a _quick and dirty_ "solution" I don't recommend:
m = re.match("<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>", str(i))
if not m:
print i
A better solution would be to rewrite without trying to parse HTML yourself,
letting BeautifulSoup do its job. For example, instead of your regex pattern,
exclude the items that contain the text `See also` and an anchor tag:
if i.find(text='See also:') and i.find('a'):
continue
print i
|
Generating all possible combinations from a list of lists
Question: I have the following lists:
[[a,b,c],[b],[d,a,b,e],[a,c]]
This list represents a mini-world in a puzzle problem. In this example the
world contains 4 piles of objects stacked on-top of each other. I can only
move the top object and place it on-top of some other stack. The letters
represent a type of object, for example a might be a rock and b a ball. I need
to generate all possible states that can exist for this mini-world. Im trying
to do this in python but don't know how to implement it.
Answer: You can use
[itertools.combinations_with_replacement](http://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement)
with list comprehension:
import itertools
ll = [['a','b','c'],['b'],['d','a','b','e'],['a','c']]
print [list(itertools.combinations_with_replacement(item,len(item))) for item in ll]
It gives the combinations for each element in list of lists.
Output:
[[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'c'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'c'), ('c', 'c', 'c')],
[('b',)],
[('d', 'd', 'd', 'd'), ('d', 'd', 'd', 'a'), ('d', 'd', 'd', 'b'), ('d', 'd', 'd', 'e'), ('d', 'd', 'a', 'a'), ('d', 'd', 'a', 'b'), ('d', 'd', 'a', 'e'), ('d', 'd', 'b', 'b'), ('d', 'd', 'b', 'e'), ('d', 'd', 'e', 'e'), ('d', 'a', 'a', 'a'), ('d', 'a', 'a', 'b'), ('d', 'a', 'a', 'e'), ('d', 'a', 'b', 'b'), ('d', 'a', 'b', 'e'), ('d', 'a', 'e', 'e'), ('d', 'b', 'b', 'b'), ('d', 'b', 'b', 'e'), ('d', 'b', 'e', 'e'), ('d', 'e', 'e', 'e'), ('a', 'a', 'a', 'a'), ('a', 'a', 'a', 'b'), ('a', 'a', 'a', 'e'), ('a', 'a', 'b', 'b'), ('a', 'a', 'b', 'e'), ('a', 'a', 'e', 'e'), ('a', 'b', 'b', 'b'), ('a', 'b', 'b', 'e'), ('a', 'b', 'e', 'e'), ('a', 'e', 'e', 'e'), ('b', 'b', 'b', 'b'), ('b', 'b', 'b', 'e'), ('b', 'b', 'e', 'e'), ('b', 'e', 'e', 'e'), ('e', 'e', 'e', 'e')],
[('a', 'a'), ('a', 'c'), ('c', 'c')]]
If you would like to avoid duplicate same element in a combination, you can
use
[itertools.permutation](http://docs.python.org/2/library/itertools.html#itertools.permutations):
[list(itertools.permutations(item,len(item))) for item in ll]
Output:
[[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')],
[('b',)],
[('d', 'a', 'b', 'e'), ('d', 'a', 'e', 'b'), ('d', 'b', 'a', 'e'), ('d', 'b', 'e', 'a'), ('d', 'e', 'a', 'b'), ('d', 'e', 'b', 'a'), ('a', 'd', 'b', 'e'), ('a', 'd', 'e', 'b'), ('a', 'b', 'd', 'e'), ('a', 'b', 'e', 'd'), ('a', 'e', 'd', 'b'), ('a', 'e', 'b', 'd'), ('b', 'd', 'a', 'e'), ('b', 'd', 'e', 'a'), ('b', 'a', 'd', 'e'), ('b', 'a', 'e', 'd'), ('b', 'e', 'd', 'a'), ('b', 'e', 'a', 'd'), ('e', 'd', 'a', 'b'), ('e', 'd', 'b', 'a'), ('e', 'a', 'd', 'b'), ('e', 'a', 'b', 'd'), ('e', 'b', 'd', 'a'), ('e', 'b', 'a', 'd')],
[('a', 'c'), ('c', 'a')]]
|
Error in Synchronize Translation Openerp 7
Question: I am getting this strange error when trying to synchronize terms in Openerp 7.
I had imported some terms for german language through a CSV file before but
now I only have English installed.
OpenERP Server Error
Client Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/http.py", line 204, in dispatch
response["result"] = method(self, **self.params)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/controllers/main.py", line 1132, in call_button
action = self._call_kw(req, model, method, args, {})
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/controllers/main.py", line 1120, in _call_kw
return getattr(req.session.model(model), method)(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/session.py", line 42, in proxy
result=self.proxy.execute_kw(self.session._db,self.session._uid,self.session._password, self.model, method, args, kw)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/session.py", line 30, in proxy_method
result = self.session.send(self.service_name, method, *args)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/session.py", line 103, in send
raise xmlrpclib.Fault(openerp.tools.ustr(e), formatted_info)
Server Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/web/session.py", line 89, in send
return openerp.netsvc.dispatch_rpc(service_name, method, args)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/netsvc.py", line 292, in dispatch_rpc
result = ExportService.getService(service_name).dispatch(method, params)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/service/web_services.py", line 626, in dispatch
res = fn(db, uid, *params)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/osv/osv.py", line 188, in execute_kw
return self.execute(db, uid, obj, method, *args, **kw or {})
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/osv/osv.py", line 131, in wrapper
return f(self, dbname, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/osv/osv.py", line 197, in execute
res = self.execute_cr(cr, uid, obj, method, *args, **kw)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/osv/osv.py", line 185, in execute_cr
return getattr(object, method)(cr, uid, *args, **kw)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/openerp/addons/base/module/wizard/base_update_translations.py", line 47, in act_update
tools.trans_export(this.lang, ['all'], buf, 'csv', cr)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/opener/tools/translate.py", line 496, in trans_export
translations = trans_generate(lang, modules, cr)
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/opener/tools/translate.py", line 788, in trans_generate
push_translation(module, 'model', name, xml_name, encode(trad))
File "/usr/lib/python2.6/site-packages/openerp-7.0_20131124_002547-py2.6.egg/opener/tools/translate.py", line 648, in push_translation
if not source or len(source.strip()) <= 1:
AttributeError: 'bool' object has no attribute 'strip'
Answer: I found the following solution to my problem: I had set a few custom boolean
fields to "translatable" in my models. Un-checking the "translatable" property
on them removed the errors.
|
How to get a value from another file function? python
Question: Does anyone can help here? I have two files called `game.py` and
`settings.py`, I just want to get one value from settings to use in game, but
I dont know what I am doing wrong.
the value I want it is in the function bbbbb...
THIS IS MY SETTINGS
from tkinter import*
import game
class Application(Frame):
def __init__ (self, master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def bbbbb(self):
self.xr = self.ball_numbers.get()
print("printing...", self.xr)
return self.xr
def create_widgets(self):
self.ball_numbers = IntVar()
Label(self,text = "Select how many balls you wish to play:").grid()
Radiobutton(self, text = "1 Ball", variable = self.ball_numbers, value = 1, command = self.bbbbb).grid ()
Radiobutton(self, text = "2 Balls", variable = self.ball_numbers, value = 2, command = self.bbbbb).grid ()
Radiobutton(self, text = "3 Balls", variable = self.ball_numbers, value = 3, command = self.bbbbb).grid ()
settings_window = Tk()
settings_window.title(" THE BOUNCER - Settings")
settings_window.geometry("600x600")
app = Application(settings_window)
settings_window.mainloop()
I need that value in the class **handling_settings** , in the function
**create_ball_numbers**
AND THIS IS MY game.py
from livewires import games, color
from tkinter import*
import settings
import random
games.init(screen_width = 735, screen_height = 350, fps = 35)
class Bounce(games.Sprite):
def update(self):
if self.right > games.screen.width or self.left < 0:
self.dx = -self.dx
if self.top < 0:
self.dy = -self.dy
if self.bottom == 315 and self.overlapping_sprites:
self.dy = -self.dy
class Bar_moving(games.Sprite):
def update(self):
self.x = games.mouse.x
self.y = 315
class handling_settings():
self.yr = bbbbb()
print("printing number from settings ", self.yr)
def create_ball_numbers(self):
print("inside def", self.yr)
def main():
background = games.load_image("BG.jpg", transparent = False)
games.screen.background = background
call = handling_settings()
call.create_ball_numbers()
bar_small = games.load_image("bar_small.jpg", transparent = False)
the_bar_small = Bar_moving(image = bar_small, x = games.mouse.x)
games.screen.add(the_bar_small)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
main()
I think I am not using on the right way IMPORT on top of the file.... keeping appearing this msg...
File "C:\Users\Bruno\Desktop\DIT\Object Oriented Programming\GAME - Assignment\game.py", line 3, in <module>
from settings import bbbbb
ImportError: cannot import name bbbbb
If I run both files individually... its ok... but when I try to get the value
in `bbbbb` function in `settings`, I get stuck...
Answer: You have a circular import; `settings` imports `game`, which imports
`settings`. At that time, neither module is fully done initializing (anything
beyond the `import` lines has not yet run).
You don't actually _use_ the `game` module in `settings`, so just remove the
`import game` line from `settings.py`.
In `game.py`, you imported the `settings` name; `bbbbb` is an attribute on the
_`Application`_ class in that module. The line:
self.yr = bbbbb()
will never work here.
You should definitely _not_ create a new `Tk()` root window in `settings`,
however; you can only ever have _one_ main loop in a Tk application. Make
`settings` a dialog window triggered by the main application in `game`.
So to get the `bbbbb()` result, you need to instead spawn the settings dialog
box, let the user interact with it, and then retrieve the `ball_numbers`
setting when the user closes the dialog again.
|
Python Turtle: How to use the write function to join an integer and a string with the integer coming from a list
Question: So, I'm trying to get the grade to be able to print a percentage sign in the
exact same line as to when I write the grade.
The aim is to have it print: 45% for the first example.
from turtle import *
grades = [45, 42, 13, 98, 82]
write(grades[0],'%')
When I run this code both the grade and percentage sign gets printed on top of
each other. How do I get the grade and the percentage sign, side by side
without the two overlapping?
Answer: Try using string `format` method:
write("{0}%".format(grades[1]))
|
Python: Can't pop from an empty list
Question: I am creating a python program to detect and enable usb to usb data transfer
between usb storage drives. However I am having an issue with updating the
`dev_label` (device name of the drive) and passing it to `Exchange`. Here is
the code :
serial_list=[]
context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='block',device_type='partition')
observer = GUDevMonitorObserver(monitor)
def device_connected(observer, device):
Welcome.device_count+=1
flag =False
for iden in serial_list :
if iden == device.__getitem__('ID_SERIAL_SHORT'):
flag=True
if flag ==False:
serial_list.append(device.__getitem__('ID_SERIAL_SHORT'))
Welcome.dev_label.append(str(device.__getitem__('ID_FS_LABEL')))
size = len(Welcome.dev_label)
label = gtk.Label('Device connected :: {0!r}'.format(Welcome.dev_label[size-1]))
Welcome.vbox.pack_start(label)
Welcome.window.show_all()
if Welcome.device_count<2:
label = gtk.Label('Connect the second device')
Welcome.vbox.pack_start(label)
Welcome.window.show_all()
else :
Exchange()
observer.connect("device-added",device_connected)
monitor.start()
class Welcome:
device_count = 0
window = gtk.Window()
vbox= gtk.VBox(False, 5)
dev_label = []
def __init__(self):
self.window.set_default_size(300, 300)
self.window.set_title("Welcome")
label = gtk.Label("Connect the desired device")
self.vbox.pack_start(label)
self.window.add(self.vbox)
self.window.connect("destroy", lambda q: gtk.main_quit())
self.window.show_all()
class Exchange:
window1 = gtk.Window(Welcome.dev_label.pop())
window2 = gtk.Window(Welcome.dev_label.pop())
def __init__(self):
width = gtk.gdk.screen_get_default().get_width()
height = gtk.gdk.screen_get_default().get_height()
self.window1.resize(width/2,height)
self.window2.resize(width/2,height)
self.window2.move(self.window1.get_position()[0]+width/2, self.window1.get_position()[1])
label = gtk.Label("Hello")
self.window1.add(label)
self.window1.connect("destroy" , lambda q : gtk.main_quit())
self.window1.show_all()
label = gtk.Label("World")
self.window2.add(label)
self.window2.connect("destroy",lambda q : gtk.main_quit())
self.window2.show_all()
Welcome()
gtk.main()
The error shown in the trace back is :
Traceback (most recent call last):
File "project.py", line 70, in <module>
class Exchange:
File "project.py", line 71, in Exchange
window1 = gtk.Window(Welcome.dev_label.pop())
IndexError: pop from empty list
I can't figure out how to synchronize all these event so that the compiler
doesn't throw an error. Values are being popped from `Welcome.dev_label` only
after they've been updated in `device_connected` so why does the compiler have
a problem? I am a python newbie so please be gentle.
Answer: This is not the compiler givin errors but the program.
You can change your class to this:
import time
class Exchange:
while not Welcome.dev_label: time.sleep(0.001)
window1 = gtk.Window(Welcome.dev_label.pop()) # line 4
while not Welcome.dev_label: time.sleep(0.001)
window2 = gtk.Window(Welcome.dev_label.pop())
This would be kind of a synchronization primitive given that only line 4 and 6
remove content. In general you would use a queue for this.
import queue # Python3 # import Queue Python 2
Welcome.dev_label # = queue.Queue()
Welcome.dev_label.put(...) # instead of append
Welcome.dev_label.get(...) # instead of pop
But I do not know wether your code uses threads and runs in parallel. If the
`time.sleep` example works then you can switch to a queue.
|
How to pass the class path to ipython's notebook when called from ipzope?
Question: I've been using iypthon as set from ipzope (buildout) for a while and it works
without problems.
Now I'm trying to use ipython's notebook and I cannot set it up properly.
When I create a new notebook it stops IPython's Kernel with an `ImportError`
(see below). I guess that the created Thread in
`IPython.html.notebook.start()` opens the `webbrowser` without passing the
`sys.path` from the calling process.
My workaround is to add the paths in `ipzope` to `PYTHONPATH`.
When I add all the paths then ipython's notebook works perfectly and I can
debug and manipulate Plone.
If I only add `ipython`, `pyzmq`, `Jinja`, and `tornado` to `PYTHONPATH`
ipython's notebook works but it has no access to the `ipzope` vars (`app`,
`utils` etc.)
**Question:** Any hint how to pass the paths to ipython's notebook without
using `PYTHONPATH`?
I start ipython's notebook from `ipzope` with
sys.argv[1:1] = "notebook --ip=192.168.45.135 --profile=zope".split()
The ImportError is:
IPython Notebook 14-03-22 14:57:17.141 [NotebookApp] Connecting to: tcp://127.0.0.1:50948
2014-03-22 14:57:17.143 [NotebookApp] Kernel started: b573fbc0-5dee-410b-91cb-01afd2e9acce
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named IPython.kernel.zmq.kernelapp
Answer: I quote `Min RK` [IPython developer](https://github.com/minrk):
> "When you start plain terminal IPython, the shell is created in the same
> process. That means that IPython executes in the same context as the changes
> you have made to sys.path, so the changes have the desired effect. In the
> notebook, only the notebook server exists in that context. Kernels are
> started as subprocesses, and thus recreate sys.path at startup, following
> the standard procedure for a Python process, and do not inherit any runtime
> changes to sys.path that may have happened in parent processes."
> (<https://github.com/ipython/ipython/issues/5420>)
## My Solution
Thus the only way to pass the path to notebook is via `PYTHONPATH`.
My workaround by now is to set `os.environ['PYTHONPATH'] = ':'.join(sys.path)`
in the script. With this you don't need to mess the PYTHONPATH (if any) of
your system and you make sure that all the necessary paths will be passed to
the kernel.
The `os.environ` is passed as `env` argument of `Popen` to the subprocess in
`launch_kernel` (`.../ipython-1.2.1-py2.7.egg/IPython/kernel/launcher.py`).
If you need to use ipython's notebook and want buildout to generate the
script, add the following to your buildout (e.g. in
`.../Plone-4.3.2/zeocluster/develop.cfg`)
parts +=
...
ipzopenb
...
[ipzopenb]
recipe = zc.recipe.egg
eggs =
ipython
pyzmq
tornado
Jinja2
#following for nbconvert
Pygments
Sphinx
${client2:eggs}
initialization =
import sys, os
os.environ["INSTANCE_HOME"] = "${client2:location}"
os.environ['PYTHONPATH'] = ':'.join(sys.path)
sys.argv[1:1] = "notebook --ip=192.168.45.135 --profile=zope".split()
scripts = ipython=ipzopenb
...
[versions]
Jinja2 = 2.7.2
Pygments = 1.6
Sphinx = 1.2.2
|
Python counter in Prolog
Question: In Python you can do
>>> import from collections counter
>>> Counter(['a','b','b','c'])
>>> Counter({'b': 2, 'a': 1, 'c': 1})
Is there something similar in Prolog? Like so:
counter([a,b,b,c],S).
S=[a/1,b/2,c/1].
This is my implementation:
counter([],List,Counts,Counts).
counter([H|T],List,Counts0,[H/N|Counts]):-
findall(H, member(H,List), S),
length(S,N),
counter(T,List,Counts0,Counts).
counter(List,Counts):-
list_to_set(List,Set),
counter(Set,List,[],Counts).
It's rather verbose, so I wondered if there was a builtin predicate or a more
terse implementation.
Answer: There is no builtin predicate, here is another way to do that :
counter([X], [X/1]).
counter([H | T], R) :-
counter(T, R1),
( select(H/V, R1, R2)
-> V1 is V+1,
R = [H/V1 | R2]
; R = [H/1 | R1]).
|
Brute force closest pair algorithms - for loops
Question: New to Python. Trying to analyze the algorithm for Closest pair of points.
Found an [example](http://rosettacode.org/wiki/Closest-pair_problem#Python)
Which has these lines:
return min( ((abs(point[i] - point[j]), (point[i], point[j]))
for i in range(numPoints-1)
for j in range(i+1,numPoints)),
key=itemgetter(0))
It is not clear to me how the for loops are being evaluated.
How are the for loops related to the points, key and itemgetter?
When I put this code in [Ideone](http://ideone.com/1u27f9)
I get a runtime error in the times() function:
def times():
''' Time the different functions
'''
import timeit
functions = [bruteForceClosestPair, closestPair]
for f in functions:
print 'Time for', f.__name__, timeit.Timer(
'%s(pointList)' % f.__name__,
'from closestpair import %s, pointList' % f.__name__).timeit(number=1)
Thank you.
Answer: Your `min` code is equivalent to using a
[generator](http://docs.python.org/2/tutorial/classes.html#generators) as
follows:
def getPoints(point, numPoints):
for i in range(numPoints - 1):
for j in range(i + 1, numPoints):
yield (abs(point[i] - point[j]), (point[i], point[j]))
return min(getPoints(point, numPoints), key=itemgetter(0))
As @DSM noted, the first argument to `min` in your code is a [generator
expression](http://docs.python.org/2/tutorial/classes.html#generator-
expressions).
|
Serving resource to QWebView of PyQT5
Question: How can serve resource (files like html, css, js, fonts) for a desktop app to
QWebView (in PyQT5)?
What I want is:
1. If possible handling requested resource by Webkit engine of PyQT5 with a custom scheme like say `custom://app/jquery.js` and returning the file.
2. If possible handling standard http verbs (GET, POST, ...) for that custom scheme.
If these 2 are not possible (at least not possible in a pure Pythonic way):
* How can I intercept requests coming from the embedded Webkit and provide resource (html, css, js) based on a pattern in url (like say some regex `(?<controller>[^/])/(?<action>[^/])`)?
Answer: You need to create your own subclass of QNetworkAccessManager, which returns a
custom QNetworkReply for the desired protocol, and then set this as network
access manager for you QWebView's page.
[This article](http://doc.qt.digia.com/qq/32/qq32-webkit-protocols.html) shows
a good example how this can be done - applied to PyQt5, this is how it could
look:
from PyQt5.QtCore import QUrl, QTimer, QIODevice
from PyQt5.QtWidgets import QApplication
from PyQt5.QtNetwork import (QNetworkAccessManager,
QNetworkReply,
QNetworkRequest)
from PyQt5.QtWebKitWidgets import QWebView
import sys
class ExampleNetworkAccessManager(QNetworkAccessManager):
def __init__(self, parent=None):
super().__init__(parent=parent)
def createRequest(self, operation, request, device):
if request.url().scheme() == 'example':
return ExampleReply(self, operation, request, device)
return super().createRequest(operation, request, device)
class ExampleReply(QNetworkReply):
def __init__(self, parent, operation, request, device):
super().__init__(parent=parent)
self.setRequest(request)
self.setOperation(operation)
self.setUrl(request.url())
self.bytes_read = 0
self.content = b''
# give webkit time to connect to the finished and readyRead signals
QTimer.singleShot(200, self.load_content)
def load_content(self):
if self.operation() == QNetworkAccessManager.PostOperation:
# handle operations ...
pass
# some dummy content for this example
self.content = b'''<html>
<h1>hello world!</h1>
<p>...</p>
</html>'''
self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.content))
self.setHeader(QNetworkRequest.ContentTypeHeader, "text/html")
self.readyRead.emit()
self.finished.emit()
def abort(self):
pass
def isSequential(self):
return True
def bytesAvailable(self):
ba = len(self.content) - self.bytes_read + super().bytesAvailable()
return ba
def readData(self, size):
if self.bytes_read >= len(self.content):
return None
data = self.content[self.bytes_read:self.bytes_read + size]
self.bytes_read += len(data)
return data
def manager(self):
return self.parent()
if __name__ == '__main__':
app = QApplication(sys.argv)
wv = QWebView()
enam = ExampleNetworkAccessManager()
wv.page().setNetworkAccessManager(enam)
wv.show()
wv.setUrl(QUrl("example://test.html"))
app.exec()
|
python drawing directed graph in SPYDER
Question: I am using SPYDER. I have below code. The code produces the graph. But the
graph is not clean. I would like to see layers in the graph - my first layer
has 'start' node, second layer has 1,2,3 node, third layer has 'a', 'b', 'c'
nodes and the last layer has 'end' node. Any idea how could i achieve my
objective?
import networkx as nx
import matplotlib.pyplot as plt
import os.path as path
![enter image description here][1]
G=nx.DiGraph()
G.add_nodes_from(['start',1,2,3,'a','b','c','end'])
G.nodes(data=True)
G.add_edge('start',2)
G.add_edge('start',3)
G.add_edge(2,'b')
G.add_edge('b','end')
G.add_edge('a','end')
G.add_edge('f','g')
nx.draw(G)
\------------------------update------------------ by layer i mean I should see
the network like in the attached figure. I want the network drawn that way
because a node in layer X will be connected directly ONLY to nodes in layer
X+1 or layer X-1
[enter image description here](http://i.stack.imgur.com/HKPLE.png)
Answer: It [seems that [networkx does not provide much for arranging
graphs](https://groups.google.com/forum/#!topic/networkx-discuss/f6x1GocCS30)
but I have only touched it a few times so I can't say for sure. I couldn't
find a way to do what you are asking.
However, I tried using [`graphviz`](http://www.graphviz.org/) (which has to be
installed first) to accomplish it. Credit for the ranking method goes to [this
SO answer](http://stackoverflow.com/a/22214653/377366).
# Copy-Paste Example
import networkx as nx
ranked_node_names = [['start'],
[1, 2, 3],
['a', 'b', 'c'],
['end']]
node_edges = [('start', 2),
('start', 3),
(2, 'b'),
('b', 'end'),
('a', 'end')]
# graph and base nodes/edges in networkx
G = nx.DiGraph()
for rank_of_nodes in ranked_node_names:
G.add_nodes_from(rank_of_nodes)
G.nodes(data=True)
G.add_edges_from(node_edges)
# I don't know a way to automatically arrange in networkx so using graphviz
A = nx.to_agraph(G)
A.graph_attr.update(rankdir='LR') # change direction of the layout
for rank_of_nodes in ranked_node_names:
A.add_subgraph(rank_of_nodes, rank='same')
# draw
A.draw('example.png', prog='dot')
# Default Output

# LR (left-right) Output

|
matplotlib imshow, ArtistAnimation and class attribute
Question: I am trying to code a Conway's game of life in Python and to display the
evolution. I have trouble displaying the output. I have pasted my whole code
below.
I used this example as a base: [from the matplotlib
doc](http://matplotlib.org/examples/animation/dynamic_image2.html). My
animation is static, but if I use
ims.append([plt.imshow(world.state+0, cmap=plt.cm.binary, interpolation='nearest')])
it animates correctly. I tried to write a function wolrd.get_state(), thinking
it was some kind of evaluation problem, to no avail.
This is driving me nuts, what am I missing here ?
Thanks
import numpy as np
from scipy.signal import convolve2d
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class World():
"""world information"""
def __init__(self, grid):
# noinspection PyNoneFunctionAssignment
self.state = np.empty(grid.shape)
self.__x_size = len(grid[0, :])
self.__y_size = len(grid[:, 0])
self.__x = range(self.__x_size)
self.__y = range(self.__y_size)
for i in self.__x:
for j in self.__y:
self.state[i, j] = grid[i, j]
def evolve(self):
alive_neighbours = convolve2d(self.state, np.ones((3, 3)), mode='same', boundary='wrap') - self.state
for i in self.__y:
for j in self.__x:
if alive_neighbours[i, j] < 2:
self.state[i, j] = 0
elif alive_neighbours[i, j] == 3:
self.state[i, j] = 1
elif alive_neighbours[i, j] > 3:
self.state[i, j] = 0
# self.state = np.random.randint(2, size=(self.__x_size, self.__y_size ))
if __name__ == "__main__":
nbx = 5
nby = 5
nb_gen = 5
initial_seed = np.random.randint(2, size=(nbx, nby))
world = World(initial_seed)
ims = []
fig = plt.figure()
for i in range(nb_gen):
ims.append([plt.imshow(world.state, cmap=plt.cm.binary, interpolation='nearest')])
world.evolve()
ani = animation.ArtistAnimation(fig, ims, interval=500, blit=True, repeat_delay=1000)
plt.show()
Note: I have succesfully used:
def animate(i):
world.evolve()
return (plt.imshow(world.state, cmap=plt.cm.binary, interpolation='nearest'),)
ani = animation.FuncAnimation(fig, animate, frames=nb_gen, interval=500, blit=True, repeat_delay=1000)
but this is not what I want.
Answer: Each frame of the animation is displaying the same world state.
Since the world class only modifies the state, a reference to the _same_
object is being passed into imshow() for each frame. Each frame of the
animation is referencing the same array.
Matplotlib doesn't draw the animation to the screen until plt.show() is
called, so only the final version of the arrays passed into imshow() can be
seen, which is the final version of World.state.
This is the same reason that
a = [1, 2, 3]
b = a
a.append(4)
print(b)
outputs [1, 2, 3, 4]. b points to a, so when a changes, b changes.
Copying the image to be shown fixes the problem.
ims.append([plt.imshow(world.state.copy(), cmap=plt.cm.binary, interpolation='nearest')])
This is also why world.state + 0 and np.random.randint(2, size=(self.__x_size,
self.__y_size )) worked: they both create new arrays, and don't modify the
arrays already passed into imshow().
|
solve an integral equation embedded with another integral equation by python 3.2
Question: I need to solve an integral equation embedded with another integral equation
by python 3.2 in win7.
There are 2 integral equations.
The code is here:
import numpy as np
from scipy.optimize.minpack import fsolve
from numpy import exp
from scipy.integrate.quadpack import quad
import matplotlib.pyplot as plt
import sympy as syp
lb = 0
def integrand2(x, a):
print("integrand2 called")
return x**(a-1) * exp(-x)
def integrand1(x, b, c):
print("integrand1 called")
integral , err = quad(integrand2, lb/b, syp.oo , args=(1+c))
return c/(b*integral)
def intergralFunc1(b,c):
integral,err = quad(integrand1, 0, 10, args=(b,c))
print("integral is ", integral, " and err is ", err)
print("b is ", b, " and c is ", c)
return 10 - integral
def findGuess():
vfunc = np.vectorize(intergralFunc1)
f1 = np.linspace(0.01, 10,10)
f2 = np.linspace(0.01, 10,10)
result = vfunc(f1, f2)
plt.plot(f1, result)
plt.xlabel('f1')
plt.subplot(211)
plt.plot(f2, result)
plt.xlabel('f2')
plt.subplot(212)
plt.show()
def solveFunction():
sol= fsolve(intergralFunc1, 5, 5, full_output=True)
return sol
if __name__ == '__main__':
findGuess()
sol = solveFunction()
print("sol is ", sol)
print("verification: \n")
print("f(b,c) is ", intergralFunc1(sol[0],5))
I got the results that make no sense.
integral is nan and err is nan
b is [ 5.] and c is 5
f(b,c) is nan
Any help would be appreciated !!!
Answer: For some reason `integrand1` is returning a `numpy.ndarray` where it is
expected to return a float.
Also on my machine `numpy` reported
y:289: UserWarning: Extremely bad integrand behavior occurs at some points of the
integration interval.
which means that your problem is numerically very instable. Therefore
nonsensical results are to be expected.
|
queryset filter month returns empty
Question: **Edit** : So I dropped this and then waited for a few days it started
working! Some how the upgrade to 1.6 took a while to 'propagate'! _shrugs_.
Thanks to all who chimed in!
The queryset filter `month` does not seem to be working correctly. I have a
bunch of objects in database with model called Note with field `pub_date`
storing a `datetime` object. I want to retrieve Note objects by month. So here
is a test I did:
>>> from blogengine.models import Note
>>> n = Note.objects.all()[0]
>>> n.pub_date
datetime.datetime(2014, 3, 8, 21, 15, 14, tzinfo=<UTC>)
>>> Note.objects.filter(pub_date__year = 2014)
[<Note: Note object>, <Note: Note object>]
>>> Note.objects.filter(pub_date__month =3)
[]
As you can see the `year` look up works correctly, giving me the two objects
with `year=2014`, but the `month` lookup returns nothing even though there is
an object with that month as can be seen from the first example object `n`.
This also happens for all other datetime lookups like `day` or `minute`.
Python = 2.7.5 Django 1.6.2
Answer: So I dropped this and then waited for a few days it started working! Some how
the upgrade to 1.6 took a while to 'propagate'! _shrugs_.
Thanks to all who chimed in!
|
Mezzanine Django Framework createdb error on Max OSX 10.9.2
Question: I want to build a django framework with mezzanine using python on my mac. from
their site they have this simple steps to create a framework in your terminal.
# Install from PyPI
$ pip install mezzanine
# Create a project
$ mezzanine-project myproject
$ cd myproject
# Create a database
$ python manage.py createdb
# Run the web server
$ python manage.py runserver
when i try to run "$ python manage.py createdb" this command it throws me this
error.
Traceback (most recent call last):
File "manage.py", line 28, in <module>
from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
pip freeze gives me this for more info.
Django==1.6.2
Mezzanine==3.0.9
Pillow==2.3.1
South==0.8.4
bleach==1.4
filebrowser-safe==0.3.2
future==0.9.0
grappelli-safe==0.3.7
html5lib==0.999
oauthlib==0.6.1
pytz==2014.1.1
requests==2.2.1
requests-oauthlib==0.4.0
six==1.6.1
tzlocal==1.0
vboxapi==1.0
virtualenv==1.11.4
wsgiref==0.1.2
Answer: You will have to set your path variables right. Python is not able to locate
Django:
To verify, with the python shell try:
import django
django.version
If you encounter the same problem, you will have to adjust $PATH variable.
Alternative to this would be using a virtual env.
|
How to select multiple columns based on their names in python?
Question: I am new to python so sorry if this is too obvious.
I have a dataframe that looks like below:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 10))
df.columns = ['date1', 'date2', 'date3', 'name1', 'col1', 'col2', 'col3', 'name2', 'date4', 'date5']
date1 date2 date3 name1 col1 col2 col3 \
0 -0.177090 0.417442 -0.930226 0.460750 1.062997 0.534942 -1.082967
1 -0.942154 0.047837 -0.494979 2.437469 -0.446984 0.709556 -0.135978
2 -1.544783 0.129307 -0.169556 -0.890697 2.650924 0.976610 0.290226
3 -0.651220 -0.196342 0.712601 0.641927 -0.009921 -0.038450 0.498087
4 -0.299145 -1.407747 1.914364 0.554330 -0.196702 2.037057 -0.287942
name2 date4 date5
0 -0.318310 0.358619 -0.243150
1 1.171024 0.277943 -1.584723
2 -0.546707 -1.951831 0.678125
3 -0.510261 -0.018574 -0.212684
4 1.929841 0.995625 -1.125044
I'd like to to keep all columns that have, for example, 'date' in their names.
That is, I want to keep columns 'date1', 'date2', 'date3', 'date4', 'date5',
etc. In some statistical packages I can use * to represent all possible
characters and use a command like this:
keep date*
Is there an equivalent way of doing this in python?
Thanks very much for any help.
Answer: You can use the [`filter`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.filter.html) method. To do the
equivalent of `keep date*`:
In [62]: df.filter(like='date')
Out[62]:
date1 date2 date3 date4 date5
0 0.091744 -0.431606 1.280286 0.263137 0.444550
1 0.688155 0.583918 0.957041 0.446047 1.654274
2 0.109004 0.608818 0.091498 0.940406 0.476479
3 -0.874016 1.312567 0.326480 1.213292 0.504049
4 -0.203515 -0.979086 0.458790 1.012296 -2.446310
The `filter` method has also a `regex` keyword, to do some more complex
filtering.
Eg to drop all dates, you can provide a regex expression that says to not
match a certain string: `df.filter(regex="^(?!date).*$")`
In the upcoming pandas (0.14), this functionality will also be provided in
`drop` method, so this will be easier.
|
Creating folders in outlook 2010 using python
Question: I know how to get the name of folders in outlook 2010 using the code below:
import win32com.client
ol = win32com.client.Dispatch("Outlook.Application")
ns = ol.GetNamespace("MAPI")
inbox = ns.Folders(6).Folders(2)
How can I add a folder in `Folder(2)`? I tried the `Folders.Add Method` method
as mentioned in <http://support.microsoft.com/kb/208520> but fail.
Answer: I think you have made a small mistake, the `Add` function is the function of
`Folders`. Not a certain Folder like `Folders(2)`
You can try the code below and it should work:
import win32com.client
ol = win32com.client.Dispatch("Outlook.Application")
ns = ol.GetNamespace("MAPI")
inbox = ns.Folders(6).Folders(2)
inbox.Folders.Add("My Folder Src")
|
Is there a Python 3.x debugger for embedded interpreter?
Question: I've embedded python in a C++ application. Is there any graphical debugger
that I can attach to debug scrips that run in the embedded console for Python
3.4?
Previously (when using Python 2.7) I've used Winpdb and attached the debugger
with
import rpdb2; rpdb2.start_embedded_debugger(password)
but Winpdb doesn't work with wxPython Phoenix that is needed for Python 3.x.
I must load the debugger from inside the embedded interpreter since a lot of
modules are only available there, so scripts can't be run outside that
environment.
What alternatives are there to Winpdb for embedded debugging with GUI? Or is
there an updated version of Winpdb that works with wxPython Phoenix?
Thanks!
Answer: You can use PTVS (Python Tools for Visual Studio) or PyDev on Eclipse Remote
debugging.
|
Special HTML characters in Python to ASCII
Question: I want to convert special characters which I see during web-page reading to
the ASCII format. I've tried a lot, but I can't figure it out. I will give
some examples below which are stored in a string in Python.I don't know what
the current encoding of the web-page is, but I want to convert it to ASCII
format.
Apaydın Ünal > want this to Apaydin Unal
Íñigo Martínez > want this to Inigo Martinez
Üstünel > want this to Ustunel
Who can help me?
EDIT: Thanks, I forgot. I'm using Python 2.7
Answer: Give <https://pypi.python.org/pypi/Unidecode> a try:
>>> from unidecode import unidecode
>>> unidecode(u'ko\u017eu\u0161\u010dek')
'kozuscek'
And to detect the encoding, see the question [Python: Is there a way to
determine the encoding of text
file?](http://stackoverflow.com/questions/436220/python-is-there-a-way-to-
determine-the-encoding-of-text-file)
|
Python readlines string issue
Question:
import os
fname = "input1.txt"
if os.path.isfile(fname):
f = open("input1.txt", "r")
for row in f.readlines():
if "logging failed" in row:
print "the file does say 'logging failed' in it"
else:
print "the file doesn\'t say 'logging failed' in it"
My `input1.txt` says **logging failedtest** so how can i make it notice the
"test" so that it should only printout logging failed if the text doesnt have
any additional characters?
EDIT: sorry for bad english, what I meant is: If input1.txt has only "logging
failed", then it should print out 'file does say it'. If it has any other
characters (for example 'logging faaaailed' or 'logging failed1', then it
should print out that 'it doesnt say logging failed'. Now it just reads that
there is logging failed and ignores any other characters in the input1.txt
Answer: Maybe I'm missing something, but why can't you explicitly compare _row_ to the
string _"logging failed"_ ?
eg. `if row == "logging failed"`
|
how to use reportlab with google app engine
Question: I am unable to import reportlab properly under google app engine. According to
the following [guide](http://blog.notdot.net/2010/04/Generating-PDFs-on-App-
Engine-Python-and-introducing-Mapvelopes) (and several other places on the
web):
"All you have to do is download it and copy the 'reportab' directory into the
root directory of your app. "
When I do so (I download the reportlab-3.0.zip from
[here](http://www.reportlab.com/software/opensource/rl-toolkit/download/)) and
extract it into the root directory of my application, as I try to import
reportlab using following lines:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
I get an import error
ImportError: No module named reportlab.pdfgen
I tried googling but to no avail. Any help on this would be greatly
appreciated as I am not sure what else I could try. Many thanks!
* * *
One other thing I tried was copying what's in the src directory of the
downloaded zip under the root directory of my application but that didn't work
either. The error I get using this is:
ImportError: Cannot re-init internal module __main__
* * *
Seems version 2.7 imports okay, only issues with 3.0
Answer: If you just unzip the reportlab zip in your root directory of your
application, then it won't work, as the reportlab zip is intended for a local
setup using `setup.py`, which you don't use in appengine.
You should look inside the zip to the src directory and inside that is a
reportlab directory - in my case the zip file contents will be
`reportlab-3.0/src/reportlab` copy/move this `reportlab` directory to the root
level of your application.
You should probably also read up on how import and modules work oin python. If
you where familiar with this you could work it out for yourself looking at the
structure of the zip contents.
ALso pay attention to the prerequesites if you want to work with images. If
you do you will need to install PIL locally, and enable it in app.yaml however
you don't deploy the PIL code. You can read more about this in the appengine
3rd part libraries docs.
|
How can I test if Python http.server.HTTPServer is serving forever?
Question: I am writing this little demo code to start an HTTP server, test that it is
running successfully and then exit.
import http.server
import urllib.request
import threading
# Start HTTP server
httpd = http.server.HTTPServer(('', 8080), http.server.SimpleHTTPRequestHandler)
thread = threading.Thread(target=httpd.serve_forever)
thread.start()
# Test HTTP server and shutdown
print(urllib.request.urlopen('http://127.0.0.1:8080/').read())
httpd.shutdown()
This seems to be working fine but it might be working fine due to luck. You
see, I am invoking `httpd.serve_forever` in a separate thread, so that my
script doesn't block at this call and it can continue with the
`urllib.request.urlopen` call to test the HTTP server.
But I must ensure that I am making the `urllib.request.urlopen` call only
after `httpd.serve_forever` has been invoked successfully and the server is
now serving requests.
Is there any flag or any method in `http.server.HTTPServer` or
`socketserver.TCPServer` that will help me to ensure that I begin testing it
with `urllib.request.urlopen` only after it is ready to serve requests?
Answer: If your goal is to not get an empty / invalid answer in your urlopen, the
answer is you won't. You actually open a socket with this line:
http.server.HTTPServer(...)
so after it (with still one thread running) you **already** have an open
socket listening for incoming connections (although nothing dispatching
requests yet). After that we may have a race of two threads. Consider both
possibilities:
1. The server thread runs serve_forever first. Well, it's the case you're aiming at.
2. The main thread connects first. Your connection will be accepted and will wait for something to dispatch it to the handler. Then the server thread runs serve_forever, attaches a dispatcher and your request still gets processed.
|
Should I use `app.exec()` or `app.exec_()` in my PyQt application?
Question: I use Python 3 and PyQt5. Here's my test PyQt5 program, focus on the last 2
lines:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class window(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle('test')
self.resize(250,200)
app=QApplication(sys.argv)
w=window()
w.show()
sys.exit(app.exec())
#sys.exit(app.exec_())
I know `exec` is a language keyword in Python. But code on [Official PyQt5
Documentation](http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html#object-
destruction-on-exit) _(specifically the**Object Destruction on Exit** part)_.
I see that example shows use of `app.exec()` which confuses me.
When I tested it on my machine. I found there is no any visible difference
from my end. Both with and without `_` produces the same output in no time
difference.
My question is:
* Is there anything wrong going when I use `app.exec()`? like clashing with Python's internal `exec`? I suspect because both `exec`'s are executing something.
* If not, can I use both interchangeably?
Answer: That's because until Python 3, `exec` [was a reserved
keyword](http://docs.python.org/2.7/reference/lexical_analysis.html#keywords),
so the PyQt devs added underscore to it. From Python 3 onwards, `exec` is [no
longer a reserved
keyword](http://docs.python.org/3/reference/lexical_analysis.html#keywords)
(because it is a builtin function; same situation as `print`), so it made
sense in PyQt5 to provide a version without an underscore to be consistent
with C++ docs, but keep a version with underscore for backwards compatibility.
So for PyQt5 with Python 3, the two `exec` functions are the same. For older
PyQt, only `exec_()` is available.
|
Error building Android Library project using Python in Eclipse
Question: I'm trying to build this library project <https://crosswalk-project.org>.
I wish to implement the XWalkView in my application to use WebRTC.
I followed the following steps:
1. Downloaded the stable ARM release
2. Extracted the core library archive (It is an Android project by default)
3. I imported the project into Eclipse
4. The Python script "prepare_r_java.py" is responsible for creating R.java files required for the project, without which the library won't complie.
5. When I try to build, I get the following error in Eclipse
Errors occurred during the build.
Errors running builder 'Integrated External Tool Builder' on project'xwalk_core_library'.
Exception occurred executing command line.
Cannot run program "C:\Users\abc\Desktop\crosswalk-3.32.53.4-x86\xwalk_core_library\prepare_r_java.py"
(in directory "C:\Users\abc\Desktop\crosswalk-3.32.53.4-x86\xwalk_core_library"): CreateProcess error=193, %1 is not a valid Win32 application
Exception occurred executing command line.
Cannot run program "C:\Users\abc\Desktop\crosswalk-3.32.53.4-x86\xwalk_core_library\prepare_r_java.py"
(in directory "C:\Users\abc\Desktop\crosswalk-3.32.53.4-x86\xwalk_core_library"): CreateProcess error=193, %1 is not a valid Win32 application
I have Python, ANT, Java installed and the PATH variable set and working fine.
What am I missing? Is there any other method to implement WebRTC in an Android
WebView (Non-native code)?
Answer: I downloaded the ARM build just now and encountered the same error while
importing the `xwalk_core_library` into eclipse. I fixed it by executing the
`prepare_r_java.py` script externally through python and importing the
generated `R.java` file in classes where it was referenced.
Also, after looking around, I found that the issue that you've mentioned is
actually a bug. [check it here](https://crosswalk-
project.org/jira/si/jira.issueviews%3aissue-html/XWALK-1036/XWALK-1036.html).
Turning off 'Build Automatically' in eclipse fixes it.
* * *
**EDIT** : The above method still threw the error while exporting the apk file
and thus failed the export process.
In order to get the whole thing to compile and work without the nag, Here's
what I did before importing the `xwalk_core_library` into eclipse.
1. Delete `.externalToolBuilders`folder.
2. Edit `.project` file and delete the following lines from line no.18 to 27
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>auto,full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value><project>/.externalToolBuilders/prepare_r_java.launch</value>
</dictionary>
</arguments>
</buildCommand>
3. Edit `build.xml` and delete the following line from line no.27
<import file="precompile.xml" />
4. Delete `precompile.xml` and `prepare_r_java.py`
Now import the library into eclipse. :)
|
how can the directory of a usb drive connected to a system be obtained?
Question: I need to obtain the path to the directory created for a usb drive(I think
it's something like /media/user/xxxxx) for a simple usb mass storage device
browser that I am making. Can anyone suggest the best/simplest way to do this?
I am using an Ubuntu 13.10 machine and will be using it on a linux device.
Need this in python.
Answer: This should get you started:
#!/usr/bin/env python
import os
from glob import glob
from subprocess import check_output, CalledProcessError
def get_usb_devices():
sdb_devices = map(os.path.realpath, glob('/sys/block/sd*'))
usb_devices = (dev for dev in sdb_devices
if 'usb' in dev.split('/')[5])
return dict((os.path.basename(dev), dev) for dev in usb_devices)
def get_mount_points(devices=None):
devices = devices or get_usb_devices() # if devices are None: get_usb_devices
output = check_output(['mount']).splitlines()
is_usb = lambda path: any(dev in path for dev in devices)
usb_info = (line for line in output if is_usb(line.split()[0]))
return [(info.split()[0], info.split()[2]) for info in usb_info]
if __name__ == '__main__':
print get_mount_points()
How does it work?
First, we parse `/sys/block` for `sd*` files (courtesy of
<http://stackoverflow.com/a/3881817/1388392>) to filter out usb devices. Later
you call `mount` and parse output for lines only for those devices.
Of course they might be some edge cases, when this won't work, portability
issues etc. Or better ways to do it. But for more information you should
rather seek help on SuperUser or ServerFault, with more experienced linux
hackers.
|
How to add an icon to an exe developed through py2exe
Question: I am working on windows-7 64 bit machine using python 2.7. Using **py2exe** to
convert mycode.py script into an exe. I am not able to find the reason why
icon to an exe is not embedded.
My setup.py is:
from distutils.core import setup
import py2exe
import time
setup(
windows=[{'script':'MyScript.pyw',
'icon_resources':[(1,'MyIcon.ico')}],
options=dict(py2exe=dict(
packages='keyring.backends',
)),
)
time.sleep(2)
I also looked into [CustomIcons](http://www.py2exe.org/index.cgi/CustomIcons),
[q&a](http://stackoverflow.com/questions/525329/embedding-icon-in-exe-with-
py2exe-visible-in-vista).
Answer: [Resource Hacker](http://www.angusj.com/resourcehacker/) might be helpful.
|
Gimp, Script-Fu: How can I set a value in the colormap directly
Question: I have a Scriptfu script written in Python for Gimp which applies several
steps on an existing image and converts it to an indexed image in the process.
The lightest color in the resulting image is always nearly white; I want to
set it to _exactly_ white. Conveniently, that lightest color is always the
topmost color in the colormap of the indexed image, so I just want to set the
topmost color in the colormap to white.
I have found nothing in the API description on how to manipulate the colormap
(i. e. colors therein), so currently that step I always do manually (Windows →
Dockable Dialogs → Colormap → Click on the topmost color → enter "ffffff" in
the text widget → close dialog). But of course the whole idea of the Scriptfu
stuff is to automate all steps, not just a few.
Can anybody tell me how to access the colormap from a Python Scriptfu script?
Here is my current code (which does not even attempt to perform that last
step, due to lack of ideas on how to do it):
#!/usr/bin/env python
"""
paperwhite -- a gimp plugin (place me at ~/.gimp-2.6/plug-ins/ and give
me execution permissions) for making fotographs of papers
(documents) white in the background
"""
import math
from gimpfu import *
def python_paperwhite(timg, tdrawable, radius=12):
layer = tdrawable.copy()
timg.add_layer(layer)
layer.mode = DIVIDE_MODE
pdb.plug_in_despeckle(timg, layer, radius, 2, 7, 248)
timg.flatten()
pdb.gimp_levels(timg.layers[0], 0, 10, 230, 1.0, 0, 255)
pdb.gimp_image_convert_indexed(timg,
NO_DITHER, MAKE_PALETTE, 16, False, True, '')
(bytesCount, colorMap) = pdb.gimp_image_get_colormap(timg)
pdb.gimp_message("Consider saving as PNG now!")
register(
"python_fu_paperwhite",
"Make the paper of the photographed paper document white.",
"Make the paper of the photographed paper document white.",
"Alfe Berlin",
"Alfe Berlin",
"2012-2012",
"<Image>/Filters/Artistic/Paperw_hite...",
"RGB*, GRAY*",
[
(PF_INT, "radius", "Radius", 12),
],
[],
python_paperwhite)
main()
Answer: just use `pdb.gimp_image_get_colormap` and `pdb.gimp_image_set_colormap`.
If the entry you want to change is indeed always the first, it would suffice
to write:
colormap = pdb.gimp_image_get_colormap(timg)[1]
colormap = (255,255,255) + colormap[3:]
pdb.gimp_image_set_colormap(timg, len(colormap), colormap)
|
Python- Regular expression to match" <textarea> </textarea> " and anything between them
Question: If the text was
`<textarea>` **xyz asdf qwr** `</textarea>`
I'm trying to write a regular expression which will help me extract the text
in **bold**.
So far I have reached `[(<textarea)][</textarea>)]` which will capture the
tags but I haven't been able to actually capture the text in between the two
tags.
I also tried `[(<textarea)]+.[</textarea>)]` and even
`[[(<textarea)]+.[</textarea>)]` but that too isn't giving the right results.
Can someone please throw some light on this or share some links which will
help me reach a solution?
Answer: Is there a particular reason that you must use regular expression to parse
what seems like HTML? I wouldn't do it. See [RegEx match open tags except
XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-
match-open-tags-except-xhtml-self-contained-tags) for the best explanation.
This becomes really simple if you use the
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) module, which
is going to be far better at parsing HTML (especially if it is messy HTML).
import bs4
f = open("test.html")
soup = bs4.BeautifulSoup(f)
for textarea in soup.find_all('textarea'):
print textarea.get_text()
|
How to avoid overwriting previous package installation with distutils
Question: I have a python package that uses distutils. I would like to configure the
setup.py to do either of the following:
* Detect a previously-installed version of the package and raise an error
* Offer to remove the previously-installed version before proceeding with the installation
Any hints? A custom subclass of distutils.command.install is probably needed,
but the [documentation](http://docs.python.org/2/distutils/apiref.html#module-
distutils.command.install) is a bit terse.
Answer: Ok, here's my initial answer. Hopefully somebody else has a better plan. I'm
not sure if Install.install_libbase is the correct place to look or if it just
happens to be correct on my system..
import distutils.command.install
class Install(distutils.command.install.install):
def run(self):
name = self.config_vars['dist_name']
if name in os.listdir(self.install_libbase):
raise Exception("It appears another version of %s is already "
"installed at %s; remove this before installing."
% (name, self.install_libbase))
print("Installing to %s" % self.install_libbase)
return distutils.command.install.install.run(self)
setup(cmdclass={'install': Install})
|
Kivy pygame error
Question: I've been trying to get Kivy to work on my Mac (Lion), but I've been
encountering issues. I followed the instructions on the Kivy site, and since
Kivy 1.8 supports Python 3, I wanted to run it with 3.3, and I finally got
that to work, by editing the kivy file to point to 3.3 instead of 2.7. I tried
drop a .py program on the Kivy icon, the app opened but nothing happened. So I
tried to run it from the command line. It opened 3.3, as expected, but I got
the following error.
Python 3.3.4 (default, Mar 6 2014, 20:14:14)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/Kivy.app/Contents/Resources/lib/sitepackages/pygame/__init__.py", line 127, in <module>
from pygame.base import *
ImportError: dlopen(/Applications/Kivy.app/Contents/Resources/lib/sitepackages/pygame/base.so, 2): Symbol not found: _PyCObject_Type
Referenced from: /Applications/Kivy.app/Contents/Resources/lib/sitepackages/pygame/base.so
Expected in: flat namespace
in /Applications/Kivy.app/Contents/Resources/lib/sitepackages/pygame/base.so
I have no idea why I would get this error, since I previously installed pygame
for 3.3, and `import pygame` or `from pygame.base import *` work error free.
Would this issue with pygame explain why .py files fail to execute when I drop
them onto the Kivy icon?
Answer: Kivy.app and all the dependencies included in it is compiled with and for
Python 2.7. You cannot use it for 3.3.
If you want to try Kivy with 3.3, you also need to compile Kivy yourself :)
|
Why am I getting an indentation error, "unexpected indent" in my code? Python
Question: On the first line of my code, I seem to be getting an indentation error. I
have 2 spaces as an indent on my code, as I always do since my class requires
it, but for the first time I'm getting an error for it.
My code looks like this at the start.
import math
def main():
Answer: You should not indent python code unless you have something like `def`, `for`,
`if` and similar such things preceding the indentation block.
Eg:
for thing in variable:
#indent code
pass
def aFunction():
#indent
pass
#invalid indentation:
def aFunction2():
pass
As you can imagine, the code not only becomes hard for human eyes to
interpret, but also for your machine to interpret because it cannot realise
where the indentation starts or ends.
Speak to your teacher about this, they might be using an interpreter which
allows them to indent their entire script by a particular amount. I would
never recommend this though.
|
how import statement executes in python?
Question: I read about about import statement in pydocs. It says it executes in two
steps. (1)find a module, and initialize it if necessary; (2) define a name or
names in the local namespace (of the scope where the import statement occurs).
The first form (without from) repeats these steps for each identifier in the
list. The form with from performs step (1) once, and then performs step (2)
repeatedly.
I understood some bits of it, but its still not clear to me completely.I am
mainly confused about initialization step and at last it says about repeating
some step.The only thing which i understood is that if we use say for example:
import sys
in this case if we use functions of this module in our script we need call
them using sys.fun_name(). As the functions weren't made available locally
using this importstatement. But when we use
from sys import argv
We can simply use argv function as it makes it available local for out srcipt.
Can someone please explain me its working and also let me know my
understanding is correct or not.
Even i tried to import one of the my script into another script and it gave
some strange result which i know have something to do with first step of
import statement,(initiallization)
##### ex17.py #####
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" %(arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" %(arg1, arg2)
def print_one(arg1):
print "arg1: %r" %arg1
def print_none():
print "I got nothing."
print_two("Gaurav","Pareek")
print_two_again("Gaurav","Pareek")
print_one("First!")
print_none()
####### ex18.py ######
import ex17
ex17.print_none()
The output which i am getting when executing ex18.py is as below
arg1: 'Gaurav', arg2: 'Pareek'
arg1: 'Gaurav', arg2: 'Pareek'
arg1: 'First!'
I got nothing.
I got nothing.
why is it like this. It should only print I got nothing once.
Answer: It prints `"I got nothing."` twice because the function `print_none` is being
invoked twice. Once when loading the ex17 module (since it's imported in ex18)
and once when it's called in the ex18 module. If you don't want the function
calls in ex17 to execute but only the function defs to be loaded, then you may
write them as follows
## in ex17.py
if __name__ == '__main__':
print_two("Gaurav","Pareek")
print_two_again("Gaurav","Pareek")
print_one("First!")
print_none()
Now this code will only be executed if it's run as a script ie. `$ python
ex17.py` but not when it's imported into some other module. More about
__main__ [here](http://stackoverflow.com/questions/419163/what-does-if-name-
main-do)
About the excerpt from the docs, it simply says how the two import forms
differ. Step 1 is responsible for finding and initializing the module and step
2 for adding the names to the local namespace. So in case of,
import sys
both step 1 and 2 will be executed once. But in case of,
from sys import argv, stdout
step 1 will be executed just once, but step 2 will be executed twice as it
needs to add both `argv` and `stdout` to the local namespace.
|
piping from stdin to a python code in a bash script
Question: I have a bash script, f, that contains python code. That python code reads
from standard input. I want to be able to call my bash script as follows:
f input.txt > output.txt
In the example above, the python code will read from input.txt and will write
to output.txt.
I'm not sure how to do this. I know that if I wanted to just write to a file,
then my bash script would look like this
#!/bin/bash
python << EOPYTHON > output.txt
#python code goes here
EOPYTHON
I tried changing the second line in the code above to the following, but
without luck
python << EOPYTHON $*
I'm not sure how else to go about doing this. Any suggestions?
**EDIT** I'll give a more concrete example. Consider the following bash
script, f
#!/bin/bash
python << EOPYTHON
import sys
import fileinput
for i in fileinput.input():
sys.stdout.write(i + '\n')
EOPYTHON
I want to run my code with the following command
f input.txt > output.txt
How do I change my bash script so that it uses "input.txt" as the input
stream?
Answer: **Updated Answer**
If you absolutely must run the way you ask, you could do something like this:
#!/bin/bash
python -c 'import os
for i in range(3):
for j in range(3):
print(i + j)
' < "$1"
**Original Answer**
Save your python code in a file called `script.py` and change your script `f`
to this:
#!/bin/bash
python script.py < "$1"
|
python regex token capture
Question: I need to capture small code (token) from html with regex, I'm writing code
with BeautifulSoup but it is not possible to compile with py2exe, so for this
I need a solution wihth regex. My html code is this:
<form method="post" enctype="multipart/form-data" class="wp-upload-form" action="http://localhost/wp-admin/update.php?action=upload-plugin">
<input type="hidden" id="_wpnonce" name="_wpnonce" value="a7a9167537"><input type="hidden" name="_wp_http_referer" value="/wp-admin/plugin-install.php?tab=upload"> <label class="screen-reader-text" for="pluginzip">Plugin zip file</label>
<input type="file" id="pluginzip" name="pluginzip">
<input type="submit" name="install-plugin-submit" id="install-plugin-submit" class="button" value="Install Now" disabled=""> </form>
and I need to capture this code: `a7a9167537`
I wrote this regex but it did not work:
id="_wpnonce" name="_wpnonce" value="(.*)"
Answer: Try :
import re
searchText = '<form method="post" enctype="multipart/form-data" class="wp-upload-form" action="http://localhost/wp-admin/update.php?action=upload-plugin"><input type="hidden" id="_wpnonce" name="_wpnonce" value="a7a9167537"><input type="hidden" name="_wp_http_referer" value="/wp-admin/plugin-install.php?tab=upload"> <label class="screen-reader-text" for="pluginzip">Plugin zip file</label><input type="file" id="pluginzip" name="pluginzip"><input type="submit" name="install-plugin-submit" id="install-plugin-submit" class="button" value="Install Now" disabled=""> </form>'
print re.sub("(.+name=\"_wpnonce\"\\ value=\"([\\d\\w]{10})\">.+)", "\\2", searchText)
|
can't find module 'cx_Freeze__init__'
Question: I'm trying to convert my Python project to a standalone executable, in order
to run it on other servers that don't have Python installed.
Command used:
python setup.py build > build.log
When I try to run the resulting exe, it always spits out the following error
message:
zipimport.ZipImportError: can't find module 'cx_Freeze__init__'
Fatal Python error: unable to locate initialization module
Current thread 0x00000b8c (most recent call first):
I've tried to define all the libraries I'm using throughout my project in the
`setup.py` module, though this has made no difference.
I have also added the DLL files to include ([described in the post cx-freeze
doesn't find all dependencies](http://stackoverflow.com/questions/15486292/cx-
freeze-doesnt-find-all-dependencies)).
The project consists of the following libraries (output of `pip list`):
cx-Freeze (4.3.2)
docopt (0.6.1)
pip (1.5.4)
psutil (2.0.0)
pywin32 (218)
requests (2.2.1)
setuptools (2.2)
virtualenv (1.11.4)
WMI (1.4.9)
Contents of `setup.py`:
include_files=[
(r'C:\Python34\Lib\site-packages\pywin32_system32\pywintypes34.dll', 'pywintypes34.dll'),
(r'C:\Python34\Lib\site-packages\pywin32_system32\pythoncom34.dll', 'pythoncom34.dll'),]
build_exe_options = dict(
packages=['os', 'concurrent.futures', 'datetime', 'docopt', 'email.mime.text', 'configparser', 'enum',
'json', 'logging', 'psutil', 'requests', 'smtplib', 'socket', 'subprocess', 'sys', 'threading', 'time',
'wmi', 'pythoncom'],
excludes=[],
include_files=include_files)
executable = Executable(
script = 'pyWatch.py',
copyDependentFiles = True,
base = 'Console')
setup( name= "pyWatch",
version= "0.1",
options= {"build_exe": build_exe_options},
executables= [executable])
cx_freeze's output (too large to paste here): <http://pastebin.com/2c4hUSeD>
All help would be greatly appreciated!
Answer: instead of cx_freeze which is last version updated on 2014
there is a module called pyinstaller which is last version update on 2016
[pyinstaller](https://github.com/pyinstaller/pyinstaller)
also easy to use just pyinstaller myscript.py and bam
|
Sorting the order of bars in pandas/matplotlib bar plots
Question: What is the Pythonic/pandas way of sorting 'levels' within a column in pandas
to give a specific ordering of bars in bar plot.
For example, given:
import pandas as pd
df=pd.DataFrame({'group':['a','a','a','a','a','a','a','b','b','b','b','b','b','b'],
'day':['Mon','Tues','Fri','Thurs','Sat','Sun','Weds','Fri','Sun','Thurs','Sat','Weds','Mon','Tues'],
'amount':[1,2,4,2,1,1,2,4,5,3,4,2,1,3]})
dfx=df.groupby(['group'])
dfx.plot(kind='bar',x='day')
I can generate the following pair of plots:

The order of the bars follows the row order.
What's the best way of reordering the data so that the bar charts have bars
ordered Mon-Sun?
UPDATE: this rubbish solution works - but it's far from elegant in the way it
uses an extra sorting column:
df2=pd.DataFrame({'day':['Mon', 'Tues', 'Weds','Thurs','Fri','Sat','Sun'],'num':[0,1,2,3,4,5,6]})
df=pd.merge(df,df2,on='day')
df = df.sort('num')
dfx=df.groupby(['group'])
dfx.plot(kind='bar',x='day')
FURTHER GENERALISATION:
Is there a solution that also fixes the order of bars in a 'dodged' bar plot:
df.pivot('day','group','amount').plot(kind='bar')

Answer: You'll have to provide a mapping to specify how to order the day names. (If
they were stored as proper dates, there would be other ways to do this.)
**Updated:**
Build the key. You could write out a dictionary explicitly or use something
clever like this dict comprehension.
weekdays = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun']
mapping = {day: i for i, day in enumerate(weekdays)}
key = df['day'].map(mapping)
And the sorting is simple:
df.iloc[key.argsort()]
|
Python subprocess command to run silent, prevent cmd from appearing
Question: I have some complicated Python3 GUI code with tinker, and compiled with
cx_Freeze.
The issue only occurs when run on Windows.
subprocess check_ouptut (or Popen) runs a similar command:
import subprocess
VAL = subprocess.check_output(['adb.exe', 'version'], shell=False, stdout=subprocess.PIPE).decode()
So I need to capture the output and store it as VAL. However, when it happens,
the cmd window pops up, and closes after the value was read. I have a set of
commands those do similar thing, and it results in the adb.exe popping up in a
cmd window, which is really annoying.
Is there a way to make these silent, so the cmd does NOT pop up?
As I mentioned, the code is run as GUI/tkinter, compiled with cx_Freeze, and
only occurs on Microsoft Windows (does not happen on Linux).
Thank you.
Answer: My solution was:
import subprocess,os
startupinfo = None
if os.platform == 'win32':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
VAL = subprocess.check_output(['adb.exe', 'version'], shell=False, startupinfo=startupinfo).decode()
|
Generating Google Cloud Endpoints Android client classes from Python project
Question: I have coded and tested a Python Endpoints server-side for an Android app that
I'm building.
The coded server-side works perfectly on the API Explorer. I'm also able to
generate the zip containing the classes jar file, but when I import it, either
on Eclipse or on Android Studio, I'm unable to use it's classes on my Android
Project.
On Eclipse, under Android Private Libraries, I can see the model module, but
none of it's classes. The main API classes are also missing.
On Android Studio, I can see all the classes when I expand the included jar
file, but I'm unable to use any of them on my project as they do not resolve,
even after a manual import. It seems that AS is properly importing the JAR as
a lib, as while typing the import line on any of the project classes, auto-
complete works, but it is missing all the classes.
Here is the command I'm using to generate the JAR file:
endpointscfg.py get_client_lib java --hostname localhost:8080 main.MyApi
My services class starts as following:
@endpoints.api(name='myapi', version='v1')
class MyApi(remote.Service):
I'm doing something wrong?
Also, from the java classes zip file, should I import into my Android project
all the jar files contained by the libs directory?
Thanks in advance.
* * *
**More information:**
The generated jar contains a main class as follows:
public class MyApi extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
}
and this main class has the following inner class:
public class Blob {
public Request request(java.lang.String type) throws java.io.IOException {
Request result = new Request(type);
initialize(result);
return result;
}
The inner class Blob has the bellow error on it's Request result object:
initialize (com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?>) in MyApi cannot be applied to (com.appspot.trim_bot.myapi.MyApi.Blob.Request)
* * *
**Added on April 16th:**
It seems that the compiled EndPoints classes cannot resolve their
dependencies.
Answer: I had a similar problem and I worked around it doing the following. Take note
that this is probably not the most efficient way of doing it.
* my app engine project is set to run with ant, so I generate the library using
$/appengine-java-sdk/bin/endpoints.sh get-client-lib name.MessageEndpoint
$mkdir tmp
$mv name-v1-java.zip tmp/
$cd tmp; unzip name-v1-java.zip; jar -xvf name_appspot_com-foo-v1.jar
$mv com {root of android studio project/src/main/java}
* edit src/build.gradle in android studio, add the list of jar that were added when building the endpoint client library.
compile(group: 'com.google.api-client', name: 'google-api-client-appengine',
version: '1.18.0-rc')
compile(group: 'com.google.api-client', name: 'google-api-client-gson',
version: '1.18.0-rc')
....
rebuild and it looks like it is working.
|
UnboundLocalError when use element tree to parse XML in plugin QGIS
Question: I make plugin to open XML and read it then parse it to show some information,
this is code I use
from PyQt4 import QtCore, QtGui
from ui_latih import Ui_latih
import xml.etree.ElementTree as ETree
# create the dialog for zoom to point
class latihDialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
# Set up the user interface from Designer.
self.ui = Ui_latih()
self.ui.setupUi(self)
cariButton = self.ui.btnCari
QtCore.QObject.connect(cariButton, QtCore.SIGNAL('clicked()'),self.cari)
def cari(self, event=None):
#open dialog
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '*.xml')
self.ui.lineFile.setText(filename)
#panggil isi data
self.isiDataFile(filename)
def isiDataFile(self, nmfile):
#buka dengan open mode baca
teksFile = open(nmfile, 'r').read()
self.ui.textFile.setText(teksFile)
#parse XML FIle
self.parsethis(teksFile)
def parsethis(self, parse):
doc = ETree.fromstring(parse)
for elem in doc.findall('{Default_Config/gco#}Integer'):
a=elem.tag, elem.text
print a
self.ui.lineSkala.setText(a)
I parse a big xml file (total 14 page when i print it) and one line that i
want to parse showed like this
<gmd:denominator>
<gco:Integer>ValueScale</gco:Integer>
</gmd:denominator>
I want to put ValueScale to show in QlineEdit and i get error message say:
File "C:\Users\Mr.Pakde/.qgis2/python/plugins\latih\latihdialog.py", line 65, in parsethis
self.ui.lineSkala.setText(a)
UnboundLocalError: local variable 'a' referenced before assignment
can someone help me?
Answer: The problem lies probably here:
for elem in doc.findall('{Default_Config/gco#}Integer'):
a=elem.tag, elem.text
print a
self.ui.lineSkala.setText(a)
If `doc.findall` returns `None`, there will be no `a`. You need to check for
the presence of a:
try:
self.ui.lineSkala.setText(a)
except (UnboundLocalError, NameError):
do_here_something_else...
|
Difference between using APSchedule and time.sleep() in Python
Question: I am creating a script that has a function that should run every X hour.
One way of doing it seems to be with
[time.sleep()](http://docs.python.org/2/library/time.html#time.sleep). Example
taken from [this Stackoverflow question](http://stackoverflow.com/a/510351).
import time
while True:
print "This prints once a minute."
time.sleep(60) # Delay for 1 minute (60 seconds)
The other way seems to be with
[APScheduler](https://pypi.python.org/pypi/APScheduler). Example taken from
[this documentation](http://pythonhosted.org/APScheduler/#starting-the-
scheduler).
from apscheduler.scheduler import Scheduler
sched = Scheduler()
@sched.interval_schedule(hours=3)
def some_job():
print "Decorated job"
sched.configure(options_from_ini_file)
sched.start()
What is the best way of doing this? What are the pros and cons of the
different ways? The script will be a daemon later on if that changes anything.
Answer: Whether or not APScheduler brings you any benefit depends on your
requirements. People who use APScheduler usually have more specific
requirements or need to add/remove jobs dynamically.
For example, if your daemon is shut down and the task misses its deadline, how
do you want to handle that? If you need any such advanced task management
capabilities, then you will want to use APScheduler. Otherwise, you can stick
with time.sleep().
|
Calling git -C /path/to/dir from python fails, runs from console
Question: I am writing a git serverside hook that needs to check if there are any
modifications to a different git folder (different from the bare git
repository in which that hook resides). To that end, I have written a `pre-
receive` hook and I am trying to use `git status --porcelain`. The script has
to select the folder which needed checking, but for now i decided to hardcode
all the paths, until I make it work.
So far, when i run this hook as just a python script, it gives me the correct
result, but when i run it as a hook, it gives me an error.
**UPD** It might also be worth mentioning that the script is executed on an
Ubuntu Linux machine. Might be there any limitations on what can be run from
pyton or what processes can be started by other processes?**/UPD**
Here is the script itself:
#!/usr/bin/env python
import sys
import subprocess
import string
import os
print "PRE-RECEIVE HOOK >>>"
def git(args):
dirname = os.path.dirname("/home/git/repos/branchone/gitremote/")
print "Dirname = " + dirname
pr = subprocess.Popen( ["git","-C", dirname, "status", "--porcelain"], shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
(details, error) = pr.communicate()
print details, error
details = details.strip()
if error != "":
print "Errors: " + error
return None
return details
def pwd():
pwd = subprocess.Popen("pwd", stdout = subprocess.PIPE)
details = pwd.stdout.read().strip()
print "PWD:. " + details
def main():
git([])
pwd()
if \__name__ == "\__main__":
main()
sys.exit(2)
Here is how i call it from cosole:
root@remine-vm:/home/git/repos/gitremote.git# ./hooks/pre-receive
PRE-RECEIVE HOOK >>>
Dirname = /home/git/repos/branchone/gitremote
M eden
?? fruit
?? snake
Here's the response when I try to push something to the remote:
Push: Not all refs have been pushed.
$ git.exe push --porcelain --progress --recurse-submodules=check origin refs/heads/branchone:refs/heads/branchone
'branchone' rejected (non-fast-forward)
Counting objects: 7, done.
Delta compression using up to 8 threads.
Total 6 (delta 0), reused 0 (delta 0)
remote: PRE-RECEIVE HOOK >>>
remote: Dirname = /home/git/repos/branchone/gitremote
remote: fatal: Not a git repository: '.'
remote:
remote: Errors: fatal: Not a git repository: '.'
remote:
remote: PWD:. /home/git/repos/gitremote.git
error: failed to push some refs to 'root@redmine-vm:/home/git/repos/gitremote.git'
Answer: Fixed the problem by adding more keys to the git command, namely specifying
the path to the git dir and the working tree. `
pr = subprocess.Popen( ["git","--git-dir", "/home/git/repos/branchone/gitremote/.git", "--work-tree", "/home/git/repos/branchone/gitremote", "-C", dirname, "status", "--porcelain"], shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
`
This article was extremely helpful:
<http://longair.net/blog/2011/04/09/missing-git-hooks-documentation/>
|
python printing each character in new line
Question: I'm trying to print lines and replace words in lines of a text/html file but
not able to do so because python (2.7) is reading it character by character.
What am I doing wrong?
Here is the code and output:
import sys
infile = open('filenmae').read()
for line in infile:
print line
The output I should get (only first line displayed here):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
The output I'm getting:
<
!
D
O
C
T
Y
P
E
.
.
.
Answer: You are looping over a single string, which yields individual characters.
Don't read the file in one go, just loop over the file object:
with open('filename') as infile:
for line in infile:
print line
I used the file as a context manager here as well (`with open(..) as
localname`); Python will now automatically close the file for you when the
`with` block is exited.
Looping over the file object reads lines as needed, avoiding reading the whole
file into memory.
Other alternatives are to read the file in one go as separate lines with the
[`file.readlines()`
method](http://docs.python.org/2/library/stdtypes.html#file.readlines):
infile = open('filename').readlines()
or to split the read data with
[`str.splitlines()`](http://docs.python.org/2/library/stdtypes.html#str.splitlines):
infile = open('filename').read().splitlines()
|
Create a simple GUI for a minimalistic python script
Question: I wrote a small python function, which takes several numerical input
parameters and prints many lines with statements, which going to be used in an
experiment, like this toy example:
def myADD(x,y,z):
res = x + y + z
print("the result is: {0}+{1}+{2}={3}").format(x,y,z,res)
I would like to create a minimalistic GUI, simply an overlay which calls my
myADD.py script, where I can fill those parameters x,y,z and after clicking a
"compute" button a text field occurs with the print statement.
Does anyone has a template, I was looking into the TKinter, but my attempts by
manipulating other templates didn't succeed.
Would appreciate help, thanks.
Answer: Tkinter is a fantastic choice since it is built-in. It is ideally suited for
this type of quick, minimalistic GUI.
Here's a basic framework for a Tkinter app to show you how simple it can be.
All you need to do is add your function, either by importing it or including
it in the same file:
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.entry = {}
# the basic layout is a form on the top, and
# a submit button on the bottom
form = tk.Frame(self)
submit = tk.Button(self, text="Compute", command=self.submit)
form.pack(side="top", fill="both", expand=True)
submit.pack(side="bottom")
# this fills in the form with input widgets for each parameter
for row, item in enumerate(("x", "y", "z")):
label = tk.Label(form, text="%s:"%item, anchor="w")
entry = tk.Entry(form)
label.grid(row=row, column=0, sticky="ew")
entry.grid(row=row, column=1, sticky="ew")
self.entry[item] = entry
# this makes sure the column with the entry widgets
# gets all the extra space when the window is resized
form.grid_columnconfigure(1, weight=1)
def submit(self):
'''Get the values out of the widgets and call the function'''
x = self.entry["x"].get()
y = self.entry["y"].get()
z = self.entry["z"].get()
print "x:", x, "y:", y, "z:", z
if __name__ == "__main__":
# create a root window
root = tk.Tk()
# add our example to the root window
example = Example(root)
example.pack(fill="both", expand=True)
# start the event loop
root.mainloop()
If you want the result to appear in the window, you can create another
instance of a `Label` widget, and change it's value when you perform the
computation by doing something like `self.results_label.configure(text="the
result")`
|
python-ldap creating a group
Question: I'm trying to create a security group in AD from a python script with python-
ldap.
I'm able to bind my user which has sufficient rights to perform such an
operation (confirmed by creating the group from ADExplorer gui client) and
search the domain, but when it comes to adding the new group it fails with:
> ldap.INSUFFICIENT_ACCESS: {'info': '00000005: SecErr: DSID-03152492, problem
> 4003 (INSUFF_ACCESS_RIGHTS), data 0\n', 'desc': 'Insufficient access'}
This is the script:
import ldap
import ldap.modlist as modlist
server = 'hidden'
user_dn = 'hidden'
user_pw = 'hidden'
fs_dn = 'ou=fssecuritygroups,ou=tkogroups,ou=tokyo,dc=unit,dc=xyz,dc=intra'
l = ldap.initialize("ldaps://"+server)
l.bind_s(user_dn, user_pw)
groupname = 'mytestfs'
attr = {}
attr['objectClass'] = ['group','top']
attr['groupType'] = '-2147483646'
attr['cn'] = groupname
attr['name'] = groupname
attr['sAMAccountName'] = groupname
ldif = modlist.addModlist(attr)
print(l.add_s(fs_dn,ldif))
Answer: I got the same error when I try to add a new object under a dn where I am not
allowed to add.
E.g. I have access rights to the ldap-server (binding works), I'm allowed to
add group-objects under `ou=germany,ou=groups,dc=ACME` \- but I'm not allowed
to add a group-object under `ou=groups,dc=ACME`.
Maybe you checkout the constraints of the ldap or the like.
|
Python String Comparison function()
Question: I am checking a piece of Python code I found online (<http://www.exploit-
db.com/exploits/18305/>), and I'm stuck over a piece of code.
To be honest I don't know Python, but I have experience in other programming
languages.
The method `_computeCollisionChars` generates a number of characters and then
adds them to a dictionary if they are _different_. Below is the method
signature along with the relevant part for the question. **Note** : The actual
code can be found on the linked source.
def _computeCollisionChars(self, function, count, charrange):
baseStr = ""
baseHash = function(baseStr) # What is this?
for item in source:
tempStr = ""
if tempStr == baseStr:
continue
if function(tempStr) == baseHash: # What type of comparison is this?
# logic goes here...
return
My questions are:
1. What does the `function` parameter mean in the method signature?
2. Most importantly what does `function(string)` do? Why are there two checks, and what sort of output does `function(tempStr)` generate then?
Thanks a lot guys!
Answer: Apparently you can pass any callable object as `function` to
`_computeCollisionChars`. Then `baseHash` is initialised as the result of
calling `function` with an empty string as parameter. Inside the loop, the
condition reads: if the result of `function` called with an empty string as
parameter equals the `baseHash` do this and that. Which is kind of senseless,
because `tempStr` is always `''` and `baseHash` never changes (or you didn't
post that part).
In the current snippet the second `if` is never reached, because invariably
`tempStr == baseStr == ''`.
As the commentors pointed out, in the real code `tempStr` and `baseStr` do
indeed change and `function` is expected to be a hashing-function (but any
other function which takes a string as argument should work).
|
How to use python os.walk, but first get the subfolders and then the files as XML file
Question: I'm python beginner and started to work on the below script. It already works,
but in the wrong way. Now i get stuck and I would like some help. I use
os.walk in order to get an index as a XML file of a filepath in Windows. I
also added the current result of the script, and what I need to get out.
The difference between the result and what i need, is that the subfolders are
before the files.
##This Script creates an Index as XML file of a filepath in Windows
import os
#variable
CrawlingStartpoint = r"D:\DATA\WorldDem"
XMLfile = r"xml_index.xml"
XMLLocation = r"D:\DATA\\"
XMLFileLocation = XMLLocation + XMLfile
text = ""
#Standard Starting text for the XML file
text += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ShoeBox>\n<Version>2011</Version>\n<FileGroup>\n<Title>ShoeBox: "
text += XMLfile + "</Title>\n<Description>" + CrawlingStartpoint + "</Description>\n<Expanded>false</Expanded>\n<AddOutputs>false</AddOutputs>\n"
#Scan all folders, subfolders and files. It writes foldernames, subfolder names and files.
#It write a closegroup for every subfolder to build the filestructure in a XML file.
startdept = CrawlingStartpoint.split('\\')
startdept = len(startdept) - 1
old = startdept - 1
for root, dirs, files in os.walk(CrawlingStartpoint, topdown=True):
path = root.split('\\')
if (len(path) - 1) < old:
text += (((old - (len(path) - 1))+1)*'</FileGroup>\n')
old = (len(path) -1)
elif (len(path) - 1) == old:
text += "</FileGroup>\n"
if os.path.join(root) <> CrawlingStartpoint:
text += "<FileGroup>\n<Title>" + os.path.basename(root) + "</Title>\n<Description>noop</Description>\n<Expanded>false</Expanded>\n<AddOutputs>false</AddOutputs>\n"
for filename in files:
if filename.endswith(".img") or filename.endswith(".jp2") or filename.endswith(".tif"):
text += "<File>\n<Path>" + os.path.join(root, filename) + "</Path>\n<Type>raster</Type>\n<Description></Description>\n</File>\n"
elif filename.endswith(".shp") or filename.endswith(".dxf"):
text += "<File>\n<Path>" + os.path.join(root, filename) + "</Path>\n<Type>vector</Type>\n<Description></Description>\n</File>\n"
if (len(path) - 1) > old:
old = old + 1
text += (((len(path) -1) - startdept)*'</FileGroup>\n')
#Standard Closing text for the XML file
text += "</FileGroup>" + "\n" + "</ShoeBox>"
#Write the filelocations stored in text in the textfile
myfile = open(XMLFileLocation,'a')
myfile.write(text)
myfile.close()
## Result of my script :
<?xml version="1.0" encoding="UTF-8"?>
<ShoeBox>
<Version>2011</Version>
<FileGroup>
<Title>ShoeBox: xml_index.xml</Title>
<Description>D:\DATA\WorldDem</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
<FileGroup>
<Title>srtm_geotiff_download</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
<File>
<Path>D:\DATA\WorldDem\srtm_geotiff_download\srtm1_90m_v41.img</Path>
<Type>raster</Type>
<Description></Description>
</File>
</FileGroup>
<FileGroup>
<Title>viewfinderpanoramas</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
<File>
<Path>D:\DATA\WorldDem\viewfinderpanoramas\mosaic_vfp_90m_bewerkt_20140211.img</Path>
<Type>raster</Type>
<Description></Description>
</File>
<FileGroup>
<Title>Compressed</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
</FileGroup>
<FileGroup>
<Title>Modellen</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
</FileGroup>
</FileGroup>
</FileGroup>
</ShoeBox>
## Result needed :
<?xml version="1.0" encoding="UTF-8"?>
<ShoeBox>
<Version>2011</Version>
<FileGroup>
<Title>ShoeBox: xml_index.xml</Title>
<Description>D:\DATA\WorldDem</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
<FileGroup>
<Title>srtm_geotiff_download</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
<File>
<Path>D:\DATA\WorldDem\srtm_geotiff_download\srtm1_90m_v41.img</Path>
<Type>raster</Type>
<Description></Description>
</File>
</FileGroup>
<FileGroup>
<Title>viewfinderpanoramas</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
<FileGroup>
<Title>Compressed</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
</FileGroup>
<FileGroup>
<Title>Modellen</Title>
<Description>noop</Description>
<Expanded>false</Expanded>
<AddOutputs>false</AddOutputs>
</FileGroup>
<File>
<Path>D:\DATA\WorldDem\viewfinderpanoramas\mosaic_vfp_90m_bewerkt_20140211.img</Path>
<Type>raster</Type>
<Description></Description>
</File>
</FileGroup>
</FileGroup>
</ShoeBox>
Answer: I don't think there's any easy way to do what you want. At least, there isn't
if you're writing your XML by hand.
The reason is that you need to build your XML document from the root up,
starting with the outermost directory, producing the top-most `<FileGroup>`
tag. On the other hand, you want to dive into the subfolders before you write
out the files from each folder, so that files in the leaf directories will
appear first, and those in the root directory will be last. Those two goals
are in tension with each other.
I think there are two strategies that you could take to solving the problem.
The first is to use a more sophisticated approach to writing your XML file.
For instance, if you use a library that lets you dynamically create the
elements of the document, rather than just using string manipulations, you may
be able to insert the subfolder information above the file information, even
though you're process them in the same order you do now (files first). I don't
know Python's XML libaries very well, so I don't have any specific suggestions
here, but probably the place to start is the documentation on the
[`xml`](http://docs.python.org/3/library/xml.html) package in the standard
library (you'll probably just want a submodule like `xml.etree.Etree`, but I'm
not sure if that's the best one for your task, so check the package out and
read up on whichever parts look appropriate).
The other option would be to change up how you get your data. If you dropped
the `topdown=True` argument to `os.walk`, it would start with some deeper
folders first, then come back to the higher level ones, which is exactly the
order you want to be showing their files. The tricky part about this is that
you'd need to build the higher level `<FileGroup>` tags before you get around
to processing the folders they are for. You'll need to deduce the depth you're
at based on the paths of the folders, but you're already doing some of this,
so it probably won't be too much more complicated. (By the way, you really
should be using the functions in the `os.path` module for file path
manipulations, rather than doing things like `my_path.split("\\")`.)
|
yet another pymacs helper did not start within 30 seconds (but with more debug)
Question: I have followed [this guide](http://milkbox.net/note/installing-pymacs-rope-
on-emacs-24/), and consulted these existing stackoverflow questions:
* [Pymacs helper did not start after 30 seconds](http://stackoverflow.com/questions/13254442/pymacs-helper-did-not-start-after-30-seconds)
* [Windows 8 + Emacs 24.3 + emacs-for-python: Pymacs helper did not start within 30 seconds](http://stackoverflow.com/questions/16973236/windows-8-emacs-24-3-emacs-for-python-pymacs-helper-did-not-start-within-30)
But unfortunately, these did not solve my problem. So, I've posted this
question with more detail on my error.
Following the debug information emacs provides, I ran with --debug-init, and
here are the results.
Debugger entered--Lisp error: (error "Pymacs helper did not start within 30 seconds")
signal(error ("Pymacs helper did not start within 30 seconds"))
pymacs-report-error("Pymacs helper did not start within %d seconds" 30)
pymacs-start-services()
pymacs-serve-until-reply("eval" (pymacs-print-for-apply (quote "pymacs_load_helper") (quote ("ropemacs" "rope-" nil))))
pymacs-call("pymacs_load_helper" "ropemacs" "rope-" nil)
pymacs-load("ropemacs" "rope-")
eval-buffer(#<buffer *load*> nil "/home/mittenchops/.emacs.d/init.el" nil t) ; Reading at buffer position 1936
load-with-code-conversion("/home/mittenchops/.emacs.d/init.el" "/home/mittenchops/.emacs.d/init.el" t t)
load("/home/mittenchops/.emacs.d/init" t t)
#[0 "\205\262
My init.el is linked [here](https://gist.github.com/mittenchops/9785915).
I've installed rope, ropemacs, pymacs, etc., but am still getting this error.
I find further that pymacs seems to be unsuccessful in being imported in
python in general:
>>> import Pymacs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named Pymacs
But this is bizarre, because:
$ git clone https://github.com/pinard/Pymacs.git
$ sudo pip install -e Pymacs
installs successfully!
Answer: Ah, nevermind, I forgot to build the repo.
$ python setup.py build
$ python setup.py install
|
Python optparse command line args
Question: I am working on a problem I need to run with different args from a command
line. I found this example online but no answer. I am not currently not
worried about the parser errors, I can do that later, I am just stumped on
getting the args right.
-l/--level INFO yes Sets the log level to DEBUG, INFO, WARNING, ERROR, and CRITICAL
-n/--name Throws a parser error if empty yes Sets the name value of the Address object
-a/--address Throws a parser error if empty yes Sets the street_address value of the Address object
-c/--city Throws a parser error if empty yes Sets the city value of the Address object
-s/--state Throws a parser error if empty yes Sets the state value of the Address object
-z/--zip_code Throws a parser error if empty yes Sets the zip_code value of the Address object
If you run your code with the following command-line arguments:
property_address.py -n Tom -a "my street" -c "San Diego" -s "CA" -z 21045
...you should see something like this in property_address.log:
2010-10-11 14:48:59,794 - INFO - __init__ - Creating a new address
I have the following code for this:
import re
import logging
LOG_FILENAME = "property_address.log"
LOG_FORMAT = "%(asctime)s-%(levelname)s-%(funcName)s-%(message)s"
DEFAULT_LOG_LEVEL = "error" # Default log level
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
def start_logging(filename=LOG_FILENAME, level=DEFAULT_LOG_LEVEL):
"Start logging with given filename and level."
logging.basicConfig(filename=filename, level=LEVELS[level],format=LOG_FORMAT)
# log a message
logging.info('Starting up the property_address program')
class StateError(Exception): pass
class ZipCodeError(Exception):pass
class Address(object):
states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN',
'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN',
'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']
def __init__(self,name, street_address, city, state, zip_code):
self._name = name
logging.info('Creating a new name')
self._street_address = street_address
logging.info('Creating a new address')
self._city = city
logging.info('Creating a new city')
self._state = state
logging.info('Creating a new state')
self._zip_code = zip_code
logging.info('Creating a new zip_code')
@property
def name(self):
return self._name.title()
@property
def state(self):
return self._state
@state.setter
def state(self,value):
if value not in self.states:
logging.error('STATE exception')
raise StateError(value)
self._state = value
logging.info('Creating a new state')
@property
def zip_code(self):
return self._zip_code
@zip_code.setter
def zip_code(self,value):
if re.match(r"^\d\d\d\d\d$",value):
self._zip_code = value
logging.info('Creating a new ZipCode')
else:
logging.error('ZIPCODE exception')
raise ZipCodeError
I am having trouble with setting up the args. I am currently trying:
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--level', dest="level", action="store",
help="sets level")
(options, args) = parser.parse_args()
How can I set the log level to warning this if I run "-l warning" from the
command line, and then run the script. I also need to call -n Tom etc. I don't
need the answer to ever arg, just a general understanding of how this would
work. I am alos not worried about the parse errors now, just being able to get
the args right.
Answer: Get the level option value from `options.level` and pass it to
`start_logging()`:
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--level', dest="level", action="store",
help="sets level")
(options, args) = parser.parse_args()
start_logging(level=options.level)
logging.error('ERROR!')
logging.info('INFO')
After running the script with `-l warning`, there is only `ERROR!` message
written to the log file.
If you run it with `-l info`, you would see both `ERROR!` and `INFO!` messages
in the log file.
Hope that helps.
|
APScheduler not executing the python
Question: I am learning Python and was tinkering with Advanced scheduler. I am not able
to gt it working though.
import time
from datetime import datetime
from apscheduler.scheduler import Scheduler
sched = Scheduler(standalone=True)
sched.start()
#@sched.cron_schedule(second=5)
def s():
print "hi"
sched.add_interval_job(s, seconds=10)
i=0
while True:
print i
i=i+1
time.sleep(3)
sched.shutdown()
I am sure I am missing something basic. Could someone please point it out?
Also would you recommend a crontab to the advanced scheduler? I want my script
to run every 24 hours. Thanks
Answer: Standalone mode means that sched.start() will block, so the code below it will
NOT be executed. So first create the scheduler, then add the interval job and
finally start the scheduler.
As for the crontab, how about just sched.add_cron_job(s, hour=0)? That will
execute it at midnight every day.
|
Python: argv and IndexError
Question: I am trying to reproduce the results of a research article which they provided
the python codes. There is a script to download their data and I am trying to
run the script from terminal by,
> python getData.py
an it raises the error
> File "getData.py", line 127, in dataFile = sys.argv[1]+"/raw-comp.txt"
> IndexError: list index out of range
Related part in the python code is here,
if __name__ == '__main__' :
dataFile = sys.argv[1]+"/raw-comp.txt"
# Read the data
I don't know if it is related or not; but 'getData.py' script is under 'src'
folder whereas 'raw-comp.txt' file is under 'data' folder.
I check out this solution here, [python : IndexError: list index out of
range](http://stackoverflow.com/questions/18509289/python-indexerror-list-
index-out-of-range) and it says `argv` stores the command line arguments and
you need to pass the arguments before calling it. I also checked this out;
[from sys import argv - what is the function of
"script"](http://stackoverflow.com/questions/13666346/from-sys-import-argv-
what-is-the-function-of-script) where script and filename were assigned to
argv. But here in this code, argv was not defined before the code piece above,
besides it is the first time argv is seen in the script.
I really have no idea why it did not run, because it supposed to work without
any modifying they say. Thanks already.
**Edit:** They have provided the description below for the script, they do not
mention any argument that has to be passed from terminal.
getData: a script to download and/or build the data files.
Answer: Try running it as:
python getData.py ../data
The presence of `sys.argv[1]` means the program cannot be run without passing
at least one command line argument.
As documented in the [python
documentation](http://docs.python.org/2/library/sys.html) `sys.argv` is a list
of command line arguments with the first entry `sys.argv[0]` being the script
name. The `ÌndexError` exception occurs when no command line arguments are
passed as the code is trying to access a none existent entry.
|
Python multiprocessing job to Celery task but AttributeError
Question: I made a multiprocessed function like this,
import multiprocessing
import pandas as pd
import numpy as np
def _apply_df(args):
df, func, kwargs = args
return df.apply(func, **kwargs)
def apply_by_multiprocessing(df, func, **kwargs):
workers = kwargs.pop('workers')
pool = multiprocessing.Pool(processes=workers)
result = pool.map(_apply_df, [(d, func, kwargs)
for d in np.array_split(df, workers)])
pool.close()
return pd.concat(list(result))
def square(x):
return x**x
if __name__ == '__main__':
df = pd.DataFrame({'a':range(10), 'b':range(10)})
apply_by_multiprocessing(df, square, axis=1, workers=4)
## run by 4 processors
Above "apply_by_multiprocessing" can execute Pandas Dataframe apply in
parallel. But when I make it to Celery task, It raised AssertionError:
'Worker' object has no attribute '_config'.
from celery import shared_task
@shared_task
def my_multiple_job():
df = pd.DataFrame({'a':range(10), 'b':range(10)})
apply_by_multiprocessing(df, square, axis=1, workers=4)
It's error trace is like this,
File "/Users/yong27/work/goldstar/kinmatch/utils.py", line 14, in apply_by_multiprocessing
pool = multiprocessing.Pool(processes=workers)
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/context.py", line 118, in Pool
context=self.get_context())
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/pool.py", line 146, in __init__
self._setup_queues()
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/pool.py", line 238, in _setup_queues
self._inqueue = self._ctx.SimpleQueue()
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/context.py", line 111, in SimpleQueue
return SimpleQueue(ctx=self.get_context())
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/queues.py", line 336, in __init__
self._rlock = ctx.Lock()
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/context.py", line 66, in Lock
return Lock(ctx=self.get_context())
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/synchronize.py", line 164, in __init__
SemLock.__init__(self, SEMAPHORE, 1, 1, ctx=ctx)
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/synchronize.py", line 60, in __init__
kind, value, maxvalue, self._make_name(),
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/synchronize.py", line 118, in _make_name
return '%s-%s' % (process.current_process()._config['semprefix'],
AttributeError: 'Worker' object has no attribute '_config'
It seems that because Celery worker is not a normal process. How can I solve
this problem? I'm using Python3.4, Django 1.6.2, celery 3.1.10, django-celery
3.1.9, pandas 0.12.0.
Answer: I don't know why multiprocessing doesn't work, but I recommend you to use
celery group task.
from celery import task, group
def feeds_fetch(feeds):
g = group(fetch_one.s(feed) for feed in feeds)
g.apply_async()
@task()
def fetch_one(feed):
return feed.fetch()
|
If identifying text structure in PDF documents is so difficult, how do PDF readers do it so well?
Question: I have been trying to write a simple console application or PowerShell script
to extract the text from a large number of PDF documents. There are several
libraries and CLI tools that offer to do this, but it turns out that none are
able to reliably identify document structure. In particular I am concerned
with the recognition of text columns. Even the very expensive PDFLib TET tool
frequently jumbles the content of two adjacent columns of text.
It is frequently noted that the PDF format does not have any concept of
columns, or even words. Several answers to similar questions on SO mention
this. The problem is so great that it even warrants academic research. [This
journal article](http://aclweb.org/anthology//W/W12/W12-3211.pdf) notes:
All data objects in a PDF file are represented in
a visually-oriented way, as a sequence of operators
which...generally do not convey information about higher
level text units such as tokens, lines, or columns—
information about boundaries between such units is
only available implicitly through whitespace
Hence, all extraction tools I have tried (iTextSharp, PDFLib TET, and Python
PDFMiner) have failed to recognize text column boundaries. Of these tools,
PDFLib TET performs best.
However, SumatraPDF, the very lightweight and open source PDF Reader, and many
others like it can identify columns and text areas perfectly. If I open a
document in one of these applications, select all the text on a page (or even
the entire document with CTRL+A) copy and paste it into a text file, the text
is rendered in the correct order almost flawlessly. It occasionally mixes the
footer and header text into one of the columns.
So my question is, how can these applications do what is seemingly so
difficult (even for the expensive tools like PDFLib)?
EDIT 31 March 2014: For what it's worth I have found that PDFBox is much
better at text extraction than iTextSharp (notwithstanding a bespoke Strategy
implementation) and PDFLib TET is slightly better than PDFBox, but it's quite
expensive. Python PDFMiner is hopeless. The best results I have seen come from
Google. One can upload PDFs (2GB at a time) to Google Drive and then download
them as text. This is what I am doing. I have written a small utility that
splits my PDFs into 10 page files (Google will only convert the first 10
pages) and then stitches them back together once downloaded.
EDIT 7 April 2014. Cancel my last. The best extraction is achieved by MS Word.
And this can be automated in Acrobat Pro (Tools > Action Wizard > Create New
Action). Word to text can be automated using the .NET OpenXml library. [Here
is a
class](http://code.msdn.microsoft.com/office/CSOpenXmlGetPlainText-554918c3/sourcecode?fileId=71592&pathId=851860130)
that will do the extraction (docx to txt) very neatly. My initial testing
finds that the MS Word conversion is considerably more accurate with regard to
document structure, but this is not so important once converted to plain text.
Answer: I once wrote an algorithm that did exactly what you mentioned for a PDF editor
product that is still the number one PDF editor used today. There are a couple
of reasons for what you mention (I think) but the important one is focus.
You are correct that PDF (usually) doesn't contain any structure information.
PDF is interested in the visual representation of a page, not necessarily in
what the page "means". This means in its purest form it doesn't need
information about lines, paragraphs, columns or anything like that. Actually,
it doesn't even need information about the text itself and there are plenty of
PDF files where you can't even copy and paste the text without ending up with
gibberish.
So if you want to be able to extract formatted text, you have to indeed look
at all of the pieces of text on the page, perhaps taking some of the line-art
information into account as well, and you have to piece them back together.
Usually that happens by writing an engine that looks at white-space and then
decides first what are lines, what are paragraphs and so on. Tables are
notoriously difficult for example because they are so diverse.
Alternative strategies could be to:
* Look at some of the structure information that is available in _some_ PDF files. Some PDF/A files and all PDF/UA files (PDF for archival and PDF for Universal Accessibility) must have structure information that can very well be used to retrieve structure. Other PDF files may have that information as well.
* Look at the creator of the PDF document and have specific algorithms to handle those PDFs well. If you know you're only interested in Word or if you know that 99% of the PDFs you will ever handle will come out of Word 2011, it might be worth using that knowledge.
So why are some products better at this than others? Focus I guess. The PDF
specification is very broad, and some tools focus more on lower-level PDF
tasks, some more on higher-level PDF tasks. Some are oriented towards "office"
use - some towards "graphic arts" use. Depending on your focus you may decide
that a certain feature is worth a lot of attention or not.
Additionally, and that may seem like a lousy answer, but I believe it's
actually true, this is an algorithmically difficult problem and it takes only
one genius developer to implement an algorithm that is much better than the
average product on the market. It's one of those areas where - if you are
clever and you have enough focus to put some of your attention on it, and
especially if you have a good idea what the target market is you are writing
this for - you'll get it right, while everybody else will get it mediocre.
(And no, I didn't get it right back then when I was writing that code - we
never had enough focus to follow-through and make something that was really
good)
|
pandas to_sql truncates my data
Question: I was using `df.to_sql(con=con_mysql, name='testdata', if_exists='replace',
flavor='mysql')` to export a data frame into mysql. However, I discovered that
the columns with long string content (such as url) is truncated to 63 digits.
I received the following warning from ipython notebook when I exported:
> /usr/local/lib/python2.7/site-packages/pandas/io/sql.py:248: Warning: Data
> truncated for column 'url' at row 3 cur.executemany(insert_query, data)
There were other warnings in the same style for different rows.
Is there anything I can tweak to export the full data properly? I could set up
the correct data schema in mysql and then export to that. But I am hoping a
tweak can just make it work straight from python.
Answer: If you are using pandas **0.13.1 or older** , this limit of 63 digits is
indeed hardcoded, because of this line in the code:
<https://github.com/pydata/pandas/blob/v0.13.1/pandas/io/sql.py#L278>
As a workaround, you could maybe monkeypatch that function `get_sqltype`:
from pandas.io import sql
def get_sqltype(pytype, flavor):
sqltype = {'mysql': 'VARCHAR (63)', # <-- change this value to something sufficient higher
'sqlite': 'TEXT'}
if issubclass(pytype, np.floating):
sqltype['mysql'] = 'FLOAT'
sqltype['sqlite'] = 'REAL'
if issubclass(pytype, np.integer):
sqltype['mysql'] = 'BIGINT'
sqltype['sqlite'] = 'INTEGER'
if issubclass(pytype, np.datetime64) or pytype is datetime:
sqltype['mysql'] = 'DATETIME'
sqltype['sqlite'] = 'TIMESTAMP'
if pytype is datetime.date:
sqltype['mysql'] = 'DATE'
sqltype['sqlite'] = 'TIMESTAMP'
if issubclass(pytype, np.bool_):
sqltype['sqlite'] = 'INTEGER'
return sqltype[flavor]
sql.get_sqltype = get_sqltype
And then just using your code should work:
df.to_sql(con=con_mysql, name='testdata', if_exists='replace', flavor='mysql')
* * *
Starting from pandas **0.14** , the sql module is uses sqlalchemy under the
hood, and strings are converted to the sqlalchemy `TEXT` type, wich is
converted to the mysql `TEXT` type (and not `VARCHAR`), and this will also
allow you to store larger strings than 63 digits:
engine = sqlalchemy.create_engine('mysql://scott:tiger@localhost/foo')
df.to_sql('testdata', engine, if_exists='replace')
Only if you still use the a DBAPI connection instead of a sqlalchemy engine,
the issue remains, but this option is deprecated and it is recommended to
provide an sqlalchemy engine to `to_sql`.
|
How can I calculate the area within a contour in Python using the Matplotlib?
Question: I am trying to figure out a way to get the area inside a specific contour
line?
I use `matplotlib.pyplot` to create my contours.
Does anyone have experience for this?
Thanks a lot.
Answer: From the `collections` attribute of the contour collection, which is returned
by the `contour` function, you can get the paths describing each contour. The
paths' `vertices` attributes then contain the ordered vertices of the contour.
Using the vertices you can approximate the contour integral 0.5*(x*dy-y*dx),
which by application of [Green's
theorem](http://en.wikipedia.org/wiki/Green%27s_theorem#Area_Calculation)
gives you the area of the enclosed region.
However, the contours must be **fully contained in the plot** , because
otherwise the contours are broken up into multiple, not necessarily connected
paths and the method breaks down.
Here's the method used to compute the area enclosed of the radius function,
i.e. r = (x^2 + y^2)^0.5, for r=1.0, r=2.0, r=3.0.
import numpy as np
import matplotlib.pylab as plt
# Use Green's theorem to compute the area
# enclosed by the given contour.
def area(vs):
a = 0
x0,y0 = vs[0]
for [x1,y1] in vs[1:]:
dx = x1-x0
dy = y1-y0
a += 0.5*(y0*dx - x0*dy)
x0 = x1
y0 = y1
return a
# Generate some test data.
delta = 0.01
x = np.arange(-3.1, 3.1, delta)
y = np.arange(-3.1, 3.1, delta)
X, Y = np.meshgrid(x, y)
r = np.sqrt(X**2 + Y**2)
# Plot the data
levels = [1.0,2.0,3.0]
cs = plt.contour(X,Y,r,levels=levels)
plt.clabel(cs, inline=1, fontsize=10)
# Get one of the contours from the plot.
for i in range(len(levels)):
contour = cs.collections[i]
vs = contour.get_paths()[0].vertices
# Compute area enclosed by vertices.
a = area(vs)
print "r = " + str(levels[i]) + ": a =" + str(a)
plt.show()
Output:
r = 1.0: a = 2.83566351207
r = 2.0: a = 11.9922190971
r = 3.0: a = 27.3977413253
|
How can python threads be programmed such that the user can distinguish between them using monitoring tools available in LINUX
Question: For example, I can name threads easily for reference within the python
program:
#!/usr/bin/python
import time
import threading
class threadly(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
while True:
time.sleep(4)
print "I am", self.name, "and I am barely awake."
slowthread=threadly("slowthread")
slowthread.start()
anotherthread=threadly("anotherthread")
anotherthread.start()
while True:
time.sleep(2)
print "I will never stop running"
print "Threading enumerate:", threading.enumerate()
print "Threading active_count:", threading.active_count()
print
And the output looks like this:
I am slowthread and I am barely awake.
I am anotherthread and I am barely awake.
I will never stop running
Threading enumerate: [<_MainThread(MainThread, started 140121216169728)>, <threadly(slowthread, started 140121107244800)>, <threadly(anotherthread, started 140121026328320)>]
Threading active_count: 3
I will never stop running
Threading enumerate: [<_MainThread(MainThread, started 140121216169728)>, <threadly(slowthread, started 140121107244800)>, <threadly(anotherthread, started 140121026328320)>]
Threading active_count: 3
I can find the PID this way:
$ ps aux | grep test
557 12519 0.0 0.0 141852 3732 pts/1 S+ 03:59 0:01 vim test.py
557 13974 0.0 0.0 275356 6240 pts/2 Sl+ 05:36 0:00 /usr/bin/python ./test.py
root 13987 0.0 0.0 103248 852 pts/3 S+ 05:39 0:00 grep test
I can then invoke top:
# top -p 13974
Pressing 'H' turns on display of threads, and we see they are all displaying
as the name of the command or of the main thread:
top - 05:37:08 up 5 days, 4:03, 4 users, load average: 0.02, 0.03, 0.00
Tasks: 3 total, 0 running, 3 sleeping, 0 stopped, 0 zombie
Cpu(s): 1.8%us, 2.7%sy, 0.0%ni, 95.3%id, 0.0%wa, 0.0%hi, 0.2%si, 0.0%st
Mem: 32812280k total, 27717980k used, 5094300k free, 212884k buffers
Swap: 16474104k total, 4784k used, 16469320k free, 26008752k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
13974 justin.h 20 0 268m 6240 1740 S 0.3 0.0 0:00.03 test.py
13975 justin.h 20 0 268m 6240 1740 S 0.0 0.0 0:00.00 test.py
13976 justin.h 20 0 268m 6240 1740 S 0.0 0.0 0:00.00 test.py
Contrast this with software like rsyslog which does name its threads:
# ps aux | grep rsyslog
root 2763 0.0 0.0 255428 1672 ? Sl Mar22 6:53 /sbin/rsyslogd -i /var/run/syslogd.pid -c 5
root 2774 47.7 0.0 265424 6276 ? Sl Mar22 3554:26 /sbin/rsyslogd -i /var/run/syslogd-01.pid -c5 -f /etc/rsyslog-01.conf
root 2785 2.7 0.0 263408 3596 ? Sl Mar22 207:46 /sbin/rsyslogd -i /var/run/syslogd-02.pid -c5 -f /etc/rsyslog-02.conf
root 2797 1.7 0.0 263404 3528 ? Sl Mar22 131:39 /sbin/rsyslogd -i /var/run/syslogd-03.pid -c5 -f /etc/rsyslog-03.conf
root 2808 24.3 0.0 265560 3352 ? Sl Mar22 1812:25 /sbin/rsyslogd -i /var/run/syslogd-04.pid -c5 -f /etc/rsyslog-04.conf
root 2819 1.3 0.0 263408 1596 ? Sl Mar22 103:42 /sbin/rsyslogd -i /var/run/syslogd-05.pid -c5 -f /etc/rsyslog-05.conf
root 2830 0.0 0.0 263404 1408 ? Sl Mar22 0:17 /sbin/rsyslogd -i /var/run/syslogd-06.pid -c5 -f /etc/rsyslog-06.conf
root 13994 0.0 0.0 103248 852 pts/3 S+ 05:40 0:00 grep rsyslog
Let's pick '2774' because it looks busy:
$ top -p 2774
And press 'H' and we see a descriptively named thread showing me that the
thread dedicated to the 'main' ruleset and the Reg Queue is consuming 55.6 %
CPU.
top - 05:50:52 up 5 days, 4:17, 4 users, load average: 0.00, 0.00, 0.00
Tasks: 4 total, 1 running, 3 sleeping, 0 stopped, 0 zombie
Cpu(s): 1.7%us, 2.6%sy, 0.0%ni, 95.5%id, 0.0%wa, 0.0%hi, 0.2%si, 0.0%st
Mem: 32812280k total, 29833152k used, 2979128k free, 214836k buffers
Swap: 16474104k total, 4784k used, 16469320k free, 28123448k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2775 root 20 0 259m 6020 1212 R 55.6 0.0 3152:40 rs:main Q:Reg
2776 root 20 0 259m 6020 1212 S 7.0 0.0 407:57.94 rsyslogd
2774 root 20 0 259m 6020 1212 S 0.0 0.0 0:00.00 rsyslogd
2777 root 20 0 259m 6020 1212 S 0.0 0.0 0:00.00 rsyslogd
Another way to see the names is:
$ grep Name /proc/2775/task/*/status
/proc/2775/task/2774/status:Name: rsyslogd
/proc/2775/task/2775/status:Name: rs:main Q:Reg
/proc/2775/task/2776/status:Name: rsyslogd
/proc/2775/task/2777/status:Name: rsyslogd
So to restate my question:
How can python threads be programmed such that the user can distinguish
between them using monitoring tools available in LINUX
In my question, I've tried to accomplish this by naming the thread within
Python. Perhaps there a better way to expose differently identifiable threads
from the OS?
Also, preferably I am looking for a Pythonic and standard way of doing this
such that it would be part of the standard python distribution (RHEL 6/Python
2.6.7 specifically but this shouldn't matter unless the support comes in a
later version of python) . Contributed modules are good to know about, but for
my intended application unfortunately they would not be allowed for
supportability reasons due to policies.
Answer: <http://code.google.com/p/procname/>
This appears to be your solution..
class worker(Thread):
def __init__(self, name)
Thread.__init__(self)
self.name = name
self.alive = True
self.start()
def run(self):
procname.setprocname('My super name')
while self.alive is True:
## Do work
x = worker('Worker')
|
Go subprocess communication
Question: GO: Is there some way to communicate with a subprocess (shell script / python
script), which is waiting for input on stdin?
e.g. python script (subprocess)
import sys
while True:
sys.stdout.write('%s\n'%eval(sys.stdin.readline()))
In the go program, I want to create a subprocess of this python script and
provide it input on its stdin, whenever necessary and repeatedly, and take its
output. Writing on stdout of Go program or reading/writing from a file will
also do.
This is roughly what I am trying, but nothing happens -
c := exec.Command("python", "-u add.py")
si,_ := c.StdinPipe()
so,_ := c.StdoutPipe()
c.Start()
si.Write([]byte("2+2\n")
Answer: Here is a working version of your go code (python code is unchanged).
Note: checking of all errors, fixed `-u` flag, use of
[bufio](http://golang.org/pkg/bufio/) to read a line, and
[Wait](http://golang.org/pkg/os/exec/#Cmd.Wait) to wait for end of process.
import (
"bufio"
"fmt"
"log"
"os/exec"
)
func main() {
c := exec.Command("python", "-u", "add.py")
si, err := c.StdinPipe()
if err != nil {
log.Fatal(err)
}
so, err := c.StdoutPipe()
if err != nil {
log.Fatal(err)
}
reader := bufio.NewReader(so)
err = c.Start()
if err != nil {
log.Fatal(err)
}
// Now do some maths
for i := 0; i < 10; i++ {
sum := fmt.Sprintf("2+%d\n", i)
_, err = si.Write([]byte(sum))
if err != nil {
log.Fatal(err)
}
answer, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
fmt.Printf("Answer to %q is %q\n", sum, answer)
}
// Close the input and wait for exit
si.Close()
so.Close()
c.Wait()
}
Which produces
Answer to "2+0\n" is "2\n"
Answer to "2+1\n" is "3\n"
Answer to "2+2\n" is "4\n"
Answer to "2+3\n" is "5\n"
Answer to "2+4\n" is "6\n"
Answer to "2+5\n" is "7\n"
Answer to "2+6\n" is "8\n"
Answer to "2+7\n" is "9\n"
Answer to "2+8\n" is "10\n"
Answer to "2+9\n" is "11\n"
|
Docker python client API copy
Question: I am using Docker python client API 'copy'. Response from copy is of type
`requests.packages.urllib3.HTTPResponse`
Does it need to be handled differently for different types of file?
I copied a text file from container but when I try to read it using
`response.read()` I am getting text data mixed with binary data. I see content
decoders as
>>>resonse.CONTENT_DECODERS
>>>['gzip', 'deflate']
What is the best way to handle/read/dump the response from copy API ?
Answer: The response from the docker API is an uncompressed tar file. I had to read
docker's source code to know the format of the response, as this is not
documented. For instance, to download a file at `remote_path`, you need to do
the following:
import tarfile, StringIO, os
reply = docker.copy(container, remote_path)
filelike = StringIO.StringIO(reply.read())
tar = tarfile.open(fileobj = filelike)
file = tar.extractfile(os.path.basename(remote_path))
print file.read()
The code should be modified to work on folders.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.