text
stringlengths 226
34.5k
|
---|
Setting up database for testing in Flask
Question: I am developing my first Flask app. It is my side project, so I focus on good
practises and design and take my time. I am a bit stuck on testing - I found
some examples in docs and here on SO, but they either do not apply to my app
or do not seem Pythonic/well designed.
The relevant pieces of code are:
# application module __init__.py
def create_app(config):
app = Flask(__name__)
app.config.from_object('config.%s' % config.title())
return app
config = os.getenv('CONFIG', 'development')
app = create_app(config)
db = SQLAlchemy(app)
#
# config.py
class Testing(Base):
TESTING = True
SQLALCHEMY_DATABASE_URI = \
'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')
#
# models.py
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(60), unique=True, nullable=False)
password_hash = db.Column(db.String(60), nullable=False)
#
# testing.py
class TestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
# TODO: create connection to testing db
def tearDown(self):
# TODO: abort transaction
pass
The question is: how to implement `setUp` and `tearDown` so that in my tests I
can use my models and connection do testing database? If I just import `db`,
it would work on development database.
If it helps anything, I do not need to create testing db from scratch, I use
Flask-Migrate and tests can assume the testing db is initialized and empty.
Any comments are welcome, I do not mind refactoring if my design is flawed.
Answer: It _looks_ like you should just be able to run `CONFIG=Testing python -m
unittest discover` and have everything just work. The only think you may want
to change is, instead of calling `create_app` in your tests, simply import it
from __init__.py:
# testing.py
from . import config, db
class TestCase(unittest.TestCase):
def setUp(self):
self.app = create_app(config)
# db is properly set up to use the testing config
# but any *changes* you make to the db object
# (e. g. monkey-patching) will persist between tests
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
See [here](https://github.com/mjhea0/flask-
tracking/blob/part-3/flask_tracking/test_base.py) for an example.
|
get raw_input data from main
Question: I'm new in python and have not much experience in programming also.
I have this code in my main file:
def user_input():
import re
name_check = re.compile(r"[^A-Za-z\s. ]")
print("Please enter name input: ")
name = raw_input("> ")
return name
def test():
if __name__ =="__main__":
user_input()
test()
How can I get the user_input parameter in order to process it in others child
modules? I'm trying to import the main module to the child file module but it
doesn't work. This is my program structure:
/main
__init__.py
main.py
/child
__init__.py
child1.py
child2.py
I need to pass user_input data to child1.py. When I do importing main:
from main.main import user_input
I've got error message:
No module named main.main
Any comments would be much appreciate.
Cheers
Answer: This code takes in input through `raw_input()` in the `user_input()` function,
and then uses `return` to return it. In our `print_input()` function, we take
_in_ the input. In our `main()` function, we assign the return value from
`user_input()` to `name`, and then pass it into `print_input()`.
def user_input():
name = raw_input("Please enter name input:\n> "
return name
def print_input(name):
print "Hello", name
def main():
name = user_input()
print_input(name)
if __name__ =="__main__":
main()
# Edit
`main.py`:
def user_input():
name = raw_input("Please enter name input:\n> "
return name
def print_input(name):
print "Hello", name
def main():
name = user_input()
print_input(name)
To call a function from here do the following:
>>> from main import user_input, print_input
>>>
>>> print_input(user_input())
Please enter name input:
> aj8uppal
Hello aj8uppal
>>>
|
Cannot remove a reference in Visual Studio 2013
Question: I am building ironpython3 with Visual Studio 2013. In the references Visual
Studio shows a yellow triangle on Microsoft.Scripting.Core reference. Since I
read this reference has been moved to System.Core I simply removed the
reference to Microsoft.Scripting.Core. The project builds just fine without
this reference. But after ending Visual Studio and opening the project again,
the reference is just back. I removed all references I found (Strg-Shift-F)
from the sources, but still no change. I had a look in the .csproj file but
did not find any references there. I simply cannot remove the reference
permanently. Any ideas where to look to permanently remove the reference?
Thank you.
Answer: As Pawel said, IronPython uses a complex build system to handle all of the
platforms it supports and make it easy-ish to add new ones (at least until
IronPython and the DLR can be refactored into portable libraries ... sometime
around 2016). In this case you need to dig through a couple of levels of
imports to find where it's defined (`Build/Common.proj`).
The reason this happen is that even though the Reference is conditional (and
handled correctly) in MSBuild, VS ignores the conditional check and displays
any Reference elements it finds. Moving the Reference into `Build/net35.props`
instead should fix the display, since VS does a much better job of handling
imports.
|
matlplot lib fails on clean numpy installation
Question: I'm trying to install `matplotlib` on OpenSUSE 11.4
Clean installation of Numpy with `pip` (success)
Then clean installation of `matplotlib` (success)
Then when I run
import matplotlib
matplotlib.test()
I get
RuntimeError: module compiled against API version 6 but this version of numpy is 4
RuntimeError: module compiled against API version 6 but this version of numpy is 4
...
...
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEERuntimeError: module compiled against API version 6 but this version of numpy is 4
ES.............
Then a bunch of errors like
======================================================================
ERROR: Failure: AttributeError ('module' object has no attribute 'test_agg')
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/loader.py", line 400, in loadTestsFromName
module = resolve_name(addr.module)
File "/usr/local/lib/python2.7/site-packages/nose/util.py", line 321, in resolve_name
obj = getattr(obj, part)
AttributeError: 'module' object has no attribute 'test_agg'
======================================================================
ERROR: Failure: AttributeError ('module' object has no attribute 'test_arrow_patches')
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/loader.py", line 400, in loadTestsFromName
module = resolve_name(addr.module)
File "/usr/local/lib/python2.7/site-packages/nose/util.py", line 321, in resolve_name
obj = getattr(obj, part)
AttributeError: 'module' object has no attribute 'test_arrow_patches'
And finally
======================================================================
ERROR: test suite for <module 'matplotlib.tests' from '/usr/local/lib64/python2.7/site-packages/matplotlib/tests/__init__.pyc'>
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose/suite.py", line 208, in run
self.setUp()
File "/usr/local/lib/python2.7/site-packages/nose/suite.py", line 291, in setUp
self.setupContext(ancestor)
File "/usr/local/lib/python2.7/site-packages/nose/suite.py", line 314, in setupContext
try_run(context, names)
File "/usr/local/lib/python2.7/site-packages/nose/util.py", line 469, in try_run
return func()
File "/usr/local/lib64/python2.7/site-packages/matplotlib/tests/__init__.py", line 28, in setup
from matplotlib.backends import backend_agg, backend_pdf, backend_svg
File "/usr/local/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 27, in <module>
from matplotlib.backend_bases import RendererBase,\
File "/usr/local/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 50, in <module>
import matplotlib.textpath as textpath
File "/usr/local/lib64/python2.7/site-packages/matplotlib/textpath.py", line 14, in <module>
from matplotlib.mathtext import MathTextParser
File "/usr/local/lib64/python2.7/site-packages/matplotlib/mathtext.py", line 62, in <module>
import matplotlib._png as _png
ImportError: numpy.core.multiarray failed to import
----------------------------------------------------------------------
Ran 50 tests in 9.038s
FAILED (SKIP=1, errors=37)
False
Answer: Turns out someone had previously install `numpy` (v 1.5) using `zypper`
instead of `pip`, and the default `numpy` version was going to 1.5 instead of
1.8 (as installed by `pip`). Insidiously, they install to
/usr/local/lib64/python2.7/site-packages/numpy # PIP
and
/usr/lib64/python2.7/site-packages/numpy # Zypper
|
Python list of variables inside a class
Question: this is my first question, and combined with my being fairly noob feel free to
tell me if there is a completely different way I should be going about this!
Anyways, I am building a program that involves coloring a map with the four
color theorem in Python 2.7, attempting to use certain colors as much as
possible, and I ran into a problem when running something like this code:
In one module:
class state:
a = 0
b = 0
variable_list = [a,b]
Then I import that module into my main program:
from State import state //State(uppercase "s") is the .py file with the state class in it
instance = state()
instance.a = 1
print instance.variable_list[0]
...and the program prints 0, despite changing it in the main program. Any
thoughts on how to update instance.variable_list with the change?
Answer: You have to think of Python variables in terms of pointers. Your question
really boils down to the following:
>>> a = 42
>>> l = [a]
>>> a = 0
>>> print l[0] # shouldn't this print 0?
42
The answer is no, because re-assigning `a` has nothing to do with the list
`l`. The list contains pointers to certain objects in memory. `l[0]` happens
to be pointing to the same object as `a` (the int `42`). When we reassign `a`,
we simply have it "point" to a new object in memory (the int `0`). This has no
bearing on the list `l`.
It looks like this:
**a = 42
l = [a]**
+----+
a -----> | 42 | <------; l[0]
+----+
**a = 0**
+----+
l[0] ---> | 42 |
+----+
+---+
a ------> | 0 |
+---+
Notice that `l[0]` has not changed.
|
Unicode error being thrown when trying to make rosserial module
Question: I've recently started a project in using ROS to publish events using an
arduino from the rosserial module. Whenever I invoke catkin_make on the
workspace I make it through many of the packages in rosserial, but get errors
when trying to make TopicInfo.msg, Log.msg, and rosserial_arduino. Below is
the thrown errors and the problems which are referencing unicode hashing
problems. I've tried repathing and sourcing to the correct areas but nothing
seems to help. Anyone have suggestions? Also I'm running Arch linux with ROS
Hypdro.
Generating Lisp code from rosserial_msgs/TopicInfo.msg
Traceback (most recent call last):
File "/opt/ros/hydro/share/gencpp/cmake/../../../lib/gencpp/gen_cpp.py", line 41, in <module>
import genmsg.template_tools
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/template_tools.py", line 74
raise RuntimeError, "Template file %s not found in template dir %s" % (template_file_name, template_dir)
^
SyntaxError: invalid syntax
rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_cpp.dir/build.make:59: recipe for target '/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/include/rosserial_msgs/TopicInfo.h' failed
make[2]: *** [/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/include/rosserial_msgs/TopicInfo.h] Error 1
CMakeFiles/Makefile2:337: recipe for target 'rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_cpp.dir/all' failed
make[1]: *** [rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_cpp.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[ 20%] Traceback (most recent call last):
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/genlisp_main.py", line 71, in genmain
retcode = generate_msg(options.package, args[1:], options.outdir, search_path)
Generating Lisp code from rosserial_msgs/Log.msg
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/generate.py", line 720, in generate_msg
generate_msg_from_spec(msg_context, spec, search_path, out_dir, pkg)
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/generate.py", line 770, in generate_msg_from_spec
write_md5sum(s, msg_context, spec)
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/generate.py", line 591, in write_md5sum
md5sum = genmsg.compute_md5(msg_context, parent or spec)
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/gentools.py", line 119, in compute_md5
return _compute_hash(msg_context, spec, hashlib.md5())
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/gentools.py", line 103, in _compute_hash
hash.update(compute_md5_text(msg_context, spec))
TypeError: Unicode-objects must be encoded before hashing
ERROR: Unicode-objects must be encoded before hashing
rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_lisp.dir/build.make:58: recipe for target '/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/share/common-lisp/ros/rosserial_msgs/msg/TopicInfo.lisp' failed
make[2]: *** [/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/share/common-lisp/ros/rosserial_msgs/msg/TopicInfo.lisp] Error 3
make[2]: *** Waiting for unfinished jobs....
[ 25%] Traceback (most recent call last):
File "/opt/ros/hydro/lib/python2.7/site-packages/genpy/generator.py", line 965, in generate_messages
outfile = self.generate(msg_context, full_type, f, outdir, search_path) #actual generation
File "/opt/ros/hydro/lib/python2.7/site-packages/genpy/generator.py", line 946, in generate
for l in self.generator_fn(msg_context, spec, search_path):
File "/opt/ros/hydro/lib/python2.7/site-packages/genpy/generator.py", line 885, in srv_generator
for l in msg_generator(msg_context, mspec, search_path):
File "/opt/ros/hydro/lib/python2.7/site-packages/genpy/generator.py", line 736, in msg_generator
md5sum = genmsg.compute_md5(msg_context, spec)
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/gentools.py", line 119, in compute_md5
return _compute_hash(msg_context, spec, hashlib.md5())
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/gentools.py", line 103, in _compute_hash
hash.update(compute_md5_text(msg_context, spec))
TypeError: Unicode-objects must be encoded before hashing
ERROR: Unable to generate services for package 'rosserial_msgs': while processing '/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/src/rosserial/rosserial_msgs/srv/RequestParam.srv': Unicode-objects must be encoded before hashing
Generating Python srv __init__.py for rosserial_arduino
rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_py.dir/build.make:78: recipe for target '/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/lib/python3.4/site-packages/rosserial_msgs/srv/_RequestParam.py' failed
make[2]: *** [/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/lib/python3.4/site-packages/rosserial_msgs/srv/_RequestParam.py] Error 1
CMakeFiles/Makefile2:399: recipe for target 'rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_py.dir/all' failed
make[1]: *** [rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_py.dir/all] Error 2
Traceback (most recent call last):
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/genlisp_main.py", line 71, in genmain
retcode = generate_msg(options.package, args[1:], options.outdir, search_path)
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/generate.py", line 720, in generate_msg
generate_msg_from_spec(msg_context, spec, search_path, out_dir, pkg)
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/generate.py", line 770, in generate_msg_from_spec
write_md5sum(s, msg_context, spec)
File "/opt/ros/hydro/lib/python2.7/site-packages/genlisp/generate.py", line 591, in write_md5sum
md5sum = genmsg.compute_md5(msg_context, parent or spec)
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/gentools.py", line 119, in compute_md5
return _compute_hash(msg_context, spec, hashlib.md5())
File "/opt/ros/hydro/lib/python2.7/site-packages/genmsg/gentools.py", line 103, in _compute_hash
hash.update(compute_md5_text(msg_context, spec))
TypeError: Unicode-objects must be encoded before hashing
ERROR: Unicode-objects must be encoded before hashing
rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_lisp.dir/build.make:64: recipe for target '/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/share/common-lisp/ros/rosserial_msgs/msg/Log.lisp' failed
make[2]: *** [/home/jared/Documents/AdvancedRoboticsArm/catkin_ws/devel/share/common-lisp/ros/rosserial_msgs/msg/Log.lisp] Error 3
CMakeFiles/Makefile2:368: recipe for target 'rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_lisp.dir/all' failed
make[1]: *** [rosserial/rosserial_msgs/CMakeFiles/rosserial_msgs_generate_messages_lisp.dir/all] Error 2
[ 33%] Built target rosserial_arduino_generate_messages_py
Makefile:126: recipe for target 'all' failed
make: *** [all] Error 2
Invoking "make" failed
Any input would be helpful. Thanks!
Answer: Your SyntaxError Exception for the comma in `raise RuntimeError, ...` suggests
the Python interpreter is actually Python 3 despite your lib path contains
Python 2.7 libs.
Double check your paths and ensure you're running Python 2.7
|
Manipulate value before inserting it with format(**locals()) in python
Question: Is it possible to manipulate a local variable before using it in .format()
with **locals() without making a new variable? So something that has the same
effect as this:
medium="image"
size_name="double"
width=200
height=100
width2=width*2
height2=height*2
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals())
But more elegant, without creating the width2 and height2 variables. I tried
this:
medium="image"
size_name="double"
width=200
height=100
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals(),height2=height*2,width2=width*2)
But it throws an error "SyntaxError: invalid syntax" at the first comma after
locals().
Answer: Just change the order:
print "A {size_name} sized {medium} is {width2} by {height2}".format(height2=height*2,width2=width*2,**locals())
Star arguments always come after normal ones.
To make this answer less trivial, this is what I have in my standard
repertoire:
import string
def f(s, *args, **kwargs):
"""Kinda "variable interpolation". NB: cpython-specific!"""
frame = sys._getframe(1)
d = {}
d.update(frame.f_globals)
d.update(frame.f_locals)
d.update(kwargs)
return string.Formatter().vformat(s, args, d)
It can be applied to your example like this:
print f("A {size_name} sized {medium} is {0} by {1}", width*2, height*2)
local (and global) variables are passed in automatically, expressions use
numeric placeholders.
|
python locale currency to 0 decimals
Question: I can't figure out how to set my currency to 0 decimals. for now it always
puts .00 behind my currency.
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
damn = locale.currency(self.damn, grouping=True).replace('$','') + " Dmn"
self.damn is always an integer.
Answer: It seems like you are just interested in grouping. You don't need to use the
currency function for this. Use `locale.format()`:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
damn = '{0} Dmn'.format(locale.format('%d', self.damn, True))
And if you don't depend on the `locale` stuff, you can group the number with
`string.format()`, too:
# Comma as separator
damn = '{:,} Dmn'.format(self.damn)
# Locale aware separator
damn = '{:n} Dmn'.format(self.damn)
|
Kivy crashes in Android on launch
Question: When I start my Kivy app on my Android phone (Samsung GSIII) the splash screen
appears then it crashes and returns to my previous screen. After trail and
error I settled on the fact that my import of ws4py was causing the error.
I added ws4py to my buildozer.spec file under requirements `requirements =
kivy,ws4py`, and it seems to download correctly while running `$>buildozer
android debug`. Looking through the source code of ws4py and reading the docs,
there are no imports other than modules in the standard lib so it doesn't seem
to be a dependency issue (but maybe it is?).
The DDMS log is here:
05-02 09:17:29.677: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libsdl.so 0x422833c8
05-02 09:17:29.687: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libsdl.so 0x422833c8
05-02 09:17:29.687: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libsdl_image.so 0x422833c8
05-02 09:17:29.697: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libsdl_image.so 0x422833c8
05-02 09:17:29.697: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libsdl_image.so 0x422833c8, skipping init
05-02 09:17:29.697: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libsdl_ttf.so 0x422833c8
05-02 09:17:29.697: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libsdl_ttf.so 0x422833c8
05-02 09:17:29.697: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libsdl_ttf.so 0x422833c8, skipping init
05-02 09:17:29.697: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libsdl_mixer.so 0x422833c8
05-02 09:17:29.707: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libsdl_mixer.so 0x422833c8
05-02 09:17:29.707: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libsdl_mixer.so 0x422833c8, skipping init
05-02 09:17:29.707: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libpython2.7.so 0x422833c8
05-02 09:17:29.727: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libpython2.7.so 0x422833c8
05-02 09:17:29.727: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libpython2.7.so 0x422833c8, skipping init
05-02 09:17:29.727: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libapplication.so 0x422833c8
05-02 09:17:29.727: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libapplication.so 0x422833c8
05-02 09:17:29.727: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libapplication.so 0x422833c8, skipping init
05-02 09:17:29.727: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libsdl_main.so 0x422833c8
05-02 09:17:29.727: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libsdl_main.so 0x422833c8
05-02 09:17:29.737: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libsdl_main.so 0x422833c8, skipping init
05-02 09:17:29.737: D/dalvikvm(22120): Trying to load lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_io.so 0x422833c8
05-02 09:17:29.737: D/dalvikvm(22120): Added shared lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_io.so 0x422833c8
05-02 09:17:29.737: D/dalvikvm(22120): No JNI_OnLoad found in /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_io.so 0x422833c8, skipping init
05-02 09:17:29.737: D/dalvikvm(22120): Trying to load lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/unicodedata.so 0x422833c8
05-02 09:17:29.747: D/dalvikvm(22120): Added shared lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/unicodedata.so 0x422833c8
05-02 09:17:29.747: D/dalvikvm(22120): No JNI_OnLoad found in /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/unicodedata.so 0x422833c8, skipping init
05-02 09:17:29.747: D/dalvikvm(22120): Trying to load lib /data/app-lib/com.shufudesign.drmb-2/libsqlite3.so 0x422833c8
05-02 09:17:29.757: D/dalvikvm(22120): Added shared lib /data/app-lib/com.shufudesign.drmb-2/libsqlite3.so 0x422833c8
05-02 09:17:29.757: D/dalvikvm(22120): No JNI_OnLoad found in /data/app-lib/com.shufudesign.drmb-2/libsqlite3.so 0x422833c8, skipping init
05-02 09:17:29.757: D/dalvikvm(22120): Trying to load lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_sqlite3.so 0x422833c8
05-02 09:17:29.757: D/dalvikvm(22120): Added shared lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_sqlite3.so 0x422833c8
05-02 09:17:29.757: D/dalvikvm(22120): No JNI_OnLoad found in /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_sqlite3.so 0x422833c8, skipping init
05-02 09:17:29.767: D/dalvikvm(22120): Trying to load lib /data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_imaging.so 0x422833c8
05-02 09:17:29.767: E/dalvikvm(22120): dlopen("/data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_imaging.so") failed: dlopen failed: library "/data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload/_imaging.so" not found
05-02 09:17:30.488: I/python(22120): ['/data/data/com.shufudesign.drmb/files/lib/python2.7/site-packages', '/data/data/com.shufudesign.drmb/files/lib/site-python']
05-02 09:17:30.488: I/python(22120): Android path ['/data/data/com.shufudesign.drmb/files/lib/python27.zip', '/data/data/com.shufudesign.drmb/files/lib/python2.7', '/data/data/com.shufudesign.drmb/files/lib/python2.7/lib-dynload', '/data/data/com.shufudesign.drmb/files/lib/python2.7/site-packages', '/data/data/com.shufudesign.drmb/files', '/data/data/com.shufudesign.drmb/files/lib/python2.7/site-packages/PIL', '/data/data/com.shufudesign.drmb/files/_applibs']
05-02 09:17:30.908: I/python(22120): [INFO ] [Logger ] Record log in /data/data/com.shufudesign.drmb/files/.kivy/logs/kivy_14-05-02_0.txt
05-02 09:17:31.990: I/python(22120): /data/data/com.shufudesign.drmb/files/lib/python2.7/site-packages/kivy/core/image/img_pygame.py:12: RuntimeWarning: import cdrom: No module named cdrom
05-02 09:17:32.250: I/ActivityManager(610): Process com.shufudesign.drmb:python (pid 22120) (adj 0) has died.
05-02 09:17:32.250: W/ActivityManager(610): Force removing ActivityRecord{42ed13d0 u0 com.shufudesign.drmb/org.renpy.android.PythonActivity}: app died, no saved state
I checked out a few questions on the kivy and python-for-android google groups
of people who had the same question about the _imaging.so error. The response
seemed to be that is not causing the issue. I stripped out everything in my
app except drawing a circle (which works) and then adding the ws4py import
(which breaks everything).
Is there something I am missing about adding third party libraries other than
adding them to the spec file? Everything works fine when running in Ubuntu.
Any help would be greatly appreciated because my app is dependent on web
sockets to connect to my backend.
Answer: Have you enabled the INTERNET Android permission?
Also, ws4py has a lot of dependencies you might have to add. I can see
problems especially with tornado, gevent, and cython.
<https://github.com/Lawouach/WebSocket-for-
Python/blob/master/requirements/py2kreqs.txt>
|
Centralize logs from Python and NodeJS thanks to RabbitMQ
Question: I have a service using NodeJS, RabbitMQ and Python workers. The NodeJS brokers
use MongoDB and the Python workers have only a connection to the rabbitMQ
server.
I would like to be able to centralize all the logs from the different
languages in a db.
My idea was to push all the logs in a rabbitMQ queue and then push them in the
mongoDB used by NodeJS.
I would like to know if this is the best way to have centralized log and how
can I redirect the logging python module to a pika consumer?
Answer: This is custom python logging Handler for RabbitMQ which I had written. I had
inherited Handler class and had overridden emit and close methods. I used
Kombu as python library to access RabbiMQ
import logging
class RabbitMQHandler(logging.Handler):
"""
A handler that acts as a RabbitMQ publisher
Requires the kombu module.
Example setup::
handler = RabbitMQHandler('amqp://guest:guest@localhost//', queue='my_log')
"""
def __init__(self, uri=None, queue='logging'):
logging.Handler.__init__(self)
try:
import kombu
except ImportError:
raise RuntimeError('The Kombu library is required for the RabbitMQSubscriber.')
if uri:
connection = kombu.Connection(uri)
self.queue = connection.SimpleQueue(queue)
def emit(self, record):
self.queue.put(record.msg)
def close(self):
self.queue.close()
Usage :
# our own logger
my_logger = logging.getLogger('teja_logger')
my_logger.setLevel(logging.DEBUG)
# rabbitmq handler
rabbitmq_handler = RabbitMQHandler('amqp://guest:guest@localhost:5672//', queue = 'log_q')
# adding rabbitmq handler
my_logger.addHandler(rabbitmq_handler)
my_logger.debug('hello')
|
blocking api redirect with requests in python 3.4
Question: I am creating a python program that uses an online thesaurus and returns
synonyms. Unfortunately sometimes it will take a word that is spelled wrong,
and redirect to a page for a word that is close to it, which is sometimes
problematic. How can I stop it from redirecting? I would appreciate any
advice. This is the code that applies:
def get_synonym(the_word):
#return a dictionary of the thesaurus results of the word
theurl = (the api key for the thesaurus)
new_word = the_word + "/json"
theurl = theurl + new_word
r = requests.get(theurl)
thewords = r.text #all the text for the results
from json import loads
thewords = json.loads(thewords) #make a dictionary of terms
return thewords #return dictionary of synonyms for the_word
Answer: Use the [`allow_redirects=False`](http://docs.python-
requests.org/en/latest/user/quickstart/#redirection-and-history) keyword
argument:
r = requests.get(url, allow_redirects=False)
By default, requests follows redirects on all methods except `HEAD`.
|
Python - Flask: render_template() not found
Question: I'm new in flask. I have this code: Will you give me an advice what I'm doing
wrong? Thanks
from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('my-form.html')
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
return processed_text
app.debug = True
print("asdsa")
if __name__ == '__main__':
app.run()
I have put file my-form.html into this folder: C:\Python33\Lib\site-
packages\flask\testsuite\templates
But when I refresh the 127.0.0.1:5000 I get
jinja2.exceptions.TemplateNotFound:
File "C:\Python33\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python33\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python33\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python33\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python33\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python33\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python33\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python33\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python33\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python33\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\workspace\ApproximateStringSearch\testest.py", line 9, in my_form
return render_template('my-form.html')
File "C:\Python33\lib\site-packages\flask\templating.py", line 127, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "C:\Python33\lib\site-packages\jinja2\environment.py", line 830, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "C:\Python33\lib\site-packages\jinja2\environment.py", line 791, in get_template
return self._load_template(name, self.make_globals(globals))
File "C:\Python33\lib\site-packages\jinja2\environment.py", line 765, in _load_template
template = self.loader.load(self, name, globals)
File "C:\Python33\lib\site-packages\jinja2\loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Python33\lib\site-packages\flask\templating.py", line 64, in get_source
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: my-form.html
Answer: You put your template in the wrong place. From the Flask docs:
> Flask will look for templates in the templates folder. So if your
> application is a module, this folder is next to that module, if it’s a
> package it’s actually inside your package:
See the docs for more information:
<http://flask.pocoo.org/docs/quickstart/#rendering-templates>
|
Installing NodeboxOpenGL on windows
Question: Hello I am trying to install and make use of NodeboxOpenGL, the python library
so I can create my own graphs with nodes and edges. But I am running into some
trouble, starting off at [NodeBox OpenGL
site](http://www.cityinabottle.org/nodebox/). I downloaded NodeBox for OpenGL
and then pyglet, I then did easy_install nodebox-opengl. _Note I did not do
pip install_ I installed pyglet from
[pyglet](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyglet). So now I am
thinking its all ready to go. I did a quick check of my c:\python27\Lib\site-
packages\ location just be sure the nodebox folder was there, all seems good.
I tried the sample program that's on the site
from nodebox.graphics import *
from nodebox.graphics.physics import Flock
flock = Flock(40, 0, 0, 500, 500)
flock.sight = 300
def draw(canvas):
background(1)
fill(0, 0.75)
flock.update(cohesion=0.15)
for boid in flock:
push()
translate(boid.x, boid.y)
scale(0.5 + 1.5 * boid.depth)
rotate(boid.heading)
arrow(0, 0, 15)
pop()
canvas.fps = 30
canvas.size = 600, 400
canvas.run(draw)
tried to run it, but i keep getting this error
Traceback (most recent call last):
File "E:\Workspace\ElasticNodes\graph1.py", line 5, in <module>
from nodebox.graphics import *
File "E:\Workspace\ElasticNodes\nodebox\graphics\__init__.py", line 1, in <module>
import bezier
File "E:\Workspace\ElasticNodes\nodebox\graphics\bezier.py", line 10, in <module>
from context import BezierPath, PathElement, PathError, Point, MOVETO, LINETO, CURVETO, CLOSE
File "E:\Workspace\ElasticNodes\nodebox\graphics\context.py", line 29, in <module>
import geometry
File "E:\Workspace\ElasticNodes\nodebox\graphics\geometry.py", line 454, in <module>
from pyglet.gl import \
ImportError: cannot import name pointer
I tried modifying the python script i.e _In your script, add the location of
NodeBox to sys.path, before importing it: >>> MODULE =
'/users/tom/python/nodebox' >>> import sys; if MODULE not in sys.path:
sys.path.append(MODULE) >>> import nodebox_
But still the same error. I am using Python2.7, running on windows. I am not
sure what I am doing wrong. Has anyone got any experience with running this
library on windows. What am I doing wrong
Answer: I am having a similar problem with Linux. The Nodebox-opengl site (
<http://www.cityinabottle.org/nodebox/> ) says that python 2.5 or 2.6 must be
used, so it is possible that the problem is that you are using 2.7.
EDIT: Ok, I installed pyglet first, with pip (and or apt-get, I did both) and
I don't get a problem with pyglet. But I still do get other problems.
|
How to draw a ring of colors using turtle module in python
Question: I have the following code which is supposed to draw a ring of colors around a
circle but only one color if printed and changed 8 times before moving to the
next
import turtle
def drawCircle(colorList, radius):
for color in colorList:
turtle.color(color)
for i in range(len(colorList)):
turtle.penup()
turtle.setpos(0, -radius)
xpos=turtle.xcor()
ypos=turtle.ycor()
head=turtle.heading()
turtle.begin_fill()
turtle.pendown()
turtle.home()
turtle.setpos(xpos,ypos)
turtle.setheading(head)
turtle.circle(radius)
turtle.end_fill()
turtle.penup()
return
colorList=["#880000","#884400","#888800","#008800",\
"#008888","#000088","#440088","#880088"]
drawCircle(colorList,200)
How would I make it that each arc around the circle is a different color.
[here is an example](http://www.hgtv.com/decorating-basics/color-wheel-
primer/index.html)
Answer: you will need something like this
def drawSegment(color,x, y, r, angleStart, angleEnd, step=1):
#More efficient to work in radians
radianStart = angleStart*pi / 180
radianEnd = angleEnd*pi / 180
radianStep=step *pi/180
#Draw the segment
turtle.penup()
turtle.setpos(x,y)
turtle.color(color)
turtle.begin_fill()
turtle.pendown()
for theta in arange(radianStart,radianEnd,radianStep):
turtle.setpos(x + r * cos(theta), y + r * sin(theta))
turtle.setpos(x + r * cos(radianEnd), y + r * sin(radianEnd))
turtle.setpos(x, y);
turtle.end_fill()
def drawCircle(colorList,radius):
#do something to draw an equal segment for each color advancing it around 360 degree's
|
return http error code for curl in python
Question:
status, output = commands.getstatusoutput("curl -k -v --cookie cookie_name 'URL' -o filename")
Above is my code , I am trying to return http response code of curl. So i
tried the following option -w %{http_code}
status, output = commands.getstatusoutput("curl -k -v --cookie cookie_name -w %{http_code} 'URL' -o filename")
When i run it in python script and print status, nothing gets printed. Can
someone please help me with the curl return code? I want to try scenario's
like when username password is wrong to get a status, or when the network host
is not reachable or content not downloaded properly.
Answer: As the other guys suggested, it is better to use HTTP to do a curl call.
[requests](http://docs.python-requests.org/en/latest/) is the easiest way:
import requests
data = {
...
}
r = requests.post(url, data=data)
print r.content
`r.content` contains the response body and if you need the status code just
use `r.status_code`.
|
Python 3.4 Issue with writing to a file with time.sleep()
Question: I am using Python 3.4. I'm trying to figure out why the writerow() is not
working if I put a sleep timer at the end it does not write the data to the
Test.dat file. The code looks like this
import csv, time
fileName = "Test.dat"
freq = 5;
with open(fileName, 'a') as fp:
a = csv.writer(fp, delimiter=',')
for i in range(1, 10):
data = [2014, 5, 3, 5, 26, 53, 'Price', '100.00']
a.writerow(data)
time.sleep(freq)
But then if I remove the timer it writes the data in the Test.dat file
import csv, time
fileName = "Test.dat"
freq = 5;
with open(fileName, 'a') as fp:
a = csv.writer(fp, delimiter=',')
for i in range(1, 10):
data = [2014, 5, 3, 5, 26, 53, 'Price', '100.00']
a.writerow(data)
Ans:
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
2014,5,3,5,26,53,Price,100.00
Answer: you are waiting 5 sec and the program take a along time to end write the file
:
wait one second ::
freq = 1;
|
Python not inserting data's into mysql
Question: I am testing Python and Mysql in that i am able to create and delete table's
but i am unable to insert data in them.I searched stackoverflow and mostly
they suggest to use
commit()
So i used it and even after i used the data is not inserted into the
database.Please help me. This is the code i use it creates the table but not
inserting data
import MySQLdb
db = MySQLdb.connect("localhost","user","password")
cxn = MySQLdb.connect(db='test')
cursor = cxn.cursor()
cursor.execute("CREATE TABLE users(name VARCHAR(40),id VARCHAR(40))")
cursor.execute("INSERT INTO users(name,id) VALUES('John','1')")
db.commit()
print "Opertion completed successfully"
Answer: Are `db` and `cxn` connections to the same database?
You should establish your connection using following:
db = MySQLdb.connect(host="localhost",
db="test",
user="user",
passwd="password")
The cursor should then be derived from _this_ connection via:
cursor = db.cursor()
I would hazard that your issue is coming from the ambiguity between `db` and
`cxn`.
|
Affine 3D transformation in Python
Question: I'm programming a function in Python in Autodesk Maya (using PyMel for Maya)
I have three 3D points; p0, p1, p2.
Then they make a rigid transformation, so after the transformation (an affine
transformation) I have their new positions; q0, q1, q2.
I also have a fourth point before the transformation; p3. I want to calculate
its position after the same transformation; q4.
So I need to calculate the transformation matrix, and then apply it to p4. I
don't know how to do either. List = an array of objects
import pymel.core as pm
import pymel.core.datatypes as dt
p0 = dt.Vector(pm.getAttr(list[0]+".tx"), pm.getAttr(list[0]+".ty"), pm.getAttr(list[0]+".tz"))
p1 = dt.Vector(pm.getAttr(list[1]+".tx"), pm.getAttr(list[1]+".ty"), pm.getAttr(list[1]+".tz"))
p2 = dt.Vector(pm.getAttr(list[2]+".tx"), pm.getAttr(list[2]+".ty"), pm.getAttr(list[2]+".tz")
p3 = dt.Vector(pm.getAttr(list[3]+".tx"), pm.getAttr(list[3]+".ty"), pm.getAttr(list[3]+".tz"))
The 3D points are read from animated objects in the Maya scene. So at another
frame, I run this code to get
q0 = dt.Vector(pm.getAttr(list[0]+".tx"), pm.getAttr(list[0]+".ty"), pm.getAttr(list[0]+".tz"))
q1 = dt.Vector(pm.getAttr(list[1]+".tx"), pm.getAttr(list[1]+".ty"), pm.getAttr(list[1]+".tz"))
q2 = dt.Vector(pm.getAttr(list[2]+".tx"), pm.getAttr(list[2]+".ty"), pm.getAttr(list[2]+".tz"))
#q3 = TransformationMatrix between (p0,p1,p2) and (q0,q1,q2), applied to p3
I tried to calculate with vectors, but I ended up with errors due to divisions
by zero... So I figured that a transformation matrix should solve it without
problems.
I've got a deadline not far ahead and I REALLY need help solving this! PLEASE
HELP!
Edit: [how to perform coordinates affine transformation using
python?](http://stackoverflow.com/questions/8873462/how-to-perform-
coordinates-affine-transformation-using-python)
I need this function "solve_affine", but it should take only 3 points from
each set instead of 4. And I can't use numpy...
Answer: Here's a solution using numpy and scipy. scipy is mostly used to generate
random rotations, except for scipy.linalg.norm which is easy to code oneself.
The main things used from numpy are cross product and matrix multiplication,
which are also easy to code oneself.
The basic idea is this: given three non-collinear points x1,x2,x3, it's
possible to find an orthogonal triple of vectors (axes) v1,v2,v3, with v1 in
the direction of x2-x1, v2 in the plane spanned by (x2-x1) and (x3-x1), and v3
completing the triple.
The points y1,y2,y3 are rotated and translated relative to x1,x2,x3. The axes
w1,w2,w3 generated from y1,y2,y3 are rotated (i.e., no translation) from
v1,v2,v3. These two sets of triples are each orthogonal, so it's easy to find
the rotation from them: `R = W * transpose(V)`
Once we have the rotation, finding the translation is simple: `y1 = R*x + t`,
so `t = y1 - R*x`. It might be a better to use a least-squares solver and
combine all three points to get an estimate of t.
import numpy
import scipy.linalg
def rand_rot():
"""Return a random rotation
Return a random orthogonal matrix with determinant 1"""
q, _ = scipy.linalg.qr(numpy.random.randn(3, 3))
if scipy.linalg.det(q) < 0:
# does this ever happen?
print "got a negative det"
q[:, 0] = -q[:, 0]
return q
def rand_noncollinear():
"""Return 3 random non-collinear vectors"""
while True:
b = numpy.random.randn(3, 3)
sigma = scipy.linalg.svdvals(b)
if sigma[2]/sigma[0] > 0.1:
# "very" non-collinear
break
# "nearly" collinear; try again
return b[:, 0], b[:, 1], b[:, 2]
def normalize(a):
"""Return argument normalized"""
return a/scipy.linalg.norm(a)
def colstack(a1, a2, a3):
"""Stack three vectors as columns"""
return numpy.hstack((a1[:, numpy.newaxis],
a2[:, numpy.newaxis],
a3[:, numpy.newaxis]))
def get_axes(a1, a2, a3):
"""Generate orthogonal axes from three non-collinear points"""
# I tried to do this with QR, but something didn't work
b1 = normalize(a2-a1)
b2 = normalize(a3-a1)
b3 = normalize(numpy.cross(b1, b2))
b4 = normalize(numpy.cross(b3, b1))
return b1, b4, b3
# random rotation and translation
r = rand_rot()
t = numpy.random.randn(3)
# three non-collinear points
x1, x2, x3 = rand_noncollinear()
# some other point
x4 = numpy.random.randn(3)
# the images of the above in the transformation.
# y4 is for checking only -- won't be used to estimate r or t
y1, y2, y3, y4 = [numpy.dot(r, x) + t
for x in x1, x2, x3, x4]
v1, v2, v3 = get_axes(x1, x2, x3)
w1, w2, w3 = get_axes(y1, y2, y3)
V = colstack(v1, v2, v3)
W = colstack(w1, w2, w3)
# W = R V, so R = W * inverse(V); but V orthogonal, so inverse(V) is
# transpose(V):
rfound = numpy.dot(W, V.T)
# y1 = R x1 + t, so...
tfound = y1-numpy.dot(r, x1)
# get error on images of x2 and x3, just in case
y2err = scipy.linalg.norm(numpy.dot(rfound, x2) + tfound - y2)
y3err = scipy.linalg.norm(numpy.dot(rfound, x3) + tfound - y3)
# and check error image of x4 -- getting an estimate of y4 is the
# point of all of this
y4err = scipy.linalg.norm(numpy.dot(rfound, x4) + tfound - y4)
print "y2 error: ", y2err
print "y3 error: ", y3err
print "y4 error: ", y4err
|
Storing username and password into a dictionary?
Question: Currently at the moment im working a small login screen in python, What i want
it to do is ask a user to register if theyre isnt a account already created,
But one small problem im having is how can i save the username and password
into a dictionary, I would also like to know how i would save the dictionary
to a .txt file that can be loaded to restore user info/variables if this is
possible.
Im not too sure whether im meant to ask for help with my code or im allowed to
ask questions like this, I just need a reffernce or a little help. Also just
to add im not asking for someone to do it for me, Just to give me a shove in
the right direction
Please dont flame me ;p
import sys
import math
user = None
password = None
store = dict()
newUser = True
while newUser == True:
userguess=""
passwordguess=""
print("Hello, Please create a unique username and password.")
user = input("USERNAME: ")
password = input("PASSWORD: ")
store[user] = password
print(store)
That is what i have tried so far, I gathered the storing to dictionary from
another page on here, Was just looking for a breakdown on assigning stuff to a
key
Answer: you dont ... you save a hash into a dictionary (a hash is simpley a non
reversable encoding)
eg: `md5("password") == '5f4dcc3b5aa765d61d8327deb882cf99'`
however there is no real way to go from that back to the password
`nothing_does_this('5f4dcc3b5aa765d61d8327deb882cf99') == "password"`
(not entirely true... but close enough fo the concept)
import hashlib
def create_users()
users = {}
while True:
username = raw_input("Enter Username:")
password = raw_input("Enter Password:")
users[username] = hashlib.md5(password).hexdigest()
if raw_input("continue?")[0].lower() != "y":
return users
def login(userdict):
username = raw_input("Username:")
password = raw_input("Password:")
return userdict.get(username,None) == hashlib.md5(password).hexdigest()
users = create_users()
if login(users):
print "Double Winning!!!"
else:
print "You Lose Sucka!!!"
as pointed out md5 is not a very secure hash, there are much better ones to
use sha256 is pretty good still I think, bcrypt is even better (for some
definition of better) ... however md5 is a simple hash to help with
understanding what they are..
|
How do I only print out the message instead of the whole text
Question: This is my Python code to read an email:
import imaplib
mailserver=imaplib.IMAP4_SSL('imap.gmail.com',993)
user = 'm****[email protected]'
passs = 'm****s'
mailserver.login(user,passs)
status, count = mailserver.select('Inbox')
status, data = mailserver.fetch(count[0],'(UID BODY[TEXT])')
print(data)
mailserver.close()
mailserver.logout()
It prints out the whole html portion of the message. How do I only print out
the message itself?
Answer:
import imaplib
mailserver=imaplib.IMAP4_SSL('imap.gmail.com',993)
user = 'm****[email protected]'
passs = 'm****s'
mailserver.login(user,passs)
status, count = mailserver.select('Inbox')
status, data = mailserver.fetch(count[0],'(RFC822)')
print(data)
# Something like this
import email
msg = email.message_from_string(data[0][1])
print(msg['Subject'], msg['Body'])
mailserver.close()
mailserver.logout()
I posted a self reminder in a gist if you are curious.
<https://gist.github.com/jmunsch/11374042>
|
Why does line_profiler in python not add up the times correctly?
Question: I am new to the line_profiler package in python. Am I reading the result
incorrectly, or shouldn't the components in the output below add up to 1.67554
seconds? Instead, they add up to 3.918 seconds (2426873 microseconds + 1491105
microseconds). Thanks!
# test.py
import numpy as np
def tf():
arr = np.random.randn(3000,6000)
np.where(arr>1,arr,np.nan)
import test
%lprun -f test.tf test.tf()
Timer unit: 4.27654e-07 s
File: test.py
Function: tf at line 9
Total time: 1.67554 s
Line # Hits Time Per Hit % Time Line Contents
==============================================================
9 def tf():
10 1 2426873 2426873.0 61.9 arr = np.random.randn(3000,6000)
11 1 1491105 1491105.0 38.1 np.where(arr>1,arr,np.nan)
Answer: You misread the time there; those are _not microseconds_.
From the [documentation](http://pythonhosted.org/line_profiler/):
> Time: The total amount of time spent executing the line **in the timer's
> units**. In the header information before the tables, you will see a line
> "Timer unit:" **giving the conversion factor to seconds**. It may be
> different on different systems.
Emphasis mine. Your output shows each _Timer unit_ is about 0.428
microseconds. The totals match if you multiply the units with the _Timer unit_
value:
>>> unit = 4.27654e-07
>>> 2426873 * unit + 1491105 * unit
1.675538963612
|
Can't get ipython console in spyder
Question: I'm having trouble getting an **ipython** console in Spyder. It only offers a
**python** interpreter under the "interpreters" menu.
I've seen this issue for a couple of others in Stackoverflow, but didn't have
much joy with the proffered solutions.
I'm running linux Mint 16 and have installed both ipython (v 1.1.0) and Spyder
(v 2.2.1) the easy way via the Mint _Software Manager_. I made sure that I
also installed **ipython-qtconsole** and verified that I could run it from a
terminal (i.e. ipython qtconsole).
I can activate an ipython console using the following commands in a Spyder
python console:
import IPython
IPython.start_ipython()
though the font coloring is strange and doesn't work well on a white
background (e.g. error messages in yellow and light green). It would be nice
anyway to be able to start ipython the normal way from the Spyder menu.
Answer: You may want to install `python-zmq` for Python 2 and `python3-zmq` for Python
3.
I use Ubuntu 14.04, so:
`sudo apt-get install python-zmq python3-zmq`
|
how to test a jline based console application
Question: I'm trying to test a console application that uses
[jline](http://jline.sourceforge.net/) for handling interaction with the user.
I'm starting the application using
[ProcessBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html)
which gives me access to the application's:
* [Standard Input](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getOutputStream%28%29)
* [Standard Output](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getInputStream%28%29)
* [Standard Error](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#getErrorStream%28%29)
I was expecting to use a workflow similar to this:
* Start Application
* Read Output until I see the application's prompt `>`
* Send Input for my test case, e.g. `login`
* Read Output until I see the expect response, e.g. `Username:`
* and so on
However, the test just freezes. Stepping through the code, it appears that
jline is freezing on JNI calls to
[_getch](https://github.com/fusesource/jansi-
native/blob/aebb7f4b37719722375f00e33c1926720c3e8406/src/main/java/org/fusesource/jansi/internal/WindowsSupport.java#L46)
on Windows. I'm guessing that the problem is because I am running Java from
ProcessBuilder which is headless so there is no console and that is confusing
windows. Setting `-Djline.terminal=jline.UnsupportedTerminal` as per the Jline
docs doesn't help either.
I've found a thread discussing [Python
pexpect](http://stackoverflow.com/a/23235611/1033422) for testing a (non-java)
readline application.
**Question** : how can I test a jline based application using just java tools?
Answer: I gave up on trying to test just using java tools and went with using the
python pexpect library to execute the console application. The tests were
integrated into the maven build, but required a *nix host to run them:
import unittest
import pexpect
import os
import signal
import subprocess
import urllib
import urllib2
import json
from wiremock import WiremockClient
class TestInteractive(unittest.TestCase):
cli_cmd = "java -jar " + os.environ["CLI_JAR"]
# ... code omitted for brevity
def test_interactive_mode_username_and_password_sent_to_server(self):
child = pexpect.spawn(TestInteractive.cli_cmd, timeout=10)
child.expect ('Username: ')
child.sendline ('1234')
child.expect ('Password: ')
child.sendline ('abcd')
child.expect ('Successfully authenticated')
child.expect ('stratos> ')
child.sendline ('exit')
child.expect (pexpect.EOF)
# CLI sends GET request to mock server url /stratos/admin/coookie
self.assertEqual(self.wiremock.get_cookie_auth_header(), "1234:abcd")
# ... code omitted for brevity
if __name__ == '__main__':
try:
unittest.main()
# handle CTRL-C
except KeyboardInterrupt:
# shut down wiremock
TestInteractive.wiremock.stop()
exit(1)
The full CLI test suite for the project I was working on can be found
[here](https://github.com/apache/stratos/tree/4.1.0-alpha/components/org.apache.stratos.cli/src/test/python).
|
Oop for class circle
Question: Im writing a class in python called Circle. Now as part of the class I want to
define methods so I did but when I run the program it crashes and says they
are not defined. I cant find the problem.
class Circle():
""" Holds data on a circle in the plane """
def __init__(self,*args):
if isinstance(args[0],Point) and isinstance(args[1],(float,int)):
assert args[1]>0
self.center= args[0]
self.r= args[1]
else:
assert args[2]>0
self.a=args[0]
self.b=args[1]
self.center= Point(self.a,self.b)
self.r= args[2]
def __mul__(self,other):
assert isinstance(other,(float,int))
assert other>0
return Circle(self.center,self.r*other)
__rmul__= __mul__
def area(self):
return math.pi*self.r**2
def circumference(self):
return 2*self.r*math.pi
def move(self,p):
assert isinstance(p,Point)
self.center= p
return None
I wrote a class for Point aswell, so thats not the problem. This is what
happens when I run the porgram:
>>> a=Circle(-3,-3,1)
>>> area(a)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
area(a)
NameError: name 'area' is not defined
Answer: **Edit** : as @jsbueno points out, this was not the error causing your error
message: _Your indentation is off (`def __mul__` should be 1 space to the
left), therefore Python thinks you have ended your class definition and are
simply defining some more functions (not class methods)._
Also, you should call `area` as a method - `a.area()`, not `area(a)`.
I've done a bit of reworking - added some comments, renamed some variables,
generally cleaned up - this now works properly:
from math import pi
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
"""
Holds data on a circle in the plane
"""
def __init__(self, a, b, c=None):
if c is None:
# Circle(Point, scalar)
self.center = a
self.r = b
else:
# Circle(scalar, scalar, scalar)
self.center = Point(a, b)
self.r = c
@property
def r(self):
return self._r
@r.setter
def r(self, new_r):
assert new_r > 0
self._r = new_r
def __mul__(self, scale_by):
return Circle(self.center, self.r * scale_by)
__rmul__ = __mul__
def area(self):
return pi * self.r**2
def circumference(self):
return 2 * pi * self.r
def move(self, new_center):
self.center = new_center
then
a = Circle(-3,-3,1)
print(a.area())
gives
3.141592653589793
which is correct.
|
Making Python list in file and editing it later
Question: I'm making an program which stores certain data in txt files. I did it like
this and it works, but I want to change it to lists, so it's easier to edit
stuff inside with list.remove and list.append... This is format I made:
Username:data1:data2:data3:data++
What I want to achieve is:
Username:[data1, data2, data3, data++]
Why I want this?
Because editing data separated with ":" is not "Pythonic way" to do this, so I
want to convert them to lists...
I get certain lines using this filter:
textfile = open("%s/CreativePoints/Data/plotovimemberi.txt"%pluginlokacija2, 'r+')
a = filter(lambda x: x.startswith("%s:%s"%(targetplot, userID)), \
textfile.readlines())
So current data file looks like this:
Username:data1:data2
Username1:data134:data453:data6534
Username3:data5345:data678:data111:data434
and so on...
What I want to achieve is:
Username:[data1, data2]
Username1:[data134, data453, data6534]
Username3:[data5345, data678, data111, data434]
and so on...
Why? Because I want to get certain line in file using filter I mentioned above
and edit list... So I just need to split lines using "line.split(':')[1]" and
get list of data, which I can edit using list.append and list.remove...
Thanks for reading/answering! :)
Answer: While I think I've given one answer to your question (see code below), I have
some remarks:
* it's not 'unpythonic' to use a colon as a separator in text file; that's not Python, that's data.
* you should look at something like YAML or JSON to store your data; you can then use libraries that take care of most of the details for you
* with the scheme you propose, you won't be able to have a "," in your data records, nor (simply) be able to start or end records with space. These sorts of problems should be handled for you by any reasonable JSON or YAML library.
* you could also look at something like sqlite (which comes with python) as a database store. It's a bit more work, but you'll be able to search for records based on criteria of your choosing, as well as easily delete and add records. With a plain-text file, you'll have to manage all of that yourself
Here's my solution:
from pprint import pprint
def writefile(outfilename,db):
outfile=open(outfilename,'wt')
for username,userdata in db:
userdatastr= ','.join(userdata)
outfile.write('%s: [%s]\n' % (username,userdatastr))
# or, better, use 'with file("...") as ...'
outfile.close()
def readfile(infilename):
infile=open(infilename,'rt')
db=[]
for line in infile:
username, rest = line.split(':',1)
lstart= rest.find('[')
if lstart==-1:
raise RuntimeError('couldn''t find "[" for user "%s"' % username)
lend= rest.rfind(']')
if lend==-1:
raise RuntimeError('couldn''t find "]" for user "%s"' % username)
userdata = rest[lstart+1:lend].split(',')
db.append((username,userdata))
return db
db=[('Bob',['foo','bar','baz']),
('Jane',['oof','rab','zab','xuuq']),
('Rudy',['some','data'])]
writefile('db.txt',db)
indb=readfile('db.txt')
print 'original:'
pprint(db)
print 'from file:'
pprint(indb)
Result is:
original:
[('Bob', ['foo', 'bar', 'baz']),
('Jane', ['oof', 'rab', 'zab', 'xuuq']),
('Rudy', ['some', 'data'])]
from file:
[('Bob', ['foo', 'bar', 'baz']),
('Jane', ['oof', 'rab', 'zab', 'xuuq']),
('Rudy', ['some', 'data'])]
while db.txt looks like:
Bob: [foo,bar,baz]
Jane: [oof,rab,zab,xuuq]
Rudy: [some,data]
|
NurbsCurve MatrixMath Maya api Python
Question: I am creating a toolset for creating nurbs curves/surfaces inside maya using
python.
I have a set of dictionaries that include cvPositions, knots, form etc. each
of which describe a preset 3d shape (cube, circle, pyramid etc). I also have a
3d matrix stored in the nodes metadata that is used as an offset for the
shape. This allows you to scale/move/rotate the shape without moving the
transform.
The problem is in the way I am applying this matrix is very slow:
First I will create a new (edit)transform at the position of the
(orig)transform containing the curves. Next I will transfer cv positions in
world space from (orig)transform to (edit)transform Next i will move the
(edit)transform into the matrix position. Finally I will transfer the
cvPositions back to the (orig)transform
When creating hundreds of shapes, this is becoming prohibitively slow...
Can someone describe a mathematical way to apply a matrix to a set of 3d
points? Perhaps using one of the math modules or numpy?
Alternatively,
Is there a way using OpenMaya api functions to do this? Perhaps with
MPointArray? This is as far as I have gotten on that front:
crv = OpenMaya.MFnNurbsCurve( self.dagPath )
cvs = OpenMaya.MPointArray()
space = OpenMaya.MSpace.kWorld
crv.getCVs(cvs, space)
positions = []
for i in range(cvs.length()):
pt = cvs[i]
positions.append( (pt[0], pt[1], pt[2]) )
Answer: The easiest method is to use pymel's built-in versions of points and matrices
(pymel is built in to maya 2011+). The math types are in pymel.datatatypes;
here's an example of transforming a point by a matrix in pymel:
import pymel.core as pm
pt = pm.datatypes.Point(0,0,0)
mt = pm.datatypes.Matrix(1,0,0,0, 0,1,0,0, 0,0,1,0, 5,5,5,1 )
moved = pt * mt
print moved
# [5,5,5]
Pymel points and matrices will let you do your algorithm. The math is going to
be done in the API but the Python <> C++ conversions may still make it feel
pretty slow for big data.
It sounds like you're basically re-creating 'freeze transforms' followed by
'zero pivots'. Maybe you should try that as an alternative to doing this in
python math...
|
Display or save a List of URL images
Question: Python is known to be an easy and powerful language. I have a List, literally,
of URL images,
>>> for i in images: print i
http://upload.wikimedia.org/wikipedia/commons/8/86/Influenza_virus_research.jpg
http://upload.wikimedia.org/wikipedia/commons/f/f8/Wiktionary-logo-en.svg
http://upload.wikimedia.org/wikipedia/en/e/e7/Cscr-featured.svg
http://upload.wikimedia.org/wikipedia/commons/f/fa/Wikiquote-logo.svg
http://upload.wikimedia.org/wikipedia/commons/4/4c/Wikisource-logo.svg
http://upload.wikimedia.org/wikipedia/commons/1/1b/Wikiversity-logo-en.svg
http://upload.wikimedia.org/wikipedia/commons/1/1b/Wikiversity-logo-en.svg
I wonder if there's some library (or snippet of code) in python to easily
display a list of URL images in a browser, or maybe save them in a folder.
Answer:
import urllib
urllib.urlretrieve("http://8020.photos.jpgmag.com/3670771_314453_2ee7120da5_m.jpg", "my.jpg")
The "my.jpg" is the path to save the file. It can be "/home/user/pics/my.jpg"
etc..
|
How check if current date and time is after a given date and time
Question: In Python:
1. How check if current date and time is after a given date and time object named "next_check"
2. Add X number of minutes to next check
Answer: You can do both of those things with
[`datetime`](https://docs.python.org/2/library/datetime.html) (assuming you
`import datetime` and `next_check` is actually a `datetime.datetime`
instance):
1. `if datetime.datetime.now() > next_check`; and
2. `next_check += datetime.timedelta(minutes=X)`.
If it isn't a `datetime.datetime` instance, that module contains various
functions (e.g.
[`strptime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime))
to make it into one.
|
Rotate a square by an angle in degree
Question: I have a square with center x0, y0. I wish to rotate the vertex of this square
for a given angle (theta) expressed in degree and return the new rotated
vertex in clockwise direction. I am using this
[approach](http://stackoverflow.com/questions/786472/rotate-a-point-by-an-
angle) to rotate a single point applied for each vertex
rotate point (px, py) around point (x0, y0) by angle theta you'll get:
p'x = cos(theta) * (px-x0) - sin(theta) * (py-y0) + x0
p'y = sin(theta) * (px-x0) + cos(theta) * (py-y0) + y0
where:
px, py = coordinate of the point
y0, x0, = centre of rotation
theta = angle of rotation
I wrote a function in Python where the parameters are: x, y (=centre of the
square), side of the square, and theta_degree (angle of rotation in degree)
but the returns is in anticlockwise direction
from math import cos, sin
def get_square_plot(x, y, side, theta_degree=0):
theta = theta_degree * pi/180
xa = x-side/2
ya = y+side/2
xb = x+side/2
yb = y+side/2
xc = x+side/2
yc = y-side/2
xd = x-side/2
yd = y-side/2
xa_new = cos(theta) * (xa - x) - sin(theta) * (ya - y) + x
ya_new = sin(theta) * (xa - x) - cos(theta) * (ya - y) + y
xb_new = cos(theta) * (xb - x) - sin(theta) * (yb - y) + x
yb_new = sin(theta) * (xb - x) - cos(theta) * (yb - y) + y
xc_new = cos(theta) * (xc - x) - sin(theta) * (yc - y) + x
yc_new = sin(theta) * (xc - x) - cos(theta) * (yc - y) + y
xd_new = cos(theta) * (xd - x) - sin(theta) * (yd - y) + x
yd_new = sin(theta) * (xd - x) - cos(theta) * (yd - y) + y
return [(xa_new, ya_new),(xb_new, yb_new),(xc_new, yc_new),(xd_new, yd_new)]
get_square_plot(0, 0, 10, 0)
[(-5.0, -5.0), (5.0, -5.0), (5.0, 5.0), (-5.0, 5.0)]
instead of
[(-5.0, 5.0), (5.0, 5.0), (5.0, -5.0), (-5.0, -5.0)]
Answer: It's such a simple thing -- you've got the formula wrong for all of your
y-values.
It should be:
ya_new = sin(theta) * (xa - x) + cos(theta) * (ya - y) + y
addition instead of subtraction.
|
size of .apk when coded with kivy compared to the one in Java
Question: I just created an apk after creating an app in kivy however it seems to me
that the size of the apk created is really big on the android and after
running the app the size is becoming bigger an bigger . See example below :
1. The Code for this example .apk is a minimal app of Hello World . Code below :
import kivy kivy.require('1.0.6')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
class MyApp(App):
def build(self):
return Button(text='Hello world')
if __name__ == '__main__':
MyApp().run()
1. Size of this file comtaining above code : 1 kb
2. On Creation of its apk using python for android project with steps its size ( 6.7 MB): 3.1 ./distribute.sh -m "kivy" 3.2 ./build.py --dir /home/kivy/HelloWorld/ --package org.ex.helloworld --name "HelloWorld" --icon /home/kivy/Work/HelloWorldDistribute/a.png --version 1.3 --orientation portrait debug installd
kivy@kivy-VirtualBox:~/android/python-for-android/dist/first/bin$ du -h
HelloWorld-1.3-debug.apk 6.7M HelloWorld-1.3-debug.apk
1. On Installing this app on android Samsung galaxy s3 using following command :
4.1 adb install -r HelloWorld-1.3-debug.apk 421 KB/s (6996727 bytes in
16.208s) pkg: /data/local/tmp/HelloWorld-1.3-debug.apk Success
Size on Android : 10.5 MB
1. If i run this app for 1 time on android and after that check the size it becomes 24.11 MB
Does it mean that minimum size of android app created from kivy will be 10.5
MB ? I have seen many apps which are of smaller size and are made in Java ? Is
there any way to make apps from kivy of smaller size ? Can someone advice ?
Answer: When you write an Android app using Kivy and Python you have to include some
Kivy and Python libs in the build, Kivy itself is 5-6mb so depending on how
much data you include in your app the size will vary. Each build has an entire
Python interpreter as Brousch pointed out.
After you have built an apk, if you look inside the file you will see the
different sizes of each file in your distribution.
If you look [here](https://github.com/kivy/python-for-
android/blob/master/docs/source/customize.rst) there is a guide to the basic
layout of a distribution.
|
Why is the conversion between RGB and HLS color systems imprecise?
Question: For one of my applications, I need to convert colors from the RGB to the HLS
color system and vice versa. I found that Python has the
[colorsys](https://docs.python.org/2/library/colorsys.html) module in its
standard library.
The problem is, the conversions are sometimes a bit imprecise and return
slightly different results compared to [this online color
converter](http://www.workwithcolor.com/color-converter-01.htm).
Here is an example, first two small functions I wrote for convenience:
from __future__ import division
import colorsys
def convert_rgb_to_hls(r, g, b):
h, l, s = colorsys.rgb_to_hls(r/255, g/255, b/255)
return "HLS(" + str(int(round(h * 359))) + ", " + str(int(round(l * 100))) + ", " + str(int(round(s * 100))) + ")"
def convert_hls_to_rgb(h, l, s):
r, g, b = colorsys.hls_to_rgb(h/359, l/100, s/100)
return "RGB(" + str(int(round(r * 255))) + ", " + str(int(round(g * 255))) + ", " + str(int(round(b * 255))) + ")"
According to the online color converter, RGB(123, 243, 61) should be equal to
HLS(100, 60, 88). The results I get using the colorsys functions are
different:
>>> convert_rgb_to_hls(123, 243, 61)
'HLS(99, 59, 88)' # should be HLS(100, 60, 88)
>>> convert_hls_to_rgb(100, 60, 88)
'RGB(122, 243, 63)' # should be RGB(123, 243, 61)
My first impression was that this is simply a rounding problem, but looking at
the difference between 61 and 63, there seems to be another reason. But what
is it? Is it possible at all to guarantee an absolute precise conversion
between color systems?
Answer:
from __future__ import division
import colorsys
def convert_rgb_to_hls(r, g, b):
h, l, s = colorsys.rgb_to_hls(r/255, g/255, b/255)
return "HLS(" + str(int(round(h * 360))) + ", " + str(int(round(l * 100))) + ", " + str(int(round(s * 100))) + ")"
def convert_hls_to_rgb(h, l, s):
r, g, b = colorsys.hls_to_rgb(h/360, l/100, s/100)
return "RGB(" + str(int(round(r * 255))) + ", " + str(int(round(g * 255))) + ", " + str(int(round(b * 255))) + ")"
**Changes** :
* 360 instead of 359 because the range is [0, 360) ([wikipedia](http://en.wikipedia.org/wiki/HSL_and_HSV#Hue_and_chroma)).
* There were two roundings missing on `convert_rgb_to_hls(r, g, b)`.
* Added python 3 division in case you use python 2.
**Tests** :
>>> convert_rgb_to_hls(123, 243, 61)
'HLS(100, 60, 88)'
>>> convert_hls_to_rgb(100, 60, 88)
'RGB(123, 243, 63)'
You were right when you said there were rounding-like errors but the
difference between 61 and 63 is because you lose precision when rounding. Do
not round for better precision:
>>> (r_orig, g_orig, b_orig) = (123, 243, 61)
>>> h,l,s = colorsys.rgb_to_hls(r_orig/255, g_orig/255, b_orig/255)
>>> r, g, b = colorsys.hls_to_rgb(h, l, s)
>>> r*255, g*255, b*255
(123.00000000000003, 242.99999999999997, 61.000000000000036)
|
Fastest way to filter json string in Python
Question: I have a json structure like
{
"a": "1",
"b": "2",
"c": {
"d": "3"
}
}
What I want is to only keep the 1st level of the json, i.e. remove if 1st
level's value is not a string, so I have a program like
import json
s = ''' {
"a": "1",
"b": "2",
"c": {
"d": "3"
} } '''
data = json.loads(s)
ret = {}
for k, v in data.items():
if (isinstance(v, basestring)):
ret[k] = v
print json.dumps(ret)
Since I need to process huge amount of json string like that, I am looking for
if any fastest way or more elegant way to do the same thing in Python
Answer: Use a dict comprehension:
ret = {k: v for k, v in json.loads(s).iteritems() if isinstance(v, basestring)}
The `dict.iteritems()` call here prevents a full list being built first.
If your JSON input is truly huge, consider switching to an iterative JSON
parser like [`ijson`](https://pypi.python.org/pypi/ijson/), and parse your
JSON with an event-driven interface:
import ijson
ret = {}
key = None
with open(some_large_jsonfile) as json_file:
for prefix, type, value in ijson.parse(json_file):
if prefix and not '.' in prefix and type == 'string':
# only top-level string values
ret[prefix] = value
but it could be a good idea to process the key-value pairs right there and
then rather than build up a full dictionary.
|
Function unwantedly alters variables
Question: I am wanting to use the baseTriangle and baseSquare variables in my for loops
in the rotateshape(), but when they are put in, the funnction seems to alter
them, meaning that they get bigger with every loop. not sure why it does this,
please help!!!
#! /usr/bin/env python
import Image, ImageDraw
import math
# functions
def rotateShape(shapeXCoordinates, shapeYCoordinates, baseXCoordinates, baseYCoordinates):
# Written by: some guy who had to do this once and thought it better to share rather than let other people suffer through the monotony
# This function below takes a shape and rotates, scales and translates it so that the first two coordinates are equal to the baseCoordinates
# Make sure that the distance between the first two shape coordinates is 1 and that they lie on the x-axis
# Find the dx, dy and the length of the baseCoordinates pair
#print 'Base coordinates: ' + str(zip(baseXCoordinates, baseYCoordinates))
dx = baseXCoordinates[1] - baseXCoordinates[0]
#print 'dx: ' + str(dx)
dy = baseYCoordinates[1] - baseYCoordinates[0]
#print 'dy: ' + str(dy)
magnitude = math.sqrt(dx**2+dy**2)
#print 'magnitude: ' + str(magnitude)
#print 'Start: ' + str(zip(shapeXCoordinates, shapeYCoordinates))
# Rotate the matrix
a = dx/magnitude
b = -dy/magnitude
c = dy/magnitude
d = dx/magnitude
for i in range(0,len(shapeXCoordinates)):
# Find the new x value
newX = a*shapeXCoordinates[i]+b*shapeYCoordinates[i]
# Find the new y value
newY = c*shapeXCoordinates[i]+d*shapeYCoordinates[i]
# Replace the old with the new
shapeXCoordinates[i] = newX
shapeYCoordinates[i] = newY
#print 'After rotate: ' + str(zip(shapeXCoordinates, shapeYCoordinates))
# Scale the matrix
for i in range(0,len(shapeXCoordinates)):
shapeXCoordinates[i] = shapeXCoordinates[i]*magnitude
shapeYCoordinates[i] = shapeYCoordinates[i]*magnitude
#print 'After scale: ' + str(zip(shapeXCoordinates, shapeYCoordinates))
# Translate the matrix
for i in range(0,len(shapeXCoordinates)):
shapeXCoordinates[i] = shapeXCoordinates[i]+baseXCoordinates[0]
shapeYCoordinates[i] = shapeYCoordinates[i]+baseYCoordinates[0]
#print 'After translate: ' + str(zip(shapeXCoordinates, shapeYCoordinates))
return (shapeXCoordinates, shapeYCoordinates)
# create a bitmap
img = Image.new('RGB', (3840, 2160))
draw = ImageDraw.Draw(img)
# setting up the varibales
# insert angle
angle = 30
angle_2 = 90 - angle
a = math.sin(angle_2) * 1
# working out the Y of the triangle
y = math.sin(angle) * a
# working out the X of Y
x = math.tan(angle)/y
baseTriangle_X = [0, 1, x]
baseTriangle_Y = [0, 0, y]
baseSquare_X = [0, 1, 1, 0]
baseSquare_Y = [0, 0, 1, 1]
startPosition_X = [1800, 2200] # flipped numbers as bitmap counts from the top left so that tree is created downwards
startPosition_Y = [0, 0]
# set number of iterations
numberOfIterations = 10
# set colour
redStart = 255
greenStart = 253
blueStart = 208
redEnd = 228
greenEnd = 82
blueEnd = 0
# colour change
redChange =(redEnd - redStart)/numberOfIterations
greenChange =(greenEnd - greenStart)/numberOfIterations
blueChange =(blueEnd - blueStart)/numberOfIterations
# set up the list of squares to make (fill with the start position)
squaresToMake_X = []
squaresToMake_Y = []
squaresToMake_X.extend(startPosition_X)
squaresToMake_Y.extend(startPosition_Y)
# set up the list of triangles
trianglesToMake_X = []
trianglesToMake_Y = []
# creating the tree
print '//////////////////////////////'
print '// // // // //'
print '//// //// ////// ////// //////'
print '//// //// ////// // //'
print '//// //// ////// ////// //////'
print '//// //// ////// // //'
print '//////////////////////////////'
# background colour
draw.rectangle((0,0,3839,2759), fill=(220, 255, 250))
for i in xrange(0, numberOfIterations):
redCurrent = redStart + redChange * i
greenCurrent = greenStart + greenChange * i
blueCurrent = blueStart + blueChange * i
# making squares
for j in xrange(0, len(squaresToMake_X)/2):
print 'Iteration ' + str(i) + ' of ' + str(numberOfIterations) + '. Square ' + str(j) + ' of ' + str(len(squaresToMake_X)/2)
k = j * 2
newVertices_X, newVertices_Y = rotateShape([0, 1, 1, 0], [0, 0, 1, 1], squaresToMake_X[k:k+2], squaresToMake_Y[k:k+2])
# merge x and y
combinedVertices = zip(newVertices_X, newVertices_Y)
# draw
#print 'Drawing square:'
#print combinedVertices
draw.polygon(combinedVertices, fill = (redCurrent, greenCurrent, blueCurrent))
trianglesToMake_X.extend([newVertices_X[3], newVertices_X[2]])
trianglesToMake_Y.extend([newVertices_Y[3], newVertices_Y[2]])
#print 'Triangles to make:'
#print zip(trianglesToMake_X, trianglesToMake_Y)
squaresToMake_X = []
squaresToMake_Y = []
# making triangles
for j in xrange(0, len(trianglesToMake_X)/2):
print 'Iteration ' + str(i) + ' of ' + str(numberOfIterations) + '. Triangle ' + str(j) + ' of ' + str(len(trianglesToMake_X)/2)
k = j * 2
newVertices_X, newVertices_Y = rotateShape([0, 1, 0.5], [0, 0, 0.5], trianglesToMake_X[k:k+2], trianglesToMake_Y[k:k+2])
# merge x and y
combinedVertices = zip(newVertices_X, newVertices_Y)
# draw
#print 'Drawing triangle:'
#print combinedVertices
draw.polygon(combinedVertices, fill = (redCurrent, greenCurrent, blueCurrent))
squaresToMake_X.extend([newVertices_X[0], newVertices_X[2], newVertices_X[2], newVertices_X[1]])
squaresToMake_Y.extend([newVertices_Y[0], newVertices_Y[2], newVertices_Y[2], newVertices_Y[1]])
#print 'Squares to make:'
#print zip(squaresToMake_X, squaresToMake_Y)
trianglesToMake_X = []
trianglesToMake_Y = []
print '----------'
img2=img.rotate(180)
img2.show()
Answer: `list` objects are mutable, so when you pass them into a function, a reference
to the original list is passed, rather than a copy. Therefore when you
_modify_ the list, such as with `shapeXCoordinates[i] = newX`, you're
modifying the _original_ list at the same time.
If you only want modifications to stay local to the function, without changing
the original, you need to make a copy of the list first:
shapeX = shapeXCoordinates[:]
Then reference `shapeX` everywhere in the function, rather than
`shapeXCoordinates`.
Obviously name the variables however makes sense to you.
|
Python Not Executing MySQLdb connect
Question: I am having some issues connecting to my hosted mysql database using python.
My code is as follows:
import MySQLdb
db = MySQLdb.connect(host="xxxxxx.db.1and1.com", user="xxxxxxx",passwd="xxxxxxx", db="xxxxxxx")
I get the following error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
db = MySQLdb.connect(host="db518597727.db.1and1.com", user="dbo518597727", passwd="OilyOily123", db="db518597727")
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 193, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'xxxxxxx.db.1and1.com' (10060)")
My sql database is hosted by 1and1. I am sure I have the right credentials, as
when I read from this database on a php website, using the same credentials (I
have triple checked) it works fine.
I have tried this both on a Raspberry Pi (where I intend to use it) and on my
Windows 8.1 PC, so I am pretty sure that it is not the computer that is the
problem.
Any help would be much appreciated.
Many thanks.
Answer: In `MySQL` credentials are per client, so we distinguish a couple of client
types:
\- `localhost` means the same machine as MySQL server connecting via Unix
Socket
\- `127.0.0.1` means the same machine as MySQL server connecting via TCP/IP
\- `A.B.C.D` where letters are replaced by numbers in range 0-255 which means
IP address of client machine connecting via TCP/IP
\- `*` is a wildcard which means that any client can connect with given
credentials via TCP/IP
Every entry in `MySQL` users table consists of client specification (described
above), username, password and some other columns (not relevant here).
So the problem you are facing is that PHP script on 1and1 server can connect
to the database hosted on 1and1 since the hosting company sets up their
database server to accept connections from their own servers with valid
credentials.
But the same credentials are considered invalid for connections coming from
client machines unknown to 1and1.
What you can do is to ask 1and1 to give your specific IP access rights to your
database.
What you can't to is to overcome this problem on your own.
|
Python - import external file via command line
Question: I am aware that this is in principle a question that has been asked a lot
already. But I have a more specific question within this general thing of
importing external files.
So, I have a few external files that each contain a database - different
grammars for parsing text - that is required for my main script to run. I want
to pass the external databse-scripts through as a command line argument. A
single one per call of the main script. So I wrote the following sequence at
the top of my main script:
extGrammar = sys.argv[-1]
import extGrammar
So my reasoning was to give the variable extGrammar the name of the command
line argument that corresponds to whatever name the database file in question
has, and then import that file. Just as if I had written
import grammar1
if I had an external file grammar1.py
But I get the error “ImportError: No module named extGrammar”
which I don't understand. Where is the flaw in my reasoning and what is a
correct way of doing this?
Thanks
Answer: You need to call the builtin _function_ ,
[`__import__`](https://docs.python.org/2/library/functions.html#__import__),
not the `import` statement, as the Python language parses the latter as a
direct import (the variable name is therefore treated as a module, with
obvious result). To import a module that is referred by name via a variable,
you need the function, not the statement.
|
Matrix input from a text file(python 3)
Question: Im trying to find a way to be able to input a matrix from a text file;
for example, a text file would contain
1 2 3
4 5 6
7 8 9
And it would make a matrix with those numbers and put it in matrix =
[[1,2,3],[4,5,6],[7,8,9]]
And then this has to be compatible with the way I print the matrix:
print('\n'.join([' '.join(map(str, row)) for row in matrix]))
So far,I tried this
chemin = input('entrez le chemin du fichier')
path = input('enter file location')
f = open ( path , 'r')
matrix = [ map(int,line.split(','))) for line in f if line.strip() != "" ]
All it does is return me a map object and return an error when I try to print
the matrix.
What am I doing wrong? Matrix should contain the matrix read from the text
file and not map object,and **I dont want to use external library such as
numpy**
Thanks
Answer: As explained in
[numpy.genfromtxt()](http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html):
import StringIO, numpy
data = "1 2 3\n4 5 6\n7 8 9"
numpy.genfromtxt(StringIO.StringIO(data), delimiter = ' ')
> array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
Take two:
[list(map(int, line.split(' '))) for line in data.split('\n')]
> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
Implement cache inPython
Question: I want to implement a basic cache in Python.
It's like this. I've 2 files named :- `cache.py` , `main.py`.
In my cache.py, I want to build a list every 24 hours. So, i run a cronjob
`cache.py` every 24 hours which returns me the latest list.
**cache.py**
def get_hubcode_threshold_time():
global threshold_time
hub_alarm_obj = HubAlarm.objects.all().values('time').distinct()
for obj in hub_alarm_obj:
threshold_time.append(obj.time)
if __name__ == "__main__":
get_hubcode_threshold_time()
print threshold_time
I run `main.py` every minute (another cronjob). I want to print threshold_time
from the cache.
**main.py**
import cache
print threshold_time
throws an error saying
NameError: global name 'threshold_time' is not defined
How do I implement a basic cache in Python:?
Answer: If you want multiple processes to be able to access the same data (e.g., the
value of `threshold_time`), then you need some sort of persistent storage or a
protocol for getting and setting the data. To be more specific, in your
`cache.py` file, you need to save the value of `threshold_time` somewhere once
you've computed it. Then your `main.py` can retrieve that value from wherever
it's been saved.
Just from what you listed, this seems like a particularly good use case for
redis, but sqlite or even a text file would also work. Each persistence
strategy comes with its own levels of data integrity and complexity.
|
simple dictionary manipulation in python
Question:
groups = ['A','B','C']
ranges = [1,2,3,4,5,6,7,8,9]
my_dict = {}
for g in groups:
my_dict[g] = ???
The result (my_dict) should be as follows:
{'A': array([1, 2, 3], dtype=int64), 'B': array([4,5,6], dtype=int64)), 'C': array([7,8,9], dtype=int64)}
Answer: First I would turn your `ranges` in to properly sized chunks:
>>> ranges = zip(*[iter(ranges)]*len(groups))
>>> print(ranges)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
This will create chunks of `len(groups)` items which you can then feed to
`zip()` in the second part.
Then create the dictionary, using a dictionary comprehension and `zip()`.
>>> from numpy import array
>>> my_dict = {g: array(r) for g, r in zip(groups, ranges)}
>>> print(my_dict)
{'A': array([1, 2, 3]), 'C': array([7, 8, 9]), 'B': array([4, 5, 6])}
|
Generate Django behave code
Question: I am using behave for acceptance testing of my Django app. Is there any
possibility to generate the python code needed for the actual tests? What I
have so far is the skeleton as follows:
@given('I am logged in')
def step_impl(context):
assert False
@given('I am on the contact list')
def step_impl(context):
assert False
...
Answer: There are examples given on the [Django Testing Example
page](http://pythonhosted.org/behave/django.html), which will give you
something like this as a starting point:
from behave import given, when, then
@given('a user')
def step_impl(context):
from django.contrib.auth.models import User
u = User(username='foo', email='[email protected]')
u.set_password('bar')
@when('I log in')
def step_impl(context):
br = context.browser
br.open(context.browser_url('/account/login/'))
br.select_form(nr=0)
br.form['username'] = 'foo'
br.form['password'] = 'bar'
br.submit()
@then('I see my account summary')
def step_impl(context):
br = context.browser
response = br.response()
assert response.code == 200
assert br.geturl().endswith('/account/')
@then('I see a warm and welcoming message')
def step_impl(context):
# Remember, context.parse_soup() parses the current response in
# the mechanize browser.
soup = context.parse_soup()
msg = str(soup.findAll('h2', attrs={'class': 'welcome'})[0])
assert "Welcome, foo!" in msg
Can Behave _automatically_ generate the code needed for testing your app? No,
not without writing your own logic to do so.
The first step in your testing of the Django app should be to start with
writing [Feature Files](http://pythonhosted.org/behave/tutorial.html#feature-
files). Once your feature files are complete, you may run `behave -d` which
will give you the stubs/skeleton code for copying into your [step
files](http://pythonhosted.org/behave/tutorial.html#python-step-
implementations). At this point, you can write scripts to interact with your
Django app.
|
How to prevent python requests from percent encoding my URLs?
Question: I'm trying to GET an URL of the following format using requests.get() in
python:
[http://api.example.com/export/?format=json&key=site:dummy+type:example+group:wheel](http://api.example.com/export/?format=json&key=site%3adummy+type%3aexample+group%3awheel)
#!/usr/local/bin/python
import requests
print(requests.__versiom__)
url = 'http://api.example.com/export/'
payload = {'format': 'json', 'key': 'site:dummy+type:example+group:wheel'}
r = requests.get(url, params=payload)
print(r.url)
However, the URL gets percent encoded and I don't get the expected response.
2.2.1
http://api.example.com/export/?key=site%3Adummy%2Btype%3Aexample%2Bgroup%3Awheel&format=json
This works if I pass the URL directly:
url = http://api.example.com/export/?format=json&key=site:dummy+type:example+group:wheel
r = requests.get(url)
Is there some way to pass the the parameters in their original form - without
percent encoding?
Thanks!
Answer: It is not good solution but you can use `string`:
r = requests.get(url, params='format=json&key=site:dummy+type:example+group:wheel')
* * *
BTW:
payload = {'format': 'json', 'key': 'site:dummy+type:example+group:wheel'}
payload_str = "&".join("%s=%s" % (k,v) for k,v in payload.items())
# 'format=json&key=site:dummy+type:example+group:wheel'
r = requests.get(url, params=payload_str)
|
Added subprocess, error that variable is not defined
Question: My script gets arguments such as
C:\> python lookup.py "sender-ip=10.10.10.10"
And would take sender-ip and find wmi information
Now I added a ping subprocess to pint the machine BEFORE attempting to get wmi
information and I get following error
C:\> python lookup.py "sender-ip=10.10.10.10"
Traceback (most recent call last):
File "lookup.py", line 10, in <module>
["ping", "-n", "1", userIP],
NameError: name 'userIP' is not defined
Then I tried to define userIP global variable at the beginning of the
beginning of the program, but I get error
C:\> python lookup.py "sender-ip=10.10.10.10"
Traceback (most recent call last):
File "lookup.py", line 10, in <module>
["ping", "-n", "1", userIP],
NameError: global name 'userIP' is not defined
Here is the program(without global declaration)
# import statements
import sys, wmi, subprocess
# subprocess
ping = subprocess.Popen(
["ping", "-n", "1", userIP],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
# get the arguments and extract user's IP address
argument = sys.argv[1]
attr_map = dict(item.strip().split('=') for item in argument.split(','))
userIP = attr_map['sender-ip']
print userIP
# can we ping the user's IP address?
out, error = ping.communicate()
# if we cannot ping user's IP address then print error message and exit program
if out.find("Reply from") == -1:
print userIP, "is NOT pingable."
sys.exit()
# remaining lines will execute if we can ping user's IP address
c = wmi.WMI(userIP)
for os in c.Win32_OperatingSystem():
print os.Caption
Answer: You don't need global variable here. Just assign value to userIP before using
it:
# import statements
import sys, wmi, subprocess
# get the arguments and extract user's IP address
argument = sys.argv[1]
attr_map = dict(item.strip().split('=') for item in argument.split(','))
userIP = attr_map['sender-ip']
print userIP
# subprocess
ping = subprocess.Popen(
["ping", "-n", "1", userIP],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
# can we ping the user's IP address?
out, error = ping.communicate()
# if we cannot ping user's IP address then print error message and exit program
if out.find("Reply from") == -1:
print userIP, "is NOT pingable."
sys.exit()
# remaining lines will execute if we can ping user's IP address
c = wmi.WMI(userIP)
for os in c.Win32_OperatingSystem():
print os.Caption
|
python line profiler view result
Question: I have ran `kernprof` on a file called `RP.py` and it spits out `RP.py.lprof`
Now, i'm trying to view this file. If i open a `cmd` window and type `python
-m line_profiler RP.py.lprof` it gives me the text, but it not formatted in a
way that I can read it.
Is there a way to 1) turn `lprof` into text?
or run it in a shell. I have tried:
import sys
import subprocess
subprocess.call([sys.executable,'C:\\Python27\\python.exe', '-m', 'line_profiler', 'RP.py.lprof'])
[execfile with argument in python
shell](http://stackoverflow.com/questions/5788891/execfile-with-argument-in-
python-shell) from this link. But this doesn't work.
Answer: I don't have ready access to a Windows box, but my first guess based on the
description is that the line-endings are `\n` instead of `\r\n`. Try piping
the results to a text file and then open it in a programmer's editor (_not_
Notepad).
`python -m line_profiler RP.py.lprof > results.txt`
|
matplotlib pgf savefig(pdf) fails
Question: On a modern texlive installation on fedora 20, using pgf backend fails in
savefig ('blah.pdf').
Example:
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
pgf_with_rc_fonts = {
"font.family": "serif",
"font.serif": [], # use latex default serif font
"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font
}
mpl.rcParams.update(pgf_with_rc_fonts)
import matplotlib.pyplot as plt
plt.figure(figsize=(4.5,2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.text(2.5, 1., "comic sans", family="Comic Sans MS")
plt.xlabel(u"µ is not $\\mu$")
plt.tight_layout(.5)
trace back:
Traceback (most recent call last):
File "testpgf.py", line 20, in <module>
plt.tight_layout(.5)
File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 1255, in tight_layout
fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 1600, in tight_layout
renderer = get_renderer(self)
File "/usr/lib64/python2.7/site-packages/matplotlib/tight_layout.py", line 222, in get_renderer
renderer = canvas.get_renderer()
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_pgf.py", line 925, in get_renderer
return RendererPgf(self.figure, None, dummy=True)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_pgf.py", line 409, in __init__
self.latexManager = LatexManagerFactory.get_latex_manager()
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_pgf.py", line 223, in get_latex_manager
new_inst = LatexManager()
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_pgf.py", line 305, in __init__
cwd=self.tmpdir)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Answer: OK, problem is that according to <http://matplotlib.org/1.3.1/users/pgf.html>
the default tex processor is xelatex, which was not installed. Either 1) sudo
yum install texlive-xetex-bin or 2) set pgf to use some other latex processor:
pgf_with_pdflatex = {
"pgf.texsystem": "lualatex",
"pgf.preamble": [
r'\usepackage{amsmath}',
r'\usepackage[scientific-notation=true]{siunitx}',
## r"\usepackage[utf8x]{inputenc}",
## r"\usepackage[T1]{fontenc}",
]
}
mpl.rcParams.update(pgf_with_pdflatex)
|
f2py loses double precision when passing to python
Question: I can't seem to get my module created with f2py to keep a number at double
precision when it is passed back to python. A minimal example, with file
fmodules.f90:
subroutine example(output)
implicit none
double precision :: output
cf2py intent(out) :: output
output = 1.3
end subroutine example
I then create the module with f2py:
$ f2py -c -m fmodules fmodules.f90
and call it from python:
>>> from fmodules import example
>>> example()
1.2999999523162842
By my count, that's about 8 digits of precision. My impression was that double
precision should give about 16. I've tried all the permutations of this I can
think of, including playing with the `.f2py_f2cmap` file. Any ideas on what I
am missing?
Answer: You should set output in the Fortran code using double precision,
output = 1.3d0
In Fortran 1.3 is a single precision constant.
|
Print float (x,y) data in a graph with Python
Question: I need to print data saved in a file in this format:
0.1545,0.68954
0.1548,0.87854
0.2545,0.54854
0.7956,0.41548
(All values between 0.0 and 1.0) And also the possibility of printing more
than one graph in the same figure differentiating them (ie: color, or line
style)
I was told to use python to this because of its easiness but all doc I have
read and examples like [this
one](http://stackoverflow.com/questions/11248812/matplotlib-basic-plotting-
from-text-file) are not working for me.
I would really appreciate if somebody could help is for my thesis. I just need
python for graph printing, no time to learn in depth.
Answer: To load the data:
# open the file so you can read from it
with open("myfile.txt") as inf:
# for each line in the file,
# split it on commas (results in a list of strings)
# then convert each string to a float (results in a list of floats)
items = (map(float, line.split(",")) for line in inf)
# transpose (convert columns to rows),
# then assign each row to a variable)
xs, ys = zip(*items)
To plot it:
import matplotlib.pyplot as plt
plt.scatter(xs, ys)
plt.show()
|
Multiprocessing with python to find Max value
Question: I'm working with Python 2.7.5 and OpenCV. I have a test image and I want to
find it's most similar image in an array of images. I have written a function
using OpenCV that will give me the total number of similarity points. The more
similar points I have the more similar the images are. Unfortunately this is a
rather time consuming function so I would like to parallelize my code to make
it faster.
#img is the image that I am trying to find the most number of similar pointswith
maxSimilarPts = 0;
#testImages is a list of testImages
for testImage in testImages:
#getNumSimilarPts returns the number of similar points between two images
similarPts = getNumSimilarPts(img, testImage)
if similarPts > maxSimilarPts:
maxSimilarPts = similarPts
How can I do this in parallel with python? Any help would be greatly
appreciated.
Answer: The following is a (untested) parallel version of the original code. It runs 5
workers in parallel. Each one takes an image from the input queue, calculates
the similary, then puts the value and image onto an output queue. When all the
workers are done, there are no more images, then the parent process prints the
(similarity, imageID) of the most similar image.
# adapted from Raymond Hettinger
# http://stackoverflow.com/questions/11920490/how-do-i-run-os-walk-in-parallel-in-python/23779787#23779787
from multiprocessing.pool import Pool
from multiprocessing import JoinableQueue as Queue
import os, sys
def parallel_worker():
while True:
testImage = imageq.get()
similarPts = getNumSimilarPts(img, testImage)
similarq.put( [similarPts, testImage] )
imageq.task_done()
similarq = Queue()
imageq = Queue()
for testImage in testImages:
imageq.put(testImage)
pool = Pool(5)
for i in range(5):
pool.apply_async(parallel_worker)
imageq.join()
print 'Done'
print max(similarq)
|
django no module named wiki
Question: Okay, so I am following along with a tutorial about how to make a wiki with
django for practice. I'm using Python 2.7 with Django 1.6.4. I am trying to
run the server so I can refresh a page but I am all of a sudden getting the
error `"ImportError: No module named wiki."`
I've searched through all the answers on here and what's strange is that I
have a subdirectory in my project called Wiki that has an **__init__.py** file
inside it. Here is what my directory looks like:
wikicamp (project)
wiki
__init__.py
admin.py
models.py
tests.py
views.py
wikicamp
__init__.py
settings.py
urls.py
wsgi.py
dbsqlite3
manage.py
My **settings.py** file `INSTALLED_APPS` looks like this:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'wiki',
)
I have tried it both as `'wikicamp.wiki`', and as `'wiki'`, and I get the same
thing with both. It won't even let me start the development server, I get that
error when I type `python manage.py runserver`. I have made sure I am in the
correct directory.
Here is all the info I get from that:
PS C:\python27\Lib\site-packages\django\bin\wikicamp> python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line
utility.execute()
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "c:\Python27\lib\site-packages\django\core\management\base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "c:\Python27\lib\site-packages\django\core\management\base.py", line 280, in execute
translation.activate('en-us')
File "c:\Python27\lib\site-packages\django\utils\translation\__init__.py", line 130, in activate
return _trans.activate(language)
File "c:\Python27\lib\site-packages\django\utils\translation\trans_real.py", line 188, in activate
_active.value = translation(language)
File "c:\Python27\lib\site-packages\django\utils\translation\trans_real.py", line 177, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "c:\Python27\lib\site-packages\django\utils\translation\trans_real.py", line 159, in _fetch
app = import_module(appname)
File "c:\Python27\lib\site-packages\django\utils\importlib.py", line 40, in import_module
__import__(name)
ImportError: No module named wiki
Answer: I am following the same tutorials which you were learning from. You just need
to go to your wikicamp/url.py file and edit the `patterns` dict as:
r'^wikicamp/(?P<page_name>[^/]+)/edit/$', 'wiki.views.edit_page'
instead of:
r'^wikicamp/(?P<page_name>[^/]+)/edit/$', 'wikicamp.wiki.views.edit_page'
|
subscribing to a tag with python-instagram API in python failing
Question: I'm trying to subscribe to a hashtag using the python-instagram wrapper for
python. I have previously used cURL to perform the authentication handshake
and it worked fine. However, I would like to use all the wrapper
functionality.
from instagram import client, subscriptions
from flask import Flask, request, render_template, session, redirect, abort, flash, jsonify
app = Flask(__name__)
api = client.InstagramAPI(client_id="", client_secret="")
callback_url = 'http://localhost.com:515'
api.create_subscription(object='tag',object_id='bacon', aspect='media', callback_url=callback_url)
@app.route('/', methods=['GET'])
def handshake():
code = request.args.get('hub.challenge')
if code:
return code
if __name__ == '__main__':
app.debug = True
app.run(host='localhost.com',port=515)
The error I get is: Traceback (most recent call last):
File "test.py", line 10, in <module>
api.create_subscription(object='tag',object_id='bacon', aspect='media', callback_url=callback_url)
File "/usr/local/lib/python2.7/dist-packages/instagram/bind.py", line 152, in _call
return method.execute()
File "/usr/local/lib/python2.7/dist-packages/instagram/bind.py", line 144, in execute
content, next = self._do_api_request(url, method, body, headers)
File "/usr/local/lib/python2.7/dist-packages/instagram/bind.py", line 100, in _do_api_request
raise InstagramClientError('Unable to parse response, not valid JSON.')
instagram.bind.InstagramClientError: Unable to parse response, not valid JSON.
When I remove the create_subscription line it seems to be fine, but the
create_subscription method does something strange and I can't figure out what.
The end goal is to subscribe to the tag and receive new pictures posted with
the tag.
Answer: This can be due to various issues:
1. Make sure your callback_url is up and available for remote hosts
2. Debug your handshake() and make sure you return the value (put prints)
3. Debug your /usr/local/lib/python2.7/dist-packages/instagram/bind.py and see the response with error message, this can be the answer))
4. Make your handshake() to accept POST from instagram
5. probably you should use authenticated api in this case
|
Error with concatenating list to string in Python
Question: I am trying to pass class element to method. Element is formed dynamically
inserting current time in it. Mine class looks something like this:
class MineContact(dict):
def __init__(self, **kwargs):
# set your default values
import time
curr_time = repr(time.time()).replace('.', '')
self['givenName'] = ['name%s' % curr_time[10:]]
...
So, I create object of this class and now I want to insert it as method
argument:
contact = MineContact()
extra_text = "-%d" % (self.iteration)
new_contact.insert_given_name(contact.givenName + extra_text)
When I run this script, I get this type of error:
> TypeError: can only concatenate list (not "str") to list
So, does anyone knows where am I getting it wrong?
Answer: `givenName` seems to be a list. You can append another list like this:
new_contact.insert_given_name(contact.givenName + [extra_text])
|
How to implement multiple signals in a program?
Question: I am starting to learn Python (newbie), so not much idea about the different
modules etc.
Scenario that I want to simulate:
I have a program `prg1.py` that I want to run for some user defined time say
`t` seconds. After this time (`t` seconds), the program should exit. For this
I am using `signal.signal()` to create alarm. Below is the working code:
import signal
import time
import sys
def receive_alarm(signum, stack):
sys.exit('Exiting!')
signal.signal(signal.SIGALRM, receive_alarm)
signal.alarm(10)
while 1:
print 'Working...'
time.sleep(1)
The program runs for 10 seconds and then exits as expected.
Note: The while loop below is just for testing, it would be replaced by my
working code.
Now I want to implement multiple signals to do different tasks at different
intervals of time.
e.g. In `EVERY`:
`5` seconds: execute a specific function `fun1()`
`10` seconds: execute a specific function `fun2()`, and so on... (tasks I want
to perform in the program)
I tried adding another alarm as shown below, but didn't work:
import signal
import time
import sys
def receive_alarm(signum, stack):
sys.exit('Exiting!')
def receive_alarm_two(signup, stack):
print 'Call to other functions!'
signal.signal(signal.SIGALRM, receive_alarm)
signal.alarm(10)
# Second Alarm
signal.signal(signal.SIGALRM, receive_alarm_two)
signal.alarm(2)
while 1:
print 'Working...'
time.sleep(1)
This doesn't work! Simple exits without any error or exit message :(
How can this functionality be implemented?
NOTE: `Use of Threads is restricted.`
NOTE: `As I want the program to keep listening to different signals, it can't
sleep i.e. cannot use time.sleep().`
Answer: You should see if your requirements can be met by the `sched` module; also,
why is multithreading not allowed?
It's possible to schedule multiple tasks with a single alarm by having the
alarm occur at time intervals of the greatest common divisor of the period of
your scheduled events. An example is below, but it's not very robust, e.g., if
any task takes very long, the timing will be inaccurate. This is fixable (keep
track of time with `time.time()`, and schedule the next alarm accordingly),
though other problems remain (what happens if one task runs so long that the
next task starts late?). My perception is that schedulers are a problem with
many tricky corner cases, and that if possible you should use an existing
solution, rather than writing your own.
import signal
import time
class Scheduler(object):
"""Trivial scheduler object.
Rather use sched.scheduler"""
def __init__(self):
self._tasks= [(1,self._heartbeat)]
self._tick= 0
self.stopped=False
def addtask(self,period,task):
"""Add a task to be executed every PERIOD seconds
addtask(period,task)
period: seconds
task: callable taking 'tick' argument
"""
self._tasks.append( (period,task) )
def _heartbeat(self,tick):
print 'heartbeat: %d' % tick
def _execute(self,signum,stack):
if self.stopped:
return
self._tick += 1
for period, task in self._tasks:
if 0==self._tick % period:
task(self._tick)
signal.alarm(1)
def start(self):
signal.signal(signal.SIGALRM, self._execute)
signal.alarm(1)
def stop(self):
self.stopped=True
class Stopper(object):
"""Callable to stop a scheduler"""
def __init__(self, scheduler):
self._scheduler=scheduler
def __call__(self,tick):
print 'stopping at tick',tick
self._scheduler.stop()
def task3s(tick):
print '3s task at tick',tick
def task7s(tick):
print '7s task at tick',tick
s= Scheduler()
s.addtask(10,Stopper(s))
s.start()
s.addtask(3,task3s)
s.addtask(7,task7s)
while not s.stopped:
time.sleep(0.5)
print 'mainloop...'
On my (python2) system this gives:
mainloop...
heartbeat: 1
mainloop...
mainloop...
heartbeat: 2
mainloop...
mainloop...
heartbeat: 3
3s task at tick 3
mainloop...
mainloop...
heartbeat: 4
mainloop...
mainloop...
heartbeat: 5
mainloop...
mainloop...
heartbeat: 6
3s task at tick 6
mainloop...
mainloop...
heartbeat: 7
7s task at tick 7
mainloop...
mainloop...
heartbeat: 8
mainloop...
mainloop...
heartbeat: 9
3s task at tick 9
mainloop...
mainloop...
heartbeat: 10
stopping at tick 10
mainloop...
|
Run py file with different arguments each time in pyCharm
Question: I have some script : **run.py** , I was using it in terminal like :
python run.py -t 10 -s adidas -f mozilla
python run.py -t 2 -s nike -f chrome
python run.py -t 100 -s puma -f safari
python run.py -t 1 -s tom
but how to live in pyCharm? I need each time to configure Run/Debug
configuration ? Thanx
Answer: easiest is to make a runner file
**testrunner.py** (same folder as run.py)
import .run
args= [ "-t 10 -s adidas -f mozilla","-t 2 -s nike -f chrome","-t 100 -s puma -f safari"]
for arg in args:
sys.argv[1:] = arg.split()
reload(run)
run.main()
or you can use `os.system` to call it with the arguments, but you lose alot of
the debugging features of pycharm doing that ...
or alternatively you could make 1 run config for each set of paramaters and
save the run config(this is probably how pycharm expects you to do it)
|
Can't install mongoengine inside virtualenv
Question: When I try to install mongoengine in virtualenv, I've got problem:
Requirement already satisfied (use --upgrade to upgrade): flask-mongoengine in ./lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): Flask>=0.8 in ./lib/python2.7/site-packages (from flask-mongoengine)
Downloading/unpacking mongoengine>=0.7.10 (from flask-mongoengine)
Running setup.py (path:/var/www/msgapp/backend/build/mongoengine/setup.py) egg_info for package mongoengine
0.8.7
no previously-included directories found matching 'docs/_build'
Downloading/unpacking flask-wtf (from flask-mongoengine)
Running setup.py (path:/var/www/msgapp/backend/build/flask-wtf/setup.py) egg_info for package flask-wtf
warning: no previously-included files matching '*.pyc' found under directory 'tests'
warning: no previously-included files matching '*.pyc' found under directory 'tests'
warning: no previously-included files matching '*.pyc' found under directory 'docs'
warning: no previously-included files matching '*.pyo' found under directory 'docs'
no previously-included directories found matching 'docs/_build'
no previously-included directories found matching 'docs/_themes/.git'
Requirement already satisfied (use --upgrade to upgrade): Werkzeug>=0.7 in ./lib/python2.7/site-packages (from Flask>=0.8->flask-mongoengine)
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.4 in ./lib/python2.7/site-packages (from Flask>=0.8->flask-mongoengine)
Requirement already satisfied (use --upgrade to upgrade): itsdangerous>=0.21 in ./lib/python2.7/site-packages (from Flask>=0.8->flask-mongoengine)
Requirement already satisfied (use --upgrade to upgrade): pymongo>=2.5 in ./lib/python2.7/site-packages (from mongoengine>=0.7.10->flask-mongoengine)
Requirement already satisfied (use --upgrade to upgrade): WTForms>=1.0.5,<2.0 in ./lib/python2.7/site-packages (from flask-wtf->flask-mongoengine)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in ./lib/python2.7/site-packages (from Jinja2>=2.4->Flask>=0.8->flask-mongoengine)
Installing collected packages: mongoengine, flask-wtf
Running setup.py install for mongoengine
0.8.7
no previously-included directories found matching 'docs/_build'
error: could not delete '/var/www/msgapp/backend/lib/python2.7/site-packages/bson/json_util.py': Permission denied
Complete output from command /var/www/msgapp/backend/bin/python2.7 -c "import setuptools, tokenize;__file__='/var/www/msgapp/backend/build/mongoengine/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-811vit-record/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/msgapp/backend/include/site/python2.7:
0.8.7
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/common.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/document.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/context_managers.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/__init__.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/connection.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/errors.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/dereference.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/python_support.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/signals.py -> build/lib.linux-x86_64-2.7/mongoengine
copying mongoengine/fields.py -> build/lib.linux-x86_64-2.7/mongoengine
creating build/lib.linux-x86_64-2.7/bson
copying bson/json_util.py -> build/lib.linux-x86_64-2.7/bson
copying bson/objectid.py -> build/lib.linux-x86_64-2.7/bson
copying bson/py3compat.py -> build/lib.linux-x86_64-2.7/bson
copying bson/tz_util.py -> build/lib.linux-x86_64-2.7/bson
copying bson/max_key.py -> build/lib.linux-x86_64-2.7/bson
copying bson/binary.py -> build/lib.linux-x86_64-2.7/bson
copying bson/__init__.py -> build/lib.linux-x86_64-2.7/bson
copying bson/code.py -> build/lib.linux-x86_64-2.7/bson
copying bson/son.py -> build/lib.linux-x86_64-2.7/bson
copying bson/errors.py -> build/lib.linux-x86_64-2.7/bson
copying bson/timestamp.py -> build/lib.linux-x86_64-2.7/bson
copying bson/regex.py -> build/lib.linux-x86_64-2.7/bson
copying bson/dbref.py -> build/lib.linux-x86_64-2.7/bson
copying bson/min_key.py -> build/lib.linux-x86_64-2.7/bson
creating build/lib.linux-x86_64-2.7/mongoengine/base
copying mongoengine/base/metaclasses.py -> build/lib.linux-x86_64-2.7/mongoengine/base
copying mongoengine/base/common.py -> build/lib.linux-x86_64-2.7/mongoengine/base
copying mongoengine/base/document.py -> build/lib.linux-x86_64-2.7/mongoengine/base
copying mongoengine/base/__init__.py -> build/lib.linux-x86_64-2.7/mongoengine/base
copying mongoengine/base/datastructures.py -> build/lib.linux-x86_64-2.7/mongoengine/base
copying mongoengine/base/fields.py -> build/lib.linux-x86_64-2.7/mongoengine/base
creating build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/shortcuts.py -> build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/sessions.py -> build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/tests.py -> build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/storage.py -> build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/__init__.py -> build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/auth.py -> build/lib.linux-x86_64-2.7/mongoengine/django
copying mongoengine/django/utils.py -> build/lib.linux-x86_64-2.7/mongoengine/django
creating build/lib.linux-x86_64-2.7/mongoengine/queryset
copying mongoengine/queryset/queryset.py -> build/lib.linux-x86_64-2.7/mongoengine/queryset
copying mongoengine/queryset/base.py -> build/lib.linux-x86_64-2.7/mongoengine/queryset
copying mongoengine/queryset/visitor.py -> build/lib.linux-x86_64-2.7/mongoengine/querset
copying mongoengine/queryset/__init__.py -> build/lib.linux-x86_64-2.7/mongoengine/queryset
copying mongoengine/queryset/field_list.py -> build/lib.linux-x86_64-2.7/mongoengine/queryset
copying mongoengine/queryset/transform.py -> build/lib.linux-x86_64-2.7/mongoengine/queryset
copying mongoengine/queryset/manager.py -> build/lib.linux-x86_64-2.7/mongoengine/queryset
creating build/lib.linux-x86_64-2.7/mongoengine/django/mongo_auth
copying mongoengine/django/mongo_auth/__init__.py -> build/lib.linux-x86_64-2.7/mongoengine/django/mongo_auth
copying mongoengine/django/mongo_auth/models.py -> build/lib.linux-x86_64-2.7/mongoengine/django/mongo_auth
running egg_info
writing requirements to mongoengine.egg-info/requires.txt
writing mongoengine.egg-info/PKG-INFO
writing top-level names to mongoengine.egg-info/top_level.txt
writing dependency_links to mongoengine.egg-info/dependency_links.txt
warning: manifest_maker: standard file '-c' not found
reading manifest file 'mongoengine.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
no previously-included directories found matching 'docs/_build'
writing manifest file 'mongoengine.egg-info/SOURCES.txt'
running install_lib
copying build/lib.linux-x86_64-2.7/mongoengine/base/metaclasses.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/base
copying build/lib.linux-x86_64-2.7/mongoengine/base/common.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/base
copying build/lib.linux-x86_64-2.7/mongoengine/base/document.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/base
copying build/lib.linux-x86_64-2.7/mongoengine/base/__init__.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/base
copying build/lib.linux-x86_64-2.7/mongoengine/base/datastructures.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/base
copying build/lib.linux-x86_64-2.7/mongoengine/base/fields.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/base
copying build/lib.linux-x86_64-2.7/mongoengine/django/mongo_auth/__init__.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django/mongo_auth
copying build/lib.linux-x86_64-2.7/mongoengine/django/mongo_auth/models.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django/mongo_auth
copying build/lib.linux-x86_64-2.7/mongoengine/django/shortcuts.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/django/sessions.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/django/tests.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/django/storage.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/django/__init__.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/django/auth.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/django/utils.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/django
copying build/lib.linux-x86_64-2.7/mongoengine/common.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/document.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/queryset.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/base.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/visitor.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/__init__.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/field_list.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/transform.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/queryset/manager.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine/queryset
copying build/lib.linux-x86_64-2.7/mongoengine/context_managers.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/__init__.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/connection.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/errors.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/dereference.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/python_support.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/signals.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/mongoengine/fields.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/mongoengine
copying build/lib.linux-x86_64-2.7/bson/json_util.py -> /var/www/msgapp/backend/lib/python2.7/site-packages/bson
error: could not delete '/var/www/msgapp/backend/lib/python2.7/site-packages/bson/json_util.py': Permission denied
----------------------------------------
Cleaning up...
Command /var/www/msgapp/backend/bin/python2.7 -c "import setuptools, tokenize;__file__='/var/www/msgapp/backend/build/mongoengine/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-811vit-record/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/msgapp/backend/include/site/python2.7 failed with error code 1 in /var/www/msgapp/backend/build/mongoengine
Storing debug log for failure in /home/www/.pip/pip.log
Would be nice to find out how to install it inside virtualenv.
Answer: The error message says that installer tries to delete file
**/var/www/msgapp/backend/lib/python2.7/site-packages/bson/json_util.py** but
it fails because you don't have permissions.
There are two possible reasons:
1. You are trying to install mongoengine as a different user from the one who own the virtualenv.
Let's assume that you are logged in as user `holms` so your bash prompt looks
like: _[holms@localhost ~]$_
Now check ownership of virtualenv with:
`ls -la /var/www/msgapp/ | grep backend`
If the output should look like:
_drwxr-xr-x. 9 holms holms 4096 05-06 15:49 backend_
If instead of _holms_ you get for example _bruce_ then virtualenv is owned by
this user and you should perform installation as _bruce_ :
`sudo su - bruce`
`source /var/www/msgapp/backend/bin/activate`
`pip install mongoengine`
2. You are logged in as the correct user but **/var/www/msgapp/backend/lib/python2.7/site-packages/bson/json_util.py** is owned by someone else. Again I'm assuming that your username is _holms_.
Check permissions:
`ls -la /var/www/msgapp/backend/lib/python2.7/site-packages/bson/ | grep json_util.py`
If you see that someone else e.g. _bruce_ owns this specific file then change
the ownerschip:
`sudo chown holms:holms /var/www/msgapp/backend/lib/python2.7/site-
packages/bson/`
Now you should be able to install mongoengine.
|
Classify type of tweet (tweet/retweet/mention) based on tweet text in Python
Question: Pulling from a couple of different examples, I've been able to create a simple
Python script that parses the JSON output from the Twitter Streaming API, and
prints out the `screen_name` and `text` for each tweet. I would like to modify
my code to also classify each tweet as one of the following:
(1) **Retweet** \--> There is an "RT @anyusername" somewhere in the tweet text
column
(2) **Mention** \--> There is an "@anyusername" but no "RT @anyusername" in
the tweet column
(3) **Tweet** \--> There is no "RT @anyusername" nor any "@anyusername" in the
tweet column
I can do this in Excel with the following formula, but I can figure it out in
Python yet.
`=IF(IFERROR(FIND("RT
@",B2)>0,"False"),"Retweet",IF(IFERROR(FIND("@",B2)>0,"False"),"Mention","Tweet"))`
**_Existing Code_**
import json
import sys
from csv import writer
with open(sys.argv[1]) as in_file, \
open(sys.argv[2], 'w') as out_file:
print >> out_file, 'tweet_author, tweet_text, tweet_type'
csv = writer(out_file)
for line in in_file:
try:
tweet = json.loads(line)
except:
pass
tweet_text = tweet['text']
row = (
tweet['user']['screen_name'],
tweet_text
)
values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
csv.writerow(values)
Answer: I don't have any python interpreter here, but it should be something similar
to this:
import re
def url_match(tweet):
match = re.match(r'RT\s@....+', tweet)
if match:
return "RT"
else:
match = re.match(r'@....+', tweet)
if match:
return "mention"
else
return "tweet"
**Note:** this will work for this classification, but if **you want to
retrieve usernames** i.e. @USERNAME you will have to tweak this a little more.
|
Change focus to Tkinter program using system-wide hotkey
Question: I'm trying to register a system-wide hotkey that will trigger some action in
my Tkinter program. I'm using
[this](http://timgolden.me.uk/python/win32_how_do_i/catch_system_wide_hotkeys.html)
as reference. When I run the code from that link, it works fine. What I'm
struggling with is integrating the loop there with the event loop in Tkinter.
The Tkinter loop needs to periodically check for the hotkey being pressed.
This should be trivial, using `root.after()`. However, the program doesn't
seem to pick up on the hotkey being pressed at all, not even when it's in
focus.
Here is a succinct code example - it's as short as I could get it. It
represents my attempts to modify the code from the link to play nicely with
Tkinter.
from tkinter import *
import ctypes
from ctypes import wintypes
import win32con
user32 = ctypes.windll.user32
byref = ctypes.byref
def hotkey_handler(root):
msg = wintypes.MSG()
if user32.GetMessageA(byref(msg), None, 0, 0) != 0:
if msg.message == win32con.WM_HOTKEY:
if msg.wParam == 1:
print("hotkey pressed")
user32.TranslateMessage(byref(msg))
user32.DispatchMessageA(byref(msg))
root.after(1, hotkey_handler, root)
root = Tk()
if user32.RegisterHotKey(None, 1, win32con.MOD_SHIFT, ord("v")) != 0:
print("--Hotkey registered!")
root.after(1, hotkey_handler, root)
root.mainloop()
One quirk I've noticed is that if I set the first argument of `root.after()`
to zero, the GUI doesn't draw correctly and Python sometimes ends up crashing.
Answer: eryksun pointed out the problem - I was using the wrong case for the hotkey.
`ord("v")` should have been `ord("V")`.
|
Python pandas tagging entries in dataframe shortening code
Question: So I am using python pandas have an the following variables:
* a dataframe `df` with a column 'TAG' I created to tag data into groups based on data from a column 'IDnumber'.
* regex patterns stored in arrays `pattern1`, `pattern2`, `pattern2-2`, ...etc
* an array `group` which is filled with strings (ie: 'software', 'engineering', 'marketing'...etc).
The code is filling in the column df.TAG with strings from the array `group`
based on the regex patterns `pattern1`, `pattern2`, `pattern22`, ...etc
So far I have working code but there is redundancy in having multiple for
loops that look the same
for i in range(len(pattern1)):
df.loc[df.IDnumber.str.contains(pattern1[i]) & (df.TAG == ''),'TAG'] = group[1]
for i in range(len(pattern2)):
df.loc[df.IDnumber.str.contains(pattern2[i]) & (df.TAG == ''),'TAG'] = group[2]
for i in range(len(pattern22)):
df.loc[df.IDnumber.str.contains(pattern22[i]) & (df.TAG == ''),'TAG'] = group[2]
for i in range(len(pattern33)):
df.loc[df.IDnumber.str.contains(pattern33[i]) & (df.TAG == ''),'TAG'] = group[3]
for i in range(len(pattern3)):
df.loc[df.IDnumber.str.contains(pattern3[i]) & (df.TAG == ''),'TAG'] = group[3]
I am also getting a warning.
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
df.loc[df.IDnumber.str.contains(pattern1[i]),'TAG'] = group[1]
But the code works so I would like to know if there is a way to make the code
more efficient by reducing the number of for loops and remove the warning
without using `pd.options.mode.chained_assignment = None` to suppress the
warnings.
Answer: Your first for-loop:
for i in range(len(pattern1)):
df.loc[df.IDnumber.str.contains(pattern1[i]) & (df.TAG == ''),'TAG'] = group[1]
can be replaced with
empty = (df.TAG == '')
mask = df.IDnumber.str.contains('|'.join(pattern1)) & empty
df.loc[mask, 'TAG'] = group[1]
This might be faster, since the entire loop is being replaced with one regex
pattern. A similar refactoring can be done for your second and last `for-
loops`.
But your third and fourth `for-loops` perplex me: `for i in
range(len(pattern2-2)):`. Python names can not contain hyphens. So what does
`pattern2-2` mean? If `pattern2-2` is just another array of strings (albeit
with an invalid variable name!?) then your third and fourth loops can be
handled the same as shown above.
* * *
If all the patterns are simply arrays of strings, then you could refactor all
the for-loops with something like
import itertools as IT
patterns = [pattern1, pattern2, pattern3, pattern4, pattern5]
empty = (df.TAG == '')
for pattern, grp in IT.izip(patterns, group):
mask = df.IDnumber.str.contains('|'.join(pattern)) & empty
df.loc[mask, 'TAG'] = grp
Note that whenever you have numbered variable names, such as `pattern1`,
`pattern2`, etc. it is usually a sign that theses variables should be replaced
by a single variable which is a list or tuple, such as `patterns` above. Then
instead of referencing `pattern1`, you'd simply use `patterns[0]`.
|
A variable list parameters in a Python Class
Question: I'm trying to make a class with a variable parameter list, the code:
**Vector.py class code:**
class Vector(tuple):
def __new__(cls, *V):
return tuple.__new__(cls, V)
def __init__(self, *V):
self.V = V
def __repr__(self):
"""An overloaded method that it writes a vector in a terminal."""
return('({})'.format(self))
**TestVector.py code:**
from Vector import Vector
def main():
'We create 2 Vectors'
V1 = Vector((3, 2))
V2 = Vector((4, 5))
print(V1)
print(V2)
When I execute the code I obtain none error message, only a white line.
Thanks
Answer: So there appears to be some confusion with the way you are specifying your
arguments.
You use:
def __init__(self, *V):
which implies (along with the title of your question) that you want to give a
variable number of arguments, like:
V1 = Vector(3, 2)
V2 = Vector(1,2,3,4,5,6,7)
yet you are passing tuples to the Vector class like:
V1 = Vector((3, 2))
V2 = Vector((1,2,3,4,5,6,7))
This is not a variable parameter list, it is just one argument regardless of
how long the tuple is.
As has been pointed out in the comments above, your overloaded `__repr__`
method is broken and will cause the code to infinitely recurse. There is no
need to overload this method as the default one does exactly what you are
asking.
Putting that all together, your code becomes:
class Vector(tuple):
def __new__(cls, *V):
return tuple.__new__(cls, V)
def __init__(self, *V):
self.V = V
def main():
'We create 2 Vectors'
V1 = Vector(3, 2)
V2 = Vector(4, 5)
print(V1)
print(V2)
main()
The only question that remains is why you would want to do this all in a
subclass of tuple, rather than using (for instance) numpy.
|
How to print non-BMP Unicode characters in Tkinter (e.g. )
Question: So, today I was making shortcuts for entering certain Unicode characters. All
was going well. Then, when I decided to do these characters (in my Tkinter
program; they wouldn't even try to go in IDLE), and , I got a strange
unexpected error and my program started deleting just about everything I had
written in the text box. That's not acceptable.
Here's the error: `_tkinter.TclError: character U+1d12b is above the range
(U+0000-U+FFFF) allowed by Tcl`
I realize most of the Unicode characters I had been using only had four
characters in the code. For some reason, it doesn't like five.
So, is there any way to print these characters in a ScrolledText widget (let
alone without messing everything else up)?
UTF-8 is my encoding. I'm using Python 3.4 (so UTF-8 is the default).
I can print these characters just fine with the print statement.
Entering the character without just using ScrolledText.insert (e.g. `Ctrl-
shift-u`, or by doing this in the code: `b'\xf0\x9d\x84\xab'`) does actually
enter it, without that error, but it still starts deleting stuff crazily, or
adding extra spaces (including itself, although it reappears randomly at
times).
Answer: There is currently no way to display those characters as they are supposed to
look in Tkinter in Python 3.4 (although someone mentioned how using surrogate
pairs may work [in Python 2.x]). However, you can implement methods to convert
the characters into displayable codes and back, and just call them whenever
necessary. You have to call them when you print to Text widgets, copy/paste,
in file dialogs*, in the tab bar, in the status bar, and other stuff.
*The default Tkinter file dialogs do not allow for much internal engineering of the dialogs. I made my own file dialogs, partly to help with this issue. Let me know if you're interested. Hopefully I'll post the code for them here in the future.
These methods convert out-of-range characters into codes and vice versa. The
codes are formatted with ordinal numbers, like this: `{119083ū}`. The brackets
and the `ū` are just to distinguish this as a code. `{119083ū}` represents ``.
As you can see, I haven’t yet bothered with a way to escape codes, although I
did purposefully try to make the codes very unlikely to occur. The same is
true for the `ᗍ119083ūᗍ` used while converting. Anyway, I'm meaning to add
escape sequences eventually. These methods are taken from my class (hence the
`self`). (And yes, I know you don’t have to use semi-colons in Python. I just
like them and consider that they make the code more readable in some
situations.)
import re;
def convert65536(self, s):
#Converts a string with out-of-range characters in it into a string with codes in it.
l=list(s);
i=0;
while i<len(l):
o=ord(l[i]);
if o>65535:
l[i]="{"+str(o)+"ū}";
i+=1;
return "".join(l);
def parse65536(self, match):
#This is a regular expression method used for substitutions in convert65536back()
text=int(match.group()[1:-2]);
if text>65535:
return chr(text);
else:
return "ᗍ"+str(text)+"ūᗍ";
def convert65536back(self, s):
#Converts a string with codes in it into a string with out-of-range characters in it
while re.search(r"{\d\d\d\d\d+ū}", s)!=None:
s=re.sub(r"{\d\d\d\d\d+ū}", self.parse65536, s);
s=re.sub(r"ᗍ(\d\d\d\d\d+)ūᗍ", r"{\1ū}", s);
return s;
|
Merge two lists with labels
Question: I want to merge two sorted lists into a new sorted lists, but I want to
include labels into the new list to see which list was the origin of each
value.
So far that's my code:
l1 = [1, 40, 90, 104]
l2 = [5, 20, 70, 85, 230]
test = [(i, "l1") for i in l1 ] + [(i, "l2") for i in l2]
test.sort()
print test
[(1, 'l1'), (5, 'l2'), (20, 'l2'), (40, 'l1'), (70, 'l2'), (85, 'l2'), (90, 'l1'), (104, 'l1'), (230, 'l2')]
I'm using Python 2.7.6. Is there a faster way to do this? Because my lists
will be very long (hundreds of thousand)
Answer: I usually use itertools for this kind of thing
import itertools
l1 = [1, 40, 90, 104]
l2 = [5, 20, 70, 85, 230]
test = zip(l1,itertools.repeat('li')) + zip(l2,itertools.repeat('l2'))
|
Python 3 pandas Marking data in dataframes using strings vs Regex
Question: So I have 2 ways of doing the same thing and was wondering which one is more
efficient:
The first way loads a list from a text file or array and marks up a dataframe
using the list:
import pandas as pd
ban_list = ['Al Gore', 'Kim jong-un','Kim jong un','Kim Jong Un', 'Al Sharpton','Kim jong il', 'Richard Johnson', 'Dick Johnson']
df=pd.DataFrame({'Users': [ 'Al Gore', 'Kim jong il', 'Kim jong un', 'Al Sharpton', 'James', 'Richard Johnson', 'Bill Gates', 'Alf pig', 'Dick Johnson', 'Python Monte'],
'Time': ['D','D','N','D','L','N', 'N','L','L','N']})
df['Banned'] = ''
for i in range(len(ban_list)):
df.loc[df.Users.str.contains(ban_list[i]) & (df.Banned == ''),'Banned'] = 'Yes'
The second way uses regex patterns instead of a list of names
import pandas as pd
ban_list = ['^(?i)Al(\s)(Gore|Sharpton)$', '^(?i)Kim\sjong(\s|-)(il|un)$', '^(?i)(Dick|Richard)\sJohnson$']
df=pd.DataFrame({'Users': [ 'Al Gore', 'Kim jong il', 'Kim jong un', 'Al Sharpton', 'James', 'Richard Johnson', 'Bill Gates', 'Alf pig', 'Dick Johnson', 'Python Monte'],
'Time': ['D','D','N','D','L','N', 'N','L','L','N']})
df['Banned'] = ''
for i in range(len(ban_list)):
df.loc[df.Users.str.contains(ban_list[i]) & (df.Banned == ''),'Banned'] = 'Yes'
Both set of code works and does about the same thing. So far the problems are
the first one can is not case sensitive and the second one has a warning
`UserWarning: This pattern has match groups. To actually get the groups, use
str.extract. " groups, use str.extract.", UserWarning)`
The array in the first way loads a large list and the second way has regex
with multiple steps. Which one should I use for efficiency? or are there other
ways to improve this?
Answer: Seems a little cleaner (at least to me) to use `isin` since you have a nice
list of the banned users (you can then map the True/False to Yes/'':
df['Banned'] = df.Users.isin(ban_list).map({True:'Yes',False:''})
print df
Time Users Banned
0 D Al Gore Yes
1 D Kim jong il Yes
2 N Kim jong un Yes
3 D Al Sharpton Yes
4 L James
5 N Richard Johnson Yes
6 N Bill Gates
7 L Alf pig
8 L Dick Johnson Yes
9 N Python Monte
Of course, if True/False is good enough you can just to the first part of the
command:
df['Banned'] = df.Users.isin(ban_list)
print df
Time Users Banned
0 D Al Gore True
1 D Kim jong il True
2 N Kim jong un True
3 D Al Sharpton True
4 L James False
5 N Richard Johnson True
6 N Bill Gates False
7 L Alf pig False
8 L Dick Johnson True
9 N Python Monte False
**Edit** : If you had a second list I would do it as follows:
Adminlist = ['Bill Gates']
df['Banned'] = (df.Users.isin(ban_list).map({True:'Yes',False:''}) +
df.Users.isin(Adminlist).map({True:'Admin',False:''}))
print df
Time Users Banned
0 D Al Gore Yes
1 D Kim jong il Yes
2 N Kim jong un Yes
3 D Al Sharpton Yes
4 L James
5 N Richard Johnson Yes
6 N Bill Gates Admin
7 L Alf pig
8 L Dick Johnson Yes
9 N Python Monte
|
Login vs Register in PythonSocialAuth
Question: I'm using [PythonSocialAuth](https://github.com/omab/python-social-auth)
(v0.1.23) and I need to differentiate "Register" (create a new user account)
from Login. In the [PSA Django example](https://github.com/omab/python-social-
auth/tree/master/examples/django_example), if a new user tries to login, the
pipeline logic redirects the new user to a "register form"; I want to avoid
this "Login or Register" behavior.
What I need is:
1. Raise an error if a **new** user tries to Login.
2. Force new users to Register in order to create the a new account/profile.
Any idea how can I manipulate the PSA pipeline in order to accomplish this?
(I'm using Django 1.6).
Thanks in advance.
Answer: Thanks for comments and suggestions. I realized how to resolve my problem, and
this is my solution, hope it helps to others.
The first problem is that PSA uses the same pipeline for both:
1. registering new users and
2. login existing ones.
So, it's mandatory differentiate one pipeline flow form the other. This can be
done (have to be done?) arranging the query string:
1. `<a href="{% url 'social:begin' 'facebook' %}?register=1">`, for Sign up.
2. `<a href="{% url 'social:begin' 'facebook' %}">`, for regular Login.
The second problem is how to read the `register` parameter in the PSA
pipeline. This task have to be done setting `FIELDS_STORED_IN_SESSION` (see
the [PSA docs](http://psa.matiasaguirre.net/docs/use_cases.html#pass-custom-
get-post-parameters-and-retrieve-them-on-authentication)):
# settings.py
...
FIELDS_STORED_IN_SESSION = ['register']
Finally, my pipeline looks like this:
# settings.py
...
SOCIAL_AUTH_PIPELINE = (
'my.path.custom_pipeline.clean_pipeline',
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'my.path.custom_pipeline.redirect_to_join_form',
...
)
And my custom tasks:
# custom_pipeline.py
from social.pipeline.partial import partial
from django.contrib import messages
from django.shortcuts import redirect
def clean_pipeline(strategy, *args, **kwargs):
_register = strategy.session.get('register', None)
strategy.session.flush()
strategy.session['register'] = _register
@partial
def redirect_to_join_form(strategy, details, user=None, is_new=False, *args, **kwargs):
if user and user.username:
return
if is_new and strategy.session_get('register', False) == '1':
strategy.session.pop('register')
return redirect('users_join_form')
if is_new and strategy.session_get('saved_username'):
return {'username': strategy.session_get('saved_username')}
messages.add_message(
strategy.request, messages.ERROR,
"Error. Account not registered %s (%s), " %
(strategy.backend.name.capitalize(), details['username'])
)
return redirect('users_login')
That's all. Hope it helps.
|
RabbitMQ brokers on different machines
Question: The [hello world example](http://www.rabbitmq.com/tutorials/tutorial-one-
python.html) in the tutorial section of rabbitMQ, asks just to change the
hostname with the ip of the different machine. But that isn't working for me.
I have tried [Binding external IP address to Rabbit MQ
server](http://stackoverflow.com/questions/7168055/binding-external-ip-
address-to-rabbit-mq-server) but that didn't work. Is there something else
that i need to do to the configuration file or the code?
Here is the sending code
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='ip_address'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
And my receiving code which I am running on another machine
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='ip_address'))
channel = connection.channel()
channel.queue_declare(queue='hello1')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
And the error I am getting is
No handlers could be found for logger "pika.adapters.base_connection"
Traceback (most recent call last):
File "send.py", line 25, in <module>
'ip_address'))
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 107, in __init__
super(BlockingConnection, self).__init__(parameters, None, False)
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/base_connection.py", line 62, in __init__
on_close_callback)
File "/usr/local/lib/python2.7/dist-packages/pika/connection.py", line 590, in __init__
self.connect()
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 206, in connect
if not self._adapter_connect():
File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 275, in _adapter_connect
raise exceptions.AMQPConnectionError(1)
pika.exceptions.AMQPConnectionError: 1
I appreciate for you guys to take the time to help me.
Answer: The problem is the new [rabbitmq access control
policy](http://www.rabbitmq.com/access-control.html)
Please read this : [client can't connect to remote rabbitmq
server](http://stackoverflow.com/questions/23487238/client-cant-connect-to-
remote-rabbitmq-server)
or read this : [Can't access RabbitMQ web management interface after fresh
install](http://stackoverflow.com/questions/22850546/cant-access-rabbitmq-web-
management-interface-after-fresh-install)
|
Image manipulation in Python using MPI
Question: I'm trying to do some image manipulation using MPI (mpi4py) in Python. This is
my code so far:
from mpi4py import MPI
from PIL import Image
comm = MPI.COMM_WORLD
size = comm.size #number of processors
rank = comm.rank #calling process rank
root = 0
if rank == 0:
print "rank = 0 \n"
img = Image.open('dog.jpg')
width, height = img.size
pix = list(img.getdata())
for i in range(len(pix)):
pix[i] = list(pix[i])
chunks = [[] for _ in range(size)]
for i, chunk in enumerate(pix):
chunks[i % size].append(chunk)
else:
print "rank != 0"
data = comm.scatter(chunks, root)
#do some pixel manipulations
data = comm.gather(data, root)
for i in range(len(pix)):
pix[i] = tuple(data[0][i])
image = Image.new("RGB", (width, height))
image.putdata(pix)
image.save("test.jpg")
When I try to run it with
mpirun -np 1 python parallel.py
it works ok. But if i try to increase the number of processors, I get the
following error
mpirun -np 3 python parallel.py
rank = 1
rank = 2
rank = 0
Traceback (most recent call last):
File "parallel.py", line 21, in <module>
data = comm.scatter(chunks, root)
NameError: name 'chunks' is not defined
Traceback (most recent call last):
File "parallel.py", line 21, in <module>
data = comm.scatter(chunks, root)
NameError: name 'chunks' is not defined
I'm running the code on a Ubuntu Virtual Machine using Virtual Box. Appreciate
your help!
Answer: This is not an MPI problem. `chunks` is undefined in the processes in which
the `else:` branch of the conditional is taken, i.e. in all processes except
rank 0. Simply add `chunks = None` there:
...
if rank == 0:
...
else:
print "rank != 0"
chunks = None
...
It works with one process since in that case there is only one rank (0) and
the else branch is never taken.
|
Album app process in Django
Question: I want to know how to display images separated by albums onto a page in
Django. So far, I've learned how to do so with the line
`<img src="{% static "images/[email protected]" %}">`
in my html file.
structure:
/PersonalWebsite
/static
/img
/albums
/album1
img1
/album2
img2
...etc
What I want to do is have a few album thumbnails out and upon click, all the
images from the album should be displayed. I believe I would do this with an
AJAX request. I am probably going to categorized these photos with tags and
put names one them and other characteristics. This would be done in my
`models.py` which I have: (though not completed)
from django.db import models
from django.contrib import admin
import os
from PersonalWebsite.settings import MEDIA_ROOT
class Album(models.Model):
title = models.CharField(max_length = 60)
def __unicode__(self):
return self.title
def get_image_by_album(self):
images = []
for root, dirs, files in os.walk(os.path.join(MEDIA_ROOT, 'albums', self.title)):
mypath = os.sep.join(os.path.join(root, file).split(os.sep[4:]))
images.append(mypath)
return images
class Tag(models.Model):
tag = models.CharField(max_length = 50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length = 60, blank = True, null = True)
#image = models.FileField(upload_to = get_upload_file_name)
tags = models.ManyToManyField(Tag, blank = True)
albums = models.ForeignKey(Album)
width = models.IntegerField(blank = True, null = True)
height = models.IntegerField(blank = True, null = True)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.image.name
class AlbumAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["title"]
class TagAdmin(admin.ModelAdmin):
list_display = ["tag"]
class ImageAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["__unicode__", "title", "created"]
list_filter = ["tags", "albums"]
admin.site.register(Album, AlbumAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(Image, ImageAdmin)
My "get_image_by_album" parses through the albums and appends the path to
"images" list. Thats as far as I've got right now =/ I also want to set up an
admin so I can maintain the site easily later on. I think I am going to make a
view method that will simply get the list of image paths and display it that
way. I am open to suggestions! let me know what you think! I also want to set
up an admin interface that would enable me to upload and edit meta data from
the photos manually but I will figure out how to do so later.
Answer: I built a very simple gallery app using django-photologue.
<http://gallery.gentryart.us>
|
Pydrive authentication using
Question: I was using gdata module to access, upload, download files from google doc. I
have the oauth key and secret with me. Now I want to switch to google drive
api. Learning and studying a bit on google drive api , it looks like a bit
different in the authentication. I also have downloaded pydrive module so as I
can start things up. But I am not able to authorize my server side python code
to authorize/authenticate the user using my oauth keys and access my drive. Do
any one has any spare know how on how I can use pydrive to access my drive
with my previous auth keys. I just need a simple way to authenticate.
Answer: For using the gdata module we use either of these credentials- 1> username &
password or 2> consumer oauth key and secret key.
Since you are trying to use oauth credentials, I think you want a Domain Wide
Delegated Access for Google Drive, which will help you to achieve
uploading/downloading files into any user's google drive through out the
domain.
For this you need to generate a new Client ID of a Service Account Type from
[Developer's Console](http://console.developers.google.com)
*.p12 file will get downloaded. Note the path where you save it. Also note the email address of your Service account. These will be use while coding.
Below is the python code where u have to carefully edit- PATH TO SERIVE
ACCOUNT PRIVATE KEY, [email protected],
[email protected] in order to run it properly and test it.
Hope this will help! Resource- [Google Drive
API](https://developers.google.com/drive/web/delegation)
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = '[email protected]'
"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'PATH TO SERIVE ACCOUNT PRIVATE KEY'
def createDriveService(user_email):
"""Build and returns a Drive service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user.
Returns:
Drive service object.
"""
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope='https://www.googleapis.com/auth/drive', sub=user_email)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
drive_service=createDriveService('[email protected]')
result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = drive_service.files().list().execute()
#print files
result.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
for f in result:
print '\n\nFile: ',f.get('title')
print "\n"
|
How to timeout a statement
Question: how to time-out a statement/block of code in python?
I tried using the below looking at a post but it couldn't identify the signal:
wls:/offline> import signal
Traceback (innermost last):
File "<console>", line 1, in ?
ImportError: no module named signal
code:
import os
import signal
def handler(signum, frame):
print "Forever is over!"
raise Exception("end of time")
def loop_forever():
import time
while 1:
print "sec"
time.sleep(1)
signal.signal(signal.SIGALRM, handler)
signal.alarm(10)
try:
loop_forever()
except Exception, exc:
print exc
Answer: Your code is working perfectly well for me:
>>> import os
>>> import signal
>>>
>>> def handler(signum, frame):
... print "Forever is over!"
... raise Exception("end of time")
...
>>> def loop_forever():
... import time
... while 1:
... print "sec"
... time.sleep(1)
...
>>> signal.signal(signal.SIGALRM, handler)
0
>>> signal.alarm(10)
0
>>>
>>> try:
... loop_forever()
... except Exception, exc:
... print exc
...
sec
sec
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time
Though, are you using a Unix system to try this? Whether this is a Linux, a
BSD or a Mac? The signal module may not be present at all on other OS, as this
is using a feature very specific to unix systems, even though windows does
have a very basic support of POSIX processes.
edit: Well, as I'm saying you're in a very particular case, which is neither
Unix or windows or even symbian ; but you're running it in Jython, which does
not have access to the OS features, whereas the lack of `signal` module. You
should have tagged your question with Jython, to help us help you more
efficiently! Then you'd better use a thread timer which should be well
implemented in Jython.
As a very basic example:
>>> threading.Timer(5.0, lambda: print("toto")).start()
As a more complex example, where I'm using a simple lock semaphore to handle
the signaling between the main thread and the timer thread:
>>> import time
>>> import threading
>>> l = threading.Lock()
>>> threading.Timer(5.0, lambda l: l.acquire(), args=(l,)).start()
>>> while not l.locked():
... print("sec")
... time.sleep(1)
...
sec
sec
sec
sec
sec
>>>
|
Importing user defined modules in Python
Question: I have the following module definition for a Stack:
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
I am trying to import this module in another program as follows:
import Stack
s=Stack()
print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
I get the following error:
s=Stack()
TypeError: 'module' object is not callable
Have I imported incorrectly? The Stack class is within the same folder as the
class that is implementing it. Or have I called the constructor incorrectly?
Answer: You should use:
from Stack import Stack
In 's=Stack()', the 'Stack' is a module name.
|
ImportError: No module named gi.repository
Question: I'm trying to launch python script on Ubuntu 10.04:
from gi.repository import Nautilus, GObject
It doesn't work:
Traceback (most recent call last):
File "script.py", line 1, in
from gi.repository import Nautilus, GObject
ImportError: No module named gi.repository
I installed python-gobject-dev, python-gobject, python-nautilus, but it didn't
help. Has anyone had this problem?
Answer: 10.04? That's pre-GNOME 3, so the preferred Python bindings were based on
PyGTK, not PyGObject. You need to either use the (obsolete) PyGTK bindings or
upgrade to a newer OS.
|
Pandas dataframe manipulation and plotting
Question: Using WinPython 3.4, matplotlib 1.3.1, I'm pulling data for a dataframe from a
mysql database. The raw dataframe that I get from the query looks like:
wafer_number test_type test_pass x_coord y_coord test_el_id wavelength intensity
0 HT2731 T2 1 38 54 24 288.68 4413
1 HT2731 T2 1 40 54 25 257.42 2595
2 HT2731 T2 1 50 54 28 300.00 2836
3 HT2731 T2 1 52 54 29 300.00 2862
4 HT2731 T2 1 54 54 30 300.00 3145
5 HT2731 T2 1 56 54 31 300.00 2804
6 HT2731 T2 1 58 54 32 255.69 2803
7 HT2731 T2 1 59 54 33 257.23 2991
8 HT2731 T2 1 60 54 34 262.45 3946
9 HT2731 T2 1 62 54 35 291.84 9398
10 HT2801 T2 1 38 55 54 288.68 4125
11 HT2801 T2 1 38 56 55 265.25 4258
What I need is to plot wavelength and intensity on the x and y axes
respectively with each different wafer number as it's own series. I need to
keep the x_coord and y_coord variables so that I can identify standout data
points later ideally by clicking on them and adding them to a list. I'll get
that working after I get these things plotted.
I thought that using the built-in dataframes plotting capability requires me
to perform a pivot_table method
wl_vs_int = results.pivot_table(values='intensity', rows=['x_coord', 'y_coord','wavelength'], cols='wafer_number')
on my dataframe which then turns the dataframe into:
wafer_number HT2478 HT2625 HT2644 HT2671 HT2673 HT2719 HT2731 HT2796 HT2801
x_coord y_coord wavelength
27 35 289.07 NaN NaN NaN 5137 NaN NaN NaN NaN NaN
36 250.88 4585 NaN NaN NaN NaN NaN NaN NaN NaN
37 260.90 NaN NaN NaN NaN 4270 NaN NaN NaN NaN
38 288.87 NaN NaN NaN 8191 NaN NaN NaN NaN NaN
40 259.74 NaN NaN NaN NaN 17027 NaN NaN NaN NaN
41 259.74 NaN NaN NaN NaN 18742 NaN NaN NaN NaN
42 259.74 NaN NaN NaN NaN 34098 NaN NaN NaN NaN
28 34 268.27 NaN NaN NaN NaN 2080 NaN NaN NaN NaN
38 257.42 7727 NaN NaN NaN NaN NaN NaN NaN NaN
44 260.13 NaN NaN NaN NaN 55329 NaN NaN NaN NaN
but now the index is a multi-index of the x, y coords and the wavelength so
when I just try to print the wl vs columns,
plt.scatter(wl_vs_int.wavelength, wl_vs_int.columns)
I get the AttributeError:
AttributeError: 'DataFrame' object has no attribute 'wavelength'
I've tried to reindex the dataframe back to a default index but that still
gives me the results that 'DataFrame' object has no 'wavelength' attribute.
There's got to be a better way to either rearrange the dataframe to make this
possible through the built-in dataframe plotting capabilities or to plot only
select columns vs other columns (with the columns being dynamic). I'm clearly
new to python and pandas but I've spent days of time trying to do this in
different ways and with no results. Any help would be greatly appreciated.
Thanks.
Answer: To plot wavelength and intensity on the x and y axes respectively with each
different wafer number as it's own series, one can group data wrt
`wafer_number`, and then deal with each group
import pandas as pd
from StringIO import StringIO
import matplotlib.pyplot as plt
data = \
"""wafer_number,test_type,test_pass,x_coord,y_coord,test_el_id,wavelength,intensity
HT2731,T2,1,38,54,24,288.68,4413
HT2731,T2,1,40,54,25,257.42,2595
HT2731,T2,1,50,54,28,300.00,2836
HT2731,T2,1,52,54,29,300.00,2862
HT2731,T2,1,54,54,30,300.00,3145
HT2731,T2,1,56,54,31,300.00,2804
HT2731,T2,1,58,54,32,255.69,2803
HT2731,T2,1,59,54,33,257.23,2991
HT2731,T2,1,60,54,34,262.45,3946
HT2731,T2,1,62,54,35,291.84,9398
HT2801,T2,1,38,55,54,288.68,4125
HT2801,T2,1,38,56,55,265.25,4258"""
df = pd.read_csv(StringIO(data),sep = ',')
dfg = df.groupby('wafer_number')
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
fig, ax = plt.subplots()
for i,k in enumerate(dfg.groups.keys()):
currentGroup = df.loc[dfg.groups[k]]
color = colors[i % len(colors)]
ax.plot(currentGroup['wavelength'].values,currentGroup['intensity'].values,\
ls='', color = color, label = k, marker = 'o', markersize = 8)
legend = ax.legend(loc='upper center', shadow=True)
plt.xlabel('wavelength')
plt.ylabel('intensity')
plt.show()
|
python/ast: evaluate an ast.Subscript node
Question: I'm using ast to parse python files and I can't work out how to get an
ast.Subscript node to evaluate. I can't even see how to get the text out of it
(so I could use eval(text) ). Can anyone see what I'm missing?
For example, here the default value for the A arg is an expression which I
want to evaluate. Ast returns the default value as an ast.Subscript node. How
can I evaluate that?
import ast
import os
text = """
def test(A=os.environ["USER"][0]):
return A
"""
fnDef = ast.parse(text).body[0]
argDefault = fnDef.args.defaults[0]
Answer: Using `ast.dump(node)`, you can see what your node is composed of. In your
case (indentation is mine):
print(ast.dump(fnDef))
> FunctionDef(name='test',
args=arguments(
args=[arg(arg='A', annotation=None)],
vararg=None,
varargannotation=None,
kwonlyargs=[],
kwarg=None,
kwargannotation=None,
defaults=[
Subscript(
value=Subscript(
value=Attribute(
value=Name(id='os', ctx=Load()),
attr='environ', ctx=Load()),
slice=Index(value=Str(s='USER')),
ctx=Load()),
slice=Index(value=Num(n=0)),
ctx=Load())],
kw_defaults=[]),
body=[Return(value=Name(id='A', ctx=Load()))],
decorator_list=[],
returns=None)
As you can see, your Subscript nodes are composed of a value, a slice and a
ctx. The first slice (`["USER"]`) is an Index which value is a Str node, the
second (`[0]`) slice is an Index which value is a Num node.
You can also see that in the [abstract
grammar](https://docs.python.org/3.4/library/ast.html#abstract-grammar
"Python's grammar") (see the 'slice' type).
|
Subprocess library won't execute compgen
Question: I am trying to make list of every command available on my linux (Lubuntu)
machine. I would like to further work with that list in Python. Normally to
list the commands in the console I would write "compgen -c" and it would print
the results to stdout.
I would like to execute that command using Python subprocess library but it
gives me an error and I don't know why.
Here is the code:
#!/usr/bin/python
import subprocess
#get list of available linux commands
l_commands = subprocess.Popen(['compgen', '-c'])
print l_commands
Here is the error I'm getting:
Traceback (most recent call last):
File "commands.py", line 6, in <module>
l_commands = subprocess.Popen(['compgen', '-c'])
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I'm stuck. Could you guys help me with this? How to I execute the compgen
command using subprocess?
Answer: [`compgen` is a builtin bash
command](http://www.gnu.org/software/bash/manual/bashref.html#Programmable-
Completion-Builtins), run it in the shell:
from subprocess import check_output
output = check_output('compgen -c', shell=True, executable='/bin/bash')
commands = output.splitlines()
You could also write it as:
output = check_output(['/bin/bash', '-c', 'compgen -c'])
But it puts the essential part (`compgen`) last, so I prefer the first
variant.
|
Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins
Question: In short: what I want is for the majority of mathematical functions I've
written (e.g., `my_average(a, b)`) to work with any `a` and `b` for which an
`f_add` and `f_div` have been defined. Without overloading + and / and without
breaking `my_average(built_in_type, built_in_type)` In python 3.
Specifically, I'm working with instances of a Pigment object I have created.
Overloading operators for these objects in not straightforward. For instance:
The difference (for distance purposes) between two instances might be `a.lab -
b.lab`. (The Lab colorspace has a good correlation between perceptive and
Euclidian distance.)
The sum (for mixing purposes) of two instances might be `a.srgb + b.srgb`.
(The srgb colorspace is linear and appropriate for mathematical manipulation.)
For other purposes, sum and difference might mean something else.
So, duck typing in my existing modules wont work.
pigment_instance.distance(self, b)
pigment_instance.mix(self, b)
are fine as long as I don't mind re-writing every function (as a method) I
need every time I have a new object like this. What I'd like to do is rewrite
my functions just once more to be more robust.
I've tried a few things:
class Averager():
__init__(self, f_mix, f_distance):
self.f_mix = f_mix
...
def __call__(self, a, b):
# return the average calculated with self.f_something functions
That works OK, but I just end up burying an entire module in a class.
def mix(a, b, f_mix=lambda x, y: x + y, f_distance=lambda x, y: x - y)
# or, same as above with decorators.
Again, works OK, but I've got to keep the long default arguments or supply an
f_add every time I want to calculate 2+2.
def pigment_functions(f_mix, f_distance):
return [
functools.partial(mix, f_mix=somefunc, f_distance=somefunc),
functools.partial(distance, f_mix=somefunc, f_distance=somefunc)]
mix, difference = pigment_functions(f_mix, f_distance)
A similar choice to the second.
def mix(a, b):
try: a + b
except TypeError: # look for some global f_mix
Also works OK, but I've got global variables and a mess inside every function
Which of these (or something else) makes sense?
Answer: if you have `my_average(a, b)` that is implemented in terms of `add` and `div`
functions e.g.:
def my_average(a, b):
return div(add(a, b), 2)
then to provide different implementations for different types, you could use
[`functools.singledispatch`](https://docs.python.org/dev/library/functools.html#functools.singledispatch):
import functools
@singledispatch
def div(x, y:int): # default implementation
raise NotImplementedError('for type: {}'.format(type(x)))
@div.register(Divisible) # anything with __truediv__ method
def _(x, y):
return x / y
@singledispatch
def add(a, b):
raise NotImplementedError('for type: {}'.format(type(a)))
@add.register(Addable) # anything with __add__ method
def _(a, b):
return a + b
where `Addable`, `Divisable` could be defined as:
from abc import ABCMeta, abstractmethod
class Divisible(metaclass=ABCMeta):
"""Anything with __truediv__ method."""
__slots__ = ()
__hash__ = None # disable default hashing
@abstractmethod
def __truediv__(self, other):
"""Return self / other."""
@classmethod
def __subclasshook__(cls, C):
if cls is Divisible:
if any("__truediv__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Addable(metaclass=ABCMeta):
"""Anything with __add__ method."""
__slots__ = ()
__hash__ = None # disable default hashing
@abstractmethod
def __add__(self, other):
"""Return self + other."""
@classmethod
def __subclasshook__(cls, C):
if cls is Addable:
if any("__add__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
### Example
>>> isinstance(1, Addable) # has __add__ method
True
>>> isinstance(1, Divisible) # has __truediv__ method
True
>>> my_average(1, 2)
1.5
>>> class A:
... def __radd__(self, other):
... return D(other + 1)
...
>>> isinstance(A(), Addable)
False
>>> _ = Addable.register(A) # register explicitly
>>> isinstance(A(), Addable)
True
>>> class D:
... def __init__(self, number):
... self.number = number
... def __truediv__(self, other):
... return self.number / other
...
>>> isinstance(D(1), Divisible) # via issubclass hook
True
>>> my_average(1, A())
1.0
>>> my_average(A(), 1) # no A.__div__
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'A' and 'int'
Builtin numbers such as `int` define `__add__`, `__truediv__` method so they
are supported automatically. As class `A` shows, you could use classes even if
they don't define the specific methods such as `__add__` by calling
`.register` method explicitly if they still can be used in the given
implementation.
Use `add.register` and `div.register` to define implementations for other
types if necessary e.g.:
@div.register(str)
def _(x, y):
return x % y
After that:
>>> my_average("%s", "b") # -> `("%s" + "b") % 2`
'2b'
|
Python myro module importerror
Question: I am completely new in Python. Installed just today in school purposes. I need
to use myro module but I am getting this error `ImportError: No module named
'myro'` all the time. I've found out that I have installed older versions of
Python already with another software like Blender or Gimp. I am using 3.4.0
version for mac. How can I get this myro module? I've downloaded zipped files
from <http://myro.roboteducation.org/download/> but I don't know where to copy
them. In Library/Python path are just these older versions (2.3, 2.5, 2.6,
2.7). There isn't the latest version I just installed. Anybody who could help
me please?
/edit. Well basically I need to be able to do some simple graphics in Python
and the myro module is what I've found in youtube tutorial. But that's from
2010. Maybe there is something else today what makes graphics possible in
Python 3.4.0. Anybody?
Answer: The absolute easiest thing to do in this situation is to go to [this
link](https://pypi.python.org/pypi/setuptools) and install Python Setuptools.
[Here](https://pypi.python.org/pypi/setuptools#unix-including-mac-os-x-curl)
are the installation instructions for OSX. From there you can use
`easy_install` and get `pip` from [here](https://pypi.python.org/pypi/pip/).
Now all you have to do whenever you want to install a module you can:
pip install myro
I know it seems like a lot just for `myro` but you'll thank yourself for doing
it when you want to get more serious with Python.
Now for your graphics needs.
**EDIT** : Update link to [Pillow](https://pypi.python.org/pypi/Pillow/2.4.0)
There are quite a few packages for dealing with graphics but I like Pillow.
**EDIT** : Installing setuptools:
1. Open your Terminal (I don't use Macs but I think you get there using Finder)
2. type the following command:
curl <https://bootstrap.pypa.io/ez_setup.py> -o - | python34
Then you should be all set. If you don't have `curl` then that's another can
of worms.
|
How do you deal with importing built-in libraries under windows using PyCharm?
Question: I have python-2.6 installed and use pycharm-3.1.3 (community edition) to
develop.
But the imports of the built-in libraries (for instance - `datetime`) are
marked as errors by the given IDE.

It only happens for built-in libraries, the external ones that are located in
`<pythondir>/Lib` (for instance `base64`) are imported without problems - IDE
can resolve symbols from them for intellisense and whatnot.
So the question is how to deal with this?
PS: I know I can mark it as "ignore this import error" but then the library
symbols won't be autocompleted.
Answer: It happened right after an upgrade from 3.0 to 3.1.x, so probably it's just
some upgrade issue.
The solution is to re-add interpreter. After that all built-in modules are
resolved fine.
|
Appending Windows Directories In Python
Question: I am creating a program that appends audio files the user selects together
using Sox.
I originally created the program for linux but I am making it compatible with
Windows. On windows when I pass the list of files to Sox, the program raises
'The filename, directory name, or volume label syntax is incorrect.'
When I print out the list of files it is `C:\\\MyProgram\\\` And So On. How Do
I Make The `'\\'` in the path become `'\'`?
I'm on windows 8.1, so that may be the problem.
I have tried:
str(nameoffile)
os.path.abspath(nameoffile)
os.path.normpath(nameoffile)
There is a huge list of files and directories, so setting the absolute file of
each is not an option, I am using os.path.join() to allow the user to navigate
through the folders.
But when I pass the files into the list and then call the list using
`subprocess.list2cmdline(mylist)`, it simply raises that error above.
Example:
mydirectory = os.getcwd()
appendlist = list()
appendlist.append("sox")
for x, i in enumerate(self.fileselected): # A List Of Files The User Selected
directory = chosendirectory
nextfile = os.path.join(chosendirectory, i)
appendlist.append(nextfile)
subprocess.call([subprocess.list2cmdline(appendlist)], shell=True)
When `os.path.join` appends the files....it produces "`C:\\\Program\\\file`"
and then it is converted to `str()`. The str() reads "`C:\\\Program\\\file`"
and the escape character does not register in a string. How do I remove the
escape character to pass it into the list as valid windows directory?
Answer: You could simplify the call if you change the current working directory for
the subprocess:
from subprocess import check_call
check_call(['sox'] + self.fileselected, cwd=chosendirectory)
Note: you don't need `shell=True` unless you want to run an internal (shell
builtin) command such as `start`.
* * *
Backslashes has special meaning inside Python string _literals_ in the source
code.
>>> len('\\') == 1 # a single backslash inside the string
True
Backslashes has no special meaning in a string object (in memory) i.e., you
shouldn't care about backslashes unless you manually write the paths in your
Python source code -- if you read the path from a file; you don't need to
escape them. If you read the paths from a GUI; you don't need to escape them.
If you read the paths from the output of a subprocess; you don't need to
escape them, etc.
If you print `repr(path)`; it shows you how Python string literal would look
like i.e., the backslashes are doubled (escaped). If you print: `[path]` then
it is equivalent to `'['+repr(path)+']'`. If you print the string along
`print(path)` then `repr` is not called on the string object and the
backslashes are not doubled.
For Windows paths and regex patterns, you could use raw-string literal where
backslashes are not escaped e.g., `r'C:\Path\n\f' == 'C:\\Path\\n\\f'`
(notice: `r` prefix).
|
Moving specific file types with Python
Question: I know this is going to be frustratingly easy for many of you. I am just
beginning to learn Python and need help with some basic file handling.
I take a lot of screenshots, which end up on my desktop (as this is the
default setting). I am aware I can change the screenshot setting to save it
somewhere else automatically. However, I think this program will be a good way
to teach me how to sort files. I would like to use python to automatically
sort through all the files on my desktop, identify those that end with .png
(the default file type for screenshots), and simply move it to a folder I've
named "Archive".
This is what I've got so far:
import os
import shutil
source = os.listdir('/Users/kevinconnell/Desktop/Test_Folder/')
destination = 'Archive'
for files in source:
if files.endswith('.png'):
shutil.move(source, destination)
I've played around with it plenty to no avail. In this latest version, I am
encountering the following error when I run the program:
> Traceback (most recent call last): File "pngmove_2.0.py", line 23, in
> shutil.move(source, destination) File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py",
> line 290, in move TypeError: coercing to Unicode: need string or buffer,
> list found
I am under the impression I have a sort of issue with the proper
convention/syntax necessary for the source and destination. However, I've thus
far been unable to find much help on how to fix it. I used os.path.abspath()
to determine the file path you see above.
Thanks in advance for any help in preserving my sanity.
# LATEST UPDATE
I believe I am very close to getting to the bottom of this. I'm sure if I
continue to play around with it I'll figure it out. Just so everyone that's
been helping me is updated...
This is the current code I'm working with:
import os
import shutil
sourcepath ='/Users/kevinconnell/Desktop/'
source = os.listdir(sourcepath)
destinationpath = '/Users/kevinconnell/Desktop/'
for files in source:
if files.endswith('.png'):
shutil.move(os.path.join(sourcepath,'Test_Folder'), os.path.join(destinationpath,'Archive'))
This works for renaming my 'Test_Folder' folder to 'Archive'. **However** , it
moves all the files in the folder, instead of moving the files that end with
'.png'.
Answer: your moving total folder,need to move only file
import os
import shutil
sourcepath='C:/Users/kevinconnell/Desktop/Test_Folder/'
source = os.listdir(sourcepath)
destinationpath = 'C:/Users/kevinconnell/Desktop/Test_Folder/Archive'
for files in source:
if files.endswith('.png'):
shutil.move(os.path.join(sourcepath,files), os.path.join(destinationpath,files))
|
python xlrd error with old xls file
Question: I have got an excel file, that was created by some rather old soft. This file
couldn't be opened in OpenOffice(some encoding errors) and in Excel 2010 at
first it could only be opened in Protected View. When I tried to open it by
xlrd:
from xlrd import open_workbook
rb = open_workbook('405_mut_1x.xls', encoding_override="utf-8")
I got an error:
Traceback (most recent call last):
File "/home/wintr/PycharmProjects/4lab_1/main.py", line 2, in <module>
rb = open_workbook('405_mut_1x.xls', encoding_override="utf-8")
File "/usr/lib/python3/dist-packages/xlrd/__init__.py", line 435, in open_workbook
ragged_rows=ragged_rows,
File "/usr/lib/python3/dist-packages/xlrd/book.py", line 107, in open_workbook_xls
bk.fake_globals_get_sheet()
File "/usr/lib/python3/dist-packages/xlrd/book.py", line 714, in fake_globals_get_sheet
self.get_sheets()
File "/usr/lib/python3/dist-packages/xlrd/book.py", line 705, in get_sheets
self.get_sheet(sheetno)
File "/usr/lib/python3/dist-packages/xlrd/book.py", line 696, in get_sheet
sh.read(self)
File "/usr/lib/python3/dist-packages/xlrd/sheet.py", line 1467, in read
self.update_cooked_mag_factors()
File "/usr/lib/python3/dist-packages/xlrd/sheet.py", line 1535, in update_cooked_mag_factors
elif not (10 <= zoom <= 400):
TypeError: unorderable types: int() <= NoneType()
Same thing with encoding by cp1252, utf-7. utf_16_le, that was adviced in
similar topic returns
ERROR *** codepage None -> encoding 'utf_16_le' -> UnicodeDecodeError: 'utf16' codec can't decode byte 0x6c in position 4: truncated data
Without encoding I got additional string in traceback
*** No CODEPAGE record, no encoding_override: will use 'ascii'
After saving file in Excel 2010 (in xlsx) format this problem had disappeared
- file can be opened both in xlrd and OO. Is there any way to open such file
by xlrd without resaving? Upd. There is no such problem for python2.7 xlrd.
However I still don't know what's wrong with python3.3 xlrd.
Answer: The problem is in different behaviour between python2 and python3:
$ python2
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 <= None
False
$ python3
Python 3.4.3 (default, Jul 28 2015, 18:20:59)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 <= None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() <= NoneType()
To fix this you can edit xlrd/sheet.py around line 1543:
Change
elif not (10 <= zoom <= 400):
to
elif zoom is None or not (10 <= zoom <= 400):
So behaviour will be like in python2
|
Blank Page with web.py and Google App Engine
Question: I'm trying to get web.py app running on local Google App Engine.
My yaml:
application: appname
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: code.app
My code.py:
import web
urls = (
"/.*", "hello",
)
app = web.application(urls, globals())
class hello:
def GET(self):
return 'Hello, world!'
app = app.gaerun()
When I start the server all I get is a blank page. So what's wrong?
Edit:
python --version
Python 2.7.6
Edit 2:
Error from console:
ImportError: No module named web
Answer: What you're trying to do is import an external module, which is not supported
by GAE.
What you can do though, is copy web.py into your app directory, and then use
it. See ["How to include third party Python libraries in Google App
Engine"](http://stackoverflow.com/a/14851686/8418).
You can get the source code from [here](https://github.com/webpy/webpy)
|
How to change permissions on a couchdb database with python
Question: I am trying to add a user in the "_security" document of a database with
python-couchdb. I am getting an error because the "_security" document doesn't
have an "_id" attribute.
import couchdb
couch=couchdb.Server("http://admin:admin@localhost:5984")
couch["db"]["_security"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/couchdb/client.py", line 977, in __repr__
return '<%s %r@%r %r>' % (type(self).__name__, self.id, self.rev,
File "/usr/local/lib/python2.7/dist-packages/couchdb/client.py", line 987, in id
return self['_id']
KeyError: '_id'
Answer: The right way to do it is
import couchdb
couch=couchdb.Server("http://admin:admin@localhost:5984")
db=couch["db"]
security_doc=db.resource.get_json("_security")[2]
db.resource.put("_security",{u'admins': {u'names': [u'admin1','admin2','admin3'], u'roles': []}, u'members': {u'names': [], u'roles': []}})
|
Using argparse to create output file
Question: I have been using argparse in a program I am writing however it doesnt seem to
create the stated output file.
My code is:
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
output_file.write("%s\n" % item)
I have also tried:
parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
output_file.write("%s\n" % item)
The error that occurs is :
output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined
Can someone please explain why I am having this error occuring and how I could
solve it?
All my code:
from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import izip
#print = print_function
parser = argparse.ArgumentParser() #simplifys the wording of using argparse as stated in the python tutorial
parser.add_argument("-r1", type=str, action='store', dest='input1', help="input the forward read file") # allows input of the forward read
parser.add_argument("-r2", type=str, action='store', dest='input2', help="input the reverse read file") # allows input of the reverse read
parser.add_argument("-v", "--verbose", action="store_true", help=" Increases the output, only needs to be used to provide feedback to Tom for debugging")
parser.add_argument("-n", action="count", default=0, help="Allows for up to 5 mismatches, however this will reduce accuracy of matching and cause mismatches. Default is 0")
#parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
parser.add_argument("-fastq", action="store_true", help=" States your input as fastq format")
parser.add_argument("-fasta", action="store_true", help=" States your input as fasta format")
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
args = parser.parse_args()
def class_chars(chrs):
if 'N' in chrs:
return 'unknown'
elif chrs[0] == chrs[1]:
return 'match'
else:
return 'not_match'
with open(output, 'w') as output_file:
s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)
for k, group in groupby(zip(s1, s2), class_chars):
elems = len(list(group))
chars[k] += elems
if k == 'match':
consec_matches.append((n, n+elems-1))
n += elems
print (chars)
print (consec_matches)
print ([x for x in consec_matches if x[1]-x[0] >= 9])
list = [x for x in consec_matches if x[1]-x[0] >= 9]
flatten_list= [x for y in list for x in y]
print (flatten_list)
matching=[y[1] for y in list for x in y if x ==0 ]
print (matching)
magic = lambda matching: int(''.join(str(i) for i in matching)) # Generator exp.
print (magic(matching))
s2_l = s2[magic(matching):]
line3=s1+s2_l
print (line3)
if line3:
output_file.write("%s\n" % item)
Answer: You are missing the bit where the arguments are actually parsed:
parser.add_argument("-o", "--output", help="Directs the output to a name of your choice")
args = parser.parse_args()
with open(args.output, 'w') as output_file:
output_file.write("%s\n" % item)
parser.parse_args() will give you an object from which you can access the
arguments by name using the long option name bar the dashes.
|
Foreign key not available on object
Question: Very very beginner question that puzzles me. I have problems showing the
foreign key ArtWorkImages in my template, so i wanted to debug it in the view,
but the foreign key ArtworkImage is not available on Artwork:
my model:
from django.db import models
class Artwork(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
class ArtworkImage(models.Model):
property = models.ForeignKey(Artwork, related_name='images')
image = models.ImageField(upload_to = "images/")
the view:
from django.shortcuts import render
from erikheide.models import Artwork
from erikheide.models import ArtworkImage
def index(request):
artworks = Artwork.objects.all()[:5]
artwork = artworks[0]
images = artwork.artworkimage_set.all()
context = {'latest_poll_list': artworks}
return render(request, 'index.html', context)
the error:
> Traceback (most recent call last): File
> "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py",
> line 115, in get_response
> response = callback(request, *callback_args, **callback_kwargs) File "/home/fhp/Hentede filer/tastypie/django15/erikheide/views.py",
> line 13, in index
> images = artwork.artworkimage_set.all() AttributeError: 'Artwork' object has no attribute 'artworkimage_set'
The template that did not work (no images turn up)
{% if artworks %}
<ul>
{% for artwork in artworks %}
<li><a href="{{ artwork.title }}/">{{ artwork.body}}</a></li>
{% for image in artwork.images_set.all %}
<img src="{{ image.image.url }}">
{% endfor %}
{% endfor %}
</ul>
{% else %}
<p>No artworks are available.</p>
{% endif %}
Answer: You have defined a
[`related_name`](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name)
on the `ForeignKey` field, you need to use it to follow the relationship.
Replace:
images = artwork.artworkimage_set.all()
with:
images = artwork.images.all()
Also see: [What is related_name used for in
Django?](http://stackoverflow.com/questions/2642613/what-is-related-name-used-
for-in-django)
|
python what is the import for threading?
Question: I want to run some python code every 120 seconds.
I tried this:
class AppServerSvc :
def f(self):
# call f() again in 120 seconds
spider = FantasySerieaSpider()
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run() # the script will block here until the spider_closed signal was sent
threading.Timer(120, f).start()
if __name__ == '__main__':
AppServerSvc().f();
I got the `threading is not defined` error
This are my imports:
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from FantasySeriea.spiders.spider import FantasySerieaSpider
from scrapy.utils.project import get_project_settings
from threading import Thread
Answer: rather than (or in addition to?):
from threading import Thread
you want:
import threading
|
Break python long into limbs
Question: I'm trying to write an implementation of [Montgomery
multiplication](https://en.wikipedia.org/wiki/Montgomery_reduction#Modular_multiplication)
in Python and I need an equivalent to GMP's
[`mpz_getlimbn()`](https://gmplib.org/manual/Integer-Special-Functions.html)
for Python longs but I can't for the life of me seem to find one.
Any help would be greatly appreciated.
**Edit**
I've implemented the following but I get index out of range errors for limbs
which don't occur in GMP.
def unpack(x, b):
if gmpy2:
return [long(x) for x in gmpy2.unpack(gmpy2.mpz(x), b)]
b = 2 ** b
r = []
while x:
x, temp = divmod(x, b)
r.append(temp)
return r
Answer: I modified your `unpack()` and it appears to work for me. If you still get an
error, please post the full error.
>>> import gmpy2
>>>
>>> def unpack(x, b):
... try:
... return [x for x in gmpy2.unpack(gmpy2.mpz(x), b)]
... except NameError:
... b = 2 ** b
... r = []
... while x:
... x, temp = divmod(x, b)
... r.append(temp)
... return r
...
>>> unpack(123456**7, 15)
[mpz(0), mpz(0), mpz(4096), mpz(25855), mpz(24508), mpz(31925), mpz(15111), mpz(10775)]
>>> del(gmpy2)
>>> unpack(123456**7, 15)
[0, 0, 4096, 25855, 24508, 31925, 15111, 10775]
When using `gmpy2`, I left the results as `mpz` to show that `gmpy2` was used.
Python's long integer type uses limbs that store either 15 or 30 bits.
`sys.int_info` will provide the specifics for your system.
BTW, I maintain `gmpy2` and it's nice to see someone use `unpack()`.
|
c++ error on a python progam
Question: in my python program a c++ error pops up. i know that my program is glitchy
and has bugs but why is there a error with c++
Assertion failed!
Program: C:\Python33\pythonw.exe
File: .-\--\audio\mpegtoraw.cpp
Line: 505
Expression: audio->rawdatawriteoffset > len
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts
(Press Retry to debug the application - JIT must be enabled)
* * *
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BGC = (0, 0, 0)
FPS = 80
PLAYERMOVERATE = 5
countBy = 10
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitShoot(playerRect, shoot):
if playerRect.colliderect(shoot):
return True
return False
def baddieHasHitShoot(baddieRect, shoot):
if baddieRect.colliderect(shoot):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None,48)
mainClock = pygame.time.Clock()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Mothers Day')
pygame.mouse.set_visible(True)
pygame.display.set_icon(pygame.image.load('gameicon.gif'))
gameStartSound = pygame.mixer.Sound('gamestart.wav')
gameOverSound = pygame.mixer.Sound('gameend.wav')
pygame.mixer.music.load('background.mp3')
playerImage = pygame.image.load('starship.bmp')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('enemy.bmp')
baddieRect = baddieImage.get_rect()
shootImage = pygame.image.load('shoot.bmp')
shootRect = shootImage.get_rect()
drawText('Star Trek', font, screen, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3.75) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
def fire(shoot):
shootRect.topleft = ((playerRect / 2), 101)
shootRect.move_ip(5, 1)
topScore = 10000
while True:
SS = []
score = 10000
playerRect.topleft = (0, 100)
moveUp = moveDown = False
pygame.mixer.music.play(-1, 0.0)
while True:
score -= countBy
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == ord(' '):
fire
if event.key == K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord(' '):
fire
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Top Score: %s' % (topScore), font, screen, 10, 40)
screen.blit(playerImage, playerRect)
screen.blit(shootImage, shootRect)
screen.blit(baddieImage, baddieRect)
pygame.display.update()
if playerHasHitShoot(playerRect, baddieRect):
score = 0
break
if baddieHasHitShoot(baddieRect, shoot):
if score > topScore:
score = topscore
break
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
Answer: This appears to be a bug in the Python music player, it has trouble converting
some MP3 files. The only solution appears to be to try a different file.
|
Python handling username and password for URL
Question: Messing with Python and I'm trying to use this
<https://updates.opendns.com/nic/update?hostname=>, when you got to the URL it
will prompt a username and password. I've been looking around and I found
something about password managers, so I came up with this:
urll = "http://url.com"
username = "username"
password = "password"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, urll, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
urllib2 = urllib2.build_opener(authhandler)
pagehandle = urllib.urlopen(urll)
print (pagehandle.read())
This all works, but it's prompting the username and password via the command
line, requiring the user's interaction. I want it to automatically enter those
values. What am I doing wrong?
Answer: You could use [requests](http://docs.python-requests.org/en/latest/) instead.
The code is as simple as:
import requests
url = 'https://updates.opendns.com/nic/update?hostname='
username = 'username'
password = 'password'
print(requests.get(url, auth=(username, password)).content)
|
Python Change Directory Google App Engine
Question: I have my webapp written in Python running on Google App Engine; so far only
testing in my localhost. My script needs to read text files located in various
directories. So in my Python script I would simply use
os.chdir("./"+subdirectory_name) and then start opening and reading the files
and using the text for analysis. However I cannot do that when trying to move
it over to App Engine.
I assume I need to make some sort of changes to app.yaml but I'm stuck after
that. Can anyone walk me through this somewhat thoroughly?
From the answer below, I was able to fix this part, I have a followup question
about the app.yaml structure though. I have my folder set up like the
following, and I'm wondering what I need to put in my app.yaml file to make it
work when I deploy the project (it works perfectly on localhost right now).
Main_Folder:
* python_my_app.py
* app.yaml
* text_file1
* text_file2
* text_file3
* subfolder1_with_10_text_files_inside
* subfolder2_with_10_text_files_inside
* subfolder3_with_10_text_files_inside
...how do I specify this structure in my app.yaml and do I need to change
anything in my code if it works right now on localhost?
Answer: You don't _need_ to change your working directory at all to read files. Use
absolute paths instead.
Use the current file location as the starting point, and resolve all relative
paths from there:
import os.path
HERE = os.path.dirname(os.path.abspath(__file__))
somefile = os.path.abspath(os.path.join(HERE, 'subfolder1_with_10_text_files_inside /somefile.txt'))
If you want to be able to read _static_ files, do remember to set the
`application_readable` flag on these, as Google will otherwise only upload
them to their content delivery network, not to the app engine.
|
Miller-Rabin code - can't find any mistakes?
Question: I used some code taken from Rosetta Code. I renamed a few things but I didn't
really change anything.
import random
def is_probable_prime(n, num_trials = 5):
assert n >= 2
if n == 2:
return True
if n % 2 == 0:
return False
s = 0
d = n-1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2**s * d == n-1)
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
It pretty closely matches some psuedocode. However, when I test the number
>
> 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901
it returns `False`. Other (python and java) implementations of Miller-Rabin
return `True` for probable prime. After some testing, `try_composite` returns
`True` after only `2` rounds! I would really like to know any error, I'm
guessing a mis-indent or some feature I don't know about.
Answer: In your `try_composite` function, the `for` loop should be `for i in
range(1,s)`. Do not test the case where `i` is zero.
**EDIT:** Also, you are missing a test in your `try_composite` function. Here
is my version of the pseudocode:
def isPrime(n, k=5):
def isComposite(s, d):
x = pow(randrange(2,n-1), d, n)
if x == 1 or x == n-1: return False
for r in range(1, s):
x = pow(x, 2, n)
if x == 1: return True
if x == n-1: return False
return True
if n < 2: return False
for p in [2, 3, 5, 7, 11, 13, 17]:
if n % p == 0: return n == p
s, d = 0, n-1
while d % 2 == 0: s, d = s+1, d/2
for i in range(k):
if isComposite(s, d): return False
return True
It's too bad that Python doesn't allow labels on `break` or `continue`
statements. Here's pseudocode for a much prettier version of the function:
function isPrime(n, k=5)
if n < 2 then return False
for p in [2,3,5,7,11,13,17,19,23,29]
if n % p == 0 then return n == p
s, d = 0, n-1
while d % 2 == 0
s, d = s+1, d/2
for i from 0 to k
x = powerMod(randint(2, n-1), d, n)
if x == 1 or x == n-1 then next i
for r from 1 to s
x = (x * x) % n
if x == 1 then return False
if x == n-1 then next i
return False
return True
Notice the two places where the control flow goes to `next i`. There is no
good way to write that in Python. One choice uses an extra boolean variable
that can be set and tested to determine when to bypass the rest of the code.
The other choice, which I took above, is to write a local function to perform
the task. This "loop-and-a-half" idiom is convenient and useful; it was
proposed in [PEP 3136](http://legacy.python.org/dev/peps/pep-3136/) and
[rejected](https://mail.python.org/pipermail/python-3000/2007-July/008663.html)
by Guido.
|
Numpy and matplotlib Import errors
Question: I have installed matplotlib 1.2.0 and numpy 1.6.2 for python 2.7.4 And I get
the below import errors when i try to run my code.
Traceback (most recent call last):
File "D:\Python\IQ_polar.py", line 16, in <module>
from matplotlib import pyplot
File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 151, in <module>
from matplotlib.rcsetup import (defaultParams,
File "C:\Python27\lib\site-packages\matplotlib\rcsetup.py", line 20, in <module>
from matplotlib.colors import is_color_like
File "C:\Python27\lib\site-packages\matplotlib\colors.py", line 52, in <module>
import numpy as np
File "C:\Python27\lib\site-packages\numpy\__init__.py", line 137, in <module>
import add_newdocs
File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 4, in <module>
from type_check import *
File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 8, in <module>
import numerictypes as nt
File "C:\Python27\lib\site-packages\numpy\core\numerictypes.py", line 429, in <module>
_set_up_aliases()
File "C:\Python27\lib\site-packages\numpy\core\numerictypes.py", line 412, in _set_up_aliases
allTypes[alias] = allTypes[t]
KeyError: 'timedelta'
Part of the code that is generating this error is
import math
import struct
import binascii
from ast import literal_eval
import matplotlib.pyplot as plt
from numpy.fft import fft, fftfreq
import scipy as sp
I feel its something to do with the numpy package. What am i missing?!
Answer: Python and python packages downloaded from the site mentioned below work just
fine! <https://www.enthought.com/downloads/>
|
Removing and updating lines in a text file - Python
Question: I'm learning Python and as a learning project, I'm developing a twitter bot.
I'm using Python 3. I use the following lines for tweets.
> What is Bruce Lee’s favorite drink? Wataaaaah!
> The dyslexic devil worshipper sold his soul to Santa.
> You kill vegetarian vampires with a steak to the heart.
> There was a prison break and I saw a midget climb up the fence. As he jumped
> down he sneered at me and I thought, well that’s a little condescending.
This is my code that uses Twython to tweet:
from twython import Twython, TwythonError
import time
APP_KEY = '##########' # Customer Key here
APP_SECRET = '#############' # Customer secret here
OAUTH_TOKEN = '###############' # Access Token here
OAUTH_TOKEN_SECRET = '################' # Access Token Secret here
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
with open('jokes.txt', 'r+') as file:
buff = file.readlines()
for line in buff:
if len(line)<140:
print ("Tweeting...")
twitter.update_status(status=line)
time.sleep(3)
with open ('jokes.txt', 'r+') as file:
buff.remove(line)
file.writelines(buff)
else:
with open ('jokes.txt', 'r+') as file:
buff.remove(line)
file.writelines(buff)
print ("Skipped line - Char Length Violation")
continue
except TwythonError as e:
print (e)
I wanted to skip the lines that has over 140 characters with a message on the
console `Skipped line - Char Length Violation` and then remove that particular
line and update the file. The script successfully tweets by ignoring the line,
but fails printing the console message. It also fails to remove the line from
the text file.
I have no idea why the third line `You kill vegetarian vampires with a steak
to the heart.`was skipped.
What's wrong with my code and why my text file looks like this after I run the
script:
> The dyslexic devil worshipper sold his soul to Santa.
> There was a prison break and I saw a midget climb up the fence. As he
> jumped down he sneered at me and I thought, well that’s a little
> condescending.d at me and I thought, well that’s a little condescending.nd I
> thought, well that’s a little condescending.
Answer:
file.close()
seems to be misplace under the `with ... as file:` block. The advantage of
`with` is that you don't need to do this bookkeeping.
In the `else` block the `file` object is close, so `file.writelines()` should
raise an exception.
As far as I can see is `buff` a string and therefore immutable. You might want
to try `buff = buff.remove(...)`, but does it even have the `remove` method?
|
Create a certain triangle with stars
Question: I'm using python IDE wing version 4.1
I'm trying to write a function with only 1 input which will be an integer and
return the next shape of stars:
*
**
***
I tried using the following code but it gave another shape:
from math import *
from string import *
def tri_1(n):
x=n*'*'
i=0
while i<5:
x=i*'*'
i=i+1
print x
n=input()
tri_1(n)
Answer: You need to think more carefully about what the algorithm should do. For each
integer in the range `1` to `n` inclusive you want to print `n-1` spaces
followed by `n` asterisks, so what is the hard-coded `5` doing there? Why
don't you have _any_ spaces? Given that you know how many times you will loop,
why use `while` rather than `for`?
The most efficient way to achieve this is using the built-in string method
[`rjust`](https://docs.python.org/2/library/stdtypes.html#str.rjust), which
pads the supplied string with spaces:
def tri_1(n):
for i in range(1, n+1):
print(str.rjust("*"*i, n))
|
Change list in python
Question: How can make several lists like this:
['The Lord of the Rings: The Fellowship of the Ring (2001)']
['The Lord of the Rings: The Two Towers (2002)']
['"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}']
Into one list like this:
['The Lord of the Rings: The Fellowship of the Ring (2001)',
'The Lord of the Rings: The Two Towers (2002)',
'"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}']
I have tried this:
x = open("ratings.list.txt","r")
movread = x.readlines()
x.close()
#s = raw_input('Search: ').lower()
for ns in movread:
if 'the lord of the' in ns.lower():
d = re.split('\s+',ns,4)
Title = d[4].rstrip()
Rating= d[3]
lists = [Title]
combined = [item for sublist in lists for item in sublist]
print combined
But its gives me this output:
['T', 'h', 'e', ' ', 'L', 'o', 'r', 'd', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 'R', 'i', 'n', 'g', 's', ':', ' ', 'T', 'h', 'e', ' ', 'R', 'e', 't', 'u', 'r', 'n', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 'K', 'i', 'n', 'g', ' ', '(', '2', '0', '0', '3', ')']
['T', 'h', 'e', ' ', 'L', 'o', 'r', 'd', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 'R', 'i', 'n', 'g', 's', ':', ' ', 'T', 'h', 'e', ' ', 'F', 'e', 'l', 'l', 'o', 'w', 's', 'h', 'i', 'p', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 'R', 'i', 'n', 'g', ' ', '(', '2', '0', '0', '1', ')']
Thanks for the help guys :D
UPDATE
The file look like this (its a list of all the movies on IMDB, so the size is
huge):
New Distribution Votes Rank Title
0000000125 1196672 9.2 The Shawshank Redemption (1994)
0000000125 829707 9.2 The Godfather (1972)
0000000124 547511 9.0 The Godfather: Part II (1974)
0000000124 1160800 8.9 The Dark Knight (2008)
0000000124 920221 8.9 Pulp Fiction (1994)
0000000124 358790 8.9 Il buono, il brutto, il cattivo. (1966)
0000000123 605734 8.9 Schindler's List (1993)
0000000133 297241 8.9 12 Angry Men (1957)
0000000124 854409 8.9 The Lord of the Rings: The Return of the King (2003)
0000000123 910109 8.8 Fight Club (1999)
0000000124 880827 8.8 The Lord of the Rings: The Fellowship of the Ring (2001)
0000000123 568723 8.8 Star Wars: Episode V - The Empire Strikes Back (1980)
0000000124 953140 8.7 Inception (2010)
Answer: You want to
[movie[0] for movie in movies]
An example script would look like this
import pprint
movies = [
['The Lord of the Rings: The Fellowship of the Ring (2001)'],
['The Lord of the Rings: The Two Towers (2002)'],
['"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}'],
]
pprint.pprint([movie[0] for movie in movies], indent=4)
This outputs
[ 'The Lord of the Rings: The Fellowship of the Ring (2001)',
'The Lord of the Rings: The Two Towers (2002)',
'"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}']
The `movies` list, would be populated by you when you read in the file.
|
Automate compilation of protobuf specs into python classes in setup.py
Question: I have a python project that uses google protobufs as a message format for
communicating over the network. Generating python files from the .proto files
is straight-forward using the `protoc` program. How can I configure my
`setup.py` file for the project so that it automatically calls the `protoc`
command?
Answer: In a similar situation, I ended up with this code (setup.py, but written in a
way to allow extraction into some external Python module for reuse). Note that
I took the generate_proto function and several ideas from the setup.py file of
the protobuf source distribution.
from __future__ import print_function
import os
import shutil
import subprocess
import sys
from distutils.command.build_py import build_py as _build_py
from distutils.command.clean import clean as _clean
from distutils.debug import DEBUG
from distutils.dist import Distribution
from distutils.spawn import find_executable
from nose.commands import nosetests as _nosetests
from setuptools import setup
PROTO_FILES = [
'goobuntu/proto/hoststatus.proto',
]
CLEANUP_SUFFIXES = [
# filepath suffixes of files to remove on "clean" subcommand
'_pb2.py',
'.pyc',
'.so',
'.o',
'dependency_links.txt',
'entry_points.txt',
'PKG-INFO',
'top_level.txt',
'SOURCES.txt',
'.coverage',
'protobuf/compiler/__init__.py',
]
CLEANUP_DIRECTORIES = [ # subdirectories to remove on "clean" subcommand
# 'build' # Note: the build subdirectory is removed if --all is set.
'html-coverage',
]
if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
protoc = os.environ['PROTOC']
else:
protoc = find_executable('protoc')
def generate_proto(source):
"""Invoke Protocol Compiler to generate python from given source .proto."""
if not os.path.exists(source):
sys.stderr.write('Can\'t find required file: %s\n' % source)
sys.exit(1)
output = source.replace('.proto', '_pb2.py')
if (not os.path.exists(output) or
(os.path.getmtime(source) > os.path.getmtime(output))):
if DEBUG:
print('Generating %s' % output)
if protoc is None:
sys.stderr.write(
'protoc not found. Is protobuf-compiler installed? \n'
'Alternatively, you can point the PROTOC environment variable at a '
'local version.')
sys.exit(1)
protoc_command = [protoc, '-I.', '--python_out=.', source]
if subprocess.call(protoc_command) != 0:
sys.exit(1)
class MyDistribution(Distribution):
# Helper class to add the ability to set a few extra arguments
# in setup():
# protofiles : Protocol buffer definitions that need compiling
# cleansuffixes : Filename suffixes (might be full names) to remove when
# "clean" is called
# cleandirectories : Directories to remove during cleanup
# Also, the class sets the clean, build_py, test and nosetests cmdclass
# options to defaults that compile protobufs, implement test as nosetests
# and enables the nosetests command as well as using our cleanup class.
def __init__(self, attrs=None):
self.protofiles = [] # default to no protobuf files
self.cleansuffixes = ['_pb2.py', '.pyc'] # default to clean generated files
self.cleandirectories = ['html-coverage'] # clean out coverage directory
cmdclass = attrs.get('cmdclass')
if not cmdclass:
cmdclass = {}
# These should actually modify attrs['cmdclass'], as we assigned the
# mutable dict to cmdclass without copying it.
if 'nosetests' not in cmdclass:
cmdclass['nosetests'] = MyNosetests
if 'test' not in cmdclass:
cmdclass['test'] = MyNosetests
if 'build_py' not in cmdclass:
cmdclass['build_py'] = MyBuildPy
if 'clean' not in cmdclass:
cmdclass['clean'] = MyClean
attrs['cmdclass'] = cmdclass
# call parent __init__ in old style class
Distribution.__init__(self, attrs)
class MyClean(_clean):
def run(self):
try:
cleandirectories = self.distribution.cleandirectories
except AttributeError:
sys.stderr.write(
'Error: cleandirectories not defined. MyDistribution not used?')
sys.exit(1)
try:
cleansuffixes = self.distribution.cleansuffixes
except AttributeError:
sys.stderr.write(
'Error: cleansuffixes not defined. MyDistribution not used?')
sys.exit(1)
# Remove build and html-coverage directories if they exist
for directory in cleandirectories:
if os.path.exists(directory):
if DEBUG:
print('Removing directory: "{}"'.format(directory))
shutil.rmtree(directory)
# Delete generated files in code tree.
for dirpath, _, filenames in os.walk('.'):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
for i in cleansuffixes:
if filepath.endswith(i):
if DEBUG:
print('Removing file: "{}"'.format(filepath))
os.remove(filepath)
# _clean is an old-style class, so super() doesn't work
_clean.run(self)
class MyBuildPy(_build_py):
def run(self):
try:
protofiles = self.distribution.protofiles
except AttributeError:
sys.stderr.write(
'Error: protofiles not defined. MyDistribution not used?')
sys.exit(1)
for proto in protofiles:
generate_proto(proto)
# _build_py is an old-style class, so super() doesn't work
_build_py.run(self)
class MyNosetests(_nosetests):
def run(self):
try:
protofiles = self.distribution.protofiles
except AttributeError:
sys.stderr.write(
'Error: protofiles not defined. MyDistribution not used?')
for proto in protofiles:
generate_proto(proto)
# _nosetests is an old-style class, so super() doesn't work
_nosetests.run(self)
setup(
# MyDistribution automatically enables several extensions, including
# the compilation of protobuf files.
distclass=MyDistribution,
...
tests_require=['nose'],
protofiles=PROTO_FILES,
cleansuffixes=CLEANUP_SUFFIXES,
cleandirectories=CLEANUP_DIRECTORIES,
)
|
Python client server to send a file Beginner Error
Question: I am trying to do simple code to send file from the client to the server after
saving in t some data. I am a beginner so I can't figure where the problem is
or what is the missing function or line in my code
The Server :
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 1024
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:
break
fileREC=open (data , 'rb')
The Client
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
TextFile= open ("TextFile","w")
TextFile.write("Here is the file")
TextFile.write("Writing data")
TextFile.close()
f=open (TextFile , 'wb')
print ("Writing the file to binart ")
client_socket .send(f)
print ("Data Sent")
The Error
ERROR:Traceback (most recent call last):
File "tenmay.py", line 5, in <module>
client_socket.connect(("192.168.1.4", 8000))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Answer: Send the contents of the file not the filehandle:
f=open ("TextFile", 'rb')
client_socket.send(f.read())
The second time the client runs the server is waiting to recv data because the
accept() command is outside of the loop.
The client could repeatedly send data from a loop, but not if the program ends
and has to be restarted.
|
The PyDev plugin can not find python 3.4
Question: I have been using eclipse 3.8+PyDev+python 3.3 on ubuntu 13. Recently I
upgraded ubuntu to 14.04. It seems that ubuntu 14.04 comes with new python
3.4, so, during upgrading, the old python 3.3 is removed and new python 3.4 is
installed. Then, the PyDev plugin of my eclipse can not find the python 3.3 in
its original dir and an error is report, as well as many red crossings, as the
image below shows.

But the installation of Python 3.4 is correct because I can import pickle or
random modules without difficulty in IDLE which uses python 3.4:

I have already upgraded the PyDev to latest 3.4.1. Could you please tell me
how to reconfigure Python interpreter (including how to locate it) in eclipse
so that PyDev can correctly locate where the Python 3.4 is? Thank you very
much.
Answer: OK, I have solved the problem by myself:
(1)Right click the project name, choose "Properties" in the popup menu. This
will open the "Properties for" dialog box.
(2) In this box, select "PyDev-Interpreter/Grammar" item on the left panel and
click the "click here to configure an interpreter not listed" link on the
right.
(3) In the popup "Python Interpreters" dialog box, click "New..." button on
the right of the window and type in the path to python 3.4 executable. In my
system, it's `/usr/bin/python3.4`.
(4) Then click OK and wait for the eclipse to finish its configuration work.
At this point the most important part of reconfiguration is done. Then move
the new Python3.4 to the top, remove python 3.3 interpreter if you want, and
...
(5) Don't forget to restart eclipse. Tata ...
Some 3rd party python packages such as pymongo are still problematic. But they
are not within the scope of discussion of this thread. That's it.
|
Setting an ID3 comment using EyeD3 in Python
Question: I have the following python script in a folder with a mp3 file:
import os
import eyed3
def track(file):
tag = eyed3.load(file)
tag.tag.comment = u"teststring"
tag.tag.genre = u"Pop"
tag.tag.save()
for fn in os.listdir('.'):
print fn[-3:]
if fn[-3:] == 'mp3':
track(fn)
The 'genre' is set or changed correctly, but my comment is just adding some
garbage. I added a 'Test' in winamp to the comment, and after I run my script
and output the ID3 info from the commandline, I see this:
ys3(01).mp3 [ 3.86 MB ]
-------------------------------------------------------------------------------
Time: 03:02 MPEG1, Layer III [ ~177 kb/s @ 48000 Hz - Joint stereo ]
-------------------------------------------------------------------------------
ID3 v2.3:
title: WANDERERS FROM YS - ?
artist:
album:
track: genre: Pop (id 13)
Comment: [Description: ] [Lang: eng]
Test
Comment: [Description: ÿþÿ] [Lang: eng]
þ
-------------------------------------------------------------------------------
Am I passing the 'Comment' in the wrong way?
Answer: I don't pretend to understand why this is the way it is, but check out how
comments are set in [the handy example
file](https://bitbucket.org/nicfit/eyed3/src/5a4ab5730ced8d5d0e21440c7c6ff212f923f9d7/examples/tag_example.py?at=default#cl-42):
from eyed3.id3 import Tag
t = Tag()
t.comments.set(u"Gritty, yo!")
I believe this has to do with comments being placed into frames, but others
may have to chime in with corrections on that. Note that this will fail unless
you pass it unicode.
This works on version:
↪ eyeD3 --version
eyeD3 0.7.4-beta (C) Copyright 2002-2013 Travis Shirk
|
Run multiple python files at same time
Question: I understand that we can use Python `multiprocessing` module and will import
`Process` for this.
But what will be our Python code, suppose we want to execute 2 files like
`a.py`, `b.py` at same time.
I was expecting a Python script to include the above and not running files
from two command prompts.
Below is the framework:
import multiprocessing
def worker(file):
#your subprocess code
if __name__ == '__main__':
files = ["path/to/file1.py","path/to/file2.py","path/to/file3.py"]
for i in files:
p = multiprocessing.Process(target=worker(i))
p.start()
What will be subprocess code ?
Answer: Just open two command prompts(in windows) or terminals (in other OS'). Then
run each of the files in one window.
|
Streaming sockets from ProcessPoolExecutor
Question: I'm trying to create a Python application in which one process (process 'A')
receives a request and puts it into a ProcessPool (from concurrent.futures).
In handling this request, a message may need to passed to a second process
(process 'B'). I'm using tornado's iostream module to help wrap the
connections and get responses.
Process A is failing to successfully connect to process B from within the
ProcessPool execution. Where am I going wrong?
The client, which makes the initial request to process A:
#!/usr/bin/env python
import socket
import tornado.iostream
import tornado.ioloop
def print_message ( data ):
print 'client received', data
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM, 0)
stream = tornado.iostream.IOStream(s)
stream.connect(('localhost',2001))
stream.read_until('\0',print_message)
stream.write('test message\0')
tornado.ioloop.IOLoop().instance().start()
Process A, that received the initial request:
#!/usr/bin/env python
import tornado.ioloop
import tornado.tcpserver
import tornado.iostream
import socket
import concurrent.futures
import functools
def handle_request ( data ):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
out_stream = tornado.iostream.IOStream(s)
out_stream.connect(('localhost',2002))
future = out_stream.read_until('\0')
out_stream.write(data+'\0')
return future.result()
class server_a (tornado.tcpserver.TCPServer):
def return_response ( self, in_stream, future ):
in_stream.write(future.result()+'\0')
def handle_read ( self, in_stream, data ):
future = self.executor.submit(handle_request,data)
future.add_done_callback(functools.partial(self.return_response,in_stream))
def handle_stream ( self, in_stream, address ):
in_stream.read_until('\0',functools.partial(self.handle_read,in_stream))
def __init__ ( self ):
self.executor = concurrent.futures.ProcessPoolExecutor()
tornado.tcpserver.TCPServer.__init__(self)
server = server_a()
server.bind(2001)
server.start(0)
tornado.ioloop.IOLoop().instance().start()
Process B, that should receive the relayed request from Process A:
#!/usr/bin/env python
import tornado.ioloop
import tornado.tcpserver
import functools
class server_b (tornado.tcpserver.TCPServer):
def handle_read ( self, in_stream, data ):
in_stream.write('server B read'+data+'\0')
def handle_stream ( self, in_stream, address ):
in_stream.read_until('\0',functools.partial(self.handle_read,in_stream))
server = server_b()
server.bind(2002)
server.start(0)
tornado.ioloop.IOLoop().instance().start()
And finally, the error returned by Process A, which is raised during the
'read_until' method:
ERROR:concurrent.futures:exception calling callback for <Future at 0x10654b890 state=finished raised OSError>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/concurrent/futures/_base.py", line 299, in _invoke_callbacks
callback(self)
File "./a.py", line 26, in return_response
in_stream.write(future.result()+'\0')
File "/usr/local/lib/python2.7/site-packages/concurrent/futures/_base.py", line 397, in result
return self.__get_result()
File "/usr/local/lib/python2.7/site-packages/concurrent/futures/_base.py", line 356, in __get_result
raise self._exception
OSError: [Errno 9] Bad file descriptor
Answer: I'm not 100% sure why you're getting this "Bad file descriptor" error
(concurrent.futures unfortunately lost backtrace information when it was
backported to 2.7), but there is no IOLoop running in the
ProcessPoolExecutor's worker processes, so you won't be able to use Tornado
constructs like IOStream in this context (unless you spin up a new IOLoop for
each task, but that may not make much sense unless you need compatibility with
other asynchronous libraries).
I'm also not sure if it works to mix tornado's multi-process mode and
ProcessPoolExecutor in this way. I think you may need to move the
initialization of the ProcessPoolExecutor until after the start(0) call.
|
How to import a python module from a relative path?
Question: I've got the following file structure: 
I'm trying to initialize some objects in `main.py` that belong to modules in
the `Listener`, `Parser` and `Configurations` folders.
I understand I can't just write `import listener` since it's not in the same
path. What simple ways are there for the imports to work without adding the
paths to the `PYTHONPATH` env variable? Is there a way to make it work on any
machine "out of the box" without the need to add the paths to `PYTHONPATH` or
any solution like that? Preferably something with a relative path like in C++?
Answer: Possible duplicate: [Importing from a relative path in
Python](http://stackoverflow.com/questions/7505988/importing-from-a-relative-
path-in-python)
In short, you need to programmatically define `PYTHONPATH` in `main.py`,
something like:
import sys, os
sys.path.append(os.path.dirname(__file__))
This implicitly adds current directory to `PYTHONPATH`. Rest of the part is
straightforward
Create `__init__.py` file in each of the directories. After that, each of the
modules can be imported as `from Listener import ...` or `from Misc import
...` etc.
The approach works 'out of box' without redefining any environmental variable.
|
Alert message on Google App Engine for Python
Question: I want to pop an alert message for error handling on an app that runs via
Google App Engine for Python.
I tried this already but non worked:
`from Tkinter import * msg = Message(text="Please, make sure you fill out the
boxes and agree with the terms") msg.config(bg='green', font=('times', 16))
msg.pack() mainloop()`
AND
import win32api
win32api.MessageBox(0, 'hello', 'title')
I am guessing the Google App Engine has its own way of handling this task but
I can't figure out how.
Thank you!
Answer: You can't do that. The GAE server suppose to run headless, so you can't
display a popup in your host machine. If you use windows to launch de dev
server, simply use the log buton from the GUI or launch your dev server from
the command line.
To generate a debug log from your application you can simply see this post.
[Google app engine logging in dev
consol](http://stackoverflow.com/questions/3128393/google-app-engine-logging-
in-dev-console)
In production your application have a full admin panel with a lot of
possibilities and a logging pannelto see all messages from your app.
|
matplotlib 3d scatter from 2d numpy array vertices error
Question: I'm stumped as to why this is not working. I am pulling a bunch of floating
point data in to a numpy array from a csv file, and I just want to create a 3d
scatter plot based from 3 of the columns in the array.
#import data from the csv file
data = np.genfromtxt('data.csv', delimiter=',', dtype=float, skiprows=1)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(data[:,1], data[:,2], data[:,7], c='r', marker='0')
plt.show()
every time i get an assertion error:
/usr/lib/pymodules/python2.7/matplotlib/path.pyc in __init__(self, vertices, codes, _interpolation_steps, closed)
127 codes[-1] = self.CLOSEPOLY
128
--> 129 assert vertices.ndim == 2
130 assert vertices.shape[1] == 2
131
AssertionError:
I have... just figured it out, but i'll post this any way because that is the
single most useless error message i have ever encountered. the problem was
here:
ax.scatter(data[:,1], data[:,2], data[:,7], c='r', marker='0')
marker='0' is invalid, i meant to hit marker='o', once fixed it works just
fine.
Answer: You can use the `scatter3D()` method of the `Axes3DSubplot` object:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter3D(data[:,1], data[:,2], data[:,7], c='r', marker='0')
|
Python: MySQL-Query fails
Question: In general, I am familiar with MySQL but not with Python. I try to generate
.py script which inserts an user with a hashed password into a mysql-database
of the radius-server.
That's my script so far:
#!/usr/bin/python2.7
import sys
import MySQLdb
from passlib.hash import django_pbkdf2_sha256 as cryptohandler
def adduser(username, password_plain):
password = cryptohandler.encrypt(password_plain)
conn = MySQLdb.connect(host="localhost", port=3306, user="radius", passwd="radpass", db="radius")
cursor = conn.cursor()
if cursor.execute("SELECT op FROM radcheck WHERE username = %s", (username)):
print 'FEHLER: User existiert bereits und kann daher nicht angelegt werden.'
sys.exit(1)
else:
try:
cursor.execute("INSERT INTO radcheck(username, attribute, op, value) VALUES(%s, 'Password', ':=', %s)", (username, password))
conn.commit()
print 'OK user '+ username +' successfully added with hash'+ password
sys.exit(0)
except:
conn.rollback()
print 'FEHLER query failed'
sys.exit(1)
def main():
adduser(sys.argv[1], sys.argv[2])
main()
The output is always "FEHLER query failed", the first query which looks up if
an username is existing works fine.
The radcheck table:
id int(11) unsigned Null=No Key=Pri Default=Null Extra=auto_increment
username varchar(64) Null=No Key=Mul
attribute varchar(64) Null=No
op char(2) Null=No Default="=="
value varchar(253) Null=No
Executing the query in the mysql-command-line works fine.
Where is the error in my script? I thought it may be a too long hash, but the
hash is only < 100 chars long. (But contains special characters such as the
dollar $). Additionally I'd appreciate help how to debug python-sql-scripts in
general!
Answer: The issue here is not your MySQL code but it is this try/except block:
try:
cursor.execute("INSERT INTO radcheck(username, attribute, op, value) VALUES(%s, 'Password', ':=', %s)", (username, password))
conn.commit()
print 'OK user '+ username +' successfully added with hash'+ password
sys.exit(0)
except:
conn.rollback()
print 'FEHLER query failed'
sys.exit(1)
When you call `sys.exit(0)`, it raises an exception called `SystemExit`. Since
a bare `except:` catch statement catches `SystemExit`, this block will always
be executed when you call `sys.exit(0)`. To prevent this from happening,
change your `except:` catch to:
except Exception as e:
conn.rollback()
print 'FEHLER query failed'
sys.exit(1)
Even better is if you catch only MySQL errors with:
except MySQLdb.Error as e:
conn.rollback()
print 'FEHLER query failed'
sys.exit(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.