text
stringlengths 226
34.5k
|
---|
Duplicating Python int * numpy.array behavior
Question: I'm attempting to build a class representation of a matrix complete with most
of the normal mathematical operations. I've hit a snag with the scalar
multiplication operation.
The relevant part of the code is as follows:
import numpy
class Matrix(object):
def __init__(self, array):
self.array = numpy.array(array, dtype=int)
def __mul__(self, other):
if type(other) == int:
return Matrix(other*self.array)
else:
raise ValueError("Can not multiply a matrix with {0}".format(type(other)))
The standard way the scalar multiplication is expressed is cA where c is a
scalar and A is a matrix, so `c*A` in Python. However, this fails with a
`TypeError: unsupported operand type(s) for *: 'int' and 'Matrix'` while `A*c`
runs as expected (note the `other*self.array`). Thus I conclude that the *
operand is defined for `int` and `numpy.array`.
What is this magic and how can I replicate the behavior?
Answer: You need a
[`__rmul__`](https://docs.python.org/3/reference/datamodel.html#object.__rmul__)
in your calss. For example if you add
def __rmul__(self, other):
return self.__mul__(other)
then:
>>> A = Matrix(np.arange(12).reshape(3, 4))
>>> (2 * A).array
array([[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]])
As in the
[docs](https://docs.python.org/3/reference/datamodel.html#object.__ror__), the
`__r***__`
> are called to implement the binary arithmetic operations with reflected
> (swapped) operands. These functions are only called if the left operand does
> not support the corresponding operation and the operands are of different
> types.
|
trying to regex in python
Question: _Can anyone please help me understand this code snippet,
from<http://garethrees.org/2007/05/07/python-challenge/> Level2_
>>> import urllib
>>> def get_challenge(s):
... return urllib.urlopen('http://www.pythonchallenge.com/pc/' + s).read()
...
>>> src = get_challenge('def/ocr.html')
>>> import re
>>> text = re.compile('<!--((?:[^-]+|-[^-]|--[^>])*)-->', re.S).findall(src)[-1]
>>> counts = {}
>>> for c in text: counts[c] = counts.get(c, 0) + 1
>>> counts
<http://garethrees.org/2007/05/07/python-challenge/>
`re.compile('<!--((?:[^-]+|-[^-]|--[^>])*)-->', re.S).findall(src)[-1]` why we
have [-1] here what's the purpose of it? is it Converting that to a list? **
Answer: Yes. `re.findall()` returns a list of all the matches. Have a look at [the
documentation](https://docs.python.org/3.4/library/re.html).
> _re.findall(pattern, string, flags=0)_
>
> Return all non-overlapping matches of pattern in string, **as a list of
> strings.** The string is scanned left-to-right, and matches are returned in
> the order found. If one or more groups are present in the pattern, return a
> list of groups; this will be a list of tuples if the pattern has more than
> one group. Empty matches are included in the result unless they touch the
> beginning of another match.
When calling `[-1]` on the result, the first element _from the end of the
list_ is accessed.
For example;
>>> a = [1,2,3,4,5]
>>> a[-1]
5
And also:
>>> re.compile('.*?-').findall('-foo-bar-')[-1]
'bar-'
|
Stem as a Python Tor client fails
Question: I am using Stem to start a Tor process. Using the [To Russia with
love](https://stem.torproject.org/tutorials/to_russia_with_love.html#using-
socksipy) tutorial as a guide. This is the code:
import requests
import socket
import socks
import stem.process
SOCKS_PORT = 9150
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
socket.socket = socks.socksocket
tor_process = stem.process.launch_tor_with_config(
tor_cmd = 'C:\Users\Sachin Kelkar\Desktop\Tor Browser\Browser\TorBrowser\Tor\\tor.exe',
config={
'SocksPort': str(SOCKS_PORT),
},
)
Gives an error:
Traceback (most recent call last):
File "<pyshell#17>", line 4, in <module>
'SocksPort': str(SOCKS_PORT),
File "C:\Python27\lib\site-packages\stem\process.py", line 255, in launch_tor_with_config
return launch_tor(tor_cmd, ['-f', '-'], None, completion_percent, init_msg_handler, timeout, take_ownership, stdin = config_str)
File "C:\Python27\lib\site-packages\stem\process.py", line 142, in launch_tor
tor_process.kill() # ... but best make sure
File "C:\Python27\lib\subprocess.py", line 1001, in terminate
_subprocess.TerminateProcess(self._handle, 1)
WindowsError: [Error 5] Access is denied
Any solutions to this?
Answer: Try to add tor.exe to Windows PATH system variable, and then run this code:
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print(line)
tor_process = stem.process.launch_tor_with_config(
config = {
'SocksPort': str(SOCKS_PORT),
#'ExitNodes': '{au}',
},
init_msg_handler = print_bootstrap_lines,
)
It's works for me fine.
Oh, and be sure that tor.exe is not running in the Windows Process Manager.
|
python: langton's ant pygame first step issues
Question: I'm trying to make a graphic representation of the Langton's ant algorithm but
I'm stuck.
here's the [Langton's Ant video
description](https://www.youtube.com/watch?v=1X-gtr4pEBU)
That's what the output should be:

My code:
import pygame
width = 800
height = 600
display = display=pygame.display.set_mode((width,height))
pygame.init()
direction = "up"
pixel_width_height = 2
qg = pixel_width_height
x=400
y=300
display.fill((0,0,0))
pygame.draw.rect(display,(255,255,255),(x,y,qg,qg))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
try:
a = display.get_at((x, y))
except:
break
if a == (255, 255, 255, 255) or a == (230, 230, 230, 255):
if direction == "right":
direction = "up"
y=y-qg
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg))
elif direction == "up":
direction = "left"
x = x-qg
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg))
elif direction == "left":
direction = "down"
y=y+qg
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg))
elif direction == "down":
direction = "right"
x = x+qg
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg))
elif a == (255,0,0,255):
if direction == "right":
direction = "down"
y=y+qg
pygame.draw.rect(display,(255,255,255),(x,y,qg,qg))
elif direction == "up":
direction = "right"
x = x+qg
pygame.draw.rect(display,(255,255,255),(x,y,qg,qg))
elif direction == "left":
direction = "up"
y = y-qg
pygame.draw.rect(display,(255,255,255),(x,y,qg,qg))
elif direction == "down":
direction = "left"
x=x-qg
pygame.draw.rect(display,(255,255,255),(x,y,qg,qg))
pygame.display.update()
print "end"
When it starts the ant goes in the upper left corner and then the program
stops. I really don't understand why it won't work.. how to fix it?
Answer: You need to first draw and then update the coordinates.
Your code instead first updates the coordinates and then draws (and this means
that the next move will not depend on the color you are moving to).
The difference is important because when done correctly instead next move
depends on the color the ant lands in and the direction the ant is coming
from; in your version except for the first move the color of the board is
never used because you're painting the square and then making an `if` on its
content (that's the color you just used).
You need to change the code from
y=y-qg
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg))
swapping the two lines to get
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg))
y=y-qg
**in all the places** you are updating the coordinates.
Another error is that the screen should be filled with white `(255,255,255)`
at the beginning of the simulation (current code uses `(0, 0, 0)` instead).
With these changes the simulation works like in the video.
Note that you could use a different approach that scales much better to more
complex cases (more than two colors). The idea is to keep an array of
`directions` and an index to the current `direction`; this way to turn left or
right you just need to increment or decrement the `direction` (modulo 4).
import pygame
width, height = 800, 600
display = pygame.display.set_mode((width,height))
pygame.init()
qg = 2
x, y = 400, 300
display.fill((255,255,255))
directions = ((0, -1), (-1, 0), (0, 1), (1, 0))
direction = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# update position
dx, dy = directions[direction]
x += dx * qg
y += dy * qg
try:
a = display.get_at((x, y))
except:
break
if a == (255, 255, 255, 255):
# White square
pygame.draw.rect(display,(255,0,0),(x,y,qg,qg)) # paint red
direction = (direction + 1) % 4 # turn left
else:
# Red square
pygame.draw.rect(display,(255,255,255),(x,y,qg,qg)) # paint white
direction = (direction + 3) % 4 # turn right
pygame.display.update()
print "end"
|
Python error: ImportError: No module named src.core.setcore?
Question: Hey guys I'm new here and I have found no solution to my problem yet. I am
currently learning to program in C but I don't know much about python, and
what happens is that when I try to run a script it gives me this error:
root@ubuntu:/usr/share/set/src/core# ./fasttrack.py
Traceback (most recent call last):
File "./fasttrack.py", line 2, in <module>
from src.core.setcore import *
ImportError: No module named src.core.setcore
Can someone tell what's happening here so I can fix this problem? (I'm using
ubuntu terminal just in case.) Thanks in advance.
Answer: Try running the script from a directory two levels up the tree.
root@ubuntu:/usr/share/set# ./fasttrack.py
The import statements encountered in python search for modules relative to the
current directory and the directories in the Python path.
|
Decompile an imported module (e.g. with uncompyle2)
Question: my task is to export an imported (compiled) module loaded from a container.
I have a Py.-Script importing a module. Upon using print(module1) I can see
that it is a compiled python (pyc) file, loaded from an archive. As I cannot
access the archive, my idea was to import the module and have it decompiled
with uncompyle2.
This is my minimum code:
import os, sys
import uncompyle2
import module1
with open("module1.py", "wb") as fileobj:
uncompyle2.uncompyle_file(module1, fileobj)
However, this prints my an error. If I substitute module1 in the uncompyle
argument with the actual path, it does not make a difference. I tried the code
snippet successfully when the pyc-file not loaded from a container but rather
a single file in a directory and it worked.
Error:
Traceback (most recent call last):
File "C:\....\run.py", line 64, in <module>
uncompyle2.uncompyle_file(module1, fileobj)
File "C:\....\Python\python-2.7.6\lib\site-packages\uncompyle2\__init__.py", line 124, in uncompyle_file
version, co = _load_module(filename)
File "C:\.....\Python\python-2.7.6\lib\site-packages\uncompyle2\__init__.py", line 67, in _load_module
fp = open(filename, 'rb')
TypeError: coercing to Unicode: need string or buffer, module found
Does anyone know where I am going wrong?
Answer: You are going wrong with your initial assumption:
> As I cannot access the archive, my idea was to import the module and have it
> decompiled with uncompyle2.
Uncompiling an already loaded module is unfortunately not possible. A loaded
Python module is not a mirror of the on-disk representation of a `.pyc` file.
Instead, it is a collection of _objects_ created as a side effect of executing
the code in the `.pyc`. Once the code has been executed, its byte code is
discarded and it (in the general case) cannot be reconstructed.
As an example, consider the following Python module:
import gtk
w = gtk.Window(gtk.WINDOW_TOPLEVEL)
w.add(gtk.Label("A quick brown fox jumped over the lazy dog"))
w.show_all()
Importing this module inside an application that happens to run a [GTK main
loop](http://www.gtk.org/) will pop up a window with some text as a side
effect. The module will have a dict with two entries, `gtk` pointing to the
`gtk` module, and `w` pointing to an already created GTK window. There is no
hint there how to create _another_ GTK window of the sort, nor how to create
another such module. (Remember that the object created might have been
arbitrarily complex and that its creation could be a very involved process.)
You might ask, then, if that is so, then what is the content of the `pyc`
file? How did it get loaded the first time? The answer is that the `pyc` file
contains an on-disk rendition of the byte-compiled code in the module, ready
for execution. Creating a `pyc` file is roughly equivalent to doing something
like:
import marshal
def make_pyc(source_code, filename):
compiled = compile(source_code, filename, "exec")
serialized = marshal.dumps(compiled)
with open(filename, "wb") as out:
out.write(serialized)
# for example:
make_pyc("import gtk\nw = gtk.Window(gtk.WINDOW_TOPLEVEL)...",
"somefile.pyc", "exec")
On the other hand, loading a compiled module is approximately equivalent to:
import sys, marshal, imp
def load_pyc(modname):
with open(modname + ".pyc", "rb") as in_:
serialized = in_.read()
compiled = marshal.loads(serialized)
module = sys.modules[modname] = imp.new_module(modname)
exec compiled in module.__dict__
load_pyc("somefile")
Note how, once the code has been executed with the `exec` statement, the
string and deserialized bytecode is no longer used and will be swept up by the
garbage collector. The only remaining effect of the `pyc` having been loaded
is the presence of a new module with living functions, classes, and other
objects that are impossible to serialize, such as references to open files,
network connections, OpenGL canvases, or GTK windows.
What modules like `uncompyle2` do is the inverse of the `compile` function.
You must have the actual _code_ of the module (either serialized as in a `pyc`
file or deserialized code object as in the `compiled` variable in the snippets
above), from which `uncompyle2` will produce a fairly faithful representation
of the original source.
|
Not understanding what is being passed into method
Question: So I've been given pre-written code and I have to fill in the `comepareTo`
function. It needs to compare strings and sort them by length but I'm not sure
what is being passed in the method.
import java.util.Arrays;
public class testString implements Comparable<testString> {
String tempStr;
public testString(String str) {
tempStr = str;
}
public String toString() {
return tempStr;
}
public int compareTo(testString Str2) {
return 0;
}
String [] list = {"dog", "cat", "lion", "python", "giraffe", "emu"};
testString [] list2 = new testString[list.length];
for (int i=0; i<list2.length; i++) {
list2[i] = new testString(list[i]);
}
I'm not exactly sure what the type is that is being passed into the
`compareTo` function (Str2).
I thought it would be a list and I could run through it with a for loop, but
that's giving me errors if I try Str2[1].
Answer: Str2 parameter is an object of type testString (your defined class). The
method is used to compare the current object with the one received as
parameter. To make sense such a comparison the objects must be of the same
type.
check also the API documentation for Comparable interface.
<https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html>
The method compareTo is part of this interface.
In your case, the easiest implementation would be: return
this.tempStr.compareTo(Str2.tempStr);
of course, Str2 must not be null :)
|
Python random number generation
Question: This is the question I am trying to answer:
1. In main, generate a random integer that is greater than 5 and less than 13. print this number on its own line. - **Done**
2. Call the makelist function with the random integer as sole argument. - **This confuses me**
3. Make an empty list inside the makelist function. - **Done**
4. Use a loop to append to the list a number of elements equal to the random integer argument. All new list elements must be random integers ranging from 1 to 100, inclusive. Duplicates are okay. - **Not Done**
5. Return the list to main. - **Not Done**
6. Back in main, catch the returned list and sort it. - **Not Done**
7. Finally, use a for loop to display the sorted list elements, all on one line, separated by single spaces. - **Not Done**
This is what I have so far:
import random
def main():
number = random.randint(6, 12)
print('the number is', number)
def makelist():
numbers = random.randint(1, 100)
empty_list = []
empty_list.append(numbers)
I am having trouble trying to understand the loops/append part...could someone
give me some guidance? Thanks.
Answer: This works.
#!/usr/bin/python
import sys, random
def makelist(number):
new_list = []
for i in range(0, number):
new_rand = random.randint(1, 100)
new_list.append(new_rand)
return new_list
def main():
number = random.randint(6, 12)
print "the number is %s" % str(number)
populated_list = makelist(number)
populated_list.sort()
for i in populated_list:
print(str(i)),
main()
Output:
test 1
the number is 11
9 11 13 17 25 33 53 61 65 85 87
test 2
the number is 8
1 14 17 23 32 49 51 81
test 3
the number is 10
16 18 24 29 35 46 50 74 78 88
|
Understanding Python Closures
Question: I always thought that Python 2.7 functions refer to the scope they were
defined in. Consider the following code. Why is the second output not
_"calculating: sin"_?
Is there any way to modify the code so it is working as expected?
import math
mymath = dict()
for fun in ["sin", "cos"]:
def _impl(val):
print "calculating: %s" % fun
return getattr(math, fun)(val)
mymath[fun] = _impl
# calculating: cos
print mymath["cos"](math.pi)
# calculating: cos <- why?
print mymath["sin"](math.pi)
Answer: The value of `fun` is evaluated when the function is called.
In the example you provided, `fun` is a global variable, and it's value is
"cos" after the `for` loop runs.
I think you expect the value of `fun` to be substituted when you create the
function, but it's not. The function evaluates the value of the variable when
it runs just like it's supposed to.
It's not about the namespace in which you define the function, but the
namespace in which you run the function.
import math
mymath = dict()
for fun in ["sin", "cos"]:
def _impl(val):
print "calculating: %s" % fun
return getattr(math, fun)(val)
mymath[fun] = _impl
fun = 'tan'
# will print and calculate tan
print mymath["cos"](math.pi)
|
Listing all instance of a class
Question: I wrote a Python module, with several classes that inherit from a single class
called `MasterBlock`. I want to import this module in a script, create several
instances of these classes, and then get a list of all the existing instances
of all the childrens of this `MasterBlock` class. I found some solutions with
`vars()['Blocks.MasterBlock'].__subclasses__()` but as the instances I have
are child of child of `MasterBlock`, it doesn't work.
Here is some example code:
Module:
Class MasterBlock:
def main(self):
pass
Class RandomA(MasterBlock):
def __init__(self):
pass
# inherit the main function
Class AnotherRandom(MasterBlock):
def __init__(self):
pass
# inherit the main function
Script:
import module
a=module.RandomA()
b=module.AnotherRandom()
c=module.AnotherRandom()
# here I need to get list_of_instances=[a,b,c]
Th ultimate goal is to be able to do:
for instance in list_of_instances:
instance.main()
Answer: What about adding a class variable, that contains all the instances of
`MasterBlock`? You can record them with:
Class MasterBlock(object):
all_instances = [] # All instances of MasterBlock
def __init__(self,…):
…
self.all_instances.append(self) # Not added if an exception is raised before
You get all the instances of `MasterBlock` with `MasterBlock.all_instances`
(or `instance.all_instances`).
This works if all base classes call the `__init__` of the master class (either
implicitly through inheritance or explicitly through the usual `super()`
call).
|
Elegant way to handle Python file read option rU in both py2 and py3
Question: What is the best way to read a file using the read mode 'rU' (read a file with
universal newline support) in an elegant way in Python 2 and 3? Py3.4 has
recently deprecated this, causing DeprecationWarings:
with open(filename, 'rU') as handle:
content = handle.read()
Answer: I don't see a way to call `open()` with a clever mix of arguments to make it
work for both. I'd wrap it in a helper method which distinguishes between
Python 2 and 3:
import sys
if sys.version_info[0] == 2:
def open_text(filename):
return open(filename, 'rU')
else:
def open_text(filename):
return open(filename, 'r', newline=None)
|
should a module export a function named `exit()`?
Question: I'm currently working on a module that wraps a C-library (let's call it `foo`)
The C-library has its functions prefixed by `foo_` to avoid nameclashes with
other libraries:
int foo_dothis(int x, int y);
void foo_dothat(struct foo_struct_*s);
In python, the `foo_` prefix makes little sense, as we have namespaces for
that kind of things.
import foo
foo.dothis(42)
The C-library also has functions for initializing/deinitializing the entire
library:
int foo_init(void);
void foo_exit(void);
Now i'm wondering whether I should strip the `foo_` prefix for those as well,
in order to prevent confusion with the built-in `exit()`:
from foo import *
exit()
I guess it is OK, as
* being consistent is important
* `exit()` is easier to remember than `foo_exit()`
* `foo.exit()` is prettier than `foo.foo_exit()`
* people are generally discouraged to use `exit()` in production code (and should only use it in the interpreter)
* importing all symbols from a module asks for trouble anyhow
So what is the common approach to that (best-practice,...)
Answer: Since the role of `foo_exit()` is to uninitialise the library, and this is
kind of the inverse of `foo_init()`, you could simply use name `foo.uninit()`
for the Python function. This will avoid name clashes and confusion with the
builtin `exit()`, and its purpose should be obvious to users of the module.
|
python and boto : 403 accessDenied
Question:
import boto
from boto.s3.connection import S3Connection
from boto.s3.connection import OrdinaryCallingFormat
conn = S3Connection(access_key, secret_key, calling_format=OrdinaryCallingFormat())
bucket = conn.get_bucket(file_name)
print(bucket.name)
And the console display:
raise err
boto.exception.S3ResponseError: S3ResponseError: 403 Forbidden
I have seen many post about the same problem but I can't figure out how to
solve it... note that I am not the owner of the bucket, but I succeed to
connect and download the file with a gui tool. I need to process it by script
for automation.
EDIT: Succeed to connect, but still struggling... I begin to hesitate to
process it automatically rather than manually ...
conn = S3Connection(access_key, secret_key, calling_format=OrdinaryCallingFormat())
bucket = conn.get_bucket(bucket_name, validate=False)
print('bucket:', bucket)
print('bucket.name:', bucket.name)
key = bucket.get_key(file_name)
print("key: {name}\t{size}\t{modified}".format(name = key.name,size = key.size,modified = key.last_modified))
print('bucket.list():',bucket.list(prefix='GA-Exports/Events_3112/DEV'))
for key in bucket.list(prefix='DEV/',delimiter='/'):
print('bucket list -> key:',key)
console :
bucket: <Bucket: GA-Exports/Events_3112/>
bucket.name: GA-Exports/Events_3112/
key: DEV/EVENTS_3113_120002892.csv.gz 3826 Sat, 16 May 2015 10:05:44 GMT
bucket.list(): <boto.s3.bucketlistresultset.BucketListResultSet object at 0x0000000004E9F7F0>
Traceback (most recent call last):
File "D:\Python\lib\xml\sax\expatreader.py", line 207, in feed
self._parser.Parse(data, isFinal)
xml.parsers.expat.ExpatError: no element found: line 1, column 0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Francois\OneDrive\IDE\Workspace\eclipse\Python_test\etltest.py", line 31, in <module>
for key in bucket.list(prefix='DEV/',delimiter='/'):
File "D:\Python\lib\site-packages\boto\s3\bucketlistresultset.py", line 34, in bucket_lister
encoding_type=encoding_type)
File "D:\Python\lib\site-packages\boto\s3\bucket.py", line 472, in get_all_keys
'', headers, **params)
File "D:\Python\lib\site-packages\boto\s3\bucket.py", line 406, in _get_all
xml.sax.parseString(body, h)
File "D:\Python\lib\xml\sax\__init__.py", line 46, in parseString
parser.parse(inpsrc)
File "D:\Python\lib\xml\sax\expatreader.py", line 107, in parse
xmlreader.IncrementalParser.parse(self, source)
File "D:\Python\lib\xml\sax\xmlreader.py", line 125, in parse
self.close()
File "D:\Python\lib\xml\sax\expatreader.py", line 217, in close
self.feed("", isFinal = 1)
File "D:\Python\lib\xml\sax\expatreader.py", line 211, in feed
self._err_handler.fatalError(exc)
File "D:\Python\lib\xml\sax\handler.py", line 38, in fatalError
raise exception
xml.sax._exceptions.SAXParseException: <unknown>:1:0: no element found
Answer: By default, boto will attempt to validate the bucket when you call
`get_bucket` by performing a `HEAD` request on the bucket. You may not have
permission to do this even though you may have permission to retrieve objects
from the bucket. Try this to disable the validation step:
bucket = conn.get_bucket(bucket_name, validate=False)
Also, make sure you are passing in the name of the bucket. Your example code
is passing in `file_name` which doesn't sound right.
|
How to print a line from a text file without a certain character
Question: Not quite sure if this question is a duplicate, but it seems like it isn't,
after searching for a fair while.
Let's say I have these lines of text in text file.
Q5) What is 1+1
A) = 1
B) = *2
C) = 0
D) = -342
E) = 121
The correct answer, `B) = *2`, is written with a `*` mark over the line. How
would you print this line, but without the character, so the line would be
printed like so:
Q5) What is 1+1
A) = 1
B) = 2
C) = 0
D) = -342
E) = 121
I am still new to Python, but I understand that:
print lines[3]
Would print the specific line. Yet I would like to know how to print a line,
without a certain character.
Any help and explanation on the Coding, will be much appreciated. Thanks Guys.
Answer: EDIT: Given this input:
Q1) What is 1*1?
A) = 0
B) = *1
C) = 2
D) = -1
Q2) What is 1-1?
A) = *0
B) = 1
C) = 2
D) = -1
Q3) What is 1/1?
A) = 0
B) = *1
C) = 2
D) = -1
Q4) What is 1%1?
A) = *0
B) = 1
C) = 2
D) = -1
Q5) What is 1+1?
A) = 1
B) = *2
C) = 0
D) = -342
E) = 121
There are many ways to tackle this. These are my first thoughts:
import re
def ask_user(answer):
user_ans = raw_input("> ").strip()
if user_ans == answer:
print "Correct!\n"
result = True
else:
print "Wrong!\n"
result = False
return result
question = None
with open('test.txt') as test:
for line in test:
if line[0] == 'Q':
if question:
ask_user(answer)
question = line
else:
m = re.match(r'(.*?)\*(\d+)', line)
if m:
line, answer = m.groups()
line = "%s%s\n" % (line,answer)
print line,
# Final question
ask_user(answer)
|
lua how to detect unused require
Question: I know lua has tools such as lualink and luacheck but none of those mark
unused "require". I know other dynamic languages such as python have tools
that specifically check and some even remove unused imports from source files.
Does lua have any tools or such functionality?
Answer: as Colonel said...
If you define your libraries with local variables you can use luacheck/lint to
determine unused variables
|
Python: How to select 10 random samples n times
Question: **Attempt** :
import numpy as np
import random
with open(r'C:\Python27\Lib\site-packages\visual\examples\hsp.txt') as f:
random.choice(set(f),10)
def repeat(f,N):
for _ in itertools.repeat(None,N): f()
**Error** :
> TypeError: choice() takes exactly 2 arguments (3 given)
It also gives me an invalid syntax if I replaced N with 50.
Answer: From Python Docs
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
New in version 2.3.
Returns a new list containing elements from the population while leaving the
original population unchanged. The resulting list is in selection order so
that all sub-slices will also be valid random samples. This allows raffle
winners (the sample) to be partitioned into grand prize and second place
winners (the subslices).
Members of the population need not be hashable or unique. If the population
contains repeats, then each occurrence is a possible selection in the sample.
To choose a sample from a range of integers, use an xrange() object as an
argument. This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60).
|
Opencv draw a rectangle in a picture were never shown
Question: Hey everybody i have some trouble using opencv 3.x and python 3.x. What i want
to do is to draw a basic rectangle in a picture but the rectangle will never
be drawn. I read this similar thread but it doesn't helped me with my fault.
[Python OpenCV: mouse callback for drawing
rectangle](http://stackoverflow.com/questions/28823243/python-opencv-mouse-
callback-for-drawing-rectangle)
It would be nice if someone could give me a hint.
#!/usr/bin/env python3
import cv2
import numpy as np
Path = 'picture.jpg'
image_float_size = 400.0
image_int_size = int(image_float_size)
color = [0,255,0]
rectangle = False
def on_event(event,x,y,flags,param):
global startpointx,startpointy,rectangle
if event == cv2.EVENT_LBUTTONDOWN:
rectangle = True
startpointx = x
startpointy = y
print('Down',x,y) #debugging
cv2.rectangle(resized,(x,y),(x,y),(0,255,0),-1)
elif event == cv2.EVENT_LBUTTONUP:
rectangle = False
print('Up',x,y)
cv2.rectangle(resized,(startpointx,startpointy),(x,y),(0,255,0),-1)
elif event == cv2.EVENT_MOUSEMOVE:
if rectangle:
print('Move',startpointx,startpointy,x,y)#debugging
cv2.rectangle(resized,(startpointx,startpointy),(x,y),(0,255,0),-1)
# Read the image and convert it into gray
image = cv2.imread(Path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# resize the image
ration = image_float_size / gray_image.shape[1]
dim = (image_int_size,int(gray_image.shape[0]*ration))
resized = cv2.resize(gray_image, dim, interpolation = cv2.INTER_AREA)
# set window for the image
cv2.namedWindow('window')
# mouse callback
cv2.setMouseCallback('window',on_event)
# wait forever for user to press any key, after key pressed close all windows
while True:
cv2.imshow('window',resized)
if cv2.waitKey(0):
break
cv2.destroyAllWindows()
Answer: You perform drawing (displaying of an image by using cv2.imshow) only once
because cv2.waitKey(0) waits indefinitely. If you use some non-zero argument
it will wait for that number of milliseconds. But notice that you're
constantly rewriting/modifying an image. This is probably not what you want. I
think you need to create a temporary (drawing) copy of an image first and
restore it each time from original one before new drawing (rectangle).
#!/usr/bin/env python3
import cv2
import numpy as np
Path = 'data/lena.jpg'
image_float_size = 400.0
image_int_size = int(image_float_size)
color = [0,255,0]
rectangle = False
def on_event(event,x,y,flags,param):
global draw_image
global startpointx,startpointy,rectangle
if event == cv2.EVENT_LBUTTONDOWN:
rectangle = True
startpointx = x
startpointy = y
print('Down',x,y) #debugging
draw_image = resized.copy()
cv2.rectangle(draw_image,(x,y),(x,y),(0,255,0))
elif event == cv2.EVENT_LBUTTONUP:
rectangle = False
print('Up',x,y)
draw_image = resized.copy()
cv2.rectangle(draw_image,(startpointx,startpointy),(x,y),(0,255,0))
elif event == cv2.EVENT_MOUSEMOVE:
if rectangle:
print('Move',startpointx,startpointy,x,y)#debugging
draw_image = resized.copy()
cv2.rectangle(draw_image,(startpointx,startpointy),(x,y),(0,255,0))
# Read the image and convert it into gray
image = cv2.imread(Path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# resize the image
ration = image_float_size / gray_image.shape[1]
dim = (image_int_size,int(gray_image.shape[0]*ration))
resized = cv2.resize(gray_image, dim, interpolation = cv2.INTER_AREA)
draw_image = resized.copy()
# set window for the image
cv2.namedWindow('window')
# mouse callback
cv2.setMouseCallback('window',on_event)
while True:
cv2.imshow('window', draw_image)
ch = 0xFF & cv2.waitKey(1)
if ch == 27:
break
cv2.destroyAllWindows()
|
Flask render_template TemplateNotFound
Question: I'm tinkering around with Flask to play around with Postgres, and the db stuff
is going swimmingly, but vexingly, I cannot get render_template to work. Here
are the relevant bits:
### app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/test2/")
def test2():
return render_template('test2.html')
if __name__ == "__main__":
app.debug = True
app.run()
The file test2.html is located in the ./templates directory. When I run the
app and hit that url I get `jinja2.exceptions.TemplateNotFound`
So I've looked at this:
[Python - Flask: render_template() not
found](http://stackoverflow.com/questions/23435150/python-flask-render-
template-not-found)
And it's not particularly enlightening. My templates folder is next to the
application in the directory tree. I'm sure it's something dead simple, but
I'm not seeing it.
Answer: Well, I'm a dope. Went to git commit my changes on the command line and saw
that the templates directory was in the parent directory. It did not look that
way in Finder.
|
Simple example of restful web service Python and client basic authentication
Question: For study purposes I'd like to know if there is a simple dummy example of how
to handle a http request with basic authentication using python. I'd like to
follow the same pattern from a example I've found and adapted, as follows:
'''webservice.py'''
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.auth
from tornado.web import HTTPError
from tornado.escape import json_encode as dumps
from tornado.escape import json_decode as loads
import db
import settings
class MainHandler(tornado.web.RequestHandler):
"""Main Handler... list all databases"""
def get(self):
self.write(dumps(db.list_databases()))
application = tornado.web.Application([
(r"/", MainHandler),
],
cookie_secret='PUT_SOME_CODE',
)
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(settings.port)
tornado.ioloop.IOLoop.instance().start()
A list of databases appears when reach <http://localhost:8888/>, which is the
purpose of the script. This can be accessed by browser and a tester script
like:
'''tester.py'''
from tornado.httpclient import HTTPClient
from tornado.escape import json_decode as loads
url='http://localhost:8888/'
http_client=HTTPClient()
response=http_client.fetch(url)
listResponse=loads(response.body)
print(listResponse)
http_client.close()
Answer: Here is simplest basic-auth example. Of course, it can be improved in many
ways, it is just a demonstration how it usually works.
import httplib
class MainHandler(tornado.web.RequestHandler):
"""Main Handler... list all databases"""
def get(self):
self.check_basic_auth()
do_stuff()
def check_basic_auth(self):
if not self.test_auth_credentials():
raise HTTPError(httplib.UNAUTHORIZED,
headers={'WWW-Authenticate': 'Basic realm="Auth realm"'})
def test_auth_credentials(self):
auth_header = self.request.headers.get('Authorization')
if auth_header and auth_header.startswith('Basic '):
method, auth_b64 = auth_header.split(' ')
try:
decoded_value = auth_b64.decode('base64')
except ValueError:
return False
given_login, _, given_passwd = decoded_value.partition(':')
return <YOUR_LOGIN> == given_login and <YOUR_PASSWORD> == given_passwd
return False
|
Bad file descriptor error in Python (Error 9) on Raspberry
Question: I am working with Python for the first time, and encountered the following
issue, while running it on a Raspberry Pi Version B+ rev 2:
The code is supposed to set an interrupt on pin 22 (BCM), and when a button is
pressed, halt the OS:
# Import the modules to send commands to the system and access GPIO pins
from subprocess import call
import RPi.GPIO as gpio
# Define a function to keep script running
def loop():
raw_input()
# Define a function to run when an interrupt is called
def shutdown(pin):
call('halt', shell=False)
gpio.setmode(gpio.BCM) # Set pin numbering to BCM numbering
gpio.setup(22, gpio.IN) # Set up pin 22 as an input
gpio.add_event_detect(22, gpio.RISING, callback=shutdown, bouncetime=200) # Set up an interrupt to look for button presses
loop() # Run the loop function to keep script running
The program runs fine when I call it like this:
python program.py
But if I put it in the background like this:
python program.py &
it works fine, until I do any another command (can be anything (eg. ls)). Then
it stops (but doesn't kill it).
I did a nohup output, and this is what I have in it:
Traceback (most recent call last):
File "haltButton.py", line 19, in <module>
loop() # Run the loop function to keep script running
File "haltButton.py", line 7, in loop
raw_input()
IOError: [Errno 9] Bad file descriptor
Can anybody please point me to the right direction?
Answer: A background program can't do `raw_input()`. That's the whole point of being a
background program: you give up user input so the shell (or some other
program) can run and handle it.
If you just want to run forever until signaled, just find a different way of
doing that. Almost _anything_ will work, except `raw_input`. For example, you
can loop over `time.sleep`, or `select.select` on some fd, or anything else
you can think of except for trying to read from an fd that you closed.
|
Omit headers in requests POST request
Question: I am making a POST request using the `import requests` library. It's adding
some headers to the request that I suspect is making it fail...
r = requests.post(url, headers = {"Content-Type" : "text/zinc; charset=utf-8"}, \
cookies = {"cookie":cookie}, \
data = data)
Here's the results of `r.request.headers`...
CaseInsensitiveDict({
'Accept': '*/*',
'Content-Type': 'text/zinc; charset=utf-8',
'Accept-Encoding': 'gzip, deflate, compress',
'User-Agent': 'python-requests/2.2.1 CPython/3.4.0 Linux/3.13.0-52-generic',
'Cookie': 'cookie=mycookie; fanws="mycookie"'
})
So the question is, how do I only include the headers that I specified?
Answer: If you really want to do this, you can create a
[`PreparedRequest`](http://docs.python-
requests.org/en/latest/user/advanced/#prepared-requests) and then edit its
headers before sending it. This is unlikely to help you here—but it may be
worth doing just to convince yourself that it's not going to help, so…
Instead of this:
r = requests.post(url, headers = {"Content-Type" : "text/zinc; charset=utf-8"}, \
cookies = {"cookie":cookie}, \
data = data)
Do this:
sess = requests.Session()
req = requests.Request('GET', url,
headers={"Content-Type": "text/zinc; charset=utf-8"},
cookies={"cookie": cookie},
data=data)
preq = req.prepare()
preq.headers = {key: value for key, value in preq.headers.items()
if key in {'Content-Type', 'Cookie'}}
r = sess.send(preq)
It's in `prepare` that all the changes get done. You obviously want to keep
the `cookies` being turned into a `Cookie` header, but you don't want to keep
any of the other changes, so I just removed any header besides the one you
explicitly passed and `Cookie`. You can, of course, do anything else you want
there.
|
How to keep a real-time data read-in loop separate from more processing intensive operations in Python?
Question: So I have an OpenCV webcam feed that I'd like to read frames from as quickly
as possible. Because of the Python GIL, the fastest rate at which my script
could read in frames seems to be the following:
#Parent or maybe client(?) script
#initilize the video capture object
cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
# Some code to pass this numpy frame array to another python script
# (which has a queue) that is not under time constraint and also
# is doing some more computationally intensive post-processing...
if exit_condition is True:
break
What I'd like to have happen is to have these frames (Numpy Arrays) added to
some kind of processing queue in a second Python script (or perhaps a
multiprocessing instance?) which will then do some post-processing that is not
under the time constraints like the cam.read() loop is...
So the basic idea would look something like:
Real-time (or as fast as I can get) data collection(camera read) script \---->
Analysis script (which would do post-processing, write results, and produce
matplotlib plots that lags a bit behind the data collection)
I've done some research and it seems like things like: pipes, sockets, pyzmq,
and python multiprocessing all might be able to achieve what I'm looking for.
Problem is I have no experience with any of the above.
So my question is what method will best be able to achieve what I'm looking
for and can anyone provide a short example or even some thoughts/ideas to
point me in the right direction?
Many thanks!
**EDIT: Many thanks to steve for getting me started on the right track. Here's
a working gist of what I had in mind... the code as it is works but if more
post-processing steps are added then the queue size will likely grow faster
than the main process can work through it. The suggestion of limiting frame
rate is likely going to be the strategy I'll end up using.**
import time
import cv2
import multiprocessing as mp
def control_expt(connection_obj, q_obj, expt_dur):
def elapsed_time(start_time):
return time.clock()-start_time
#Wait for the signal from the parent process to begin grabbing frames
while True:
msg = connection_obj.recv()
if msg == 'Start!':
break
#initilize the video capture object
cam = cv2.VideoCapture(cv2.CAP_DSHOW + 0)
#start the clock!!
expt_start_time = time.clock()
while True:
ret, frame = cam.read()
q_obj.put_nowait((elapsed_time(expt_start_time), frame))
if elapsed_time(expt_start_time) >= expt_dur:
q_obj.put_nowait((elapsed_time(expt_start_time),'stop'))
connection_obj.close()
q_obj.close()
cam.release()
break
class test_class(object):
def __init__(self, expt_dur):
self.parent_conn, self.child_conn = mp.Pipe()
self.q = mp.Queue()
self.control_expt_process = mp.Process(target=control_expt, args=(self.child_conn, self.q, expt_dur))
self.control_expt_process.start()
def frame_processor(self):
self.parent_conn.send('Start!')
prev_time_stamp = 0
while True:
time_stamp, frame = self.q.get()
#print (time_stamp, stim_bool)
fps = 1/(time_stamp-prev_time_stamp)
prev_time_stamp = time_stamp
#Do post processing of frame here but need to be careful that q.qsize doesn't end up growing too quickly...
print (int(self.q.qsize()), fps)
if frame == 'stop':
print 'destroy all frames!'
cv2.destroyAllWindows()
break
else:
cv2.imshow('test', frame)
cv2.waitKey(30)
self.control_expt_process.terminate()
if __name__ == '__main__':
x = test_class(expt_dur = 60)
x.frame_processor()
Answer: The multiprocessing docs are a great place to start.
<https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-
between-processes> I suggest reading this even if you might not understand it
now.
Using pipes over the other techniques you mentioned will allow you to maintain
performance and keep your code simple.
Below is some code that I have not tested that should give you a good place to
start.
from multiprocessing import Process, Pipe
def read_frames(connection_obj):
#initilize the video capture object
cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
connection_obj.send(frame) # is this what you want to send?
if exit_condition is True:
connection_obj.close()
break
def launch_read_frames(connection_obj):
"""
Starts the read_frames function in a separate process.
param connection_obj: pipe to send frames into.
Returns a pipe object
"""
read_frames_process = Process(target=read_frames, args=(connection_obj,)) # this trailing comma is intentional
read_frames_process.start()
read_frames_process.join()
return parent_conn
def act_on_frames(connection_obj):
while True:
frame = connection_obj.recv()
# Do some stuff with each frame here
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
launch_read_frames(child_conn)
# You could also call this function as a separate process, though in
# this instance I see no performance benefit.
act_on_frames(parent_conn)
|
Python: How to print out sequences with length n from sliding window in FASTA file?
Question: I have a fasta file with few sequences and I would like to perform sliding
windows of window size 5 and extract the sequences whenever it sweeps through
the sequence.
For example ( test1.fasta ):
>human1
ATCGCGTC
>human2
ATTTTCGCGA
Expected output ( test1_out.txt ):
>human1
ATCGC
>human1
TCGCG
>human1
CGCGT
>human1
GCGTC
>human2
ATTTT
>human2
TTTTC
>human2
TTTCG
>human2
TTCGC
>human2
TCGCG
>human2
CGCGA
My following code only able to extract the first five base pairs. How can I
shift the window to extract 5 bp for every step size of 1 with window size 5?
from Bio import SeqIO
with open("test1_out.txt","w") as f:
for seq_record in SeqIO.parse("test1.fasta", "fasta"):
f.write(str(seq_record.id) + "\n")
f.write(str(seq_record.seq[:5]) + "\n") #first 5 base positions
Above code I got it from other example in stackoverflow*
Answer: So I guess "seq_record.seq" is the whole DNA sequece like in human1
"ATCGCGTC". You can write like this:
from Bio import SeqIO
with open("test1_out.txt","w") as f:
for seq_record in SeqIO.parse("test1.fasta", "fasta"):
for i in range(len(seq_record.seq) - 4) :
f.write(str(seq_record.id) + "\n")
f.write(str(seq_record.seq[i:i+5]) + "\n") #first 5 base positions
|
Python : Writing a dictionary to a csv (short way)
Question: I am trying to write a dictionary to csv file, but not directly. I put a new
field name for dictionary keys.
The following does what I want, but I am wondering if it can be shortened?
Especially the last line.
import csv
mydict = {"John":{'car':'BMW','age':27}, 'Mike':{'car':'Jetta', 'age':35}}
col_names = ['name','car','age']
with open('junk', 'w' ) as f:
writer = csv.DictWriter(f,fieldnames=col_names)
writer.writeheader()
for key, value in mydict.items():
writer.writerow({'name':key, 'car':value['car'], 'age':value['age']}) #
desired output should be:
name,car,age
Mike,Jetta,35
John,BMW,27
Answer: To avoid repeating field names in the last line you can store data in a
temporary dictionary and update it:
out = {'name':key}
out.update(value)
writer.writerow(out)
|
PyCharm unittests only work individually
Question: I can run my test cases individually by right-clicking them and selecting `Run
'Unittests in test_whatever'` but when I right-click the project root folder
and select `Run 'Unittests in MyProject'` I get ImportErrors such as this:
Testing started at 10:42 ...
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5\helpers\pycharm\utrunner.py", line 113, in <module>
modules = loadModulesFromFolderRec(a[0])
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5\helpers\pycharm\utrunner.py", line 63, in loadModulesFromFolderRec
os.path.walk(folder, walkModules, (modules, pattern))
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 272, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 268, in walk
func(arg, top, names)
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5\helpers\pycharm\utrunner.py", line 51, in walkModules
modules.append(loadSource(os.path.join(dirname, name)))
File "C:\Program Files (x86)\JetBrains\PyCharm 4.5\helpers\pycharm\utrunner.py", line 40, in loadSource
module = imp.load_source(moduleName, fileName)
File "C:\Users\Filip\PycharmProjects\MyProject\venv\lib\python2.7\site-packages\Crypto\SelfTest\Cipher\test_AES.py", line 29, in <module>
from common import dict # For compatibility with Python 2.1 and 2.2
ImportError: No module named common
I'm assuming this has something to do with the working directory.
I'm running python 2.7.9. And yes, the virtualenv is in the project folder,
and on git. Don't ask.
Answer: Did you set the checkboxes _Add content roots to PYTHONPATH_ and _Add source
roots to PYTHONPATH_ in the _Run/Debug Configuration_ Dialog of pyCharm. If
not, this could help.
|
how to create barchart in python xlsxwriter that does not start at 0?
Question: I found the following image that consists exactly the chart that I want to be
able to create, however I can't figure out how to start the bar somewhere else
than zero. Does anybody know how to solve this?

as mentioned below in the comments it is a line chart with up_down_bars. How
can I get an example of this to work?
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_line.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
# Add the worksheet data that the charts will refer to.
headings = ['Number', 'Batch 1', 'Batch 2']
data = [
[2, 3, 4, 5, 6, 7],
[10, 40, 50, 20, 10, 50],
[30, 60, 70, 50, 40, 30],
]
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])
# Create a new chart object. In this case an embedded chart.
chart1 = workbook.add_chart({'type': 'line'})
# Configure the first series.
chart1.add_series({
'name': '=Sheet1!$B$1',
'categories': '=Sheet1!$A$2:$A$7',
'values': '=Sheet1!$B$2:$B$7',
})
# Configure second series. Note use of alternative syntax to define ranges.
chart1.add_series({
'name': ['Sheet1', 0, 2],
'categories': ['Sheet1', 1, 0, 6, 0],
'values': ['Sheet1', 1, 2, 6, 2],
})
# Add a chart title and some axis labels.
chart1.set_title ({'name': 'Results of sample analysis'})
chart1.set_x_axis({'name': 'Test number'})
chart1.set_y_axis({'name': 'Sample length (mm)'})
chart1.set_up_down_bars({
'up': {
'fill': {'color': '#00B050'},
'border': {'color': 'black'}
},
'down': {
'fill': {'color': 'red'},
'border': {'color': 'black'},
},
})
# Set an Excel chart style. Colors with white outline and shadow.
chart1.set_style(10)
# Insert the chart into the worksheet (with an offset).
worksheet.insert_chart('D2', chart1, {'x_offset': 25, 'y_offset': 10})
workbook.close()
Answer: I'm going to guess that by "can't figure out how to start the bar somewhere
else than zero" you mean that you don't want the Y-Axis to start from 0.
You can change that in the same way that you would in Excel: by changing the
minimum value for the axis range. See the
[`set_x_axis()`](https://xlsxwriter.readthedocs.org/chart.html#chart-set-x-
axis) section of the docs and also [Working with
Charts](https://xlsxwriter.readthedocs.org/working_with_charts.html).
chart.set_y_axis({'min': 10})
If that isn't what you are looking for then you probably need to clarify your
question.
Also, to avoid confusion, the above image isn't a bar chart. It is a line
chart with Up-Down bars. If you need a bar chart that is also shown in the
docs and the examples.
|
Python / Curses - How to print separate items?
Question: this code the result screen: foobar (OK)
stdscr.addstr(10, 10, "foobar")
this code the result screen: **foobar** (OK)
stdscr.addstr(10, 10, "foobar", curses.A_REVERSE)
But how to get the result screen fo**ob** ar ?
Please consult anyone? Thank you.
Answer: Just split this into more than one `addstr()` call. For example:
stdscr.addstr(10, 10, 'fo..ar')
stdscr.addstr(10, 12, 'ob', curses.A_REVERSE)
Instead of the dots you can use spaces. The dots make it easier to see how
many characters are between 'fo' and 'ar'. If the cursor position at the end
of the output is important either split the output into three function calls
in the order the text parts should appear or set the cursor position
explicitly after adding the text.
|
How to call django-pipeline compressor with jinja2 templates
Question: I wish to compress the JS and CSS in my Jinja2 based Python project for Google
App engine. I have installed django-pipeline, and added it to my project path.
Some of the [documentation](http://django-
pipeline.readthedocs.org/en/latest/usage.html) is not clear to me.
Particularly Jinja2 usage.
For Django Templates, in base.html
[example](http://www.glenrobertson.co.nz/blog/2013/02/04/django-js-css-
compression-with-pipeline.html), insert:
{% load compressed %}
{% compressed_css 'colors' %}
{% compressed_js 'stats' %}
I assume the equivalent for Jina2 would be something like
{{ compressed_css("main") }}
{{ compressed_js("main") }}
But this gives UndefinedError: 'compressed_css' is undefined
My question is **how to load the 'compressed' template in Jinja2?** This is
not done in the same way as Django and I can't find an example.
The docs also say
> In order to use Django Compressor’s Jinja2 extension we would need to pass
> compressor.contrib.jinja2ext.CompressorExtension into environment:
I have done that.
import jinja2
from compressor.contrib.jinja2ext import CompressorExtension
env = jinja2.Environment(extensions=[CompressorExtension])
The docs also state
> "Unlike the Django template tag implementation the Jinja2 implementation
> uses different templates, so if you wish to override them please override
> pipeline/css.jinja and pipeline/js.jinja."
I am not sure if I need to do anything here.
My setings.py includes the following statements:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = '{{ project_name }}.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = '{{ project_name }}.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, "templates"),
os.path.join(PROJECT_PATH, "templates/includes")
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework_swagger',
'django_jinja.contrib._pipeline',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder'
)
PIPELINE_ENABLE = True
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.closure.ClosureCompressor'
PIPELINE_CLOSURE_BINARY = 'C:\bunjilsrc\tools\minify\minify.bat'
PIPELINE_DISABLE_WRAPPER = True
PIPELINE_ENABLE_GAE_SUPPORT = True
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
MEDIA_ROOT = 'uploads/'
MEDIA_URL = "/media/"
PIPELINE_JS = {
'main': {
'source_filenames': (
'js/site.js '
),
'output_filename': 'js/main.js'
},
'vendor': {
'source_filenames': (
'js/vendor/jquery.js',
),
'output_filename': 'js/vendor.js'
}
}
PIPELINE_CSS = {
'main': {
'source_filenames': (
'bootstrap.css',
'site.css'
),
'output_filename': 'css/main.css'
}
}
Answer: Going to describe things which worked for me on local env (not GAE).
If you follow [django-pipeline official guide](http://django-
pipeline.readthedocs.org/en/latest/usage.html#jinja) it states, that you
should add `pipeline.templatetags.ext.PipelineExtension` to your environment,
which for me meant updating my `settings.py` to this:
# myproject/settings.py
TEMPLATES = [
{
...
},
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'myproject.jinja2.environment',
'extensions': ['pipeline.templatetags.ext.PipelineExtension']
}
}
]
How to migrate your template? For me it was dead easy, I just removed `{% load
pipeline %}` from top of the template and it worked.
|
Retrieving multiple values from a large jsonb field faster (postgresql 9.4)
Question: **tl;dr**
Using PSQL 9.4, is there a way to retrieve multiple values from a jsonb field,
such as you would with the imaginary function:
jsonb_extract_path(x, ARRAY['a_dictionary_key', 'a_second_dictionary_key', 'a_third_dictionary_key'])
With the hope of speeding up the otherwise almost linear time required to
select multiple values (1 value = 300ms, 2 values = 450ms, 3 values = 600ms)
**Background**
I have the following jsonb table:
CREATE TABLE "public"."analysis" (
"date" date NOT NULL,
"name" character varying (10) NOT NULL,
"country" character (3) NOT NULL,
"x" jsonb,
PRIMARY KEY(date,name)
);
With roughly 100 000 rows where each rows has a jsonb dictionary with 90+ keys
and corresponding values. I'm trying to write an SQL query to select a few (<
10) key+values in a fairly quick way (< 500 ms)
**Index and querying: 190ms**
I started by adding an index:
CREATE INDEX ON analysis USING GIN (x);
This makes querying based on values in the "x" dictionary fast, such as this:
SELECT date, name, country FROM analysis where date > '2014-01-01' and date < '2014-05-01' and cast(x#>> '{a_dictionary_key}' as float) > 100;
This takes ~190 ms (acceptable for us)
**Retrieving dictionary values**
However, once I start adding keys to return in the SELECT part, execution time
rises almost linear:
**1 value: 300ms**
select jsonb_extract_path(x, 'a_dictionary_key') from analysis where date > '2014-01-01' and date < '2014-05-01' and cast(x#>> '{a_dictionary_key}' as float) > 100;
Takes 366ms (+175ms)
select x#>'{a_dictionary_key}' as gear_down_altitude from analysis where date > '2014-01-01' and date < '2014-05-01' and cast(x#>> '{a_dictionary_key}' as float) > 100 ;
Takes 300ms (+110ms)
**3 values: 600ms**
select jsonb_extract_path(x, 'a_dictionary_key'), jsonb_extract_path(x, 'a_second_dictionary_key'), jsonb_extract_path(x, 'a_third_dictionary_key') from analysis where date > '2014-01-01' and date < '2014-05-01' and cast(x#>> '{a_dictionary_key}' as float) > 100;
Takes 600ms (+410, or +100 for each value selected)
select x#>'{a_dictionary_key}' as a_dictionary_key, x#>'{a_second_dictionary_key}' as a_second_dictionary_key, x#>'{a_third_dictionary_key}' as a_third_dictionary_key from analysis where date > '2014-01-01' and date < '2014-05-01' and cast(x#>> '{a_dictionary_key}' as float) > 100 ;
Takes 600ms (+410, or +100 for each value selected)
**Retrieving more values faster**
Is there a way to retrieve multiple values from a jsonb field, such as you
would with the imaginary function:
jsonb_extract_path(x, ARRAY['a_dictionary_key', 'a_second_dictionary_key', 'a_third_dictionary_key'])
Which could possibly speed up these lookups. It can return them either as
columns or as an list/array or even a json object.
**Retrieving an array using PL/Python**
Just for the heck of it I made a custom function using PL/Python, but that was
much slower (5s+), possibly due to json.loads:
CREATE OR REPLACE FUNCTION retrieve_objects(data jsonb, k VARCHAR[])
RETURNS TEXT[] AS $$
if not data:
return []
import simplejson as json
j = json.loads(data)
l = []
for i in k:
l.append(j[i])
return l
$$ LANGUAGE plpython2u;
# Usage:
# select retrieve_objects(x, ARRAY['a_dictionary_key', 'a_second_dictionary_key', 'a_third_dictionary_key']) from analysis where date > '2014-01-01' and date < '2014-05-01'
**Update 2015-05-21**
I re-implemented the table using hstore with GIN index and the performance is
almost identical to using jsonb, i.e not helpfull in my case.
Answer: You're using the [`#>`
operator](http://www.postgresql.org/docs/9.4/static/functions-json.html),
which looks like it performs a path search. Have you tried a normal `->`
lookup? Like:
select json_column->'json_field1'
, json_column->'json_field2'
It would be interesting to see what happened if you used a temporary table.
Like:
create temporary table tmp_doclist (doc jsonb)
;
insert tmp_doclist
(doc)
select x
from analysis
where ... your conditions here ...
;
select doc->'col1'
, doc->'col2'
, doc->'col3'
from tmp_doclist
;
|
Remove non-GtkListBoxRow parent from GtkListBox
Question: Just a quick note about something I have encountered recently. I used python,
but I guess, it applies for other languages as well.
from gi.repository import Gtk
win = Gtk.Window()
listbox = Gtk.ListBox()
somewidget = Gtk.Somewidget()
win.add(listbox)
listbox.insert(somewidget -1)
listbox.remove(somewidget) #ERROR
This is a GtkListBox, filled with an item not of type GtkListBoxRow. When
attempting to remove it from the GtkListBox, it gives me the following:
Gtk-CRITICAL **: gtk_container_remove: assertion 'gtk_widget_get_parent (widget) == GTK_WIDGET (container) || GTK_IS_ASSISTANT (container) || GTK_IS_ACTION_BAR (container) || GTK_IS_POPOVER_MENU (container)' failed
Answer: The problem is, that GtkListBox must only have children of type GtkListBoxRow.
(see [GTK
doc](https://developer.gnome.org/gtk3/stable/GtkListBox.html#GtkListBoxRow))
So, when trying to insert another widget, there is automatically added a
GtkListBoxRow widget inbetween:
+-----------------------------------+
| |
| GtkListBox |
| + |
| +---> GtkListBoxRow (auto-added) |
| + |
| +---> Gtksomewidget |
| |
+-----------------------------------+
Gtk will fail if you try to remove your own widget, because it wants the
direct children of your ListBox. So instead of using
listbox.remove(somewidget)
type
listbox.remove(somewidget.get_parent())
|
Python: Error importing OpenCV
Question: I installed opencv with Homebrew. I'm getting the following error -
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/cv2.so, 2): Library not loaded: /usr/local/lib/libpng16.16.dylib
Referenced from: /usr/local/Cellar/opencv/2.4.11_1/lib/libopencv_highgui.2.4.dylib
Reason: Incompatible library version: libopencv_highgui.2.4.dylib requires version 34.0.0 or later, but libpng16.16.dylib provides version 33.0.0
How do I fix this?
Answer:
Library not loaded: /usr/local/lib/libpng16.16.dylib
^ libpng hasn't been loaded for some reason
Referenced from: /usr/local/Cellar/opencv/2.4.11_1/lib/libopencv_highgui.2.4.dylib
^ highgui tried to load it.
Reason: Incompatible library version
^ `libopencv_highgui` looks to require at least version 34.0.0 of `libpng`,
whereas you have version 33.0.0. I expect updating libpng should do the trick.
|
How to do a simple Pika SelectConnection to send a message, in python?
Question: I am trying to convert my code to send rabbitmq messages via Pika instead. I
am having a lot of trouble understanding how to send a simple message using an
asynchronous connection (such as SelectConnection).
In my old code, which I use the amqp library I simply declare a class like
this:
import amqp as amqp
class MQ():
mqConn = None
channel = None
def __init__(self):
self.connect()
def connect(self):
if self.mqConn is None:
self.mqConn = amqp.Connection(host="localhost", userid="dev", password="dev", virtual_host="/", insist=False)
self.channel = self.mqConn.channel()
elif not self.mqConn.connected:
self.mqConn = amqp.Connection(host="localhost", userid="dev", password="dev", virtual_host="/", insist=False)
self.channel = self.mqConn.channel()
def sendMQ(self, message):
self.connect()
lMessage = amqp.Message(message)
self.channel.basic_publish(lMessage, exchange="DevMatrixE", routing_key="dev_matrix_q")
And then elsewhere in my code I call sendMQ("this is my message"), and then
the code continues. I do not need to listen for acknowledgements etc.
Could someone please write a simple class utilizing pika and SelectConnection
that would also work to just send a message using sendMQ("this is my
message")? I've looked at the pika examples but I don't know how to get around
the ioloop and KeyboardInterrupt. I guess I'm just not sure how to make my
code continue to run without all these try/excepts... Also, not exactly sure
how I can pass my message on through all the callbacks...
Any help is appreciated!
Thanks.
Answer: As a first approach I recommend you to start with this pub/sub examples
provided at the end of the post. Once you understand this simple example start
following the tutorial provided right before the code blocks at the end. The
tutorial that has 6 different use cases, with its python examples. With the 5
first steps you will understand the way it works. You should have the clear
the concept of exchange (entity that routes the messages to each queue),
binding key (key used to connect an exchange and a queue), routing key (key
that is sent along with the message from the publisher and that is used by the
exchange to route message to one queue or another) and queue (a buffer that
can store messages, can have more than 1 (or 1 if wanted) subscriber and that
can get messages from more than 1 exchange and based in different binding
keys). Besides, there's more than one type of exchange (fanout, topic (this
one is probably the one you need)...).
If this all sounds new, please follow the tutorial provided by RabbitMQ:
<https://www.rabbitmq.com/tutorials/tutorial-one-python.html>
pub.py:
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
sub.py:
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
|
Operational Error No such table Django
Question: Hi I am doing the djangogirls tutorial and have come across the
OperationalError no such table: blog_post. This works perfect on my virtual
environment, but I get the OperationalError after pushing to heroku.
I am using Django 1.7.7. More information on the error is available at:
<https://girlsblog.herokuapp.com/>
I have done `python manage.py makemigrations python manage.py migrate`
initially in the beginning of the tutorial. Then I attempted to do it again
and there are "No changes detected" and "No migrations to make"
This is my post_list.html
{% extends 'blog/base.html' %}
{% block content %}
{% for post in posts %}
<div class="post">
<div class="date">
{{ post.published.date }}
</div>
<h1><a href="{% url 'blog.views.post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
<p> {{ post.text|linebreaks }}</p>
</div>
{% endfor %}
{% endblock content %}
This is my .gitignore
myvenv
__pycache__
staticfiles
local_settings.py
db.sqlite3
Models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Settings.py
"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1l8)#&q8r_wwev1r9mm8q5ezz8p#)rvg(l4%(t^-t8s4bva2+r'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
import dj_database_url
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
DEBUG = False
try:
from .local_settings import *
except ImportError:
pass
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
blog/views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from .forms import PostForm
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
I am really new to this, so please forgive "simple" mistakes.
Answer: Old post, but does not appeared to be answered so I'll take a shot. I was led
here via google after having a similar problem.
This issue is probably a missing database on the heroku side. If you are
pushing via git, and db.sqlite3 is in your .gitignore, it definitely will be
missing there and will need to be created there. This was exactly my issue
when fiddling with a pre-made example (where the db had not yet been created).
$ python manage.py migrate
on your heroku environment should fix it.
|
Unsure of my python explanatory comments
Question: I'm doing Learn Python the Hard Way exercise 15
A study drill is to explain every line with comments, but I feel unsure of my
explanations. I'm looking for corrections to my mistakes and improvements.
Correct term usage is my biggest worry, especially when it comes to variables
and file-objects.
this is the plain code
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
This is the code with my inadequate explanatory comments.
#the following is what is run from commandline
#each word(?) following python is an argument
#python ex15.py ex15_example.txt
#imports the "argument variable" module from the sys package
from sys import argv
#assigns commandline arguments to variables
script, filename = argv
#creates "txt" variable that creates a file-object of the filename variable
txt = open(filename)
#prints written string followed by filename variable
print "Here's your file %r:" % filename
#reads and prints variable "txt" which is a file object
print txt.read()
#prints string asking for raw_input
print "Type the filename again:"
#prompts you for raw_input and takes your raw_input and makes file_again variable
file_again = raw_input ("> ")
#creates txt_again file-object of file_again variable
txt_again = open(file_again)
#reads and prints txt_again file-object
print txt_again.read()
Answer: The purpose of these comments is only for you to write them and, by doing so,
learning and remembering what each line does. they don't have to follow rules
of proper commenting (not like anybody comments every single line in real
code, what'd be using python for then? LOL)
So, with that out of the way, lemme go through each line like you did.
#the following is what is run from commandline
#each word(?) following python is an argument
#python ex15.py ex15_example.txt
# (Correct. )
#imports the "argument variable" module from the sys package
# (It doesn't work like that. sys is a module,
# meaning a sis.py file stored somewhere else is accessed and interpreted.
# And argv is an object declared within
# said file (could be a class, a global variable, etc.
# for example. in this case, it's the list of command parameters. )
from sys import argv
#assigns commandline arguments to variables
# (Yeah, since he's doing this, it means argv has 2 items inside, and
# each is assigned to the respective variable).
script, filename = argv
#creates "txt" variable that creates a file-object of the filename variable
#(Yup)
txt = open(filename)
#prints written string followed by filename variable
#(This is a formatted string, similar to how you use printf in C.
# If you don't know them now, you will later, probably.)
print "Here's your file %r:" % filename
#reads and prints variable "txt" which is a file object
#(the method 'read' basically goes through the remaining unread
#lines and returns them as a big-ass string, which is then printed
# by you)
print txt.read()
#prints string asking for raw_input
print "Type the filename again:"
#prompts you for raw_input and takes your raw_input and makes file_again variable
# (yup, nothing to see here...)
file_again = raw_input ("> ")
#creates txt_again file-object of file_again variable
# (yup)
txt_again = open(file_again)
#reads and prints txt_again file-object
# (no big surprises here. BTW, if you use txt.read() again, you'll get
# an empty string. If you already know iterators from some other language,
# think of file objects as iterators of a file. Once they are used once,
# you need another one (you can reset this one, though, with some other method).
print txt_again.read()
|
How to let MagicMock behave like a dict?
Question: mock(<http://mock.readthedocs.org/en/latest/index.html>) is a great tool in
python for unit test. It can conveniently mock a method or class or dict.But I
encountered a problem which I couldn't find a straightforward way to deal with
by mock.
This is the function to be tested:
def function_to_be_tested(id, responses):
if not id in responses:
print '%s not exist'%pole_id
return
if id in responses.redundantErrorResponses:
print '%s is redundant'%pole_id
return
do_something()
argument **responses** is a dict like object which has some other
attributes(such as redundantErrorResponses) except dict inherent features. Now
I want to construct a mock responses to let `id in responses`to be True and
`id in responses.redundantErrorResponses` to be False. This is what I do:
pole_id = 30
pole_value = 100
pole_dic = {pole_id:pole_value}
mock_responses = MagicMock()
mock_responses.__getitem__.side_effect = lambda k: pole_dic[k]
mock_responses.__iter__.side_effect = iter(pole_dic)
mock_responses.redundantErrorResponses = {}
But error occurred:
function_to_be_tested(pole_id, mock_responses)
>>30 not exist
So how can I construct a MagicMock object meanwhile can iterate like a dict or
how can I construct a dict meanwhile support MagicMock features(add attribute
freely)?
Answer: Why mess around with `__iter__`? It seems to me that you want to mess with
`__contains__`:
>>> import mock
>>> m = mock.MagicMock()
>>> d = {'foo': 'bar'}
>>> m.__getitem__.side_effect = d.__getitem__
>>> m.__iter__.side_effect = d.__iter__
>>> m['foo']
'bar'
>>> 'foo' in m
False
>>> m.__contains__.side_effect = d.__contains__
>>> 'foo' in m
True
|
Why is python giving large errors when dividing the results of sin()
Question: I was trying to find the values for the first ten integer inputs of n for an
equation I found: `x = sin(2π / n) / sin(π / n)`. The output I got from the
code I wrote to find them was quite surprising:
>>> for i in range(1, 11):
print math.sin(2 * math.pi / i) / math.sin(math.pi / i)
-2.0
1.22464679915e-16
1.0
1.41421356237
1.61803398875
1.73205080757
1.8019377358
1.84775906502
1.87938524157
1.90211303259
I realise that there will be rounding errors, and as such the following
results don't surprise me at all:
>>> math.sin(2 * math.pi)
-2.4492935982947064e-16
>>> math.sin(math.pi)
1.2246467991473532e-16
The question is, how did the first result end up with -2.0, I might expect it
to return something close to zero or an error / nan?
If you are interested in knowing, this equation should give the length (x) of
a line that stretches between one point and another point 2 points away in a
shape with n equal sides of 1 and all equal angles (the length of the smallest
diagonal of an isogon with side length 1).
Answer: For the second result, the impact is quite small in absolute terms:
1.22464679915e-16 is a very small number and very close to zero, about
0.00000000000000012246
If you simply want to avoid that small error having a large impact in how your
results are displayed, use a formatting string, e.g:
for i in range(1, 11):
print "{0:.10f}".format(math.sin(2 * math.pi / i) / math.sin(math.pi / i))
output:
-2.0000000000
0.0000000000
1.0000000000
1.4142135624
1.6180339887
1.7320508076
1.8019377358
1.8477590650
1.8793852416
1.9021130326
> how did the first result end up with -2.0, I might expect it to return
> something close to zero or an error / nan?
The first result is when i is 1, so it simplifies to:
math.sin(2 * math.pi) / math.sin(math.pi)
Due to floating point errors, `math.sin(2 * math.pi)` evaluates to
`-2.44921270764e-16`, while `math.sin(math.pi)` evaluates to
`1.22460635382e-16`.
A floating point division of `-2.44921270764e-16 / 1.22460635382e-16` gives
`-2.0`, so that's the final output.
In the absence of floating point errors, both `math.sin(2 * math.pi)` and
`math.sin(math.pi)` should have evaluated to zero, but it just so happened by
the combined quirks of the floating point implementation and Python sin
function implementation that the floating point error of the first was twice
that of the second, and negative, so dividing them gave -2.
The floating point error in the internal representation of `math.pi * 2` is
twice that of `math.pi` because when you double a value with an error margin
the error margin also doubles, and it is not possible to represent pi as a
floating point number without some error. Speculation: that error propagates
through the sin calculation, and a negative is introduced because of something
in the sin calculation related to the fact that the sin function in the range
of pi to 2 pi is the negative of the function in the range of 0 to pi.
If you want to round extremely small values to zero, you can use
[numpy.around](http://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html#numpy.around)
to round to a given number of decimals, e.g:
import numpy
for i in range(1, 11):
print numpy.around(numpy.sin(2 * numpy.pi / i), 15) / numpy.around(numpy.sin(numpy.pi / i), 15)
This produces a nan for the first result.
|
Python, optimizing a list comprehension for string concatenation
Question: I'm using `cProfile` to run benchmarks on a script that process strings via
list comprehension. The target line I'd like to optimize looks like this:
signals = [('prefix' + str(day) + '_' + s) for s in signals]
where `day` is an integer.
This particular line is using a whopping 33% of the entire run time. Of
course, it's called million of times during the execution.
I've tried a couple obvious alternatives, including `''.join('prefix',
str(day), '_', s)`, `'prefix{:}_'.format(day)`, and using
`numpy.core.defchararray.add` to concatenate a prefix array created via
`numpy.tile` with `signals`. They are both up to 2x slower than list
comprehension.
Is there still room for speed optimization for this line?
Answer: This should bring at least a minimum improvement:
# First precalculate the static part of the string
template = 'prefix%s_' % day + '%s'
# Then, use the %s string interpolation instead of joining strings with '+'
# -->> Note: this proved to be wrong later...
signals = [template % s for s in signals]
# Alternatively you could use map to compare efficiency (be aware of differences between python 2 and 3)
signals = map(template.__mod__, signals)
The `str.format` is more expensive than the `%s` interpolation, so I am not
going to try it.
Now let's compare the timings. Your method:
>>> import timeit
>>> day = 45
>>> signals = ['aaaa', 'bbbb', 'cccccc', 'dddddddddddd']
>>> timeit.timeit("[('prefix' + str(day) + '_' + s) for s in signals]", 'from __main__ import day, signals')
1.35095184709592
My first approach
>>> template = 'prefix%s_' % day + '%s'
>>> timeit.timeit("[template % s for s in signals]", 'from __main__ import template, signals')
0.7075940089748229
My second approach
>>> timeit.timeit("map(template.__mod__, signals)", 'from __main__ import template, signals')
0.9939713030159822
So, the precalculation of the template with list comprehension seems to win.
There are further things to consider, as for example, if a generator is good
enough for you.
**EDIT** from info pointed out in the interesing comments, I add another
solution: inside of the tight loop we are only joining two strings together,
so we can concatenate them directly instead of %-formatting
>>> template = 'prefix%s_' % day
>>> timeit.timeit("[template + s for s in signals]", 'from __main__ import template, signals')
0.39771016975851126
Which for the moment is the winner.
|
M2Crypto installation
Question: I am struggling to get my M2Crypto installation to work
C:\Python27>python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from M2Crypto import RSA
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\M2Crypto\__init__.py", line 22, in <module>
import __m2crypto
ImportError: No module named __m2crypto
>>>
Not really surprising as there is no __m2crypto module anywhere, but where
should it be and where should I get it from?
I have installed M2Crypto from <https://pypi.python.org/pypi/M2Crypto> by
downloading M2Crypto-master and copying the unziped M2Crypto folder to
c:\Python27\lib
From M2Crypto I only need the RSA functionality so suggestions involving
alternatives to M2Crypto would also be helpful.
Any help highly appreciated
Answer: There pretty good instruction on building M2Crypto, I've using myself, here:
<http://www.gooli.org/blog/building-m2crypto-on-windows/>
> **Building M2Crypto for Windows**
>
> M2Crypto uses a tool called SWIG to help write the Python code that wraps
> the OpenSSL library that is written in C, so we’ll have to download and
> install it.
>
> Let’s go.
>
> 1. Download the latest SWIG Windows binaries from
> <http://www.swig.org/download.html> .
> 2. Unzip and untar the SWIG package to some directory and add that
> directory to your PATH.
> 3. Download the latest M2Crypto sources from
> <http://chandlerproject.org/bin/view/Projects/MeTooCrypto>.
> 4. Unzip and untar the M2Crypto source somewhere and open a command prompt
> there.
> 5. > python setup.py build_ext –openssl c:/openssl
> 6. > python setup.py bdist_wininst
>
>
> That last command will create a nice M2Crypto-0.18.win32-py2.4.exe file in
> the dist subdirectory which you can run to install M2Crypto in the Python
> site-packages directory.
>
> To test your build, run python and do import M2Crypto. If you get an error
> that says ‘ImportError: DLL load failed with error code 182′, it’s because
> the M2Crypto library can’t find the OpenSSL DLLs. You’ll need to place the
> libeay32.dll and ssleay32.dll files somewhere python can find them. The
> directory in which your script resides is a good bet.
If you still have problems with building, I'd recently compiled M2Crypto for
my needs on Windows 7 x64 - Python 2.7 You can download binary here
(M2Crypto-0.22.3.win32-py2.7.exe):
<https://drive.google.com/file/d/0ByAiJQIq8icYOUNiZEJQQzVhdVU/view?usp=sharing>
Good Luck
|
Ubuntu, Anaconda: Cannot import python shapely package
Question: [Shapely Import problem Related to MAC OS
X](http://stackoverflow.com/questions/25761682/python-cant-import-shapely)
I installed shapely using `sudo apt-get install python-shapely`.
I am using `Python 2.7.8 |Anaconda 2.1.0 (64-bit)|` with `ubuntu 14.04 LTS (64
bit)`
After successful installation, when I try to import it from `ipython` it gives
me an import error. `ImportError: No module named shapely`
How do I fix this?
Answer: That happens because `apt-get` installs packages to the system default python,
under `/usr/python2.7/lib/site-packages`. Anaconda has its own package
manager, [`conda`](http://conda.pydata.org/docs/intro.html), which you might
want to use in your case. `conda install shapely` should do the trick.
|
Python Django: Minimal Django + Cassandra local application
Question: I am trying to put together a minimum Django application that uses Cassandra
as the database.
Here is what I tried:
1. Started a brand new Django project in PyCharm. Checked that `python manage.py runserver` works as expected.
2. Installed Cassandra using the instructions [here](http://wiki.apache.org/cassandra/DebianPackaging). I had to change the `rpc_port` and `storage_port` to numbers lower than 9000 to get this to work (probably something to do with my firewall). Cassandra is running, and I am able to execute instructions using `cqlsh`.
3. Installed [`cassandra-django-engine`](http://r4fek.github.io/django-cassandra-engine/).
4. Made the following changes to the `settings.py` file:
* Added `django_cassandra_engine` to the front of the `INSTALLED_APPS` tuple:
INSTALLED_APPS = (
'django_cassandra_engine',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
* Replaced SQLite as the database to Cassandra, like so:
DATABASES = {
'default': {
'ENGINE': 'django_cassandra_engine',
'NAME': 'db',
'TEST_NAME': 'test_db',
'HOST': 'localhost',
'PORT': '8160',
'OPTIONS': {
'replication': {
'strategy_class': 'SimpleStrategy',
'replication_factor': 1
}
}
}
}
Note that this is the part that I am least sure about. I could not figure out,
based on the documentation what the parameters `NAME` and `TEST_NAME` are
supposed to be. Note also that I have added a `'PORT'` key and that the port
number defaults to `9160` but I have changed it to `8160` for the reasons
mentioned above. Not sure I need to add this key.
# Error information:
Here is a full traceback of the error from running a `python manage.py
runserver` with the above project. Note that there are no apps defined in the
project yet.
/usr/local/lib/python3.4/dist-packages/django/db/utils.py:238: RemovedInDjango19Warning: In Django 1.9 the TEST_NAME connection setting will be moved to a NAME entry in the TEST setting
self.prepare_test_settings(alias)
/usr/local/lib/python3.4/dist-packages/cassandra/util.py:486: UserWarning: The blist library is not available, so a pure python list-based set will be used in place of blist.sortedset for set collection values. You can find the blist library here: https://pypi.python.org/pypi/blist/
"The blist library is not available, so a pure python list-based set will "
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django_cassandra_engine/models.py", line 7, in <module>
from uwsgidecorators import postfork
File "/usr/local/lib/python3.4/dist-packages/uwsgidecorators.py", line 10, in <module>
import uwsgi
ImportError: No module named 'uwsgi'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/usr/local/lib/python3.4/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/local/lib/python3.4/dist-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/usr/local/lib/python3.4/dist-packages/django_cassandra_engine/models.py", line 12, in <module>
cassandra_connection.connect()
File "/usr/local/lib/python3.4/dist-packages/django_cassandra_engine/base/__init__.py", line 94, in connect
self.connection = CassandraConnection(**settings)
File "/usr/local/lib/python3.4/dist-packages/django_cassandra_engine/connection.py", line 52, in __init__
self.setup()
File "/usr/local/lib/python3.4/dist-packages/django_cassandra_engine/connection.py", line 59, in setup
connection.setup(self.hosts, self.keyspace, **self.connection_options)
File "/usr/local/lib/python3.4/dist-packages/cassandra/cqlengine/connection.py", line 129, in setup
session = cluster.connect()
File "/usr/local/lib/python3.4/dist-packages/cassandra/cluster.py", line 755, in connect
self.control_connection.connect()
File "/usr/local/lib/python3.4/dist-packages/cassandra/cluster.py", line 1868, in connect
self._set_new_connection(self._reconnect_internal())
File "/usr/local/lib/python3.4/dist-packages/cassandra/cluster.py", line 1903, in _reconnect_internal
raise NoHostAvailable("Unable to connect to any servers", errors)
cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'localhost': OperationTimedOut('errors=None, last_host=None',)})
From what I can understand,
1\. There is a top level `ImportError`:
ImportError: No module named 'uwsgi'
2\. And there is a nested error:
cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'localhost': OperationTimedOut('errors=None, last_host=None',)})
I am not sure which one of the two above is the more relevant error, and how
to resolve the error in either case. Note that I have installed both the
modules `uwsgi` and `uwsgidecorators`.
Answer: So it turns out that the answer was fairly straightforward. Yes, a `'PORT'`
key is required (actually a `'port'` key), but it goes into the `'connection'`
setting, and is set to the `storage_port` and not to the `rpc_port`. Once I
make these changes, the Django server runs cleanly.
|
undefined symbol: PyUnicodeUCS2_Decode
Question: I'm trying to connect to my google sheets with gspread. Here is the code:
#IMPORT STANDARD LIBRARIES
import json
import os
#IMPORT THIRD PARTY LIBRARIES
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
key_location = '/home/selecaotwo/Dropbox/Public/my.ENV/' + os.sep + 'sys.CREDENTIALS'
key_file_h = 'test-project-auth-a4f3c4bd20c4.json'
print key_location + os.sep + key_file_h
json_key = json.load(open(key_location + os.sep + key_file_h))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)
Running this code gives me the following error:
/home/selecaotwo/Dropbox/Public/my.ENV//sys.CREDENTIALS/test-project-auth-a4f3c4bd20c4.json
Traceback (most recent call last):
File "/home/selecaotwo/Desktop/gspread-test/gspread-test-001-codeRegist-0001.py", line 17, in <module>
gc = gspread.authorize(credentials)
File "/usr/local/lib/python2.7/site-packages/gspread/client.py", line 335, in authorize
client.login()
File "/usr/local/lib/python2.7/site-packages/gspread/client.py", line 98, in login
self.auth.refresh(http)
File "build/bdist.linux-x86_64/egg/oauth2client/client.py", line 598, in refresh
File "build/bdist.linux-x86_64/egg/oauth2client/client.py", line 769, in _refresh
File "build/bdist.linux-x86_64/egg/oauth2client/client.py", line 795, in _do_refresh_request
File "build/bdist.linux-x86_64/egg/oauth2client/client.py", line 1425, in _generate_refresh_request_body
File "build/bdist.linux-x86_64/egg/oauth2client/client.py", line 1554, in _generate_assertion
File "build/bdist.linux-x86_64/egg/oauth2client/crypt.py", line 162, in from_string
File "/usr/local/lib/python2.7/site-packages/OpenSSL/__init__.py", line 36, in <module>
from OpenSSL import crypto
ImportError: /usr/local/lib/python2.7/site-packages/OpenSSL/crypto.so: undefined symbol: PyUnicodeUCS2_Decode
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/home/selecaotwo/Desktop/gspread-test/gspread-test-001-codeRegist-0001.py"]
[dir: /home/selecaotwo/Desktop/gspread-test]
[path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]
I read on the forums that this is likely an issue between my Ubuntu system
(14.04 LTS) and Python (2.7.9) but the weird thing was when I recompiled
python with --enable-encoding=usc2, I got the same error on the same line but
instead of saying "undefined symbol: PyUnicodeUCS2_Decode" it simply said
"undefined symbol: PyUnicodeUCS4_Decode". This leads me to believe the problem
may be something else and I'm not sure how to proceed.
Answer: I'm not sure if this will solve the problem. Instead of putting in the json
file itself, can you try entering the client_email and private key like this.
The client_email can be copied as such. For the private key, do this instead:
key = u"-----BEGIN PRIVATE KEY-----\nBLABLA_\n-----END PRIVATE KEY-----\n".encode("utf-8")
credentials = SignedJwtAssertionCredentials(client_email,key,scope)
|
mvpa2.suite: Runtime warning and erro in Python 2.7.6
Question: I just installed mvpa2 module on my ubuntu 14.04, Python 2.7.6. following the
instruction at <http://www.pymvpa.org/installation.html> using `sudo aptitude
install python-mvpa2`
Command `import mvpa2` works well, but when I run `from mvpa2.suite import *`
, I get the followin warning in my terminal:
**/usr/local/lib/python2.7/dist-packages/sklearn/pls.py:7: DeprecationWarning:
This module has been moved to cross_decomposition and will be removed in 0.16
"removed in 0.16", DeprecationWarning)**
And also fallowing error:
**TypeError: __init__() got an unexpected keyword argument 'rho'**
Appreciate your help!
Answer: That problem is due to an incompatibility of the python-mvpa2 and scikit-learn
versions. You can check more details on that in this
[page](https://github.com/PyMVPA/PyMVPA/blob/master/mvpa2/clfs/warehouse.py),
because depends on which scikit-learn version you have what will be the
parameters to call a given function.
A short solution is to uninstall your python-mvpa2 and scikit-learn, and
install them directly from their github repos:
* [python-mvpa2] `https://github.com/PyMVPA`
* [scikit-learn] `https://github.com/scikit-learn/scikit-learn`
I just did it and now the example `doc/examples/som.py` (for my case) is
working perfectly.
|
Trouble importing yahoo finance to python
Question: I have installed yahoo finance from the PyPI with pip, and when I go to run
the following script i get an import error: No module named yahoo_finance
from yahoo_finance import Share
BlackDiamond = Share('BDE')
print(BlackDiamond.get_open)
Answer: Make sure `pip` installed to somewhere in Python's include path. Run this
command:
$ pip show yahoo-finance
---
Metadata-Version: 1.1
Name: yahoo-finance
Version: 1.2.1
Summary: Python module to get stock data from Yahoo! Finance
Home-page: https://github.com/lukaszbanasiak/yahoo-finance
Author: Lukasz Banasiak
Author-email: [email protected]
License: MIT
Location: /usr/local/lib/python2.7/site-packages
Requires: pytz, simplejson
Entry-points:
[console_scripts]
yahoo-finance = yahoo_finance:main
See where it says `Location: /usr/local/lib/python2.7/site-packages`? Make
sure yours is the system site-packages directory. Often (for example, on Mac
or Ubuntu) you need to `sudo pip install` to get them in system site-packages.
If your intention is to install it as a user to somewhere in your home
directory, you need to ensure that directory is in your python-path.
To see your current path settings, create a file called `path.py` in your home
directory and include the following:
import os
import sys
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
print "PYTHONPATH: ", user_paths
print "sys.path: ", sys.path
Run `python path.py` and you should see output similar to this:
$ python path.py
PYTHONPATH: ['/usr/local/lib/python2.7/site-packages', '']
sys.path: ['/Users/me/dir', '/usr/local/Cellar/python/2.7.9/..../lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/usr/local/lib/python2.7/site-packages']
Now, make sure the path where `yahoo_finance` was installed is inside your
path configuration. If it's not, you can modify `$PYTHONPATH` via your
`.bashrc` and/or `.bash_profile`:
export PYTHONPATH="${PYTHONPATH}:/path/to/your/dir"
For example:
$ export PYTHONPATH="${PYTHONPATH}:/path/to/your/dir"
$ python path.py
PYTHONPATH: ['/usr/local/lib/python2.7/site-packages', '', '/path/to/your/dir']
Then, you should be able to include your module. Again, though: If you're
installing a system-wide site package, you probably just want to use `sudo
pip`.
|
Release the Python import lock from a thread you do not control & do not have access to
Question: So, I'm injecting a DLL into a Cython application in order to extend its
functionality. I am doing this using the following code: Note: using Python
2.7; uses the old ModuleNoBlock scheme
PyGILState_STATE sMain = PyGILState_Ensure();
PyObject* mHook = PyImport_ImportModuleNoBlock("hookmodule");
PyGILState_Release(sMain);
Now, when I inject the DLL into the application and print errors, I get the
following:
ImportError: Failed to import hookmodule because the import lockis held by another thread.
I found the source to the imp module here:
<http://svn.python.org/projects/python/trunk/Python/import.c>
However _PyImport_ReleaseLock(void) only releases the lock if you call it from
the same thread where the lock was acquired.
Is it possible to do this?
Answer: Fixed. Use _PyImport_ReInitLock(void) before importing
|
Replace CSS block of text within file Python
Question: I'm tying to make a python program to help me make simple edits to a config
file. I want to be able to read the file, replace a section of the file and
then write the changes. One of the problems i have been having is that there
are multiple lines that are the same. For example the config file looks like:
/* Panel */
#panel {
background-color: black;
font-weight: bold;
height: 1.86em;
}
#panel.unlock-screen,
#panel.login-screen {
background-color: transparent;
there are two lines that contain background-color: so i am unable to test if
the line is equal to a string because if i were to replace every line
containing background-color: i would get unwanted changes. Also I dont want to
have to rely on the index of the line because as lines of the config file are
added or removed, it will change. Any help would be appreciated!
Answer: It looks like you are trying to deal with CSS files. To properly parse this
file format, you need something like
[cssutils](https://pypi.python.org/pypi/cssutils/):
import cssutils
# Parse the stylesheet, replace color
parser = cssutils.parseFile('style.css')
for rule in parser.cssRules:
try:
if rule.selectorText == '#panel':
rule.style.backgroundColor = 'blue' # Replace background
except AttributeError as e:
pass # Ignore error if the rule does not have background
# Write to a new file
with open('style_new.css', 'wb') as f:
f.write(parser.cssText)
# Update
I made a change in the code and now only change the background for `#panel`
|
Sending Response to OPTIONS in Python Flask application
Question: I have a python Flask listener waiting on port 8080. I expect another process
to make a series of POST's to this port.The code for listener is as follows.
#!/usr/bin/env python2
from __future__ import print_function
from flask import Flask, request
from werkzeug import secure_filename
from datetime import datetime
import os, traceback, sys
import zlib
import ssl
import json
import os
import base64
app = Flask('__name__')
@app.route('/',methods=['GET','POST','OPTIONS'])
def recive_fe_events():
try:
data = request.get_data()
if request.content_length < 20000 and request.content_length != 0:
filename = 'out/{0}.json'.format(str(datetime.now()))
with open(filename, 'w') as f:
f.write(data)
print('Wrote', filename)
else:
print("Request too long", request.content_length)
content = '{{"status": 413, "content_length": {0}, "content": "{1}"}}'.format(request.content_length, data)
return content, 413
except:
traceback.print_exc()
return None, status.HTTP_500_INTERNAL_SERVER_ERROR
return '{"status": 200}\n'
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=False,port=8080)
However whenever I try to trigger an event to be pushed to the above
listener.It seems that I am getting `OPTIONS` instead of `POST`.
192.168.129.75 - - [20/May/2015 14:33:45] "OPTIONS / HTTP/1.1" 200 -
192.168.129.75 - - [20/May/2015 14:33:45] "OPTIONS / HTTP/1.1" 200 -
192.168.129.75 - - [20/May/2015 14:33:51] "OPTIONS / HTTP/1.1" 200 -
192.168.129.75 - - [20/May/2015 14:33:51] "OPTIONS / HTTP/1.1" 200 -
The investigation of my client revealed that it expects the following flags in
its `response` to `OPTIONS`.
Access-Control-Allow-Origin value_1
Access-Control-Allow-Methods value_2
Access-Control-Allow-Headers value_3
How do I format the above `response` to `OPTIONS` so that my server can start
receiving `POST` messages from the client.
Answer: You need to set up your application for CORS. The easiest was is to use
[Flask-CORS](http://flask-cors.readthedocs.org/en/latest/).
|
Avoiding TCP/IP connection hanging
Question: I am communicating with an instrument via TCP/IP using the Python `socket`
package.
The program sends a command to the instrument to perform an action, and then
repetitively sends another "check" command until it receives a "done" reply.
However, after many loops, the program hangs while waiting for a "done" reply.
I have circumvented this problem by using the `recv_timeout()` function below,
which returns no data if the socket is hanging, then I close the connection
with `socket.close()` and reconnect.
Is there a more elegant solution without having to reboot anything?
import socket
import time
def recv_timeout(self,timeout=0.5):
'''
code from http://code.activestate.com/recipes/408859/
'''
self.s.setblocking(0)
total_data=[];data='';begin=time.time()
while 1:There must be a way I can reboot to carry on communicating with the instrument, without having to restart.
#if you got some data, then break after wait sec
if total_data and time.time()-begin>timeout:
break
#if you got no data at all, wait a little longer
elif time.time()-begin>timeout*2:
break
try:
data=self.s.recv(8192)
if data:
total_data.append(data)
begin=time.time()
else:
time.sleep(0.1)
except:
pass
return ''.join(total_data)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(('555.555.55.555',23))
for action_num in range(0,1000):
socket.sendall(('performaction %s \r'%action_num).encode())
while True:
time.sleep(0.2)
socket.sendall(('checkdone \r').encode())
done = socket.recv_timeout()
if not done:
print 'communication broken...what should I do?'
socket.close()
time.sleep(60)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(('555.555.55.555',23))
elif done == '1':
print 'done performing action'
break
socket.close()
Answer: > I have circumvented this problem by using the recv_timeout() function below,
> which returns no data if the socket is hanging
Are you certain that the socket will hang forever? What about the possibility
that the instrument just sometimes takes more than half a second to respond?
(Note that even if the instrument's software is good at responding in a timely
manner, that is no guarantee that the response data will actually get to your
Python program in a timely manner. For example, if the TCP packets containing
the response get dropped by the network and have to be resent, that could
cause them to take more than .5 seconds to return to your program. You can
force that scenario to occur by pulling the Ethernet cable out of your PC for
a second or two, and then plugging it back in... you'll see that the response
bytes still make it through, just a second or two later on (after the dropped
packets get resent); that is, if your Python program hasn't given up on them
and closed the socket already.
> Is there a more elegant solution without having to reboot anything?
The elegant solution is to figure out what is happening to the reply bytes in
the fault scenario, and fixing the underlying bug so that the reply bytes no
longer get lost. WireShark can be very helpful in diagnosing where the fault
is; for example if WireShark shows that the response bytes did enter your
computer's Ethernet port, then that is a pretty good clue that the bug is in
your Python program's handling of the incoming bytes(*). On the other hand if
the response bytes never show up in WireShark, then there might be a bug in
the instrument itself that causes it to fail to respond sometimes. Wireshark
would also show you if the problem is that your Python script failed to send
out the "check" command for some reason.
That said, if you really can't fix the underlying bug (e.g. because it's a bug
in the instrument and you don't have the ability to upgrade the source code of
the software running on the instrument) then the only thing you can do is what
you are doing -- close the socket connection and reconnect. If the instrument
doesn't want to respond for some reason, you can't force it to respond.
(*) One thing to do is print out the contents of the string returned by
recv_timeout(). You may find that you did get a reply, but it just wasn't the
'1' string you were expecting.
|
What is the purpose of creating symbolic variables in Theano?
Question: In Theano, variables are written as 'symbols':
x = T.matrix("x")
y = T.vector("y")
From reading the documentation, it is implied that the reason we create these
symbols may be due to the fact that these variables are compiled into C code.
But I'm not sure if this is the case, much less the only reason for using
symbolic variables.
What is the purpose of creating symbolic variables in Theano? What can they do
that a, out of the box assignment in Python can't do?
Answer: The Theano web site opens with
> Theano is a Python library that allows you to define, optimize, and evaluate
> mathematical expressions involving multi-dimensional arrays efficiently.
which seems like quite a good summary of what it does but perhaps not why it
does it.
One of the main features of Theano is its symbolic differentiation feature.
That is, given a symbolic mathematical expression, Theano can automatically
differentiate the expression with respect to some variable within the
expression, i.e. it can automatically determine the gradient of the expression
along some dimension(s) of interest.
For example, if `y=x**2` (where `**` is the power operator) then the gradient
of `y` with respect to `x` is `dy/dx = 2*x`. Theano can do this automatically:
import theano
import theano.tensor
x = theano.tensor.scalar('x')
y = x ** 2
theano.printing.pp(y)
dy_dx = theano.grad(y, x)
theano.printing.pp(dy_dx)
If you run this code you'll see the output
(x ** TensorConstant{2})
((fill((x ** TensorConstant{2}), TensorConstant{1.0}) * TensorConstant{2}) * (x ** (TensorConstant{2} - TensorConstant{1})))
The `fill` operation just creates a tensor of the correct shape (a scalar in
this case) filled with ones and `TensorConstant{a}` is just the number `a` so
this can be simplified to
(x ** 2) == x ** 2
((1 * 2) * (x ** (2 - 1))) == (2 * (x ** 1)) == 2 * x
As expected.
Clearly this is not particularly helpful for such a simple mathematical
expression, but now imagine you're constructing an arbitrarily large and
complex mathematical expression for which the gradient is not so immediately
obvious, as is often the case in neural network research.
But there's more. Theano can do the above for expressions that involve
operations over not just scalars but also vectors, matrices, or any other
tensor.
Besides symbolic differentiation, Theano's symbolic approach offers other
significant benefits:
* Theano can compile symbolic mathematical expressions into executable code. It uses various techniques that can yield executable code that can run faster than plain Python code.
* Theano programs can often be switched between running on CPU and GPU with no code changes whatsoever.
* When running on CPU, Theano makes full use of numpy BLAS and OpenMP facilities, when available, to parallelize the execution over multiple CPU cores.
* When running on GPU, Theano makes full use of of the many cores on modern GPUs to parallelize the most costly operations (most notably matrix multiplication).
* Theano's compiler is an optimizing compiler in that it can change the expression (also known as the computation graph) using various transforms that maintain the semantics of the expression (it still computes the same results given the same inputs) but achieving various performance and, crucially, [numerical stability](http://mathworld.wolfram.com/NumericalStability.html) gains.
Plain Python does not offer any of the above and using numpy alone only offers
some of the parallelization features (via BLAS and OpenMP).
More on this topic [in the Theano
documentation](http://deeplearning.net/software/theano/introduction.html).
P.S. this is an expansion of @eickenberg brief comment to the question.
|
How to set timeout to pyplot.show() in matplotlib?
Question: I am using python's matplotlib to draw figures.
I want to draw a figure with a timeout, say 3 seconds, and the window will
close to move on the code.
I have known that pyplot.show() will create a blocking window with unlimited
timeout; pyplot.show(block=False) or pyplot.draw() will make the window non-
blocking. But what I want is let the code block for some seconds.
I have come up an idea that I might use an event handler or something, but
still not really clear how to solve this. Is there any simple and elegant
solution?
Suppose my code is like the following:
Draw.py:
import matplotlib.pyplot as plt
#Draw something
plt.show() #Block or not?
Answer: Here's a simple example where I have created a timer to set your timeout and
performed closing of window `plot.close()` in the callback function of the
timer. Start the timer before `plot.show()` and after three seconds timer
invokes `close_event()` and then continues with the rest of the code.
import matplotlib.pyplot as plt
def close_event():
plt.close() #timer calls this function after 3 seconds and closes the window
fig = plt.figure()
timer = fig.canvas.new_timer(interval = 3000) #creating a timer object and setting an interval of 3000 milliseconds
timer.add_callback(close_event)
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
timer.start()
plt.show()
print "Am doing something else"
Hope that was helpful.
|
edit:pandas multiline value in ipython notebook
Question: If I put something with newlines in cell into pandas dataframe, for example:
pd.DataFrame(data=[["""aa\n<br>
bb"""], ['bb']], columns=["col"])
I get something where all "newlines" are escaped. (html source looks like:
<td> aa\n<br>\n\nbb</td>)
Is there way to get table with formatted multiline output in cell?
**edit** : inspired by firelynx I could use now this:
**edit2** : html escaping added
**edit3** : nowrap attribute for td and th tags
df=pd.Dataframe(...) # see definition above
from IPython.display import HTML
import cgi
def escape(a):
return cgi.escape(a).replace('\n','<br>')
htm='<table>'+\
'<thead><tr><th></th>'+\
''.join(['<th nowrap>'+escape(c)+\
'</th>' for c in df])+'</tr></thead>'+ \
'<tbody>'+''.join(['<tr>'+'<th>'+str(r[0])+\
'</th>'+''.join(['<td nowrap>'+escape(c)+\
'</td>' for c in r[1]])+'</tr>' for r in enumerate(df.values)])+\
'</tbody></table>'
#print(htm)
HTML(htm)
Answer: The ipython notebook formats data for you if you just return values from a
cell in the way you do.
To see the actual value, you have to explicitly print it, look here:
df = pd.DataFrame(data=[["""aa\n<br>
bb"""], ['bb']], columns=["col"])
print df.ix[0].col
aa
<br>
bb
So nothing is actually wrong, it's just the ipython representation that fails
to show the truth.
There are display options to be changed, but nothing that revokes this default
behaviour. The display options are set by, for example:
pd.options.display.expand_frame_repr = False
[Display option reference](http://pandas.pydata.org/pandas-
docs/stable/options.html)
|
Local variable referenced before assignment, using multi-threading
Question: Code to add and delete values in a list are operations performed in different
threads.
using these global variables in multi-threading:
from threading import Thread
import time
a=[]
i = 0
j = 0
function for thread1:
def val_in():
while 1:
a.append(raw_input())
print "%s value at %d: %d added" % ( time.ctime(time.time()), i ,int(a[i])) // line 14
i+=1
function for thread 2:
def val_out():
while 1:
time.sleep(5)
try:
print "%s value at %d: %d deleted" % (time.ctime(time.time()), j, int(a.pop(j)))
i-=1
except:
print"no values lefts"
time.sleep(2)
defining and starting threads:
t = Thread(target = val_in)
t1 = Thread(target= val_out)
t.start()
t1.start()
Now when input is given as `1`, it should be added to the list `a`, but there
is an error:
Error: Exception in thread Thread-1:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/Users/dhiraj.agarwal/Documents/workspace/try3/multithread.py", line 14, in val_in
UnboundLocalError: local variable 'i' referenced before assignment
Answer: You should tell python that i is global:
def val_in():
global i
...
def val_out():
global i
...
|
Find variable closest to a value in a list
Question: I have only programmed basic functions in python before, so I hope this is
clear.
I have a list of variables `[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10]` to 1
decimal place. I have a variable B which can be any number to decimal place. I
would like to find the closest value in the list to variable B. And return not
the value but the A number(A5 for example).
Thanks!
Answer:
from operator import itemgetter
a = [A1, A2, ........, A10]
minimum_list = [abs(variable - B) for variable in a]
return min(enumerate(minimum_list), key=itemgetter(1))[0]
This will return the index of the variable with the minimum difference.
return a[min(enumerate(minimum_list), key=itemgetter(1))[0]]
This will return the value in the list with the minimum difference with the
variable B
|
Textexpander with Python to match phone numbers
Question: I want to use Textexpander and Python to match phone numbers via the
clipboard:
1. Click a phone number formated like `0798008080` in one application, _copy_ the number and insert the clipboard content with a Textexpander-Shortcut in another application like `0041 79 800 80 80`.
2. Click a phone number formatted like `079 800 80 80` in one application, _copy_ , insert the clipboard content with a Textexpander-Shortcut in another application like `0041 79 800 80 80`.
I have found a Textexpander snippet which sets the clipboard content in
uppercase:
#!/usr/bin/python
import sys
selection = """%clipboard"""
sys.stdout.write(selection.upper(),
but I have no clue how to adapt this snippet for my purpose (`%clipboard` is a
code used in Textexpander to access the clipboard content)
Does anyone have a suggestion?
Answer: @hackworks:
Yes I need still help in matching a pattern and transforming it.
I suppose that I need a Python-, Ruby- or perhaps AppleScript-Code for
transforming phone numbers like `0798008080` from the Clipboard (simple copy
the number by ⌘-C on a Mac) to `0041 79 800 80 80` and `079 800 80 80` to
`0041 79 800 80 80`:
1. ⌘-C (copy) a phone number (`0798008080`) to the clipboard
2. Go to another application, we say Evernote/Word etc.
3. Tipping a defined abbreviation from Textexpander like `;phone` which paste the transformed phone number `0041 79 800 80 80` into Evernote/Word etc.
The Python-, Ruby- or AppleScript-Code transforming the phone number is within
the snippet `;phone` from Textexpander:
1. If I type the shortcut `;phone` (or whatsoever: the shortcuts can be defined by the user itself), Textexpander should get the content from the clipboard (for that, the code `%clipboard` can be used within Textexpander),
2. then initiate a
3. Python-, Ruby- or whatsoever-code transforming the clipboard content (here: phone number),
4. transfer the transformed clipboard content to Textexpander,
5. which will (e) replace the shortcut `;phone` (Textexpander) with the transformed phone number and will insert the transformed phone number in Evernote/Word/Excel whatsoever
1, 2, 4 and 5 will be done by Textexpander. The clipboard content
"transforming" Code will be also placed directly in the Textexpander snippet,
in other words, Textexpander will initiate the Python-/Ruby-code.
In the example
#!/usr/bin/python
import sys
selection = """%clipboard"""
sys.stdout.write(selection.upper(),
Textexpander will do like a similar process: This code is written within a
Textexpander snippet. A shortcut like `;uc` (for uppercase) tipped in Word
will start the Textexpander snippet. Textexpander will get the clipboard
content (%clipboard), push a Python code
(`sys.stdout.write(selection.upper(),`) to uppercase the clipboard content,
and insert the transformed clipboard content in to Word. `#!/usr/bin/python`,
`import sys` and `selection` also have something to do with Python (I suggest
so), but I'am far away from really understand Python.
So, what I need is a Python/Ruby-code for transforming phone numbers formatted
like `0798008080` and `079 800 80 80` to `0041 79 800 80 80` and to put in the
code within Textexpander-workflow.
Does it make sense? Are my remarks understandable enough?
|
Python 3.4 : cStringIO vs. StringIO
Question: # QUESTION
I am returning an ImportError: No module named 'cStringIO'. Unfortunately
cStringIO doesn't exist anymore and I need to use StringIO as a replacement.
How can I do this?
import edgar
import ftplib
from io import StringIO
ftp = ftplib.FTP(edgar.FTP_ADDR)
ftp.login()
try:
edgar.download_all(ftp, "/tmp")
except Exception as e:
print(e)
finally:
ftp.close()
# OUTPUT
Traceback (most recent call last):
File "/usr/local/lib/ana/lib/python3.4/site- packages/edgar/downloader.py", line 5, in <module>
from cStringIO import StringIO
ImportError: No module named 'cStringIO'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/aranjohn/PycharmProjects/edgar/secEd.py", line 1, in <module>
import edgar
File "/usr/local/lib/ana/lib/python3.4/site- packages/edgar/__init__.py", line 1, in <module>
from .downloader import FTP_ADDR, file_list, download, download_all
File "/usr/local/lib/ana/lib/python3.4/site- packages/edgar/downloader.py", line 7, in <module>
from StringIO import StringIO
ImportError: No module named 'StringIO'
Process finished with exit code 1
Answer: `StringIO` no longer exists in 3.x. Use either `io.StringIO` for text or
`io.BytesIO` for bytes.
|
Run 'query session' from python
Question: So I am making a program in python that will report the users on a system who
connected with RGS.
One way to get users on windows is the `query session` command. I have tried
with both `os.popen` and `subprocess.Popen` with and without shell=True. I
even specified the full path of the command.
All I get is this error:
'C:/Windows/System32/query.exe' is not recognized as an internal or external command, operable program or batch file.
I can get it working using PsLoggedon.exe, but that wont tell me session type.
So I guess my question is: how can I get this command to work, or what is
another way to address this problem?
Answer:
import subprocess
args = ['C:\\Windows\\system32\\query.exe', 'user']
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output, err = process.communicate()
users = [line[1:].split(' ')[0] for line in output.strip().split('\n')[1:]]
print(users)
Prints `['poke']` for me.
|
Dividing point clouds into quadrants in python
Question: Suppose I have an array of 30 points in 3 dimensions cast as a numpy array in
python:
import numpy as np
b = np.round(np.random.random((30,3))*20)
b = b - b.mean(axis=0)
I want to separate these points into eight quadrants with reference to the
"center of mass" of the point cloud. I could do something like this:
for a in (b, -b):
q_list = a[a[:,0]>0.][a[a[:,0]>0.][:,1]>0][a[a[:,0]>0.][a[a[:,0]>0.][:,1]>0][:,2]>0]
quad_list.append(q_list * sign)
q_list = a[a[:,0]>0.][a[a[:,0]>0.][:,1]>0][a[a[:,0]>0.][a[a[:,0]>0.][:,1]>0][:,2]<=0]
quad_list.append(q_list * sign)
q_list = a[a[:,0]>0.][a[a[:,0]>0.][:,1]<=0][a[a[:,0]>0.][a[a[:,0]>0.][:,1]<=0][:,2]>0]
quad_list.append(q_list * sign)
q_list = a[a[:,0]>0.][a[a[:,0]>0.][:,1]<=0][a[a[:,0]>0.][a[a[:,0]>0.][:,1]<=0][:,2]<=0]
quad_list.append(q_list * sign)
sign *= -1
This works fine, of course. It returns a list with eight arrays of position
coordinates, each of which contains only the points that lie in a particular
quadrant. However I get the feeling that there should be clearer, more concise
way to handle this. Suggestions?
Answer: Here's a recursive solution. It should work for an arbitrary number of
dimensions.
import numpy as np
def split_into_quadrants(points, idx=0):
if idx < points.shape[-1]:
positive = points[points[:, idx] >= 0]
negative = points[points[:, idx] < 0]
return (split_into_quadrants(positive, idx+1) +
split_into_quadrants(negative, idx+1))
else:
return [points]
b = np.round(np.random.random((30,3))*20)
b = b - b.mean(axis=0)
print(split_into_quadrants(b))
|
Mutually recursive coroutines with asyncio
Question: I had the hypothesis that if I wrote mutually recursive coroutines with
asyncio, they would not hit the maximum recursion depth exception, since the
event loop was calling them (and act like a trampoline). This, however, is not
the case when I write them like this:
import asyncio
@asyncio.coroutine
def a(n):
print("A: {}".format(n))
if n > 1000: return n
else: yield from b(n+1)
@asyncio.coroutine
def b(n):
print("B: {}".format(n))
yield from a(n+1)
loop = asyncio.get_event_loop()
loop.run_until_complete(a(0))
When this runs, I get `RuntimeError: maximum recursion depth exceeded while
calling a Python object`.
Is there a way to keep the stack from growing in recursive coroutines with
asyncio?
Answer: To keep the stack from growing, you have to allow each coroutine to actually
exit after it schedules the next recursive call, which means you have to avoid
using `yield from`. Instead, you use
[`asyncio.async`](https://docs.python.org/3/library/asyncio-
task.html#asyncio.async) (or `asyncio.ensure_future` if using Python 3.4.4+)
to schedule the next coroutine with the event loop, and use
[`Future.add_done_callback`](https://docs.python.org/3/library/asyncio-
task.html#asyncio.Future.add_done_callback) to schedule a callback to run once
the recursive call returns. Each coroutine then returns an `asyncio.Future`
object, which has its result set inside the callback that's run when the
recursive call it scheduled completes.
It's probably easiest to understand if you actually see the code:
import asyncio
@asyncio.coroutine
def a(n):
fut = asyncio.Future() # We're going to return this right away to our caller
def set_result(out): # This gets called when the next recursive call completes
fut.set_result(out.result()) # Pull the result from the inner call and return it up the stack.
print("A: {}".format(n))
if n > 1000:
return n
else:
in_fut = asyncio.async(b(n+1)) # This returns an asyncio.Task
in_fut.add_done_callback(set_result) # schedule set_result when the Task is done.
return fut
@asyncio.coroutine
def b(n):
fut = asyncio.Future()
def set_result(out):
fut.set_result(out.result())
print("B: {}".format(n))
in_fut = asyncio.async(a(n+1))
in_fut.add_done_callback(set_result)
return fut
loop = asyncio.get_event_loop()
print("Out is {}".format(loop.run_until_complete(a(0))))
Output:
A: 0
B: 1
A: 2
B: 3
A: 4
B: 5
...
A: 994
B: 995
A: 996
B: 997
A: 998
B: 999
A: 1000
B: 1001
A: 1002
Out is 1002
Now, your example code doesn't actually return `n` all the way back up the
stack, so you could make something functionally equivalent that's a bit
simpler:
import asyncio
@asyncio.coroutine
def a(n):
print("A: {}".format(n))
if n > 1000: loop.stop(); return n
else: asyncio.async(b(n+1))
@asyncio.coroutine
def b(n):
print("B: {}".format(n))
asyncio.async(a(n+1))
loop = asyncio.get_event_loop()
asyncio.async(a(0))
loop.run_forever()
But I suspect you really meant to return `n` all the way back up.
|
All of a sudden str.decode('unicode_escape') stopped working [2.7.3]
Question: This snippet is taken from my recent python work. And it used to work just
fine
strr = "What is th\u00e9 point?"
print strr.decode('unicode_escape')
But now it throws the unicode decoding error:
Traceback (most recent call last):
File "C:\Users\Lenon\Documents\WorkDir\pyWork\ocrFinale\F1\tests.py", line 49, in <module>
print strr.decode('unicode_escape')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)
What is the possible cause of this?
Answer: You either have enabled unicode literals or have created a _Unicode_ object by
another means, by mistake.
The `strr` value is _already_ a unicode object, so in order to decode the
value Python first tries to _encode_ to a byte string.
If you have an actual byte string your code works:
>>> strr = "What is th\u00e9 point?"
>>> strr.decode('unicode_escape')
u'What is th\xe9 point?'
but as soon as `strr` is in fact a Unicode object, you get the error as Python
tries to _encode_ the object using the default ASCII codec first:
>>> strr.decode('unicode_escape').decode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)
It could be that you enabled `unicode_literals`, for example:
>>> from __future__ import unicode_literals
>>> strr = "What is th\u00e9 point?"
>>> type(strr)
<type 'unicode'>
>>> strr.decode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)
|
Multi threading using Python and pymongo
Question: Hi im looking to make a program that will class tweets positively and
negatively classifies tweets about a company already saved in a mongodb and
once classified, to update a integer based on then result.
I have code made to make this possible but i would like to multi-thread the
program but I have had no experience of this in python whatsoever and have
been trying to follow tutorials with no luck as the program just starts and
exits without going through any of the code.
If anyone could help me with this it would be much appreciated. The code for
the program and the intended multi-threading is below.
from textblob.classifiers import NaiveBayesClassifier
import pymongo
import datetime
from threading import Thread
train = [
('I love this sandwich.', 'pos'),
('This is an amazing place!', 'pos'),
('I feel very good about these beers.', 'pos'),
('This is my best work.', 'pos'),
("What an awesome view", 'pos'),
('I do not like this restaurant', 'neg'),
('I am tired of this stuff.', 'neg'),
("I can't deal with this", 'neg'),
('He is my sworn enemy!', 'neg'),
('My boss is horrible.', 'neg'),
(':)', 'pos'),
(':(', 'neg'),
('gr8', 'pos'),
('gr8t', 'pos'),
('lol', 'pos'),
('bff', 'neg'),
]
test = [
'The beer was good.',
'I do not enjoy my job',
"I ain't feeling dandy today.",
"I feel amazing!",
'Gary is a friend of mine.',
"I can't believe I'm doing this.",
]
filterKeywords = ['IBM', 'Microsoft', 'Facebook', 'Yahoo', 'Apple', 'Google', 'Amazon', 'EBay', 'Diageo',
'General Motors', 'General Electric', 'Telefonica', 'Rolls Royce', 'Walmart', 'HSBC', 'BP',
'Investec', 'WWE', 'Time Warner', 'Santander Group']
# Create pos/neg counter variables for each company using dicts
vars = {}
for word in filterKeywords:
vars[word + "SentimentOverall"] = 0
# Initialising the classifier
cl = NaiveBayesClassifier(train)
class TrainingClassification():
def __init__(self):
#creating the mongodb connection
try:
conn = pymongo.MongoClient('localhost', 27017)
print "Connected successfully!!!"
global db
db = conn.TwitterDB
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB: %s" % e
thread1 = Thread(target=self.apple_thread, args=())
thread1.start()
thread1.join()
print "thread finished...exiting"
def apple_thread(self):
appleSentimentText = []
for record in db.Apple.find():
if record.get('created_at'):
created_at = record.get('created_at')
dt = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')
if record.get('text') and dt > datetime.today():
appleSentimentText.append(record.get("text"))
for targetText in appleSentimentText:
classificationApple = cl.classify(targetText)
if classificationApple == "pos":
vars["AppleSentimentOverall"] = vars["AppleSentimentOverall"] + 1
elif classificationApple == "neg":
vars["AppleSentimentOverall"] = vars["AppleSentimentOverall"] - 1
Answer: The main issue with your code is here:
thread1.start()
thread1.join()
when you call join on a thread, it has the effect of making the current
running thread (in your case, the main thread) wait until completion of the
thread (here, thread1). So you can see that your code will actually not be
faster. It just launches one thread and waits for it. It will actually be
marginally slower because of the thread creation.
Here's a proper way to do multithreading:
thread1.start()
thread2.start()
thread1.join()
thread2.join()
In this code, the threads 1 and 2 will both run in parallel.
IMPORTANT: Note that in Python, it is a "simulated" parallelisation. Because
Python's core is not thread safe (mainly because of the way it does garbage
collection), it uses the GIL (Global Interpreter Lock), and therefore all
threads in a process run on only 1 core. If you are keen on using real
parallelisation (for example if your 2 threads are CPU bounds rather than I/O
bounds), then look at the multiprocessing module.
|
Binomial iterated expectation in Cython
Question: I am brand new to Cython. How to convert the Python function called Values
below to Cython? With factors=2 and i=60 this takes 2.8 secs on my big Linux
box. The goal is sub 1 sec with factors=2 and i=360.
Here's the code. Thanks!
import numpy as np
import itertools
class Numeraire:
def __init__(self, rate):
self.rate = rate
def __call__(self, timenext, time, state):
return np.exp(-self.rate*(timenext - time))
def Values(values, i1, i0=0, numeraire=Numeraire(0.)):
factors=len(values.shape)
norm=0.5**factors
for i in np.arange(i1-1, i0-1, -1):
for j in itertools.product(np.arange(i+1), repeat=factors):
value = 0.
for k in itertools.product(np.arange(2), repeat=factors):
value += values[tuple(np.array(j) + np.array(k))]
values[j] = value*norm*numeraire(i+1, i, j)
return values
factors = 2
i = 60
values = np.ones([i+1]*factors)
Values(values, i, numeraire=Numeraire(0.05/12))
print values[(0,)*factors], np.exp(-0.05/12*i)
Answer: Before using Cython, you should optimize your code with Numpy. Here,
vectorizing the third and second inner `for` loops, yields a x40 speed-up,
In [1]: import numpy as np
...: import itertools
...:
...: # define Numaire and Values functions from the question above
...:
...: def Values2(values, i1, i0=0, numeraire=Numeraire(0.)):
...: factors=len(values.shape)
...: norm=0.5**factors
...: k = np.array(list(itertools.product(np.arange(2), repeat=factors)))
...: for i in np.arange(i1-1, i0-1, -1):
...: j = np.array(list(itertools.product(np.arange(i+1), repeat=factors)))
...: mask_all = j[:,:,np.newaxis] + k.T[np.newaxis, :, :]
...: mask_x, mask_y = np.swapaxes(mask_all, 2, 1).reshape(-1, 2).T
...:
...: values_tmp = values[mask_x, mask_y].reshape((j.shape[0], k.shape[0]))
...: values_tmp = values_tmp.sum(axis=1)
...: values[j[:,0], j[:,1]] = values_tmp*norm*numeraire(i+1, i, j)
...: return values
...:
...: factors = 2
...: i = 60
...: values = lambda : np.ones([i+1]*factors)
...: print values()[(0,)*factors], np.exp(-0.05/12*i)
...:
...: res = Values(values(), i, numeraire=Numeraire(0.05/12))
...: res2 = Values2(values(), i, numeraire=Numeraire(0.05/12))
...: np.testing.assert_allclose(res, res2)
...:
...: %timeit Values(values(), i, numeraire=Numeraire(0.05/12))
...: %timeit Values2(values(), i, numeraire=Numeraire(0.05/12))
...:
1.0 0.778800783071
1 loops, best of 3: 1.26 s per loop
10 loops, best of 3: 31.8 ms per loop
The next step would be to replace the line,
j = np.array(list(itertools.product(np.arange(i+1), repeat=factors)
with it's Numpy equivalent, taken from this
[answer](https://stackoverflow.com/a/4714857/1791279) (not very pretty),
def itertools_product_numpy(some_list, some_length):
return some_list[np.rollaxis(
np.indices((len(some_list),) * some_length), 0, some_length + 1)
.reshape(-1, some_length)]
k = itertools_product_numpy(np.arange(i+1), factors)
this result in an overall x160 speed up and the code runs in 1.2 second on my
laptop for `i=360` and `factors = 2`.
In this last version, I don't think that you will get much speed up, if you
port it to Cython, since there is just one loop remaining and it has only ~360
iterations. Rather, some fine-tunned Python/Numpy optimizations should be
performed to get a further speed increase.
Alternatively, you can try applying Cython to your original implementation.
However because it is based on `itertools.product`, which is slow when called
repeatedly in a loop, Cython will not help there.
|
Python Traceback Error
Question: Unable to create a response with this api.I am unable to call the function
locu_search('new york'). I get the following error shown below. I am using
Komodo as my IDE, this started when I created a new python shell.
import urllib2
import json
local_api = '0d5897aae41eeafbd62ad0815af15cc42b2ed7c0'
def locu_search(query):
api_key = local_api
url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key
locality = query.replace('','%20')
final_url = url + "&locality=" + locality + "&category=restaurant"
json_obj = urllib2.urlopen(final_url)
data = json.load(json_obj)
for item in data['objects']:
print item['name'],item['phone']
locu_search('new york')
The error is listed below:
**Traceback (most recent call last):
File "<console>", line 0, in <module>
File "<console>", line 0, in locu_search
File "c:\python27\lib\urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "c:\python27\lib\urllib2.py", line 437, in open
response = meth(req, response)
File "c:\python27\lib\urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "c:\python27\lib\urllib2.py", line 475, in error
return self._call_chain(*args)
File "c:\python27\lib\urllib2.py", line 409, in _call_chain
result = func(*args)
File "c:\python27\lib\urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: BAD_REQUEST**
Answer: 400 Bad Request should give you a headsup about the problem , this is
basically due to a malformed request and I strongly suspect the culprit is in
th line `url = 'https://api.locu.com/v1_0/venue/search/?api_key=' + api_key` ,
check if `api_key` token is invalid or no longer valid.
|
Popen not responding to kill
Question: Environment: Raspberry Pi Wheezy
I have a python program that uses Popen to call another python program
from subprocess import *
oJob = Popen('sudo python mypgm.py',shell=True)
Another menu option is supposed to end the job immediately
oJob.kill()
but the job is still running??
Answer: You need to add a creation flag arg
oJob = Popen('sudo python mypgm.py',shell=True, creationflags = subprocess.CREATE_NEW_PROCESS_GROUP)
[source](https://docs.python.org/2/library/subprocess.html#popen-objects)
> subprocess.CREATE_NEW_PROCESS_GROUP A Popen creationflags parameter to
> specify that a new process group will be created. This flag is necessary for
> using os.kill() on the subprocess.
**EDIT** I agree with the comment on how to import stuff and why you are
getting something is undefined. Also the other answer seems to be on the right
track getting the pid
import subprocess as sub
oJob = sub.Popen('sudo python mypgm.py', creationflags = sub.CREATE_NEW_PROCESS_GROUP)
oJob.kill()
> Warning Executing shell commands that incorporate unsanitized input from an
> untrusted source makes a program vulnerable to shell injection, a serious
> security flaw which can result in arbitrary command execution. For this
> reason, the use of `shell=True` is strongly discouraged in cases where the
> command string is constructed from external input:
|
Sum elements in a row (Python/Numpy)
Question: Working on a project that gives us free reign on what to use. So I decided I'd
learn python for it.
To make this short, I want sum all the elements in a "row" of a matrix I'm
reading in.
This is what my 2D array looks like after I read in my table from my text
file.
['0000' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '1']
['0001' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1']
['0010' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1']
['0011' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1']
['0100' '0' '0' '0' '0' '0' '1' '0' '1' '0' '0' '1' '0' '0' '1']
['0101' '0' '0' '1' '0' '0' '0' '1' '0' '0' '1' '0' '1' '1' '0']
['0110' '0' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '1' '1' '0']
['0111' '0' '0' '1' '0' '0' '0' '0' '0' '0' '1' '0' '0' '1' '0']
['1000' '0' '0' '0' '0' '0' '1' '0' '1' '0' '0' '1' '0' '0' '1']
['1001' '1' '0' '0' '0' '0' '0' '1' '0' '0' '1' '0' '1' '1' '0']
['1010' '1' '0' '0' '0' '1' '0' '0' '0' '0' '1' '0' '1' '1' '0']
['1011' '1' '0' '0' '0' '0' '0' '0' '0' '0' '1' '0' '0' '1' '0']
['1100' '0' '0' '0' '0' '0' '1' '0' '1' '0' '0' '1' '0' '0' '1']
['1101' '0' '0' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1' '1' '0']
['1110' '0' '0' '0' '0' '1' '0' '0' '0' '0' '0' '0' '1' '1' '0']
['1111' '0' '0' '0' '0' '0' '0' '0' '0' '0' '1' '0' '1' '1' '0']
I want to sum all elements of each row excluding index 0 (the 4 digit
numbers). And then store those sums in a list.
This is what my list of sums should look like:
[1, 4, 4, 4, 4, 4, 5, 5, 3,.......,3] (Imagine it was all filled with the right sums)
However, this is what my code outputs:
number of rows: 16
number of cols: 15
num1s before: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
num1s after : [3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 7, 9, 7]
I'm not sure what the error is, but I think it has to do with string/int
conversion. Since my table is in strings, but I convert it to ints for
summing. Debugging it shows the correct results, so I'm not sure where the
error is.
Here is my code:
import numpy
print ("Reading..")
txtfile = open("test1.txt", "r")
print(txtfile.readline())
txtfile.close()
r= numpy.genfromtxt('test1.txt',dtype=str,skiprows=1)
for x in range (0,len(r)):
print(r[x])
allTested = [0] * (len(r[0]) - 1)
num1s = [0] * (len(r[0]) - 1)
print("number of rows:", len(r))
print("number of cols:", len(r[0]))
print("num1s before:",num1s)
for x in range (0,len(r)):
for y in range(1,len(r[0])):
num1s[y-1] += int(r[x][y])
print("num1s after :",num1s)
Answer: Okay. Figured out the answer.
@wajid Farhani was close, but it wasn't working in my case.
His command for np.sum works, but I had to perform some indexing so I can
ignore index 0 of every row. My issue was that I thought indexing 2D array was
done by array[x][y], when it's array[x,y].
Fixed code:
import numpy
print ("Reading..")
txtfile = open("test1.txt", "r")
print(txtfile.readline())
txtfile.close()
r= numpy.genfromtxt('test1.txt',dtype=str,skiprows=1)
for x in range (0,len(r)):
print(r[x])
allTested = [0] * (len(r[0]) - 1)
num1s = [0] * (len(r))
print("number of rows:", len(r))
print("number of cols:", len(r[0]))
print("num1s before:",num1s)
array = numpy.array(r,dtype=int)
s = numpy.sum(array[0:len(array),1:len(array[0])],axis=1).tolist()
print("num1s after :",s)
Correct output:
num1s before: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
num1s after : [1, 4, 4, 4, 4, 5, 5, 3, 4, 5, 5, 3, 4, 3, 3, 3]
|
Sending a C++ array to Python and back (Extending C++ with Numpy)
Question: I am going to send a `c++` array to a python function as `numpy array` and get
back another `numpy array`. After consulting with `numpy` documentation and
some other threads and tweaking the code, finally the code is working but I
would like to know if this code is written optimally considering the:
* Unnecessary copying of the array between `c++` and `numpy (python)`.
* Correct dereferencing of the variables.
* Easy straight-forward approach.
C++ code:
// python_embed.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/arrayobject.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
import_array()
// Build the 2D array
PyObject *pArgs, *pReturn, *pModule, *pFunc;
PyArrayObject *np_ret, *np_arg;
const int SIZE{ 10 };
npy_intp dims[2]{SIZE, SIZE};
const int ND{ 2 };
long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
long double* c_out;
for (int i{}; i < SIZE; i++)
for (int j{}; j < SIZE; j++)
c_arr[i][j] = i * SIZE + j;
np_arg = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNewFromData(ND, dims, NPY_LONGDOUBLE,
reinterpret_cast<void*>(c_arr)));
// Calling array_tutorial from mymodule
PyObject *pName = PyUnicode_FromString("mymodule");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (!pModule){
cout << "mymodule can not be imported" << endl;
Py_DECREF(np_arg);
delete[] c_arr;
return 1;
}
pFunc = PyObject_GetAttrString(pModule, "array_tutorial");
if (!pFunc || !PyCallable_Check(pFunc)){
Py_DECREF(pModule);
Py_XDECREF(pFunc);
Py_DECREF(np_arg);
delete[] c_arr;
cout << "array_tutorial is null or not callable" << endl;
return 1;
}
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, reinterpret_cast<PyObject*>(np_arg));
pReturn = PyObject_CallObject(pFunc, pArgs);
np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
if (PyArray_NDIM(np_ret) != ND - 1){ // row[0] is returned
cout << "Function returned with wrong dimension" << endl;
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_DECREF(np_arg);
Py_DECREF(np_ret);
delete[] c_arr;
return 1;
}
int len{ PyArray_SHAPE(np_ret)[0] };
c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
cout << "Printing output array" << endl;
for (int i{}; i < len; i++)
cout << c_out[i] << ' ';
cout << endl;
// Finalizing
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_DECREF(np_arg);
Py_DECREF(np_ret);
delete[] c_arr;
Py_Finalize();
return 0;
}
In CodeReview, there is a fantastic answer:
[Link...](http://codereview.stackexchange.com/questions/92266/sending-a-c-
array-to-python-numpy-and-back/92353#92353)
Answer: From my experience that seems to be pretty efficient. To get even more
efficiency out of it try this :
<http://ubuntuforums.org/showthread.php?t=1266059>
Using weave you can inline C/C++ code in Python so that could be useful.
<http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.weave.inline.html>
Here's a link on how Python can be used to interface between many different
languages along with examples.
<http://docs.scipy.org/doc/numpy/user/c-info.python-as-glue.html>
This is a quick and easy example of how to pass numpy arrays to c++ using
Cython:
<http://blog.birving.com/2014/05/passing-numpy-arrays-between-python-and.html>
|
Re render content in angular
Question: I am using angular for front end and Python-Django as backend . I am rendering
an HTML in python using `TemplateResponse()` and this response is then sent to
angular as response where I store this in some `$scope variable` . The
important thing here is The HTML I am rendering in PYthon includes Css, Js ,
HTML + Angular code . e.g.,
<div ng-repeat='val in values'>
<span>{{ val }}</span>
</div>
Now Python will render this code (includes much more but this a sample) and
send response to angular (I'll also send this values data from python )where
I'll store this in $scope.
$scope.html_response = response sent from Python
$scope.values = values data from python (it will be a object so angular can loop over this easily )
I have everything in angular HTMl + Angular Scope which is used in HTML . Now
The main thing is how to bind them together so that HTML gets angular scope
and loop over the data. For this I am using angular directive .
**HTML :**
<div dynamic="html_response"></div>
**Angular directive :**
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
This directive is doing binding of angular scope with HTML for me .
Everything was working for me until I got one issue . AS I explained above I
am rendering HTML first then binding angular scope. But In one of my case (a
js slider) I need to render angular first then render HTML (js code) means
slider js must render after angular so that slider can already have data
available to show .
But I can't render angular data from python side first . I have to send HTML
response to angular whatever it includes .
Is their any other approach or something I can do at angular end so that I can
solve my issue .
Answer: One approach you can take is to separate the HTML/CSS/JS rendering from the
data itself.
You can achieve this by first generating the HTML/CSS/JS in Python and have
Angular then fetch the data (in JSON format?) needed for the JS slider from
the Django backend and render it. This means you would have 2 accesses to the
backend - one for the page itself and the other for the data required by the
page.
|
Sum of an array
Question: So in Python `sum([])` will yield 0, which is pretty important.
Whereas in ruby `[].reduce(:+)` will give nil, of course the ternary operator
isn't a replacement, because:
(my_complicated_mapping).empty? ? 0 : (my_complicated_mapping).reduce(:+)
Will call `my_complicated_mapping` twice. Therefore the obvious method is:
res = my_complicated_mapping
res = (res.empty? ? 0 : res.reduce(:+))
I think there must be a neater way to do this though.
Answer: With reduce you can specify the initial value as the first parameter e.g.
my_complicated_mapping.reduce(0, :+)
then if the list is empty you'll get 0 instead of `nil`. You can check the
different alternative ways of using `reduce` [here](http://ruby-
doc.org/core-2.2.0/Enumerable.html#method-i-reduce).
or if using a block for `reduce` it would be:
my_complicated_mapping.reduce(0) { |sum, n| sum + n }
i.e. a single parameter with with initial value and supplying your block.
It's important to understand _why_ `reduce` returns `nil` in the case of the
empty array: If you don't specify an explicit initial value for memo, then the
first element of the array is used as the initial value of memo, which of
course doesn't exist in the empty case.
|
How can we convert 01-01-2011 19:00 to weekdays like Mon ,Tue .. in python?
Question: I was working on a pandas dataframe where I had a column of datetime now I
haveto convert it into Weekdays.How can I do this?
Answer: There is a datetime module you may want to use.
[strptime and
strftime](http://www.tutorialspoint.com/python/time_strftime.htm) methods from
[datetime](https://docs.python.org/2/library/datetime.html) module:
In [1]: import datetime
In [4]: datetime.datetime.strptime('01-01-2011 19:00','%d-%m-%Y %H:%M').strftime('%A')
Out[4]: 'Saturday'
|
Port C++ class to PyQt
Question: I am trying to convert a Qt4 custom widget written in C++ to a Python 2.7
custom widget. However, I have not been able to figure out how
`QLabel(parent)` would be written in Python. This is the original C++ code
from the ".ccp" file:
DocumentWidget::DocumentWidget(QWidget *parent)
: QLabel(parent)
{
currentPage = -1;
setAlignment(Qt::AlignCenter);
}
The `QLabel(parent)` seems to be some sort of initializer list. I've tried
using multiple inheritance in Python in parallel, but this leads to the
following error: `Cannot create a consistent method resolution order (MRO) for
bases QLabel, QWidget`.
I'm trying to port the code instead of creating a wrapper for the C++ widget,
because I don't know C++ and think I will have to customize the widget further
in the future.
I'm not trained as a programmer and this is the first day I ran into C++, so
feel free to correct me even if I'm doing something silly. I will not feel
embarrassed.
Answer: The code defines a constructor for the `DocumentWidget` class, which inherits
`QLabel` and requires a `QWidget` as parent.
The equivalent PyQt code would be:
from PyQt4 import QtCore, QtGui
class DocumentWidget(QtGui.QLabel):
def __init__(self, parent):
super(DocumentWidget, self).__init__(parent)
# or QtGui.QLabel.__init__(self, parent)
self.currentPage = -1
self.setAlignment(QtCore.Qt.AlignCenter)
|
Matplotlib graph appearing as a Python list type
Question: The following code produces a graph:
import matplotlib
gr = matplotlib.pyplot.plot([1,2,3])

Now, if I check the type of this seemingly graph object:
type(gr)
The output is:
list
I was expecting it to be some sort of matplotlib graph object, but this comes
to be a native Python list. Can anyone explain why?
Answer: Well what is returned is a list of the lines that are plotted not the graph
object itself, see the
[docs](http://matplotlib.org/api/pyplot_api.html?highlight=.plot#matplotlib.pyplot.plot)
> Return value is a list of lines that were added.
in my case I see this as the object:
[<matplotlib.lines.Line2D at 0xb2f83c8>]
the type is a `list` and the contents are a `Line2D` object:
In [141]:
for e in l:
print(e)
Line2D(_line0)
The contents of the `Line2D` are the lines added to the plot:
In [146]:
l[0].get_data()
Out[146]:
(array([ 0., 1., 2.]), array([1, 2, 3]))
**EDIT**
If you want to access the `Figure` for saving, I personally write like this:
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.Figure() # do something with Figure here
|
Using Mozmill for testing Firefox addon
Question: I have a Mozilla Firefox addon and wanna test it. I've found Mozmill and wrote
the small Python script, which is just taking each Firefox version and run the
command like this:
mozmill --binary=C:\browsers\firefox\38.0.1\firefox.exe
--addon=C:\my_ext\ext
--test=C:\my_ext\tests\mozmill\
Here is the script `unit_test_runner_public.py`:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import check_output
import time
firefox_binary_path = 'C:\\browsers\\firefox\\'
ff_addon_location = 'C:\\my_ext\\ext'
tests_folder = 'C:\\my_ext\\tests\\mozmill\\'
ff_versions = ['38.0.1', '37.0.2', '36.0.4', '35.0.1', '34.0.5', '33.1.1',
'32.0.3', '31.0', '30.0', '29.0.1', '28.0', '27.0.1', '26.0',
'25.0.1', '24.0', '23.0.1', '22.0', '21.0', '20.0.1', '19.0.2',
'18.0.2', '17.0.1', '16.0.2', '15.0.1', '14.0.1', '13.0.1']
def build_ff_path(ff_version):
return "%s%s%s" % (firefox_binary_path, ff_version, "\\firefox.exe")
for item in ff_versions:
print "##### Started unit tests for Mozilla Firefox %s #####" % item
current_run = "mozmill --binary=%s --addon=%s --test=%s" % \
(build_ff_path(item), ff_addon_location, tests_folder)
test_run_result = check_output(current_run, shell=True)
print "##### Finished unit tests for Mozilla Firefox %s #####" % item
time.sleep(10)
So Mozmill is starting the browser, running the tests and then closing the
browser and doing it for each Firefox version starting from 38.0.1 to 13.0.1
The problem is, that almost each time it hangs on some random Firefox version.
So it opens the browser instance, run the tests, but then it's not closing the
browser and the Firefox window hangs for some time and then I see such
exception in the terminal:
##### Finished unit tests for Mozilla Firefox 16.0.2 #####
##### Started unit tests for Mozilla Firefox 15.0.1 #####
mozversion INFO | application_buildid: 20120905151427
mozversion INFO | application_changeset: 0b774a1067fe
mozversion INFO | application_display_name: Firefox
mozversion INFO | application_id: {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
mozversion INFO | application_name: Firefox
mozversion INFO | application_repository: http://hg.mozilla.org/releases/mozilla
-release
mozversion INFO | application_vendor: Mozilla
mozversion INFO | application_version: 15.0.1
mozversion INFO | platform_buildid: 20120905151427
mozversion INFO | platform_changeset: 0b774a1067fe
mozversion INFO | platform_repository: http://hg.mozilla.org/releases/mozilla-re
lease
mozversion INFO | platform_version: 15.0.1
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\mozmill\__init__.py", line 878, in run
mozmill.run(tests, self.options.restart)
File "C:\Python27\lib\site-packages\mozmill\__init__.py", line 473, in run
self.stop_runner()
File "C:\Python27\lib\site-packages\mozmill\__init__.py", line 595, in stop_ru
nner
raise Exception('client process shutdown unsuccessful')
Exception: client process shutdown unsuccessful
Traceback (most recent call last):
File "unit_test_runner_public.py", line 24, in <module>
test_run_result = check_output(current_run, shell=True)
File "C:\Python27\lib\subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'mozmill --binary=C:\browsers\firefox\15.
0.1\firefox.exe --addon=C:\my_ext\ext --test=C:\my_ext\tests\mozmill\' returned
non-zero exit status 1
C:\my_ext>
And every time it happens with the random version of Firefox, so there is no
pattern like issue with some specific Firefox version.
System details are:
* OS: Microsoft Windows 7 Enterprise SP1 x86
* Python: 2.7.9
* Mozmill: 2.0.10
And the output of pip list:
blessings (1.6)
jsbridge (3.0.3)
ManifestDestiny (0.5.7)
manifestparser (1.1)
mozcrash (0.14)
mozdevice (0.45)
mozfile (1.1)
mozinfo (0.7)
mozlog (2.11)
mozmill (2.0.10)
moznetwork (0.24)
mozprocess (0.22)
mozprofile (0.23)
mozrunner (5.35)
mozversion (1.0)
pip (1.5.6)
setuptools (7.0)
Does anyone had experience with such issues?
Answer: So, after posting a question on [Mozmill Developers Google
Groups](https://groups.google.com/forum/#!topic/mozmill-dev/6BdIJtoWVqw) \-
I've got an answer from [Henrik Skupin](https://github.com/whimboo), who is
responsible for Mozmill.
In short, they've also came across this issue, but Mozmill will be
discontinued soon - and it's better start using the new framework [firefox-ui-
tests](https://github.com/mozilla/firefox-ui-tests). Unfortunately it doesn't
have yet possibility to specify `--addon` like it was with Mozmill, but
[bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1168803) (feature request)
;) is already created - so most likely this functionality will be added in
future releases. Meanwhile, if you need to test Firefox addon, you can specify
`--profile` to already prebuilt Firefox profile with preinstalled addon in it.
|
Review Board Setup Issue - Target WSGI script cannot be loaded as Python module
Question: Complete Review Board set-up but getting following error on accessing Apache
web server, please suggest fix for the problem.
Error logs for Apache web server:
[Fri May 22 13:17:47.175095 2015] [core:notice] [pid 23324] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0
[Fri May 22 13:17:47.176057 2015] [suexec:notice] [pid 23324] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Fri May 22 13:17:47.216294 2015] [auth_digest:notice] [pid 23324] AH01757: generating secret for digest authentication ...
[Fri May 22 13:17:47.217002 2015] [lbmethod_heartbeat:notice] [pid 23324] AH02282: No slotmem from mod_heartmonitor
[Fri May 22 13:17:47.292938 2015] [mpm_prefork:notice] [pid 23324] AH00163: Apache/2.4.6 (Red Hat Enterprise Linux) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations
[Fri May 22 13:17:47.292972 2015] [core:notice] [pid 23324] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Fri May 22 13:18:04.915419 2015] [autoindex:error] [pid 23331] [client *.*.*.*:37923] AH01276: Cannot serve directory /var/www/code.development.com/htdocs/: No matching DirectoryIndex (index.html) found, and server-generated directory index forbidden by Options directive
[Fri May 22 13:18:24.855506 2015] [:error] [pid 23328] [client *.*.*.*:37924] mod_wsgi (pid=23328): Target WSGI script '/var/www/code.development.com/htdocs/reviewboard.wsgi' cannot be loaded as Python module.
[Fri May 22 13:18:24.855538 2015] [:error] [pid 23328] [client *.*.*.*:37924] mod_wsgi (pid=23328): Exception occurred processing WSGI script '/var/www/code.development.com/htdocs/reviewboard.wsgi'.
[Fri May 22 13:18:24.855561 2015] [:error] [pid 23328] [client *.*.*.*:37924] Traceback (most recent call last):
[Fri May 22 13:18:24.855577 2015] [:error] [pid 23328] [client *.*.*.*:37924] File "/var/www/code.development.com/htdocs/reviewboard.wsgi", line 3, in <module>
[Fri May 22 13:18:24.855625 2015] [:error] [pid 23328] [client *.*.*.*:37924] import pkg_resources
[Fri May 22 13:18:24.855636 2015] [:error] [pid 23328] [client *.*.*.*:37924] File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 3011, in <module>
[Fri May 22 13:18:24.856109 2015] [:error] [pid 23328] [client *.*.*.*:37924] parse_requirements(__requires__), Environment()
[Fri May 22 13:18:24.856121 2015] [:error] [pid 23328] [client *.*.*.*:37924] File "/usr/lib/python2.7/site-packages/pkg_resources.py", line 626, in resolve
[Fri May 22 13:18:24.856147 2015] [:error] [pid 23328] [client *.*.*.*:37924] raise DistributionNotFound(req)
[Fri May 22 13:18:24.856167 2015] [:error] [pid 23328] [client *.*.*.*:37924] DistributionNotFound: Whoosh>=2.6
Configuration:
# python --version
Python 2.7.5
# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.1 (Maipo)
# mysql --version
mysql Ver 14.14 Distrib 5.6.24, for Linux (x86_64) using EditLine wrapper
# memcached -h
memcached 1.4.15
Setup -> ReviewBoard + Mysql + Memcache + Apache Web Server(httpd service)
# pip freeze
alabaster==0.7.4
Babel==1.3
backports.ssl-match-hostname==3.4.0.2
chardet==2.0.1
cloud-init==0.7.6
configobj==4.7.2
decorator==3.4.0
Django==1.6.11
django-evolution==0.7.5
django-haystack==2.3.1
django-pipeline==1.3.24
django-storages==1.1.8
Djblets==0.8.18
docutils==0.12
ecdsa==0.13
ethtool==0.8
feedparser==5.1.3
flup==1.0.2
futures==2.1.6
iniparse==0.4
IPy==0.75
Jinja2==2.7.3
jsonpatch==1.2
jsonpointer==1.0
kitchen==1.1.1
lxml==3.2.1
M2Crypto==0.21.1
Markdown==2.4.1
MarkupSafe==0.23
mercurial==2.6.2
mimeparse==0.1.3
MySQL-python==1.2.3
nose==1.3.0
paramiko==1.15.2
pciutils==1.7.3
Pillow==2.0.0
pillowfight==0.2
policycoreutils-default-encoding==0.1
prettytable==0.7.2
psycopg2==2.5.1
pycrypto==2.6.1
pycurl==7.19.0
Pygments==2.0.2
pygobject==3.8.2
pygpgme==0.3
pyliblzma==0.5.3
pyOpenSSL==0.13.1
python-dateutil==1.5
python-dmidecode==3.10.13
python-memcached==1.54
python-mimeparse==0.1.4
pytz==2015.4
pyudev==0.15
pyxattr==0.5.1
PyYAML==3.10
recaptcha-client==1.0.6
requests==1.1.0
ReviewBoard==2.0.15
rhnlib==2.5.65
rhsm==1.13.10
seobject==0.1
sepolicy==1.1
six==1.7.3
snowballstemmer==1.2.0
Sphinx==1.3.1
sphinx-rtd-theme==0.1.8
urlgrabber==3.10
urllib3==1.5
Whoosh==2.7.0
yum-metadata-parser==1.1.4
Let me know if you need more information on complete set-up.
Answer: Main problem was with **DistributionNotFound: Whoosh>=2.6** , I had 2.7.0
installed, thus I uninstalled Whoosh package and installed 2.6.0 version which
solved the problem.
#pip uninstall Whoosh
#pip install Whoosh==2.6.0
|
How to block import of specific python package?
Question: I need to programmatically block import of a python package and all child
packages.
For example, I need to block loading of the package "foo" and also ensure that
all children of foo such as "foo.bar" cannot be imported.
How can this be achieved in python 2.x without restructuring my site packages
or PYTHONPATH?
For context, the intent is to programmatically avoid the risk of importing
proprietary code into GPL licensed code.
Answer: This might not fit your solution _exactly_ but you can simply mock out the
entire module so the module and all of it's submodules have no effect:
<https://pypi.python.org/pypi/mock>
|
Python sockets will not connect
Question: I'm trying to run a server and a client on two separate Windows 7 machines on
the same network using sockets in Python 2.7. First I'm just trying to get
them to connect before trying to do anything.
Currently my server is:
import socket
host = '0.0.0.0' #Also tried '', 'localhost', gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, 12345))
s.listen(5)
cs, addr = s.accept()
print "Connected."
My client is:
import socket
host = '127.0.0.1' #Also tried 'localhost', gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(host, 12345)
print "Connected."
The error I get is:
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
I've looked through lots of other questions but none of the answers solved my
problem. Any help is appreciated.
When I use the IP address of the server (10.0.63.40) as the host for the
client, I get
[Errno 10060] A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected host has
failed to respond
Answer: You are saying these are **two separate machines**. You cannot reach the one
machine from the other by connecting to `127.0.0.1` or `localhost`.
Listening on `0.0.0.0` is fine, this means that the listening socket is
reachable from all interfaces, including the local network.
However, for connecting to your server, you obviously need to use the IP
address (or hostname, if you have properly set up a local name server) of your
server machine in the local network.
Per your comment, the local IP address of your server machine is `10.0.63.40`.
That means you should end up calling `s.connect("10.0.63.40", 12345)`.
|
How can I pass a file from a python program to a perl script and then reopen it in python?
Question: I have a python program that opens and manipulates a file. It takes a file
with a single fasta entry (ex1) and splits it into a mulit-fasta file (ex2).
ex1:
>genome_fasta
ATCG.... (thousands of chars)
ex 2:
>genome_split_1
ATCG.... (300 chars)
>genome_split_2
GCTT.... (300 chars)
>genome_split_3
ATGG....(300 chars, etc.)
That is working fine. But now I want to get the penta-nucleotide frequencies
for each one of these fasta entries. I have a perl script that does this
nicely and formats the output how I want it.
How can I pass my file (ex2) to this perl script, run it and get my output
file, then pass the file back into my python script for further manipulation?
I have tried to understand the subprocess module because that seems like the
easiest idea (i.e. just run a subprocess on the terminal that runs the
./perl_script.pl), but can't figure it out.
Answer: You can use the popen method of the subprocess module.
from subprocess import Popen, PIPE
p = Popen(['perl', 'myscript.perl'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
output variable is then your text.
|
Error: Set not JSON Serializable while converting TSV File into JSON Format using Python
Question: I'm looking to convert a TSV File I have into JSON Format for mapping (google
fusion maps doesn't support mapping multiple objects in the same location so
I'm converting it to JSON format to try on Mapbox). Here's my TSV file if
you're curious:
<https://github.com/yongcho822/Movies-in-the-
park/blob/master/MovieParksGeocodeTest.tsv>
And here is my corresponding python code thus far:
import json
import csv
def create_map(datafile):
geo_map = {"type":"FeatureCollection"}
item_list = []
with open(datafile, 'r') as tsvfile:
reader = csv.DictReader(tsvfile, delimiter = '\t')
for i, line in enumerate(reader):
data = {}
data['type'] = 'Feature'
data['id'] = i
data['properties']={'title': line['Movie Title'],
'description': line['Amenities'],
'date': line['Date']}
data['name'] = {line['Location']}
data['geometry'] = {'type':'Point',
'coordinates':(line['Lat'], line['Lng'])}
item_list.append(data)
#print item_list
for point in item_list:
geo_map.setdefault('features', []).append(point)
print 'CHECKPOINT'
with open("thedamngeojson.geojson", 'w') as f:
f.write(json.dumps(geo_map))
create_map('MovieParksGeocodeTest.tsv')
It's throwing me an error at the end (after it prints CHECKPOINT), saying
> TypeError: set(['Edgebrook Park, Chicago ']) is not JSON serializable
I figure the last two lines is where the error is.. but what's wrong and how
do I fix it??
Answer: [JSON](http://www.json.org/) is designed to be a very simple, very portable
format; the only kinds of values it understands are strings, numbers,
booleans, null (like Python `None`), `object`s (like a Python `dict`) and
`array`s (like a Python `list`).
But at least one of the values in your dictionary is a `set`:
data['name'] = {line['Location']}
Since JSON doesn't have a `set` type, you get an error telling you that `set …
is not JSON serializable`.
If you don't actually _need_ this to be a `set` instead of a `list` (which you
probably don't—if it really only ever have one element, who cares which
collection type it is?), the easy answer is to change it to be a `list`:
data['name'] = [line['Location']]
(In fact, even when you _do_ need this to be a set during processing, you
usually don't need it to be a set during storage/interchange. If the consumer
of your file needs to use it as a set, it can always convert it back later.)
|
JSON SyntaxError: Unexpected end of input
Question: I have the following ajax call where I am passing the data in JSON format and
when this code gets executed I get the error shown below,I showed the
Console.log(data_cp) below and I validated it in <http://jsonlint.com/> and it
is a validated input?what am I missing here?how to fix this error?I looked at
other posts like [json parsing error syntax error unexpected end of
input](http://stackoverflow.com/questions/20827372/json-parsing-error-syntax-
error-unexpected-end-of-input) but couldnt figure out...
$.ajax({
dataType: "json",
type: "POST",
contentType: "application/json",//note the contentType defintion
url: "scripts/cherrypick.py",
data: JSON.stringify(data_cp),
//data: data_cp,
error : function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
},
success: function(message){
console.log("cherypick sucess");
}
Serverside python script:-
#!/usr/bin/python
import os
import sys
import json
print "Content-type: application/json\n\n"
...............
...............
def main():
result = {'success':'true','message':'The Command Completed Successfully'}
cherrypicklist = []
cherrypickfaillist = []
myjson = json.load(sys.stdin)
gerritlist = myjson['gerrits']
resource = r'buildserver'
buildlocation = r'cd /local/mnt/workspace/user/buildlocation ; '
for gerrit in gerritlist:
cmd = buildlocation
project,ref = fetchgerritproject(gerrit, connection=None)
proj_path = getprojectpath(project)
cmd += 'cd ' + proj_path + ' ;'
new_cmd = ' gknife am-or-cp ' + gerrit
pick_cmd = cmd + new_cmd
errorlist =''
errorlist = cherrypick(resource,pick_cmd)
if len(errorlist) <= 2:
cherrypicklist.append(gerrit)
else:
chk_cmd = cmd + ' git checkout -f'
connection = ssh_connect(resource)
errorlist = execute_command(connection,chk_cmd)
cherrypickfaillist.append(gerrit)
for gerrit in cherrypicklist:
cmd = buildlocation
project,ref = fetchgerritproject(gerrit, connection=None)
proj_path = getprojectpath(project)
cmd += ' cd ' + proj_path + ' ;'
errorlist = resetgerrit(resource,cmd)
errorlist = execute_command(connection,chk_cmd)
print json.dumps(result)
#return
if __name__ == "__main__":
main()
Error:-
SyntaxError: Unexpected end of input
Console.log(data_cp) output:-
{"gerrits":["1258565","1279604"]}
Answer: As per definition of error method from Jquery docs, you get error from server
side or if call is not successful.
So it means you are getting error from server. Check the server code.
**Definition of Error method from JQuery**
> error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
> function to be called if the request fails. The function receives three
> arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string
> describing the type of error that occurred and an optional exception object,
> if one occurred. Possible values for the second argument (besides null) are
> "timeout", "error", "abort", and "parsererror". When an HTTP error occurs,
> errorThrown receives the textual portion of the HTTP status, such as "Not
> Found" or "Internal Server Error." As of jQuery 1.5, the error setting can
> accept an array of functions. Each function will be called in turn. Note:
> This handler is not called for cross-domain script and cross-domain JSONP
> requests. This is an Ajax Event.
|
Python Django installing mysql: easy_install and pip errors
Question: Trying to `python manage.py syncdb` but it gives me an error. Similar to a lot
of other questions on here, but the solutions provided do not solve the error
after I install them.
My `settings.py` file inside my project directory
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'network',
'USER': 'root',
'PASSWORD': 'mypass',
'HOST': '', #EMPTY FOR LOCALHOST
'PORT': '3307', #Empty by default
}
}
I am using Windows 7, Python 3.4 (I heard was not compatible with install
MySQL-python so instead I downloaded mysqlclient 1.3.6).
When I ran `easy_install mysql-python` it results in
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
error: Setup script exited with error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\BIN\\cl.exe'
failed with exit status 2
Similarly it asks for config-win.h when running `pip install mysql-python`,
along with a scary error
Command "D:\Users\Python\python.EXE -c "import setuptools, tokenize;__file__='C:\\Users\\AppData\\Local\\T
emp\\pip-build-w7q9kjxi\\mysql-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('
\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\AppData\Local\Temp\pip-u982sugf-record\install-record.t
xt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\AppData\Local\Temp\pip-build
-w7q9kjxi\mysql-python
I'm pretty confused about this. The tutorial I've been looking at strays from
me here, and I have no idea what to do with a WHL of mysqlclient.
Things I've tried already:
* `easy_install Distribute` works but does not change anything
* `python manage.py syncdb` no module named 'MySQLdb'
* `apt-get install python-mysqldb` term 'apt-get' not recognized at all.
Please help with this beginner question, thanks for your time, if more info is
needed I'd be happy to provide.
Answer: Without Visual Studio, you'll need a [binary
installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python) for the
right Python version and architecture. The easiest is probably to get both 32-
and 64- bit packages for the installed Python version and install them both.
|
Python Requests set cookies in a non-random order
Question: I need to send cookies in a specific, not random order.
Python requests use a dictionary to manage cookies, so the predefined cookies
I set are always in a random order.
Also, the subsequent cookies from the session are placed randomly after the
predefined cookies.
import requests
s = requests.Session()
predefined_cookies = dict(cookie1='a', cookie2='b', cookie3='c')
r = s.get('http://eu.httpbin.org/cookies/set?k1=v1&k2=v2', cookies=predefined_cookies)
r = s.get('http://eu.httpbin.org/cookies/set?k3=v3&k4=v4', cookies=predefined_cookies)
Outcome:
cookie2=b; cookie1=a; cookie3=c; k2=v2; k1=v1
cookie2=b; cookie1=a; cookie3=c; k3=v3; k2=v2; k4=v4; k1=v1
Ideally, I'd like to send the predefined cookies in an order they're written,
but more importantly, I need to place a session cookie I want at a very end,
so for example place a k4=v4 cookie at the very end.
This doesn't have to be a session. I'd appreciate your input.
* [cookies documentation](http://docs.python-requests.org/en/latest/api/#cookies)
* [headers dict ordering](http://stackoverflow.com/a/29474948/4674587)
Answer: You can use
[`OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict),
from the [`collections`
module](https://docs.python.org/2/library/collections.html), to keep your data
in the order it was inserted.
>>> import collections
>>> d = collections.OrderedDict()
>>> d["cookie1"] = 'a'
>>> d["cookie2"] = 'b'
>>> d["cookie3"] = 'c'
You can check to see the data is in the right place:
>>> print(d)
OrderedDict([('cookie1', 'a'), ('cookie2', 'b'), ('cookie3', 'c')])
|
TypeError: 'Weather' object is not callable
Question: I'm very new to programming so please excuse me if I lack the correct
terminology.
I'm trying to retrieve an image from a website and post it onto a GUI with
tkinter. It works, insofar as it posts the image on the GUI; however it still
produces an error as per the title of this post.
The section of code that's causing the error is as follows:
raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
image = raw_data("img", ("class", "si"))[0]
image = image["src"]
if image == ("/images/icons/5.gif"):
URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
b64_data = base64.encodestring(URL)
image = PhotoImage(data = b64_data)
label = Label(self, image = image).grid(row = 1, column = 2)
self(image)
Narrowed down further it seems line 39 is causing the error.
self(image)
Full program as follows:
#!/usr/bin/env python
from tkinter import *
import sys
import urllib.request
from urllib.request import urlopen
import base64
from bs4 import BeautifulSoup
class Weather(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.configure(bg = "#ededed")
self.grid()
self.heading = Label(self, bg = "#ededed", text = " Temperature ").grid(row = 0, column = 1, pady = 5)
self.heading = Label(self, bg = "#ededed", text = " Picture ").grid(row = 0, column = 2, pady = 5)
button = Button(self, bg = "#ededed", text = "Canberra", command = self.canberra_data).grid(row = 3, column = 0, sticky = EW)
self.obsVar1 = StringVar()
label = Label(self, textvariable = self.obsVar1, bg = "#e5e5e5", fg = "#751974").grid(row = 1, column = 1)
self.obsVar1.set("")
def canberra_data(self):
soup = BeautifulSoup(urllib.request.urlopen("http://www.bom.gov.au/act/observations/canberra.shtml").read())
table = soup.find("table", {"id" : "tCANBERRA"}).tbody("tr", "rowleftcolumn")
for row in soup("th", {"id" : "obs-station-canberra"}):
for temp in soup("td", {"headers" : "obs-temp obs-station-canberra"}):
self.obsVar1.set(temp.text)
raw_data = BeautifulSoup(urllib.request.urlopen("http://www.weather.com.au/act/canberra").read())
image = raw_data("img", ("class", "si"))[0]
image = image["src"]
if image == ("/images/icons/5.gif"):
URL = urllib.request.urlopen("http://www.weather.com.au/images/icons/5.gif").read()
b64_data = base64.encodestring(URL)
image = PhotoImage(data = b64_data)
label = Label(self, image = image).grid(row = 1, column = 2)
self(image)
master = Tk()
master.title("Weather Program")
app = Weather(master)
master.mainloop()
I should add that if the website has updated its image and it's no longer
'5.gif' (being a weather icon it's highly likely) then a picture won't show
up.
Any help or direction would be much appreciated. I've looked high and low but
to no avail. Thank you in advance.
Answer: The line containing self(image) is not correct. The 'self' is not a class,
it's an object. So, if you want to create an object of type Weather and pass
something to its constructor, just call Weather(image).
|
python - is it possible to enter user-chosen input and output files
Question: I'm a newbie in python, so please bear with me.
I don't know how to describe,so I'll just show an example.
python CODE.py -i1 input1.txt -i2 input2.txt -o output.txt
Is such thing possible with python? I've looked up for a while but haven't
find an answer.
Thank you!
Answer: As [thefourtheye](http://stackoverflow.com/users/1903116/thefourtheye) said
you can used argparse module. But if you want simple solution, just pass 2
inputs and output file paths as arguments to your executable and use
`sys.argv` to get them in your program in order. The `sys.argv[0]` is your
application name, `sys.argv[1]` is first input file path, `sys.argv[2]` is
second input file path and `sys.argv[3]` is output file path.
import sys
input1 = sys.argv[1]
input2 = sys.argv[2]
output = sys.argv[3]
now you can call like below:
python my_app.py /path/to/input1.txt /path/to/input2.txt /path/to/output.txt
|
python install lxml on mac os 10.10.1
Question: I bought a new macbook and I am so new to mac os. However, I read a lot on
internet about how to install scrap
I did everything, but i have a problem with installing lxml
I tried this on terminal
pip install lxml
and a lot of stuff started to be downloading and many text was written on the
terminal, but i got this error message on red in the terminal
1 error generated.
error: command '/usr/bin/clang' failed with exit status 1
----------------------------------------
Cleaning up...
Command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -c "import setuptools, tokenize;__file__='/private/var/folders/rd/fxgsy46j3l77f6l9h_hv2fjm0000gn/T/pip_build_mycomputername/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/rd/fxgsy46j3l77f6l9h_hv2fjm0000gn/T/pip-WvDTPQ-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/rd/fxgsy46j3l77f6l9h_hv2fjm0000gn/T/pip_build_mycomputername/lxml
Storing debug log for failure in /Users/mycomputername/.pip/pip.log
and now when I call scrapy spider that words with lxml, i got this error
message
ImportError: No module named lxml.html
what should I do please?
any suggestion is appreciated
Answer: I had that problem, and what I did is:
installed all xcode (2.8GB) from apple store.
to be sure that the installation is successfully finished: open terminal and
typed
xcode-select -p
you should get something like this:
/Applications/Xcode.app/Contents/Developer
now you need to install command line tools. try to type `gcc` on the terminal,
then there are two possibilities: either you get a window asking to install
the tools and you have to click on `install`, or you will get an error
message.
if you get an error message, then don't worry just try to install the tools
using this command `xcode-select --install`
after that restart the mac and then re install lxml again like this :
pip install lxml
then try to run scrapy again
if you encounter any other error on any other library, easily just reinstall
scrapy using **easy_install** and **NOT** using pip
|
attribute error in python (code-skulpor)
Question: im trying to run the following code on codeskulptor. and its giving an error:
Line 17: AttributeError: 'card' object has no attribute 'rank'. y is this so?
import simplegui
ranks=('A','2','3','4','5','6','7','8','9','T','J','Q','K')
suits=('C','S','H','D')
card_centre=(36.5,49)
card_size=(73,98)
tiled_image=simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")
class card:
def _init_(self,suit,rank):
self.rank=rank
self.suit=suit
def draw(self,canvas,loc):
global ranks,suits
i=ranks.index(self.rank)
j=suits.index(self.suit)
card_pos=[card_centre[0]+i*card_size[0],card_centre[1]+j*card_size[1]]
canvas.draw_image(tiled_image,card_pos,card_size,loc,card_size)
def draw(canvas):
one_card.draw(canvas,[300,200])
frame=simplegui.create_frame("Card draw",600,400)
frame.set_draw_handler(draw)
one_card=card('H','J')
frame.start()
Answer: Not sure whether this really is the problem, but your `_init_` method should
look like this:
def __init__(self, suit, rank):
self.rank = rank
self.suit = suit
Note that it has two `__` instead of just one `_`. This will make it a
_constructor_ (instead of just some method that happens to be called
`_init_`), and only then it will actually be called when you create your
`card` instance with `one_card = card('H','J')` and only then the attributes
`self.rank` and `self.suit` will get initialized.
However, _if_ this is the problem, you should actually get another error even
before that, namely `TypeError: this constructor takes no arguments` because
there is no constructor defined that takes two parameters, but maybe your IDE
can statically (before actually running the program) recognize the one problem
but not the other.
|
fabric.api vs fabric.operations
Question: I am new to Python and Fabric, using Fabric==1.10.1 and Python 2.7.6. I don't
understand the difference between fabric.api and fabric.operations calls, both
seem to be doing the same thing. Which one should I use in fabfile? One thing
that I noticed is when I do `fabric.api.reboot()` then it does display
message,
[127.0.0.1] out: Broadcast message from [email protected]
[127.0.0.1] out:
[127.0.0.1] out: (/dev/pts/0) at 17:39 ...
[127.0.0.1] out:
[127.0.0.1] out:
[127.0.0.1] out:
[127.0.0.1] out:
[127.0.0.1] out: The system is going down for reboot NOW!
[127.0.0.1] out:
But when I use `fabric.operations.reboot()` it does not display any message.
Update: Actually seems `fabric.operations.reboot()` and `fabric.api.reboot()`
produce the message.
Answer: You can use either, but `fabric.api` is specifically the better option. This
is because it's where the other fabric modules are imported for simplicity's
sake. See here:
$ cat fabric/api.py (env: selenium)
"""
Non-init module for doing convenient * imports from.
Necessary because if we did this in __init__, one would be unable to import
anything else inside the package -- like, say, the version number used in
setup.py -- without triggering loads of most of the code. Which doesn't work so
well when you're using setup.py to install e.g. ssh!
"""
from fabric.context_managers import (cd, hide, settings, show, path, prefix,
lcd, quiet, warn_only, remote_tunnel, shell_env)
from fabric.decorators import (hosts, roles, runs_once, with_settings, task,
serial, parallel)
from fabric.operations import (require, prompt, put, get, run, sudo, local,
reboot, open_shell)
from fabric.state import env, output
from fabric.utils import abort, warn, puts, fastprint
from fabric.tasks import execute
`fabric.api` is importing `fabric.operations.reboot` for you already.
|
Create a thread using a class constructor as function
Question: I know that I can create and start a thread in Python using the following
syntax:
import threading
tracker_thread = threading.Thread(target=func, args=(x,y,z))
tracker_thread.daemon = True
tracker_thread.start()
What I need is to use a class constructor as `target`. I know that a solution
for this is the following:
def wrap_function(x,y,z):
MyClas(x,y,z)
tracker_thread = threading.Thread(target=wrap_function, args=(x,y,z))
But I am trying to avoid the use of a similar "wrap function", by using only
the constructor in the initialization of `Thread`.
How can I do this?
Answer: Solved. The simplest solution is always the best:
tracker_thread = threading.Thread(target=MyClass, args=(x,y,z))
Thanks to [Sir_FZ](http://stackoverflow.com/users/3572366/sir-fz) for the
comment.
|
Django - Save file to static directory from view
Question: I am building a website with Django, hosted on PythonAnywhere. One of the
website pages is a private page that I use to build content that will be then
displayed in the public pages. Rather than saving the content produced within
the private page to the database and then retrieving it from the database, I
would like to save it to static files, in my static directory (it's a small
number of JSON files that will be served over and over again, so I think it
makes sense to serve them as static files).
In the view that defines my private page I have the following code for saving
the file:
json=request.POST.get('json')
name=request.POST.get('name')
file=open(settings.STATIC_ROOT+'/'+name+'.json','w')
file.write(json)
file.close()
Note that I previously imported the settings:
from django.conf import settings
Strangely, this worked for a while, but then it stopped working. The error I
get is:
Exception Value: 'function' object has no attribute 'STATIC_ROOT'
Am I doing something wrong? Is the fact that I am on PythonAnywhere relevant?
Is it possible that the app is served by a worker that is not able to write to
my static directory? What can I do to solve the problem?
Answer: As pointed out by PythonAnywhere staff, the procedure was legitimate and
supposed to work because the app is served by a worker running as my own user
ID which has permissions to write to the static directory. The problem was
generated by a naming conflict due to the fact that also one of the views had
been named settings. To solve the problem I substituted the import statement
with
from django.conf import settings as djangoSettings
and the open statement with
file=open(djangoSettings.STATIC_ROOT+'/game'+name+'.json','w')
After doing these substitutions, everything seemed to work.
|
Sending multiple POST data in Python
Question: I have a Python code that sends POST request to a website, reads the response
and filters it. For the POST data I used ('number', '11111') and it works
perfect. However, I want to create a txt file that contains 100 different
numbers as 1111,2222,3333,4444... and then send the POST requests for each of
them. Can you help me how to do this in Python?
import urllib
from bs4 import BeautifulSoup
headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Origin': 'http://mahmutesat.com/python.aspx',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17',
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'http://mahmutesat.com/python.aspx',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}
class MyOpener(urllib.FancyURLopener):
version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'
myopener = MyOpener()
url = 'http://mahmutesat.com/python.aspx'
# first HTTP request without form data
f = myopener.open(url)
soup = BeautifulSoup(f)
# parse and retrieve two vital form values
viewstate = soup.select("#__VIEWSTATE")[0]['value']
eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value']
viewstategenerator = soup.select("#__VIEWSTATEGENERATOR")[0]['value']
formData = (
('__EVENTVALIDATION', eventvalidation),
('__VIEWSTATE', viewstate),
('__VIEWSTATEGENERATOR',viewstategenerator),
('number', '11111'),
('Button', 'Sorgula'),
)
encodedFields = urllib.urlencode(formData)
# second HTTP request with form data
f = myopener.open(url, encodedFields)
soup = BeautifulSoup(f.read())
name=soup.findAll('input',{'id':'name_field'})
for eachname in name:
print eachname['value']
Answer: 1 - Here is an example on how to create a file:
f = open('test.txt','w')
This will open the `test.txt` file for writing (`'w'`) (if it has already
data, it will be erased but if you want to append it write: `f =
open('test.txt','a')` ) or create one if it does not exist yet. Note that this
will happen in your current working directory, if you want it in a specific
directory, include with the file name the full directory path, example:
f = open('C:\\Python\\test.txt','w')
2 - Then write/append to this file the data you want, example:
for i in range(1,101):
f.write(str(i*1111)+'\n')
This will write 100 numbers as string from 1111 to 111100
3 - You should always close the file at the end:
f.close()
4 - Now if you want to read from this file '`test.txt`':
f = open('C:\\Python\\test.txt','r')
for i in f:
print i,
file.close()
This is as simple as it can be,
You need to read about File I/O in python from:
<https://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-
files>
Make sure you select the right Python version for you in this docs.
|
I'm getting a recursive error [RuntimeError: maximum recursion depth exceeded while calling a Python object] - but my code is iterative -- or is it?
Question: I'm getting a recursive error:
> RuntimeError: maximum recursion depth exceeded while calling a Python object
But my code is iterative...or is it? I thought it was, based on documentation
(here, for example: <http://www.pythonlearn.com/html-008/cfbook006.html>).
I've been reading on how to change an algorithm/code from recursive to
iterative (e.g., <http://blog.moertel.com/posts/2013-05-11-recursive-to-
iterative.html>) but I just don't see how it is recursive in the first place.
This code goes to a website, does a search and returns about 122 pages of
results. It then clicks through each results page and gathers the links. Then
it is meant to click on each link and scrape the text/html from each one.
The code runs beautifully until it gets to the final for loop: `for url in
article_urls:`. It will capture and store (on dropbox) just over 200 shtml
pages before it returns the error.
The puzzle I'm trying to solve is: how do I avoid getting this error?
Here is the code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
def isReady(browser):
return browser.execute_script("return document.readyState") == "complete"
def waitUntilReady(browser):
if not isReady(browser):
waitUntilReady(browser)
browser = webdriver.Firefox()
browser.get('http://www.usprwire.com/cgi-bin/news/search.cgi')
# make a search
query = WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.NAME, "query")))
query.send_keys('"test"')
submit = browser.find_element_by_xpath("//input[@value='Search']")
submit.click()
numarticles = 0
# grab article urls
npages = 1
article_urls = []
for page in range(1, npages + 1):
article_urls += [elm.get_attribute("href") for elm in browser.find_elements_by_class_name('category_links')]
if page <= 121: #click to the next page
browser.find_element_by_link_text('[>>]').click()
if page == 122: #last page in search results, so no '[>>]'' to click on. Move on to next steps.
continue
# iterate over urls and save the HTML source
for url in article_urls:
browser.get(url)
waitUntilReady(browser)
numarticles = numarticles+1
title = browser.current_url.split("/")[-1]
with open('/Users/My/Dropbox/File/Place/'+str(numarticles)+str(title), 'w') as fw:
fw.write(browser.page_source.encode('utf-8'))
Many thanks in advance for any input.
Answer: Obviously, your `waitUntilReady` goes into infinite recursion, calling itself.
You should change it to something like this:
while not isReady(browser):
time.sleep(1)
Waiting for page to completely load in Selenium is not as obvious as it seems,
you can read more in [Harry J.W. Percival's
article](http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-
page-load-after-a-click.html)
|
Python: parallelizing operations on a big array iteratively
Question: I am trying to parallelize operations on a big array. I summarized my approach
in the code snippet below. Since the operations on the big array are costly,
of the 100 processes, I want to parallelize 4 (i.e. n_cpus) at each iteration.
After an iteration is finished, some garbage collection will be done and the
next iteration should start. The main loop does the first iteration and
terminates. I will be glad if some parallel processing expert can point out
how I can correct my code to achieve the desired task.
from multiprocessing import Process
def train_model(model, big_array, i):
model = do_operations_on(big_array)
# edit: this part is within a class
n_processes = 100
n_cpus = 4
models = [None for _ in range(n_processes)]
n_iterations = n_processes / n_cpus
for it in range(n_iterations):
procs = [Process(target=train_model, \
args=(models[it*n_cpus+i], big_array, i)) for i in range(n_cpus)]
for p in procs: p.start()
for p in procs: p.join()
Answer: Your idea seems basically OK, except for a few problems:
* As RaJa pointed out, you should probably pass stuff using queues instead of using shared state
* I think your use of `multiprocessing.Process` is unnecessarily low level here; you should be using [`multiprocessing.Pool`](https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers), which would also be more efficient, as you can just reuse the processes (instead of keeping up setting them up and tearing them down).
* Your code has some mixup as your `train_model` ignores `model` and `i`, and just overwrites model.
So, in the following code, I assume you have something like
def train_model(specs, big_array):
return ...
that takes some `spec` specifics and data, and returns a model built for these
specifics.
I also assume in the following you have some array `specifics` containing all
the specifics you want to try (and also that it is divisible in the number of
cpus, which is not that difficult to get rid of).
Finally, I assume the point is to build a list `models` of all the models.
Your code becomes:
from multiprocessing import Pool
n_cpus = 4
n_iterations = len(specifics) / n_cpus
models = []
p = multiprocessing.Pool(n_cpus)
for it in range(n_iterations):
cur_specs = specifics[it * n_cpus: (it + 1) * n_cpu]
cur_models = p.map(lambda specs: train_model(specs, big_array), cur_specs)
models.extend(cur_models)
# Cleanup here
|
How to read a particular data format
Question: What shold I use in python 3 to read Json format?
Answer: To read in a some JSON data in a file:
from json import loads
with open("data.txt", "r") as f:
data = loads(f.read())
To get the first date in "items":
first_date = date["items"][0]["date"]
|
and operator with random
Question: i dont understand why the code bellow doesnt work properly. If both variables
a and b < 0 it should print that both numbers are negative,else the last
message. But it just dont work so, what am i doing wrong? please help!
import random
while True:
input()
a=random.randint(-9,9)
b=random.randint(-9,9)
print(a,b)
if a and b < 0:
print("2 negative numbers:",a,b)
else:
print("one or both of the numbers are positive!")
I'm running this on python 3.4.
Answer: Evaluating Both Operands will resolve the issue. Here both Operands are
expressions which results in true or false, so if both result in true; you
will get your required result.
if ((a < 0) and (b < 0)):
|
sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working?
Question: first i'd like to thanks everyone who can help me
i've been using a program that automated some boring features in a game i
like, but it's not working anymore.
the thing i want it to do is really stupid, but am not getting good results..
so
1) since i need to run it at a precise time i've found this in the forums and
tweaked a very little bit to set it to start around 11 am:
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day, hour=11, minute=0, second=20, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def something():
***Script below***
t = Timer(secs, something)
t.start()
so, is this first part correct ?
2) second part is the actual script, that something is actually something like
this:
for x in range (0, 50):
wait("im0.png"),25)
click("im0.png")
wait("im1.png",15)
if exists("im2.png"):
click("im2.png")
if exists("im3.png",50)
type("something")
x +=1
as you can see i set it to wait (or exists) an image for 25 (15 and 40)
seconds, but i have the feeling it's not waiting for that time i set it to, i
can't try the script often, but i think it tangles around the wait for image
commands, saying something like "FindFailed xxx.png" and so on
i'd like it to check every second if the image is present then do the action
below (cause it will appear, and i don't want it to skip anything), should i
change it in something like loops of "if not exists" then it checks itself
again? (input of this kind would be appreciated, am not so good at scripting
in python)
could anyone help me write it in a better/right way ?
Answer: There are more ways to Rome, so there is not 1 good answer but there are more.
If you would like to make a simple loop that does something at a given time
you could simply use:
import time
image1 = ("image1.png")
alarm = '17:37:00'
while (True):
# Look what time it is right now [24 hour format].
currentTime = time.strftime("%H:%M:%S")
if (currentTime == alarm):
print('It is time!')
# Exit the (while) loop.
break;
For the second part you could also make us of `while not exists()` To make it
more of a complete script you could use:
import time
image1 = ("image1.png")
image2 = ("image2.png")
image3 = ("image3.png")
alarm = '17:37:00'
class Robot():
# Automaticly executes when class is called.
def __init__(self):
# Wait until it is time for the alarm to go off.
while (True):
# Look what time it is right now [24 hour format].
currentTime = time.strftime("%H:%M:%S")
if (currentTime == alarm):
print('It is time!')
# Call another definition.
self.startWork()
# Exit the (while) loop to finsih the script.
break;
# Find and click the image.
def startWork(self):
while not exists(image1):
# We didn't see the image, sleep for 1 second.
wait(1)
# When the code gets here, image1 has appeared.
imageLoc1 = find(image1)
imageLoc1.click()
# Now we are going to look if we see eather image2 or image3
while not exists(image2) or not exists(image3):
wait(1)
# Image2 or image3 is seen.
if exists(image2):
imageLoc2 = find(image2)
imageLoc2.click()
elif exists(image3):
imageLoc3 = find(image3)
imageLoc3.click()
# Run class
Robot()
To make the loop `while not exists()` to also end after a certain time when
the image does not appear, you could use:
i = 0
while not exists(image1):
i = i + 1
wait(1)
# After 60 seconds break the loop anyway.
if (i == 60):
break
|
Python using a string (with variables) in lambda expression
Question: I want to use a string of a polynomial in a lambda expression, but I couldn't
figure out how to do it. It may not be possible, but if it is I'd love some
help!
An example of what I'm trying to do is:
f = lambda x: '3*x^3 + 2*x^2 -4*x +8'
Assume that I only have access to the polynomial in type str.
Is there something that removes the quotes or a version of eval that works
with variables?
Answer: Instead of a `lambda` you can use
[np.polyval](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyval.html)
from `numpy`
In [19]: import numpy as np
In [20]: np.polyval([3,2,-4,8],2)
Out[20]: 32
If you meant `4^x` then a quick fix
In [21]: np.polyval([3,2,0,-pow(4,2)+8],2)
Out[21]: 24
or with lambda
f=lambda mylist,x: sum((x**power) * coeff for power, coeff in enumerate(reversed(mylist)))
print f([3,2,-4,8],2)
|
Cant Add Shape (image)
Question: I am trying to add a image to my code but it keep raising the error
> Bad arguments for register_shape
I am following the tutorial at <http://blog.trinket.io/using-images-in-turtle-
programs/>
my code is:
import turtle
screen = turtle.Screen()
# click the image icon in the top right of the code window to see
# which images are available in this trinket
image = "C:\Users\--myName--\Desktop\Python\FinalPrj\rocketship.png"
# add the shape first then set the turtle shape
screen.addshape(image)
turtle.shape(image)
I am using python 2.6. furthermore when I use the function of
> screen.bgpic("C:\Users--
> myName--\Desktop\Python\FinalPrj\Space\images\Backgrounds\giphy2.gif")
The background works. Thanks in advance.
Answer: You may look for answers here: [How can i add an image
(Python)](http://stackoverflow.com/questions/30427742/how-can-i-add-an-image-
python)
> The turtle module does have support for images, but only GIF images, not PNG
> or any other format. As the docs for addshape say:
>
>> name is the name of a gif-file and shape is None: Install the corresponding
image shape.
|
Connecting to Google Datastore using gcloud
Question: I am trying to connect to my Google Datastore instance but I can't find any
sample code for how to initialize a connection!
Gcloud's main [documentation](https://googlecloudplatform.github.io/gcloud-
python/latest/datastore-api.html) immediately starts with how to assign an
Entity or a Query but skips the crucial connection bit. The demo section seems
specific to the demo in that it uses test environment variables which is quite
confusing.
Most importantly, I am interested in what environment variables I need to
define and if it is possible to define the service email and path to key from
within the python program.
Highly appreciate it if anyone can provide a sample code of how to commit
something to a datastore instance.
Thanks!
Answer: After looking around, I finally found the environment variables I need define.
To connect to your google datastore from within Python:
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = <path to private key>
os.environ['GCLOUD_DATASET_ID'] = <dataset_id, also known as project id>
# Fetching queries should work now
query = datastore.Query(kind=<kind>, namespace=<namespace>)
for result in query.fetch():
print result
Google assumes you are using App Engine with Datastore that is why it is
trickier to find these variables if you first introduction to Google Cloud is
its Datastore service.
|
python / kivy .kv file wont read
Question: I have just started learning to program I have a really basic App based on a
pong game tutorial on the kivy.org site but I must have a basic flaw that I
can't see as when I run the program all I am getting is a blank screen rather
than the expected canvas and labels. Please help me to waste less time on
basics!
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
class Singularity(Widget):
pass
class SingularityApp(App):
def build(self):
return Singularity()
if __name__ in ('__main__', '__android__'):
SingularityApp().run()
and the singularity.kv:
#:kivy 1.9.0
<Singularity>:
canvas:
Rectangle:
pos: self.center_x - 5, 0
size: 10, self.height
Label:
font_size: 70
center_x: root.width / 4
top: root.top - 50
text: "0"
Label:
font_size: 70
center_x: root.width * 3 / 4
top: root.top - 50
text: "0"
Answer: * Check whether your MainApp(App) class name is same as your .kv file name without the 'App' (if not make them same) It's not case sensitive. for example: MaNagerApp(App) will load manager.kv
**OR**
* If you don't want to change name then simply add self.load_kv(your_kv_file_name).
Like this:
def build(self):
self.load_kv('singularity.kv')
return Singularity()
|
xlsxwriter expected an indented block
Question: After spending some time to compile
[libxlsxwriter](http://libxlsxwriter.github.io/) as a dylib for osx without
success, I made the decision to switch to NSTask using the Python module
[XlsxWriter](http://xlsxwriter.readthedocs.org/). But another problem come
out: indentation! I want to achieve iteration through an array and put each
value in a row and column programmatically. However I am struggling with this
example from the docs:
import xlsxwriter.
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()
# Some data we want to write to the worksheet.
expenses = (
['Rent', 1000],
['Gas', 100],
['Food', 300],
['Gym', 50],
)
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0
# Iterate over the data and write it out row by row.
for item, cost in (expenses):
worksheet.write(row, col, item) #LINE 21 <---
worksheet.write(row, col + 1, cost)
row += 1
# Write a total using a formula.
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')
workbook.close()
OUTPUT
File "test.py", line 21
worksheet.write(row, col, item)
^
IndentationError: expected an indented block
Answer: XlsxWriter doesn't expect the block to be indented, Python does.
You will need to indent the code as shown in the original [example that the
code above was taken from](http://libxlsxwriter.github.io/tutorial01.html).
|
I've mangled Cython badly, it's performing worse than pure Python. Why?
Question: I'm rather new to Python and absolutely ignorant of C (unfortunately) so I am
struggling to properly understand some aspects of working with Cython.
After profiling a Python program and discovering that it was just a couple of
loops that were hogging most of the time, I decided to look into dumping them
into Cython. Initially, I just let Cython interpret the Python as it was, and
the result was a (remarkable!) ~2x speed boost. Cool!
From the Python main, I pass the function two 2-D arrays ("a" and "b") and a
float, "d", and it returns a list, "newlist". As examples:
a =[[12.7, 13.5, 1.0],[23.4, 43.1, 1.0],...]
b =[[0.46,0.95,0],[4.56,0.92,0],...]
d = 0.1
Here is the original code, with just the cdefs added for Cython:
def loop(a, b, d):
cdef int i, j
cdef double x, y
newlist = []
for i in range(len(a)):
if b[i][2] != 1:
for j in range(i+1,len(a)):
if a[i] == a[j] and b[j][2] != 1:
x = b[i][0]+b[j][0]
y = b[i][1]+b[j][1]
b[i][2],b[j][2] = 1,1
if abs(y)/abs(x) > d:
if y > 0: newlist.append([a[i][0],a[i][1],y])
return newlist
In "pure Python", this ran (with several ten-thousand loops) in ~12.5s. In
Cython it ran in ~6.3s. Great progress with near-zero work done!
However, with a little reading, it was clear that much, much more could be
done, so I set about trying to apply some type changes to get things going
even faster, following the Cython docs,
[here](http://docs.cython.org/src/tutorial/numpy.html "here") (also referenced
in the comments).
Here are the collected modifications, meant to mimic the Cython docs:
import numpy as np
cimport numpy as np
DtypeA = np.float
DtypeB = np.int
ctypedef np.float_t DtypeA_t
ctypedef np.int_t DtypeB_t
def loop(np.ndarray[DtypeA_t, ndim=2] A,
np.ndarray[DtypeA_t, ndim=2] B,
np.ndarray[DtypeB_t, ndim=1] C,
float D):
cdef Py_ssize_t i, j
cdef float x, y
cdef np.ndarray[DtypeA_t, ndim=2] NEW_ARRAY = np.zeros((len(C),3), dtype=DtypeA)
for i in range(len(C)):
if C[i] != 1:
for j in range(i+1,len(C)):
if A[i][0]==A[j][0] and A[i][1]==A[j][1] and C[j]!= 1:
x = B[i][0]+B[j][0]
y = B[i][1]+B[j][1]
C[i],C[j] = 1,1
if abs(y)/abs(x) > D:
if y > 0: NEW_ARRAY[i]=([A[i][0],A[i][1],y])
return NEW_ARRAY
Among other things, I split the previous array "b" into two different input
arrays "B" and "C", because each row of "b" contained 2 float elements and an
integer that just acted as a flag. So I removed the flag integers and put them
in a separate 1-D array, "C". So, the inputs now looked liked this:
A =[[12.7, 13.5, 1.0],[23.4, 43.1, 1.0],...]
B =[[0.46,0.95],[4.56,0.92],...]
C =[0,0,...]
D = 0.1
Ideally, this should go much faster with all the variables now being
typed(?)...but obviously I'm doing something very wrong, because the function
now comes in at a time of 35.3s...way WORSE than the "pure Python"!!
What am I botching so badly? Thanks for reading!
Answer: I believe the use of the indexing notation `b[j][0]` may be throwing Cython
off, making it impossible for it to use fast indexing operations behind the
scenes. Incidentally, even in pure Python code this style is not idiomatic and
may lead to slower code.
Try instead to use the notation `b[j,0]` throughout and see if it improves
your performance.
|
Python Tkinter shown before rest of program executed
Question: I'm working on creating a Launcher/updater for my small scale game I'm
building. I have the program create the gui then have it auto start
downloading the version file to check if it needs to be updated. Sadly the
gui, which is made using Tkinter, won't show till after the file is
downloaded. Is there a way to have the file download after the gui shows up?
"""
Programmer: JR Padfield
Description: Downloads file/s from a web server
Version: 1
Date: 05/16/15
"""
import urllib2
import ConfigParser
import os
import hashlib
from Tkinter import *
import ttk
from PIL import Image, ImageTk
class Launcher(Frame):
""" Main class for the launcher """
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.parent.title("The World Launcher")
self.pack(fill=BOTH, expand=1)
# create a lists for the.py checksum
self.pymd5 = []
self.pymd5fromini = []
# create a list for the graphics checksum
self.graphicsmd5 = []
self.graphicsmd5fromini = []
self.initUI()
def initUI(self):
""" Intializes the gui interface. """
self.image = Image.open('azurekite.jpg')
self.tkimage = ImageTk.PhotoImage(self.image)
canvas = Canvas(self, width=self.image.size[0]+20,
height=self.image.size[1]+20)
canvas.create_image(0, 0, anchor='nw', image=self.tkimage)
canvas.pack(fill=BOTH, expand=1)
self.playButton = Button(self, text="Play The World", command=self.play)
self.playButton.place(x=900, y=725)
self.forumButton = Button(self, text="Check Forums", command=self.forums)
self.forumButton.place(x=780, y=725)
self.newsText = Text(self, height=20, width=40)
self.newsText.place(x=10, y=10)
self.newsText.insert(END, "News Text goes here")
self.newsText.config(state=DISABLED)
self.updateLabel = Label(self, text="Starting Update Checks...")
self.updateLabel.place(x=50, y=680)
self.updateBar = ttk.Progressbar(self, orient='horizontal', length=400, mode="determinate")
self.updateBar.place(x=50, y=700)
self.updateBar["value"] = 0
# calls the first check to get things rolling
#self.startCheck()
def play(self):
""" Closes the launcher and plays the game """
def forums(self):
""" Launches the forums """
def startCheck(self):
self.updateLabel.config(text="Downloading news and version files")
try:
url = "http://removedrealurl.net/game/updates/version.ini"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
file_name = url.split('/')[-1]
print(file_name)
req = urllib2.Request(url, headers=hdr)
u = urllib2.urlopen(req)
print("opened url")
f = open(file_name, "wb")
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
self.updateBar["maximum"] = file_size
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status += chr(8) * (len(status) + 1)
self.updateBar["value"] = file_size_dl
print status
f.close()
except urllib2.HTTPError, e:
print(e)
self.updateLabel.config(text="Reading Version file....")
config = ConfigParser.ConfigParser()
config.read("version.ini")
gameweb = config.get('UPDATER', 'GameWebsite')
updateurl = config.get('UPDATER', 'updateURL')
versionNum = config.get('UPDATER', 'GameWebsite')
# # get the pyfiles check sum values.
# pycount = config.get('PYFILES', 'COUNT')
#
# for i in range(pycount):
# self.pymd5fromini.append(config.get('PYFILES', 'pyfile' + i))
#
# # get the graphics check sum
# gcount = config.getint('GRAPHICS', 'COUNT')
#
# for i in range(gcount):
# self.graphicsmd5fromini.append(config.get('GRAPHICS', 'graphic' + i))
os.rename("version.ini", "oldVersion.ini")
def checksum(self):
self.updateLabel.config(text="Checking local files....")
""" Checks all files to see if they have been changed. """
for file in os.listdir('/TW'):
if file.endswith('.py'):
# check the md5. open the file to check the contents.
with open(file) as checkFile:
data = checkFile.read()
md5 = hashlib.md5(data).hexdigest()
self.pymd5.append(md5)
self.updateLabel.config(text="Checking local graphics....")
for file in os.listdir('/data/gui'):
if file.endswith('.png'):
# check the md5. open the file to check the contents.
with open(file) as checkFile:
data = checkFile.read()
md5 = hashlib.md5(data).hexdigest()
self.graphicsmd5.append(md5)
for file in os.listdir('/data/items'):
if file.endswith('.png'):
# check the md5. open the file to check the contents.
with open(file) as checkFile:
data = checkFile.read()
md5 = hashlib.md5(data).hexdigest()
self.graphicsmd5.append(md5)
for file in os.listdir('/data/sprites'):
if file.endswith('.png'):
# check the md5. open the file to check the contents.
with open(file) as checkFile:
data = checkFile.read()
md5 = hashlib.md5(data).hexdigest()
self.graphicsmd5.append(md5)
for file in os.listdir('/data/tilesets'):
if file.endswith('.png'):
# check the md5. open the file to check the contents.
with open(file) as checkFile:
data = checkFile.read()
md5 = hashlib.md5(data).hexdigest()
self.graphicsmd5.append(md5)
def main():
""" Launches the program """
root = Tk()
root.geometry('1024x768')
app = Launcher(root)
root.mainloop()
if __name__ == '__main__':
main()
Answer: I figured out if you throw in self.parent.update() before calling the file
download call the gui will show up before executing the file download def.
|
Issue in deploying django application
Question: I am getting "Internal Server Error" when I try to access the django website.
I am using Django 1.8, Python 2.7.10, centos 6.5 and apache.
In apache log I am getting the following error:
mod_wsgi (pid=23866): Target WSGI script '/abc/abc/abc/wsgi.py' cannot be loaded as Python module.
[Mon May 25 14:40:47 2015] [error] [client xyz] mod_wsgi (pid=23866): Exception occurred processing WSGI script '/abc/abc/abc/wsgi.py'.
[Mon May 25 14:40:47 2015] [error] [client xyz] Traceback (most recent call last):
[Mon May 25 14:40:47 2015] [error] [client xyz] File "/abc/abc/abc/wsgi.py", line 12, in <module>
[Mon May 25 14:40:47 2015] [error] [client xyz] from django.core.wsgi import get_wsgi_application
[Mon May 25 14:40:47 2015] [error] [client xyz] File "/abc/lib/python2.7/site-packages/django/__init__.py", line 1, in <module>
[Mon May 25 14:40:47 2015] [error] [client xyz] from django.utils.version import get_version
[Mon May 25 14:40:47 2015] [error] [client xyz] File "/abc/lib/python2.7/site-packages/django/utils/version.py", line 7, in <module>
[Mon May 25 14:40:47 2015] [error] [client xyz] from django.utils.lru_cache import lru_cache
[Mon May 25 14:40:47 2015] [error] [client xyz] File "/abc/lib/python2.7/site-packages/django/utils/lru_cache.py", line 28
[Mon May 25 14:40:47 2015] [error] [client xyz] fasttypes = {int, str, frozenset, type(None)},
[Mon May 25 14:40:47 2015] [error] [client xyz] ^
[Mon May 25 14:40:47 2015] [error] [client xyz] SyntaxError: invalid syntax
Thanks
Answer: Although you say you are running Python 2.7, this error indicates that in fact
you are using 2.6, as set literals were only introduced in 2.7.
The issue is that mod_wsgi is compiled against a specific Python version,
which in your case is the one that comes with Centos 6.5. You will need to
recompile it for 2.7, or find a version already compiled against that.
|
Tkinter GUI and reading serial
Question: I am new to python and tkinter... I am using Tkinter to display a gauge and
receive the info through serial com. I have my GUI ready and now need to read
the serial values.
The problem I am facing is that I am not being able to read continuously the
serial COM. I came across `self.after`, but it still does not work. Basically
it does not display any value on the console. Any idea what might be wrong?
This is the main code. I have another file meter.py that has the gauge design
import tkinter as tk
import meter as m
import serial
class Mainframe(tk.Frame):
def __init__(self,master,*args,**kwargs):
super(Mainframe,self).__init__(master,*args,**kwargs)
self.meter = m.Meter(self,height = 400,width = 400)
self.meter.setrange(20,90)
self.meter.pack()
tk.Scale(self,width = 15 ,from_ = 20, to = 90
,orient = tk.HORIZONTAL
,command = self.setmeter).pack()
tk.Button(self,text = 'Quit',width = 15,command = master.destroy).pack()
tk.Button(self,text = 'Zoom',width = 15).pack()
def setmeter(self,value):
value = int(value)
self.meter.set(value)
class App(tk.Tk):
def __init__(self):
super(App,self).__init__()
self.title('Try Meter')
Mainframe(self).pack()
def serie():
ser = serial.Serial('COM2', 2400, timeout=1)
line = ser.readline() # read a '\n' terminated line
print (line)
self.after(100,serie)
App().mainloop()
Answer: The reason why your code doesn't work as expected is that you never call the
`serie()` method of the `App` class. If you modify your code to add this call,
perhaps at the end of the `__init__()` method, you should see serial data
being printed to the console.
However, handling serial IO and the user interface in the same thread isn't a
good idea. If there isn't any data to read from the serial port, `readline()`
will block for up to 1 second (the timeout value you set when you initialised
the serial port). This will block the tk main loop, and your user interface
will be completely unresponsive. In my opinion, the best way to fix this would
be to use one of the asynchronous IO libraries. I like
[Twisted](http://twistedmatrix.com/trac/) as it has built-in support for tk
([example](http://twistedmatrix.com/documents/13.2.0/core/howto/choosing-
reactor.html#auto16)) and serial communication, but there are several other
options. If this feels like overkill, you could also move the serial polling
code to its own thread or process using the `threading` or `multiprocessing`
modules respectively.
# Update
To answer the second part of your question:
In `readSerial()` you create a new instance of `Mainframe()`, but I think what
you actually want to do is use the instance you created in the `__init__()`
method of the `App` class. You'll need to store this as an attribute, using
code like `self.main_frame = Mainframe(self)`, then in `readSerial()` you can
access it using `root.main_frame.setmeter(50)`.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.