text
stringlengths 226
34.5k
|
---|
Python PIL has no attribute 'Image'
Question: I'm using python2.6 and got a problem this morning. It said 'module' has no
attribute 'Image'. Here is my input. Why the first time I can not use
PIL.Image?
>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
Answer: PIL's `__init__.py` is just an empty stub as is common. It won't magically
import anything by itself.
When you do `from PIL import Image` it looks in the PIL package and finds the
file Image.py and imports that. When you do `PIL.Image` you are actually doing
an attribute lookup on the PIL module (which is just an empty stub unless you
explicitly import stuff).
In fact, importing a module usually **doesn't** import submodules. `os.path`
is a famous exception, since the os module is magic.
More info:
[The Image Module](http://effbot.org/imagingbook/image.htm)
|
Multipart form encoding file upload in Python 3
Question: I was wondering if it was possible to post to a form with
`enctype='multipart/form-data'` in Python 3. I looked around and could only
find things for Python 2 (such as poster).
Answer: Use [requests](http://docs.python-requests.org/en/latest/), it supports python
3.
import requests
response = requests.post('http://httpbin.org/post', files={'file': open('filename','rb')})
print(response.content)
|
Packaging and distributing a python (for windows) application for client side
Question: Lets say I have developed a desktop application using python for windows
users. I want to distribute this application.
So what is the standard process of packaging and distributing? I want the
setup to be installed other .msi or .exe setups are installed.
Answer: [PyInstaller](http://www.pyinstaller.org/)
> PyInstaller is a program that converts (packages) Python programs into
> stand-alone executables, under Windows, Linux, Mac OS X, Solaris and AIX.
> Its main advantages over similar tools are that PyInstaller works with any
> version of Python since 2.3, it builds smaller executables thanks to
> transparent compression, it is fully multi-platform, and use the OS support
> to load the dynamic libraries, thus ensuring full compatibility.
[cx-freeze](http://cx-freeze.sourceforge.net/)
> cx_Freeze is a set of scripts and modules for freezing Python scripts into
> executables, in much the same way that py2exe and py2app do. Unlike these
> two tools, cx_Freeze is cross platform and should work on any platform that
> Python itself works on. It supports Python 2.3 or higher (including Python
> 3), since it makes use of the zip import facility which was introduced in
> 2.3.
Once you have it packaged into a self-contained environment, be it either a
single exe or a directory structure, you can use any standard Windows
Installer application if you need special installation procedures. Or you can
simply distribute it as the .exe, ready to run.
|
Python: Unit Testing Module and Relative Imports
Question: Currently have the following file hierarchy:
\package
__init__.py
run_everything.py
\subpackage
__init__.py
work.py
work1.py
work2.py
\test
__init__.py
test_work.py
test_work1.py
My first question is regarding relative imports. Suppose in
\subpackage\work.py I have a function called custom_function(), and I would
like to test that function in test_work.py. For some reason I can not figure
out how to make this import from one module to another. Trying `from ..
subpackage.work1 import custom_function()` does not seem to work, and yields
the error `Attempted relative import in non-package` Is there any way to
resolve this?
2) I would like to run all test files from run_everything.py with one
function, would adding a suite() function in each test_work*.py file, which
adds each unit_testing class to suite.addTest(unittest.makeSuite(TestClass)),
and finally importing them into the top-level run_everything.py be the most
_conventional way_ in Python2.7?
Answer: Here is a hack*
Insert the path's to "subpackage" and "test" to your python path in
run_everything using:
import sys
sys.path.insert(0, '/path/to/package/subpackage')
sys.path.insert(0, '/path/to/package/test')
And then, you can import all your files using vanilla imports in
run_everything:
import work, work1, work2
import test_work, test_work1
*This won't permanently affect your PYTHONPATH. *Don't forget to down-vote me for hard-coding :(
|
Ideal Way to Create a Python "Library"
Question: I want to create a "library" of Python modules which I will be able to access
from several separate project folders.
For example, I want the Python scripts in /proj1/ and /proj2/ to have access
to /lib/.
/lib/help.py
/lib/more_help.py
/proj1/script.py
/proj1/script2.py
/proj2/this_script.py
/proj2/another_script.py
I don't want a single directory with all the Python scripts, as this seems
rather disorganized. I also definitely don't want to copy the same /lib/
script into each of the different projects.
What is the ideal way to handle this in Python? Is it [appending to Python's
path](http://stackoverflow.com/questions/4383571/importing-files-from-
different-folder-in-python)? Or is this more of a hack? This seems to have the
disadvantage of making the files less portable. Or is it [this
question/answer](http://stackoverflow.com/questions/279237/python-import-a-
module-from-a-folder) about using relative paths? Or something else?
I should add that I'm interested in Python 2.x rather than 3.x, if it matters.
Answer: Turn `lib/` into a
[package](http://docs.python.org/tutorial/modules.html#packages), then put it
in one of the directories in `sys.path` (or add a new entry). You can then
import e.g. `lib.help` into your projects.
|
How do I run os.walk in parallel in Python?
Question: I wrote a simple app in Java that takes a list of paths and generates a file
with all the file paths under that original list.
If I have paths.txt that has:
c:\folder1\
c:\folder2\
...
...
c:\folder1000\
My app runs the recursive function on each path multithreaded, and returns a
file with all the file paths under these folders.
Now I want to write this app in Python.
I've written a simple app that uses `os.walk()` to run through a given folder
and print the filepaths to output.
Now I want to run it in parallel, and I've seen that Python has some modules
for this: multithreaded and multiprocessing.
What is the best what to do this? And within that way, how is it performed?
Answer: Here is a _multiprocessing_ solution:
from multiprocessing.pool import Pool
from multiprocessing import JoinableQueue as Queue
import os
def explore_path(path):
directories = []
nondirectories = []
for filename in os.listdir(path):
fullname = os.path.join(path, filename)
if os.path.isdir(fullname):
directories.append(fullname)
else:
nondirectories.append(filename)
outputfile = path.replace(os.sep, '_') + '.txt'
with open(outputfile, 'w') as f:
for filename in nondirectories:
print >> f, filename
return directories
def parallel_worker():
while True:
path = unsearched.get()
dirs = explore_path(path)
for newdir in dirs:
unsearched.put(newdir)
unsearched.task_done()
# acquire the list of paths
with open('paths.txt') as f:
paths = f.split()
unsearched = Queue()
for path in paths:
unsearched.put(path)
pool = Pool(5)
for i in range(5):
pool.apply_async(parallel_worker)
unsearched.join()
print 'Done'
|
What is the Python equivalent of Ruby's fork block?
Question: With Ruby, a `fork` block can be used to express that
> Statements in this block are only executed in the child process and will be
> skipped over by the parent process.
Is there something similar in Python?
Answer: If you want to have some code executed in child processes, use
[`multiprocessing`](http://docs.python.org/library/multiprocessing.html)
module. Here's an example from documentation:
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
This example shows how function **f** can be executed inside child process.
|
Configuring apache2 conf for several python web.py apps
Question: I am working on a small web dashboard -project that has backend implemented
with python's web.py framework.
The dashboard has all sorts of widget's on it, one of which also has its
backend implemented using web.py. The problem is that only one of the
designated application entry points seem to function at a time. Both the
dashboard's and the widget's apache configurations are placed in the same
file. The original configuration file (that actually worked for a while) in
apache2/conf.d/ looks like this:
WSGIPythonPath /var/www/ProjectDASHBOARD/api
WSGIScriptAlias /ProjectDASHBOARD/api /var/www/ProjectDASHBOARD/api/api.py/
AddType text/html .py
<Directory /var/www/ProjectDASHBOARD/api/>
Order deny,allow
Allow from all
</Directory>
# Stuff for graphingwidget
WSGIPythonPath /var/www/ProjectDASHBOARD/widgets/graphingwidget/api
WSGIScriptAlias /ProjectDASHBOARD/widgets/graphingwidget/api /var/www/ProjectDASHBOARD/widgets/graphingwidget/api/api.py/
AddType text/html .py
<Directory /var/www/ProjectDASHBOARD/widgets/graphingwidget/api/>
Order deny,allow
Allow from all
</Directory>
This alone does not work, there is also the next piece of code that is needed
in both api.py files, checking their approriate paths and adding them if not
found (excerpt from the widget's file):
import web
import json
import sys
path = '/var/www/ProjectDASHBOARD/widgets/graphingwidget/api'
if path not in sys.path:
sys.path.append(path)
A similiar check is done for the dashboard.
All of this indeed worked for a whole week, and then suddenly stopped working
when trying to install from scratch, making it all the more confusing as to
what is wrong. The error received when trying to access the api from a webpage
is HTTP Error 500 Internal server error. Then after a few changes to the
apache config file ONE of the api's started working:
WSGIPythonPath /var/www/ProjectDASHBOARD/widgets/graphingwidget/api
WSGIPythonPath /var/www/ProjectDASHBOARD/api
WSGIScriptAlias /ProjectDASHBOARD/api /var/www/ProjectDASHBOARD/api/api.py/
WSGIScriptAlias /ProjectDASHBOARD/widgets/graphingwidget/api /var/www/ProjectDASHBOARD/widgets/graphingwidget/api/api.py/
AddType text/html .py
<Directory /var/www/ProjectDASHBOARD/api/>
Order deny,allow
Allow from all
</Directory>
# Stuff for graphingwidget
AddType text/html .py
<Directory /var/www/ProjectDASHBOARD/widgets/graphingwidget/api/>
Order deny,allow
Allow from all
</Directory>
Basically just moved the paths to the beginning of the file, and switched the
order around a little bit, and suddenly one of api's start to work again.
Changing the order a little bit then makes the other api work and brakes the
other one. I don't remember the correct order for the paths, but the point is
that it used to work well, then it stopped working when installed to a fresh
identical virtual machine, and only one of the api's work depending on the
order of the paths.
Initially the configs were in different files, but it didn't work like that.
Had all kinds of errors like "Target WSGI script 'path' cannot be loaded as
Python module.", and only started to work when they were moved to the same
file.
Im thinking here that somehow one of the paths is overwritten by the other, or
that all this time the whole config has been fundamentally wrong and has been
working only by sheer luck (for a whole week, without issues...)
Any clues as to what is wrong?
Answer: Sorry for the late return, but the case was basically had to carefully RTFM at
<http://webpy.org/install#apachemodwsgi> and make use of .htaccess files.
No idea really why the solution in the original question worked as far as it
did.
|
python: download file and send it to online storage in realtime
Question: I want to download file to my server and automatically send it to online
storage(minus or dropbox) via minus or dropbox API, without saving the
downloaded file in my server. So, its like streaming or pipe the HTTP
connection. Right now im using minus.com API, but its require file object or
local file as parameter. I can't figure out how to convert http response to
file object.
It is possible to do this? if possible, how?
concept :
FILE_ON_ANOTHER_SERVER ----(http)---> MY_SERVER ----(http)----> ONLINE_STORAGE
thanks
Answer: You can get the data from a response via the read() method
response = urllib2.urlopen(request)
data = response.read()
The variable data has the binary data from the response.
Now you can create a StringIO Object which handles the data as a file like
object.
import StringIO
datastream = StringIO.StringIO()
datastream.write(data)
datastream.seek(0)
#create dropbox client
client.put_file('/test', datastream)
|
Python sys.argv TypeErrors with printing function results?
Question: I have been trying to learn how to use sys.argv properly, while calling an
executable file from the command line.
I wanted to have the functions results print to the command line when passing
the filename and argument on the command line but, I get a TypeError.
So far I have:
#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys
def dictionary(word):
br = mechanize.Browser()
response = br.open('http://www.dictionary.reference.com')
br.select_form(nr=0)
br.form['q'] = sys.argv
br.submit()
definition = BeautifulSoup(br.response().read())
trans = definition.findAll('td',{'class':'td3n2'})
fin = [i.text for i in trans]
query = {}
for i in fin:
query[fin.index(i)] = i
return query
print dictionary(sys.argv)
When I call this:
./this_file.py 'pass'
I am left with this error message:
Traceback (most recent call last):
File "./hot.py", line 20, in <module>
print dictionary(sys.argv)
File "./hot.py", line 10, in dictionary
br.form['q'] = sys.argv
File "/usr/local/lib/python2.7/dist-packages/mechanize/_form.py", line 2782, in __setitem__
control.value = value
File "/usr/local/lib/python2.7/dist-packages/mechanize/_form.py", line 1217, in __setattr__
raise TypeError("must assign a string")
TypeError: must assign a string
Answer: With
`br.form['q'] = sys.argv`
you are assigning a _list of strings_ here _instead_ of a string.
>>> type(sys.argv)
<type 'list'>
>>> type(sys.argv[0])
<type 'str'>
>>>
You want to identify a specific string to assign via an index.
Most likely it will be be index 1 given what you have in your post (and since
index 0 is the name of the script). So perhaps
`br.form['q'] = sys.argv[1]`
will do for you. Of course it could be another index too, depending on your
particular application/needs.
Note as @Dougal observes in a helpful comment below, the function parameter
`word` in the function is not being used. You are calling your `dictionary`
function sending it `sys.argv` and then ought to refer to `word` inside the
function. The type doesn't change only the name that you refer to the command
line args inside your function. The idea of `word` is good as it avoids the
use of global variables. If you refer to use globals (not really encouraged)
then removing `word` is recommended as it will be confusing to have it there).
So your statement should really read
`br.form['q'] = word[1]`
|
How to pass a C++ object to another C++ object with Boost.Python
Question: I have some C++ code that defines two classes, A and B. B takes an instance of
A during construction. I have wrapped A with Boost.Python so that Python can
create instances of A, as well as subclasses. I want to do the same with B.
class A {
public:
A(long n, long x, long y) : _n(n), _x(x), _y(y) {};
long get_n() { return _n; }
long get_x() { return _x; }
long get_y() { return _y; }
private:
long _n, _x, _y;
};
class B {
public:
B(A a) : _a(a) {};
doSomething() { ... };
private:
A _a;
};
While wrapping B, I needed to work out how to pass an instance of A to B's
constructor. I did some digging and the
[solution](http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-
converters/) I found was to write a "converter" class:
struct A_from_python_A {
static void * convertible(PyObject* obj_ptr) {
// assume it is, for now...
return obj_ptr;
}
// Convert obj_ptr into an A instance
static void construct(PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data) {
// extract 'n':
PyObject * n_ptr = PyObject_CallMethod(obj_ptr, (char*)"get_n", (char*)"()");
long n_val = 0;
if (n_ptr == NULL) {
cout << "... an exception occurred (get_n) ..." << endl;
} else {
n_val = PyInt_AsLong(n_ptr);
Py_DECREF(n_ptr);
}
// [snip] - also do the same for x, y
// Grab pointer to memory into which to construct the new A
void* storage = (
(boost::python::converter::rvalue_from_python_storage<A>*)
data)->storage.bytes;
// in-place construct the new A using the data
// extracted from the python object
new (storage) A(n_val, x_val, y_val);
// Stash the memory chunk pointer for later use by boost.python
data->convertible = storage;
}
// register converter functions
A_from_python_A() {
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<A>());
}
};
Then I register this with:
BOOST_PYTHON_MODULE(interpolation_ext)
{
// register the from-python converter for A
A_from_python_A();
class_<A>("A", init<long, long, long>())
;
class_<B>("B", init<object>())
;
}
Convertible and construct are methods that answer the "is this convertible?"
and "how to convert?" questions respectively. I have observed that the
construct() method is non-trivial - it has to reach into A's PyObject*,
extract all relevant fields, then rebuild a C++ instance that it then passes
to B's constructor. Because A contains some private fields, it has to do this
via public access mechanisms (whereas with a pure Python object it wouldn't
have to, right?). This seems to work.
However, _is the field extraction in the 'construct' function really
necessary?_ It seems laborious. If A is a compound object, it could get very
complicated, and possibly require one converter to invoke another. I perhaps
understand the requirement if A is a Python class, but if the A instance
originated from the C++ side, is there a way to determine that this is the
case, and then simply get a handle (e.g. pointer) to this 'native' object, as
a shortcut?
Here's the associated python code:
from my_ext import A, B
a = A(1,2,3)
b = B(a)
b.doSomething()
Answer: In short, define `B`'s wrapper as:
class_<B>( "B", init< A >() )
instead of
class_<B>( "B", init< object >() )
When defining a wrapper for class in Boost.Python (at least in 1.50), the
`class_` template generates convert and construct functions. This allows `A`
to be converted to and constructed from a `A`'s wrapper. These `PyObject`
conversions have strict type-checking, and require that the following be true
in python: `isinstance( obj, A )`.
Custom converters are often used to support:
* Automatic conversions to and from existing Python types. For example, converting `std::pair< long, long >` to and from a `PyTupleObject`.
* Duck-typing. For example, having `B` accept class `D`, which is not derived from `A`, as long as `D` provides a compatible interface.
* * *
### Constructing `B` from an instance of `A`
Since `A` and `B` are neither existing Python types nor is duck-typing
required, custom converters are not necessary. For `B` to take an instance of
`A`, it can be as simple as specifying that `init` takes an `A`.
Here is a simplified example of `A` and `B`, where `B` can be constructed from
an `A`.
class A
{
public:
A( long n ) : n_( n ) {};
long n() { return n_; }
private:
long n_;
};
class B
{
public:
B( A a ) : a_( a ) {};
long doSomething() { return a_.n() * 2; }
private:
A a_;
};
And the wrappers would be defined as:
using namespace boost::python;
BOOST_PYTHON_MODULE(example)
{
class_< A >( "A", init< long >() )
;
class_<B>( "B", init< A >() )
.def( "doSomething", &B::doSomething )
;
}
`B`'s wrapper explicitly indicates that it will be constructed from an `A`
object via `init< A >()`. Also, `A`'s interface is not fully exposed to the
Python objects, as no wrapper was defined for the `A::n()` function.
>>> from example import A, B
>>> a = A( 1 )
>>> b = B( a )
>>> b.doSomething()
2
This also works for types that are derived from `A`. For example:
>>> from example import A, B
>>> class C( A ):
... def __init__( self, n ):
... A.__init__( self, n )
...
>>> c = C( 2 )
>>> b = B( c )
>>> b.doSomething()
4
However, duck-typing is not enabled.
>>> from example import A, B
>>> class E: pass
...
>>> e = E()
>>> b = B( e )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
B.__init__(B, instance)
did not match C++ signature:
__init__(_object*, A)
* * *
### Constructing `B` from an object that is convertible to `A`.
To support the case where `B` can be constructed from an object that provides
a compatible interface, then custom converters are required. Although wrappers
were not previously generated for `A::n()`, lets continue with the statement
that an object can be converted to `A` if the object provides a `get_num()`
method that returns an `int`.
First, write an `A_from_python` struct that provides converter and
constructors functions.
struct A_from_python
{
static void* convertible( PyObject* obj_ptr )
{
// assume it is, for now...
return obj_ptr;
}
// Convert obj_ptr into an A instance
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
std::cout << "constructing A from ";
PyObject_Print( obj_ptr, stdout, 0 );
std::cout << std::endl;
// Obtain a handle to the 'get_num' method on the python object.
// If it does not exists, then throw.
PyObject* n_ptr =
boost::python::expect_non_null(
PyObject_CallMethod( obj_ptr,
(char*)"get_num",
(char*)"()" ));
long n_val = 0;
n_val = PyInt_AsLong( n_ptr );
Py_DECREF( n_ptr );
// Grab pointer to memory into which to construct the new A
void* storage = (
(boost::python::converter::rvalue_from_python_storage< A >*)
data)->storage.bytes;
// in-place construct the new A using the data
// extracted from the python object
new ( storage ) A( n_val );
// Stash the memory chunk pointer for later use by boost.python
data->convertible = storage;
}
A_from_python()
{
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id< A >() );
}
};
`boost::python::expect_non_null` is used to throw an exception if `NULL` is
returned. This helps provide the duck-typing guarantee that the python object
must provide a `get_num` method. If the `PyObject` is known to be an instance
of given type, then it is possible to use
[`boost::python::api::handle`](http://www.boost.org/doc/libs/1_50_0/libs/python/doc/v2/handle.html)
and
[`boost::python::api::object`](http://www.boost.org/doc/libs/1_50_0/libs/python/doc/v2/object.html)
to directly extract the type, and avoid having to generically make calls
through the `PyObject` interface.
Next, register the converter in the module.
using namespace boost::python;
BOOST_PYTHON_MODULE(example)
{
// register the from-python converter for A
A_from_python();
class_< A >( "A", init< long >() )
;
class_<B>( "B", init< A >() )
.def( "doSomething", &B::doSomething )
;
}
No changes have occurred to `A`, `B`, or their associated wrapper definitions.
The auto-conversion functions were created, and then defined/registered within
the module.
>>> from example import A, B
>>> a = A( 4 )
>>> b = B( a )
>>> b.doSomething()
8
>>> class D:
... def __init__( self, n ):
... self.n = n
... def get_num( self ):
... return self.n
...
>>> d = D( 5 )
>>> b = B( d )
constructing A from <__main__.D instance at 0xb7f7340c>
>>> b.doSomething()
10
>>> class E: pass
...
>>> e = E()
>>> b = B( e )
constructing A from <__main__.E instance at 0xb7f7520c>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: get_num
`D::get_num()` exists, and thus `A` is constructed from an instance of `D`
when `D` is passed to `B`'s constructor. However, `E::get_num()` does not
exists, and an exception is raised when trying to construct `A` from an
instance of `E`.
* * *
### An alternative conversion solution.
Implementing duck-typing via the C-API can become very complicated with larger
types. An alternative solution is perform the duck-typing in python, and
distribute the python file alongside the library.
`example_ext.py` will import the `A` and `B` types, as well as monkey patch
`B`'s constructor:
from example import A, B
def monkey_patch_B():
# Store handle to original init provided by Boost.
original_init = B.__init__
# Construct an A object via duck-typing.
def construct_A( obj ):
return A( obj.get_num() )
# Create a new init that will delegate to the original init.
def new_init( self, obj ):
# If obj is an instance of A, use it. Otherwise, construct
# an instance of A from object.
a = obj if isinstance( obj, A ) else construct_A ( obj )
# Delegate to the original init.
return original_init( self, a )
# Rebind the new_init.
B.__init__ = new_init
monkey_patch_B()
The only change required to the end-user is to import `example_ext` instead of
`example`:
>>> from example_ext import A, B
>>> a = A( 6 )
>>> b = B( a )
>>> b.doSomething()
12
>>> class D:
... def __init__( self, n ):
... self.n = n
... def get_num( self ):
... return self.n
...
>>> d = D( 7 )
>>> b = B( d )
>>> b.doSomething()
14
>>> class E: pass
...
>>> e = E()
>>> b = B( e )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "example_ext.py", line 15, in new_init
a = obj if isinstance( obj, A ) else construct_A ( obj )
File "example_ext.py", line 9, in construct_A
return A( obj.get_num() )
AttributeError: E instance has no attribute 'get_num'
Since the patched constructor guarantees an instance of `A` will be passed to
`B`, the `A_from_python::construct` will not get invoked. Hence, the missing
print statements in the output.
While this approach avoids the C-API, making it easier to perform duck-typing,
it does have one major trade-off in that it requires parts of the API to be
specifically patched for conversions. On the other hand, no patching is
required when auto-type conversion functions are available.
* * *
Also, for what it is worth, access control in both C++ and Python is intended
to protect against accidental misuse. Neither protect against deliberately
obtaining access to members with private visibility. It is much easier to do
in Python, but it is specifically permitted in the C++ Standard through
explicit template instantiations.
|
Declaring a python function with an array parameters and passing an array argument to the function call?
Question: I am a complete newbie to python and attempting to pass an array as an
argument to a python function that declares a list/array as the parameter.
I am sure I am declaring it wrong,
here goes:
def dosomething(listparam):
#do something here
dosomething(listargument)
Clearly this is not working, what am I doing wrong?
Thanks
Answer: What you have is on the right track.
def dosomething( thelist ):
for element in thelist:
print element
dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )
Produces the output:
1
2
3
red
green
blue
A couple of things to note given your comment above: unlike in C-family
languages, you often don't need to bother with tracking the index while
iterating over a list, unless the index itself is important. If you really do
need the index, though, you can use `enumerate(list)` to get `index,element`
pairs, rather than doing the `x in range(len(thelist))` dance.
|
(Python) Append text dynamically in multi-threaded IRC GUI
Question: I'm writing a simple IRC server and client GUI using wxPython. In my
application, I had two threads running: One for the GUI, and one for the
socket connections required to send and receive information. So far, I believe
that I am successfully connecting to the server with the client application,
but I am seeing no messages processed. I tried using my client with another
TCP listener application and I was able to send a message successfully. I
believe the problem lies in the way I have set up the GUI. Here is my code for
the serverside application (apologies for any awkward spacing)
I have a feeling the problem lies within the bootUp() function..
#!/usr/bin/python
import wx
import socket
import threading
from threading import Thread
ip = ""
port = 0
backlog = 5
chatText = ""
class relayServerGUI(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, "Enter IP address", size = (600, 600))
orciPanel = wx.Panel(self)
relayChat = wx.TextCtrl(orciPanel, 0, chatText, (50, 50), (500, 500),style = wx.TE_MULTILINE)
portInput = wx.TextEntryDialog(None, "Enter Port: ", "")
if portInput.ShowModal() == wx.ID_OK:
global port
port = int(portInput.GetValue())
thread2()
def relayInterpretor():
socketRelay = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketRelay.bind((ip, port))
socketRelay.listen(backlog)
client, address = socketRelay.accept()
while 1:
relayData = client.recv(1024)
global chatText
chatText += (relayData)
client.send(relayData)
def bootUP():
if __name__ == "__main__":
relayApplication = wx.PySimpleApp()
relayFrame = relayServerGUI(parent = None, id = -1)
relayFrame.Show()
relayApplication.MainLoop()
while 1:
relayChat.Clear()
relayChat.AppendText(chatText)
Thread(target = bootUP).start()
def thread2():
Thread(target = relayInterpretor).start()
EDIT: relayChat is where the messages would, ideally, be displayed. I set it
to copy chatText, a global string variable so I would not have to delve into
cross-threading.
Answer: I am not very fluent in wx, but I think this problem isn't very specifically
wx related anyways. I see two possible issues here.
First, you are sharing a string between threads to communicate text to the
`relayChat` widget, which is usually a very bad approach. There should be a
way for your to emit an event in wx from the thread, so that the event loop
will pick it up in the main thread and run a handler that updates the widget.
Secondly, the event loop...
relayApplication.MainLoop()
That is a blocking call. Your application enters the event loop, so this
following code is not getting executed:
while 1:
relayChat.Clear()
relayChat.AppendText(chatText)
Again, this ties back into the first point. When the socket in the thread
receives some data, it should be emitting an event with that data, so the main
gui thread can properly call a handler that will append to your widget.
**Update**
Referencing [this
question](http://stackoverflow.com/questions/2345608/wxpython-threading-gui-
using-custom-event-handler) on how to emit custom wx events, you could
probably fix it like this:
from wx.lib.newevent import NewEvent
ChatTextEvent, EVT_CHATTEXT = NewEvent()
class relayServerGUI(wx.Frame):
def __init__(self, parent, id):
...
# make sure to save a ref to your chat widget
self.relayChat = wx.TextCtrl(orciPanel, 0, chatText, (50, 50), (500, 500),style = wx.TE_MULTILINE)
self.Bind(EVT_CHATTEXT, self.newChatTextEvent)
...
thread2(self)
def newChatTextEvent(self, event):
self.relayChat.AppendText(event.data)
def relayInterpretor(wxObject):
...
while 1:
...
# wxObject needs to be an instance of relayServerGUI
wx.PostEvent(wxObject, ChatTextEvent(data=relayData))
def thread2(wxObject):
Thread(target = relayInterpretor, args=(wxObject,)).start()
*Note: I am not 100% on that syntax. Try it out. It may need a slight tweak.
|
Pyconfigini: ImportError: No module named lib.pyconfigini
Question: I have been looking for an ini parse with inheritance support such as
Zend_Config_Ini, So I found pyconfigini
(https://bitbucket.org/maascamp/pyconfigini)
I have the following project structure:
* app
* __ init __.py
* settings.py
* lib
* __ init __.py
* pyconfigini.py
I copied pyconfigini.py module source
here(https://bitbucket.org/maascamp/pyconfigini) to lib/pyconfigini.py and In
my setting module (app/setting.py) I coded:
import os
from lib.pyconfigini import parse_ini
PROJECT_DIR = os.path.join( os.path.dirname(__file__), '../');
APP_ENV = os.getenv('APP_ENV','development')
config = parse_ini(os.path.abspath(os.path.join(PROJECT_DIR,"config.ini")), APP_ENV)
print config.nome
However when I run it in command line I get this error
> python settings.py
Traceback (most recent call last):
File "settings.py", line 7, in <module>
from lib.pyconfigini import parse_ini
ImportError: No module named lib.pyconfigini
Why I am getting this error? How could I fix it?
Answer: The problem is that you're running
python setting.py
from `app/` directory (which at the moment of script start becomes `current
working directory`) . Python looks for modules in directories that are listed
in **PYTHONPATH** environment variable (you can get access to it from Python
code via `sys.path` variable).
This list of directories contains standard `site-packages`, `dist-packages`,
etc. directories and you `current working directory` \- a directory, from
which you're trying to run your script.
As you can see from the above information, `lib` package cannot be found as it
doesn't exist in directories listed in `sys.path`.
So, I advice you to change entry point script location to you root directory,
where `app` and `lib` packages are located.
But if you wan't to test `settings.py` module for some reason running it
directly, you can define your PYTHONPATH manually, running your script e.g.
such way:
PYTHONPATH="../lib" python ./settings.py
This will patch your PYTHONPATH with needed `lib` directory.
Another way to run your app is to put `lib` package inside `app/` directory.
|
How to check in makefile if python script outputs OK
Question: I have a Python script, which checks my language translation files (in CSV
format), if all the lines contain translations for all languages included in
the CSV's first, header line. Script lists files/lines with missing
translations. If no problem is found, it outputs OK. **My question is
following:** how do I call the script from within the makefile and check, if
the output was OK? If something else than OK was printed out by the script, I
want the makefile to stop.
Any ideas?
Answer: `make` checks output status, not text which is output. The simplest solution
is to use `sys.exit(1)` in your python script if it doesn't check out OK.
for example:
targetfile: dependsonfile
python pythonscript.py -o targetfile dependsonfile
Of course the actual syntax will depend critically on how `pythonscript.py` is
meant to be called.
If your pythonscript just does a check, you can accomplish that as follows:
makethis: didcheck
echo "made it" > makethis
didcheck: #dependencies here
python -c 'import sys; sys.exit(1)'
touch didcheck
then you call make as `make makethis`.
|
Twisted Python: reactor and protocol
Question: I have several questions about the Twisted reactor.
1/ What kind of errors would crash/stop/terminate the reactor? what kind of
errors would not?
2/ I have two reactors, each running a different protocol. I have protocols A
and B.
One reactor creates a new instance of protocol A every time it handles an
input. If there is an error in an instance of protocol A, that error only
affects the instance, and the reactor keeps running smoothly.
The other reactor runs only ONE instance of protocol B (specifically I use it
to handle standard IO). It is simply like this:
stdio.StandardIO(ProtocolB())
reactor.run()
If an input somehow gives an error in Protocol B, then it affects the entire
reactor. Does the reactor actually stop in that case?
3/ In the case of the second reactor above, is it possible to create a new
instance of protocol B to replace the old instance if an error is detected?
Answer: > 1/ What kind of errors would crash/stop/terminate the reactor? what kind of
> errors would not?
A rule of thumb is: `reactor` runs until `reactor.stop()` is called by you or
in response to an expected event e.g., SIGINT signal (keyboard interrupt).
> If an input somehow gives an error in Protocol B, then it affects the entire
> reactor. Does the reactor actually stop in that case?
No, exceptions in your code won't stop the reactor:
import sys
from twisted.internet import reactor, task
def raise_exception():
raise RuntimeError
reactor.callWhenRunning(raise_exception)
task.LoopingCall(sys.stderr.write, '.').start(.4) # heartbeat
reactor.callLater(5, reactor.stop) # stop reactor
reactor.run()
> 2/ I have two reactors, each running a different protocol. I have protocols
> A and B.
There should be only one reactor whatever number of protocols is.
> 3/ In the case of the second reactor above, is it possible to create a new
> instance of protocol B to replace the old instance if an error is detected?
You can but you shouldn't do it. if `connectionMade`, `lineReceived` raise
exceptions it is a bug and you should fix it.
Here's an example that relaunches after exception. It is just a demonstration
that it is possible, _don't use it_ in a actual code.
from twisted.internet import reactor
from twisted.internet.stdio import StandardIO
from twisted.protocols.basic import LineReceiver
prompt = ">>>> "
class ReverseLineProtocol(LineReceiver):
delimiter = '\n'
def connectionMade(self):
self.sendLine("Write everything in reverse.")
self.transport.write(prompt)
def lineReceived(self, line):
if line == 'raise':
reactor.callLater(1, launch)
raise RuntimeError
self.sendLine(line[::-1])
self.transport.write(prompt)
def launch():
StandardIO(ReverseLineProtocol())
launch()
reactor.run()
|
PYGame - ImportError: No module named locals Raspberry Pi
Question: I have the following code:
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import pygame, random
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
and so on
The app all appears OK, but when I compile the code I get the following error:
Traceback (most recent call last):
File "fish.py", line 4, in <module>
import pygame, random
File "/home/pi/pygame/pygame.py", line 2, in <module>
ImportError: No module named locals
------------------
(program exited with code: 1)
Press return to continue
Can anyone help? I'm new to Python and Linux.
I've done the following:
pi@raspberrypi:~$ sudo apt-get install python-pygame
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-pygame is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 40 not upgraded.
pi@raspberrypi:~$
Answer: Your problem is that you have a file that is named `pygame.py`, or a bytecode
left-over from such a file named `pygame.pyc`.
* * *
Calling `import pygame` works, but it will not import pygame, but the that
very file.
And since your file can't find a module named `locals` in that file, the error
is raised.
So, just rename your file to anything other than `pygame.py` or other modules
you want to import, or, if there's a `pygame.pyc` bytecode file, remove that.
|
Sharing object (class instance) in python using Managers
Question: I need to share an object and its methods between several processes in python.
I am trying to use Managers (in module multiprocessing) but it crashes. Here
is a silly example of producer-consumer where the shared object between the
two processes is just a list of numbers with four methods.
from multiprocessing import Process, Condition, Lock
from multiprocessing.managers import BaseManager
import time, os
lock = Lock()
waitC = Condition(lock)
waitP = Condition(lock)
class numeri(object):
def __init__(self):
self.nl = []
def getLen(self):
return len(self.nl)
def stampa(self):
print self.nl
def appendi(self, x):
self.nl.append(x)
def svuota(self):
for i in range(len(self.nl)):
del self.nl[0]
class numManager(BaseManager):
pass
numManager.register('numeri', numeri, exposed = ['getLen', 'appendi', 'svuota', 'stampa'])
def consume(waitC, waitP, listaNumeri):
lock.acquire()
if (listaNumeri.getLen() == 0):
waitC.wait()
listaNumeri.stampa()
listaNumeri.svuota()
waitP.notify()
lock.release()
def produce(waitC, waitP, listaNumeri):
lock.acquire()
if (listaNumeri.getLen() > 0):
waitP.wait()
for i in range(10):
listaNumeri.appendi(i)
waitC.notify()
lock.release()
def main():
mymanager = numManager()
mymanager.start()
listaNumeri = mymanager.numeri()
producer = Process(target = produce, args =(waitC, waitP, listaNumeri,))
producer.start()
time.sleep(2)
consumer = Process(target = consume, args =(waitC, waitP, listaNumeri,))
consumer.start()
main()
Anyway it always crashes like that, telling me this:
Process Process-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "./trySemProc.py", line 61, in consume
if (listaNumeri.getLen() == 0):
File "<string>", line 2, in getLen
File "/usr/lib/python2.7/multiprocessing/managers.py", line 755, in _callmethod
self._connect()
File "/usr/lib/python2.7/multiprocessing/managers.py", line 742, in _connect
conn = self._Client(self._token.address, authkey=self._authkey)
File "/usr/lib/python2.7/multiprocessing/connection.py", line 169, in Client
c = SocketClient(address)
File "/usr/lib/python2.7/multiprocessing/connection.py", line 293, in SocketClient
s.connect(address)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 2] No such file or directory
So what's the matter? How should I use these Managers to share objects and
their methods?
Answer: You must
[join](http://docs.python.org/library/multiprocessing.html#multiprocessing.Process.join)
your processes to prevent main process exiting before child processes continue
their execution. So add joins to your code:
consumer.join()
producer.join()
after you called `start()` methods of your processes.
|
How to preserve matlab struct when accessing in python?
Question: I have a mat-file that I accessed using
from scipy import io
mat = io.loadmat('example.mat')
From matlab, example.mat contains the following struct
>> load example.mat
>> data1
data1 =
LAT: [53x1 double]
LON: [53x1 double]
TIME: [53x1 double]
units: {3x1 cell}
>> data2
data2 =
LAT: [100x1 double]
LON: [100x1 double]
TIME: [100x1 double]
units: {3x1 cell}
In matlab, I can access data as easy as data2.LON, etc.. It's not as trivial
in python. It give me several option though like
mat.clear mat.get mat.iteritems mat.keys mat.setdefault mat.viewitems
mat.copy mat.has_key mat.iterkeys mat.pop mat.update mat.viewkeys
mat.fromkeys mat.items mat.itervalues mat.popitem mat.values mat.viewvalues
Is is possible to preserve the same structure in python? If not, how to best
access the data? The present python code that I am using is very difficult to
work with.
Thanks
Answer: Found this tutorial about matlab struct and python
<http://docs.scipy.org/doc/scipy/reference/tutorial/io.html>
|
How to read Excel files from a stream (not a disk-backed file) in Python?
Question: XLRD is installed and tested:
>>> import xlrd
>>> workbook = xlrd.open_workbook('Sample.xls')
When I read the file through html form like below, I'm able to access all the
values.
xls_file = request.params['xls_file']
print xls_file.filename, xls_file.type
I'm using Pylons module, request comes from: `from pylons import request,
tmpl_context as c`
My questions:
1. Is `xls_file` read through `requst.params` an object?
2. How can I read `xls_file` and make it work with xlrd?
**Update:**
The `xls_file` is uploaded on web server, but the xlrd library expects a
filename instead of an open file object, How can I make the uploaded file to
work with xlrd? (Thanks to Martijn Pieters, I was being unable to formulate
the question clearly.)
Answer: xlrd does support providing data directly without a filepath, just use the
file_contents argument:
xlrd.open_workbook(file_contents=fileobj.read())
For more info see the docs:
<https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966#__init__.open_workbook-
function>
|
logging module for python reports incorrect timezone under cygwin
Question: I am running python script that uses logging module under cygwin on Windows 7.
The `date` command reports correct time:
$ date
Tue, Aug 14, 2012 2:47:49 PM
However, the python script is five hours off:
2012-08-14 19:39:06,438: Done!
I don't do anything fancy when I configure logging for the script:
logging.basicConfig(format='%(asctime)-15s: %(message)s', level=logging.DEBUG)
Can someone tell me what is going on and how I can fix it?
Answer: You need to unset the environment "TZ" in your python script prior to any
importing the date/time modules. It is set by cygwin but not understood by
Windows:
if os.getenv("TZ"):
os.unsetenv("TZ")
|
Python 3: apply an operator over an iterable
Question: `sum(iterable)` is effectively:
def sum(iterable):
s = 0
for x in iterable:
s = s.__add__(x)
return s
Does Python have a built-in function that accomplishes this without setting
the initial value?
# add is interchangeable with sub, mul, etc.
def chain_add(iterable):
iterator = iter(iterable)
s = next(iterator)
while True:
try:
s = s.__add__(next(iterator))
except StopIteration:
return s
The problem I have with `sum` is that it does not work for other types that
support the `+` operator, e.g. `Counter`.
Answer: Try looking into the python reduce function:
<http://docs.python.org/library/functions.html#reduce>
You pass in a function, an iterable, and an optional initializer and it would
apply the function cumulatively to all the values.
For example:
import functools
def f(x,y):
return x+y
print functools.reduce(f, [1, 2, 3, 4]) # prints 10
print functools.reduce(f, [1, 2, 3, 4], 10) # prints 20, because it initializes at 10, not 0.
You can change the function based on your iterable, so it's very customizable.
|
Why isn't my python code printing my list?
Question: I've written a function that should return a list of column numbers that
correspond to specific variables I'd like to extract later on from a csv file.
The variable names are specified by `state_aggregate_vars`.
import csv
import numpy
def compute_countyStats(state_aggregate, year, state_aggregate_vars, listCounties, county_var, int_obese, int_healthy, int_refuse): :
f = open(state_aggregate, 'r')
readit = csv.reader(f)
headers = readit.next()
use_cols = []
for name in state_aggregate_vars:
use_cols.append(headers.index(name))
return use_cols
county_data = numpy.genfromtxt(f, dtype=float, delimiter=',', names = state_aggregate_vars, filling_values= -1,
usecols= use_cols, usemask=False)
sorted_array = county_data(numpy.argsort(county_data, axis= headers.index(county_var))
for code in listCounties:
temp = []
for entry in sorted_array:
if entry[0] == code:
temp.append(float(entry[1]))
else:
continue
percent_healthy = numpy.true_divide(temp.count(int_healthy),num_obs)
percent_obese = numpy.true_divide(temp.count(int_obese),num_obs)
percent_refused = numpy.true_divide(temp.count(int_refuse),num_obs)
county_stats[code] = year, code, percent_healthy, percent_obese, percent_refused,
return county_stats
Next, I call this function using the following:
state_aggregate = "Aggregate_test90.csv"
year = 1990
state_aggregate_vars = ['_BMI90', 'AGE90', 'CTYCODE90', 'IYEAR90', 'SEX90', '_RFOBESE90']
listCounties = [31, 43, 163, 32, 167, 97]
county_var = 'CTYCODE90'
int_obese = 2
int_healthy = 1
int_refuse = 0
test = compute_countyStats(state_aggregate, year, state_aggregate_vars, listCounties, county_var, int_obese, int_healthy, int_refuse)
Here is my error:
SyntaxError: invalid syntax in line 6:
for name in state_aggregate_vars:
What could be going wrong?
Here is my `python -V`:
Python 2.7.3 -- EPD 7.3-2 (32-bit)
Answer: There are some errors in your code:
line 4 : a colon to much
line 14: missing brace
line 17: missing indent
line 27: missing indent
|
Exploring Python Exercise
Question: I am learning Python from the book _Exploring Python_ by Timothy Budd. One of
the exercises from this chapter is this:
15. The function `randint` from the random module can be used to produce random numbers. A call on `random.randint(1, 6)`, for example, will produce the values 1 to 6 with equal probability. Write a program that loops 1000 times. On each iteration it makes two calls on `randint` to simulate rolling a pair of dice. Compute the sum of the two dice, and record the number of times each value appears. Afterthe loop, print the array of sums. You can initialize the array using the idiom shown earlier in this chapter:
`times = [0] * 12 # make an array of 12 elements, initially zero`
I am able to print the sum in the array, but I have not understood the concept
of recording the number of times each value appears. Also, what purpose would
`times = [0]` serve? Here is my code for printing the sum:
#############################################
# Program to print the sum of dice rolls #
#############################################
from random import randint
import sys
times = [0] * 12
summation = []
def diceroll():
print "This program will print the"
print "sum of numbers, which appears"
print "after each time the dice is rolled."
print "The program will be called 1000 times"
for i in range(1,1000):
num1 = randint(1,6)
num2 = randint(1,6)
sum = num1 + num2
summation.append(sum)
#times[i] = [i] * 12
print summation
#print times
diceroll()
Answer: `times[0] * 12` initiates a list of 12 elements with value 0. What you want to
do next is
times[s] += 1 #adds 1 to the number of times s occurs
This is similar to using a dict to encode a value, but its simpler.
`times = [0]` initializes a list called times of length 1 and value 0. The
idiom `times = [0] * 12` means times is a list of 12 zeroes.
If you want to be able to use this without keyerror when `num1==num2==6`, you
need to do `times = [0]*13` because python is a 0 indexed system.
Sidenote: Don't use `sum` as a variable name because it is a builtin function
(predefined) and you don't want to override it. Use `times[sum([num1,num2])]
+= 1` or `times[num1+num2]` instead.
|
Time slot availablity in python
Question: I am writing a slot booking algorithm for my application in python like this
from datetime import datetime, timedelta
appointments = [(datetime(2012, 5, 22, 10), datetime(2012, 5, 22, 10, 30)),
(datetime(2012, 5, 22, 12), datetime(2012, 5, 22, 13)),
(datetime(2012, 5, 22, 15, 30), datetime(2012, 5, 22, 17, 10))]
hours = (datetime(2012, 5, 22, 9), datetime(2012, 5, 22, 18))
def get_slots(hours, appointments, duration=timedelta(hours=1)):
slots = sorted([(hours[0], hours[0])] + appointments + [(hours[1], hours[1])])
for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
assert start <= end, "Cannot attend all appointments"
while start + duration <= end:
print "{:%H:%M} - {:%H:%M}".format(start, start + duration)
start += duration
This works fine for me if i am checking slot for a particular date within 9
hours to 18 hours But it is not fulfilling my requirements for week or month
availability .Because i want to check availability for week or month between 9
hour to 18 hour .
Please help me to improve my code so that it could check the available slots
between 9 hours to 18 hours for weeks and months also.
Answer: I think you intend that `hours` applies to every day of the week or month
(except perhaps some days off?), so you might change it to use `time` objects.
Then for each day, you can `datetime.combine` to create an interval from the
previous day's end until this day's start. Don't forget to create one more
interval that starts at the last day's end.
|
Numpy arrays, fancy indexing, complex numbers
Question: The following code multiplies a part of the array by a number
def mul_by_num(a,b):
a[0:2] *= b
import numpy as np
a = np.ones(5,dtype=np.float64)
mul_by_num(a,1.0)
mul_by_num(a,1j) #Generates a warning (and casts to float!)
The second call generates a warning
-c:2: ComplexWarning: Casting complex values to real discards the imaginary part
The question is, what is the most pythonic way to multiply parts of numpy
arrays by complex/real numbers without messing with dtypes? I do not really
want to convert an array to complex from the beginning, but the program in
principle can get a complex input.
**EDIT:**
I do not care about copying the full array, casting it to complex; But I want
to avoid checking dtypes (i.e., np.float32, np.float64, np.complex, np.int
etc.)
Answer: You're going to need to convert the array to complex at some point, otherwise
it won't be able to hold complex numbers.
The easiest way to convert an array to complex is to add `0j`:
if (np.iscomplexobj(b)):
a = a + 0j
a[0:2] *= b
note: _not_ `a += 0j` as that will attempt to modify the array inplace, which
won't work if it isn't complex already.
|
Is is possible for a python script to know whether it is run with the interactive option '-i'?
Question: > **Possible Duplicate:**
> [tell whether python is in -i
> mode](http://stackoverflow.com/questions/640389/tell-whether-python-is-in-i-
> mode)
> [Tell if python is in interactive
> mode](http://stackoverflow.com/questions/2356399/tell-if-python-is-in-
> interactive-mode)
Is there a way to check whether a python script has been run with the
interactive option -i?
e.g.
if interactive_mode:
print 'I am in interactive mode!'
else:
print 'I am in batch mode!'
Then call with
python hello_world.py
I am in batch mode!
python -i hello_world.py
>> I am in interactive mode!
Answer:
import sys
if sys.flags.interactive:
print 'I am in interactive mode!'
else:
print 'I am in batch mode!'
|
Printing all combinations, python
Question: say I have 3 different variables and each has 2 possible values, so in total I
have 8 different combinations. Is there a python library function, or an
algorithm that I can use to print all possible combinations?
Thanks
Answer: I think you're looking for
[product](http://docs.python.org/library/itertools.html#itertools.product):
a = [1, 2]
b = [100, 200]
c = [1000, 2000]
import itertools
for p in itertools.product(a, b, c):
print p
prints:
(1, 100, 1000)
(1, 100, 2000)
(1, 200, 1000)
(1, 200, 2000)
(2, 100, 1000)
(2, 100, 2000)
(2, 200, 1000)
(2, 200, 2000)
|
python multiprocessing, pool workers do not complete all tasks
Question: I have a relatively simple python multiprocessing script that sets up a pool
of workers that append output to a pandas dataframe by way of a custom
manager. What I am finding is when I call close()/join() on the pool, not all
the tasks submitted by apply_async are being completed.
Here's a simplified example that submits 1000 jobs but only half complete
causing an assertion error. Have I overlooked something very simple or is this
perhaps a bug?
from pandas import DataFrame
from multiprocessing.managers import BaseManager, Pool
class DataFrameResults:
def __init__(self):
self.results = DataFrame(columns=("A", "B"))
def get_count(self):
return self.results["A"].count()
def register_result(self, a, b):
self.results = self.results.append([{"A": a, "B": b}], ignore_index=True)
class MyManager(BaseManager): pass
MyManager.register('DataFrameResults', DataFrameResults)
def f1(results, a, b):
results.register_result(a, b)
def main():
manager = MyManager()
manager.start()
results = manager.DataFrameResults()
pool = Pool(processes=4)
for (i) in range(0, 1000):
pool.apply_async(f1, [results, i, i*i])
pool.close()
pool.join()
print results.get_count()
assert results.get_count() == 1000
if __name__ == "__main__":
main()
Answer: **[EDIT]** The issue which you're seeing is because of this code:
self.results = self.results.append(...)
this isn't atomic. So in some cases, the thread will be interrupted after
reading `self.results` (or while appending) but before it can assign the new
frame to `self.results` -> this instance will be lost.
The correct solution is to wait use the results objects to get the results and
then append all of them in the main thread.
|
Lists as reference types in python
Question: Following is the piece of code that i wrote to calculate the nth prime number.
I initialize arr = [2,3,5]; and prime(arr,n) is supposed to modify arr to
contain first n prime numbers. But arr does not reflect changes after
prime(arr,n) is executed. I read that lists are passed as reference types ,so
what is the problem in the following code. t denotes the number of test cases
against which verification has to be done.
The program results in an error saying array index out of bound for arr.
import sys;
def prime (arr,n):
while(len(arr)< n):
num=arr[len(arr)-1]+1;prime=0;
while(prime==0):
prime = 1
for val in arr:
if(num%val==0):
prime=0;
break;
if(prime == 1):
print "hello";
arr = arr + [num];print arr; print "--";
else:
num = num+1;
t=raw_input();
t=int(t);
arr=[2,3,5];
ans =[];
for v in range (0,t):
n = raw_input();
n = int(n);
if(n<=len(arr)):
ans = ans + [arr[n-1]];
else:
prime(arr,n);print arr;print"arr was printed"
ans= ans + [arr[n-1]];
print ans;print 'ans ';
below is sample run of the above code
>>>
1
4
hello
[2, 3, 5, 7]
--
[2, 3, 5]
arr was printed
Traceback (most recent call last):
File "C:\Users\Pulkit\Desktop\Random\nth_prime.py", line 30, in <module>
ans= ans + [arr[n-1]];
IndexError: list index out of range
Thanks in advance :)
Answer: Change the line:
arr = arr + [num];
to
arr.append(num)
The new line actually changes the `arr` array. The original line didn't change
it; it created a _new_ variable called `arr` (it was a [rebinding operation
instead of a mutating
one](http://en.wikipedia.org/wiki/Name_binding#Rebinding_and_mutation))
Sample run after this change:
1
4
hello
[2, 3, 5, 7]
--
[2, 3, 5, 7]
arr was printed
[7]
ans
|
Monkey Patching in python: When we need it?
Question: In Python, the term `monkey patch` only refers to dynamic modifications of a
class or module at runtime, As a beginner its really difficult to me
understand this term in context of python. Can anybody explain to me with a
real world example How exactly we do ?
1. dynamic modifications of a class
2. dynamic modifications of module at runtime
I am insisting a real world example (as simple as possible) to understand in
which scenarios we have to do such task ?
Answer: Monkey-patching is a way to make some global under-the-hood change in a way
that existing code will continue to run, but with modified behavior.
### A really really trivial example of changing the behavior of the builtin
`str` command:
**b.py**
def foo(msg):
s = str(msg)
print s, type(s)
**a.py**
import b
b.foo('foo')
# monkey-patch
import __builtin__
__builtin__.str = unicode
b.foo('foo')
# Results:
#foo <type 'str'>
#foo <type 'unicode'>
The `a` module has modified the behavior of other code using the `str`
command, by patching it to use `unicode` instead. This would be necessary
since we pretend that we have no access to `b.py`'s code. It could have been a
huge package that we simply use and can't change. But we can slip in new code
to be called that changes the behavior.
### A real world example [from
gevent](http://www.gevent.org/intro.html#monkey-patching)
>
> >>> import gevent
> >>> from gevent import socket
> >>> urls = ['www.google.com', 'www.example.com', 'www.python.org']
> >>> jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
> >>> gevent.joinall(jobs, timeout=2)
> >>> [job.value for job in jobs]
> ['74.125.79.106', '208.77.188.166', '82.94.164.162']
>
>
> The example above used gevent.socket for socket operations. If the standard
> socket module was used it would took it 3 times longer to complete because
> the DNS requests would be sequential. Using the standard socket module
> inside greenlets makes gevent rather pointless, so what about module and
> packages that are built on top of socket?
>
> **That’s what monkey patching for. The functions in gevent.monkey carefully
> replace functions and classes in the standard socket module with their
> cooperative counterparts. That way even the modules that are unaware of
> gevent can benefit from running in multi-greenlet environment.**
>
>
> >>> from gevent import monkey; monkey.patch_socket()
> >>> import urllib2 # it's usable from multiple greenlets now
>
|
Python Error Getting Timestamp from List Slice
Question: I'm in the process of writing a script that chunks a large CSV file down into
smaller chunked files. It cross references a log file that holds the last
timestamp that was chunked so that only the timestamps that are later than the
logged time are written/chunked.
The first column of the csv file has a timestamp that is in `%Y%m%d %H%M%S`
form. The CSV file also has four rows of header information that I don't
want/need in my script, which the `rows in ts_pre` clause removes.
The `log_lookup()` function just pulls the last timeseries from the log for a
particular station's CSV file that I'm viewing. Obviously, I'm working with
six different stations that all have different columns of information, except
they all share the same structure as I described in the second paragraph.
The partial script is:
import csv, sys, datetime
def log_lookup():
global STN_num
global STN_date
with open('/home/log.txt', 'rb') as open_log:
log_file = csv.reader(open_log)
for row in log_file:
for item in row:
STN_date.append(item)
if find == 'STN_1':
return STN_date[1]
if find == 'STN_2':
return STN_date[2]
if find == 'STN_3':
return STN_date[3]
if find == 'STN_4':
return STN_date[4]
if find == 'STN_5':
return STN_date[5]
if find == 'STN_6':
return STN_date[6]
def get_ts(line):
print line[0:19]
return datetime.datetime.strptime(line, "%Y/%m/%d %H:%M:%S")
def main():
log = str(log_lookup()) #useful for knowing when to start chunking
log_datetime = datetime.datetime.strptime(log, "%Y/%m/%d %H:%M:%S")
with open(sys.argv[1], 'rb') as open_file:
ts_from_file = csv.reader(open_file)
for genrows in ts_from_file:
ts_pre.append(genrows)
for rows in ts_pre:
if rownum < 4:
ts_pre.pop()
rownum += 1
else:
for line in rows:
if get_ts(line) > log_datetime:
timeseries.append(line)
The log file is simply:
0
2011/10/06 18:40:00
2012/06/27 13:25:00
1900/01/01 00:00:00
2011/08/03 14:55:00
2012/06/27 20:05:00
2011/10/03 19:25:00
... with 0 as a placeholder. _(Is it obvious I'm not a programmer?)_
An example CSV file looks like:
"2011/10/03 16:40:00",0,0
"2011/10/03 16:45:00",1,0
"2011/10/03 16:50:00",2,0
"2011/10/03 16:55:00",3,0
The error I'm getting when the `ts_line(line)` function is that it's saying
`line[0:19]` is:
2011/10/03 16:40:00
0
and the function returns `0` and Python throws this error:
ValueError: time data '0' does not match format '%Y/%m/%d %H:%M:%S'
I have verified that the `0` that's returned is the second item in the CSV
file, but I'm confused as to why Python returns it at all in my slice
selection. Can someone explain to me why it's returning that value and what I
need to do to get the timestamp to compare to the log timestamp?
For extra credit, any advice on coding/style is always appreciated and/or
advice for better ways accomplish what I'm doing. The CSV files I'm looking at
are quite large _(~8 MB)_ so the more efficient the better.
Answer: It looks like you are calling `get_ts` for each column in every line of the
csv.
Instead of
for line in rows:
if get_ts(line) > log_datetime:
timeseries.append(line)
Try:
if get_ts(line[0]) > log_datetime:
timeseries.append(line)
|
Reverse dns lookup with scapy in python
Question: How can I do reverse DNS lookup using `scapy` in Python? I look for it in
Google but I couldn't find related to this topic.
Answer: Reverse DNS is already written into Python's Socket module. Simply use the
following:
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
Which was originally posted here, [Python lookup hostname from IP with 1
second timeout](http://stackoverflow.com/questions/2575760/python-lookup-
hostname-from-ip-with-1-second-timeout), by
<http://stackoverflow.com/users/81179/christophed>
|
"password authentication failed for user" after push to Heroku
Question: I followed the [heroku
documentation](https://devcenter.heroku.com/articles/django) to install a
django app and at first it worked fine. After a day I pushed some changes to
the server. After that, I was not able to access the app at all: `FATAL:
password authentication failed for user "drjstoymyqyarj"`
I can not even sync the db anymore:
$ heroku run python manage.py syncdb
Running `python manage.py syncdb` attached to terminal... up, run.1
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle
return self.handle_noargs(**options)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 57, in handle_noargs
cursor = connection.cursor()
File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/__init__.py", line 306, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 177, in _cursor
self.connection = Database.connect(**conn_params)
File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL: password authentication failed for user "drjstoymyqyarj"
FATAL: password authentication failed for user "drjstoymyqyarj"
I have used the database settings recommended in the heroku doc:
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
When I check the logs after pushing code to the server, there is a suspicious
`Process exited with status 143` that I did not notice before. Maybe that has
something to do with it?
$ heroku logs
heroku[web.1]: State changed from up to starting
heroku[web.1]: Stopping all processes with SIGTERM
heroku[web.1]: Starting process with command `python ./manage.py runserver 0.0.0.0:41048 --noreload`
app[web.1]: Validating models...
app[web.1]:
app[web.1]: 0 errors found
app[web.1]: Django version 1.4, using settings 'ClosetList.settings'
app[web.1]: Development server is running at http://0.0.0.0:41048/
app[web.1]: Quit the server with CONTROL-C.
heroku[web.1]: Process exited with status 143
heroku[web.1]: State changed from starting to up
**[Edit]**
Same error msg with `heroku pg:psql`. I am however able to open a Django shell
with `heroku run python manage.py shell`, but I can not access any data from
within it (same error of course).
**[/Edit]**
any help with this is appreciated.
Answer: Run
heroku config
and see if there are more than 2 heroku dbs configured and also see if
DATABASE_URL point to your configured DB. If not, then you can promote your db
to default DATABASE_URL by running:
heroku pg:promote HEROKU_POSTGRESQL_GREEN
Where HEROKU_POSTGRESQL_GREEN is your database name, you will see
HEROKU_POSTGRESQL_GREEN_URL in your config.
Once your configured database is promoted to default database, you are ready
to go.
|
python: integer out of range for 'L' format code
Question: In python, the code is the following
envimsg = struct.pack("!LHL", 1, 0, int(jsonmsg["flow_id"], 16)) + \
struct.pack("!HQH", 1, int(flow["src id"],16), 0) + \
struct.pack("!HQH", 1, int(flow["dst id"],16), int(flow["dst port"],16)) + \
struct.pack("!H", 0) + \
struct.pack("!HHHLL", int(jsonmsg["app_src_port"],10), int(jsonmsg["app_dst_port"],10), int(jsonmsg["app_proto"],10), int(jsonmsg["app_src_ip"],10), int(jsonmsg["app_dst_ip"],10))
at the line
struct.pack("!H", 0) + \
I encounter this error:
File "./Translate_2503.py", line 205, in lavi2envi
struct.pack("!H", 0) + \
struct.error: integer out of range for 'L' format code
which is strange because I try to pack in H (unsigned short).
Any clues?
My python version 2.7.3. CPU archi is 32bit.
Answer: Even in the error line is pointing to this line, the error is not located
there. Executing this instruction in the Python interpreter produces no error:
import struct
struct.pack("!H", 0)
>>> '\x00\x00'
This makes sense, as the error is complaining on the 'L' format code, so the
error will be located in the ones which use this format.
Given that 'L' is used for unsigned long, and the message complains on being
out of range, the error is because one (or more) of the variables used are
negative, producing the out of range for unsigned long.
This can be verified in the Python interpreter:
import struct
struct.pack("!HHHLL", 1, 2, 3, 4, 5)
>>> '\x00\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05'
struct.pack("!HHHLL", 1, 2, 3, -4, 5)
>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: integer out of range for 'L' format code
|
Python hashlib & decode() on a Bytes Object
Question: I'm not understanding something about hashlib. I'm not sure why I can decode a
regular byte object, but can't decode a hash that's returned as a byte object.
I keep getting this error:
**UnicodeDecodeError: 'utf-8' codec can't decode byte 0xad in position 1:
invalid start byte**
Here's my test code that's producing this error. The error is on line 8 (`h2 =
h.decode('utf-8')`)
import hashlib
pw = 'wh@teV)r'
salt = 'b7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua'
pwd = pw + salt
h = hashlib.sha512(pwd.encode('utf-8')).digest()
print(h)
h2 = h.decode('utf-8')
print(h2)
If I don't hash it, it works perfectly fine...
>>> pw = 'wh@teV)r'
>>> salt = 'b7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua'
>>> pwd = pw + salt
>>> h = pwd.encode('utf-8')
>>> print(h)
b'wh@teV)rb7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua'
>>> h2 = h.decode('utf-8')
>>> print(h2)
wh@teV)rb7u2qw^T&^#U@Lta)hvx7ivRoxr^tDyua
So I'm guessing I'm not understanding something about the hash, but I have no
clue what I'm missing.
Answer: In the second example you're just encoding to UTF-8 and then decoding the
result straight back.
In the first example, on the other hand, you're encoding to UTF-8, messing
about with the bytes, and then trying to decode it as though it's still UTF-8.
Whether the resulting bytes are still valid as UTF-8 is purely down to chance
(and even if it is still valid UTF-8, the Unicode string it represents will
bear no relation to the original string).
|
python salesforce beatbox: beatbox._beatbox.SoapFaultError: 'INVALID_FIELD'
Question: I am using [beatbox](http://www.pocketsoap.com/beatbox/) to connect to
Salesforce from Python and it works fine until I try to add constraint with
dates.
When I add a CreatedDate constraint it fails saying
File "/Library/Python/2.7/site-packages/beatbox/_beatbox.py", line 332, in post
raise SoapFaultError(faultCode, faultString)
beatbox._beatbox.SoapFaultError: 'INVALID_FIELD' "INVALID_FIELD: from Assets__c where CreatedDate > 2012-08-08 ^ ERROR at Row:1:Column:1061 value of filter criterion for field 'CreatedDate' must be of type dateTime and should not be enclosed in quotes"
* How can I send a datetype object to query and fix this?
Answer: This will give you a datetime object:
import datetime
def return_datetime(year, month, day):
return datetime.datetime(year, month, day)
date = return_datetime(2012, 8, 12)
|
Error with class in python
Question: I've written some code that works when typed directly into the interpreter,
but fails when called.
Here's some code (there's a lot here to make it reproducible):
import scikits.statsmodels.api as sm
import pandas as pd
data = sm.datasets.longley.load()
df = pd.DataFrame(data.exog, columns=data.exog_name)
y = data.endog
df['intercept'] = 1.
olsresult = sm.OLS(y, df).fit()
olsresult2 = sm.OLS(y, df[['GNP', 'UNEMP', 'ARMED']]).fit()
olsresult3 = sm.OLS(y, df[['GNP', 'POP', 'ARMED', 'YEAR']]).fit()
models = [olsresult, olsresult2, olsresult3]
class generateTable(object):
def __init__(self, output, models, center='True', parens='se', var_names=None):
self.output = output
self.models = models
self.center = center
self.parens = parens
self.var_names = var_names
def createModel(self):
results = []
for model in self.models:
params = dict(model.params)
bse = dict(model.bse)
pvals = dict(model.pvalues)
results.append(dict((k, [params[k], bse[k], pvals[k]]) for k in sorted(params.iterkeys())))
tempModel = {}
for key in results[0]:
tempModel[key] = [results[0][key]]
for model in results[1:len(results)]:
for key in model:
if key not in tempModel:
tempModel[key] = [['', '', '']]
for i in range(1,len(results)):
diff = set(tempModel) - set(results[i])
for key in results[i]:
tempModel[key].append(results[i][key])
for key in diff:
tempModel[key].append(['','',''])
if self.var_names == None:
self.inputModel = tempModel
elif type(self.var_names) == list:
replace = self.var_names
newResults = []
resultsList = sorted(tempModel.iteritems())
for item in resultsList:
newVar = list(item)
newResults.append(newVar)
for i in range(len(newResults)):
newResults[i][0] = replace[i]
self.inputModel = dict(newResults)
Whenever I try to run the script I receive an error `AttributeError:
'generateTable' object has no attribute 'model'`. IPython points out the line
`bse = dict(model.bse)`. Again, this works when I run it interactively (i.e.
chunk by chunk, no class), but when I import the file and try to run it I
receive the error.
**EDIT:**
1) How is it being created?
import project
a = project.generateTable('/path/to/test.tex', models, center='True', parens='se', var_names=None)
a.createModel()
2) The whole traceback is:
In [26]: a.createModel()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/path/to/project/<ipython-input-26-6774b6d1804c> in <module>()
----> 1 a.createModel()
/path/to/project/project.py in createModel(self)
39 for model in models:
40 params = dict(model.params)
---> 41 bse = dict(model.bse)
42 pvals = dict(model.pvalues)
43 results.append(dict((k, [params[k], bse[k], pvals[k]]) for k in sorted(params.iterkeys())))
3) I'm going to try changing the var name `model` to something else.
4) Sorry about the syntax error. Thank you, asmeurer, for the fix.
**EDIT 2:**
3 above (changing the var name `model` to something else) didn't work.
## EDIT 3:
It works now. Here's the latest code:
def __init__(self, output, models, center='True', parens='se', var_names=None):
self.output = output
self.models = models
self.center = center
self.parens = parens
self.var_names = var_names
def createModel(self):
results = []
for test_model in self.models:
params = dict(test_model.params)
bse = dict(test_model.bse)
pvals = dict(test_model.pvalues)
results.append(dict((k, [params[k], bse.get(k), pvals.get(k)]) for k in sorted(params.iterkeys())))
The only thing that's different is model in the for loop has been changed to
test_model. I tried that before and it didn't work, so I'm not quite sure how
it happend.
Thanks everyone for the help! And if anyone could point how why this change
got rid of that particular error message it'd be greatly appreciated. I'd like
to actually know what I was doing instead of just moving on and accepting it.
Answer: Whenever you see an error like `AttributeError: 'xxx' object has no attribute
'yyy'`, that can only mean one thing: you have an object of type `xxx` and you
are trying to access the attribute `.yyy` but the object doesn't have that
attribute. First rule of debugging: assume the error is telling the truth.
To put it in concrete terms, somewhere you are doing something like:
a = project.generateTable()
...
foo=a.model
When I look at the code you posted, I see nowhere where the attribute `model`
is defined for the class `generateTable`. Do you think you are setting it
somewhere? Either you aren't (which seems to be the case), or you are but you
are setting it at some point after you are first trying to access it.
|
Python how to access subfolder of subfolders
Question: I am new to python and I have trouble accessing the math text-files within the
subfolders.

This is the code I have written so far:
import os, sys
for folder, sub_folders, files in os.walk(my_directory):
for special_file in files:
if special_file == 'math.txt'
file_path = os.path.join(folder, special_file)
with open(file_path, 'r+') as read_file
counter += 1
print('Reading math txt file' + str(counter))
for line in read_file:
print(line)
I am not able to do print lines of all the `math.txt` files within all the
classes and all the schools and all the zones.
Before I had a version of the script that merged all the files, but some of
the log files were extremely large (combined > 16GB).
Answer: This seems to work for me. Only changes were those that @jdi, @MRAB and I were
indicating - missing colons and initializing the `counter` variable. Since
you're on Windows, you may want to make sure that you're properly specifying
your directory path.
import os, sys
# Specify directory
# In your case, you may want something like the following
my_directory = 'C:/Users/<user_name>/Documents/ZoneA'
# Define the counter
counter = 1
# Start the loop
for folder, sub_folders, files in os.walk(my_directory):
for special_file in files:
if special_file == 'math.txt':
file_path = os.path.join(folder, special_file)
# Open and read
with open(file_path, 'r+') as read_file:
print('Reading math txt file ' + str(counter))
# Print the file
for line in read_file:
print(line)
# Increment the counter
counter += 1
|
Made a new model in Django. But it's not showing up in the database
Question: I am using Django 1.1.4 with python 2.6. I just added a new model to the list
of models and used the syncdb command, but it's not showing in the database. I
have already made sure I use 'my_app' name for app label in the Meta class. I
also tried making a new database and syncing all the models again, but
strangely my model is the only one not getting synced. Below I have included
the code:
from django.db import models
from coredump.analyzer.models.model import ExtendedModel
class Netpath(ExtendedModel):
buildno=models.IntegerField()
path = models.CharField(max_length=300)
class Meta:
app_label = 'analyzer'
ordering = ['buildno']
def __unicode__(self):
return '%d' % self.buildno
Extended Model is another model that I have made that works perfectly fine
with the other models in the framework.Adding it's code as well won't be that
useful. Any help will be greatly appreciated
Answer: `syncdb` will only create tables for models found in `<app>.models`. Import
the model class there if necessary.
|
Pythons Multiprocess on Windows in a Package
Question: I am trying to use multiprocess on windows but I am encountering the infinite
loop error. Now I know this can be fixed by using the **name** == "**main** "
in a standard python script. My problem is I am packaging the script so
**name** is equal to "testmultiprocess" (The package name).
I have created a small project on
[github](https://github.com/niallm90/testmultiprocess) to demonstrate my issue
as it requires multiple files and an install.
Thanks, Niall
Edit:
test.py:
from multiprocessing import Process, Queue
def testFunction():
print "testFunction"
def main():
print __name__
p = Process(target=testFunction)
p.start()
p.join()
**name** that is printed is allways "testmultiprocessing" as it is the package
name
Answer: I managed to fix this by patching the script created in the python directory
that runs my package.
**C:\Python27\Scripts\testmultiprocess-script.py**
from:
sys.exit(
load_entry_point(.....)
)
to:
if __name__ == '__main__':
sys.exit(
load_
|
python: export method as function close over object
Question: In python I would like to export an object-method as a normal function. The
object will be closed over. Like in the following:
from functools import partial
class A(object):
def __init__(self,a):
self.a = a
def m(self,b):
return self.a+b
def exportm(self):
return lambda b,self=self: self.m(b)
#return partial(self.m,self=self)
f = A(10).exportm()
print f(5)
This works well and prints 15 as expected. But if I replace the return-lambda-
line with the commented line it will fail giving the following error:
TypeError: m() got multiple values for keyword argument 'self'
I understand that using functools is cleaner than resorting to lambda
expressions. So I'd like to know how to do this using partial or some other
tool in functools.
Answer: `self.m` is already bound, so there's no need to pass `self=self` to it.
Simply return `self.m`. For more arguments, use `partial(self.m, ...)`:
class A(object):
def __init__(self, a):
self.a = a
def m(self, b, c):
return self.a + b + c
def exportm(self):
return partial(self.m, 300)
f = A(10).exportm()
print f(5)
|
calling CLR method with variable arguments from IronPython
Question: I am using Iron Python as an added 'for free' tool to test the an API that
wrapps comms to some custom hardware so the non-development team can play with
the hardware via python.
However I can't work out how to get .NET `void func(params object[] args)` to
map to Python `def (*args)`.
Here is some code to explain.
I have a type that allows injecting a logging callback to format and deal with
messages is follows the signature of Console.WriteLine and Debug.WriteLine.
public class Engine
{
Action<string, object[]> _logger;
public void Run()
{
Log("Hello '{0}'", "world");
}
public void SetLog(Action<string, object[]> logger)
{
_logger = logger;
}
void Log(string msg, params object[] args)
{
_logger(msg, args);
}
}
in my IronPython code
import clr
from System import *
from System.IO import Path
clr.AddReferenceToFileAndPath(Path.GetFullPath(r"MyAssembly.dll"))
from MyNamespace import *
def logger(msg, *args):
print( String.Format(msg, args))
print( String.Format(msg, list(args)))
print( String.Format(msg, [args]))
a=[]
for i in args:
a.append(i)
print( String.Format(msg, a) )
e = Engine()
e.SetLog(logger)
e.Run()
output
Hello '('world',)'
Hello 'IronPython.Runtime.List'
Hello 'IronPython.Runtime.List'
Hello 'IronPython.Runtime.List'
I would like
Hello 'world'
Answer: Because [String.Format](http://msdn.microsoft.com/en-
us/library/system.string.format.aspx) handles your iron python objects (tuple
for your first output case, lists for the last three) as single objects and is
not aware that you would like the python collection to be used as `params
object[]` you are getting the unexpected output. The single python
object/tuple is implicitly created when `def logger` is invoked.
Depending on your actual use-case/style you can solve this in different ways.
The most python-y way would be expanding the arguments at their call site like
Jeff explains in his answer:
def logger(msg, *args):
print( String.Format(msg, *args) )
If you call `logger` only as from CLR as implementation of `Action<string,
object[]>` you could just have `args` be a single (not variable) argument of
type `object[]` like
def logger(msg, args):
print( String.Format(msg, args) )
If you would like to call `logger` from python with variable arguments as well
(and you don't mind the back and forth conversion) you could do
def logger(msg, *args):
print( String.Format(msg, Array[object](args)) )
|
Python nosetests skip certain Tests
Question: I am working on tests for a web application written in python.
Suppose I have 5 tests in my test_login.py module.
Every single test is a Class.
There is often one, base test that extends TestFlow class, which is our
predefined test class.
And then other tests in this module extend that base test.
For instance :
#The base test
TestLogin(TestFlow):
#do login_test_stuff_here
#Another test in the same module
TestAccountDetails(TestLogin)
#do account_details_test_stuff_here
...
It's actually quite handy, because in order to test for example AccountDetails
user has to be logged in, so I can just inherit from TestLogin test and I am
ready to test other functionality as a logged user.
All tests are in Project/project/tests folder.
We use nosetests with option --with-pylons to run tests.
And my question is if there is a way to mark certain TestClass as "Do not test
this one".
Because I don't want to waste time to execute these "base tests" directly,
because they will be execute by other tests that iherit from them.
There will be probably tones of these tests and I want to save every single
second where it is possible.
I've already found something like Skip, SkipTest or @nottest, but these only
work for **test_methods** within a ceratin TestClass, so I don't think it will
work here, were I have a single class for each test case.
Answer: Form nosetests it can be done as below by specifying the attributes
<http://nose.readthedocs.org/en/latest/plugins/attrib.html>
> Oftentimes when testing you will want to select tests based on criteria
> rather than simply by filename. For example, you might want to run all tests
> except for the slow ones. You can do this with the Attribute selector plugin
> by setting attributes on your test methods. Here is an example:
>
>
> def test_big_download():
> import urllib
> # commence slowness...
>
> test_big_download.slow = 1
>
>
> Once you’ve assigned an attribute slow = 1 you can exclude that test and all
> other tests having the slow attribute by running
>
>
> $ nosetests -a '!slow'
>
|
Better ways to get nth element from an unsubscriptable iterable
Question: Sometimes an iterable might be not subscriptable. Say the return from
`itertools.permutations`:
ps = permutations(range(10), 10)
print ps[1000]
Python will complain that `'itertools.permutations' object is not
subscriptable`
Of course one can perform `next()` by `n` times to get the nth element. Just
wondering are there better ways to do so?
Answer: Just use `nth` recipe from
[`itertools`](http://docs.python.org/library/itertools.html#recipes)
>>> from itertools import permutations, islice
>>> def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
>>> print nth(permutations(range(10), 10), 1000)
(0, 1, 2, 4, 6, 5, 8, 9, 3, 7)
|
importing without executing the class - python
Question: my problem is about i have a file that contain class and inside this class
there is bunch of code will be executed
so whenever i import that file it will executed ! without creating an object
of the class ! , here is the example
FILE `X`
class d:
def __init__(self):
print 'print this will NOT be printed'
print "this will be printed"
file `B`
import x
output is `this will be printed`, so my question is **how to skip executing it
until creating a new object?**
Answer: You can't do that in Python, in Python every class is a first level object, a
Python class is an object too and an class attribute can exist even if there
is no instances of that class. If you just want to suppress the output of the
print statement you can redirect the output of your print statements on the
importing moment or create a context like the one provided in [this first
answer](http://stackoverflow.com/questions/1809958/hide-stderr-output-in-unit-
tests) and use the `__import__` statement manually.
|
Alternate Data Streams on a folder
Question: I'm using StgCreateStorageEx from python win32com based adapting the code in
[testStorage.py](http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/file/9f6fdae45eb7/com/win32com/test/testStorage.py)
to write my own file_id attribute onto any file.
According to [alternate-
streams](http://www.flexhex.com/docs/articles/alternate-streams.phtml) (though
not necessarily from this API call) it should be possible to save to a
directory/folder, but changing the flags yield different errors, eg:
from win32com import storagecon
import pythoncom, os, win32api
fname = r"c:\temp\test\test.txt" #works
fname = r"c:\temp\test\test2"
def testit():
m=storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE
pss=pythoncom.StgOpenStorageEx(fname, m, storagecon.STGFMT_FILE, 0, pythoncom.IID_IPropertySetStorage)
results in:
> pywintypes.com_error: (-2147024895, 'Incorrect function.', None, None)
**EDIT:** Any suggestions on how to get this to work from both WinXP, Win7 and
Windows Server 2003/R2?
Note that the end result does not necessarily need to use this API, I just
need to be able to do it efficiently from Python. By efficiently I mean not
through many different technology layers.
Answer: It succeeds if storagecon.STGM_DIRECT is added to the mode.
|
Error connecting to mysqldb
Question: how to solve the following error on the below code. The application is a
python phones application that retrieves names and phone numbers from a
mysqldb database. The line that gives me the error is phoneList =
c.fetchrows(). I really appreciate your assistance.
# AttributeError: 'NoneType' object has no attribute 'fetchrows'
#connecting to database
from Tkinter import *
import MySQLdb
db = MySQLdb.connect(host = "localhost", user = "xxxxxxx", passwd = "xxxxxxxx", db ="test")
# which item is selected
def whichSelected () :
print "At %s" % (select.curselection())
return int(select.curselection()[0])
# doing sql query
def dosql (cmd) :
print cmd
c = db.query(cmd)
setSelect ()
# the generation of new id numbers as new rows are inserted.
def addEntry () :
c = db.query("select max(id)+1 from phones")
id = c.fetchdict()[0].values()[0] # digs deep to get next id
dosql("insert into phones values (%d,'%s','%s')" % (id,nameVar.get(), phoneVar.get()))
#updating the entries
def updateEntry() :
id = phoneList[whichSelected()][0]
dosql("update phones set name='%s', phone='%s' where id=%d" %
(nameVar.get(), phoneVar.get(), id))
# deleting the entries
def deleteEntry() :
id = phoneList[whichSelected()][0]
dosql("delete from phones where id=%d" % id)
# loading the entries
def loadEntry () :
id, name, phone = phoneList[whichSelected()]
nameVar.set(name)
phoneVar.set(phone)
# building my windows
def makeWindow () :
global nameVar, phoneVar, select
win = Tk()
frame1 = Frame(win)
frame1.pack()
.
.
.
.
# the function "setSelect" which fills in our list control. Here, instead of importing the phone list, we simply use fetchrows to get the same list of lists.
def setSelect () :
global phoneList
c = db.query("select id,name,phone from phones order by name")
phoneList = c.fetchrows()
select.delete(0,END)
for id,name,phone in phoneList :
select.insert (END, name)
win = makeWindow()
setSelect()
win.mainloop()
Answer: So the main reason is that `db.query` doesn't return anything - you have to
use either `db.store_result()` or `db.use_result()` (see the full docs
[here](http://mysql-python.sourceforge.net/MySQLdb.html)). However that is
using `_mysql`\- we'll use `MySQLdb` in this example:
def setSelect():
global phoneList
# You have your connection db set up, so now we make a cursor
c = db.cursor()
# Now execute your query using the cursor 'execute' method
c.execute("select id,name,phone from phones order by name")
# Now we pull the results from the query and store them in phoneList
phoneList = c.fetchall()
# And I know nothing about Tkinter, so hopefully the rest will work :)
select.delete(0,END)
# phoneList will represent each row as a tuple, so make sure to verify this part
for id,name,phone in phoneList :
select.insert (END, name)
Hope that helps!
|
Python tkinter app adding a right click context menu?
Question: I have a python-tkinter gui app that I've been trying to find some way to add
in some functionality. I was hoping there would be a way to right-click on an
item in the app's listbox area and bring up a context menu. Is tkinter able to
accomplish this? Would I be better off looking into gtk or some other gui-
toolkit?
Answer: Here is an example from [effbot](http://effbot.org/tkinterbook/menu.htm) that
uses the Menu widget to create a "popup menu":
from Tkinter import * # Tkinter -> tkinter in Python 3
root = Tk()
def hello():
print "hello!"
# create a popup menu
menu = Menu(root, tearoff=0)
menu.add_command(label="Undo", command=hello)
menu.add_command(label="Redo", command=hello)
# create a frame
frame = Frame(root, width=512, height=512)
frame.pack()
def popup(event):
menu.post(event.x_root, event.y_root)
# attach popup to frame
frame.bind("<Button-3>", popup)
root.mainloop()
Here is the same example written as a class:
import Tkinter as tki # Tkinter -> tkinter in Python 3
class GUI(tki.Tk):
def __init__(self):
tki.Tk.__init__(self)
# create a popup menu
self.aMenu = tki.Menu(self, tearoff=0)
self.aMenu.add_command(label="Undo", command=self.hello)
self.aMenu.add_command(label="Redo", command=self.hello)
# create a frame
self.aFrame = tki.Frame(self, width=512, height=512)
self.aFrame.pack()
# attach popup to frame
self.aFrame.bind("<Button-3>", self.popup)
def hello(self):
print "hello!"
def popup(self, event):
self.aMenu.post(event.x_root, event.y_root)
gui = GUI()
gui.mainloop()
|
How to fix this UnicodeDecodeError that appears when I try to remove accents in Python strings?
Question: I'm trying to use this function:
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
in the code below (which unzips and reads files with non-ASCII strings). But
I'm getting this error, (from this library file
`C:\Python27\Lib\encodings\utf_8.py`):
Message File Name Line Position
Traceback
<module> C:\Users\CG\Desktop\Google Drive\Sci&Tech\projects\naivebayes\USSSALoader.py 64
getNameList C:\Users\CG\Desktop\Google Drive\Sci&Tech\projects\naivebayes\USSSALoader.py 26
remove_accents C:\Users\CG\Desktop\Google Drive\Sci&Tech\projects\naivebayes\USSSALoader.py 17
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 3: ordinal not in range(128)
Why am I getting this error? How to avoid it and make `remove_accents` work?
Thanks for any help!
Here's the entire code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import os
import re
from zipfile import ZipFile
import csv
##def strip_accents(s):
## return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
def getNameList():
namesDict=extractNamesDict()
maleNames=list()
femaleNames=list()
for name in namesDict:
print name
# name = strip_accents(name)
name = remove_accents(name)
counts=namesDict[name]
tuple=(name,counts[0],counts[1])
if counts[0]>counts[1]:
maleNames.append(tuple)
elif counts[1]>counts[0]:
femaleNames.append(tuple)
names=(maleNames,femaleNames)
# print maleNames
return names
def extractNamesDict():
zf=ZipFile('names.zip', 'r')
filenames=zf.namelist()
names=dict()
genderMap={'M':0,'F':1}
for filename in filenames:
file=zf.open(filename,'r')
rows=csv.reader(file, delimiter=',')
for row in rows:
#name=row[0].upper().decode('latin1')
name=row[0].upper()
gender=genderMap[row[1]]
count=int(row[2])
if not names.has_key(name):
names[name]=[0,0]
names[name][gender]=names[name][gender]+count
file.close()
# print '\tImported %s'%filename
# print names
return names
if __name__ == "__main__":
getNameList()
Answer: You get it because you are decoding from a bytestring without specifying a
codec:
unicode(input_str)
Add a codec there (here I assume your data is encoded in utf-8, `0xe1` would
be the first of a 3-byte character):
unicode(input_str, 'utf8')
|
Python3: How to dynamically resize button text in tkinter/ttk?
Question: I want to know how to arrange for the text on a ttk widget (a label or button,
say) to resize automatically.
Changing the size of the text is easy, it is just a matter of changing the
font in the style. However, hooking it into changes in the size of the window
is a little more tricky. Looking on the web I found some hints, but there was
nowhere a complete answer was posted.
So, here below is a complete working example posted as an answer to my own
question. I hope someone finds it useful. If anyone has further improvements
to suggest, I will be delighted to see them!
Answer: The example below shows two techniques, one activated by re-sizing the window
(see the `resize()` method, bound to the `<Configure>` event), and the other
by directly changing the size of the font (see the `mutate()` method).
Other code necessary to get resizing working is the grid configuration code in
the `__init__()` method.
When running the example, there is some interaction between the two methods,
but I think in a 'real' situation one technique would be sufficient, so that
issue won't arise.
from tkinter import *
from tkinter.ttk import *
class ButtonApp(Frame):
"""Container for the buttons."""
def __init__(self, master=None):
"""Initialize the frame and its children."""
super().__init__(master)
self.createWidgets()
# configure the frame's resize behaviour
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
self.grid(sticky=(N,S,E,W))
# configure resize behaviour for the frame's children
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# bind to window resize events
self.bind('<Configure>', self.resize)
def createWidgets(self):
"""Make the widgets."""
# this button mutates
self.mutantButton = Button(self, text='Press Me',
style='10.TButton')
self.mutantButton.grid(column=0, row=0, sticky=(N,S,E,W))
self.mutantButton['command'] = self.mutate
# an ordinary quit button for comparison
self.quitButton = Button(self, text='Quit', style='TButton')
self.quitButton.grid(column=0, row=1, sticky=(N,S,E,W))
self.quitButton['command'] = self.quit
def mutate(self):
"""Rotate through the styles by hitting the button."""
style = int(self.mutantButton['style'].split('.')[0])
newStyle = style + 5
if newStyle > 50: newStyle = 10
print('Choosing font '+str(newStyle))
self.mutantButton['style'] = fontStyle[newStyle]
# resize the frame
# get the current geometries
currentGeometry = self._root().geometry()
w, h, x, y = self.parseGeometry(currentGeometry)
reqWidth = self.mutantButton.winfo_reqwidth()
reqHeight = self.mutantButton.winfo_reqheight()
# note assume height of quit button is constant at 20.
w = max([w, reqWidth])
h = 20 + reqHeight
self._root().geometry('%dx%d+%d+%d' % (w, h, x, y))
def parseGeometry(self, geometry):
"""Geometry parser.
Returns the geometry as a (w, h, x, y) tuple."""
# get w
xsplit = geometry.split('x')
w = int(xsplit[0])
rest = xsplit[1]
# get h, x, y
plussplit = rest.split('+')
h = int(plussplit[0])
x = int(plussplit[1])
y = int(plussplit[2])
return w, h, x, y
def resize(self, event):
"""Method bound to the <Configure> event for resizing."""
# get geometry info from the root window.
wm, hm = self._root().winfo_width(), self._root().winfo_height()
# choose a font height to match
# note subtract 30 for the button we are NOT scaling.
# note we assume optimal font height is 1/2 widget height.
fontHeight = (hm - 20) // 2
print('Resizing to font '+str(fontHeight))
# calculate the best font to use (use int rounding)
bestStyle = fontStyle[10] # use min size as the fallback
if fontHeight < 10: pass # the min size
elif fontHeight >= 50: # the max size
bestStyle = fontStyle[50]
else: # everything in between
bestFitFont = (fontHeight // 5) * 5
bestStyle = fontStyle[bestFitFont]
# set the style on the button
self.mutantButton['style'] = bestStyle
root = Tk()
root.title('Alice in Pythonland')
# make a dictionary of sized font styles in the range of interest.
fontStyle = {}
for font in range(10, 51, 5):
styleName = str(font)+'.TButton'
fontName = ' '.join(['helvetica', str(font), 'bold'])
fontStyle[font] = styleName
Style().configure(styleName, font=fontName)
# run the app
app = ButtonApp(master=root)
app.mainloop()
root.destroy()
|
wpa-handshake with python - hashing difficulties
Question: I try to write a Python program which calculates the WPA-handshake, but I have
problems with the hashes. For comparison I installed cowpatty _(to see where I
start beeing wrong)_.
My PMK-generation works fine, but the PTK-calculation alsways seems to be
wrong. I am not sure if I have to format my input _(macadresses and noces)_ or
just give them into the function as a string.
I will give you my routerinformation, which is no problem since I just set it
up for testing.
My program looks as follows:
import hmac,hashlib,binascii
passPhrase = "10zZz10ZZzZ"
ssid = "Netgear 2/158"
A = "Pairwise key expansion"
APmac = "001e2ae0bdd0"
Clientmac = "cc08e0620bc8"
ANonce = "61c9a3f5cdcdf5fae5fd760836b8008c863aa2317022c7a202434554fb38452b"
SNonce = "60eff10088077f8b03a0e2fc2fc37e1fe1f30f9f7cfbcfb2826f26f3379c4318"
B = min(APmac,Clientmac)+max(APmac,Clientmac)+min(ANonce,SNonce)+max(ANonce,SNonce)
data="0103005ffe010900200000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
def customPRF512(key,A,B):
blen = 64
i = 0
R = ''
while i<=((blen*8+159)/160):
hmacsha1 = hmac.new(key,A+chr(0x00)+B+chr(i),sha)
i+=1
R = R+hmacsha1.digest()
return R[:blen]
pmk = pbkdf2(passPhrase, ssid, 4096, 32) #no sourcecode, since b2a_p(pmk) output fits to those of cowpatty
ptk = customPRF512(pmk,A,B) #the prf-function fits the pseudocode in the ieee, but does not give me the correct output (like cowpatty does)
# and i have no idea why :(
print b2a_p(pmk),"\n\n\n"
print b2a_p(ptk),"\n\n\n"
mic1 = hmac.new(ptk[0:16],data)
print mic1.hexdigest() #should be the mic-calculation, not sure if this is correct...
the desired outputs _(which cowpatty confirmed)_ are:
PMK is
01b8 09f9 ab2f b5dc 4798 4f52 fb2d 112e
13d8 4ccb 6b86 d4a7 193e c529 9f85 1c48
Calculated PTK for "10zZz10ZZzZ" is
bf49 a95f 0494 f444 2716 2f38 696e f8b6
428b cf8b a3c6 f0d7 245a d314 a14c 0d18
efd6 38aa e653 c908 a7ab c648 0a7f 4068
2479 c970 8aaa abc3 eb7e da28 9d06 d535
Calculated MIC with "10zZz10ZZzZ" is
4528 2522 bc67 07d6 a70a 0317 a3ed 48f0
Maybe someone of you could tell me, why my program simply doesn't work. Do the
hmac-functions work correctly? Is my input formatted wrong? Do I have to
regard endianess anywhere? Thanks for your time in advance, I would appreciate
any help!
Answer: Alright, I figured it out by myself... more by desperate testing and some
luck, than successful research, which lead to nothing long enough. Instead of
using the MAC-adresses and nonces as the strings they were, I had to unhexlify
them. I used
a2b_hex() #alternatively unhexlify()
My final code looks somewhat like this, defs excluded:
import hmac,hashlib,binascii
passPhrase="10zZz10ZZzZ"
ssid = "Netgear 2/158"
A = "Pairwise key expansion"
APmac = a2b_hex("001e2ae0bdd0")
Clientmac = a2b_hex("cc08e0620bc8")
ANonce = a2b_hex("61c9a3f5cdcdf5fae5fd760836b8008c863aa2317022c7a202434554fb38452b")
SNonce = a2b_hex("60eff10088077f8b03a0e2fc2fc37e1fe1f30f9f7cfbcfb2826f26f3379c4318")
B = min(APmac,Clientmac)+max(APmac,Clientmac)+min(ANonce,SNonce)+max(ANonce,SNonce)
data = a2b_hex("0103005ffe01090020000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
pmk = pbkdf2(passPhrase, ssid, 4096, 32)
ptk = customPRF512(pmk,A,B)
mic = hmac.new(ptk[0:16],data)
print "desiredpmk:\t","01b809f9ab2fb5dc47984f52fb2d112e13d84ccb6b86d4a7193ec5299f851c48"
print "pmk:\t\t",b2a_hex(pmk),"\n"
print "desired ptk:\t","bf49a95f0494f44427162f38696ef8b6"
print "ptk:\t\t",b2a_hex(ptk[0:16]),"\n"
print "desired mic:\t","45282522bc6707d6a70a0317a3ed48f0"
print "mic:\t\t",mic.hexdigest(),"\n"
So the answers to my questions were: yes, hashfunctions work correctly, yes,
input is formatted wrong, no, no endianess-issues.
|
PYTHON: Trying to create a vocabulary/translation quiz (Beginner)
Question: I'm new to Python (and also to stackoverflow, as you will easily notice it !)
I'm actually trying to write a program that would work as follow : the user
launch the program. he's being asked whether he wants to enter a new word, and
the translation of that word. The word and its translation are stored in a
file (data.txt). When he's done adding new words, the quiz starts. The program
pick a word, and ask the user for the translation. If the answer is similar to
the translation in the file, the program returns "Great !", if not, it prints
the correct answer.
As you can see, it's pretty simple. My problem here is working with the file,
especially retrieving what is inside the file and using it correctly.
Here is my code :
#!/usr/bin/python3.2
# -*-coding:Utf-8 -*
#Vocabulary/translation quiz
import os
import random
keep_adding=input("Would you like to add a new word ? If yes, press \"O\" : ")
while keep_adding=="O":
entry=[]
word=input("Enter a word : ")
word=str(word)
entry.append(word)
translation=input("And its translation : ")
translation=str(translation)
entry.append(translation)
entry=str(entry)
f = open("data.txt","a")
f.write(entry)
f.close()
keep_adding=input("To continue, press \"O\" : ")
f = open("data.txt","a") #in case the file doesn't exist, we create one
f.close()
os.system('clear')
print("* * * QUIZ STARTS ! * * *")
f = open("data.txt","r")
text = f.readlines()
text = list(text)
print("What is the translation for : ",text[0], "?")
answer = input("Answer : ")
if (answer == text[1]):
print("Congratulations ! That's the good answer !")
else:
print("Wrong. The correct answer was : ",text[1])
Thanks a lot for your help !
**EDIT :** did bring some corrections to my code. What I get is the following
:
* * * QUIZ STARTS ! * * *
What is the translation for : ['alpha', 'bravo']['one', 'two']['x', 'y'] ?
Answer : alpha
Traceback (most recent call last):
File "Python_progs/voc.py", line 43, in <module>
if (answer == text[1]):
IndexError: list index out of range
and in my file, I have this :
['alpha', 'bravo']['one', 'two']['x', 'y']
So actually, I would like to get only the first word in the question (i.e.
alpha) and when answering bravo, having it right.
Answer: ### The problem
You're main issue is the way you're storing/retrieving things in the quiz
file.
You're doing `f.write(str(entry))`, which is writing the string representation
of the entry. I'm not quite sure what your intent is here, but you should
realize two things: 1) `str` representations of lists are tricky to turn back
into lists (when reading the file) and 2) `write()` doesn't append newlines at
the end. If you were to do:
f.write("line1")
f.write("line2")
f.write("line3")
Then your file would look like this:
line1line2line3
Anyway, everything is saved on one line, so when you do `f.readlines()`, this
returns an object like so:
["['alpha', 'bravo']['one', 'two']['x', 'y']"]
Or more generally:
[a_string,]
As you can see, it's a list with only one item in it. That's why you get an
error when you do
if (answer == text[1]):
You're trying to access a second item that doesn't exist.
### The solution?
What you need to do is store each quiz/answer pair as a separate line, with a
specific delimiter separating the quiz and answer:
quiz, answer
alpha, bravo
one, two
etc...
For example:
with open("myquizfile.txt", "w") as f:
while keepGoing: #You'd have to add your own exit logic.
question = input("Enter a question: ")
answer = input("Enter an answer: ")
f.write("{0},{1}\n".format(question, answer)) #Notice the newline, \n
And to read this file, you'd do something like this:
with open("myquizfile.txt", "r") as f:
question_answer_pairs = [line.split(",") for line in f]
|
Python + Windows: How to write a script that pops up a reminder on computer sleep/shutdown?
Question: I want to write a Python script that will remind me to take my medicine on
sleep/shutdown. (just a simple pop up message). Where do I begin?
(I'm looking for a really simple implementation if it exists. I don't want to
put too much effort into this)
Answer: This will tell you how to detect event
Linux:- [Detect user logout / shutdown in Python / GTK under Linux -
SIGTERM/HUP not received](http://stackoverflow.com/questions/2490166/detect-
user-logout-shutdown-in-python-gtk-under-linux-sigterm-hup-not-rece).
Windows :- [Python - Windows Shutdown
Events](http://stackoverflow.com/questions/1411186/python-windows-shutdown-
events)
And this will pop up notice
from tkinter import *
root = Tk()
w = Label(root, text="Take your Medicine \n :):)...Get Well Soon...")
w.pack()
root.mainloop()
|
Danger of mixing numpy matrix and array
Question: The science/engineering application I'm working on has lots of linear algebra
matrix multiplications, therefore I use Numpy matrices. However, there are
many functions in python that interchangeably accept matrix or array types.
Nice, no? Well, not really. Let me demonstrate the problem with an example:
from scipy.linalg import expm
from numpy import matrix
# Setup input variable as matrix
A = matrix([[ 0, -1.0, 0, 0],
[ 0, 0, 0, 1.0],
[ 0, 0, 0, 0],
[ 0, 0, 1.0, 0]])
# Do some computation with that input
B = expm(A)
b1 = B[0:2, 2:4]
b2 = B[2:4, 2:4].T
# Compute and Print the desired output
print "The innocent but wrong answer:"
print b2 * b1
print "The answer I should get:"
print matrix(b2) * matrix(b1)
When run you get:
The innocent but wrong answer:
[[-0.16666667 -0.5 ]
[ 0. 1. ]]
The answer I should get, since I expected everything to still be matrices:
[[ 0.33333333 0.5 ]
[ 0.5 1. ]]
Any tips or advice on how to avoid this sort of a mix up? Its really messy to
keep wrapping variables in matrix() calls to ensure they still are matrices.
It seems there is no standard in this regard, and so it can lead to bugs that
are hard to detect.
Answer: I tend to use `array` instead of `matrix` in `numpy` for a few reasons:
1. `matrix` is strictly 2D whereas you can have a `numpy` `array` of any dimension.
2. Aside from a few differences, `array` and `matrix` operations are pretty much [interchangeable](http://www.scipy.org/NumPy_for_Matlab_Users) for a Matlab user.
3. If you use `array` consistently, then you would use `numpy.dot()` (or in Python 3.5 the new `@` binary operator) for matrix multiplication. This will prevent the problem of not sure what `*` actually does in your code. And when you encounter a multiplication error, you can find the problem easier since you are certain of what kind of multiplication you are trying to perform.
So I would suggest you try to stick to `numpy.array`, but also keep in mind
the differences between `array` and `matrix`.
Lastly, I found it a joy to work with `numpy/scipy` on
[bpython](http://bpython-interpreter.org). The auto-prompt helps you to learn
the properties of the function you are trying to use at a much faster pace
than having to consult the `numpy/scipy` doc constantly.
**Edit:** The difference between `array` vs `matrix` is perhaps best answered
here: [**'array' or 'matrix'? Which should I use?**
](http://www.scipy.org/NumPy_for_Matlab_Users#head-e9a492daa18afcd86e84e07cd2824a9b1b651935)
|
Trying to serve django static files on development server - not found
Question: I've followed the instructions in [this
question](http://stackoverflow.com/q/9197599/344286), [the
documentation](https://docs.djangoproject.com/en/dev/howto/static-files/), and
I've even looked at [this one](http://stackoverflow.com/q/10644649/344286),
but so far I'm unable to get at my static files using `python manage.py
runserver`.
These are my (relevant?) settings:
STATIC_ROOT '/home/wayne/programming/somesite/static'
STATICFILES_DIRS ('/home/wayne/programming/somesite/static/styles',
'/home/wayne/programming/somesite/static/admin')
In my urls.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# The rest of my urls here...
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
I have the following code in my base.html
<link rel="stylesheet" type="text/css" href="{% static "styles/main.css" %}">
{% block styles %}
{% for sheet in styles %}
<link rel="stylesheet" type="text/css" href="{% static sheet %}">
{% endfor %}
And I promise I'm not hallucinating:
(.env)wayne:~/programming/somesite/static$ pwd
/home/wayne/programming/somesite/static
(.env)wayne:~/programming/somesite/static$ ls
admin styles
However, when navigate to `http://localhost:8000/` my site is missing its
stylesheets, and when I go to `http://localhost:8000/static/styles/main.css` I
get `'styles/main.css' could not be found`, and trying to navigate to
`localhost:8000/static/`, or `localhost:8000/static/styles` it tells me that
Directory indexes are not allowed.
What am I missing here?
Answer: Django's handling of static files continue to be slightly confusing,
particularly in terms of the naming of relevant settings.
The short answer is to move your static files; instead of
/home/wayne/programming/somesite/static
put them in
/home/wayne/programming/somesite/yourapp/static
(where "yourapp" is obviously the name of your main application).
The longer answer is that I think you've (understandably) become confused
about the various settings. `STATIC_ROOT` _only_ refers to the location
**where your static files should end up** after running `manage.py
collectstatic`. You don't need this set (as you shouldn't really need
`collectstatic`) when developing locally. Either way, `STATIC_ROOT` should
always refer to an empty directory.
Your `STATICFILES_DIRS` setting would almost work, except that you've told
Django there are two paths where it should find static files
/home/wayne/programming/somesite/static/styles
/home/wayne/programming/somesite/static/admin
so when you do `{% static "styles/main.css" %}` it will look for
/home/wayne/programming/somesite/static/styles/styles/main.css
/home/wayne/programming/somesite/static/admin/styles/main.css
and will obviously not find them. What _might_ work is
STATICFILES_DIRS = ('/home/wayne/programming/somesite/static',)
but there's no need to do that, as you can just rely on
`django.contrib.staticfiles.finders.AppDirectoriesFinder` (in [the default
STATICFILES_FINDERS](https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std%3asetting-
STATICFILES_FINDERS)) and move your static files to an app directory.
Hope this clears things up a little.
|
importing updated files into a database
Question: I have files that are updated every 2 hours. I have to detect the files
automatically and insert the extracted information from them into a database.
Our DBMS is Postgresql and programming language is Python. How would you
suggest I do that?
I want to make use of DAL (Database Abstraction Layer) to make connection
between the files and database and use postgresql `LISTEN`/`NOTIFY` techniques
to detect the new files. If you agree with me please tell me how I can use
`LISTEN`/`NOTIFY` functions to detect the files.
Thank you
Answer: What you need is to write a script that stays running as a dæmon, using a file
system notify API to run a callback function when the files change. When the
script is notified that the files change it should connect to PostgreSQL and
do the required work, then go back to sleep waiting for the next change.
The only truly cross platform way to watch a directory for changes is to use a
delay loop to poll `os.listdir` and `os.stat` to check for new files and
updated modification times. This is a waste of power and disk I/O; it also
gets slow for big sets of files. If your OS reliably changes the directory
modification time whenever files within the directory change you can just
`os.stat` the directory in a delay-loop, which helps.
It's much better to use an operating system specific notification API. Were
you using Java I'd tell you to use the NIO2 [watch
service](http://docs.oracle.com/javase/tutorial/essential/io/notification.html),
which handles all the platform specifics for you. It looks like
[Watchdog](http://packages.python.org/watchdog/) may offer something similar
for Python, but I haven't needed to do directory change notification in my
Python coding so I haven't tested it. If it doesn't work out you can use
platform-specific techniques like inotify/dnotify for Linux, and the various
watcher APIs for Windows.
See also:
* [How do I watch a file for changes using Python?](http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python)
* [Python daemon to watch a folder and update a database](http://stackoverflow.com/questions/2314892/python-daemon-to-watch-a-folder-and-update-a-database)
|
python regex of group match
Question: here is my code:
import re
pattern_str = '(?P<style>[^|]*>)\|(?P<tags>[^|]*)'
p = re.compile(pattern_str)
m = p.match('OL|AAAAA')
a = m.group('style') # AttributeError: 'NoneType' object has no attribute 'group'
print a
it doesn't work,how to fix it?
THX advance
\----------append1-----------
my python version is 2.6.5
Answer: You have an extra `>` in the `style` pattern:
pattern_str = '(?P<style>[^|]*)\|(?P<tags>[^|]*)'
|
Making a job fail in jenkins
Question: This question might sound weird, but how do I make a job fail?
I have a python script that compiles few files using scons, and which is
running as a jenkins job. The script tests if the compiler can build x64 or
x86 binaries, I want the job to fail if it fails to do one of these.
For instance: if I'm running my script on a 64-bit system and it fails to
compile a 64-bit. Is there something I can do in the script that might cause
to fail?
Answer: If your script exit with a non-zero status the build should fail.
import sys
sys.exit(-1)
|
How to avoid blocking code in python with gevent?
Question: I am playing around with gevent, and I am trying to understand why my code is
blocking and how I can fix it.
I have a pool of greenlets, and each of them talk to a thrift client which
gathers data from a remote thrift server. For the purpose of the exercise, the
thrift server always take > 1s to return any data. When I spawn the greenlets,
and run join, they don't execute all in parallel, but instead one after the
other. My understanding is that this is happening because my code is
"blocking", since when I run `monkey.patch_all()`, all greenlets magically run
in parallel.
So how do I make the code non-blocking myself rather that monkey patching
everything and not understanding what it's doing?
An example here of what I don't understand :
import time
from gevent.pool import Pool
def hello():
print 'Hello %d' % time.time()
time.sleep(1)
def main():
pool = Pool(5)
for _ in xrange(5):
pool.spawn(hello)
pool.join()
if __name__ == '__main__':
main()
Output
Hello 1345477112
Hello 1345477113
Hello 1345477114
Hello 1345477115
Hello 1345477116
I know I could be using gevent.sleep, but how to make that function non
blocking with the regular time.sleep?
Thanks
Answer: Greenlets never run in parallel, they all share the same process and the same
thread, so, there is at most one of them running at a time.
Greenlets are green because they are co-routines ("co" from cooperation),
thus, it can not even be said that they run concurrently, because you need to
coordinate their running. Gevent does most of this work for you behind the
scenes, and knows from libevent (or libev) what greenlets are ready to run.
There is no preemption at all.
On the example you gave, `time.sleep(2)` will put the process to sleep inside
the operating system, so gevent's scheduler won't run and won't be able to
switch to another greenlet.
So, concerning your question: if you don't want to monkey patch an existing
code, you will have to manually replace every blocking call to the gevent's
equivalent, so that gevent may schedule away the calling greenlet and choose
another one to run.
EDIT: Regarding using gevent with thrift without monkey patching all: I don't
know if it is worth.
If you want to modify (fork) thrift's library, just need to change the file
`TSocket.py`, and change:
import socket
to:
from gevent import socket
But then your thrift library will depend on gevent, and you will need to
reapply the patch if you ever update thrift.
You may also subclass `TSocket`, change the method `open()` to use gevent's
socket, and use it in place of the former, but seems more complicated to me.
I am actually using Thrift with Gevent, and I choose for monkey patching the
whole thing for sake of simplicity.
|
(not list inherited) Deck class (card games) can be used in for loops, without __iter__
Question: 'sup guys,
I'm just doing my usual random little programs before my exam within a few
days and I decided to write a five card draw poker. Since it's simply for
playing a bit with code, I didn't inherit anything from basic classes. My deck
contains a list attribute, which has been given the functionality it needs for
simple readability and functionality:
import random
from card import Card
class Deck():
def __init__(self):
self.cards = self.__generate_cards()
random.shuffle(self.cards)
def __str__(self):
cards_str = ""
for card in self.cards:
cards_str += str(card)
return cards_str
def __getitem__(self,index):
return self.cards[index]
def __generate_cards(self):
cards = []
for i in range(4):
for j in range(13):
cards.append(Card(i,j+1))
return cards
def pop(self,index):
return self.cards.pop(index)
as you can see, there is no `.__iter__` method to be found, which means I
can't iterate over a `Deck()` object right? Python shows me a different story:
for some reason the next code results in looping over the card objects in
`self.cards` and actually printing the cards without the need of an
`iterator`:
deck = Deck()
for card in deck:
print(card) # cards have a __str__ method
Doesn't make much sense to me, unless it's part of the python magic, giving
any object a chance for possible looping. ;p Can anyone show me the light with
this one? thanks in advance!
Answer: [Why does defining __getitem__ on a class make it iterable in
python?](http://stackoverflow.com/questions/926574/why-does-defining-getitem-
on-a-class-make-it-iterable-in-python)
It's a back-compat thing. Having `__getitem__` makes it iterable.
|
Is there any case where datetime.fromtimestamp returns an incorrect result using pytz?
Question: `pytz` asks you to use the `.astimezone` method for all time conversion to and
from UTC. However, in one special case — `datetime.fromtimestamp` — it looks
like you should be able to use the Python library's datetime methods.
It seems to work here:
>>> import datetime
>>> import pytz
>>> ambigtime = 1352017800 # http://www.wolframalpha.com/input/?i=1352017800+unix+time+in+Los+Angeles
>>> amla = pytz.timezone('America/Los_Angeles')
>>> datetime.datetime.fromtimestamp(ambigtime, tz=amla)
datetime.datetime(2012, 11, 4, 1, 30, tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)
>>> datetime.datetime.fromtimestamp(ambigtime + 3600, tz=amla)
datetime.datetime(2012, 11, 4, 1, 30, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
Are there situations where `datetime.fromtimestamp` won't give you the correct
results with `pytz` timezones?
Answer: As far as I know, `pytz.timezone()` will give you an instance of
[tzinfo](http://docs.python.org/library/datetime.html#datetime.tzinfo) (or
rather a subclass thereof), and as such is totally fine to use with
`datetime.fromtimestamp()`.
As long as `pytz` has updated zoneinfo files, you can create localized
datetimes using that method. Converting a datetime between two zones however
is really loads easier to do with the `astimezone()` method. If I am correct,
it basically switches the `tzinfo` property on the datetime.
|
Python log-the-display problems
Question: I'm trying to log the terminal display produced by a script which contains a
Scipy optimization routine. I've tried three different ways, all with
disappointing results.
open() and cmd-prompt redirection (">") did not log the warnings nor the per-
iteration information I would like to keep track of; it only logged the
parameter solutions.
logging.basicConfig() produced a blank file.
If possible, I would like to be able to log the exact terminal display of a
script file. I've begun looking into using the logging module, but it seems
pretty complex for what I would think is a very basic task (I'm coming from a
Matlab background).
Environment:
. Python 2.7.3
. Operating Systems: Windows Vista and XP
Answer: Probably the stuff you're interested in is being sent to stderr rather than
stdout. Try redirecting both to a file. You can either do that in Python:
import sys
with open("log.txt", "w") as logfile:
sys.stdout, sys.stderr = logfile, logfile
# do your stuff here, e.g. import the module that you want to log
Or from the command line:
python myscript.py > log.txt 2>&1
|
Is it safe in Python to use 'from copy import copy' statement?
Question: Python has complicated namespaces and modules notion, so i unsure about this.
Normally python `module` and something that is imported from it has different
names or only module is imported and it's content used by fully qualified
name:
import copy # will use copy.copy
from time import localtime # "localtime" has different name from "time".
But what if module has same name as something that i'm importing from it? For
example:
from copy import copy
copy( "something" )
Is it safe? Maybe it's some complicated consequences that i can't see?
Answer: From PEP8 ( <http://www.python.org/dev/peps/pep-0008/#imports>):
When importing a class from a class-containing module, it's usually okay to
spell this:
from myclass import MyClass
from foo.bar.yourclass import YourClass
If this spelling causes local name clashes, then spell them
import myclass
import foo.bar.yourclass
and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".
|
scipy's splrep/splev for python interpolation returns nan
Question: I have a [data set](http://users-phys.au.dk/daniel89/test.txt) with the first
column is the `x` data (wavelenght) and the second column is the `y` data
(relative intensity).
I wish to interpolate it on to another `x_new`-data but my problem is that
`splrep` returns `nan`-values:
>>import numpy as np
>>from scipy.interpolate import splrep, splev
>>d = np.loadtxt("test.txt")
>>x,y = d[:,0],d[:,1]
>>
>>f = splrep( x,y,k=5 )
>>print f
>>(array([ 4501.19, 4501.19, 4501.19, ..., 7091.74, 7091.74, 7091.74]), array([ nan, nan, nan, ..., 0., 0., 0.]), 5)
It also happens when I don't specify `k`. Any suggestions how to overcome this
problem?
Answer: Your `x` values probably contain duplicates, use `s=...` keyword argument to
splrep to set a smoothing factor, because if this is not set the splines are
supposed to go through every point _exactly_ which is impossible with
duplicates.
It might be that they are not duplicates but just very close too.
|
Getting the "wrong" type generated with SQLAlchemy 0.7.8 and Oracle XE
Question: Can anyone please tell me why the DateTime type below creates a "DATE" object
and not a DateTime (or more appropriately, a TIMESTAMP type) as I have to
force the type as in the row below :
#!/bin/python
import sqlalchemy
from sqlalchemy import Column, Integer, String, DateTime, Index, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy.dialects import oracle
Base = declarative_base()
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
class TypeTest(Base):
__tablename__ = "TYPETESTZ"
thisisinteger = Column(Integer, primary_key = True)
thisisnotadatetime = Column(DateTime)
thisisdatetime = Column(oracle.TIMESTAMP)
if __name__ == "__main__":
engine = sqlalchemy.create_engine('oracle://richard:password@xe')
metadata = Base.metadata
metadata.create_all(engine)
Log output:
INFO:sqlalchemy.engine.base.Engine:SELECT USER FROM DUAL
INFO:sqlalchemy.engine.base.Engine:{}
INFO:sqlalchemy.engine.base.Engine:SELECT table_name FROM all_tables WHERE table_name = :name AND owner = :schema_name
INFO:sqlalchemy.engine.base.Engine:{'name': u'TYPETESTZ', 'schema_name': u'RICHARD'}
INFO:sqlalchemy.engine.base.Engine:
CREATE TABLE "TYPETESTZ" (
thisisinteger INTEGER NOT NULL,
thisisnotadatetime DATE,
thisisdatetime TIMESTAMP,
PRIMARY KEY (thisisinteger)
)
INFO:sqlalchemy.engine.base.Engine:{}
INFO:sqlalchemy.engine.base.Engine:COMMIT
Answer: Oracle does not have a `DateTime` data type. In Oracle, a `Date` contains both
a day (i.e. August 21, 2012) and a time (i.e. 1:30 PM) with granularity of 1
second. A `Timestamp`, without additional qualifiers, merely allows you to
increase the granularity to nanoseconds (10^-9 seconds). It seems reasonable
for SQLAlchemy to translate a `DateTime` to an Oracle `Date` unless there is
some requirement that the `DateTime` supports fractional seconds (in which
case you would need a `Timestamp`) or time zones (in which case you would need
a `Timestamp with [local] time zone`).
|
How to make an object in VPython move through the camera automatically?
Question: I have this grocery isle and I'm supposed to make it seem as if the person is
walking through the isle, but in order to do that the object has to pass the
camera and every time it gets close, it hits the frame of the window and it
almost look like it backs off and goes in the opposite direction. But if I
zoom in a little, then it goes through but slows down mid-way. Is there a way
for the object to move through the camera automatically? Thanks
from visual import *
sphere(pos=(0,0,0), radius = 0.5)
text(pos=(-2,1,0), text="Center")
rightside = box(pos=(10,0,-40), axis=(1,300,0), height=0.5, width=60, length=12, material=materials.emissive)
leftside = box(pos=(-10,0,-40), axis=(-1,300,0), height=0.5, width=60, length=12, material=materials.emissive)
bottomside = box(pos=(0,-5.8,-40), axis=(1,0,0), height=0.5, width=60, length=20, color=color.cyan, material=materials.emissive)
leftfirstshelf = box(pos=(8,0,-40), axis=(1,0,0), height=0.5, width=60, length=4, color=color.cyan, material=materials.emissive)
leftsecondshelf = box(pos=(-8,0,-40), axis=(1,0,0), height=0.5, width=60, length=4, color=color.white, material=materials.emissive)
leftthirdshelf = box(pos=(-8,-4,-40), axis=(1,0,0), height=0.5, width=60, length=4, color=color.cyan, material=materials.emissive)
rightfirstshelf = box(pos=(8,4,-40), axis=(1,0,0), height=0.5, width=60, length=4, color=color.white, material=materials.emissive)
rightsecondshelf = box(pos=(-8,4,-40), axis=(1,0,0), height=0.5, width=60, length=4, color=color.cyan, material=materials.emissive)
rightthirdshelf = box(pos=(8,-4,-40), axis=(1,0,0), height=0.5, width=60, length=4, color=color.white, material=materials.emissive)
cheeriosbox = box(pos=(8,6,-60), axis=(1,0,0), height=4, width=2.5, length=0.8, color=color.yellow, material=materials.emissive)
cheeriostext = text(pos=(7.7,7,-61), axis=(0,0,25), height=0.5, width=2.5, length=0.8, color=color.black, text='Cheerios')
watermelon = ellipsoid(pos=(8,2,-40), height=3, width=3.5, length=3, color=color.green, material=materials.emissive)
cokecan = cylinder(pos=(-8,-3.5,-60), height=0, width=0, length=3, color=color.red, material=materials.emissive, axis=(0,7,0))
cokecantext = text(pos=(-7.1,-2,-59), height=1, width=2, length=1, axis=(0,0,-25), color=color.black, text="Coke")
leftcarrotbody = cone(pos=(-8,0.5,-30), radius=0.2, color=color.orange, axis=(0,0,3), material=materials.emissive)
leftcarrottop = sphere(pos=(-8,0.5,-30),radius=0.3, color=color.green, material=materials.emissive)
middlecarrotbody = cone(pos=(-7.5,0.5,-30), radius=0.2, color=color.orange, axis=(0,0,3), material=materials.emissive)
middlecarrottop = sphere(pos=(-7.5,0.5,-30),radius=0.3, color=color.green, material=materials.emissive)
rightcarrotbody = cone(pos=(-7,0.5,-30), radius=0.2, color=color.orange, axis=(0,0,3), material=materials.emissive)
rightcarrottop = sphere(pos=(-7,0.5,-30),radius=0.3, color=color.green, material=materials.emissive)
orangefruit = sphere(pos=(-7.5,5.3,-15), radius=1, color=color.orange, material=materials.emissive)
bottomrowcupone = cylinder(pos=(8,-3.75,-15), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
bottomrowcuptwo = cylinder(pos=(8,-3.75,-14), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
bottomrowcupthree = cylinder(pos=(8,-3.75,-13), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
bottomrowcupfour = cylinder(pos=(8,-3.75,-12), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
thirdrowcupone = cylinder(pos=(8,-2.86,-14.5), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
thirdrowcuptwo = cylinder(pos=(8,-2.86,-13.5), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
thirdrowcupthree = cylinder(pos=(8,-2.86,-12.5), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
secondrowcupone = cylinder(pos=(8,-1.97,-14), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
secondrowcuptwo = cylinder(pos=(8,-1.97,-13), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
topcup = cylinder(pos=(8,-1.08,-13.5), radius=0.5, height=2, axis=(0,0.9,0),color=color.blue, material=materials.emissive)
a = vector(10,0,-40)
b = vector(-10,0,-40)
c = vector(0,-5.8,-40)
d = vector(8,0,-40)
e = vector(-8,0,-40)
f = vector(-8,-4,-40)
g = vector(8,4,-40)
h = vector(-8,4,-40)
i = vector(8,-4,-40)
j = vector(8,6,-60)
k = vector(7.7,7,-61.15)
l = vector(8,2,-40)
m = vector(-8,-3.5,-60)
n = vector(-7.1,-2,-59)
o = vector(-8,0.5,-30)
p = vector(-8,0.5,-30)
q = vector(-7.5,0.5,-30)
r = vector(-7.5,0.5,-30)
s = vector(-7,0.5,-30)
t = vector(-7,0.5,-30)
u = vector(-7.5,5.3,-15)
v = vector(8,-3.75,-15)
w = vector(8,-3.75,-14)
x = vector(8,-3.75,-13)
y = vector(8,-3.75,-12)
z = vector(8,-2.86,-14.5)
aia = vector(8,-2.86,-13.5)
bib = vector(8,-2.86,-12.5)
cic = vector(8,-1.97,-14)
did = vector(8,-1.97,-13)
eie = vector(8,-1.08,-13.5)
while a.z < 100:
rate(20)
rightside.pos = a
leftside.pos = b
bottomside.pos = c
leftfirstshelf.pos = d
leftsecondshelf.pos = e
leftthirdshelf.pos = f
rightfirstshelf.pos = g
rightsecondshelf.pos = h
rightthirdshelf.pos = i
cheeriosbox.pos = j
cheeriostext.pos = k
watermelon.pos = l
cokecan.pos = m
cokecantext.pos = n
leftcarrotbody.pos = o
leftcarrottop.pos = p
middlecarrotbody.pos = q
middlecarrottop.pos = r
rightcarrotbody.pos = s
rightcarrottop.pos = t
orangefruit.pos = u
bottomrowcupone.pos = v
bottomrowcuptwo.pos = w
bottomrowcupthree.pos = x
bottomrowcupfour.pos = y
thirdrowcupone.pos = z
thirdrowcuptwo.pos = aia
thirdrowcupthree.pos = bib
secondrowcupone.pos = cic
secondrowcuptwo.pos = did
topcup.pos = eie
a.z = a.z + 1
b.z = b.z + 1
c.z = c.z + 1
d.z = d.z +1
e.z = e.z + 1
f.z = f.z + 1
g.z = g.z + 1
h.z = h.z + 1
i.z = i.z + 1
j.z = j.z + 1
k.z = k.z + 1
l.z = l.z + 1
m.z = m.z + 1
n.z = n.z + 1
o.z = o.z + 1
p.z = p.z + 1
q.z = q.z + 1
r.z = r.z + 1
s.z = s.z + 1
t.z = t.z + 1
u.z = u.z + 1
v.z = v.z + 1
w.z = w.z + 1
x.z = x.z + 1
y.z = y.z + 1
z.z = z.z + 1
aia.z = aia.z + 1
bib.z = bib.z + 1
cic.z = cic.z + 1
did.z = did.z + 1
eie.z = eie.z + 1
Answer: I got it, there's an auto zoom thing in VPython called autoscaling and in
order to turn that off, the code is `scene.autoscale = False` and all you do
is place it before the while loop. And it stops the camera from zooming out in
order to keep all the objects in the frame.
|
why is Python datetime.date inconsistent with the input format it allows? is this a bug in datetime.date?
Question: Why does using date(2012,08,01) & date(2012,09,01) fail but date(2012,01,01)
through date(2012,07,01) succeed?
I'm using Python v.2.6.6
here is a copy paste from my console
In [2]: from datetime import date
In [6]: date(2012,01,01)
Out[6]: datetime.date(2012, 1, 1)
In [7]: date(2012,02,01)
Out[7]: datetime.date(2012, 2, 1)
In [8]: date(2012,03,01)
Out[8]: datetime.date(2012, 3, 1)
In [9]: date(2012,04,01)
Out[9]: datetime.date(2012, 4, 1)
In [10]: date(2012,05,01)
Out[10]: datetime.date(2012, 5, 1)
In [11]: date(2012,06,01)
Out[11]: datetime.date(2012, 6, 1)
In [12]: date(2012,07,01)
Out[12]: datetime.date(2012, 7, 1)
Everything up to here works then watch when I try to do the same for Aug/Sept
In [13]: date(2012,08,01)
File "<ipython-input-13-765ad867a574>", line 1
date(2012,08,01)
^
SyntaxError: invalid token
In [14]: date(2012,09,01)
File "<ipython-input-14-f150aaea4c6c>", line 1
date(2012,09,01)
^
SyntaxError: invalid token
does anyone know if this this a bug and if it's been resolved in a more
current version of python that is not python 3.0?
Answer: A number prefixed by `0` indicates an octal number in Python (before Python
3). `08` and `09` are not valid octal integers.
|
installing pytz in gae is giving UnknownTimeZoneError
Question: [unutbu](http://stackoverflow.com/users/190597/unutbu) answered my previous
question nicely [here 2](http://stackoverflow.com/questions/11925664/what-is-
the-local-timezone), but there does not appear to be a pytz to import directly
using my SDK. So I went looking for alternatives and found, for example [this
answer](http://stackoverflow.com/questions/10843148/importerror-using-pytz-in-
google-app-engine) which recommends downloading from [here
4](http://pypi.python.org/pypi/gaepytz).
I placed the following code in my local interactive console.
import datetime as dt
import pytz
utc = pytz.utc
western = pytz.timezone('US/Pacific')
I put the downloaded directory `pytz` in my local root directory `scheduler`
and I unzipped the included file `scheduler/pytz/zoneinfo.zip` and got the
following error in the interactive console. I did NOT adjust `app.yaml` at
all; is that correct?
"/Users/brian/googleapps/scheduler/pytz/__init__.py", line 173, in timezone
raise UnknownTimeZoneError(zone)
UnknownTimeZoneError: 'US/Pacific'
I also found an answer to a similar error [here
5](http://stackoverflow.com/questions/1718724/how-to-properly-add-pytz-to-a-
google-app-engine-application) which recommends a patch to the **init**.py
file.
Now I have found an answer [here
6](http://stackoverflow.com/questions/1718724/how-to-properly-add-pytz-to-a-
google-app-engine-application) which suggests that errors occur if VERSION
2010h is used instead of VERSION 2011h and the pytz I downloaded is 2010h.
What is UP?
Is there an easy way to be able to use Wooble's answer with pytz. And does his
answer imply I have to upload the `pytz` directory with my gae app when it is
deployed or is there a pytz alread there?
Answer: You need to call `from pytz.gae import pytz` in order that gae-pytz will work,
otherwise you will be using the regular pytz.
|
Fastest way to count three items referenced by one of them (using python)?
Question: I have a multi column (13 columns) space separated file (some 5 million+
lines), going like this:
1. W5 403 407 P Y 2 2 PR 22 PNIYR 22222 12.753 13.247
2. W5 404 408 N V 2 2 PR 22 PIYYR 22222 13.216 13.247
3. W3 274 276 E G 1 1 EG 11 EPG 121 6.492 6.492
4. W3 275 277 P R 2 1 PR 21 PGR 211 6.365 7.503
5. W3 276 278 G Y 1 1 GY 11 GRY 111 5.479 5.479
6. W3 46 49 G L 1 1 GY 11 GRY 111 5.176 5.176
7. W4 47 50 D K 1 1 DK 11 DILK 1111 4.893 5.278
8. W4 48 51 I K 1 1 IK 11 ILKK 1111 4.985 5.552
etc., etc.,
I'm interested in 2 of these columns (col 8 & 11) and want to count the number
of occurrences of particular pairs (col 8) with the strings that follow (in
col 11).
Ex., reference key 'GY' : # of occurrences of '111' : 2 key 'PR' : # of
occurrences of '22222': 2 key 'DK' : # of occurrences of '1111' :1 key 'EG' :
# of occurrences of '121': 1
I have a dict based basic implementation of it.
countshash={}
for l in bigtable:
cont = l.split()
if cont[7] not in countshash: countshash[cont[7]] = {}
if cont[11] not in countshash[cont[7]]: countshash[cont[7]][cont[10]] = 0
countshash[cont[7]][cont[10]]+= 1;
I also have a simple awk based counting (which is super-fast) but was
wondering about an efficient & faster way to do this in python. Thanks for
your inputs.
Answer: I'm not sure if this will help with speed, but you are creating a ton of
`defaultdict`-like objects, which I think you can make a bit more readable:
from collections import defaultdict
countshash = defaultdict(lambda: defaultdict(int))
for l in bigtable:
cont = l.split()
countshash[cont[7]][cont[10]] += 1
|
Is There Any Way To Check if a Twitch Stream Is Live Using Python?
Question: I'm just wondering if there is any way to write a python script to check to
see if a twitch.tv stream is live? Any and all thoughts are appreciated!
EDIT: I'm not sure why my app engine tag was removed, but this would be using
app engine.
Answer: It looks like Twitch provides an API (documentation
[here](http://apiwiki.justin.tv/mediawiki/index.php/Stream/list)) that
provides a way to get that info. A very simple example of getting the feed
would be:
import urllib2
url = 'http://api.justin.tv/api/stream/list.json?channel=FollowGrubby'
contents = urllib2.urlopen(url)
print contents.read()
This will dump all of the info, which you can then parse with a [JSON
library](http://docs.python.org/library/json.html) (XML looks to be available
too). Looks like the value returns empty if the stream isn't live (haven't
tested this much at all, nor have I read anything :) ). Hope this helps!
|
How do I convert a string to a python datetime object with a relevant timezone?
Question: I have a string similar to "2012-06-14 20:38:24.213-7:00" and want to convert
it to a python date time object with the time zone kept intact, how would I do
this?
Answer: [A fixed offset is not enough to find out the timezone
name.](http://stackoverflow.com/q/1274743/4279)
Otherwise [`pytz`](http://pytz.sourceforge.net/) and/or
[`dateutil`](http://labix.org/python-
dateutil/#head-8d03c6c25ead6f9cab0cde83e6f672b52480ab90) libraries might help:
>>> from dateutil import parser
>>> parser.parse('2012-06-14 20:38:24.213-7:00')
datetime.datetime(2012, 6, 14, 20, 38, 24, 213000, tzinfo=tzoffset(None, -25200))
|
itertools: Cartesian product of permutations
Question: Using pythons `itertools`, I'd like to create an iterator over the outer
product of all permutations of a bunch of lists. An explicit example:
import itertools
A = [1,2,3]
B = [4,5]
C = [6,7]
for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)):
print x
While this works, I'd like to generalize it to an arbitrary list of lists. I
tried:
for x in itertools.product(map(itertools.permutations,[A,B,C])):
print x
but it did not do what I intended. The expected output is:
((1, 2, 3), (4, 5), (6, 7))
((1, 2, 3), (4, 5), (7, 6))
((1, 2, 3), (5, 4), (6, 7))
((1, 2, 3), (5, 4), (7, 6))
((1, 3, 2), (4, 5), (6, 7))
((1, 3, 2), (4, 5), (7, 6))
((1, 3, 2), (5, 4), (6, 7))
((1, 3, 2), (5, 4), (7, 6))
((2, 1, 3), (4, 5), (6, 7))
((2, 1, 3), (4, 5), (7, 6))
((2, 1, 3), (5, 4), (6, 7))
((2, 1, 3), (5, 4), (7, 6))
((2, 3, 1), (4, 5), (6, 7))
((2, 3, 1), (4, 5), (7, 6))
((2, 3, 1), (5, 4), (6, 7))
((2, 3, 1), (5, 4), (7, 6))
((3, 1, 2), (4, 5), (6, 7))
((3, 1, 2), (4, 5), (7, 6))
((3, 1, 2), (5, 4), (6, 7))
((3, 1, 2), (5, 4), (7, 6))
((3, 2, 1), (4, 5), (6, 7))
((3, 2, 1), (4, 5), (7, 6))
((3, 2, 1), (5, 4), (6, 7))
((3, 2, 1), (5, 4), (7, 6))
Answer: You missed the `*` to unpack the list into 3 arguments
itertools.product(*map(itertools.permutations,[A,B,C]))
|
Globals and singletons in Python
Question: I have some few classes which are widespread in my Python application and
which should have only one global instance (eg Logger, DbConnection). Python
does not support static variables/methods in a class, so the usual Java/C++
way to create a singleton here does not work. I have looked for alternatives
to implement singleton in Python. I want a simple (no metaprogramming if
possible) and clean implementation. This looks good:
class MyClass(object):
def a():
pass
singleton = MyClass()
Using the singleton would be simple as
import myClass
myClass.singleton.a()
The direct assignment could be replaced by a creation function if object
initialization is not so simple.
I could also create a getInstance() in module scope and always use it to get
myObj.
Question 1) This works ok? The module code (myObj assignment) only runs the
first time it is imported into some other module and myObj won't be created
every time I import this module somewhere?
An alternative method I have seen is to use a globals module. Something like:
from myClass1 import MyClass1
from myClass2 import MyClass2
myObj1 = MyClass1()
myObj2 = MyClass2()
Using this:
import globals
globals.myObj1.a()
I tend to prefer the first alternative.
Question 2) Between the 2 solutions, what do you recommend?
Question 3) A third solution would be passing the widespread objects such as
Logger to several classes/functions, but this is not a good solution imho. Is
there a better solution not mentioned here ?
I'm aware of the downsides of using global variables and singletons. However,
having a global state is not a big issue in my application. I'll prefer
solutions that have code clarity and are simple to use.
Answer: If you want to have a `logger` class that only has one instance, just make it
a separate module.
# In logging.py
def log(msg):
print msg
Then from any script you want logging in.
from logging import log
log("A critical error occured.")
|
Created with py2exe program doesn't work on Windows XP without python
Question: I need to use my python program on many different computers with Windows XP
and 7, without having to download a Python interpreter. So I create *.exe with
py2exe. But when I start it on XP without python installed, I'm getting an
error message: «file is corrupt». Is there any way to start it on XP without
python?
Here's my setup.py:
from distutils.core import setup
import py2exe
setup(
windows=[{"script":"linksender.py"}],
options={"py2exe": {"includes":[]}}
)
Answer: 1.Check your distutils.core.It exist or not.Are you copying the setup.py from
the internet?If so ,Copy distutils.core also. 2.Try this(script
name=myscript.py):
# setup.py
from distutils.core import setup
import py2exe
setup(console=["myscript.py"])
3.Your distutils should be something like this:
#!/usr/bin/env python
from distutils.core import setup
setup(name='Distutils',
version='1.0',
description='Python Distribution Utilities',
author='Greg Ward',
author_email='[email protected]',
url='http://www.python.org/sigs/distutils-sig/',
packages=['distutils', 'distutils.command'],
)
**Note:I am not an expert I have used it once before and it worked for me.**
|
Why does this go code fail?
Question: I have written some go code in FP style to generate primes:
package main
import (
"fmt"
)
func gen_number_stream() func() (int, bool) {
i := 1
return func() (int, bool) {
i += 1
return i, true
}
}
func filter_stream(stream func() (int, bool), f func(int) bool) func() (int, bool) {
return func() (int, bool) {
for i, ok := stream(); ok; i, ok = stream() {
if f(i) {
return i, true
}
}
return 0, false
}
}
func sieve(stream func() (int, bool)) func() (int, bool) {
return func() (int, bool) {
if p, ok := stream(); ok {
remaining := filter_stream(stream, func(q int) bool { return q % p != 0 })
stream = sieve(remaining)
return p, true
}
return 0, false
}
}
func take(stream func() (int, bool), n int) func() (int, bool) {
return func() (int, bool) {
if n > 0 {
n -= 1
return stream()
}
return 0, false
}
}
func main() {
primes := take(sieve(gen_number_stream()), 50)
for i, ok := primes(); ok; i, ok = primes() {
fmt.Println(i)
}
}
when I run this code, it becomes slower and slower and finally gets a runtime
error like this:
runtime: out of memory: [...]
here is a version of python code, and it just runs fine:
def gen_numbers():
i = 2
while True:
yield i
i += 1
def sieve(stream):
p = stream.next()
yield p
for i in sieve( i for i in stream if i % p != 0 ):
yield i
def take(stream,n):
for i,s in enumerate(stream):
if i == 50: break
yield s
def main():
for i in take(sieve(gen_numbers()),50):
print i
if __name__ == '__main__':
main()
I wonder why and how to fix it. Is it a problem of my code or golang compiler?
Thanks!
PS: Sorry for my poor english.
Answer: The problem is your sieve function which is recursive. I suspect that you are
blowing your stack by continually calling sieve recursively in a loop.
func sieve(stream func() (int, bool)) func() (int, bool) {
return func() (int, bool) {
if p, ok := stream(); ok {
remaining := filter_stream(stream, func(q int) bool { return q % p != 0 })
stream = sieve(remaining) // just keeps calling sieve recursively which eventually blows your stack.
return p, true
}
return 0, false
}
}
|
Converting an image instance (file) to an array (python)
Question: I have an image sequence and I am trying to run a script on a specific frame.
I need to switch to this frame and convert it to an array. However, I am
unable to as the frame is an instance `<TiffImagePlugin.TiffImageFile image
mode=I;16 size=512x512 at 0x104A0C998>`. How can I convert this instance to an
array? I have already used numpy.array and it does not work. Thank you!
prot=Image.open("F23BN.tif")
for frame in ImageSequence.Iterator(dna):
if frame==16:
frame.convert('L')
print frame.mode, frame.format #I checked the format and it is still in the Instance format
Answer: As I understand your question, you are trying to get access to the binary data
contained in a tiff image. As Dav1d suggested you can do it in PIL. I tested
the following in python 2.6.5
import Image
import numpy
im = Image.open('Tiff.tif')
imarray = numpy.array(im)
print imarray.shape, im.size #these agree
For a more difficult way to do this, you can open the file just as you would
any other file. In the code snippet, I assume that your file isn't too big to
just load into memory all at once.
im = open('Tiff.tif','r')
image_data = im.read()
im.close()
#lets look at the first few characters
for char in image_data[:64]:
print ord(char), #need to use ord so we can see the number
With the data in the string image_data, you are free to turn it into any other
data type you wish. However, this may not be useful right away. First of all
the data is binary. You will need to decipher it using the tiff specification.
For example, the first 8 bytes are a header.
More details: <http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf>
|
Python module to change system date and time
Question: How can I change System Date, Time, Timezone in Python? Is there any module
available for this?
1. I don't want to execute any system commands
2. I want one common solution, which should work on both Unix and Windows.
Answer:
import sys
import datetime
time_tuple = ( 2012, # Year
9, # Month
6, # Day
0, # Hour
38, # Minute
0, # Second
0, # Millisecond
)
def _win_set_time(time_tuple):
import pywin32
# http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
# pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
dayOfWeek = datetime.datetime(time_tuple).isocalendar()[2]
pywin32.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])
def _linux_set_time(time_tuple):
import ctypes
import ctypes.util
import time
# /usr/include/linux/time.h:
#
# define CLOCK_REALTIME 0
CLOCK_REALTIME = 0
# /usr/include/time.h
#
# struct timespec
# {
# __time_t tv_sec; /* Seconds. */
# long int tv_nsec; /* Nanoseconds. */
# };
class timespec(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long),
("tv_nsec", ctypes.c_long)]
librt = ctypes.CDLL(ctypes.util.find_library("rt"))
ts = timespec()
ts.tv_sec = int( time.mktime( datetime.datetime( *time_tuple[:6]).timetuple() ) )
ts.tv_nsec = time_tuple[6] * 1000000 # Millisecond to nanosecond
# http://linux.die.net/man/3/clock_settime
librt.clock_settime(CLOCK_REALTIME, ctypes.byref(ts))
if sys.platform=='linux2':
_linux_set_time(time_tuple)
elif sys.platform=='win32':
_win_set_time(time_tuple)
I don't have a windows machine so I didn't test it on windows... But you get
the idea.
|
Set up python path in mac osx?
Question: I installed python on mac os (mountain lion) with Macports. When I run $python
It gives an error on "cannot import urandom" when I try to import pandas or
matplotlib.
If I run $python 2.7 Everything runs perfectly.
I want to change python to use python2.7 always.
I tried using sudo port select python python27. But that didn't help.
Please help me on this, I'm new to mac.
Answer: First let me preface by saying that OSX already comes with python installed.
Lion and Mountain Lion have python2.7 as the system defaults.
Now assuming you really did want to use a macports version, my guess is that
you only installed it, but didn't do the step of modifying your `PATH` to have
it look first for macport installed executables...
[Installing MacPorts](https://trac.macports.org/wiki/InstallingMacPorts)
1. Edit your `~/.profile`
2. Add this line: `export PATH=/opt/local/bin:/opt/local/sbin:$PATH`
The next time you open a shell, it will place the macports install location at
the front of your path, giving you access to the executables.
|
Is there any way to install nose in Maya?
Question: I'm using Autodesk Maya 2008 on Linux at home, and Maya 2012 on Windows 7 at
work. Most of my efforts so far have been focused on the former. I found [this
thread](http://stackoverflow.com/questions/639744/running-unit-tests-with-
nose-inside-a-python-environment-such-as-autodesk-maya), and managed to get
the setup there working at home. The gist of it is that you install nose for
whatever Python you have installed on your system, then create a py script
that adds that nose egg to sys.path, and loads in the maya.standalone module,
then imports nose and runs it. Then you run that py script through Maya's
version of Python (mayapy in the maya directory structure).
I'm unsure if running a Python 2.6 install of nose in Maya 2008's baked-in
Python 2.5 installation is of concern. Moreover, it's just a more messy setup,
and I'd like to do this for many coworkers. It would be nice to install nose
right into Maya 2008 (Python 2.5) and 2012 (Python 2.6).
To that end, I tried downloading nose and installing it via Maya's mayapy
executable:
~sudo /autodesk/maya2008-x64/bin/mayapy setup.py build
running install
error: invalid Python installation: unable to open /autodesk/maya2008-x64/lib/python2.5/config/Makefile (No such file or directory)
There's no config folder in there. Apparently this has to do with a missing
python-dev. I have that installed, but out in the system version of Python. I
don't know how to install it for Maya's Python, or if it's even possible. Is
it? Is Maya's version of Python too crazy/one-off to even consider this?
Answer: Since `nose` is a pure-Python package, it is safe to force it onto the
sys.path of Maya's built-in Python.
The worst that I believe could happen is some `*.pyc` thrashing if you use the
same `nose` installation with another 2.X version of Python. Over here, Maya
2011 and 2013 use Python 2.6.4 on OS X and Linux, so I just make sure to add a
version installed into a `python2.6/site-packages` directory.
This generally holds for compiled packages as well, enabling us to build
`PyQt4` for Maya as well.
I have been doing this without consequence for a few months now, even going so
far as to add it to the `sys.path` of a running Maya GUI in order to write
tests against the GUI!
|
DateField always return None value
Question:
class News(models.Model):
title = models.CharField(max_length=70)
full_text = models.TextField()
pub_date = models.DateField('-pub_date')
then i run python manage.py shell whatever i do value for News.pub_date is
None
i am using sqlite3 and when i open database i could see that date values are
there. but when i recover an object pub_date is None. I dont reveive any error
after s=News.objects.all()[0].pub_date enter code here
>>> from face.models import News
>>> from datetime import datetime
>>> s=News()
>>> s.pub_date
>>> s=News()
>>> s.title="hgello"
>>> s.full_text="hello there"
>>> s.pub_date = datetime.now()
>>> s.show=True
>>> s.save()
>>> t=News.objects.all()
>>> t
[<News: This is title>, <News: second text>, <News: sample>, <News: hgello>]
>>> t=t[3]
>>> print t.pub_date
None
*_I have solved the issue. i just deleted database file of sqllite3. I think it happened becouse initially it was named DateTimeField and then I changed it to DateField. But i did syncdb in between of changes. So django was able successfully store date data but cannot recover. And re-syncdb didnt help i did it several times. only phisycal delete of database and recreation structure of database solved the usue. *_
Answer: You probably wanted to set the [`auto_now_add`
parameter](https://docs.djangoproject.com/en/1.4/ref/models/fields/#django.db.models.DateField):
pub_date = models.DateField(auto_now_add=True)
Alternatively, you could override the `.save()` method:
class News(models.Model):
title = models.CharField(max_length=70)
full_text = models.TextField()
pub_date = models.DateField()
def save(self, *args, **kwargs):
if not self.id:
self.pub_date = datetime.datetime.today()
super(News, self).save(*args, **kwargs)
|
python:print(''.join(doc.xpath('//text()'))
Question: What is wrong? Please,somebody says me,what I have to write instead of
application/x-abiwordAbiWord.
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f=open('a.abw','r').read()
>>> from lxml import etree
>>> doc=etree.fromstring
>>> from lxml import html
>>> doc=html.fromstring
>>> doc
<function fromstring at 0x0113B858
>>> print(''.join(doc.xpath('//text()'))
application/x-abiwordAbiWord
SyntaxError: invalid syntax
Answer: You're missing a close-paren on the print statement. Also, unless I'm
monumentally mistaken, your fromstring functions are missing parentheses and a
parameter; according to the [python
reference](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstring),
the function signature needs to be `xml.etree.ElementTree.fromstring(text)`
As it currently stands, it looks like you're assigning a reference to function
"fromstring()" to "doc". You can't call ".xpath()" on a function reference.
EDIT: Try this. EDIT 2: Tried to clarify in response to OP comment
1: paste this code into an empty document:
MY_FILE_NAME = "path/to/my/file.abw"
# MY_FILE_NAME = "C:\\path\\to\\my\\file.abw" ## use this on windows
from lxml import etree
from lxml import html
import os
f=open(MY_FILE_NAME,'r')
myStr = f.read()
f.close()
doc=etree.fromstring(myStr)
doc=html.fromstring(myStr)
text = ''.join(doc.xpath('//text()'))
f = open(os.environ["HOME"] + "output.txt",'w')
f.write(text)
f.close()
2: save document as recover.py
3: run the script in python
4: ???
5: profit! (aka, your story should now be in output.txt in your home
directory)
* * *
Note: **What exactly are you trying to do?** If you give us a precise
problem/task, people will be able to help you better. Also try to describe
what you have already tried - SO isn't supposed to be a place where people do
your work for free, so its important to show that you put in some effort to
solve/research your problem.
|
Reading multiple XML files in a specific folder - Python
Question: I need a little help from you guys.
Im new to programming, so dont expect much from my code.
Here is the thing, i need to parse a bunch of XML files in a folder and write
it on a .xls or a .csv. Until now i've made it to parse the xml and write it
to a .txt, but the file that ive use it is located in the same folder that the
program is.
Here is the code:
from xml.dom import minidom
from datetime import *
ano = int(input("Year: "))
mes = int(input("Month: "))
dia = int(input("Day: "))
dt_obj = datetime(ano, mes, dia)
date_str = dt_obj.strftime("%Y-%m-%d")
#Extracting the information from the XML nodes
xmldoc = minidom.parse("NAME OF THE FILE.XML")
NFe = xmldoc.getElementsByTagName("NFe")[0]
infNFe = NFe.getElementsByTagName("infNFe")[0]
ide = infNFe.getElementsByTagName("ide")[0]
nNF = ide.getElementsByTagName("nNF")[0].firstChild.data
dEmi = ide.getElementsByTagName("dEmi")[0].firstChild.data
serie = ide.getElementsByTagName("serie")[0].firstChild.data
emit = infNFe.getElementsByTagName("emit")[0]
cnpj = emit.getElementsByTagName("CNPJ")[0].firstChild.data
nfeProc = xmldoc.getElementsByTagName("nfeProc")[0]
chNFe = nfeProc.getElementsByTagName("chNFe")[0].firstChild.data
try:
# This will create a new file or **overwrite an existing file**.
f = open(date_str+".txt", "w")
try:
f.write("CNPJ: "+cnpj) # Write a string to a file
f.writelines("\nNUMERO DA NOTA: "+nNF)
f.write("\nDATA DE EMISSAO: "+dEmi)
f.write("\nSERIE: "+serie)
f.write("\nCHAVE ELETRONICA: "+chNFe)
finally:
f.close()
except IOError:
pass
I've succeed reading the XML, parsing it and write the information from the
nodes that i needed.
What i need now is to read a folder with a bunch of them and writing on a .XLS
Anyone?
Answer: try this on for size.
from xml.dom import minidom
from datetime import *
ano = int(input("Year: "))
mes = int(input("Month: "))
dia = int(input("Day: "))
dt_obj = datetime(ano, mes, dia)
date_str = dt_obj.strftime("%Y-%m-%d")
#Extracting the information from the XML nodes
def get_files(d):
return [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d,f))]
def parse(files):
for xml_file in files:
xmldoc = minidom.parse(xml_file)
NFe = xmldoc.getElementsByTagName("NFe")[0]
infNFe = NFe.getElementsByTagName("infNFe")[0]
ide = infNFe.getElementsByTagName("ide")[0]
nNF = ide.getElementsByTagName("nNF")[0].firstChild.data
dEmi = ide.getElementsByTagName("dEmi")[0].firstChild.data
serie = ide.getElementsByTagName("serie")[0].firstChild.data
emit = infNFe.getElementsByTagName("emit")[0]
cnpj = emit.getElementsByTagName("CNPJ")[0].firstChild.data
# now whatever you want...
parse(get_files(DIRECTORY))
DIRECTORY being the location where the XML files are.
since this is only partial of your code, you will need to fill in the rest on
your own. you have not provided exactly what you want to write, or the format
you want to write it in....
something to help you write your CSV FILE:
# csv_lovation is a location os a *.csv file, and contents is a list of lists:
# ( [ ["row1 item1", "row1 item2", "row1 item3"], ["row2 item1", "row2 item2", "row2 item3"] ] )
def write_csv(csv_location, contents):
with open(csv_location, "w") as file_writer:
file_writer.write("Header,Items,Here\n") #if you have no need for a header, remove this line.
for line in contents:
file_writer.write("%s\n" % ",".join(line))
|
How to detect Endianess and Filesystem with Python3
Question: I'm theorizing of a project where my python script looks at filesystem(s) on
the machine running the script but also reports back on the filesystem(s) of
devices that it mounts, thumb drives, mobile devices, etc.
Is anyone aware of the a BIF in python3 that would looks at endianness and
filesystem.
Finally, I want to make a loop that looks at what storage devices are mounted,
but I'm not sure how/whre to access that on OSX or Linux (fstab on linux?) and
see what is currently mounted and if that changes. If Fstab was the correct
file, would I constantly sort through it or should I just periodically open it
and compare it against a file object? I'm still very new at programming, so
please pardon any newbie oversights.
Thanks
Answer: For the endianness of the platform:
>>> import sys
>>> print(sys.byteorder)
little
|
Reading files in a particular order in python
Question: Lets say I have three files in a folder: file9.txt, file10.txt and file11.txt
and i want to read them in this particular order. Can anyone help me with
this?
Right now I am using the code
import glob, os
for infile in glob.glob(os.path.join( '*.txt')):
print "Current File Being Processed is: " + infile
and it reads first file10.txt then file11.txt and then file9.txt.
Can someone help me how to get the right order?
Answer: Files on the filesystem are not sorted. You can sort the resulting filenames
yourself using the [`sorted()`
function](http://docs.python.org/library/functions.html#sorted):
for infile in sorted(glob.glob('*.txt')):
print "Current File Being Processed is: " + infile
Note that the `os.path.join` call in your code is a no-op; with only one
argument it doesn't do anything but return that argument unaltered.
Note that your files will sort in alphabetical ordering, which puts `10`
before `9`. You can use a custom key function to improve the sorting:
import re
numbers = re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
for infile in sorted(glob.glob('*.txt'), key=numericalSort):
print "Current File Being Processed is: " + infile
The `numericalSort` function splits out any digits in a filename, turns it
into an actual number, and returns the result for sorting:
>>> files = ['file9.txt', 'file10.txt', 'file11.txt', '32foo9.txt', '32foo10.txt']
>>> sorted(files)
['32foo10.txt', '32foo9.txt', 'file10.txt', 'file11.txt', 'file9.txt']
>>> sorted(files, key=numericalSort)
['32foo9.txt', '32foo10.txt', 'file9.txt', 'file10.txt', 'file11.txt']
|
python webcrawler downloading files
Question: I have a webcrawler that searches for certain files and downloads them, but
how do I download a pdf file when the "save as or open" dialog prompts up. I
am currently using python selenium to crawl. Here is my code.
from selenium import webdriver
import time
browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.tda-sgft.com/TdaWeb/jsp/fondos/Fondos.tda") # Load page
link = browser.find_element_by_link_text("Mortgage Loan")
link.click()
link2 = browser.find_element_by_link_text("ABS")
link2.click()
link3 = browser.find_element_by_link_text("TDA 13 Mixto")
link3.click()
download = browser.find_element_by_link_text("General Fund Information")
download.click()
time.sleep(0.2) # Let the page load, will be added to the API
browser.close()
Answer: You are going to need to modify the preferences of your Firefox profile. In
order to get it to stop showing that dialog, you need to set the
`browser.helperApps.neverAsk.saveToDisk` property of the profile in use. To do
so, you could do this (note that this is for CSVs/Excel files - I believe your
type would be 'application/pdf'):
profile = webdriver.firefox.firefox_profile.FirefoxProfile()
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('text/csv,'
'application/csv,'
'application/msexcel'))
For your case (I haven't tested this with a PDF, so take it with a grain of
salt :) ), you could try this:
profile = webdriver.firefox.firefox_profile.FirefoxProfile()
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/pdf'))
The second argument is a tuple that contains the types of files that will
never trigger a `Save As` prompt. You then pass this profile into your
`browser`:
browser = webdriver.Firefox(firefox_profile=profile)
Now when you download a file of a type in that tuple, it should bypass the
prompt and put it in your default directory. If you want to change the
directory to which the file downloads, you can use the same process, just
changing a few things (do this before attaching the `profile` to the browser):
profile.set_preference('browser.download.folderList': 2)
profile.set_preference('browser.download.dir': '/path/to/your/dir')
|
What is causing my HTTP server to fail with "exit status -1073741819"?
Question: As an exercise I created a small HTTP server that generates random game
mechanics, similar to [this
one](http://inventwithpython.com/randommechanic.html). I wrote it on a Windows
7 (32-bit) system and it works flawlessly. However, when I run it on my home
machine, Windows 7 (64-bit), it always fails with the same message: `exit
status -1073741819`. I haven't managed to find anything on the web which
references that status code, so I don't know how important it is.
Here's code for the server, with redundancy abridged:
package main
import (
"fmt"
"math/rand"
"time"
"net/http"
"html/template"
)
// Info about a game mechanic
type MechanicInfo struct { Name, Desc string }
// Print a mechanic as a string
func (m MechanicInfo) String() string {
return fmt.Sprintf("%s: %s", m.Name, m.Desc)
}
// A possible game mechanic
var (
UnkillableObjects = &MechanicInfo{"Avoiding Unkillable Objects",
"There are objects that the player cannot touch. These are different from normal enemies because they cannot be destroyed or moved."}
//...
Race = &MechanicInfo{"Race",
"The player must reach a place before the opponent does. Like \"Timed\" except the enemy as a \"timer\" can be slowed down by the player's actions, or there may be multiple enemies being raced against."}
)
// Slice containing all game mechanics
var GameMechanics []*MechanicInfo
// Pseudorandom number generator
var prng *rand.Rand
// Get a random mechanic
func RandMechanic() *MechanicInfo {
i := prng.Intn(len(GameMechanics))
return GameMechanics[i]
}
// Initialize the package
func init() {
prng = rand.New(rand.NewSource(time.Now().Unix()))
GameMechanics = make([]*MechanicInfo, 34)
GameMechanics[0] = UnkillableObjects
//...
GameMechanics[33] = Race
}
// serving
var index = template.Must(template.ParseFiles(
"templates/_base.html",
"templates/index.html",
))
func randMechHandler(w http.ResponseWriter, req *http.Request) {
mechanics := [3]*MechanicInfo{RandMechanic(), RandMechanic(), RandMechanic()}
if err := index.Execute(w, mechanics); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/", randMechHandler)
if err := http.ListenAndServe(":80", nil); err != nil {
panic(err)
}
}
In addition, the [unabridged code](http://pastebin.com/naxzbxPc), the
[_base.html template](http://pastebin.com/c069YJjp), and the [index.html
template](http://pastebin.com/d87Hd0WZ).
What could be causing this issue? Is there a process for debugging a cryptic
exit status like this?
Answer: When I ran it, I got the following two errors:
template: content:6: nil pointer evaluating *main.MechanicInfo.Name
http: multiple response.WriteHeader calls
The former was in the web browser, the latter in the console window where I
launched your server.
The nil pointer problem is because your abridged program leaves
GameMechanics[1:32] set to nil.
The second error is interesting. The only place in your program that any
methods on your http.ResponseWriter get called is inside of index.Execute,
which is not your code -- meaning maybe there is something wrong happening in
html/template. I'm testing this with Go 1.0.2.
I put _base.html at the top of index.html and then changed index to this:
var index = template.Must(template.ParseFiles("templates/index.html"))
and the http.WriteHeaders warning went away.
Not really an answer, but a direction you could explore.
As a bonus, here's the more "Go way" of writing your program. Note that I
simplified the use of the PRNG (you don't need to instantiate unless you want
several going in parallel) and simplified the structure initializer:
package main
import (
"fmt"
"html/template"
"math/rand"
"net/http"
)
// Info about a game mechanic
type MechanicInfo struct{ Name, Desc string }
// Print a mechanic as a string
func (m MechanicInfo) String() string {
return fmt.Sprintf("%s: %s", m.Name, m.Desc)
}
// The game mechanics
var GameMechanics = [...]*MechanicInfo{
{"Avoiding Unkillable Objects",
"There are objects that the player cannot touch. These are different from normal enemies because they cannot be destroyed or moved."},
{"Race",
"The player must reach a place before the opponent does. Like \"Timed\" except the enemy as a \"timer\" can be slowed down by the player's actions, or there may be multiple enemies being raced against."},
}
// Get a random mechanic
func RandMechanic() *MechanicInfo {
i := rand.Intn(len(GameMechanics))
return GameMechanics[i]
}
var index = template.Must(template.ParseFiles("templates/index.html"))
func randMechHandler(w http.ResponseWriter, req *http.Request) {
mechanics := [3]*MechanicInfo{RandMechanic(), RandMechanic(), RandMechanic()}
if err := index.Execute(w, mechanics); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/", randMechHandler)
if err := http.ListenAndServe(":80", nil); err != nil {
panic(err)
}
}
|
Issues that could happen if importing site-packages from python2.6 to be used with python2.7?
Question: I finally managed to install numpy, but it seems to only work in python2.6 . I
don't know how to install it in the 2.7 folder (been trying for hours, but I'm
just a beginner developer in my first months). Anyway, if I use Python 2.7 and
append the absolute path to sys.path, could there be problems?
Any suggestions?
Thank you.
Answer: It could _partially_ work but this is a bad idea. **Just don't do it.** Even
if it seems to work, it may not. And if it really does, then it will fail
randomly in the future.
These are the potential problems that come into my mind:
1. Extensions (those written in C, C++ etc.) are specific to a particular Python version; and numpy has a few extensions, AFAICS. It will work only if you don't use any of them (i.e. use pure Python modules);
2. Python compiles modules into bytecode. The bytecode is specific to a particular Python version. If you use modules from python2.6 directory in python2.7, the compiled files will collide. I doubt this will cause major problems except for the fact that they will be recompiled every time Python version is switched;
3. Python code can be version-specific. It's unlikely for minor versions (but for example Python 2/3 could have serious differences) but still can happen. In other words, the modules installed for Python2.6 can be actually a bit different than those for Python2.7;
4. If you change the loading order, Python2.7 may start loading some standard modules from Python2.6. it could work, it could cause random breakages;
5. It will make all modules installed for Python2.6 visible. It can cause a few random switches somewhere with unpredictable result. I doubt there's something specific for that version but some modules may actually decide to use some kind of deprecated interface finding it visible.
There could be more. You may actually try but be prepared that you may waste a
lot of time trying to find out why something does not work as expected later.
And unless I'm missing something, I think installing numpy for Python2.7
involves mostly running the setup _using_ Python 2.7; like:
python2.7 setup.py clean
python2.7 setup.py build
python2.7 setup.py install
Depending on your particular install/system, it may be preferable to use the
package manager, binary bundle or a tool like `pip` instead. If you'd like
more details on how to enforce Python2.7 with those, you'd have to tell us
which one is of your choice.
|
getting output with weird text like☻
Question: Hey! I am getting a problem with my script.
I wrote it when reading [LPTHW](http://learnpythonthehardway.org/) book.
I am not getting an error message but I am not getting the correct output, I
think there might be a setting wrong with my system. I am confused.
Here is the script:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w+')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1= raw_input("line1: ")
line2= raw_input("line2: ")
line3= raw_input("line3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "Now, I am going to read the file"
print target.read()
print "And finally, we close it."
target.close()
and here is the output:
PS C:\Users\Isaac\lpthw> python ex1.py sample.txt
We're going to erase 'sample.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line1: i
line2: love
line3: mo
I'm going to write these to the file.
Now, I am going to read the file
#☻ ` ▬☻ ` ▬☻ .☻
Answer: When you call `target.write()`, the file pointer is left just after the
written data. You can call `target.tell()` to see where it is:
>>> target.tell()
0
>>> target.write('hello')
>>> target.tell()
5
You need to seek to the beginning of the file before you read it:
target.seek(0)
print target.read()
|
Listing installed modules in Python
Question: Here is a basic code I came up with to list modules installed.
import sys as s
mod=s.modules.keys()
for indx,each in enumerate(mod):
print indx,each
But what I am looking for is, it should only print out the parent module name
like for
numpy.f2py.pprint'
numpy.distutils.atexit'
numpy.distutils.sys'
numpy.f2py.sys'
It should count it once as Numpy and move to look for next module and repeat
same way...
Answer:
import sys
print set([each.split('.')[0] for each in sys.modules.keys()])
|
Using Cython to speed up connected components algorithm
Question: First off, I am using python[2.7.2], numpy[1.6.2rc1], cython[0.16], gcc[MinGW]
compiler, on a windows xp machine.
I needed a 3D connected components algorithm to process some 3D binary data
(i.e. 1s and 0s) stored in numpy arrays. Unfortunately, I could not find any
existing code so I adapted the code found
[here](http://stackoverflow.com/questions/1989987/my-own-ocr-program-in-
python) to work with 3D arrays. Everything works great, however speed is
desirable for processing huge data sets. As a result I stumbled upon cython
and decided to give it a try.
So far cython has improved the speed: Cython: 0.339 s Python: 0.635 s
Using cProfile, my time consuming line in the pure python version is:
new_region = min(filter(lambda i: i > 0, array_region[xMin:xMax,yMin:yMax,zMin:zMax].ravel()))
* * *
**The Question:** What is the correct way to "cythonize" the lines:
new_region = min(filter(lambda i: i > 0, array_region[xMin:xMax,yMin:yMax,zMin:zMax].ravel()))
for x,y,z in zip(ind[0],ind[1],ind[2]):
Any help would be appreciated and hopefully this work will help others.
* * *
**Pure python version [*.py]:**
import numpy as np
def find_regions_3D(Array):
x_dim=np.size(Array,0)
y_dim=np.size(Array,1)
z_dim=np.size(Array,2)
regions = {}
array_region = np.zeros((x_dim,y_dim,z_dim),)
equivalences = {}
n_regions = 0
#first pass. find regions.
ind=np.where(Array==1)
for x,y,z in zip(ind[0],ind[1],ind[2]):
# get the region number from all surrounding cells including diagnols (27) or create new region
xMin=max(x-1,0)
xMax=min(x+1,x_dim-1)
yMin=max(y-1,0)
yMax=min(y+1,y_dim-1)
zMin=max(z-1,0)
zMax=min(z+1,z_dim-1)
max_region=array_region[xMin:xMax+1,yMin:yMax+1,zMin:zMax+1].max()
if max_region > 0:
#a neighbour already has a region, new region is the smallest > 0
new_region = min(filter(lambda i: i > 0, array_region[xMin:xMax+1,yMin:yMax+1,zMin:zMax+1].ravel()))
#update equivalences
if max_region > new_region:
if max_region in equivalences:
equivalences[max_region].add(new_region)
else:
equivalences[max_region] = set((new_region, ))
else:
n_regions += 1
new_region = n_regions
array_region[x,y,z] = new_region
#Scan Array again, assigning all equivalent regions the same region value.
for x,y,z in zip(ind[0],ind[1],ind[2]):
r = array_region[x,y,z]
while r in equivalences:
r= min(equivalences[r])
array_region[x,y,z]=r
#return list(regions.itervalues())
return array_region
_Pure python speedups:_
#Original line:
new_region = min(filter(lambda i: i > 0, array_region[xMin:xMax+1,yMin:yMax+1,zMin:zMax+1].ravel()))
#ver A:
new_region = array_region[xMin:xMax+1,yMin:yMax+1,zMin:zMax+1]
min(new_region[new_region>0])
#ver B:
new_region = min( i for i in array_region[xMin:xMax,yMin:yMax,zMin:zMax].ravel() if i>0)
#ver C:
sub=array_region[xMin:xMax,yMin:yMax,zMin:zMax]
nlist=np.where(sub>0)
minList=[]
for x,y,z in zip(nlist[0],nlist[1],nlist[2]):
minList.append(sub[x,y,z])
new_region=min(minList)
Time results:
O: 0.0220445
A: 0.0002161
B: 0.0173195
C: 0.0002560
* * *
**Cython version [*.pyx]:**
import numpy as np
cimport numpy as np
DTYPE = np.int
ctypedef np.int_t DTYPE_t
cdef inline int int_max(int a, int b): return a if a >= b else b
cdef inline int int_min(int a, int b): return a if a <= b else b
def find_regions_3D(np.ndarray Array not None):
cdef int x_dim=np.size(Array,0)
cdef int y_dim=np.size(Array,1)
cdef int z_dim=np.size(Array,2)
regions = {}
cdef np.ndarray array_region = np.zeros((x_dim,y_dim,z_dim),dtype=DTYPE)
equivalences = {}
cdef int n_regions = 0
#first pass. find regions.
ind=np.where(Array==1)
cdef int xMin, xMax, yMin, yMax, zMin, zMax, max_region, new_region, x, y, z
for x,y,z in zip(ind[0],ind[1],ind[2]):
# get the region number from all surrounding cells including diagnols (27) or create new region
xMin=int_max(x-1,0)
xMax=int_min(x+1,x_dim-1)+1
yMin=int_max(y-1,0)
yMax=int_min(y+1,y_dim-1)+1
zMin=int_max(z-1,0)
zMax=int_min(z+1,z_dim-1)+1
max_region=array_region[xMin:xMax,yMin:yMax,zMin:zMax].max()
if max_region > 0:
#a neighbour already has a region, new region is the smallest > 0
new_region = min(filter(lambda i: i > 0, array_region[xMin:xMax,yMin:yMax,zMin:zMax].ravel()))
#update equivalences
if max_region > new_region:
if max_region in equivalences:
equivalences[max_region].add(new_region)
else:
equivalences[max_region] = set((new_region, ))
else:
n_regions += 1
new_region = n_regions
array_region[x,y,z] = new_region
#Scan Array again, assigning all equivalent regions the same region value.
cdef int r
for x,y,z in zip(ind[0],ind[1],ind[2]):
r = array_region[x,y,z]
while r in equivalences:
r= min(equivalences[r])
array_region[x,y,z]=r
#return list(regions.itervalues())
return array_region
_Cython speedups:_
Using:
cdef np.ndarray region = np.zeros((3,3,3),dtype=DTYPE)
...
region=array_region[xMin:xMax,yMin:yMax,zMin:zMax]
new_region=np.min(region[region>0])
Time: 0.170, original: 0.339 s
* * *
## Results
After considering the many useful comments and answers provided, my current
algorithms are running at:
Cython: 0.0219
Python: 0.4309
Cython is providing a 20x increase in speed over the pure python.
Current Cython Code:
import numpy as np
import cython
cimport numpy as np
cimport cython
from libcpp.map cimport map
DTYPE = np.int
ctypedef np.int_t DTYPE_t
cdef inline int int_max(int a, int b): return a if a >= b else b
cdef inline int int_min(int a, int b): return a if a <= b else b
@cython.boundscheck(False)
def find_regions_3D(np.ndarray[DTYPE_t,ndim=3] Array not None):
cdef unsigned int x_dim=np.size(Array,0),y_dim=np.size(Array,1),z_dim=np.size(Array,2)
regions = {}
cdef np.ndarray[DTYPE_t,ndim=3] array_region = np.zeros((x_dim,y_dim,z_dim),dtype=DTYPE)
cdef np.ndarray region = np.zeros((3,3,3),dtype=DTYPE)
cdef map[int,int] equivalences
cdef unsigned int n_regions = 0
#first pass. find regions.
ind=np.where(Array==1)
cdef np.ndarray[DTYPE_t,ndim=1] ind_x = ind[0], ind_y = ind[1], ind_z = ind[2]
cells=range(len(ind_x))
cdef unsigned int xMin, xMax, yMin, yMax, zMin, zMax, max_region, new_region, x, y, z, i, xi, yi, zi, val
for i in cells:
x=ind_x[i]
y=ind_y[i]
z=ind_z[i]
# get the region number from all surrounding cells including diagnols (27) or create new region
xMin=int_max(x-1,0)
xMax=int_min(x+1,x_dim-1)+1
yMin=int_max(y-1,0)
yMax=int_min(y+1,y_dim-1)+1
zMin=int_max(z-1,0)
zMax=int_min(z+1,z_dim-1)+1
max_region = 0
new_region = 2000000000 # huge number
for xi in range(xMin, xMax):
for yi in range(yMin, yMax):
for zi in range(zMin, zMax):
val = array_region[xi,yi,zi]
if val > max_region: # val is the new maximum
max_region = val
if 0 < val < new_region: # val is the new minimum
new_region = val
if max_region > 0:
if max_region > new_region:
if equivalences.count(max_region) == 0 or new_region < equivalences[max_region]:
equivalences[max_region] = new_region
else:
n_regions += 1
new_region = n_regions
array_region[x,y,z] = new_region
#Scan Array again, assigning all equivalent regions the same region value.
cdef int r
for i in cells:
x=ind_x[i]
y=ind_y[i]
z=ind_z[i]
r = array_region[x,y,z]
while equivalences.count(r) > 0:
r= equivalences[r]
array_region[x,y,z]=r
return array_region
Setup file [setup.py]
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("ConnectComp", ["ConnectedComponents.pyx"],
include_dirs =[numpy.get_include()],
language="c++",
)]
)
Build command:
python setup.py build_ext --inplace
Answer: As @gotgenes points out, you should definitely be using `cython -a <file>`,
and trying to reduce the amount of yellow you see. Yellow corresponds to worse
and worse generated C.
Things I found that reduced the amount of yellow:
1. This looks like a situation where there will never be any out of bounds array access, as long as the input `Array` has 3 dimensions, so one can turn off bounds checking:
cimport cython
@cython.boundscheck(False)
def find_regions_3d(...):
2. Give the compiler more information for [efficient indexing](http://wiki.cython.org/tutorials/numpy#Efficientindexing), i.e. whenever you `cdef` an `ndarray` give as much information as you can:
def find_regions_3D(np.ndarray[DTYPE_t,ndim=3] Array not None):
[...]
cdef np.ndarray[DTYPE_t,ndim=3] array_region = ...
[etc.]
3. Give the compiler more information about positive/negative-ness. I.e. if you know a certain variable is always going to be positive, `cdef` it as `unsigned int` rather than `int`, as this means that Cython can eliminate any negative-indexing checks.
4. Unpack the `ind` tuple immediately, i.e.
ind = np.where(Array==1)
cdef np.ndarray[DTYPE_t,ndim=1] ind_x = ind[0], ind_y = ind[1], ind_z = ind[2]
5. Avoid using the `for x,y,z in zip(..[0],..[1],..[2])` construct. In both cases, replace it with
cdef int i
for i in range(len(ind_x)):
x = ind_x[i]
y = ind_y[i]
z = ind_z[i]
6. Avoid doing the fancy indexing/slicing. And especially avoid doing it twice! And avoid using `filter`! I.e. replace
max_region=array_region[xMin:xMax,yMin:yMax,zMin:zMax].max()
if max_region > 0:
new_region = min(filter(lambda i: i > 0, array_region[xMin:xMax,yMin:yMax,zMin:zMax].ravel()))
if max_region > new_region:
if max_region in equivalences:
equivalences[max_region].add(new_region)
else:
equivalences[max_region] = set((new_region, ))
with the more verbose
max_region = 0
new_region = 2000000000 # "infinity"
for xi in range(xMin, xMax):
for yi in range(yMin, yMax):
for zi in range(zMin, zMax):
val = array_region[xi,yi,zi]
if val > max_region: # val is the new maximum
max_region = val
if 0 < val < new_region: # val is the new minimum
new_region = val
if max_region > 0:
if max_region > new_region:
if max_region in equivalences:
equivalences[max_region].add(new_region)
else:
equivalences[max_region] = set((new_region, ))
else:
n_regions += 1
new_region = n_regions
This doesn't look so nice, but the triple loop compiles down to about 10 or so
lines of C, while the compiled version of the original is hundreds of lines
long and has a lot of Python object manipulation.
(Obviously you must `cdef` all the variables you use, especially `xi`, `yi`,
`zi` and `val` in this code.)
7. You don't need to store all the equivalences, since the only thing you do with the set is find the minimum element. So if you instead have `equivalences` mapping `int` to `int`, you can replace
if max_region in equivalences:
equivalences[max_region].add(new_region)
else:
equivalences[max_region] = set((new_region, ))
[...]
while r in equivalences:
r = min(equivalences[r])
with
if max_region not in equivalences or new_region < equivalences[max_region]:
equivalences[max_region] = new_region
[...]
while r in equivalences:
r = equivalences[r]
8. The last thing to do after all that would be to not use any Python objects at all, specifically, don't use a dictionary for `equivalences`. This is now easy, since it is mapping `int` to `int`, so one could use `from libcpp.map cimport map` and then `cdef map[int,int] equivalences`, and replace `.. not in equivalences` with `equivalences.count(..) == 0` and `.. in equivalences` with `equivalences.count(..) > 0`. (Note that it will then require a C++ compiler.)
|
A value in a list, python
Question: Every character in the English language has a percentage of occurrence, these
are the percentages:
A B C D E F G H I
.0817 .0149 .0278 .0425 .1270 .0223 .0202 .0609 .0697
J K L M N O P Q R
.0015 .0077 .0402 .0241 .0675 .0751 .0193 .0009 .0599
S T U V W X Y Z
.0633 .0906 .0276 .0098 .0236 .0015 .0197 .0007
A list called `letterGoodness` is predefined as:
letterGoodness = [.0817,.0149,.0278,.0425,.1270,.0223,.0202,...
I need to find the "goodness" of a string. For example the goodness of 'I EAT'
is: .0697 + .1270 + .0817 + .0906 =.369. This is part of a bigger problem, but
I need to solve this to solve the big problem. I started like this:
def goodness(message):
for i in L:
for j in i:
So it will be enough to find out how to get the occurrence percentage of any
character. Can you help me? The string contains only uppercase letters and
spaces.
Answer: letterGoodness is better as a dictionary, then you can just do:
sum(letterGoodness.get(c,0) for c in yourstring.upper())
# #^.upper for defensive programming
To convert `letterGoodness` from your list to a dictonary, you can do:
import string
letterGoodness = dict(zip(string.ascii_uppercase,letterGoodness))
If you're guaranteed to only have uppercase letters and spaces, you can do:
letterGoodness = dict(zip(string.ascii_uppercase,letterGoodness))
letterGoodness[' '] = 0
sum(letterGoodness[c] for c in yourstring)
but the performance gains here are probably pretty minimal so I would favor
the more robust version above.
* * *
If you insist on keeping `letterGoodness` as a list (and I don't advise that),
you can use the builtin `ord` to get the index (pointed out by cwallenpoole):
ordA = ord('A')
sum(letterGoodness[ord(c)-ordA] for c in yourstring if c in string.ascii_uppercase)
I'm too lazy to `timeit` right now, but you may want to also define a
temporary set to hold `string.ascii_uppercase` \-- It might make your function
run a little faster (depending on how optimized `str.__contains__` is compared
to `set.__contains__`):
ordA = ord('A')
big_letters = set(string.ascii_uppercase)
sum(letterGoodness[ord(c)-ordA] for c in yourstring.upper() if c in big_letters)
|
python: logging output from external API to logger module
Question: I am python beginner. My python script logs output to a file (say example.log)
using the basic python logging module. However, my python script also makes
some 3rd party API calls (for example, parse_the_file) over which I don't have
any control. I want to capture the output (usually on console) produced by the
API into my example.log. The following example code works partially but the
problem is that the contents get overwritten as soon as I start logging output
of the API into my log file.
#!/usr/bin/env python
import logging
import sys
import os
from common_lib import * # import additional modules
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a log message.') # message goes to log file.
sys.stdout = open('example.log','a')
metadata_func=parse_the_file('/opt/metadata.txt') # output goes to log file but OVERWRITES the content
sys.stdout = sys.__stdout__
logging.debug('This is a second log message.') # message goes to log file.
I know there have been post suggesting to similar question on this site but I
haven't a workaround/solution for this problem that will work in this
scenario.
Answer: Try:
log_file = open('example.log', 'a')
logging.basicConfig(stream=log_file, level=logging.DEBUG)
logging.debug("Test")
sys.stdout = log_file
sys.stderr = log_file
stdout_fd = os.dup(1)
stderr_fd = os.dup(2)
os.dup2(log_file.fileno(), 1)
os.dup2(log_file.fileno(), 2)
os.system("echo foo")
os.dup2(stdout_fd, 1)
os.dup2(stderr_fd, 2)
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
However, this will not format it accordingly. If you want that, you can try
something like <http://plumberjack.blogspot.com/2009/09/how-to-treat-logger-
like-output-stream.html>
|
UnicodeWarning: Unicode equal comparison. How to replace non-standard characters in NavigableString dataype?
Question: I'm scraping a website with Python 2.7 using BeautifulSoup. Here's my code:
# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup
import urllib
import json
url = 'http://www.website.com'
file_pointer = urllib.urlopen(url)
html_object = BeautifulSoup(file_pointer)
type_select = html_object('select',{'id':'which'})
for option in type_select:
value = option('option')
for type_value in value:
type = type_value.contents[0]
param_1 = type_value['value']
print 'Type:', type
url2 = 'http://www/website.com/' + param_1
file_pointer2 = urllib.urlopen(url2)
html_object2 = BeautifulSoup(file_pointer2)
result = json.loads(str(html_object2))
for json1 in result['DATA']:
category = json1[0].title()
param_2 = json1[0]
print ' Category:', category
url3 = 'http://www/website.com/' + param_2 + '&which=' + param_1
file_pointer3 = urllib.urlopen(url3)
html_object3 = BeautifulSoup(file_pointer3)
result2 = json.loads(str(html_object3))
for json2 in result2['DATA']:
sub_category = json2[0]
param_3 = sub_category.replace(' ','+').replace('&','%26')
print ' sub_category:', sub_category
for i in param_3:
if i == 'â':
print i
...
I need to replace the `'â'` character for a fourth URL request to continue my
scrape, but no matter what I try to replace (`u'\u2019'`, `â`, etc.), I get a
`UnicodeEncodeError`.
I tried converting `param_3` to a string (because it is a BeautifulSoup
Navigable String datatype) and replacing, but I get the same error, except on
my `str(param_3)` line. I finally tried this for-loop comparison and get the
warning:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if i == 'â':
I'm at a loss here. How can I translate this character and replace it with
other characters in `param_3`?
Any help is appreciated! Thanks in advance!
Answer: `BeautifulSoup` returns Unicode strings, so use Unicode strings when operating
on them. Also check out `urllib.quote_plus`. It looks like it does the
replacements you want. You'll need to `.encode` the Unicode string before
using it with `quote_plus`.
|
Numpy distutils howto
Question: I spent almost an hour googling for the solution, but the documentation for
numpy.distutils is very sparse.
I have a f2py-wrapped module. It consists basically of 3 files:
a.f90
a.pyf
lib.a <- this is a static library that contains most of the computational code
The module is well compiled with the following shell-script command.
f2py --build-dir temp -c a.pyf a.f90 lib.a --fcompiler=gnu95
--fcompiler-flags="Zillions of compiler options"
As a result, I have the python module a.so (the name is specified in the .pyf
file).
How do I do that with numpy.distutils (or some other python-oriented building
tools)? A less important question is, can I also include the dependence from
lib.a (and rebuild it when necessary?)
Answer: So, it is not 1 hour of Googling, it took 2 days of Googling, but finally I
found the way to do that. Hope, it will be helpful to someone.
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration, get_info
config = Configuration('a', parent_package, top_path)
lib = ['./libdir/lib.a']
src = ['a.f90','a.pyf']
inc_dir = ['libdir']
config.add_extension('mya',sources=src,depends=lib_tt,
include_dirs=inc_dir,extra_objects="lib.a")
#The main trick was to use extra_objects keyword
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
removing extra blank spaces in python
Question: I have a file which reads:
o hi! My name is Saurabh.
o I like python.
I want something like:
o hi! My name is Saurabh.
o I like python.
I tried the line:
removedSpaces=' '.join(lineWithSpaces.split())
Looks like it removes all the spaces
It gives me
o hi! My name is Saurabh.o I like python.
Which is incorrect. Is it possible to achieve the above output by anyway.
Answer:
import re
removedSpaces = re.sub(r'\n{3,}', "\n\n", lineWithSpaces)
This converts all runs of three and more newlines to two newlines.
|
calling third party c functions from python
Question: I have a requirement of calling third party c functions from inside python. To
do this I created a c api which has all the python specific c code ( using
METH_VARARGS) to call the third party functions. I linked this code liba.so
with the 3 party library libb.so In my python file , I'm doing:
import liba *
Python now complains libb.so not found. What am I doing wrong ?
Answer: You have to include `liba.so` in your PATH, otherwise Python won't know where
to look for it.
Try the following code, it'll load the library if it can find it from PATH,
otherwise it'll try loading it from the directory of the load script
from ctypes import *
from ctypes.util import find_library
import os
if find_library('a'):
liba = CDLL(find_library('a'))
else:
# library is not in your path, try loading it from the current directory
print 'liba not found in system path, trying to load it from the current directory'
print '%s/%s'%(os.path.dirname(__file__),'liba.so')
liba = CDLL(os.path.join(os.path.dirname(__file__),'liba.so'))
<http://docs.python.org/library/ctypes.html#finding-shared-libraries>
**UPDATE:** I was wondering why you created a native library (`liba`) to
access a native 3rd party library (`libb`). You can import the third party c
library straight into python using `ctypes` and create a python (not native)
wrapper for `libb`. For instance to call the standard c lib `time` you would
do
>>> from ctypes import *
>>> lib_c = CDLL("libc.so.6")
>>> print lib_c.time(None)
1150640792
and for libb
>>> from ctypes import *
>>> lib_b = CDLL("libb")
>>> lib_b.hello_world(None)
|
Python: tf-idf-cosine: to find document similarity
Question: I was following a tutorial which was available at [Part
1](http://blog.christianperone.com/?p=1589) & [Part
2](http://blog.christianperone.com/?p=1747) unfortunately author didn't have
time for the final section which involves using cosine to actually find the
similarity between two documents. I followed the examples in the article with
the help of following link from
[stackoverflow](http://stackoverflow.com/questions/11911469/tfidf-for-search-
queries) I have included the code that is mentioned in the above link just to
make answers life easy.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA
train_set = ["The sky is blue.", "The sun is bright."] #Documents
test_set = ["The sun in the sky is bright."] #Query
stopWords = stopwords.words('english')
vectorizer = CountVectorizer(stop_words = stopWords)
#print vectorizer
transformer = TfidfTransformer()
#print transformer
trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray
transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()
transformer.fit(testVectorizerArray)
print
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()
as a result of above code I have following matrix
Fit Vectorizer to train set [[1 0 1 0]
[0 1 0 1]]
Transform Vectorizer to test set [[0 1 1 1]]
[[ 0.70710678 0. 0.70710678 0. ]
[ 0. 0.70710678 0. 0.70710678]]
[[ 0. 0.57735027 0.57735027 0.57735027]]
I am not sure how to use this output to calculate cosine similarity, I know
how to implement cosine similarity respect to two vectors with similar length
but here I am not sure how to identify the two vectors.
Answer: First off, if you want to extract count features and apply TF-IDF
normalization and row-wise euclidean normalization you can do it in one
operation with `TfidfVectorizer`:
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()
>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
with 1787553 stored elements in Compressed Sparse Row format>
Now to find the cosine distances of one document (e.g. the first in the
dataset) and all of the others you just need to compute the dot products of
the first vector with all of the others as the tfidf vectors are already row-
normalized. The scipy sparse matrix API is a bit weird (not as flexible as
dense N-dimensional numpy arrays). To get the first vector you need to slice
the matrix row-wise to get a submatrix with a single row:
>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
with 89 stored elements in Compressed Sparse Row format>
scikit-learn already provides pairwise metrics (a.k.a. kernels in machine
learning parlance) that work for both dense and sparse representations of
vector collections. In this case we need a dot product that is also known as
the linear kernel:
>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602,
0.04457106, 0.03293218])
Hence to find the top 5 related documents, we can use `argsort` and some
negative array slicing (most related documents have highest cosine similarity
values, hence at the end of the sorted indices array):
>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([ 0, 958, 10576, 3277])
>>> cosine_similarities[related_docs_indices]
array([ 1. , 0.54967926, 0.32902194, 0.2825788 ])
The first result is a sanity check: we find the query document as the most
similar document with a cosine similarity score of 1 which has the following
text:
>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15
I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.
Thanks,
- IL
---- brought to you by your neighborhood Lerxst ----
The second most similar document is a reply that quotes the original message
hence has many common words:
>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26
In article <[email protected]> [email protected] (where's my
thing) writes:
>
> I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.
Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.
> ---- brought to you by your neighborhood Lerxst ----
Rush fan?
--
Robert Seymour [email protected]
Physics and Philosophy, Reed College (NeXTmail accepted)
Artificial Life Project Reed College
Reed Solar Energy Project (SolTrain) Portland, OR
|
Twython updateStatus - Unauthorized: Invalid / expired Token
Question: I'm trying to post a tweet using Twython from Django-powered site. However,
the 'twitter.updateStatus(status=tweet_text)' line results in the following
error:
TwythonError: u'Unauthorized: Authentication credentials were missing or incorrect. -- Invalid / expired Token'
I do have requests version 0.13.9, so this shouldn't be an issue:
>>>import pkg_resources
>>>pkg_resources.get_distribution("requests").version
'0.13.9'
>>>pkg_resources.get_distribution("twython").version
'2.3.4'
**Any idea how to fix this? Thanks in advance!**
Here's the python method itself:
def tweet_link(request, tweet_text):
try:
c = RequestContext(request)
twitter = Twython(
twitter_token = TWITTER_KEY,
twitter_secret = TWITTER_SECRET,
oauth_token = request.session['request_token']['oauth_token'],
oauth_token_secret = request.session['request_token']['oauth_token_secret']
)
twitter.updateStatus(status=tweet_text)
except Exception, e:
print traceback.print_exc()
return HttpResponse('')
Answer: I'm the author of Twython.
This bug was occurring due to an issue with a dependency we have (Requests),
which has been fixed as of Requests v0.13.9. It should be fine now; do feel
free to contact me if not.
|
How to achieve forward compatible string literals in python?
Question: I've got a script which runs with python 3 except string literals. Python 2.x
force me to prefix string literals with u'' and python 3 dosen't understand
it. How to so solve that?
Answer: try this when running it in python 2.x:
>>> from __future__ import unicode_literals
>>> s=['xx','yy','zz','aa']
>>> s
[u'xx', u'yy', u'zz', u'aa']
same thing when executed in python 3.x:
>>> from __future__ import unicode_literals
>>> s=['xx','yy','zz','aa']
>>> s
['xx', 'yy', 'zz', 'aa']
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.