title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to create unittests for python prompt toolkit? | 38,975,025 | <p>I want to create unittests for my command line interface
build with the Python <code>prompt-toolkit</code> (<a href="https://github.com/jonathanslenders/python-prompt-toolkit">https://github.com/jonathanslenders/python-prompt-toolkit</a>).</p>
<ul>
<li><strong>How can I emulate user interaction with the prompt-toolkit?</strong> </li>
<li><strong>Is there a best practice for these unittests?</strong></li>
</ul>
<p>Example Code:</p>
<pre><code>from os import path
from prompt_toolkit import prompt
def csv():
csv_path = prompt('\nselect csv> ')
full_path = path.abspath(csv_path)
return full_path
</code></pre>
| 9 | 2016-08-16T12:30:33Z | 39,049,257 | <p>You could <a href="https://pypi.python.org/pypi/mock">mock</a> the prompt calls.</p>
<p><strong>app_file</strong></p>
<pre><code>from prompt_toolkit import prompt
def word():
result = prompt('type a word')
return result
</code></pre>
<p><strong>test_app_file</strong></p>
<pre><code>import unittest
from app import word
from mock import patch
class TestAnswer(unittest.TestCase):
def test_yes(self):
with patch('app.prompt', return_value='Python') as prompt:
self.assertEqual(word(), 'Python')
prompt.assert_called_once_with('type a word')
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Just an attention to the point you should mock the prompt from the <strong>app.py</strong>, not from <strong>prompt_toolkit</strong>, because you want to intercept the call from the file.</p>
<p>According with the <a href="https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/shortcuts.py#L4-L7">docstring module</a>:</p>
<blockquote>
<p>If you are using this library for retrieving some input from the user (as a
pure Python replacement for GNU readline), probably for 90% of the use cases,
the :func:<code>.prompt</code> function is all you need.</p>
</blockquote>
<p>And as <a href="https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/shortcuts.py#L512-L515">method docstring</a> says:</p>
<blockquote>
<p>Get input from the user and return it.
This is a wrapper around a lot of <code>prompt_toolkit</code> functionality and can be a replacement for <code>raw_input</code>. (or GNU readline.)</p>
</blockquote>
<p>Following the <a href="https://github.com/jonathanslenders/python-prompt-toolkit#getting-started">Getting started</a> from project:</p>
<pre><code>>>> from prompt_toolkit import prompt
>>> answer = prompt('Give me some input: ')
Give me some input: Hello World
>>> print(answer)
'Hello World'
>>> type(answer)
<class 'str'>
</code></pre>
<p>As <code>prompt</code> method return a string type, you could use <code>mock.return_value</code> to simulate the user integration with your app.</p>
| 7 | 2016-08-20T00:13:07Z | [
"python",
"python-3.x"
] |
Python - Matrix IndexError exception not working | 38,975,148 | <p>I am trying to write a function which enables a move 1 unit to the left (in the x-axis) in a grid. It should only work if there is a valid coordinate to the left, and if not (i.e. the start point is on the edge of the grid), the function should return <code>None</code>. Here is my attempt:</p>
<pre><code>def left_move(point):
try:
LEFT = grid[point[1]][point[0]-1]
except IndexError:
return None
if LEFT == '.':
change = [-1,0]
for idx, amount in enumerate(change):
point[idx]+=amount
return point
return None
</code></pre>
<p>Say the starting point is <code>[0,3]</code> and therefore on the edge of the grid and I only run the top part of the code:</p>
<pre><code>def left_move(point):
try:
LEFT = grid[point[1]][point[0]-1]
except IndexError:
return None
</code></pre>
<p>It returns <code>None</code> as expected. But if the whole block is executed it returns <code>[-1,3]</code> which is outside of the grid and shouldn't be allowed by the <code>try-except</code> . Why is this? And how can it be corrected? </p>
| 1 | 2016-08-16T12:37:31Z | 38,975,256 | <p>Here, you need to place the rest of the code inside the try statement. Otherwise, it will try, fail, and then run the rest of the code. </p>
<pre><code>def left_move(point):
if point[0]-1 != -1:
LEFT = grid[point[1]][point[0]-1]
if LEFT == '.':
change = [-1,0]
for idx, amount in enumerate(change):
point[idx]+=amount
return point
return None
else:
return None
</code></pre>
| 2 | 2016-08-16T12:42:13Z | [
"python",
"matrix",
"indexing"
] |
Python - Matrix IndexError exception not working | 38,975,148 | <p>I am trying to write a function which enables a move 1 unit to the left (in the x-axis) in a grid. It should only work if there is a valid coordinate to the left, and if not (i.e. the start point is on the edge of the grid), the function should return <code>None</code>. Here is my attempt:</p>
<pre><code>def left_move(point):
try:
LEFT = grid[point[1]][point[0]-1]
except IndexError:
return None
if LEFT == '.':
change = [-1,0]
for idx, amount in enumerate(change):
point[idx]+=amount
return point
return None
</code></pre>
<p>Say the starting point is <code>[0,3]</code> and therefore on the edge of the grid and I only run the top part of the code:</p>
<pre><code>def left_move(point):
try:
LEFT = grid[point[1]][point[0]-1]
except IndexError:
return None
</code></pre>
<p>It returns <code>None</code> as expected. But if the whole block is executed it returns <code>[-1,3]</code> which is outside of the grid and shouldn't be allowed by the <code>try-except</code> . Why is this? And how can it be corrected? </p>
| 1 | 2016-08-16T12:37:31Z | 38,975,311 | <p>This is because Python's interpretation of <code>-1</code> in array indexing is the last element of the array. <code>-1</code> is a legal way of referencing array elements and thus will not trigger an <code>IndexError</code> exception.</p>
<pre><code>>>> a = [0,1,2]
>>> print a[-1]
2
</code></pre>
<p>You would need to manually check if the value you are given resolves to <code>-1</code> and then handle that accordingly.</p>
| 2 | 2016-08-16T12:45:01Z | [
"python",
"matrix",
"indexing"
] |
Unable to copy using shutil | 38,975,164 | <p>I am using shutil.copy() to copy file form a location(say a/b/c/d/file.txt) to another location(e/f/g/h). But the problem is the command copies the file to location(i.e e/f/g/h) but the 'file.txt' is empty. I am working on a linux machine which is the slave for my jenkins, so I can't directly access the machine. Please help</p>
| -1 | 2016-08-16T12:38:15Z | 38,975,418 | <p>shutil.copy(src, dst, *, follow_symlinks=True)
Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.</p>
<p>If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to.</p>
<p>copy() copies the file data and the fileâs permission mode (see os.chmod()). Other metadata, like the fileâs creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead.</p>
| 0 | 2016-08-16T12:49:40Z | [
"python",
"linux"
] |
I am getting error when printing the pixel value of the read image in python-opencv, TypeError: 'NoneType' object has no attribute '__getitem__' | 38,975,230 | <p>I have freshly installed opencv, and checked that its properly installed by typing:
pkg-config --modversion opencv at the command terminal.</p>
<p>I started using pything-opencv for reading and displaying an image, but when I run my code, it throws an error:
TypeError: 'NoneType' object has no attribute '<strong>getitem</strong>'</p>
<p>My code is very minimal, but not getting where is there error.</p>
<p>The code which I am running is:
import cv2
import numpy as np
from matplotlib import pyplot as plt
import argparse</p>
<p>img = cv2.imread('messi5.jpg')
print img<br>
print "end of file"</p>
<p>It gives the output:
None
end of file</p>
<p>When I write two more lines as this:
px = img[100,100]
print px</p>
<p>then it throws error:
Traceback (most recent call last):
File "testing_opencv_python.py", line 23, in
px = img[100,100]
TypeError: 'NoneType' object has no attribute '<strong>getitem</strong>'</p>
<p>The same code runs perfectly on other systems.</p>
<p>I would be thankful if you can point out the mistake.</p>
<p>I basically want to install caffe, but when i did that i was getting error, and seems like it depends on opencv, thats whey I have installed opencv.</p>
<p>Thanks and regards.</p>
| 0 | 2016-08-16T12:41:02Z | 38,975,278 | <p>The returned image is <code>None</code> (you can see it when you print it), which is causing the other error down the line.</p>
<p>This is most likely due to specifying the wrong image path ('messi5.jpg'). In the the documentation <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html" rel="nofollow">here</a>, it states:</p>
<blockquote>
<p>Warning Even if the image path is wrong, it wonât throw any error, but print img will give you None</p>
</blockquote>
<p>Either provide a correct path to 'messi5.jpg', or copy the image into your current directory (where you execute the python script).</p>
| 0 | 2016-08-16T12:43:31Z | [
"python",
"opencv",
"caffe",
"nonetype"
] |
provide a mask to pandas dataframe as function argument | 38,975,246 | <p>I would like to use a mask as a function argument. What works:</p>
<pre><code>data = pd.DataFrame([[50, 100, 1], [0, 2, 1]], columns=['a', 'b', 'c'])
# the function argument
kwargs = {'a': 0, 'b': 2, 'c':1}
# generate a list of the elements
temp = []
for item in kwargs.items():
temp.append('(data.{}'.format(item[0]) + ' == {})'.format(item[1]))
temp
# generate mask as string
mask = ' & '.join(elem for elem in temp)
# apply mask
data[eval(mask)]
</code></pre>
<p>I was wondering if</p>
<p>a) there is a more elegant solution ?</p>
<p>b) does the <code>èval(mask)</code> potentially cause troubles if the size of the dataframe gets larger ?</p>
| 1 | 2016-08-16T12:41:49Z | 38,978,716 | <p>The following should work.</p>
<pre><code>data[pd.DataFrame(data[k] == v for k, v in kwargs.items()).all()]
</code></pre>
<p>Using a generator comprehension, it creates a DataFrame of <code>bool</code>s for whether or not the <code>data</code> value is equivalent to the <code>kwargs</code> value. It calls <code>.all()</code> on this dataframe, and uses that as the mask.</p>
<p><code>eval</code> is strongly discouraged for use in most code - there is almost always a better solution. For example, <code>eval(mask)</code> will cause issues if the column is not accessible via <code>data.column_name</code> (if the name is not valid, such as <code>x y</code>).</p>
| 1 | 2016-08-16T15:22:10Z | [
"python",
"pandas"
] |
python combobox with return variable | 38,975,269 | <p>I'm trying to Tkinter with a Combox the press of a
Button to output a variable, but do not get ahead here.</p>
<pre><code>from tkinter import *
import tkinter as tk
from tkinter import ttk
def select():
name_option = var.get()
print (Number of choices)
root = tk.Tk()
var = StringVar(root)
choices = {
'A': '11',
'B': '22',
'C': '33',
'D': '44',
'E': '55',
}
option = tk.OptionMenu(root, var, *choices)
option.place(x = 1, y = 50, width=80, height=25)
change_button = tk.Button(root, text="Klick me", command=select)
change_button.place(x = 100, y = 50, width=80, height=25)
root.mainloop()
</code></pre>
| 0 | 2016-08-16T12:43:07Z | 38,975,717 | <p>change </p>
<p><code>print (Number of choices)</code></p>
<p>to</p>
<p><code>print(name_option)</code></p>
<p>or just change <code>select()</code> to:</p>
<pre><code>def select():
print(var.get())
</code></pre>
| 0 | 2016-08-16T13:01:54Z | [
"python",
"tkinter",
"combobox"
] |
python combobox with return variable | 38,975,269 | <p>I'm trying to Tkinter with a Combox the press of a
Button to output a variable, but do not get ahead here.</p>
<pre><code>from tkinter import *
import tkinter as tk
from tkinter import ttk
def select():
name_option = var.get()
print (Number of choices)
root = tk.Tk()
var = StringVar(root)
choices = {
'A': '11',
'B': '22',
'C': '33',
'D': '44',
'E': '55',
}
option = tk.OptionMenu(root, var, *choices)
option.place(x = 1, y = 50, width=80, height=25)
change_button = tk.Button(root, text="Klick me", command=select)
change_button.place(x = 100, y = 50, width=80, height=25)
root.mainloop()
</code></pre>
| 0 | 2016-08-16T12:43:07Z | 38,975,990 | <p>Change your function body to:</p>
<pre><code>def select():
name_option = var.get()
num = choices[name_option]
print ("Number of choices", num)
</code></pre>
<p>I just added <code>num = choices[name_option]</code> which returns the value of the item (key) you select. And then print out <code>num</code>.</p>
| 0 | 2016-08-16T13:14:21Z | [
"python",
"tkinter",
"combobox"
] |
How to count the number of calls to a method? | 38,975,292 | <p>I'm working with the pi2go lite robot. This is my code</p>
<pre><code>import pi2go, time
import sys
import tty
import termios
import time
pi2go.init()
def stepCount():
countL += 0
countR += 0
speed = 60
try:
pi2go.stepForward(60,16)
print stepCount
finally:
pi2go.cleanup()
</code></pre>
<p>The question is I am wondering how to count everytime the "pi2go.stepForward(60,16)" is used.</p>
| -1 | 2016-08-16T12:43:57Z | 38,975,331 | <p>You were very close. <code>stepCount</code> is a function, so you should call it - that is add the parentheses at the end. </p>
<pre><code>speed = 60
try:
pi2go.stepForward(60,16)
stepCount()
</code></pre>
<p>Also you didn't define <code>countL</code> and <code>countR</code>. So you need to define those before hand. </p>
<p>But the best way would be to wrap the <code>pi2go.stepForward(60,16)</code> in another function. </p>
<p>Like: </p>
<pre><code>countL = 0
countR = 0
def stepForward(x, y):
countL += 1
countR += 1
pi2go.stepForward(x,y)
</code></pre>
<p>And then you can just call <code>stepForward(60, 16)</code>. </p>
| 0 | 2016-08-16T12:46:03Z | [
"python"
] |
How to count the number of calls to a method? | 38,975,292 | <p>I'm working with the pi2go lite robot. This is my code</p>
<pre><code>import pi2go, time
import sys
import tty
import termios
import time
pi2go.init()
def stepCount():
countL += 0
countR += 0
speed = 60
try:
pi2go.stepForward(60,16)
print stepCount
finally:
pi2go.cleanup()
</code></pre>
<p>The question is I am wondering how to count everytime the "pi2go.stepForward(60,16)" is used.</p>
| -1 | 2016-08-16T12:43:57Z | 38,975,538 | <pre><code>counter = dict(ok=0, fail=0, all=0)
try:
pi2go.stepForward(60,16)
counter['ok'] += 1
except:
counter['fail'] += 1
finally:
counter['all'] += 1
pi2go.cleanup()
</code></pre>
| 0 | 2016-08-16T12:54:07Z | [
"python"
] |
Can I feed lame a blob and have it convert 'on the fly?' | 38,975,299 | <p>I have a situation where a <code>wav</code> blob will be posted to my django project and I will have to convert it to an mp3. I have the process down, but it seems a little verbose and I would like to cut it down a bit but IDK how to go about doing it. </p>
<pre><code>wav_path = os.path.join(full_path, "%s%s.wav" % (word.name, file_number))
mp3_path = wav_path[:-3] + "mp3"
with open(wav_path, 'w') as f:
f.write(request.FILES['audio_file'].read())
os.popen("lame %s --comp 40 %s" % (wav_path, mp3_path))
os.popen("rm %s" % wav_path)
</code></pre>
<p>lame says it can take something from stdin instead of a named file with <code>-</code> so I tried this</p>
<pre><code>lame - --comp 40 outfile.m3p << infile.wav
something infile.wav | lame - --comp 40 outfile.mp3
</code></pre>
<p>Sorry for adding <code>something</code> there but I am unsure of what to use in that spot. It seems like writing the blob to a file > converting it and then deleting the blob can be shortened up</p>
| 0 | 2016-08-16T12:44:14Z | 38,975,582 | <p>You could replace 'something' with 'cat' in your example.</p>
<pre><code>cat infile.wav | lame - --comp 40 outfile.mp3
</code></pre>
<p>But in case you already have the blob in python, you could directly pipe it via stdin, instead of going the detour of writing it to a .wav file. See
<a href="http://stackoverflow.com/questions/8475290/how-do-i-write-to-a-python-subprocess-stdin">how do i write to a python subprocess' stdin</a></p>
| 1 | 2016-08-16T12:55:49Z | [
"python",
"django",
"bash",
"lame"
] |
2D mask for a specific color | 38,975,339 | <p>I solved a problem with a loop, but it is both slow and unpythonic. I'm looking for a mask solution. If I were interested in pixels with values for a specific channel, that would be simple: </p>
<pre><code>img[img[:,:,0]==64] = [0,0,0]
</code></pre>
<p>to turn them all black. I want to change a specific color, e.g. <code>[192,0,128]</code>, so I need all three channels, something like <code>img[ img[:,:,0]==192 and img[:,:,1]==0 and img[:,:,2]==128]=[0,0,0]</code> but of course this is wrong. I also tried <code>np.all(img==[192,0,128])</code> but it didn't work either. </p>
| 1 | 2016-08-16T12:46:13Z | 38,975,477 | <p>OK, I just used <code>numpy.logical_and()</code> and it did the trick! </p>
| 0 | 2016-08-16T12:51:36Z | [
"python",
"image",
"rgb",
"scikit-image"
] |
2D mask for a specific color | 38,975,339 | <p>I solved a problem with a loop, but it is both slow and unpythonic. I'm looking for a mask solution. If I were interested in pixels with values for a specific channel, that would be simple: </p>
<pre><code>img[img[:,:,0]==64] = [0,0,0]
</code></pre>
<p>to turn them all black. I want to change a specific color, e.g. <code>[192,0,128]</code>, so I need all three channels, something like <code>img[ img[:,:,0]==192 and img[:,:,1]==0 and img[:,:,2]==128]=[0,0,0]</code> but of course this is wrong. I also tried <code>np.all(img==[192,0,128])</code> but it didn't work either. </p>
| 1 | 2016-08-16T12:46:13Z | 39,017,369 | <p>You were almost there: </p>
<pre><code>np.all(img == [192,0,128], axis=-1)
</code></pre>
<p>gives what you're looking for. You need to specify an axis to do the dimension reduction, which corresponds to the color channel axis here.</p>
| 1 | 2016-08-18T11:44:44Z | [
"python",
"image",
"rgb",
"scikit-image"
] |
Limiting the number of processes being run at once by subprocess.Popen | 38,975,417 | <p>I have a list of computationally intensive files that I'm running using Python's subprocess module. The idea is to use <code>Popen</code> rather than something like <code>check_call</code> to go through the list more quickly. However, when the list is larger than say 4 or 5 elements the computers, the program saps all of the computers resources making it unusable until its finished. My question is: is there a convenient way to limit the number of processes that my program opens at once?</p>
<p>The code I'm using is simple but part of a larger program so that pasting all code needed to run it is not possible.</p>
<pre><code>def run_fast(self):
'''
self.cps_dct is a nested dictionary dct[index1][index2]=filename
CopasiSE is a program for simulating mathematical models using the terminal/cmd
'''
for i in self.cps_dct.keys():
for j in self.cps_dct[i]:
subprocess.Popen('CopasiSE {}'.format(self.cps_dct[i][j]))
return self.cps_dct
</code></pre>
<p>thanks</p>
| 0 | 2016-08-16T12:49:39Z | 38,976,167 | <p>Adding to what was suggested by Klaus:
Something like that could work:</p>
<pre><code>from multiprocessing import Pool
import subprocess
class Cps:
def __init__(self):
self.cps_dct = {
'a': {
'1': 'file1',
'2': 'file2',
'3': 'file3',
'4': 'file4'
},
'b': {
'1': 'file1',
'2': 'file2',
'3': 'file3',
'4': 'file4'
}
}
def open_proc(file_name):
subprocess.Popen('CopasiSE {}'.format(file_name))
if __name__ == '__main__':
process_cap = 4
p = Pool(process_cap)
# Initialize the object.
item = Cps()
for i in item.cps_dct.keys():
iterable = item.cps_dct[i].values()
p.map(open_proc, iterable)
p.close()
p.join()
</code></pre>
| 2 | 2016-08-16T13:23:24Z | [
"python",
"subprocess",
"popen"
] |
How to create contracts on Ethereum block-chain in python? | 38,975,431 | <p>I want to create contract on Ethereum to store data. I'm beginner on this domain...Do we have a better solution ? </p>
<p>In this <a href="http://ethereum.stackexchange.com/questions/7884/how-can-i-store-data-in-ethereum-blockchain?noredirect=1&lq=1">post</a>, someone tell me to download a plugin. This is one way to do it, but I want to insert data in a block-chain with python (or other language).</p>
<p>I don't know where to start ... download Ethereum? Create an account?</p>
<p>Does it incur any cost? How much?</p>
<p>If contracts can be update, can I use Ethereum contract to prove work?</p>
| 2 | 2016-08-16T12:50:00Z | 38,982,630 | <blockquote>
<p>I don't know where to start ... download Ethereum? Create an account?</p>
</blockquote>
<ol>
<li><p>Install the command line tools. <a href="https://www.ethereum.org/cli" rel="nofollow">ethereum.org/cli</a></p>
<p>I would not recommend to start with the <code>pyethapp</code> (Python) or the <code>eth</code> (C++) client. Use <code>geth</code> (Golang) or <code>parity</code> (Rust). They are good to get started with and well documented.</p></li>
<li><p>Create a hello world contract. <a href="https://www.ethereum.org/greeter" rel="nofollow">ethereum.org/greeter</a></p>
<p><code>greeter</code> is the most simple smart contract deployed using the command line. </p>
<pre><code>contract mortal {
/* Define variable owner of the type address*/
address owner;
/* this function is executed at initialization and sets the owner of the contract */
function mortal() { owner = msg.sender; }
/* Function to recover the funds on the contract */
function kill() { if (msg.sender == owner) selfdestruct(owner); }
}
contract greeter is mortal {
/* define variable greeting of the type string */
string greeting;
/* this runs when the contract is executed */
function greeter(string _greeting) public {
greeting = _greeting;
}
/* main function */
function greet() constant returns (string) {
return greeting;
}
}
</code></pre></li>
<li><p>Come back here if you have <em>specific</em> issues with a client, with a contract source code or with deploying them on the blockchain.</p></li>
</ol>
<p>Hope that helps getting you bootstrapped :)</p>
| 2 | 2016-08-16T19:05:02Z | [
"python",
"storage",
"blockchain",
"ethereum"
] |
PyMongo cursor - Modify and use value | 38,975,441 | <p>I am encountering difficulties with my PyMongo script:
My documents have a field "used" : "false" or "true".
I want to iterate over the documents whose "use" fields are "false" and use their "friends" field (which is an array of _id values) to add their own _id value to the friends field of every person who is also in the current person's friends field. It should look somewhat like this:</p>
<pre><code>"person_id": "Hans",
"used": "false",
"friends": {
"Hugo",
"Kunigunde"
}
</code></pre>
<p>Afterwards, <code>Hugo</code> and <code>Kunigunde</code> should have <code>Hans</code> as entry in their friends list and <code>used</code> of <code>Hans</code> should be <code>true</code>.
My current approach is</p>
<pre><code>cursor = db.People.find({"used": "false" })
for document in cursor:
</code></pre>
<p>But I don't know how to continue this. Thanks for helping!</p>
| 0 | 2016-08-16T12:50:28Z | 39,036,617 | <p>For adding <code>Hans</code> to <code>Hugo</code> and <code>Kunigundes</code> friendslist:</p>
<pre><code>for friend in cursor_pointing_to_Hans['friends']:
friend_list=db.People.find({'person_id':friend})['friends']
friend_list.append(cursor_pointing_to_Hans['person_id'])
db.People.update({'person_id':friend},{'friends':friend_list})
</code></pre>
<p>For setting <code>Hans</code> <code>used</code> field to true:</p>
<pre><code>db.People.update({'person_id':cursor_pointing_to_Hans['person_id']}, {'used':"true"})
</code></pre>
<p>Furthermore as you are working in Python I´d suggest to use the boolean python values <code>True</code> and <code>False</code> instead of the Strings "true" and "false"</p>
| 0 | 2016-08-19T10:22:52Z | [
"python",
"mongodb",
"cursor",
"pymongo"
] |
Python remove elements from unknown list with a specific string | 38,975,623 | <p>There are similar questions to this but not quite what im looking for.</p>
<p>Having created a list with all files from a specific path im looking to filter out anything that does not contain a specific sequence in a string.</p>
<pre><code>def filter():
someFiles = os.listdir(somePath)
listSize = len(someFiles)
for i in range(0, listSize):
if (".py" not in someFiles):
someFiles.remove(i)
print("{0}".format(someFiles))
</code></pre>
<p>Im aware i shouldn't be modifying the size of a list through a loop but i left it just to roughly give an idea of what i'm trying to accomplish</p>
<p>I did not make it clear, the issue that im facing is that i'm not sure what approach i should be taking when trying to remove every element that does not contain ".py". What I wrote above is more of a rough draft.</p>
| 0 | 2016-08-16T12:57:44Z | 38,975,756 | <pre><code>for i in range(0, listSize):
if (".py" not in someFiles):
someFiles.remove(i)
</code></pre>
<p>Note that you are trying to remove <code>i</code> from the list. <code>i</code> will be an index of an element in the list (<code>0</code>, <code>1</code>, etc) and not an actual element. This will raise an error.</p>
<p><br/></p>
<p>Simply use list comprehension to get only the files you <em>do</em> need:</p>
<pre><code>required_files = [f for f in someFiles if '.py' in f]
</code></pre>
<p>You could also use <code>filter</code> but it will require a lambda (and also note it will return a <code>filter</code> object and not a <code>list</code>):</p>
<pre><code>required_files = list(filter(lambda x: '.py' in x, someFiles))
</code></pre>
| 3 | 2016-08-16T13:04:03Z | [
"python",
"python-3.x"
] |
Python remove elements from unknown list with a specific string | 38,975,623 | <p>There are similar questions to this but not quite what im looking for.</p>
<p>Having created a list with all files from a specific path im looking to filter out anything that does not contain a specific sequence in a string.</p>
<pre><code>def filter():
someFiles = os.listdir(somePath)
listSize = len(someFiles)
for i in range(0, listSize):
if (".py" not in someFiles):
someFiles.remove(i)
print("{0}".format(someFiles))
</code></pre>
<p>Im aware i shouldn't be modifying the size of a list through a loop but i left it just to roughly give an idea of what i'm trying to accomplish</p>
<p>I did not make it clear, the issue that im facing is that i'm not sure what approach i should be taking when trying to remove every element that does not contain ".py". What I wrote above is more of a rough draft.</p>
| 0 | 2016-08-16T12:57:44Z | 38,975,805 | <p>First of all, you don't need to use for loop to iterate over a list in Python. Simpler version of what you've done would be</p>
<pre><code>list2 = []
for filename in list1:
if (".py" in filename):
list2.append(filename)
</code></pre>
<p>but filtering a list (or more generally, an iterator) is so common, that there is Python builtin function called, unsurprisingly, <code>filter</code>:</p>
<pre><code>list2 = list(filter(lambda i: ".py" in i, list1))
</code></pre>
<p>(this would work at least in Python3)</p>
| 1 | 2016-08-16T13:06:35Z | [
"python",
"python-3.x"
] |
test error message in python 3 | 38,975,640 | <p>I have the following test method</p>
<pre><code>def test_fingerprintBadFormat(self):
"""
A C{BadFingerPrintFormat} error is raised when unsupported
formats are requested.
"""
with self.assertRaises(keys.BadFingerPrintFormat) as em:
keys.Key(self.rsaObj).fingerprint('sha256-base')
self.assertEqual('Unsupported fingerprint format: sha256-base',
em.exception.message)
</code></pre>
<p>Here is the exception class.</p>
<pre><code>class BadFingerPrintFormat(Exception):
"""
Raises when unsupported fingerprint formats are presented to fingerprint.
"""
</code></pre>
<p>this test method works perfectly fine in Python2 but fails in python 3 with the following message</p>
<pre><code>builtins.AttributeError: 'BadFingerPrintFormat' object has no attribute 'message'
</code></pre>
<p>How can I test the error message in Python3. I don't like the idea of using <code>asserRaisesRegex</code> as it tests the regex rather than the exception message.</p>
| 0 | 2016-08-16T12:58:18Z | 38,977,895 | <p>The <code>.message</code> attribute was removed from exceptions in Python 3. Use <code>.args[0]</code> instead:</p>
<pre><code>self.assertEqual('Unsupported fingerprint format: sha256-base',
em.exception.args[0])
</code></pre>
<p>or use <code>str(em.exception)</code> to get the same value:</p>
<pre><code>self.assertEqual('Unsupported fingerprint format: sha256-base',
str(em.exception))
</code></pre>
<p>This will work both on Python 2 and 3:</p>
<pre><code>>>> class BadFingerPrintFormat(Exception):
... """
... Raises when unsupported fingerprint formats are presented to fingerprint.
... """
...
>>> exception = BadFingerPrintFormat('Unsupported fingerprint format: sha256-base')
>>> exception.args
('Unsupported fingerprint format: sha256-base',)
>>> exception.args[0]
'Unsupported fingerprint format: sha256-base'
>>> str(exception)
'Unsupported fingerprint format: sha256-base'
</code></pre>
| 2 | 2016-08-16T14:42:09Z | [
"python",
"unit-testing",
"python-3.x",
"exception"
] |
two keys with the same name "$or" | 38,975,664 | <p>This is a PARSE REST API question. I need to send some json to query the parse server using the Parse REST API. The json needs to contain two keys with the same name "$or". The first key/value is ignored and the second key/value is used by the server. I realise dictionaries can't have two keys with the same name. I've spent a fair bit of time looking at the documentation but its unclear how multiple $or can be done. Is there any way around this? </p>
<pre><code> import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
"gender": "male",
"$or": [
{
"brand": "nike"
},
{
"brand": "adidas"
}
],
"$or": [
{
"prim_color": "red"
},
{
"prim_color": "blue"
}
]
})})
connection.connect()
connection.request('GET', '/1/classes/My_Class?%s' % params, '', {
"X-Parse-Application-Id": "API-ID",
"X-Parse-REST-API-Key": "REST-KEY"
})
result = json.loads(connection.getresponse().read())
print result
</code></pre>
| 0 | 2016-08-16T12:59:24Z | 38,975,949 | <p>As shown in the <a href="http://parseplatform.github.io/docs/rest/guide/#query-constraints" rel="nofollow">doc</a>, <code>$or</code> accept an array with one or more conditions to optionally fulfill:</p>
<pre><code>import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
"gender": "male",
"$or": [
{
"brand": "nike"
},
{
"brand": "adidas"
},
{
"prim_color": "red"
},
{
"prim_color": "blue"
}
]
})})
connection.connect()
connection.request('GET', '/1/classes/Player?%s' % params, '', {
"X-Parse-Application-Id": "${APPLICATION_ID}",
"X-Parse-REST-API-Key": "${REST_API_KEY}"
})
result = json.loads(connection.getresponse().read())
print result
</code></pre>
<hr>
<p><strong><em>Edit:</em></strong> Ok, you want to have at least one brand/color from your lists.<br>
Sadly their parser is pretty bad and you cannot do complex query (In your case even doing an <code>$and</code> with <code>$or</code> inside...). Where's operators cannot be embedded into others (and only <code>$or</code> is implemented so far).</p>
<p>Anyway you can use <code>$in</code> to use as an <code>$or</code> condition ...</p>
<pre><code>import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"where":json.dumps({
"gender": "male",
"brand": { "$in": ["nike", "adidas"] }
"prim_color": { "$in": ["red", "blue"] }
})})
connection.connect()
connection.request('GET', '/1/classes/Player?%s' % params, '', {
"X-Parse-Application-Id": "${APPLICATION_ID}",
"X-Parse-REST-API-Key": "${REST_API_KEY}"
})
result = json.loads(connection.getresponse().read())
print result
</code></pre>
| 2 | 2016-08-16T13:12:36Z | [
"python",
"json",
"parse.com"
] |
Can internal dictionary order change? | 38,975,722 | <pre><code>exampleDict = {'a':1, 'b':2, 'c':3, 'd':4}
</code></pre>
<p>The above dictionary initially iterated through in this order:</p>
<pre><code>b=2
d=4
a=1
c=3
</code></pre>
<p>Then, I moved around a ton of files in my code, and now it iterates through in this order:</p>
<pre><code>d=4
a=1
c=3
b=2
</code></pre>
<p>I know that the order is internally stored as a hashmap, but what would cause that internal order to change?</p>
<p>Edit: I don't need to preserve order so I will stick with using a dict. I am just wondering why it happened. I thought order wasn't guaranteed, but once it has its arbitrary internal order, it sticks with it for future iterations.</p>
| 4 | 2016-08-16T13:02:12Z | 38,975,783 | <p>Yes. If you do change the code between different calls to the dict, the order of iteration will change.</p>
<p>From the <a href="https://docs.python.org/2/library/stdtypes.html#dict.items" rel="nofollow">docs</a></p>
<blockquote>
<p>If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.</p>
</blockquote>
<p>If the order of insertion matter, check out the <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a> class</p>
| -1 | 2016-08-16T13:05:12Z | [
"python",
"dictionary",
"hashmap"
] |
Can internal dictionary order change? | 38,975,722 | <pre><code>exampleDict = {'a':1, 'b':2, 'c':3, 'd':4}
</code></pre>
<p>The above dictionary initially iterated through in this order:</p>
<pre><code>b=2
d=4
a=1
c=3
</code></pre>
<p>Then, I moved around a ton of files in my code, and now it iterates through in this order:</p>
<pre><code>d=4
a=1
c=3
b=2
</code></pre>
<p>I know that the order is internally stored as a hashmap, but what would cause that internal order to change?</p>
<p>Edit: I don't need to preserve order so I will stick with using a dict. I am just wondering why it happened. I thought order wasn't guaranteed, but once it has its arbitrary internal order, it sticks with it for future iterations.</p>
| 4 | 2016-08-16T13:02:12Z | 38,975,844 | <p>Dict don't have a fixed order, from <a href="https://docs.python.org/2/library/stdtypes.html#dict.items" rel="nofollow">documentation</a></p>
<blockquote>
<p>CPython implementation detail: Keys and values are listed in an
arbitrary order which is non-random, varies across Python
implementations, and depends on the dictionaryâs history of insertions
and deletions.</p>
</blockquote>
<p>If you really need to keep it ordered, there is an object called <code>OrderedDict</code> :</p>
<pre><code>from collections import OrderedDict
exampleDict = OrderedDict({'a':1, 'b':2, 'c':3, 'd':4})
</code></pre>
<p>see also OrderedDict documentation <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">here</a></p>
| 4 | 2016-08-16T13:08:05Z | [
"python",
"dictionary",
"hashmap"
] |
Can internal dictionary order change? | 38,975,722 | <pre><code>exampleDict = {'a':1, 'b':2, 'c':3, 'd':4}
</code></pre>
<p>The above dictionary initially iterated through in this order:</p>
<pre><code>b=2
d=4
a=1
c=3
</code></pre>
<p>Then, I moved around a ton of files in my code, and now it iterates through in this order:</p>
<pre><code>d=4
a=1
c=3
b=2
</code></pre>
<p>I know that the order is internally stored as a hashmap, but what would cause that internal order to change?</p>
<p>Edit: I don't need to preserve order so I will stick with using a dict. I am just wondering why it happened. I thought order wasn't guaranteed, but once it has its arbitrary internal order, it sticks with it for future iterations.</p>
| 4 | 2016-08-16T13:02:12Z | 38,976,376 | <p>Curious about why you want them ordered. Any chance it's just for consistent logging/printing or similar? If so, you can sort the keys alphabetically. See other article:
<a href="http://stackoverflow.com/questions/22264956/how-to-sort-dictionary-by-key-in-numerical-order-python">How to sort dictionary by key in numerical order Python</a></p>
| 0 | 2016-08-16T13:33:16Z | [
"python",
"dictionary",
"hashmap"
] |
python shapely: retrieve the x,y,z value of a LinearRing | 38,975,740 | <p>I`m trying to plot a LinearRing that shows the difference of the crossover of two Polygons:</p>
<pre><code>import mpl_toolkits.mplot3d as a3
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
fig = plt.figure()
ax = Axes3D(fig)
poly1 = Polygon([(220.0, 780, 500), (840, 780, 500), (840, 180, 500), (220.0, 180, 500)])
poly2 = Polygon ([(320.0, 380, 500), (740, 380, 500), (740, 180, 500), (320.0, 180, 500)])
dif = poly1.difference(poly2)
</code></pre>
<p>I`d like to plot dif, however, when using:</p>
<pre><code>top1 = a3.art3d.Poly3DCollection([dif],alpha=0.6)
</code></pre>
<p>I get an erros saying "TypeError: 'Polygon' object is not iterable" </p>
<p>I therefore try to get the x,y,z coordinates of dif and plot them, but I`ve only managed to get the x,y ones. For the sake of testing, I currently feed-in the Z value manualy:</p>
<pre><code>z= [500,500,500,500,500,500,500,500]
x,y = a.exterior.xy
zipped = list(zip (x,y,z))
top1 = a3.art3d.Poly3DCollection([zipped],alpha=0.6)
top1.set_color('wheat')
top1.set_edgecolor('k')
ax.add_collection3d(top1)
ax.set_xlim(0, 1000)
ax.set_ylim(0, 1000)
ax.set_zlim(0, 1000)
plt.show()
</code></pre>
<p>I then get the plot I am after, but I`m looking for an easier way to plot dif.</p>
| 0 | 2016-08-16T13:03:10Z | 39,347,934 | <p>With the <code>exterior</code> attribute you are using, you can get the coords:</p>
<pre><code>top1 = a3.art3d.Poly3DCollection([dif.exterior.coords],alpha=0.6)
</code></pre>
<p>Beware, with this code and also with your solution, you are loosing the interior rings of the polygon, if there are any.</p>
<p>Notice that <code>coords</code> returns an iterable, if you want a list you must create it (<code>list(dif.exterior.coords)</code>).</p>
<p>For a polygon with interior rings, you could handle it as in this example:</p>
<pre><code>poly = Point(0,0).buffer(500)
poly = Polygon([ (x, y, 500) for x, y in poly.exterior.coords ])
spoly = Point(0,0).buffer(200)
spoly = Polygon([ (x, y, 500) for x, y in spoly.exterior.coords ])
poly = poly.difference(spoly)
all_coords = [p.coords for p in poly.interiors]
all_coords.append(poly.exterior.coords)
top1 = a3.art3d.Poly3DCollection(all_coords,alpha=0.6)
</code></pre>
<p>IMHO, using shapely with 3D polygons is misleading, since shapely only handles 2D polygons, and will bring you problems if you spread the 3D part all over the code that uses Shapely. Besides, someone reading the code could think you are actually doing 3D math when you are not. Perhaps you can isolate all 2D computation with shapely, and after that add it the 3D part.</p>
| 0 | 2016-09-06T11:26:46Z | [
"python",
"shapely"
] |
Pcolorfast image/array rotation | 38,975,743 | <p>I have the code below:</p>
<pre><code>fig, ax = pyplot.subplots()
graph = ax.pcolorfast(data, cmap='viridis', vmin = min, vmax = max)
pyplot.colorbar(graph)
pyplot.show()
</code></pre>
<p>and it plots what I wanted, however it is sideways. Is there a good way of rotating it -90 or 270 degrees? I have tried <code>a.T</code>, which returns the original plot. I have also tried <code>ndimage.rotate(graph, -90|270)</code>, <code>ndimage.interpolation.rotate(graph, -90|270)</code>, and <code>numpy.rot90(data,3)</code>. The first two return errors for invalid rotation planes and the second appears to shove the graph off the edge, losing a majority of my data points.</p>
<p>If anyone has some thoughts, I would be very grateful. Even if it's that I put in the wrong arguments. I am at a loss here.</p>
| 0 | 2016-08-16T13:03:12Z | 38,976,203 | <p>Is <code>a</code> supposed to be equal to <code>data</code> in your example? Tried your code with a random 2D array, and <code>np.transpose(a)</code> as well as <code>a.T</code> seem to properly rotate the figure, as opposed to what you indicate here ('returns the original plot'). If this is not the case for you, I think we need more information.</p>
| 0 | 2016-08-16T13:25:06Z | [
"python",
"numpy",
"matplotlib",
"rotation"
] |
Extracting element from a bitarray using indexes in a list | 38,975,747 | <p>I got a list of index of element of a BitArray. I want to extract the elements.</p>
<p>If I try on this simple example the classical method</p>
<pre><code>from bitstring import BitArray
barray = BitArray('0b101111011110101')
index = [1,2,3,4]
barray[index]
</code></pre>
<p>I got the error </p>
<pre><code>IndexError: Slice index out of range.
</code></pre>
<p>It's the same if I use as index a tuple or a numpy array. I watched the documentation and the main funtion, it's weird for me, but it seems impossible and I don't know why.</p>
<p>It seems for that the only solutions is to do a loop, and I would like to avoid it for speed.</p>
<p>Anybody get an idea?</p>
| 2 | 2016-08-16T13:03:25Z | 38,975,820 | <p>Well you could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html" rel="nofollow"><code>np.take</code></a> to extract those as a NumPy boolean array -</p>
<pre><code>np.take(barray,index)
</code></pre>
<p>Sample run -</p>
<pre><code>In [156]: barray
Out[156]: BitArray('0b101111011110101')
In [157]: index
Out[157]: [1, 2, 3, 4]
In [158]: np.take(barray,index)
Out[158]: array([False, True, True, True], dtype=bool)
</code></pre>
| 0 | 2016-08-16T13:06:56Z | [
"python",
"numpy",
"bitarray"
] |
Python numpy float16 datatype operations, and float8? | 38,975,770 | <p>when performing math operations on float16 Numpy numbers, the result is also in float16 type number.
My question is how exactly the result is computed?
Say Im multiplying/adding two float16 numbers, does python generate the result in float32 and then truncate/round the result to float16? Or does the calculation performed in '16bit multiplexer/adder hardware' all the way?</p>
<p>another question - is there a float8 type? I couldnt find this one... if not, then why? Thank-you all!</p>
| 3 | 2016-08-16T13:04:32Z | 38,977,958 | <p>To the first question: there's no hardware support for <code>float16</code> on a typical processor (at least outside the GPU). NumPy does exactly what you suggest: convert the <code>float16</code> operands to <code>float32</code>, perform the scalar operation on the <code>float32</code> values, then round the <code>float32</code> result back to <code>float16</code>. It can be proved that the results are still correctly-rounded: the precision of <code>float32</code> is large enough (relative to that of <code>float16</code>) that double rounding isn't an issue here, at least for the four basic arithmetic operations and square root.</p>
<p>In the current NumPy source, this is what the definition of the four basic arithmetic operations looks like for <code>float16</code> scalar operations.</p>
<pre><code>#define half_ctype_add(a, b, outp) *(outp) = \
npy_float_to_half(npy_half_to_float(a) + npy_half_to_float(b))
#define half_ctype_subtract(a, b, outp) *(outp) = \
npy_float_to_half(npy_half_to_float(a) - npy_half_to_float(b))
#define half_ctype_multiply(a, b, outp) *(outp) = \
npy_float_to_half(npy_half_to_float(a) * npy_half_to_float(b))
#define half_ctype_divide(a, b, outp) *(outp) = \
npy_float_to_half(npy_half_to_float(a) / npy_half_to_float(b))
</code></pre>
<p>The code above is taken from <a href="https://github.com/numpy/numpy/blob/bfd91d9e91ec5ea1c1d77b27b09952a11a24e19e/numpy/core/src/umath/scalarmath.c.src#L309-L316" rel="nofollow">scalarmath.c.src</a> in the NumPy source. You can also take a look at <a href="https://github.com/numpy/numpy/blob/bfd91d9e91ec5ea1c1d77b27b09952a11a24e19e/numpy/core/src/umath/loops.c.src#L1879" rel="nofollow">loops.c.src</a> for the corresponding code for array ufuncs. The supporting <code>npy_half_to_float</code> and <code>npy_float_to_half</code> functions are defined in <a href="https://github.com/numpy/numpy/blob/1429c606643d1ad305e710c4a31cb6f398d04c53/numpy/core/src/npymath/halffloat.c" rel="nofollow">halffloat.c</a>, along with various other support functions for the <code>float16</code> type.</p>
<p>For the second question: no, there's no <code>float8</code> type in NumPy. <code>float16</code> is a standardized type (described in the IEEE 754 standard), that's already in wide use in some contexts (notably GPUs). There's no IEEE 754 <code>float8</code> type, and there doesn't appear to be an obvious candidate for a "standard" <code>float8</code> type. I'd also guess that there just hasn't been that much demand for <code>float8</code> support in NumPy.</p>
| 3 | 2016-08-16T14:45:27Z | [
"python",
"numpy",
"floating-point",
"precision"
] |
Python: Setup.py doesn't copy code to site-packages | 38,975,786 | <p>I wrote my own python package and when I try to install with:</p>
<pre><code>python setup.py install
</code></pre>
<p>It installs the package and puts an <em>egg</em> file in site-packages folder, but the code stays in the original folder (on my desktop) instead of moving to site-packages too.
The setup.py script looks like this:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from mypackage import __version__
setup(
name = 'mypackage',
packages = ['mypackage'],
version = __version__
)
</code></pre>
<p>The folder of the package looks like this:</p>
<pre><code>setup.py
mypackage/
__init__.py
mymodule.py
</code></pre>
<p>How can I get it to copy the package to site-package like it normally does?</p>
| -1 | 2016-08-16T13:05:27Z | 38,977,571 | <p>No need. That egg file is a <a href="https://wiki.python.org/moin/egg" rel="nofollow">single file importable distribution format</a> containing your code. You should be able to import it as is.</p>
| 0 | 2016-08-16T14:27:39Z | [
"python",
"windows",
"python-2.7",
"setup.py"
] |
Elaborating very large array in Python | 38,975,843 | <p>I open a TIFF LAB image and return a big numpy array (4928x3264x3 float64) using python with this function:</p>
<pre><code>def readTIFFLAB(filename):
"""Read TIFF LAB and retur a float matrix
read 16 bit (2 byte) each time without any multiprocessing
about 260 sec"""
import numpy as np
....
....
# Data read
# Matrix creation
dim = (int(ImageLength), int(ImageWidth), int(SamplePerPixel))
Image = np.empty(dim, np.float64)
contatore = 0
for address in range(0, len(StripOffsets)):
offset = StripOffsets[address]
f.seek(offset)
for lung in range(0, (StripByteCounts[address]/SamplePerPixel/2)):
v = np.array(f.read(2))
v.dtype = np.uint16
v1 = np.array(f.read(2))
v1.dtype = np.int16
v2 = np.array(f.read(2))
v2.dtype = np.int16
v = np.array([v/65535.0*100])
v1 = np.array([v1/32768.0*128])
v2 = np.array([v2/32768.0*128])
v = np.append(v, [v1, v2])
riga = contatore // ImageWidth
colonna = contatore % ImageWidth
# print(contatore, riga, colonna)
Image[riga, colonna, :] = v
contatore += 1
return(Image)
</code></pre>
<p>but this routine need about 270 second to do all the work and return a numpy array.</p>
<p>I try to use multiprocessing but is not possible to share an array or to use queue to pass it and sharedmem is not usable in windows system (at home I use openSuse but at work I must use windows).</p>
<p>Someone could help me to reduce the elaboration time? I read about threadind, to write some part in C language but I donât understand what the best (and easier) solution,...Iâm a food technologist not a real programmer :-)</p>
<p>Thanks</p>
| 0 | 2016-08-16T13:08:02Z | 38,978,955 | <p>Wow, your method is really slow indeed, try <a href="https://github.com/blink1073/tifffile" rel="nofollow">tifffile</a> library, you can find it <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#distribute" rel="nofollow">here</a>. That library will open your file very fast, then you just need to make the proper conversion, here's the simple usage:</p>
<pre><code>import numpy as np
import tifffile
from skimage import color
import time
import matplotlib.pyplot as plt
def convert_to_tifflab(image):
# divide the color channel
L = image[:, :, 0]
a = image[:, :, 1]
b = image[:, :, 2]
# correct interpretation of a/b channel
a.dtype = np.int16
b.dtype = np.int16
# scale the result
L = L / 65535.0 * 100
a = a / 32768.0 * 128
b = b / 32768.0 * 128
# join the result
lab = np.dstack([L, a, b])
# view the image
start = time.time()
rgb = color.lab2rgb(lab)
print "Lab2Rgb: {0}".format(time.time() - start)
return rgb
if __name__ == "__main__":
filename = '/home/cilladani1/FERRERO/Immagini Digi Eye/Test Lettura CIELAB/TestLetturaCIELAB (LAB).tif'
start = time.time()
I = tifffile.imread(filename)
end = time.time()
print "Image fetching: {0}".format(end - start)
rgb = convert_to_tifflab(I)
print "Image conversion: {0}".format(time.time() - end)
plt.imshow(rgb)
plt.show()
</code></pre>
<p>The benchmark gives this data:</p>
<ul>
<li>Image fetching: 0.0929999351501</li>
<li>Lab2Rgb: 12.9520001411</li>
<li>Image conversion: 13.5920000076</li>
</ul>
<p>As you can see the bottleneck in this case is <a href="https://github.com/scikit-image/scikit-image/blob/master/skimage/color/colorconv.py#L1031" rel="nofollow">lab2rgb</a>, which converts from xyz to rgb space. I'd recommend you to report an issue to the author of tifffile requesting the feature to read your fileformat, I'm sure he'll be able to speed up directly the C code.</p>
| 0 | 2016-08-16T15:32:12Z | [
"python",
"arrays",
"numpy",
"image-processing"
] |
Elaborating very large array in Python | 38,975,843 | <p>I open a TIFF LAB image and return a big numpy array (4928x3264x3 float64) using python with this function:</p>
<pre><code>def readTIFFLAB(filename):
"""Read TIFF LAB and retur a float matrix
read 16 bit (2 byte) each time without any multiprocessing
about 260 sec"""
import numpy as np
....
....
# Data read
# Matrix creation
dim = (int(ImageLength), int(ImageWidth), int(SamplePerPixel))
Image = np.empty(dim, np.float64)
contatore = 0
for address in range(0, len(StripOffsets)):
offset = StripOffsets[address]
f.seek(offset)
for lung in range(0, (StripByteCounts[address]/SamplePerPixel/2)):
v = np.array(f.read(2))
v.dtype = np.uint16
v1 = np.array(f.read(2))
v1.dtype = np.int16
v2 = np.array(f.read(2))
v2.dtype = np.int16
v = np.array([v/65535.0*100])
v1 = np.array([v1/32768.0*128])
v2 = np.array([v2/32768.0*128])
v = np.append(v, [v1, v2])
riga = contatore // ImageWidth
colonna = contatore % ImageWidth
# print(contatore, riga, colonna)
Image[riga, colonna, :] = v
contatore += 1
return(Image)
</code></pre>
<p>but this routine need about 270 second to do all the work and return a numpy array.</p>
<p>I try to use multiprocessing but is not possible to share an array or to use queue to pass it and sharedmem is not usable in windows system (at home I use openSuse but at work I must use windows).</p>
<p>Someone could help me to reduce the elaboration time? I read about threadind, to write some part in C language but I donât understand what the best (and easier) solution,...Iâm a food technologist not a real programmer :-)</p>
<p>Thanks</p>
| 0 | 2016-08-16T13:08:02Z | 38,992,264 | <p>After doing what BPL suggest me I modify the result array as follow:</p>
<pre><code># divide the color channel
L = I[:, :, 0]
a = I[:, :, 1]
b = I[:, :, 2]
# correct interpretation of a/b channel
a.dtype = np.int16
b.dtype = np.int16
# scale the result
L = L / 65535.0 * 100
a = a / 32768.0 * 128
b = b / 32768.0 * 128
# join the result
lab = np.dstack([L, a, b])
# view the image
from skimage import color
rgb = color.lab2rgb(lab)
plt.imshow(rgb)
</code></pre>
<p>So now is easier to read TIFF LAB image.
Thank BPL</p>
| 0 | 2016-08-17T09:02:17Z | [
"python",
"arrays",
"numpy",
"image-processing"
] |
Reusing a Tkinter window for a game of Tic Tac Toe | 38,975,929 | <p>I've written a program (listed below) which plays Tic Tic Toe with a Tkinter GUI. If I invoke it like this:</p>
<pre><code>root = tk.Tk()
root.title("Tic Tac Toe")
player1 = QPlayer(mark="X")
player2 = QPlayer(mark="O")
human_player = HumanPlayer(mark="X")
player2.epsilon = 0 # For playing the actual match, disable exploratory moves
game = Game(root, player1=human_player, player2=player2)
game.play()
root.mainloop()
</code></pre>
<p>it works as expected and the <code>HumanPlayer</code> can play against <code>player2</code>, which is a computer player (specifically, a <code>QPlayer</code>). The figure below shows how the <code>HumanPlayer</code> (with mark "X") easily wins.</p>
<p><a href="http://i.stack.imgur.com/Ji4is.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ji4is.png" alt="enter image description here"></a></p>
<p>In order to improve the performance of the <code>QPlayer</code>, I'd like to 'train' it by allowing it to play against an instance of itself before playing against the human player. I've tried modifying the above code as follows:</p>
<pre><code>root = tk.Tk()
root.title("Tic Tac Toe")
player1 = QPlayer(mark="X")
player2 = QPlayer(mark="O")
for _ in range(1): # Play a couple of training games
training_game = Game(root, player1, player2)
training_game.play()
training_game.reset()
human_player = HumanPlayer(mark="X")
player2.epsilon = 0 # For playing the actual match, disable exploratory moves
game = Game(root, player1=human_player, player2=player2)
game.play()
root.mainloop()
</code></pre>
<p>What I then find, however, is that the Tkinter window contains two Tic Tac Toe boards (depicted below), and the buttons of the second board are unresponsive.</p>
<p><a href="http://i.stack.imgur.com/DvXzl.png" rel="nofollow"><img src="http://i.stack.imgur.com/DvXzl.png" alt="enter image description here"></a></p>
<p>In the above code, the <code>reset()</code> method is the same one as used in the callback of the "Reset" button, which usually makes the board blank again to start over. I don't understand why I'm seeing two boards (of which one is unresponsive) instead of a single, responsive board?</p>
<p>For reference, the full code of the Tic Tac Toe program is listed below (with the 'offensive' lines of code commented out):</p>
<pre><code>import numpy as np
import Tkinter as tk
import copy
class Game:
def __init__(self, master, player1, player2, Q_learn=None, Q={}, alpha=0.3, gamma=0.9):
frame = tk.Frame()
frame.grid()
self.master = master
self.player1 = player1
self.player2 = player2
self.current_player = player1
self.other_player = player2
self.empty_text = ""
self.board = Board()
self.buttons = [[None for _ in range(3)] for _ in range(3)]
for i in range(3):
for j in range(3):
self.buttons[i][j] = tk.Button(frame, height=3, width=3, text=self.empty_text, command=lambda i=i, j=j: self.callback(self.buttons[i][j]))
self.buttons[i][j].grid(row=i, column=j)
self.reset_button = tk.Button(text="Reset", command=self.reset)
self.reset_button.grid(row=3)
self.Q_learn = Q_learn
self.Q_learn_or_not()
if self.Q_learn:
self.Q = Q
self.alpha = alpha # Learning rate
self.gamma = gamma # Discount rate
self.share_Q_with_players()
def Q_learn_or_not(self): # If either player is a QPlayer, turn on Q-learning
if self.Q_learn is None:
if isinstance(self.player1, QPlayer) or isinstance(self.player2, QPlayer):
self.Q_learn = True
def share_Q_with_players(self): # The action value table Q is shared with the QPlayers to help them make their move decisions
if isinstance(self.player1, QPlayer):
self.player1.Q = self.Q
if isinstance(self.player2, QPlayer):
self.player2.Q = self.Q
def callback(self, button):
if self.board.over():
pass # Do nothing if the game is already over
else:
if isinstance(self.current_player, HumanPlayer) and isinstance(self.other_player, HumanPlayer):
if self.empty(button):
move = self.get_move(button)
self.handle_move(move)
elif isinstance(self.current_player, HumanPlayer) and isinstance(self.other_player, ComputerPlayer):
computer_player = self.other_player
if self.empty(button):
human_move = self.get_move(button)
self.handle_move(human_move)
if not self.board.over(): # Trigger the computer's next move
computer_move = computer_player.get_move(self.board)
self.handle_move(computer_move)
def empty(self, button):
return button["text"] == self.empty_text
def get_move(self, button):
info = button.grid_info()
move = (info["row"], info["column"]) # Get move coordinates from the button's metadata
return move
def handle_move(self, move):
try:
if self.Q_learn:
self.learn_Q(move)
i, j = move # Get row and column number of the corresponding button
self.buttons[i][j].configure(text=self.current_player.mark) # Change the label on the button to the current player's mark
self.board.place_mark(move, self.current_player.mark) # Update the board
if self.board.over():
self.declare_outcome()
else:
self.switch_players()
except:
print "There was an error handling the move."
pass # This might occur if no moves are available and the game is already over
def declare_outcome(self):
if self.board.winner() is None:
print "Cat's game."
else:
print "The game is over. The player with mark %s won!" % self.current_player.mark
def reset(self):
print "Resetting..."
for i in range(3):
for j in range(3):
self.buttons[i][j].configure(text=self.empty_text)
self.board = Board(grid=np.ones((3,3))*np.nan)
self.current_player = self.player1
self.other_player = self.player2
# np.random.seed(seed=0) # Set the random seed to zero to see the Q-learning 'in action' or for debugging purposes
self.play()
def switch_players(self):
if self.current_player == self.player1:
self.current_player = self.player2
self.other_player = self.player1
else:
self.current_player = self.player1
self.other_player = self.player2
def play(self):
if isinstance(self.player1, HumanPlayer) and isinstance(self.player2, HumanPlayer):
pass # For human vs. human, play relies on the callback from button presses
elif isinstance(self.player1, HumanPlayer) and isinstance(self.player2, ComputerPlayer):
pass
elif isinstance(self.player1, ComputerPlayer) and isinstance(self.player2, HumanPlayer):
first_computer_move = player1.get_move(self.board) # If player 1 is a computer, it needs to be triggered to make the first move.
self.handle_move(first_computer_move)
elif isinstance(self.player1, ComputerPlayer) and isinstance(self.player2, ComputerPlayer):
while not self.board.over(): # Make the two computer players play against each other without button presses
move = self.current_player.get_move(self.board)
self.handle_move(move)
def learn_Q(self, move): # If Q-learning is toggled on, "learn_Q" should be called after receiving a move from an instance of Player and before implementing the move (using Board's "place_mark" method)
state_key = QPlayer.make_and_maybe_add_key(self.board, self.current_player.mark, self.Q)
next_board = self.board.get_next_board(move, self.current_player.mark)
reward = next_board.give_reward()
next_state_key = QPlayer.make_and_maybe_add_key(next_board, self.other_player.mark, self.Q)
if next_board.over():
expected = reward
else:
next_Qs = self.Q[next_state_key] # The Q values represent the expected future reward for player X for each available move in the next state (after the move has been made)
if self.current_player.mark == "X":
expected = reward + (self.gamma * min(next_Qs.values())) # If the current player is X, the next player is O, and the move with the minimum Q value should be chosen according to our "sign convention"
elif self.current_player.mark == "O":
expected = reward + (self.gamma * max(next_Qs.values())) # If the current player is O, the next player is X, and the move with the maximum Q vlue should be chosen
change = self.alpha * (expected - self.Q[state_key][move])
self.Q[state_key][move] += change
class Board:
def __init__(self, grid=np.ones((3,3))*np.nan):
self.grid = grid
def winner(self):
rows = [self.grid[i,:] for i in range(3)]
cols = [self.grid[:,j] for j in range(3)]
diag = [np.array([self.grid[i,i] for i in range(3)])]
cross_diag = [np.array([self.grid[2-i,i] for i in range(3)])]
lanes = np.concatenate((rows, cols, diag, cross_diag)) # A "lane" is defined as a row, column, diagonal, or cross-diagonal
any_lane = lambda x: any([np.array_equal(lane, x) for lane in lanes]) # Returns true if any lane is equal to the input argument "x"
if any_lane(np.ones(3)):
return "X"
elif any_lane(np.zeros(3)):
return "O"
def over(self): # The game is over if there is a winner or if no squares remain empty (cat's game)
return (not np.any(np.isnan(self.grid))) or (self.winner() is not None)
def place_mark(self, move, mark): # Place a mark on the board
num = Board.mark2num(mark)
self.grid[tuple(move)] = num
@staticmethod
def mark2num(mark): # Convert's a player's mark to a number to be inserted in the Numpy array representing the board. The mark must be either "X" or "O".
d = {"X": 1, "O": 0}
return d[mark]
def available_moves(self):
return [(i,j) for i in range(3) for j in range(3) if np.isnan(self.grid[i][j])]
def get_next_board(self, move, mark):
next_board = copy.deepcopy(self)
next_board.place_mark(move, mark)
return next_board
def make_key(self, mark): # For Q-learning, returns a 10-character string representing the state of the board and the player whose turn it is
fill_value = 9
filled_grid = copy.deepcopy(self.grid)
np.place(filled_grid, np.isnan(filled_grid), fill_value)
return "".join(map(str, (map(int, filled_grid.flatten())))) + mark
def give_reward(self): # Assign a reward for the player with mark X in the current board position.
if self.over():
if self.winner() is not None:
if self.winner() == "X":
return 1.0 # Player X won -> positive reward
elif self.winner() == "O":
return -1.0 # Player O won -> negative reward
else:
return 0.5 # A smaller positive reward for cat's game
else:
return 0.0 # No reward if the game is not yet finished
class Player(object):
def __init__(self, mark):
self.mark = mark
self.get_opponent_mark()
def get_opponent_mark(self):
if self.mark == 'X':
self.opponent_mark = 'O'
elif self.mark == 'O':
self.opponent_mark = 'X'
else:
print "The player's mark must be either 'X' or 'O'."
class HumanPlayer(Player):
def __init__(self, mark):
super(HumanPlayer, self).__init__(mark=mark)
class ComputerPlayer(Player):
def __init__(self, mark):
super(ComputerPlayer, self).__init__(mark=mark)
class RandomPlayer(ComputerPlayer):
def __init__(self, mark):
super(RandomPlayer, self).__init__(mark=mark)
@staticmethod
def get_move(board):
moves = board.available_moves()
if moves: # If "moves" is not an empty list (as it would be if cat's game were reached)
return moves[np.random.choice(len(moves))] # Apply random selection to the index, as otherwise it will be seen as a 2D array
class THandPlayer(ComputerPlayer):
def __init__(self, mark):
super(THandPlayer, self).__init__(mark=mark)
def get_move(self, board):
moves = board.available_moves()
if moves:
for move in moves:
if THandPlayer.next_move_winner(board, move, self.mark):
return move
elif THandPlayer.next_move_winner(board, move, self.opponent_mark):
return move
else:
return RandomPlayer.get_move(board)
@staticmethod
def next_move_winner(board, move, mark):
return board.get_next_board(move, mark).winner() == mark
class QPlayer(ComputerPlayer):
def __init__(self, mark, Q={}, epsilon=0.2):
super(QPlayer, self).__init__(mark=mark)
self.Q = Q
self.epsilon = epsilon
def get_move(self, board):
if np.random.uniform() < self.epsilon: # With probability epsilon, choose a move at random ("epsilon-greedy" exploration)
return RandomPlayer.get_move(board)
else:
state_key = QPlayer.make_and_maybe_add_key(board, self.mark, self.Q)
Qs = self.Q[state_key]
if self.mark == "X":
return QPlayer.stochastic_argminmax(Qs, max)
elif self.mark == "O":
return QPlayer.stochastic_argminmax(Qs, min)
@staticmethod
def make_and_maybe_add_key(board, mark, Q): # Make a dictionary key for the current state (board + player turn) and if Q does not yet have it, add it to Q
state_key = board.make_key(mark)
if Q.get(state_key) is None:
moves = board.available_moves()
Q[state_key] = {move: 0.0 for move in moves} # The available moves in each state are initially given a default value of zero
return state_key
@staticmethod
def stochastic_argminmax(Qs, min_or_max): # Determines either the argmin or argmax of the array Qs such that if there are 'ties', one is chosen at random
min_or_maxQ = min_or_max(Qs.values())
if Qs.values().count(min_or_maxQ) > 1: # If there is more than one move corresponding to the maximum Q-value, choose one at random
best_options = [move for move in Qs.keys() if Qs[move] == min_or_maxQ]
move = best_options[np.random.choice(len(best_options))]
else:
move = min_or_max(Qs, key=Qs.get)
return move
root = tk.Tk()
root.title("Tic Tac Toe")
player1 = QPlayer(mark="X")
player2 = QPlayer(mark="O")
# for _ in range(1): # Play a couple of training games
# training_game = Game(root, player1, player2)
# training_game.play()
# training_game.reset()
human_player = HumanPlayer(mark="X")
player2.epsilon = 0 # For playing the actual match, disable exploratory moves
game = Game(root, player1=human_player, player2=player2)
game.play()
root.mainloop()
</code></pre>
| 0 | 2016-08-16T13:11:56Z | 38,977,007 | <p>It looks like you only need to create the board one time as the reset method resets it for the new players. Each type you create a Game instance, you create a new Tk frame so you either need to destroy the old one or you can reuse the windows by not creating a new Game instance each time.</p>
<p>A minor change to the main code at the bottom of the file seems to fix this:</p>
<pre><code>player1 = QPlayer(mark="X")
player2 = QPlayer(mark="O")
game = Game(root, player1, player2)
for _ in range(1): # Play a couple of training games
game.play()
game.reset()
human_player = HumanPlayer(mark="X")
player2.epsilon = 0 # For playing the actual match, disable exploratory moves
game.player1 = human_player
game.player2 = player2
game.play()
</code></pre>
| 1 | 2016-08-16T14:01:46Z | [
"python",
"tkinter"
] |
Healpy coordinate error after interpolation: appearance of bisector | 38,975,961 | <p>I have a coarse skymap made up of 128 points, of which I would like to make a smooth healpix map (see attached Figure, LHS). Figures referenced in the text:</p>
<p><img src="http://i.stack.imgur.com/bv9P0.jpg" alt="here"></p>
<p>I load my data, then make new longitude and latitude arrays of the appropriate pixel length for the final map (with e.g. nside=32). </p>
<p>My input data are:</p>
<pre><code>lats = pi/2 + ths # theta from 0, pi, size 8
lons = phs # phi from 0, 2pi, size 16
data = sky_data[0] # shape (8,16)
</code></pre>
<p>New lon/lat array size based on number of pixels from nside:</p>
<pre><code>nside = 32
pixIdx = hp.nside2npix(nside) # number of pixels I can get from this nside
pixIdx = np.arange(pixIdx) # pixel index numbers
</code></pre>
<p>I then find the new data values for those pixels by interpolation, and then convert back from angles to pixels.</p>
<pre><code># new lon/lat
new_lats = hp.pix2ang(nside, pixIdx)[0] # thetas I need to populate with interpolated theta values
new_lons = hp.pix2ang(nside, pixIdx)[1] # phis, same
# interpolation
lut = RectSphereBivariateSpline(lats, lons, data, pole_values=4e-14)
data_interp = lut.ev(new_lats.ravel(), new_lons.ravel()) #interpolate the data
pix = hp.ang2pix(nside, new_lats, new_lons) # convert latitudes and longitudes back to pixels
</code></pre>
<p>Then, I construct a healpy map with the interpolated values:</p>
<pre><code>healpix_map = np.zeros(hp.nside2npix(nside), dtype=np.double) # create empty map
healpix_map[pix] = data_interp # assign pixels to new interpolated values
testmap = hp.mollview(healpix_map)
</code></pre>
<p>The result of the map is the upper RHS of the attached Figure.</p>
<p>(Forgive the use of jet -- viridis doesn't have a "white" zero, so using that colormap adds a blue background.)</p>
<p>The map doesn't look right: you can see from the coarse map in the Figure that there should be a "hotspot" on the lower RHS, but here it appears in the upper left.</p>
<p>As a sanity check, I used matplotlib to make a scatter plot of the interpolated points in a mollview projection, Figure 2, where I removed the edges of the markers to make it look like a map ;)</p>
<pre><code>ax = plt.subplot(111, projection='astro mollweide')
ax.grid()
colors = data_interp
sky=plt.scatter(new_lons, new_lats-pi/2, c = colors, edgecolors='none', cmap ='jet')
plt.colorbar(sky, orientation = 'horizontal')
</code></pre>
<p>You can see that this map, lower RHS of attached Figure, produces exactly what I expect! So the coordinates are ok, and I am completely confused. </p>
<p>Has anyone encountered this before? What can I do? I'd like to use the healpy functions on this and future maps, so just using matplotlib isn't an option.</p>
<p>Thanks!</p>
| 1 | 2016-08-16T13:12:57Z | 38,981,335 | <p>I figured it out -- I had to add pi/2 to my thetas for the interpolation to work, so in the end need to apply the following transformation for the image to render correctly:</p>
<pre><code>newnew_lats = pi - new_lats
newnew_lons = pi + new_lons
</code></pre>
<p>There still seems to be a bit of an issue with the interpolation, although the seem is not so visible now. I may try a different one to compare.</p>
| 1 | 2016-08-16T17:47:55Z | [
"python",
"matplotlib",
"maps",
"astronomy",
"healpy"
] |
Healpy coordinate error after interpolation: appearance of bisector | 38,975,961 | <p>I have a coarse skymap made up of 128 points, of which I would like to make a smooth healpix map (see attached Figure, LHS). Figures referenced in the text:</p>
<p><img src="http://i.stack.imgur.com/bv9P0.jpg" alt="here"></p>
<p>I load my data, then make new longitude and latitude arrays of the appropriate pixel length for the final map (with e.g. nside=32). </p>
<p>My input data are:</p>
<pre><code>lats = pi/2 + ths # theta from 0, pi, size 8
lons = phs # phi from 0, 2pi, size 16
data = sky_data[0] # shape (8,16)
</code></pre>
<p>New lon/lat array size based on number of pixels from nside:</p>
<pre><code>nside = 32
pixIdx = hp.nside2npix(nside) # number of pixels I can get from this nside
pixIdx = np.arange(pixIdx) # pixel index numbers
</code></pre>
<p>I then find the new data values for those pixels by interpolation, and then convert back from angles to pixels.</p>
<pre><code># new lon/lat
new_lats = hp.pix2ang(nside, pixIdx)[0] # thetas I need to populate with interpolated theta values
new_lons = hp.pix2ang(nside, pixIdx)[1] # phis, same
# interpolation
lut = RectSphereBivariateSpline(lats, lons, data, pole_values=4e-14)
data_interp = lut.ev(new_lats.ravel(), new_lons.ravel()) #interpolate the data
pix = hp.ang2pix(nside, new_lats, new_lons) # convert latitudes and longitudes back to pixels
</code></pre>
<p>Then, I construct a healpy map with the interpolated values:</p>
<pre><code>healpix_map = np.zeros(hp.nside2npix(nside), dtype=np.double) # create empty map
healpix_map[pix] = data_interp # assign pixels to new interpolated values
testmap = hp.mollview(healpix_map)
</code></pre>
<p>The result of the map is the upper RHS of the attached Figure.</p>
<p>(Forgive the use of jet -- viridis doesn't have a "white" zero, so using that colormap adds a blue background.)</p>
<p>The map doesn't look right: you can see from the coarse map in the Figure that there should be a "hotspot" on the lower RHS, but here it appears in the upper left.</p>
<p>As a sanity check, I used matplotlib to make a scatter plot of the interpolated points in a mollview projection, Figure 2, where I removed the edges of the markers to make it look like a map ;)</p>
<pre><code>ax = plt.subplot(111, projection='astro mollweide')
ax.grid()
colors = data_interp
sky=plt.scatter(new_lons, new_lats-pi/2, c = colors, edgecolors='none', cmap ='jet')
plt.colorbar(sky, orientation = 'horizontal')
</code></pre>
<p>You can see that this map, lower RHS of attached Figure, produces exactly what I expect! So the coordinates are ok, and I am completely confused. </p>
<p>Has anyone encountered this before? What can I do? I'd like to use the healpy functions on this and future maps, so just using matplotlib isn't an option.</p>
<p>Thanks!</p>
| 1 | 2016-08-16T13:12:57Z | 38,983,260 | <p>I'm no expert in healpix (actually I've never used it before - I'm a particle physicist), but as far as I can tell it's just a matter of conventions: in a Mollweide projection, healpy places the north pole (positive latitude) at the bottom of the map, for some reason. I'm not sure why it would do that, or whether this is intentional behavior, but it seems pretty clear that's what is happening. If I mask out everything below the equator, i.e. keep only the positive-latitude points</p>
<pre><code>mask = new_lats - pi/2 > 0
pix = hp.ang2pix(nside, new_lats[mask], new_lons[mask])
healpix_map = np.zeros(hp.nside2npix(nside), dtype=np.double)
healpix_map[pix] = data_interp[mask]
testmap = hp.mollview(healpix_map)
</code></pre>
<p>it comes up with a plot with no data above the center line:</p>
<p><a href="http://i.stack.imgur.com/cvGBg.png" rel="nofollow"><img src="http://i.stack.imgur.com/cvGBg.png" alt="masked plot from healpy"></a></p>
<p>At least it's easy enough to fix. <code>mollview</code> admits a <code>rot</code> parameter that will effectively rotate the sphere around the viewing axis before projecting it, and a <code>flip</code> parameter which can be set to <code>'astro'</code> (default) or <code>'geo'</code> to set whether east is shown at the left or right. A little experimentation shows that you get the coordinate system you want with</p>
<pre><code>hp.mollview(healpix_map, rot=(180, 0, 180), flip='geo')
</code></pre>
<p>In the tuple, the first two elements are longitude and latitude of the point to set in the center of the plot, and the third element is the rotation. All are in degrees. With no mask it gives this:</p>
<p><a href="http://i.stack.imgur.com/Rjas5.png" rel="nofollow"><img src="http://i.stack.imgur.com/Rjas5.png" alt="unmasked rotated image"></a></p>
<p>which I believe is just what you're looking for.</p>
| 0 | 2016-08-16T19:46:40Z | [
"python",
"matplotlib",
"maps",
"astronomy",
"healpy"
] |
How to apply salt and pepper noise to only specific part of the image using python? | 38,975,969 | <p>I have a image of size (1200 X 1000) and I am creating multiple patches (using sliding window of 256 X 256 with a stride of 10) out of it. My ultimate goal to supply the patches to the convolutional neural networks. I wish to introduce some salt and pepper noise to the patches generated out of the image. The image is nothing but screenshot of a webpage. Now I wish to make sure that the salt and pepper noise which I am adding doesn't fall on the HTML object regions of the patch which is generated. For e.g. Suppose I have radiobutton, textbox, selection dropwdown and buttons in the patch, I need to make sure that the noise generated shouldn't fall on these objects in the patch. Other than that, it could fall inside any other region in the patch.</p>
<p>I have written code for salt and pepper noise as follows:</p>
<pre><code> import numpy as np
import os
import cv2
def noisy(image):
row,col,ch = image.shape
s_vs_p = 0.5
amount = 0.004
out = image
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
</code></pre>
<p>I have the coordinates of the html objects in the json file and have read and stored it into list of objects in my program. It contains X-Coord, Y-Coord, Width, Height and Type of the HTML object.</p>
<p>I have created a label matrix which is replica of the original image which has 5 classes:</p>
<p>0 : it is the default class value (i.e. is the region of the image excluding the HTML objects)
1: it is the value stored in the matrix for Textbox in the image</p>
<p>2: it is the value stored in the matrix for Button in the image</p>
<p>3: it is the value stored in the matrix for RadioButton in the image</p>
<p>4: it is the value stored in the matrix for selection in the image</p>
<p>So each of these values will represent specific HTML objects of the screen shot image in my Label Matrix.</p>
<p>Now, using the Label Matrix, How do I ensure that salt and pepper noise doesn't fall in the regions of the HTML objects in the patch created, is my challenge here.</p>
| 0 | 2016-08-16T13:13:12Z | 38,976,197 | <p>It's kind of crude, but why don't you apply the noise uniformly on a copy of the original picture, then copy the patches of each object from the original image back on top of that noisy image?</p>
<p><strong>EDIT after you rephrased your question</strong></p>
<p>Basically, you need to test whether <code>coords</code> falls on a place where your mask (your "label matrix") is equal to 0.
Here is what you could do (or something in that vein, I can't say my code is very pretty):</p>
<pre><code>out = np.zeros((26,26))
# salt coordinates
coords = [np.random.randint(0,26,50), np.random.randint(0,26,50)]
# mask - 0 are regions where salt can be applied, otherwise don't touch
mask = np.zeros(out.shape)
mask[:13,:13] = 1
mask[-13:,-13:] = 2
# where does the salt coordinates land on the mask
a = mask[coords]
# find points where mask is 0
b, = np.nonzero(a==0)
# copy from coords only where mask is 0
valid_coords = np.array(coords)[:,b]
# apply salt on valid coordinates
out[valid_coords.tolist()]=1
</code></pre>
<p><a href="http://i.stack.imgur.com/nvXFk.png" rel="nofollow"><img src="http://i.stack.imgur.com/nvXFk.png" alt="enter image description here"></a></p>
| 2 | 2016-08-16T13:24:50Z | [
"python",
"opencv",
"numpy",
"image-processing"
] |
python partial with keyword arguments | 38,975,975 | <p>I have a function that takes 3 keyword parameters. It has default values for x and y and I would like to call the function for different values of z using map. When I run the code below I get the following error:</p>
<blockquote>
<p>foo() got multiple values for keyword argument 'x'</p>
</blockquote>
<pre><code>def foo(x =1, y = 2, z = 3):
print 'x:%d, y:%d, z:%d'%(x, y, z)
if __name__ == '__main__':
f1 = functools.partial(foo, x= 0, y = -6)
zz = range(10)
res = map(f1, zz)
</code></pre>
<p>Is there a Pythonic way to solve this problem?</p>
| 0 | 2016-08-16T13:13:28Z | 38,976,079 | <p>When trying to call <code>res = map(f1, zz)</code> internally it actually looks like <code>[f1(i) for i in range(10)</code>. As you can see you call <code>f1</code> function with only one positional argument (in this case <code>f1(x=i)</code>). A possible solution would be to do something like this</p>
<pre><code>res = [f1(z=i) for i in range(10)]
</code></pre>
| 1 | 2016-08-16T13:18:49Z | [
"python",
"partial"
] |
python partial with keyword arguments | 38,975,975 | <p>I have a function that takes 3 keyword parameters. It has default values for x and y and I would like to call the function for different values of z using map. When I run the code below I get the following error:</p>
<blockquote>
<p>foo() got multiple values for keyword argument 'x'</p>
</blockquote>
<pre><code>def foo(x =1, y = 2, z = 3):
print 'x:%d, y:%d, z:%d'%(x, y, z)
if __name__ == '__main__':
f1 = functools.partial(foo, x= 0, y = -6)
zz = range(10)
res = map(f1, zz)
</code></pre>
<p>Is there a Pythonic way to solve this problem?</p>
| 0 | 2016-08-16T13:13:28Z | 38,976,247 | <p><code>map(f1, zz)</code> tries to call the function <code>f1</code> on every element in <code>zz</code>, but it doesn't know with which arguments to do it. <code>partial</code> redefined <code>foo</code> with <code>x=0</code> but <code>map</code> will try to reassign <code>x</code> because it uses positional arguments.</p>
<p>To counter this you can either use a simple list comprehension as in <a href="http://stackoverflow.com/a/38976079/1453822">@mic4ael's</a> answer, or define a lambda inside the <code>map</code>:</p>
<pre><code>res = map(lambda z: f1(z=z), zz)
</code></pre>
<p>Another solution would be to change the order of the arguments in the function's signature:</p>
<pre><code>def foo(z=3, x=1, y=2):
</code></pre>
| 2 | 2016-08-16T13:27:23Z | [
"python",
"partial"
] |
Group by and filter max(date) between two dates in elastic search | 38,976,025 | <p>Currently we are able to group by customer_id in elastic search.</p>
<p>Following is the document structure</p>
<pre><code>{
"order_id":"6",
"customer_id":"1",
"customer_name":"shailendra",
"mailing_addres":"shailendra@gmail.com",
"actual_order_date":"2000-04-30",
"is_veg":"0",
"total_amount":"2499",
"store_id":"276",
"city_id":"12",
"payment_mode":"cod",
"is_elite":"0",
"product":["1","2"],
"coupon_id":"",
"client_source":"1",
"vendor_id":"",
"vendor_name: "",
"brand_id":"",
"third_party_source":""
}
</code></pre>
<p>Now we need to filter the group to find the documents</p>
<ol>
<li>last ordered date between two dates</li>
<li>first order date between two dates</li>
</ol>
<p>How can we achieve this ?</p>
| 1 | 2016-08-16T13:16:03Z | 38,982,827 | <p>You can try with the query below. Within each customer bucket, we further filter all document between two dates (here I've taken the month of August 2016) and then we run a <code>stats</code> aggregation on the date field. The <code>min</code> value will be the first order date and the <code>max</code> value will be the last order date.</p>
<pre><code>{
"aggs": {
"customer_ids": {
"terms": {
"field": "customer_id"
},
"aggs": {
"date_filter": {
"filter": {
"range": {
"actual_order_date": {
"gt": "2016-08-01T00:00:00.000Z",
"lt": "2016-09-01T00:00:00.000Z"
}
}
},
"aggs": {
"min_max": {
"stats": {
"field": "actual_order_date"
}
}
}
}
}
}
}
}
</code></pre>
| 0 | 2016-08-16T19:17:05Z | [
"python",
"elasticsearch"
] |
Receive non-standard UDP broadcast python | 38,976,068 | <p>I am having great difficulty receiving a UDP broadcast in Python. A device connected to PC via ethernet broadcasts messages on a specific address and port. I have tried numerous multicast python examples found online but I can never receive the data. Using wireshark I can see the UDP broadcasts are reaching the PC.</p>
<p><a href="http://i.stack.imgur.com/BcOhy.png" rel="nofollow"><img src="http://i.stack.imgur.com/BcOhy.png" alt="Wireshark capture"></a></p>
<p>I have tried on OSX and Linux and neither work. I can only assume the messages are not being received because the device uses a non standard UDP structure, i.e. no checksum validation etc</p>
<p>Any ideas on how to receive these UDP broadcasts?</p>
<p>Thanks!</p>
<p>Edit: In the simplest form the current code would be:</p>
<pre><code>from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('239.255.60.60',4876))
m=s.recvfrom(1024)
print (m[0])
</code></pre>
<p>However I have tried additional multicast examples such as <a href="http://stackoverflow.com/questions/603852/multicast-in-python">Multicast in Python</a> and am yet to be able to receive ANYTHING!</p>
| 0 | 2016-08-16T13:18:20Z | 38,977,311 | <p>You are not receiving the broadcast because you are not using the broadcast address. </p>
<p>Either use:</p>
<pre><code>s.bind(('',4876))
</code></pre>
<p>Or the correct broadcast address for your ip.</p>
| 0 | 2016-08-16T14:15:41Z | [
"python",
"udp",
"broadcast",
"multicast"
] |
Receive non-standard UDP broadcast python | 38,976,068 | <p>I am having great difficulty receiving a UDP broadcast in Python. A device connected to PC via ethernet broadcasts messages on a specific address and port. I have tried numerous multicast python examples found online but I can never receive the data. Using wireshark I can see the UDP broadcasts are reaching the PC.</p>
<p><a href="http://i.stack.imgur.com/BcOhy.png" rel="nofollow"><img src="http://i.stack.imgur.com/BcOhy.png" alt="Wireshark capture"></a></p>
<p>I have tried on OSX and Linux and neither work. I can only assume the messages are not being received because the device uses a non standard UDP structure, i.e. no checksum validation etc</p>
<p>Any ideas on how to receive these UDP broadcasts?</p>
<p>Thanks!</p>
<p>Edit: In the simplest form the current code would be:</p>
<pre><code>from socket import *
s=socket(AF_INET, SOCK_DGRAM)
s.bind(('239.255.60.60',4876))
m=s.recvfrom(1024)
print (m[0])
</code></pre>
<p>However I have tried additional multicast examples such as <a href="http://stackoverflow.com/questions/603852/multicast-in-python">Multicast in Python</a> and am yet to be able to receive ANYTHING!</p>
| 0 | 2016-08-16T13:18:20Z | 38,979,715 | <p>Ok found the answer, rather isolated to this scenario and kicking myself for overlooking it.</p>
<p>The device connected via ethernet was waiting to be assigned an IP address!! Wireshark must capture network traffic at a lower level than python.</p>
<p>Anyway manually assigned the device an ip address and now it is working. Much relief.</p>
| 0 | 2016-08-16T16:10:56Z | [
"python",
"udp",
"broadcast",
"multicast"
] |
How to check if website is listed in DMOZ from Python? | 38,976,089 | <p>I need to check if website is listed in DMOZ using Python script. How can I do it? I'm trying to do it like this:</p>
<pre><code>import urllib2
search = "http://www.dmoz.org/search?q="
domain = "example.com"
r = urllib2.urlopen(search+domain).read()
</code></pre>
<p>It returns html code. I don't understand what should I search in that html code to check if website is listed in DMOZ. Please help me :)</p>
| -1 | 2016-08-16T13:19:16Z | 38,976,796 | <p>If you look inside returned HTML you will see <code><!---------- SITES RESULTS ----------></code> comment with <code><section class="results sites"></code> section. Inside this section you will find <code><div class="site-item"></code>. Several <code><div></code> deeper you can see what you are looking for:</p>
<pre><code><div class="site-url">
...
</div>
</code></pre>
<p>Site itself and it's sub-domains listed there. </p>
<p>If your site is not in catalog there will be no <code><div class="site-item"></code>. Search for it in your Python script.</p>
| 1 | 2016-08-16T13:53:12Z | [
"python",
"django"
] |
Python - how to get value from a text field in another module | 38,976,165 | <p>I've written a simple program with a tkinter GUI. The entire code is in one big module and I'd like to split it into two or three modules to separate the logic from the GUI.
This is the example code:</p>
<h1>main.py:</h1>
<pre><code>import gui
inst1 = gui.guitest()
</code></pre>
<h1>gui.py:</h1>
<pre><code>import tkinter, defs
class guitest:
def __init__(self):
win1 = tkinter.Tk()
self.field1 = tkinter.Text(win1)
self.field1.grid(column = 0, row = 0)
self.but1 = tkinter.Button(win1, text='click',
command=defs.getVar)
self.but1.grid(column = 1, row = 0)
win1.mainloop()
</code></pre>
<h1>defs.py:</h1>
<pre><code>def getVar():
captured = str(field1.get(1.0))
</code></pre>
<p>I can't get getVar to work; I'd like it to get the value from the Text field, but after trying different solutions all I get are Name or Attribute Errors.
Is there any possibility to make it work that way? Or maybe my idea is completely wrong? If it is, then please let me know how to do it. I wonder if there are more problems with this code.</p>
| 1 | 2016-08-16T13:23:10Z | 38,976,828 | <p>Alright, let's start from the beginning, here's a working example of your code:</p>
<pre><code>import tkinter
class guitest:
def __init__(self):
win1 = tkinter.Tk()
self.field1 = tkinter.Text(win1)
self.field1.grid(column=0, row=0)
self.but1 = tkinter.Button(win1, text='click', command=self.getVar)
self.but1.grid(column=1, row=0)
win1.mainloop()
def getVar(self):
captured = str(self.field1.get("1.0", tkinter.END))
print captured
inst1 = guitest()
</code></pre>
<p>Now, before breaking down that piece of code, you should ask yourself if the reason you want to is strong enough. In case your answer is affirmative (think it twice) one possible way to do it would be this:</p>
<hr>
<pre><code># main.py
import gui
inst1 = gui.guitest()
</code></pre>
<hr>
<pre><code># gui.py
import tkinter
import defs
class guitest:
def __init__(self):
win1 = tkinter.Tk()
self.field1 = tkinter.Text(win1)
self.field1.grid(column=0, row=0)
self.but1 = tkinter.Button(win1, text='click', command=self.getVar)
self.but1.grid(column=1, row=0)
win1.mainloop()
def getVar(self):
defs.getVar(self)
</code></pre>
<hr>
<pre><code># defs.py
import tkinter
def getVar(guitest_inst):
captured = str(guitest_inst.field1.get("1.0", tkinter.END))
print captured
</code></pre>
<p>But again, think twice before breaking down widgets like this... just saying :)</p>
| 1 | 2016-08-16T13:54:24Z | [
"python",
"user-interface",
"tkinter",
"module"
] |
How to retrieve text from a button type webelement | 38,976,308 | <p>I am trying to retrieve text from a button type webelement using Python scripting in Selenium
The HTML code of the button looks like:</p>
<pre><code><button class="list-item ng-binding" ng-click="selectLineFilter(line)" type="button">
<i class="mdi mdi-domain blue" aria-hidden="true"></i>
12063497545
</button>
</code></pre>
<p>How can I retrieve the text. I used .text, it returns an error as " 'list' object has no attribute 'text' ". Please Help.</p>
| 1 | 2016-08-16T13:30:10Z | 38,976,887 | <p>I think you are using <code>find_elements</code> which returns list of <code>WebElement</code> while <code>.text</code> works on single <code>WebElement</code>, So you should try using <code>find_element</code> as below :-</p>
<pre><code>driver.find_element_by_css_selector("button.list-item.ng-binding[type='button']").text
</code></pre>
<p>Or if you want to find all elements text with the same locator, you should try using <code>find_elements</code> and iterate through in loop as below :-</p>
<pre><code>buttons= driver.find_elements_by_css_selector("button.list-item.ng-binding[type='button']")
for button in buttons:
button.text
</code></pre>
| 1 | 2016-08-16T13:56:34Z | [
"python",
"selenium-webdriver"
] |
How to retrieve text from a button type webelement | 38,976,308 | <p>I am trying to retrieve text from a button type webelement using Python scripting in Selenium
The HTML code of the button looks like:</p>
<pre><code><button class="list-item ng-binding" ng-click="selectLineFilter(line)" type="button">
<i class="mdi mdi-domain blue" aria-hidden="true"></i>
12063497545
</button>
</code></pre>
<p>How can I retrieve the text. I used .text, it returns an error as " 'list' object has no attribute 'text' ". Please Help.</p>
| 1 | 2016-08-16T13:30:10Z | 38,977,928 | <p>use .GetAttribute("innerHTML")</p>
| 0 | 2016-08-16T14:43:55Z | [
"python",
"selenium-webdriver"
] |
How to retrieve text from a button type webelement | 38,976,308 | <p>I am trying to retrieve text from a button type webelement using Python scripting in Selenium
The HTML code of the button looks like:</p>
<pre><code><button class="list-item ng-binding" ng-click="selectLineFilter(line)" type="button">
<i class="mdi mdi-domain blue" aria-hidden="true"></i>
12063497545
</button>
</code></pre>
<p>How can I retrieve the text. I used .text, it returns an error as " 'list' object has no attribute 'text' ". Please Help.</p>
| 1 | 2016-08-16T13:30:10Z | 38,988,498 | <p>you can use the concept of this Java code :</p>
<p>WebDriver driver;</p>
<p>String a = driver.findelement(by.xpath("")).getText(); //use css or id attribute </p>
<p>System.out.println(a); //this will print the text present on the button.</p>
| 0 | 2016-08-17T05:07:48Z | [
"python",
"selenium-webdriver"
] |
Initializing a very large pandas dataframe | 38,976,431 | <p>Background: I have a sequence of images. In each image, I map a single pixel to a number. Then I want to create a pandas dataframe where each pixel is in its own column and images are rows. The reason I want to do that is so that I can use things like forward fill.</p>
<p>Challenge: I have transformed each image into a one dimensional array of numbers, each of which is about 2 million entries and I have thousands of images. Simply doing pd.DataFrame(array) is very slow (testing it on a smaller number of images). Is there a faster solution for this? Other ideas how to do this efficiently are also welcome, but using non-core different libraries may be a challenge (corporate environment).</p>
| 1 | 2016-08-16T13:35:32Z | 38,976,616 | <p>Out of curiosity, is there a reason you want to use Pandas for this? Image analysis is typically handled in matrices making NumPy a clear favorite. If I'm not mistaken, both sk-learn and PIL/IMAGE use NumPy arrays to do their analysis and operations.</p>
<p>Another option: avoid the in-memory step! Do you need to access all 1K+ images at the same time? If not, and you're operating on each one individually, you can iterate over the files and perform your operations there. For an even more efficient step, break your files into lists of 200 or so images, then use Python's MultiProcessing capabilities to analyze in parallel.</p>
<p>JIC, do you have PIL or IMAGE installed, or sk-learn? Those packages have some nice image analysis algorithms already packaged in which may save you some time in not having to re-invent the wheel.</p>
| 0 | 2016-08-16T13:44:16Z | [
"python",
"pandas",
"numpy",
"large-data"
] |
Get N terms with top TFIDF scores for each documents in Lucene (PyLucene) | 38,976,466 | <p>I am currently using PyLucene but since there is no documentation for it, I guess a solution in Java for Lucene will also do (but if anyone has one in Python it would be even better).</p>
<p>I am working with scientific publications and for now, I retrieve the keywords of those. However, for some documents there are simply no keywords. An alternative to this would be to get N words (5-8) with the highest TFIDF scores. </p>
<p>I am not sure how to do it, and also <strong>when</strong>. By when, I mean : Do I have to tell Lucene at the stage of indexing to compute these values, of it is possible to do it when searching the index. </p>
<p>What I would like to have for each query would be something like this :</p>
<pre><code>Query Ranking
Document1, top 5 TFIDF terms, Lucene score (default TFIDF)
Document2, " " , " "
...
</code></pre>
<p>What would also be possible is to first retrieve the ranking for the query, and then compute the top 5 TFIDF terms for each of these documents.</p>
<p>Does anyone have an idea how shall I do this ?</p>
| 1 | 2016-08-16T13:37:25Z | 38,986,733 | <p>If a field is <a href="http://lucene.apache.org/core/4_10_1/core/org/apache/lucene/document/FieldType.html#indexed()" rel="nofollow">indexed</a>, document frequencies can be retrieved with <a href="http://lucene.apache.org/core/4_10_1/core/org/apache/lucene/index/MultiFields.html#getTerms(org.apache.lucene.index.IndexReader,%20java.lang.String)" rel="nofollow">getTerms</a>. If a field has <a href="http://lucene.apache.org/core/4_10_1/core/org/apache/lucene/document/FieldType.html#storeTermVectors()" rel="nofollow">stored term vectors</a>, term frequencies can be retrieved with <a href="http://lucene.apache.org/core/4_10_1/core/org/apache/lucene/index/IndexReader.html#getTermVector(int,%20java.lang.String)" rel="nofollow">getTermVector</a>.</p>
<p>I also suggest looking at <a href="http://lucene.apache.org/core/4_10_1/queries/org/apache/lucene/queries/mlt/MoreLikeThis.html" rel="nofollow">MoreLikeThis</a>, which uses tf*idf to create a query similar to the document, from which you can extract the terms.</p>
<p>And if you'd like a more pythonic interface, that was my motivation for <a href="https://pypi.python.org/pypi/lupyne/" rel="nofollow">lupyne</a>:</p>
<pre><code>from lupyne import engine
searcher = engine.IndexSearcher(<filepath>)
df = dict(searcher.terms(<field>, counts=True))
tf = dict(searcher.termvector(<docnum>, <field>, counts=True))
query = searcher.morelikethis(<docnum>, <field>)
</code></pre>
| 1 | 2016-08-17T01:16:03Z | [
"java",
"python",
"lucene",
"tf-idf"
] |
Get N terms with top TFIDF scores for each documents in Lucene (PyLucene) | 38,976,466 | <p>I am currently using PyLucene but since there is no documentation for it, I guess a solution in Java for Lucene will also do (but if anyone has one in Python it would be even better).</p>
<p>I am working with scientific publications and for now, I retrieve the keywords of those. However, for some documents there are simply no keywords. An alternative to this would be to get N words (5-8) with the highest TFIDF scores. </p>
<p>I am not sure how to do it, and also <strong>when</strong>. By when, I mean : Do I have to tell Lucene at the stage of indexing to compute these values, of it is possible to do it when searching the index. </p>
<p>What I would like to have for each query would be something like this :</p>
<pre><code>Query Ranking
Document1, top 5 TFIDF terms, Lucene score (default TFIDF)
Document2, " " , " "
...
</code></pre>
<p>What would also be possible is to first retrieve the ranking for the query, and then compute the top 5 TFIDF terms for each of these documents.</p>
<p>Does anyone have an idea how shall I do this ?</p>
| 1 | 2016-08-16T13:37:25Z | 38,994,211 | <p>After digging a bit in the mailing list, I ended up having what I was looking for.</p>
<p>Here is the method I came up with :</p>
<pre><code>def getTopTFIDFTerms(docID, reader):
termVector = reader.getTermVector(docID, "contents");
termsEnumvar = termVector.iterator(None)
termsref = BytesRefIterator.cast_(termsEnumvar)
tc_dict = {} # Counts of each term
dc_dict = {} # Number of docs associated with each term
tfidf_dict = {} # TF-IDF values of each term in the doc
N_terms = 0
try:
while (termsref.next()):
termval = TermsEnum.cast_(termsref)
fg = termval.term().utf8ToString() # Term in unicode
tc = termval.totalTermFreq() # Term count in the doc
# Number of docs having this term in the index
dc = reader.docFreq(Term("contents", termval.term()))
N_terms = N_terms + 1
tc_dict[fg]=tc
dc_dict[fg]=dc
except:
print 'error in term_dict'
# Compute TF-IDF for each term
for term in tc_dict:
tf = tc_dict[term] / N_terms
idf = 1 + math.log(N_DOCS_INDEX/(dc_dict[term]+1))
tfidf_dict[term] = tf*idf
# Here I get a representation of the sorted dictionary
sorted_x = sorted(tfidf_dict.items(), key=operator.itemgetter(1), reverse=True)
# Get the top 5
top5 = [i[0] for i in sorted_x[:5]] # replace 5 by TOP N
</code></pre>
<p>I am not sure why I have to cast the <code>termsEnum</code> as a <code>BytesRefIterator</code>, I got this from a thread in the mailing list which can be found <a href="https://mail-archives.apache.org/mod_mbox/lucene-pylucene-dev/201402.mbox/%3CCAPJ5eE-WM78oZronESNAcurM3azp=ho2XHv-HS4aVr_S5V18Yg@mail.gmail.com%3E" rel="nofollow">here</a></p>
<p>Hope this will help :)</p>
| 1 | 2016-08-17T10:34:18Z | [
"java",
"python",
"lucene",
"tf-idf"
] |
devpi upload error: no commands supplied to setup.py | 38,976,483 | <p>When trying to upload to <code>devpi-4.1.0</code>, the same error occurs no matter what options I choose. The workaround is to build package and upload it as a file, but I'm not able to upload any docs.</p>
<pre><code>(tstenv) [root@master workspace]# devpi upload --formats sdist
detected devpi:upload section in /var/lib/jenkins/jobs/myproject-deploy-release/workspace/setup.cfg
using workdir /tmp/devpi29
pre-build: cleaning /var/lib/jenkins/jobs/myproject-deploy-release/workspace/dist
--> /var/lib/jenkins/jobs/myproject-deploy-release/workspace$ tstenv/bin/python setup.py sdist
warning: sdist: standard file not found: should have one of README, README.rst, README.txt
built: /var/lib/jenkins/jobs/myproject-deploy-release/workspace/dist/myproject-1.0.0.dev0.tar.gz [SDIST] 2642.98kb
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: no commands supplied
Traceback (most recent call last):
File "/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/bin/devpi", line 11, in <module>
sys.exit(main())
File "/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/lib/python3.5/site-packages/devpi/main.py", line 30, in main
return method(hub, hub.args)
File "/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/lib/python3.5/site-packages/devpi/upload.py", line 48, in main
name_version = exported.setup_name_and_version()
File "/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/lib/python3.5/site-packages/devpi/upload.py", line 311, in setup_name_and_version
report=False).splitlines()[-1].strip()
File "/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/lib/python3.5/site-packages/devpi/main.py", line 214, in popen_output
return check_output(args, cwd=str(cwd))
File "/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/lib/python3.5/site-packages/devpi_common/proc.py", line 18, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/bin/python', '/var/lib/jenkins/jobs/myproject-deploy-release/workspace/setup.py', '--name']' returned non-zero exit status 1
</code></pre>
<hr>
<p>As requested in the answers, here is the output of <code>devpi sdist upload</code>:</p>
<pre><code>(tstenv) [root@master workspace]# devpi sdist upload
usage: /var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/bin/devpi
[-h] [--version] [--debug] [-y] [-v] [--clientdir DIR]
{quickstart,use,getjson,patchjson,list,remove,user,login,logoff,index,upload,test,push,install,refresh}
...
/var/lib/jenkins/jobs/myproject-deploy-release/workspace/tstenv/bin/devpi: error: argument command: invalid choice: 'sdist' (choose from 'quickstart', 'use', 'getjson', 'patchjson', 'list', 'remove', 'user', 'login', 'logoff', 'index', 'upload', 'test', 'push', 'install', 'refresh')
</code></pre>
| 0 | 2016-08-16T13:38:02Z | 38,977,714 | <p><a href="http://doc.devpi.net/latest/quickstart-releaseprocess.html#devpi-upload-uploading-one-or-more-packages" rel="nofollow">According to documentation</a> it's just <code>devpi upload</code>.</p>
| 1 | 2016-08-16T14:34:23Z | [
"python",
"devpi"
] |
Python Error: "global name server_loop() is not defined" | 38,976,497 | <p>I have been following along the "black hat python" book and when I typed in this particular code I got the error "global name server_loop() is not defined". Here is the statement BEFORE the main() function having the error:</p>
<pre><code>if listen:
server_loop()
</code></pre>
<p>and here is the server_loop() function IN the main() function:</p>
<pre><code>def server_loop():
global target
# if no target is defined, we listen on all interfaces
if (not len(target)):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-16T13:38:47Z | 38,976,707 | <p>I hope I understand the question correctly.</p>
<p>I can reproduce your case easily:</p>
<pre><code>something()
def something():
pass
</code></pre>
<p>I get</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "<module1>", line 1, in <module>
NameError: name 'something' is not defined
</code></pre>
<p>If I call <code>something</code> after having defined it it works.</p>
<p>You <em>have</em> to define functions before using them.</p>
<p>I suppose that your book just gave the information in the inverted order (top => down, from global/main to implementation/function) expecting that you knew that as a lot of languages, python requires function definition before function call.
Personally I prefer single-block examples that you can type (or copy/paste) without thinking and it works right away.</p>
| 0 | 2016-08-16T13:48:40Z | [
"python",
"sockets",
"hacking"
] |
Python Flask Restful API | 38,976,532 | <p>Part of my Flask code:</p>
<pre><code>@app.route('/api/post', methods=['POST'])
def post():
body = request.get_json()
json_body = json.loads(body)
new_id = mongo.db.Projects.insert(json_body)
return str(new_id)
</code></pre>
<p>Script to post a new database entry:</p>
<pre><code>payload = { 'ProjectName' : 'KdB Test Project' }
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
r = requests.post('http://localhost:5000/api/post', headers=headers, data=json.dumps(payload))
</code></pre>
<p>I keep getting json decoder TypeError problems, e.g.</p>
<pre><code>TypeError: expected string or buffer
2016-08-16 15:19:31,388 - werkzeug - INFO - 127.0.0.1 - - [16/Aug/2016 15:19:31] "POST /api/post HTTP/1.1" 500 -
</code></pre>
<p>I have tried several things, incl. posting strings. Any clue what is wrong with the way I post a dictionary?
The problem appears to be at the point of body = request.get_json(). I don't think I am picking up any data...</p>
| 1 | 2016-08-16T13:40:14Z | 38,976,826 | <p>You don't need to <code>loads</code> request message to get dict format. Information stored in <code>body</code> variable is already in dict form. Simply doing the following should remove the error:</p>
<pre><code>@app.route('/api/post', methods=['POST'])
def post():
body = request.get_json()
# json_body = json.loads(body)
new_id = mongo.db.Projects.insert( body )
return str( new_id )
</code></pre>
| 4 | 2016-08-16T13:54:20Z | [
"python",
"json",
"flask",
"flask-restful"
] |
Python Flask Restful API | 38,976,532 | <p>Part of my Flask code:</p>
<pre><code>@app.route('/api/post', methods=['POST'])
def post():
body = request.get_json()
json_body = json.loads(body)
new_id = mongo.db.Projects.insert(json_body)
return str(new_id)
</code></pre>
<p>Script to post a new database entry:</p>
<pre><code>payload = { 'ProjectName' : 'KdB Test Project' }
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
r = requests.post('http://localhost:5000/api/post', headers=headers, data=json.dumps(payload))
</code></pre>
<p>I keep getting json decoder TypeError problems, e.g.</p>
<pre><code>TypeError: expected string or buffer
2016-08-16 15:19:31,388 - werkzeug - INFO - 127.0.0.1 - - [16/Aug/2016 15:19:31] "POST /api/post HTTP/1.1" 500 -
</code></pre>
<p>I have tried several things, incl. posting strings. Any clue what is wrong with the way I post a dictionary?
The problem appears to be at the point of body = request.get_json(). I don't think I am picking up any data...</p>
| 1 | 2016-08-16T13:40:14Z | 38,976,837 | <p><a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request.get_json" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#flask.Request.get_json</a></p>
<p><code>get_json</code> is probably returning a dict already, so you don't need to call <code>json.loads(body)</code> (this is what most likely causes the <code>TypeError</code>).</p>
<pre><code>@app.route('/api/post', methods=['POST'])
def post():
json_body = request.get_json()
new_id = mongo.db.Projects.insert(json_body)
return str(new_id)
</code></pre>
| 0 | 2016-08-16T13:54:48Z | [
"python",
"json",
"flask",
"flask-restful"
] |
Is there any way to get the AST (Abstract Syntax Tree) of a block of code in Java rather than of the entire class ? | 38,976,558 | <p>I tried using Javalang module available in python to get the AST of Java source code , but it requires an entire class to generate the AST . Passing a block of code like an 'if' statement throws an error . Is there any other way of doing it ?
PS : I am preferably looking for a python module to do the task.
Thanks </p>
| 2 | 2016-08-16T13:41:08Z | 38,991,801 | <p>OP is interested in a non-Python answer.</p>
<p>Our <a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow">DMS Software Reengineering Toolkit</a> with its <a href="http://www.semanticdesigns.com/Products/FrontEnds/JavaFrontEnd.html?" rel="nofollow">Java Front End</a> can accomplish this.</p>
<p>DMS is a general purpose tools for parsing/analyzing/transforming code, parameterized by langauge definitions (including grammars). Given a langauge definition, DMS can easily be invoked on a source file/stream representing the goal symbol for a grammar by calling the Parse method offered by the langauge parameter, and DMS will build a tree for the parsed string. Special support is provided for parsing source file/streams for arbitrary nonterminals as defined by the langauge grammar; DMS will build an AST whose root is that nonterminal, parsing the source according to the subgrammar define by that nonterminal.</p>
<p>Once you have the AST, DMS provides lots of support for visiting the AST, inspecting/modifying nodes, carry out source-to-source transformations on the AST using surface syntax rewrite rules. Finally you can prettyprint the modified AST and get back valid source code. (If you have only parsed a code fragment for a nonterminal, what you get back is valid code for that nonterminal).</p>
<p>If OP is willing to compare complete files instead of snippets, our Smart Differencer might be useful out of the box. SmartDifferencer builds ASTs of its two input files, finds the smallest set of conceptual edits (insert, delete, move, copy, rename) over structured code elemnts that explains the differences, and reports that difference.</p>
| 0 | 2016-08-17T08:36:14Z | [
"java",
"python",
"abstract-syntax-tree"
] |
Using for loops in sqlalchemy query | 38,976,632 | <p>So i wanna use a for loop in a query and pull results if a record's field is equal to an object's property (in a list of objects) how do i do that? This is my code:</p>
<pre><code>you = session.query(Users).filter_by(id=login_session['userid']).first()
friends = session.query(Friends).filter_by(user_id=login_session['userid']).all()
dashboard = session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
</code></pre>
<p>but then i get this:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pearadox6/travellr/app.py", line 423, in feed
dashboard = session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
File "<string>", line 1, in <lambda>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 51, in generate
fn(self, *args[1:], **kw)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 1216, in filter
criterion = expression._literal_as_text(criterion)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/expression.py", line 1521, in _literal_as_text
"SQL expression object or string expected."
ArgumentError: SQL expression object or string expected.
</code></pre>
<p>Why?</p>
| 0 | 2016-08-16T13:45:18Z | 38,976,702 | <blockquote>
<p>Why?</p>
</blockquote>
<p>Because you can't pass a generator object as an argument for <code>filter</code>:</p>
<pre><code>session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
</code></pre>
<p>Use <code>in_</code> with a list instead:</p>
<pre><code>session.query(Markers).filter(Markers.owner.in_([f.friend_id for f in friends)]).all()
</code></pre>
| 2 | 2016-08-16T13:48:30Z | [
"python",
"postgresql",
"sqlalchemy"
] |
python quits unexpectedly running pyautogui | 38,976,711 | <p>I'm running Python 2.7.12 installed with homebrew on my Mac OS X 10.11 and trying to use pyautogui. However, it keeps crashing ("Python quit unexpectedly.") when I try to run it as an imported module in another .py file. Like this:</p>
<pre><code> # gui.py
import pyautogui
def myfunction():
pyautogui.click( 100 , 200 )
if __name__ == '__main__':
myfunction()
# another.py
import gui
gui.myfunction()
</code></pre>
<p>It works fine when I run "python gui.py" alone. But when I try to run another.py, even without calling any function from gui.py, Python would crash every single time. After narrowing it down with line by line elimination, it seems it's the</p>
<pre><code> import pyautogui
</code></pre>
<p>that caused the crash. Any idea why? All I know is when included as a module, a .pyc file is created. I tried to delete it and run again, but didn't do anything.</p>
<p>Thank you!</p>
| 2 | 2016-08-16T13:48:44Z | 39,023,362 | <p>I got it! This is because I'm importing pyscreenshot, and there is a conflict between it and pyautogui. Both use pillow and probably have some different reference to it that I'm not knowledgeable enough to tell. But as soon as I removed the pyscreenshot, pyautogui is running normal.</p>
| 0 | 2016-08-18T16:35:21Z | [
"python",
"osx",
"compilation",
"pyautogui"
] |
how to get proxy ip and port from text file | 38,976,741 | <p>how to get proxy ip and port from text file </p>
<p>Code :</p>
<pre><code>import re , urllib , urllib2 , socks , socket
proxys = open('IPs.txt', 'r')
links = open('URs.txt', 'r')
#----
P = proxys.readlines()
E = links.readlines()
#----
nm = 0
#----
PROXY = P[nm]
#----
for links in E :
Post = 'id='+ links
cj = CookieJar()
#----
IP,PORT = PROXY.split(":")
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, IP, PORT)
socket.socket = socks.socksocket
#----
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
request = urllib2.Request('https://google.com/', Post)
# ----------------- ++
nm+=1
PROXY = P[nm]
# ----------------- ++
</code></pre>
<p>IPs.txt:</p>
<pre><code>96.47.156.166:10200
96.47.88.7:14328
97.88.243.210:24598
98.201.217.101:23320
</code></pre>
<p>Error Here :</p>
<pre><code>PROXY = P[0] # = 96.47.156.166:10200 #from the text file
IP,PORT = PROXY.split(":")
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "96.47.156.166", "10200")
</code></pre>
<p>i need it like this to work :</p>
<pre><code> socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "96.47.156.166", 10200) #withot ""
</code></pre>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
| 2 | 2016-08-16T13:49:55Z | 38,976,845 | <p>You need to convert <code>PORT</code> to an <code>int</code>:</p>
<pre><code>socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, IP, int(PORT))
</code></pre>
<p>Note that this will raise a <code>ValueError</code> if for some whatever reason <code>PORT</code> can't be converted, so you may want to catch it.</p>
<p>Depending on the structure of your file, it is most likely that <code>PORT</code> will include a <code>'\n'</code> in the end. You will need to get rid of it with <code>strip</code> before trying to convert it to an <code>int</code>.</p>
<pre><code>try:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, IP, int(PORT.strip()))
except ValueError:
print('Illegal port')
</code></pre>
| 2 | 2016-08-16T13:55:09Z | [
"python",
"python-2.7",
"websocket",
"socks"
] |
Pandas apply function to groups of columns and indexing | 38,976,800 | <p>Given a dataframe <code>df</code> consisting of multiple columns:</p>
<pre><code>Col1 Col2 Col3 Col4 Col5 Col6
4 2 5 3 4 1
8 3 9 7 4 5
1 3 6 7 4 7
</code></pre>
<p>I want to apply a function <code>func</code> for a group of columns</p>
<pre><code>df.apply(lambda x: func(x[['Col1', 'Col2', 'Col3']]), axis=1)
</code></pre>
<p>This works fine as expected. However, using</p>
<pre><code>df.apply(lambda x: func(x.iloc[:,0:3]), axis=1)
</code></pre>
<p>I get the following error:</p>
<blockquote>
<p>IndexingError: ('Too many indexers', u'occurred at index 0')</p>
</blockquote>
<p>Since I want to automate the function using a loop in groups of three columns I would prefer using <strong>pandas</strong> <code>iloc</code> or <code>ix</code> as an indexing method.</p>
<p>Can someone please explain this error?</p>
| 2 | 2016-08-16T13:53:21Z | 38,976,883 | <p>You need remove first <code>:</code> in <code>iloc</code>, because working with <code>Series</code> in <code>apply</code>, not with <code>DataFrame</code>:</p>
<pre><code>print (df.apply(lambda x: func(x.iloc[0:3]), axis=1))
</code></pre>
<p>Test:</p>
<pre><code>def func(x):
return x.sum()
print (df.apply(lambda x: func(x[['Col1', 'Col2', 'Col3']]), axis=1))
0 11
1 20
2 10
dtype: int64
print (df.apply(lambda x: func(x.iloc[0:3]), axis=1))
0 11
1 20
2 10
dtype: int64
</code></pre>
<hr>
<p>You can also check it by <code>print</code> (print return nothing, so in output are <code>None</code>):</p>
<pre><code>print (df.apply(lambda x: print(x.iloc[0:3]), axis=1))
dtype: int64
Col1 4
Col2 2
Col3 5
Name: 0, dtype: int64
Col1 8
Col2 3
Col3 9
Name: 1, dtype: int64
Col1 1
Col2 3
Col3 6
Name: 2, dtype: int64
0 None
1 None
2 None
</code></pre>
| 1 | 2016-08-16T13:56:23Z | [
"python",
"pandas",
"indexing",
"dataframe",
"multiple-columns"
] |
python/sqlite3: multiple columns with the same name not correctly treated by sqlite3.Row | 38,976,811 | <p>I am accessing a sqlite database taken from my phone (specifically, from the gnucash app). I want to access the columns by name, so I set conn.row_factory = sqlite3.Row on my connection. Then I join two tables with the following query:</p>
<pre><code>>>> rows = curr.execute('select * from splits s left join transactions t on s.transaction_uid = t.uid')
</code></pre>
<p>The column names are correctly reported, but without the table alias:</p>
<pre><code>>>> row = rows.fetchone()
>>> print(row.keys())
['_id', 'uid', 'memo', 'type', 'value_num', 'value_denom', 'quantity_num', 'quantity_denom', 'account_uid', 'transaction_uid', 'created_at', 'modified_at', '_id', 'uid', 'name', 'description', 'timestamp', 'is_exported', 'is_template', 'currency_code', 'scheduled_action_uid', 'created_at', 'modified_at', 'commodity_uid']
</code></pre>
<p>so, when I access values, I get the same values for duplicate columns:</p>
<pre><code>>>> for k in row.keys():
... print(k, row[k])
...
_id 3690
uid a93bf33079924d82afcca4fd6acc0823
memo None
type CREDIT
value_num 1882.9999999999998
value_denom 100
quantity_num 1882.9999999999998
quantity_denom 100
account_uid sbilancio-e966169c8dfe
transaction_uid 2ad90ed9766b4716b8e443c8c19b35a0
created_at 2015-11-03 13:55:03
modified_at 2015-11-03 13:55:03
_id 3690
uid a93bf33079924d82afcca4fd6acc0823
name Sbilancio
description
timestamp 1412340295000
is_exported 0
is_template 0
currency_code EUR
scheduled_action_uid None
created_at 2015-11-03 13:55:03
modified_at 2015-11-03 13:55:03
commodity_uid None
</code></pre>
<p>The values for _id, uid, created_at and modified_at come from SPLITS, and the one from TRANSACTIONS are not available.</p>
<p>You may tell me I shouldn't use "SELECT *", but that doesn't solve the problem:</p>
<pre><code>>>> rows = curr.execute('select s._id, t._id from splits s left join transactions t on s.transaction_uid = t.uid where s._id = 3758')
>>> row = rows.fetchone()
>>> print(row.keys())
['_id', '_id']
>>> for k in row.keys():
... print(k, row[k])
...
_id 3758
_id 3758
</code></pre>
<p>while using column aliases, luckily, works:</p>
<pre><code>>>> rows = curr.execute('select s._id s_id, t._id t_id from splits s left join transactions t on s.transaction_uid = t.uid where s._id = 3758')
>>> row = rows.fetchone()
>>> print(row.keys())
['s_id', 't_id']
</code></pre>
<p>Would you consider this behaviour a bug? And what would you expect from sqlite3, in such a case? I think that if table aliases are given they should be prepended to column names, otherwise a sqlite3.OperationalError exception should be thrown, as for syntax errors in the query. Other ideas?</p>
| 2 | 2016-08-16T13:53:55Z | 38,980,316 | <p>The <a href="http://www.sqlite.org/c3ref/column_name.html" rel="nofollow">documentation</a> says:</p>
<blockquote>
<p>The name of a result column is the value of the "AS" clause for that column, if there is an AS clause. If there is no AS clause then the name of the column is unspecified.</p>
</blockquote>
<p>So when you have a row with two columns that happen to have the same name, it is not possible to access both of them <em>by their name</em>.
How should Python know that <code>row['_id']</code> and <code>row['_id']</code> should be different?</p>
<p>You either have to explicitly rename some columns, or access the row values by their position (<code>row[0]</code> and <code>row[1]</code>).</p>
| 0 | 2016-08-16T16:44:41Z | [
"python",
"sqlite3"
] |
In Python, change the attributes of a class instance which is passed as input to __init__ | 38,977,005 | <p>Consider the following code, which generates a (basic) GUI:</p>
<pre><code>import Tkinter as tk
class Game:
def __init__(self, root):
self.root = root
button = tk.Button(root, text="I am a button")
button.pack()
root = tk.Tk()
root.title("This is a game window") # I would like to move this code to the Game class
game = Game(root)
root.mainloop()
</code></pre>
<p>The resulting GUI looks like this:</p>
<p><a href="http://i.stack.imgur.com/MC50T.png" rel="nofollow"><img src="http://i.stack.imgur.com/MC50T.png" alt="enter image description here"></a></p>
<p>I'd like to achieve the same effect but move the setting of the window title to the class definition. (I've tried <code>self.root.title = "This is a game window"</code> in the <code>__init__</code> but this seemed to have no effect). Is this possible?</p>
| 4 | 2016-08-16T14:01:43Z | 38,977,181 | <p>Sure. You need to call the <code>.title</code> method. Doing </p>
<pre><code>root.title = "This is a game window"
</code></pre>
<p>doesn't set the title, it overwrites the method with the string.</p>
<pre><code>import Tkinter as tk
class Game:
def __init__(self, root):
self.root = root
root.title("This is a game window")
button = tk.Button(root, text="I am a button")
button.pack()
root = tk.Tk()
game = Game(root)
root.mainloop()
</code></pre>
<p>You <em>could</em> also do <code>self.root.title("This is a game window")</code> but it's more typing, and using <code>self.root</code> is slightly less efficient than using the <code>root</code> parameter that was passed to the <code>__init__</code> method, since <code>self.root</code> requires an attribute lookup but <code>root</code> is a simple local variable.</p>
| 6 | 2016-08-16T14:09:11Z | [
"python",
"tkinter"
] |
elif statement not running? | 38,977,008 | <p>The aim is to open the page get url nr 18, swap the url with url in position 18 and rerun 7 times but my code is stuck after getting position 18, why is the elif not running in line 24 ? (no traceback given, program just sitting there)</p>
<pre><code>import urllib
from BeautifulSoup import *
#not the real url
url= ('http://abc.googl.com')
count=7
position = 0
#n will be used to check that the code i running
n=0
while count >= 0:
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup('a')
for tag in tags:
x= tag.get('href', None)
position=position+1
if position <= 18:
n=n+1
print 'calculating', n
print x
elif position == 18:
url=(x)
print 'new url', x
count=count-1
print 'new count', count
position=0
if count == 0:
print "done"
print x
</code></pre>
| 0 | 2016-08-16T14:01:46Z | 38,977,059 | <pre><code>if position <= 18:
...
elif position == 18:
...
</code></pre>
<p>Both the <code>if</code> and <code>elif</code> branches are catching <code>position</code> if <code>position == 18</code> (note the <code><=</code> in the <code>if</code> statement), so the <code>elif</code> branch will never be executed.</p>
| 2 | 2016-08-16T14:03:46Z | [
"python",
"python-2.7"
] |
elif statement not running? | 38,977,008 | <p>The aim is to open the page get url nr 18, swap the url with url in position 18 and rerun 7 times but my code is stuck after getting position 18, why is the elif not running in line 24 ? (no traceback given, program just sitting there)</p>
<pre><code>import urllib
from BeautifulSoup import *
#not the real url
url= ('http://abc.googl.com')
count=7
position = 0
#n will be used to check that the code i running
n=0
while count >= 0:
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup('a')
for tag in tags:
x= tag.get('href', None)
position=position+1
if position <= 18:
n=n+1
print 'calculating', n
print x
elif position == 18:
url=(x)
print 'new url', x
count=count-1
print 'new count', count
position=0
if count == 0:
print "done"
print x
</code></pre>
| 0 | 2016-08-16T14:01:46Z | 38,977,069 | <p>Your <code>if</code> <em>excludes</em> the <code>elif</code> condition:</p>
<pre><code>if position <= 18:
</code></pre>
<p>This matches if <code>position == 18</code> <em>too</em>. Python ignores all following <code>elif</code> conditions when a <code>if</code> or <code>elif</code> branch has matched.</p>
<p>If you want to run <em>additional</em> code for the <code>== 18</code> case, use a new <code>if</code> statement:</p>
<pre><code>if position <= 18:
# will run for all values of `position up to and including 18
if position == 18:
# will *also* be run for the `position == 18` case
</code></pre>
<p>Alternatively, fix your conditions to not overlap:</p>
<pre><code>if position < 18:
# ...
elif position == 18:
# runs only when position is exactly equal to 18
</code></pre>
<p>or</p>
<pre><code>if position <= 18:
# ...
else:
# runs when the first condition no longer matches, so position > 18
</code></pre>
| 2 | 2016-08-16T14:04:02Z | [
"python",
"python-2.7"
] |
elif statement not running? | 38,977,008 | <p>The aim is to open the page get url nr 18, swap the url with url in position 18 and rerun 7 times but my code is stuck after getting position 18, why is the elif not running in line 24 ? (no traceback given, program just sitting there)</p>
<pre><code>import urllib
from BeautifulSoup import *
#not the real url
url= ('http://abc.googl.com')
count=7
position = 0
#n will be used to check that the code i running
n=0
while count >= 0:
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup('a')
for tag in tags:
x= tag.get('href', None)
position=position+1
if position <= 18:
n=n+1
print 'calculating', n
print x
elif position == 18:
url=(x)
print 'new url', x
count=count-1
print 'new count', count
position=0
if count == 0:
print "done"
print x
</code></pre>
| 0 | 2016-08-16T14:01:46Z | 38,977,079 | <p>Change</p>
<pre><code>if position <= 8:
</code></pre>
<p>by </p>
<pre><code>if position < 8:
</code></pre>
<p>And leave your <code>elif</code> the same.</p>
<p>By having the condition <code><=8</code> your code always enter the if (When <code>position</code> is <code><=8</code>), but when is 9 (<code>>8</code>) it will enter the <code>elif</code>. So if you want that the code enters the <code>elif</code> statement when <code>position = 8</code>, the <code>if</code> can not be true when <code>position = 8</code>.</p>
| 2 | 2016-08-16T14:04:24Z | [
"python",
"python-2.7"
] |
Split string by the first occurance from a set of delimiters with Python and regex | 38,977,041 | <p>First of all the question is tagged with <code>Python</code> and <code>regex</code> but it is not really tied to those - an answer can be high level.</p>
<p>At the moment I'm splitting a string with multiple delimiters with the following pattern. There are actually more delimiting patterns and they are more complex but let's keep it simple and limit them to 2 characters - <code>#</code> and <code>*</code>:</p>
<p><code>parts = re.split('#|*', string)</code></p>
<p>Which such approach a string <code>aaa#bbb*ccc#ddd</code> is split to 4 substrings <code>aaa</code>, <code>bbb</code>, <code>ccc</code>, <code>ddd</code>. But it is required to split either by a delimiter that occurs first in the string or by a delimiter that is most frequent in the string. <code>aaa#bbb*ccc#ddd</code> should be split to <code>aaa</code>, <code>bbb*ccc</code>, <code>ddd</code> and <code>aaa*bbb#ccc*ddd</code> should be split to <code>aaa</code>, <code>bbb#ccc</code>, <code>ddd</code>.</p>
<p>I know a straightforward way to achieve that - to find what delimiter occurs first or is the most frequent in a string and then split with that single delimiter. But the method has to be efficient and I'm wondering if it is possible to achieve that by a single regex expression. The question is mostly for splitting with the first occurance of the set of delimiters - for most frequent delimiter case almost for sure it will be required to calculate occurrence count in advance.</p>
<p>Update:</p>
<p>The question does not ask to split by first occurrence or most frequent delimiter simultaneously - any of this methods individually will be sufficient. I do understand that splitting by most frequent delimiter is not possible with regex without preliminary determination of the delimiter but I think there's a chance that splitting by first occurrence is possible with regex and lookahead without preparation made in advance.</p>
| 5 | 2016-08-16T14:03:04Z | 38,977,361 | <blockquote>
<p><em>it is required to split either by a delimiter that occurs first in the string or by a delimiter that is most frequent in the string.</em></p>
</blockquote>
<p>So you can first find all the delimiters and preserve them in a proper container with their frequency, then find the most common and first one, then split your string based on them.</p>
<p>Now for finding the delimiters, you need to separate them from the plain text based on a particular feature, for example if they are none word characters, and for preserving them we can use a dictionary in order to preserve the count of similar delimiters (in this case <code>collections.Counter()</code> will do the job).</p>
<p>Demo:</p>
<pre><code>>>> s = "aaa#bbb*ccc#ddd*rkfh^ndjfh*dfehb*erjg-rh@fkej*rjh"
>>> delimiters = re.findall(r'\W', s)
>>> first = delimiters[0]
'#'
>>> Counter(delimiters)
Counter({'*': 5, '#': 2, '@': 1, '-': 1, '^': 1})
>>>
>>> frequent = Counter(delimiters).most_common(1)[0][0]
'*'
>>> re.split(r'\{}|\{}'.format(first, frequent), s)
['aaa', 'bbb', 'ccc', 'ddd', 'rkfh^ndjfh', 'dfehb', 'erjg-rh@fkej', 'rjh']
</code></pre>
<p>Note that if you are dealing with delimiters that are more than one characters you can use <code>re.escape()</code> in order to escape the special regex characters (like <code>*</code>).</p>
| 3 | 2016-08-16T14:17:50Z | [
"python",
"regex",
"split"
] |
Split string by the first occurance from a set of delimiters with Python and regex | 38,977,041 | <p>First of all the question is tagged with <code>Python</code> and <code>regex</code> but it is not really tied to those - an answer can be high level.</p>
<p>At the moment I'm splitting a string with multiple delimiters with the following pattern. There are actually more delimiting patterns and they are more complex but let's keep it simple and limit them to 2 characters - <code>#</code> and <code>*</code>:</p>
<p><code>parts = re.split('#|*', string)</code></p>
<p>Which such approach a string <code>aaa#bbb*ccc#ddd</code> is split to 4 substrings <code>aaa</code>, <code>bbb</code>, <code>ccc</code>, <code>ddd</code>. But it is required to split either by a delimiter that occurs first in the string or by a delimiter that is most frequent in the string. <code>aaa#bbb*ccc#ddd</code> should be split to <code>aaa</code>, <code>bbb*ccc</code>, <code>ddd</code> and <code>aaa*bbb#ccc*ddd</code> should be split to <code>aaa</code>, <code>bbb#ccc</code>, <code>ddd</code>.</p>
<p>I know a straightforward way to achieve that - to find what delimiter occurs first or is the most frequent in a string and then split with that single delimiter. But the method has to be efficient and I'm wondering if it is possible to achieve that by a single regex expression. The question is mostly for splitting with the first occurance of the set of delimiters - for most frequent delimiter case almost for sure it will be required to calculate occurrence count in advance.</p>
<p>Update:</p>
<p>The question does not ask to split by first occurrence or most frequent delimiter simultaneously - any of this methods individually will be sufficient. I do understand that splitting by most frequent delimiter is not possible with regex without preliminary determination of the delimiter but I think there's a chance that splitting by first occurrence is possible with regex and lookahead without preparation made in advance.</p>
| 5 | 2016-08-16T14:03:04Z | 38,984,902 | <p>I've found the string.count() method to be very fast since it's implemented in C. Anything that avoids for loops will generally be faster, even if you iterate the string multiple times. This is probably the fastest solution:</p>
<pre><code>>>> s = 'aaa*bbb#ccc*ddd'
>>> a, b = s.count('*'), s.count('#')
>>> if a == b: a, b = -s.find('*'), -s.find('#')
...
>>> s.split('*' if a > b else '#')
['aaa', 'bbb#ccc', 'ddd']
</code></pre>
| 0 | 2016-08-16T21:39:38Z | [
"python",
"regex",
"split"
] |
Find and clicking button with selenium without ID | 38,977,169 | <p>I'm trying to click on a particular button on a webpage with Selenium in Python. How do I select and click on the button "Replace", with the following HTML?</p>
<pre><code><div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-dialog-buttons ui-draggable ui-resizable no-close" tabindex="-1" role="dialog" style="position: absolute; height: auto; width: 300px; top: 411.009px; left: 692.001px; display: block;" aria-describedby="dialog" aria-labelledby="ui-id-5">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-id-5" class="ui-dialog-title">Search and replace</span>
<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>
<span class="ui-button-text">close</span>
</button>
</div>
<div id="dialog" class="title ui-dialog-content ui-widget-content" style="width: auto; min-height: 62px; max-height: none; height: auto;">
<div class="findReplaceText">Search for:</div>
<input type="text" id="FindTerm" class="text ui-widget-content ui-corner-all input-large">
<br>
<div class="findReplaceText">Replace with:</div>
<input type="text" id="ReplaceTerm" class="text ui-widget-content ui-corner-all input-large"></div>
<div class="ui-resizable-handle ui-resizable-n" style="z-index: 90;">
</div>
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-w" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;"></div>
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Cancel</span>
</button>
</div>
</div>
</div>
</code></pre>
<p>There is another instance of a "Replace" button within the HTML which should be ignored:</p>
<pre><code><button type="button" class="titleButton replaceButton" id="riskFieldTemplateReplace">Replace</button>
</code></pre>
<p>Update: </p>
<p>Unsure if this is helpful. How the buttons HTML updates when hovering / clicking.</p>
<p>When hovering over the button:</p>
<pre><code><div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
</div>
</code></pre>
<p>When clicking the button:</p>
<pre><code><div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover ui-state-focus ui-state-active" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
</div>
</code></pre>
<p>When I run: </p>
<pre><code>driver.find_element_by_xpath(".//button[//span[text() = 'Replace' and @class = 'ui-button']]").click()
</code></pre>
<p>I'm presented with the following: </p>
<pre><code>Traceback (most recent call last):
File "<pyshell#205>", line 1, in <module>
driver.find_element_by_xpath(".//button[//span[text() = 'Replace' and @class = 'ui-button']]").click()
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 294, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 748, in find_element
{'using': by, 'value': value})['value']
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 237, in execute
self.error_handler.check_response(response)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//button[//span[text() = 'Replace' and @class = 'ui-button']]"}
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.1.7601 SP1 x86_64)
</code></pre>
| 2 | 2016-08-16T14:08:34Z | 38,977,261 | <p>You should try using <code>xpath</code> as below :-</p>
<pre><code>driver.find_element_by_xpath(".//button[contains(.,'Replace')]").click()
</code></pre>
<p>Or if there is multiple button with same text <code>Replace</code> try as below :-</p>
<pre><code>driver.find_element_by_xpath(".//button[child::span[text() = 'Replace' and @class = 'ui-button-text']]").click()
</code></pre>
<p>Or</p>
<pre><code>driver.find_element_by_xpath(".//span[text() = 'Replace' and @class = 'ui-button-text']/parent::button").click()
</code></pre>
<p><strong>Edited</strong> : If you are unable to <code>click</code> on element due to overlay of other element, you can try to <code>click</code> using <code>execute_script</code> as below :-</p>
<pre><code> replace = driver.find_element_by_xpath(".//span[text() = 'Replace' and @class = 'ui-button-text']/parent::button");
driver.execute_script("arguments[0].click()", replace);
</code></pre>
| 1 | 2016-08-16T14:13:04Z | [
"python",
"python-3.x",
"selenium"
] |
Find and clicking button with selenium without ID | 38,977,169 | <p>I'm trying to click on a particular button on a webpage with Selenium in Python. How do I select and click on the button "Replace", with the following HTML?</p>
<pre><code><div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-dialog-buttons ui-draggable ui-resizable no-close" tabindex="-1" role="dialog" style="position: absolute; height: auto; width: 300px; top: 411.009px; left: 692.001px; display: block;" aria-describedby="dialog" aria-labelledby="ui-id-5">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-id-5" class="ui-dialog-title">Search and replace</span>
<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>
<span class="ui-button-text">close</span>
</button>
</div>
<div id="dialog" class="title ui-dialog-content ui-widget-content" style="width: auto; min-height: 62px; max-height: none; height: auto;">
<div class="findReplaceText">Search for:</div>
<input type="text" id="FindTerm" class="text ui-widget-content ui-corner-all input-large">
<br>
<div class="findReplaceText">Replace with:</div>
<input type="text" id="ReplaceTerm" class="text ui-widget-content ui-corner-all input-large"></div>
<div class="ui-resizable-handle ui-resizable-n" style="z-index: 90;">
</div>
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-w" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;"></div>
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Cancel</span>
</button>
</div>
</div>
</div>
</code></pre>
<p>There is another instance of a "Replace" button within the HTML which should be ignored:</p>
<pre><code><button type="button" class="titleButton replaceButton" id="riskFieldTemplateReplace">Replace</button>
</code></pre>
<p>Update: </p>
<p>Unsure if this is helpful. How the buttons HTML updates when hovering / clicking.</p>
<p>When hovering over the button:</p>
<pre><code><div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
</div>
</code></pre>
<p>When clicking the button:</p>
<pre><code><div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover ui-state-focus ui-state-active" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
</div>
</code></pre>
<p>When I run: </p>
<pre><code>driver.find_element_by_xpath(".//button[//span[text() = 'Replace' and @class = 'ui-button']]").click()
</code></pre>
<p>I'm presented with the following: </p>
<pre><code>Traceback (most recent call last):
File "<pyshell#205>", line 1, in <module>
driver.find_element_by_xpath(".//button[//span[text() = 'Replace' and @class = 'ui-button']]").click()
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 294, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 748, in find_element
{'using': by, 'value': value})['value']
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 237, in execute
self.error_handler.check_response(response)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//button[//span[text() = 'Replace' and @class = 'ui-button']]"}
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.1.7601 SP1 x86_64)
</code></pre>
| 2 | 2016-08-16T14:08:34Z | 38,977,366 | <p>Try xpath:</p>
<pre><code>//span[.='Replace']
</code></pre>
| 1 | 2016-08-16T14:17:56Z | [
"python",
"python-3.x",
"selenium"
] |
Find and clicking button with selenium without ID | 38,977,169 | <p>I'm trying to click on a particular button on a webpage with Selenium in Python. How do I select and click on the button "Replace", with the following HTML?</p>
<pre><code><div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-dialog-buttons ui-draggable ui-resizable no-close" tabindex="-1" role="dialog" style="position: absolute; height: auto; width: 300px; top: 411.009px; left: 692.001px; display: block;" aria-describedby="dialog" aria-labelledby="ui-id-5">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-id-5" class="ui-dialog-title">Search and replace</span>
<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>
<span class="ui-button-text">close</span>
</button>
</div>
<div id="dialog" class="title ui-dialog-content ui-widget-content" style="width: auto; min-height: 62px; max-height: none; height: auto;">
<div class="findReplaceText">Search for:</div>
<input type="text" id="FindTerm" class="text ui-widget-content ui-corner-all input-large">
<br>
<div class="findReplaceText">Replace with:</div>
<input type="text" id="ReplaceTerm" class="text ui-widget-content ui-corner-all input-large"></div>
<div class="ui-resizable-handle ui-resizable-n" style="z-index: 90;">
</div>
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-w" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;"></div>
<div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;"></div>
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Cancel</span>
</button>
</div>
</div>
</div>
</code></pre>
<p>There is another instance of a "Replace" button within the HTML which should be ignored:</p>
<pre><code><button type="button" class="titleButton replaceButton" id="riskFieldTemplateReplace">Replace</button>
</code></pre>
<p>Update: </p>
<p>Unsure if this is helpful. How the buttons HTML updates when hovering / clicking.</p>
<p>When hovering over the button:</p>
<pre><code><div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
</div>
</code></pre>
<p>When clicking the button:</p>
<pre><code><div class="ui-dialog-buttonset">
<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover ui-state-focus ui-state-active" role="button" aria-disabled="false">
<span class="ui-button-text">Replace</span>
</button>
</div>
</code></pre>
<p>When I run: </p>
<pre><code>driver.find_element_by_xpath(".//button[//span[text() = 'Replace' and @class = 'ui-button']]").click()
</code></pre>
<p>I'm presented with the following: </p>
<pre><code>Traceback (most recent call last):
File "<pyshell#205>", line 1, in <module>
driver.find_element_by_xpath(".//button[//span[text() = 'Replace' and @class = 'ui-button']]").click()
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 294, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 748, in find_element
{'using': by, 'value': value})['value']
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 237, in execute
self.error_handler.check_response(response)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//button[//span[text() = 'Replace' and @class = 'ui-button']]"}
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.1.7601 SP1 x86_64)
</code></pre>
| 2 | 2016-08-16T14:08:34Z | 38,977,374 | <pre><code>def click_link(self, link_name: str):
if link_name in self.driver.page_source:
elem = self.driver.find_element_by_link_text(link_name)
elem.click()
</code></pre>
| 0 | 2016-08-16T14:18:14Z | [
"python",
"python-3.x",
"selenium"
] |
Pandas - append strings in data frame: ValueError: cannot reindex from a duplicate axis | 38,977,184 | <p>I have a data.frame looking similar to this (except much longer and with way more colornames):</p>
<pre><code>ff = pd.DataFrame({'OldCol':['darkbrown','lightbeige','lightbrown / beige','beige','brown','beige / cognac'], 'NewCol':['nan','nan','nan','nan','nan','nan']})
</code></pre>
<p>I want the data.frame to look like this:</p>
<pre><code>ffnew = pd.DataFrame({'OldCol':['darkbrown','lightbeige','lightbrown / beige','beige','brown','beige / cognac'], 'NewCol':['brown','beige','beige / brown','sand','brown','sand / brown']})
</code></pre>
<p>I tried the following:</p>
<pre><code>ff.loc[ff['OldCol'].str.contains(r'brown|cognac',na=False) & ff['NewCol'].str.contains(r'nan'), 'NewCol'] = 'brown'
ff.loc[ff['OldCol'].str.contains(r'brown|cognac',na=False) & ~ff['NewCol'].str.contains(r'nan|brown'), 'NewCol'] = ff['NewCol']+'/ brown'
ff.loc[ff['OldCol'].str.contains(r'beige|sand',na=False) & ff['NewCol'].str.contains(r'nan'), 'NewCol'] = 'beige'
ff.loc[ff['OldCol'].str.contains(r'beige|sand',na=False) & ~ff['NewCol'].str.contains(r'nan|beige'), 'NewCol'] = ff['NewCol'] +'/ beige'
</code></pre>
<p>In my longer data.frame I typically get the error: </p>
<blockquote>
<p>ValueError: cannot reindex from a duplicate axis</p>
</blockquote>
<p>Can anyone help?
Thanks very much in advance!</p>
| 2 | 2016-08-16T14:09:20Z | 38,977,377 | <p>There is problem with duplicates in <code>index</code>. You can replace all values of index by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> to <code>Regular Index</code> (<code>0,1,2..len(df)-1</code>). Old values are removed by parameter <code>drop=True</code>:</p>
<pre><code>ff.reset_index(drop=True, inplace=True)
</code></pre>
<p>Test:</p>
<pre><code>ff = pd.DataFrame({'OldCol':['darkbrown','lightbeige','lightbrown / beige','beige','brown','beige / cognac'], 'NewCol':['nan','nan','nan','nan','nan','nan']})
ffnew = pd.DataFrame({'OldCol':['darkbrown','lightbeige','lightbrown / beige','beige','brown','beige / cognac'], 'NewCol':['brown','beige','beige / brown','sand','brown','sand / brown']})
ff.index = [0,0,2,3,4,5]
#ValueError: cannot reindex from a duplicate axis
ff.reset_index(drop=True, inplace=True)
</code></pre>
| 1 | 2016-08-16T14:18:25Z | [
"python",
"string",
"pandas",
"indexing",
"dataframe"
] |
Making python interpret spaces as newline characters | 38,977,285 | <p>I am not sure about input format that user will enter. There are two possibities:</p>
<p>code:</p>
<pre><code>n=int(input("enter the no of workers \n"))
print("enter the names of workers")
NameList=[]
for i in range(n):
NameList.append(input())
print(NameList)
</code></pre>
<p>possibility 1:</p>
<p>enter the no of workers </p>
<p>4</p>
<p>enter the names of workers</p>
<p>name1</p>
<p>name2</p>
<p>name3</p>
<p>name4</p>
<p>['name1', 'name2', 'name3', 'name4']</p>
<p>working great...!!</p>
<p>possibility 2:</p>
<p>input will be : </p>
<p>enter the no of workers </p>
<p>4</p>
<p>enter the names of workers</p>
<p>name1 name2 name3 name4</p>
<p>in this case my code will fail. I'll need to write different code( i know how to write that ;) ) to accept this format of input.</p>
<p>So is there anyway that one code will work for both input formats. By treating spaces as Enter. Thanks</p>
| -3 | 2016-08-16T14:14:37Z | 38,977,345 | <p>If a worker name can't include a space, you can check that and change the behavior accordingly.</p>
<p>This will even work if the user combine the 2 options (e.g. entering <code>'a'</code> and then <code>'b c'</code>), although it is not perfect (it is possible to get more than <code>n</code> names, for example if <code>n == 3</code> and inputting <code>'a b'</code> and <code>'c d'</code>)</p>
<pre><code>n = int(input("enter the no of workers \n"))
print("enter the names of workers")
NameList = []
while len(NameList) < n:
worker_name = input()
if ' ' in worker_name:
if NameList:
NameList.extend(worker_name.split())
else:
NameList = worker_name.split()
else:
NameList.append(worker_name)
print(NameList)
</code></pre>
| 1 | 2016-08-16T14:17:16Z | [
"python",
"python-3.x"
] |
Making python interpret spaces as newline characters | 38,977,285 | <p>I am not sure about input format that user will enter. There are two possibities:</p>
<p>code:</p>
<pre><code>n=int(input("enter the no of workers \n"))
print("enter the names of workers")
NameList=[]
for i in range(n):
NameList.append(input())
print(NameList)
</code></pre>
<p>possibility 1:</p>
<p>enter the no of workers </p>
<p>4</p>
<p>enter the names of workers</p>
<p>name1</p>
<p>name2</p>
<p>name3</p>
<p>name4</p>
<p>['name1', 'name2', 'name3', 'name4']</p>
<p>working great...!!</p>
<p>possibility 2:</p>
<p>input will be : </p>
<p>enter the no of workers </p>
<p>4</p>
<p>enter the names of workers</p>
<p>name1 name2 name3 name4</p>
<p>in this case my code will fail. I'll need to write different code( i know how to write that ;) ) to accept this format of input.</p>
<p>So is there anyway that one code will work for both input formats. By treating spaces as Enter. Thanks</p>
| -3 | 2016-08-16T14:14:37Z | 38,977,553 | <p>Instead of the spaces, I would <em>highly</em> recommend the following:</p>
<pre><code>for i in range(n):
NameList.append(input("What is the name of worker " + i +"?"))
</code></pre>
<p>If you <em>absolutely</em> need to accept spaces,
use DeepSpace's answer.</p>
| 0 | 2016-08-16T14:26:44Z | [
"python",
"python-3.x"
] |
Install numpy from a wheel package on Redhat 6.5 | 38,977,344 | <p>I am trying to install numpy from a wheel package (that I have generated in my virtualenv) on a Redhat 6.5 with python version =2.6.6:</p>
<pre><code>pip install numpy-1.11.1-cp26-cp26mu-linux_x86_64.whl
</code></pre>
<p>I am getting the following error: </p>
<pre><code>numpy-1.11.1-cp26-cp26mu-linux_x86_64.whl is not a supported wheel on this platform.
</code></pre>
<p>Any way to fix that? thanks :) </p>
| 1 | 2016-08-16T14:17:14Z | 39,014,240 | <p>Based on the answer of Simon Visser on question :
<a href="http://stackoverflow.com/questions/28107123/cannot-install-numpy-from-wheel-format?rq=1">Cannot install numpy from wheel format</a>
the solution is to replace "cp26mu" in the name of the file by none. </p>
| 0 | 2016-08-18T09:13:21Z | [
"python",
"numpy",
"pip"
] |
500 internal server Error running cgi python | 38,977,390 | <p>i run my python file on web browser but i have some error can u help me solve them</p>
<pre><code>Internal Server Error
</code></pre>
<p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p>
<p>Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error.</p>
<p>More information about this error may be available in the server error log.
Apache/2.4.18 (Ubuntu) Server at localhost Port 80</p>
| -1 | 2016-08-16T14:18:54Z | 38,977,559 | <p>you can find your apache logs in this directory <code>/var/log/apache/</code>. Error 500 usually means there is a server error. If you can't find the error in these logs, then try to use verbose logging.</p>
| 0 | 2016-08-16T14:27:06Z | [
"python",
"apache",
"cgi"
] |
error in installing google api python client | 38,977,457 | <p>I'm installing google api python client on python 3 using pip from <a href="https://github.com/google/gdata-python-client" rel="nofollow">the GitHub repository</a>.</p>
<p>But getting the following error:</p>
<blockquote>
<p>Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279</p>
</blockquote>
<p>I already installed microsoft windows sdk 7.1 and net framework 4.0.</p>
<p>But it's not working.</p>
<p>Please check <a href="http://i.stack.imgur.com/PZk8U.png" rel="nofollow">the snapshot</a> for more details.</p>
| 1 | 2016-08-16T14:22:04Z | 38,977,627 | <p>gdata is <a href="https://developers.google.com/gdata/docs/directory" rel="nofollow">deprecated</a> and does not have support for Python 3.x in the first place. Use any of <a href="https://developers.google.com/products" rel="nofollow">these</a> APIs.</p>
| 1 | 2016-08-16T14:30:20Z | [
"python",
"python-3.x",
"gdata",
"google-api-python-client"
] |
Non-blocking way to determine if thread is finished? | 38,977,472 | <p>I have the following code:</p>
<pre><code>import threading
import time
class TestWorker (threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print "Starting " + self.name
time.sleep(20)
print "Exiting " + self.name
# how do I let the calling thread know it's done?
class TestMain:
def __init__(self):
pass
def do_work(self):
thread = TestWorker(1, "Thread-1")
thread.start()
def do_something_else(self):
print "Something else"
def on_work_done(self):
print "work done"
</code></pre>
<p>How can I let the main thread know that the <code>TestWorker</code> has finished (call <code>on_work_done()</code>), without blocking calls to <code>do_something_else()</code> as <code>thread.join()</code> would?</p>
| 2 | 2016-08-16T14:22:33Z | 38,978,075 | <pre><code>import threading
dt = {}
threading.Thread(target=dt.update, kwargs=dict(out=123)).start()
while 'out' not in dt:
print('out' in dt)
print(dt)
</code></pre>
| 0 | 2016-08-16T14:50:56Z | [
"python",
"multithreading"
] |
Non-blocking way to determine if thread is finished? | 38,977,472 | <p>I have the following code:</p>
<pre><code>import threading
import time
class TestWorker (threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print "Starting " + self.name
time.sleep(20)
print "Exiting " + self.name
# how do I let the calling thread know it's done?
class TestMain:
def __init__(self):
pass
def do_work(self):
thread = TestWorker(1, "Thread-1")
thread.start()
def do_something_else(self):
print "Something else"
def on_work_done(self):
print "work done"
</code></pre>
<p>How can I let the main thread know that the <code>TestWorker</code> has finished (call <code>on_work_done()</code>), without blocking calls to <code>do_something_else()</code> as <code>thread.join()</code> would?</p>
| 2 | 2016-08-16T14:22:33Z | 38,978,438 | <p>You can give your thread instance an optional callback function to call when it's finished.<br>
Note I added a <code>Lock</code> to prevent concurrent printing (which does block).</p>
<pre><code>import threading
import time
print_lock = threading.Lock() # prevent threads from printing at same time
class TestWorker(threading.Thread):
def __init__(self, threadID, name, callback=None):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.callback = callback if callback else lambda: None
def run(self):
with print_lock:
print("Starting " + self.name)
time.sleep(3)
with print_lock:
print("Exiting " + self.name)
self.callback()
class TestMain:
def __init__(self):
self.work_done = False
def do_work(self):
thread = TestWorker(1, "Thread-1", self.on_work_done)
thread.start()
def do_something_else(self):
with print_lock:
print("Something else")
def on_work_done(self):
with print_lock:
print("work done")
self.work_done = True
main = TestMain()
main.do_work()
while not main.work_done:
main.do_something_else()
time.sleep(.5) # do other stuff...
print('Done')
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Starting Thread-1
Something else
Something else
Something else
Something else
Something else
Something else
Exiting Thread-1
Something else
work done
Done
</code></pre>
| 1 | 2016-08-16T15:07:22Z | [
"python",
"multithreading"
] |
Non-blocking way to determine if thread is finished? | 38,977,472 | <p>I have the following code:</p>
<pre><code>import threading
import time
class TestWorker (threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print "Starting " + self.name
time.sleep(20)
print "Exiting " + self.name
# how do I let the calling thread know it's done?
class TestMain:
def __init__(self):
pass
def do_work(self):
thread = TestWorker(1, "Thread-1")
thread.start()
def do_something_else(self):
print "Something else"
def on_work_done(self):
print "work done"
</code></pre>
<p>How can I let the main thread know that the <code>TestWorker</code> has finished (call <code>on_work_done()</code>), without blocking calls to <code>do_something_else()</code> as <code>thread.join()</code> would?</p>
| 2 | 2016-08-16T14:22:33Z | 38,980,087 | <pre><code>import queue
import threading
class SThread(threading.Thread, queue.Queue):
def __init__(self, queue_out: object):
threading.Thread.__init__(self)
queue.Queue.__init__(self)
self.queue_out = queue_out
self.setDaemon(True)
self.start()
def run(self):
print('Thread start')
while True:
cmd = self.get()
if cmd is None:
break # exit thread
self.queue_out.put(cmd['target'](*cmd.get('args', ())), **cmd.get('kwargs', {}))
self.task_done()
print('Thread stop')
def testFn(a):
print('+ %s' % a)
return a
if __name__ == '__main__':
print('main 1')
# init
queue_out = queue.Queue()
thread = SThread(queue_out)
# in
for a in range(5): thread.put(dict(target=testFn, args=(a,)))
thread.put(None)
print('main 2')
# out
while True:
try:
print('- %s' % queue_out.get(timeout=3))
except queue.Empty:
break
print('main 3')
</code></pre>
<p>OUT:</p>
<pre><code>main 1
Thread start
main 2
+ 0
+ 1
+ 2
+ 3
+ 4
Thread stop
- 0
- 1
- 2
- 3
- 4
main 3
</code></pre>
| 1 | 2016-08-16T16:32:32Z | [
"python",
"multithreading"
] |
How to use idlelib.PyShell to embed an interpreter in a tkinter program? | 38,977,525 | <p>I need to embed an interative python interpreter into my tkinter program. Could anyone help me out as to how to integrate it?</p>
<p>I have already looked at the <code>main()</code> function, but it's way to complex for my needs, but I can't seem to reduce it without breaking it.</p>
| 2 | 2016-08-16T14:25:05Z | 38,984,338 | <p>Some details of what you must do may depend on what you want to do with IDLE's Shell once you have it running. I would like to know more about that. But let us start simple and make the minimum changes to pyshell.main needed to make it run with other code. </p>
<p>Note that in 3.6, which I use below, <code>PyShell.py</code> is renamed <code>pyshell.py</code>. Also note that everything here amounts to using IDLE's private internals and is 'use at your own risk'.</p>
<p>I presume you want to run Shell in the same process (and thread) as your tkinter code. Change the signature to</p>
<pre><code>def main(tkroot=None):
</code></pre>
<p>Change root creation (find <code># setup root</code>) to</p>
<pre><code>if not tkroot:
root = Tk(className="Idle")
root.withdraw()
else:
root = tkroot
</code></pre>
<p>In current 3.6, there are a couple more lines to be indented under <code>if not tkroot</code>:</p>
<pre><code> if use_subprocess and not testing:
NoDefaultRoot()
</code></pre>
<p>Guard mainloop and destroy (at the end) with</p>
<pre><code>if not tkroot:
while flist.inversedict: # keep IDLE running while files are open.
root.mainloop()
root.destroy()
# else leave mainloop and destroy to caller of main
</code></pre>
<p>The above adds 'dependency injection' of a root window to the function. I might add it in 3.6 to make testing (an example of 'other code') easier.</p>
<p>The follow tkinter program now runs, displaying the both the root window and an IDLE shell.</p>
<pre><code>from tkinter import *
from idlelib import pyshell
root = Tk()
Label(root, text='Root id is '+str(id(root))).pack()
root.update()
def later():
pyshell.main(tkroot=root)
Label(root, text='Use_subprocess = '+str(pyshell.use_subprocess)).pack()
root.after(0, later)
root.mainloop()
</code></pre>
<p>You should be able to call pyshell.main whenever you want.</p>
| 1 | 2016-08-16T20:56:12Z | [
"python",
"shell",
"python-3.x",
"tkinter",
"python-idle"
] |
Replacing multiple words in a string from different data sets in Python | 38,977,756 | <p>Essentially I have a python script that loads in a number of files, each file contains a list and these are used to generate strings. For example: "Just been to see $film% in $location%, I'd highly recommend it!" I need to replace the $film% and $location% placeholders with a random element of the array of their respective imported lists.</p>
<p>I'm very new to Python but have picked up most of it quite easily but obviously in Python strings are immutable and so handling this sort of task is different compared to other languages I've used.</p>
<p>Here is the code as it stands, I've tried adding in a while loop but it would still only replace the first instance of a replaceable word and leave the rest.</p>
<pre><code>#!/usr/bin/python
import random
def replaceWord(string):
#Find Variable Type
if "url" in string:
varType = "url"
elif "film" in string:
varType = "film"
elif "food" in string:
varType = "food"
elif "location" in string:
varType = "location"
elif "tvshow" in string:
varType = "tvshow"
#LoadVariableFile
fileToOpen = "/prototype/default_" + varType + "s.txt"
var_file = open(fileToOpen, "r")
var_array = var_file.read().split('\n')
#Get number of possible variables
numberOfVariables = len(var_array)
#ChooseRandomElement
randomElement = random.randrange(0,numberOfVariables)
#ReplaceWord
oldValue = "$" + varType + "%"
newString = string.replace(oldValue, var_array[randomElement], 1)
return newString
testString = "Just been to see $film% in $location%, I'd highly recommend it!"
Test = replaceWord(testString)
</code></pre>
<p>This would give the following output: Just been to see Harry Potter in $location%, I'd highly recommend it!</p>
<p>I have tried using while loops, counting the number of words to replace in the string etc. however it still only changes the first word. It also needs to be able to replace multiple instances of the same "variable" type in the same string, so if there are two occurrences of $film% in a string it should replace both with a random element from the loaded file.</p>
| 1 | 2016-08-16T14:36:03Z | 38,978,076 | <p>A few points about your code:</p>
<ul>
<li>You can replace the randrange with <a href="https://docs.python.org/2/library/random.html#random.choice" rel="nofollow">random.choice</a> as you just
want to select an item from an array.</li>
<li>You can iterate over your types and do the replacement without
specifying a limit (the third parameter), then assign it to the same object, so you keep all your replacements.</li>
<li>readlines() do what you want for open, read from the file as store the lines as an array</li>
<li>Return the new string after go through all the possible replacements</li>
</ul>
<p>Something like this:</p>
<pre><code>#!/usr/bin/python
import random
def replaceWord(string):
#Find Variable Type
types = ("url", "film", "food", "location", "tvshow")
for t in types:
if "$" + t + "%" in string:
var_array = []
#LoadVariableFile
fileToOpen = "/prototype/default_" + varType + "s.txt"
with open(fname) as f:
var_array = f.readlines()
tag = "$" + t + "%"
while tag in string:
choice = random.choice(var_array)
string = string.replace(tag, choice, 1)
var_array.remove(choice)
return string
testString = "Just been to see $film% in $location%, I'd highly recommend it!"
new = replaceWord(testString)
print(new)
</code></pre>
| 0 | 2016-08-16T14:50:57Z | [
"python",
"string",
"random"
] |
Replacing multiple words in a string from different data sets in Python | 38,977,756 | <p>Essentially I have a python script that loads in a number of files, each file contains a list and these are used to generate strings. For example: "Just been to see $film% in $location%, I'd highly recommend it!" I need to replace the $film% and $location% placeholders with a random element of the array of their respective imported lists.</p>
<p>I'm very new to Python but have picked up most of it quite easily but obviously in Python strings are immutable and so handling this sort of task is different compared to other languages I've used.</p>
<p>Here is the code as it stands, I've tried adding in a while loop but it would still only replace the first instance of a replaceable word and leave the rest.</p>
<pre><code>#!/usr/bin/python
import random
def replaceWord(string):
#Find Variable Type
if "url" in string:
varType = "url"
elif "film" in string:
varType = "film"
elif "food" in string:
varType = "food"
elif "location" in string:
varType = "location"
elif "tvshow" in string:
varType = "tvshow"
#LoadVariableFile
fileToOpen = "/prototype/default_" + varType + "s.txt"
var_file = open(fileToOpen, "r")
var_array = var_file.read().split('\n')
#Get number of possible variables
numberOfVariables = len(var_array)
#ChooseRandomElement
randomElement = random.randrange(0,numberOfVariables)
#ReplaceWord
oldValue = "$" + varType + "%"
newString = string.replace(oldValue, var_array[randomElement], 1)
return newString
testString = "Just been to see $film% in $location%, I'd highly recommend it!"
Test = replaceWord(testString)
</code></pre>
<p>This would give the following output: Just been to see Harry Potter in $location%, I'd highly recommend it!</p>
<p>I have tried using while loops, counting the number of words to replace in the string etc. however it still only changes the first word. It also needs to be able to replace multiple instances of the same "variable" type in the same string, so if there are two occurrences of $film% in a string it should replace both with a random element from the loaded file.</p>
| 1 | 2016-08-16T14:36:03Z | 38,978,454 | <p>The <code>varType</code> you are assigning will be set in only one of your <code>if-elif-else</code> sequence and then the interpreter will go outside. You would have to run all over it and perform operations. One way would be to set flags which part of sentence you want to change. It would go that way:</p>
<pre><code>url_to_change = False
film_to_change = False
if "url" in string:
url_to_change = True
elif "film" in string:
film_to_change = True
if url_to_change:
change_url()
if film_to_change:
change_film()
</code></pre>
<p>If you want to change all occurances you could use a <code>foreach</code> loop. Just do something like this in the part you are swapping a word:</p>
<pre><code>for word in sentence:
if word == 'url':
change_word()
</code></pre>
<p>Having said this, I'd reccomend introducing two improvements. Push changing into separate functions. It would be easier to manage your code.
For example function for getting items from file to random from could be</p>
<pre><code>def load_variable_file(file_name)
fileToOpen = "/prototype/default_" + file_name + "s.txt"
var_file = open(fileToOpen, "r")
var_array = var_file.read().split('\n')
var_file.clos()
return var_array
</code></pre>
<p>Instead of</p>
<pre><code>if "url" in string:
varType = "url"
</code></pre>
<p>you could do:</p>
<pre><code>def change_url(sentence):
var_array = load_variable_file(url)
numberOfVariables = len(var_array)
randomElement = random.randrange(0,numberOfVariables)
oldValue = "$" + varType + "%"
return sentence.replace(oldValue, var_array[randomElement], 1)
if "url" in sentence:
setnence = change_url(sentence)
</code></pre>
<p>And so on. You could push some part of what I've put into change_url() into a separate function, since it would be used by all such functions (just like loading data from file). I deliberately do not change everything, I hope you get my point. As you see with functions with clear names you can write less code, split it into logical, reusable parts, no needs to comment the code.</p>
| 0 | 2016-08-16T15:08:04Z | [
"python",
"string",
"random"
] |
Replacing multiple words in a string from different data sets in Python | 38,977,756 | <p>Essentially I have a python script that loads in a number of files, each file contains a list and these are used to generate strings. For example: "Just been to see $film% in $location%, I'd highly recommend it!" I need to replace the $film% and $location% placeholders with a random element of the array of their respective imported lists.</p>
<p>I'm very new to Python but have picked up most of it quite easily but obviously in Python strings are immutable and so handling this sort of task is different compared to other languages I've used.</p>
<p>Here is the code as it stands, I've tried adding in a while loop but it would still only replace the first instance of a replaceable word and leave the rest.</p>
<pre><code>#!/usr/bin/python
import random
def replaceWord(string):
#Find Variable Type
if "url" in string:
varType = "url"
elif "film" in string:
varType = "film"
elif "food" in string:
varType = "food"
elif "location" in string:
varType = "location"
elif "tvshow" in string:
varType = "tvshow"
#LoadVariableFile
fileToOpen = "/prototype/default_" + varType + "s.txt"
var_file = open(fileToOpen, "r")
var_array = var_file.read().split('\n')
#Get number of possible variables
numberOfVariables = len(var_array)
#ChooseRandomElement
randomElement = random.randrange(0,numberOfVariables)
#ReplaceWord
oldValue = "$" + varType + "%"
newString = string.replace(oldValue, var_array[randomElement], 1)
return newString
testString = "Just been to see $film% in $location%, I'd highly recommend it!"
Test = replaceWord(testString)
</code></pre>
<p>This would give the following output: Just been to see Harry Potter in $location%, I'd highly recommend it!</p>
<p>I have tried using while loops, counting the number of words to replace in the string etc. however it still only changes the first word. It also needs to be able to replace multiple instances of the same "variable" type in the same string, so if there are two occurrences of $film% in a string it should replace both with a random element from the loaded file.</p>
| 1 | 2016-08-16T14:36:03Z | 38,979,403 | <p>The following program may be somewhat closer to what you are trying to accomplish. Please note that documentation has been included to help explain what is going on. The templates are a little different than yours but provide customization options.</p>
<pre><code>#! /usr/bin/env python3
import random
PATH_TEMPLATE = './prototype/default_{}s.txt'
def main():
"""Demonstrate the StringReplacer class with a test sting."""
replacer = StringReplacer(PATH_TEMPLATE)
text = "Just been to see {film} in {location}, I'd highly recommend it!"
result = replacer.process(text)
print(result)
class StringReplacer:
"""StringReplacer(path_template) -> StringReplacer instance"""
def __init__(self, path_template):
"""Initialize the instance attribute of the class."""
self.path_template = path_template
self.cache = {}
def process(self, text):
"""Automatically discover text keys and replace them at random."""
keys = self.load_keys(text)
result = self.replace_keys(text, keys)
return result
def load_keys(self, text):
"""Discover what replacements can be made in a string."""
keys = {}
while True:
try:
text.format(**keys)
except KeyError as error:
key = error.args[0]
self.load_to_cache(key)
keys[key] = ''
else:
return keys
def load_to_cache(self, key):
"""Warm up the cache as needed in preparation for replacements."""
if key not in self.cache:
with open(self.path_template.format(key)) as file:
unique = set(filter(None, map(str.strip, file)))
self.cache[key] = tuple(unique)
def replace_keys(self, text, keys):
"""Build a dictionary of random replacements and run formatting."""
for key in keys:
keys[key] = random.choice(self.cache[key])
new_string = text.format(**keys)
return new_string
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-08-16T15:54:46Z | [
"python",
"string",
"random"
] |
How to find all unused and first missing number in an array (in Python)? | 38,977,776 | <p>I'm new to python and I need help in trying to find all unused and the first unused/missing number in an array (in python 2.7.3)? </p>
<p>The array is of length 20 and is used by an application. When the application is launched, the array is empty, but as users begin to populate it, I need to find all unused numbers and first unused number. </p>
<p>Think of it as a car-park with 20 spots numbered 1 to 20. As people begin to park their cars, the spaces get filled. People may not necessarily park cars in a sequence, two people may park in spots 1 and 16, so i need to find all the missing spots and the first unused parking spot.</p>
<p><em>Parking cars is given as an example to help you understand what I'm trying to convey. Array will always be integer, and will hold values from 1 to 20.</em> </p>
<p>Below is what the code should do</p>
<p>On Launch, myArray is empty:</p>
<pre><code>myarray = []
</code></pre>
<p>So the first missing number should be 1 (i.e. Park car in first spot)</p>
<pre><code>missingNumbers = [1,2,3,.......20]
firstMissingNoInMyArray = 1
</code></pre>
<p>As spaces in the array are filled, the array will look like this</p>
<pre><code>myarray = [1, 5, 15]
</code></pre>
<p>So first missing number and missing numbers are: </p>
<pre><code>missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20].
firstMissingNoInMyArray = 2
</code></pre>
<p>I need to see both missing numbers list and the first missing number, can anyone help with Python code, I'm restricted to using Python 2.7.3; if you have a solution in Python 3, do write it, it may help Python 3 users.</p>
<p>Many thanks in advance.</p>
| 1 | 2016-08-16T14:36:43Z | 38,977,942 | <p>I think this listcomprehension should do the trick for you</p>
<pre><code>missingNumbers = [ i for i in range(20) if i not in myarray ]
</code></pre>
<p>to get the first number you only need to take the first element </p>
<pre><code>firstMissingNoInMyArray = missingNumbers[0]
</code></pre>
| 1 | 2016-08-16T14:44:30Z | [
"python",
"arrays",
"dynamic"
] |
How to find all unused and first missing number in an array (in Python)? | 38,977,776 | <p>I'm new to python and I need help in trying to find all unused and the first unused/missing number in an array (in python 2.7.3)? </p>
<p>The array is of length 20 and is used by an application. When the application is launched, the array is empty, but as users begin to populate it, I need to find all unused numbers and first unused number. </p>
<p>Think of it as a car-park with 20 spots numbered 1 to 20. As people begin to park their cars, the spaces get filled. People may not necessarily park cars in a sequence, two people may park in spots 1 and 16, so i need to find all the missing spots and the first unused parking spot.</p>
<p><em>Parking cars is given as an example to help you understand what I'm trying to convey. Array will always be integer, and will hold values from 1 to 20.</em> </p>
<p>Below is what the code should do</p>
<p>On Launch, myArray is empty:</p>
<pre><code>myarray = []
</code></pre>
<p>So the first missing number should be 1 (i.e. Park car in first spot)</p>
<pre><code>missingNumbers = [1,2,3,.......20]
firstMissingNoInMyArray = 1
</code></pre>
<p>As spaces in the array are filled, the array will look like this</p>
<pre><code>myarray = [1, 5, 15]
</code></pre>
<p>So first missing number and missing numbers are: </p>
<pre><code>missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20].
firstMissingNoInMyArray = 2
</code></pre>
<p>I need to see both missing numbers list and the first missing number, can anyone help with Python code, I'm restricted to using Python 2.7.3; if you have a solution in Python 3, do write it, it may help Python 3 users.</p>
<p>Many thanks in advance.</p>
| 1 | 2016-08-16T14:36:43Z | 38,977,964 | <p>You could use <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set</code></a> operations.</p>
<pre><code>limit = 20
myarray = [1, 5, 15] # Example
missingNumbers = list(set(range(1, limit + 1)) - set(myarray))
print 'Missing numbers ->', missingNumbers
print 'First missing number ->', missingNumbers[0] # Access the first element.
</code></pre>
<p><strong>Sample Output:</strong></p>
<pre><code>Missing numbers -> [2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20]
First missing number -> 2
</code></pre>
<hr>
<p>Although user @<strong>Magellan88</strong>'s solution is quite pythonic, set operations are highly optimized for this class of calculations. Running some bench marks below, the <em>list comprehension</em> takes significantly longer to finish execution even for smaller data sets -> <em>Search list</em>: <strong>100,000 items</strong>, <em>list to subtract</em> -> <strong>100 items.</strong></p>
<pre><code>import timeit
print timeit.timeit("list(set(range(1,100000)) - set(range(1,100)))", number=100)
print timeit.timeit("[ i for i in range(1,100000) if i not in myarray]", number=100, setup="myarray = range(1,100)")
</code></pre>
<p><strong>Results (in seconds):</strong></p>
<blockquote>
<ul>
<li>1.43372607231 - <em>Set operations</em>.</li>
<li>18.2217440605 - <em>List comprehension</em>.</li>
</ul>
</blockquote>
<p>Set difference is a relatively low costing operation with a time complexity of <strong><em>O(n)</em></strong>, (<em><a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">python documentation</a> on complexities</em>). Sets in python are essentially implemented using a hash-table giving way to very fast operations (<em><a href="http://svn.python.org/view/python/trunk/Objects/setobject.c?view=markup" rel="nofollow">source code</a></em>). </p>
<p>Meanwhile, in the list comprehension, there is an <code>in</code> operation which has an average case of <strong><em>O(n)</em></strong>, this operation occurs within a for loop <strong><em>O(n)</em></strong>, thus giving us an average time complexity of <strong><em>O(n<sup>2</sup>)</em></strong>. The list comprehension follows a <em>quadratic asymptotic growth</em> pattern (<em>far slower than the set operation</em>).</p>
| 2 | 2016-08-16T14:45:57Z | [
"python",
"arrays",
"dynamic"
] |
How to find all unused and first missing number in an array (in Python)? | 38,977,776 | <p>I'm new to python and I need help in trying to find all unused and the first unused/missing number in an array (in python 2.7.3)? </p>
<p>The array is of length 20 and is used by an application. When the application is launched, the array is empty, but as users begin to populate it, I need to find all unused numbers and first unused number. </p>
<p>Think of it as a car-park with 20 spots numbered 1 to 20. As people begin to park their cars, the spaces get filled. People may not necessarily park cars in a sequence, two people may park in spots 1 and 16, so i need to find all the missing spots and the first unused parking spot.</p>
<p><em>Parking cars is given as an example to help you understand what I'm trying to convey. Array will always be integer, and will hold values from 1 to 20.</em> </p>
<p>Below is what the code should do</p>
<p>On Launch, myArray is empty:</p>
<pre><code>myarray = []
</code></pre>
<p>So the first missing number should be 1 (i.e. Park car in first spot)</p>
<pre><code>missingNumbers = [1,2,3,.......20]
firstMissingNoInMyArray = 1
</code></pre>
<p>As spaces in the array are filled, the array will look like this</p>
<pre><code>myarray = [1, 5, 15]
</code></pre>
<p>So first missing number and missing numbers are: </p>
<pre><code>missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20].
firstMissingNoInMyArray = 2
</code></pre>
<p>I need to see both missing numbers list and the first missing number, can anyone help with Python code, I'm restricted to using Python 2.7.3; if you have a solution in Python 3, do write it, it may help Python 3 users.</p>
<p>Many thanks in advance.</p>
| 1 | 2016-08-16T14:36:43Z | 38,977,967 | <p>You can use <code>set</code>s then you can simply subtract the sets.
In order to see the first missing number you can take the <code>min</code> in the resulting set:</p>
<pre><code>all_nums = set(xrange(1, 21))
arr = set(xrange(5, 10))
print all_nums - arr
print min(all_nums - arr)
# note that sets are unordered
>> {1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
1
</code></pre>
<p>This <em>should</em> work on Python 2.7.3, but you should consider upgrading anyway. Python 2.7.3 is 7 years old.</p>
| 1 | 2016-08-16T14:46:01Z | [
"python",
"arrays",
"dynamic"
] |
How to find all unused and first missing number in an array (in Python)? | 38,977,776 | <p>I'm new to python and I need help in trying to find all unused and the first unused/missing number in an array (in python 2.7.3)? </p>
<p>The array is of length 20 and is used by an application. When the application is launched, the array is empty, but as users begin to populate it, I need to find all unused numbers and first unused number. </p>
<p>Think of it as a car-park with 20 spots numbered 1 to 20. As people begin to park their cars, the spaces get filled. People may not necessarily park cars in a sequence, two people may park in spots 1 and 16, so i need to find all the missing spots and the first unused parking spot.</p>
<p><em>Parking cars is given as an example to help you understand what I'm trying to convey. Array will always be integer, and will hold values from 1 to 20.</em> </p>
<p>Below is what the code should do</p>
<p>On Launch, myArray is empty:</p>
<pre><code>myarray = []
</code></pre>
<p>So the first missing number should be 1 (i.e. Park car in first spot)</p>
<pre><code>missingNumbers = [1,2,3,.......20]
firstMissingNoInMyArray = 1
</code></pre>
<p>As spaces in the array are filled, the array will look like this</p>
<pre><code>myarray = [1, 5, 15]
</code></pre>
<p>So first missing number and missing numbers are: </p>
<pre><code>missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20].
firstMissingNoInMyArray = 2
</code></pre>
<p>I need to see both missing numbers list and the first missing number, can anyone help with Python code, I'm restricted to using Python 2.7.3; if you have a solution in Python 3, do write it, it may help Python 3 users.</p>
<p>Many thanks in advance.</p>
| 1 | 2016-08-16T14:36:43Z | 38,978,260 | <p>If you know the upper limit of the range, then remove element, that came from user, from pre-populated list and return the first element. Like below:</p>
<pre><code>prepop_list = [ i for i in xrange( 1, 20+1 ) ]
def new_user( item ):
if item in prepop_list:
prepop_list.remove( item )
else:
return "Item "+ str(item) +" not found"
return prepop_list[0]
first_e_pos = new_user( 4 ) # some new user reserved 4th position
print( first_e_pos )
</code></pre>
| 0 | 2016-08-16T14:58:49Z | [
"python",
"arrays",
"dynamic"
] |
write a reverse proxy in node js to call the api in django | 38,977,853 | <p>My frontend code is running in angular at node httpserver port 127.0.0.1:8081
My backend services runnning in python django framework at port 127.0.0.1:9000
While calling my backend servies from angular http methods throws cors exception
so i wrote a proxy controller in my node js</p>
<pre><code>var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
http.createServer(function (req, res) {
// This simulates an operation that takes 500ms to execute
setTimeout(function () {
proxy.web(req, res, {
target: 'http://127.0.0.1:9000/dummy/'
});
}, 500);
}).listen(8080, "127.0.0.1");
</code></pre>
<p>to listen and bind at angular. i run as the node proxycontroller.js, results a another port no 127.0.0.1:8080</p>
<p>from proxy controller it calls my backend service and result json but from the angular js calling the proxy controller from the http.get() method results cors problem</p>
<p>please help to solve this problem.</p>
| 1 | 2016-08-16T14:40:15Z | 38,978,177 | <p>Enable <code>CORS</code> in Django</p>
<p>Uses this third-party lib <a href="https://github.com/ottoyiu/django-cors-headers/" rel="nofollow">django-cors</a> to do it.</p>
<p>You are getting CORS because you are making the call from your AngularJS app and its host is <code>127.0.0.1:8081</code>, different from your Django app host <code>127.0.0.1:9000</code></p>
| 0 | 2016-08-16T14:55:16Z | [
"python",
"angularjs",
"node.js",
"django",
"reverse-proxy"
] |
write a reverse proxy in node js to call the api in django | 38,977,853 | <p>My frontend code is running in angular at node httpserver port 127.0.0.1:8081
My backend services runnning in python django framework at port 127.0.0.1:9000
While calling my backend servies from angular http methods throws cors exception
so i wrote a proxy controller in my node js</p>
<pre><code>var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
http.createServer(function (req, res) {
// This simulates an operation that takes 500ms to execute
setTimeout(function () {
proxy.web(req, res, {
target: 'http://127.0.0.1:9000/dummy/'
});
}, 500);
}).listen(8080, "127.0.0.1");
</code></pre>
<p>to listen and bind at angular. i run as the node proxycontroller.js, results a another port no 127.0.0.1:8080</p>
<p>from proxy controller it calls my backend service and result json but from the angular js calling the proxy controller from the http.get() method results cors problem</p>
<p>please help to solve this problem.</p>
| 1 | 2016-08-16T14:40:15Z | 38,991,895 | <p>The error said CORS is supported only for specific protocals like http:// etc. So you have to add http to that url. When you say, 127.0.0.1, the browser is unable to understand which protocol to use to access that url, should it be using http:// or data:// or chrome:// etc. So you've to explicitly say http:// </p>
<p>You have to configure cors in the backend. The backend (the API server) much explcitly say a site is allowed using the http header I specified earlier. Otherwise, I can open your website, edit the frontend using chrome console and remove all the security stuff. It has the be in the backend.</p>
<p>as <a href="http://127.0.0.1:9000" rel="nofollow">http://127.0.0.1:9000</a> from the front end angular app, dosent need to create proxy server to transfer the calls to backend service.</p>
| 0 | 2016-08-17T08:41:58Z | [
"python",
"angularjs",
"node.js",
"django",
"reverse-proxy"
] |
TTK, Buttons only have one number on them | 38,977,891 | <pre><code>import tkinter
from tkinter import ttk
def main():
root = tkinter.Tk()
numpad = NumPad(root)
root.mainloop()
numbers = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3']
class NumPad(ttk.Frame):
def __init__(self, root):
ttk.Frame.__init__(self, root)
self.grid()
self.num()
def num(self):
for c in range(1,4):
for r in range(3):
for b in numbers:
cmd = lambda b=b: print(b)
self.b= ttk.Button(self, text=b, command=cmd).grid(row = r, column = c, pady = 5)
#print(b)
main()
</code></pre>
<p>I'm having an issue with this code, as when I try to run it all the buttons only have 3 on them, and the only output is 3. I tried looking at what I did wrong, but still can't find the error. It only picks the last number that is in the "Numbers" function. </p>
<p>Any help is appreciated.</p>
| 2 | 2016-08-16T14:42:00Z | 38,978,138 | <p>For each spot on your grid, you are creating 9 buttons and putting one on top of the other. Only the last button (the one corresponding to 3) ends up showing up and it shows up every time. Instead, you need to figure out the index based on <code>c</code> and <code>r</code> and only create 1 button:</p>
<pre><code>def num(self):
for c in range(1,4):
for r in range(3):
b = (c - 1) * 3 + r
cmd = lambda b=b: print(b)
self.b= ttk.Button(self, text=b, command=cmd).grid(row = r, column = c, pady = 5)
#print(b)
</code></pre>
| 3 | 2016-08-16T14:53:36Z | [
"python",
"python-3.x",
"tkinter",
"ttk"
] |
TTK, Buttons only have one number on them | 38,977,891 | <pre><code>import tkinter
from tkinter import ttk
def main():
root = tkinter.Tk()
numpad = NumPad(root)
root.mainloop()
numbers = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3']
class NumPad(ttk.Frame):
def __init__(self, root):
ttk.Frame.__init__(self, root)
self.grid()
self.num()
def num(self):
for c in range(1,4):
for r in range(3):
for b in numbers:
cmd = lambda b=b: print(b)
self.b= ttk.Button(self, text=b, command=cmd).grid(row = r, column = c, pady = 5)
#print(b)
main()
</code></pre>
<p>I'm having an issue with this code, as when I try to run it all the buttons only have 3 on them, and the only output is 3. I tried looking at what I did wrong, but still can't find the error. It only picks the last number that is in the "Numbers" function. </p>
<p>Any help is appreciated.</p>
| 2 | 2016-08-16T14:42:00Z | 38,978,343 | <p>You are overriding <code>self.b</code> in the last inner loop. Try this:</p>
<pre><code>import tkinter
from tkinter import ttk
def main():
root = tkinter.Tk()
numpad = NumPad(root)
root.mainloop()
numbers = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3']
class NumPad(ttk.Frame):
def __init__(self, root):
ttk.Frame.__init__(self, root)
self.grid()
self.num()
def num(self):
for c in range(3):
for r in range(3):
text = numbers[c*3+r]
cmd = lambda text=text: print(text)
self.b= ttk.Button(self, text=text, command=cmd).grid(row = r, column = c, pady = 5)
main()
</code></pre>
| 1 | 2016-08-16T15:02:31Z | [
"python",
"python-3.x",
"tkinter",
"ttk"
] |
TTK, Buttons only have one number on them | 38,977,891 | <pre><code>import tkinter
from tkinter import ttk
def main():
root = tkinter.Tk()
numpad = NumPad(root)
root.mainloop()
numbers = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3']
class NumPad(ttk.Frame):
def __init__(self, root):
ttk.Frame.__init__(self, root)
self.grid()
self.num()
def num(self):
for c in range(1,4):
for r in range(3):
for b in numbers:
cmd = lambda b=b: print(b)
self.b= ttk.Button(self, text=b, command=cmd).grid(row = r, column = c, pady = 5)
#print(b)
main()
</code></pre>
<p>I'm having an issue with this code, as when I try to run it all the buttons only have 3 on them, and the only output is 3. I tried looking at what I did wrong, but still can't find the error. It only picks the last number that is in the "Numbers" function. </p>
<p>Any help is appreciated.</p>
| 2 | 2016-08-16T14:42:00Z | 38,978,685 | <p>Pair each row-column coordinate with one item from <code>numbers</code> using <code>zip</code>:</p>
<pre><code>def num(self):
rc_gen = ((r, c) for r in range(3) for c in range(3))
for (r, c), num in zip(rc_gen, numbers):
cmd = lambda num=num: print(num)
self.b = ttk.Button(self, text=num, command=cmd).grid(row=r, column=c, pady=5)
</code></pre>
| 0 | 2016-08-16T15:20:49Z | [
"python",
"python-3.x",
"tkinter",
"ttk"
] |
pyinstaller creating EXE RuntimeError: maximum recursion depth exceeded while calling a Python object | 38,977,929 | <p>I am running WinPython 3.4.4.3 with pyinstaller 3.2 (obtained via pip install pyinstaller).</p>
<p>Now I've got some really simple Qt4 code that I want to convert to EXE and I've run into problem that I cannot solve. </p>
<p><strong>The Code:</strong></p>
<pre><code>import sys
import math
from PyQt4 import QtGui, QtCore
import SMui
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
class SomeCalculation(QtGui.QMainWindow, SMui.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.setWindowTitle('Some Calculation')
self.calculate.clicked.connect(self.some_math)
def some_math(self):
a_diameter=self.a_diameter.value()
b_diameter=self.b_diameter.value()
complement=self.complement.value()
angle=self.angle.value()
preload=self.preload.value()
### ONLY MATH HAPPENS HERE also defining X and Y ####
interpolator = InterpolatedUnivariateSpline(X, Y)
### MORE MATH HAPPENS HERE ####
self.axial.setText(str(axial))
self.radial.setText(str(radial))
def main():
app = QtGui.QApplication(sys.argv)
window=SomeCalculation()
window.show()
app.exec_()
if __name__=='__main__':
main()
</code></pre>
<p>I try to run <code>pyinstaller file_name.py</code> and I'm getting:</p>
<pre><code>RuntimeError: maximum recursion depth exceeded while calling a Python object
</code></pre>
<p>Now if there's a few things that I have found out that also affect the issue:</p>
<p>1) If I comment out this line: <code>from scipy.interpolate import InterpolatedUnivariateSpline</code></p>
<p>2) Creating EXE file from another different script that uses Scipy.Interpolate (RBS, but still) - works like a charm.</p>
<p>3) If I try to convert it to EXE using WinPython 3.5.1.1 + pyinstaller obtained the same way, and it's the same 3.2 version of it - it generates my exe file no problems. </p>
<p>I want to understand what's causing the error in the original case and I cannot find any answer on google unfortunately, most of the fixes I could find were related with matplotlib and not interpolation though. </p>
| 1 | 2016-08-16T14:44:00Z | 38,977,984 | <p>i'd try to increase recursion depth limit. Insert at the beginning of your file:</p>
<pre><code>import sys
sys.setrecursionlimit(5000)
</code></pre>
| 0 | 2016-08-16T14:46:44Z | [
"python",
"recursion",
"scipy",
"exe",
"pyinstaller"
] |
How to rerun a script? | 38,977,994 | <p>I have a function named plot(), which displays a graph with data in it. plot() takes it's data from a text file that is being updated every few seconds.</p>
<p>I want plot() to close the matplotlib window, and then run it again every t seconds.</p>
<p>What I have so far:</p>
<pre><code>plot(t):
draw plt
plt.show()
time.sleep(t)
plt.close('all')
def rinse_repeat(t, total_time):
while time.time < total_time
plot()
rinse_repeat
</code></pre>
<p>How can I get this to work? Thanks.</p>
| 0 | 2016-08-16T14:47:09Z | 38,978,335 | <p>This should work for you. Just make a loop that waits and counts seconds:</p>
<pre><code>import time
def plot(t):
draw plt
plt.show()
time.sleep(t)
plt.close('all')
def rinse_repeat(t, total_time):
seconds = 0
while(seconds < total_time):
time.sleep(t)
seconds += t
plot(10) # or whatever you want t to be
</code></pre>
| 0 | 2016-08-16T15:02:09Z | [
"python",
"matplotlib",
"time",
"sleep"
] |
Python how to programmatically build function calls | 38,978,084 | <p>Ok I am not even sure the proper terminology to use to describe what I am trying to do. Anyway, I want to know if it is possible to programmatically or dynamically build a function call in python.</p>
<p>Let me explain.</p>
<p>I have a function inside a class that is defined with optional parameters like so:</p>
<pre><code> class Agents(object):
def update(self, agent_id, full_name = "none", role = "none", status = "none"):
# do some stuff
</code></pre>
<p>So when I when I go to use that function, I may be updating just one, two or all 3 of the optional parameters. Sometimes it may be full_name and role but not status... or status and role but not name, or just status, or well you get the idea.</p>
<p>So I could handle this with a big block of if elif statements to account for all the permutations but that strikes me as really clumsy.</p>
<p>Currently I am calling the function like so:</p>
<pre><code> an_agent = Agents()
an_agent.update(agent_id = r_agent_id)
</code></pre>
<p>Is there anyway to construct that function call programmatically, like appending the arguments to the call before making it. So that I can account for multiple scenarios like so:</p>
<pre><code> an_agent = Agents()
an_agent.update(agent_id = r_agent_id, full_name = r_full_name)
</code></pre>
<p>or </p>
<pre><code> an_agent = Agents()
an_agent.update(agent_id = r_agent_id, full_name = r_full_name, status = r_status)
</code></pre>
<p>Anyway, what is the best way to approach this?</p>
| 0 | 2016-08-16T14:51:21Z | 38,978,161 | <p>If I understand correctly, I think this is what you're looking for:</p>
<pre><code>params = {}
if x:
params['full_name'] = 'something'
if y:
params['role'] = 'something else'
an_agent.update(r_agent_id, **params)
</code></pre>
<p><strong>UPDATE</strong></p>
<p>There are other options, assuming you control the code for <code>Agents</code>. E.g., you could redefine the method like this:</p>
<pre><code>def update(self, agent_id, full_name=None, role=None, status=None):
if full_name is None: full_name = 'none'
if role is None: role = 'none'
if status is None: status = 'none'
...
</code></pre>
<p>and then always pass all arguments:</p>
<pre><code>full_name = None
role = None
status = None
if x:
full_name = 'something'
if y:
role = 'something else'
an_agent.update(r_agent_id, full_name, role, status)
</code></pre>
<p>or perhaps keep the definition of <code>update</code> the same and just initialize your parameters to the string <code>'none'</code>.</p>
| 1 | 2016-08-16T14:54:35Z | [
"python"
] |
How to get GETted json data in Flask | 38,978,160 | <p>I am implementing a REST API in Python using Flask.
I have to get parameters to perform a query and return resources. To be aligned with <code>REST</code> principles, I am going to use a <code>GET</code> request for this operation.</p>
<p>Given that there can be a lot of parameters, I want to send them through a <code>conf.json</code> file, for instance:</p>
<pre><code>{"parameter": "xxx"}
</code></pre>
<p>I perform the request through <code>curl</code>:</p>
<blockquote>
<p>$ curl -H "Content-Type: application/json" --data @conf.json -G <a href="http://localhost:8080/resources/" rel="nofollow">http://localhost:8080/resources/</a></p>
</blockquote>
<p>The request is redirected to the route with these operations:</p>
<pre><code>@resources.route('/resources/', methods=['GET'])
def discover():
if request.get_json():
json_data=request.get_json()
return jsonify(json_data)
</code></pre>
<p>what I get back is:</p>
<pre><code><head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code 400.
<p>Message: Bad request syntax ('GET /resources/?{"parameter": "xxx"} HTTP/1.1').
<p>Error code explanation: 400 = Bad request syntax or unsupported method. </body>
</code></pre>
<p>Somebody knows how to get the json data and properly handle it in the request?</p>
| 0 | 2016-08-16T14:54:25Z | 38,978,254 | <p><code>request.get_json()</code> looks for JSON data in the request <em>body</em> (e.g. what a POST request would include). You put the JSON data in the <em>URL query string</em> of a GET request instead.</p>
<p>Your <code>curl</code> command sends your JSON un-escaped, and produces an invalid URL, so the server <em>rightly</em> rejects that:</p>
<pre><code>http://localhost:8080/resources/?{"parameter": "xxx"}
</code></pre>
<p>You can't have spaces in a URL, for example. You'd have to use <code>--data-urlencode</code> instead for this to be escaped properly:</p>
<pre><code>$ curl --data-urlencode @conf.json -G http://localhost:8080/resources/
</code></pre>
<p>Note that the <code>Content-Type</code> header is not needed here; you don't have any request body to record the content <em>of</em>.</p>
<p>The adjusted <code>curl</code> command now sends a properly encoded URL:</p>
<pre><code>http://localhost:8080/resources/?%7B%22parameter%22%3A%20%22xxx%22%7D%0A%0A
</code></pre>
<p>Access that data with <code>request.query_string</code>. You will also have to <em>decode</em> the URL encoding again before passing this to <code>json.loads()</code>:</p>
<pre><code>from urllib import unquote
json_raw_data = unquote(request.query_string)
json_data = json.loads(json_raw_data)
</code></pre>
<p>Take into account that many webservers put limits on how long a URL they'll accept. If you are planning on sending more than 4k characters in a URL this way, you really need to reconsider and use <code>POST</code> requests instead. That's 4k with the JSON data <em>URL encoded</em>, which adds a considerable overhead.</p>
| 4 | 2016-08-16T14:58:16Z | [
"python",
"json",
"curl",
"flask"
] |
How to get GETted json data in Flask | 38,978,160 | <p>I am implementing a REST API in Python using Flask.
I have to get parameters to perform a query and return resources. To be aligned with <code>REST</code> principles, I am going to use a <code>GET</code> request for this operation.</p>
<p>Given that there can be a lot of parameters, I want to send them through a <code>conf.json</code> file, for instance:</p>
<pre><code>{"parameter": "xxx"}
</code></pre>
<p>I perform the request through <code>curl</code>:</p>
<blockquote>
<p>$ curl -H "Content-Type: application/json" --data @conf.json -G <a href="http://localhost:8080/resources/" rel="nofollow">http://localhost:8080/resources/</a></p>
</blockquote>
<p>The request is redirected to the route with these operations:</p>
<pre><code>@resources.route('/resources/', methods=['GET'])
def discover():
if request.get_json():
json_data=request.get_json()
return jsonify(json_data)
</code></pre>
<p>what I get back is:</p>
<pre><code><head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code 400.
<p>Message: Bad request syntax ('GET /resources/?{"parameter": "xxx"} HTTP/1.1').
<p>Error code explanation: 400 = Bad request syntax or unsupported method. </body>
</code></pre>
<p>Somebody knows how to get the json data and properly handle it in the request?</p>
| 0 | 2016-08-16T14:54:25Z | 38,989,657 | <p>Martijn answer was right with this</p>
<pre><code>$ curl --data-urlencode @conf.json -G http://localhost:8080/resources/
</code></pre>
<p>But you do not need to use <code>urllib</code> to get the args with flask. I would instead on my endpoint just use the following.</p>
<pre><code>@resources.route('/resources')
def test():
args = request.args
return args.get('parameter')
</code></pre>
<p>Also I would look at using the <code>flask_testing</code> extension that way you can setup reproducible test cases that exist within the context of the running application.</p>
<pre><code>from flask_testing import TestCase
from app import app
class TestQueryString(TestCase):
def create_app(self): # Must be implemented
return app
def test_json_parse_args(self):
data = {
'parameter': 'value'
}
r = self.client.get('/resources', query_string=data)
self.assert200(r)
self.assertEqual(r.data, 'value')
</code></pre>
<p><a href="https://pythonhosted.org/Flask-Testing/" rel="nofollow">https://pythonhosted.org/Flask-Testing/</a></p>
| 0 | 2016-08-17T06:37:22Z | [
"python",
"json",
"curl",
"flask"
] |
Does lock file when using flock need to be global | 38,978,163 | <p>I am setting up cron job for single instance.
Does the lock below need to be global? I believe so, in order that it stays in scope until the program finishes. Or at least outside of try/except block. Also, return values should be positive from Python? Seems -2 returns 254 on echo $? in bash. </p>
<pre><code>import time, fcntl, sys
LOCK_FILE = '/tmp/test_flock.lock'
lock = None
def do_wait():
print ('waiting N sec')
time.sleep(3)
def main(argv=None):
try:
global lock
lock = open(LOCK_FILE,'w')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
print ("got flock")
except IOError as err:
print ("Could not obtain lock file")
return -2
if argv is None:
argv = sys.argv
try:
print ('entering main')
print ('waiting')
# raise ValueError("Error raised")
do_wait()
print ('done')
except Exception as err:
print ("Exception in main")
return -1
if __name__ == '__main__':
sys.exit(main())
</code></pre>
| 0 | 2016-08-16T14:54:36Z | 38,984,401 | <p><em>Seems -2 returns 254 on echo $? in bash.</em></p>
<p>The Bash is interpreting the -2 as 254 probably due to how it handles negative numbers which <em>I believe</em> is by returning 8-bit unsigned integers. </p>
<p><strong>Soln:</strong> Use a postive integer number > 0 but < 256. Bash will see a return code > 0 as an error.</p>
<p><em>Does the lock below need to be global? I believe so, in order that it stays in scope until the program finishes.</em></p>
<p><strong>Ans:</strong> If there are no other conflicts with locking the file than I would say that the global lock is fine.</p>
| 0 | 2016-08-16T21:00:59Z | [
"python",
"bash",
"cron"
] |
using bash commands in python on mac: error 127 | 38,978,174 | <p>I am using am using Python 2.7 on MacOS and want to use a bash command within a python script.</p>
<pre><code>command = "someProgram --option1 value 1 --option2 value 2"
</code></pre>
<p>I had to include the path of this program in my bash_profile in order to run it. I tested so far:</p>
<pre><code>os.system(command)
</code></pre>
<p>and</p>
<pre><code>subprocess.check_call(command.split(" "),shell=True)
</code></pre>
<p>Neither worked. The latter threw error 127 and the first one only returned 32512. A google search told me that this occurs when the command is not known. </p>
<p>If I now start this command within the terminal everything works perfectly fine.</p>
<p>Do I have to include something such that python can find this command? Why is this behavior?</p>
| -1 | 2016-08-16T14:55:08Z | 38,978,267 | <p>With <code>shell=True</code> the cmd needs to be a string.</p>
<p><code>subprocess.check_call(command, shell=True)</code></p>
<p>where command is of type <code>str</code></p>
| 1 | 2016-08-16T14:59:07Z | [
"python",
"bash",
"osx"
] |
using bash commands in python on mac: error 127 | 38,978,174 | <p>I am using am using Python 2.7 on MacOS and want to use a bash command within a python script.</p>
<pre><code>command = "someProgram --option1 value 1 --option2 value 2"
</code></pre>
<p>I had to include the path of this program in my bash_profile in order to run it. I tested so far:</p>
<pre><code>os.system(command)
</code></pre>
<p>and</p>
<pre><code>subprocess.check_call(command.split(" "),shell=True)
</code></pre>
<p>Neither worked. The latter threw error 127 and the first one only returned 32512. A google search told me that this occurs when the command is not known. </p>
<p>If I now start this command within the terminal everything works perfectly fine.</p>
<p>Do I have to include something such that python can find this command? Why is this behavior?</p>
| -1 | 2016-08-16T14:55:08Z | 38,998,694 | <p>Thanks for your help. The final solution is kind of stupid. I started spyder via the anaconda GUI. If I do so the above code does not work.</p>
<p>If I run this directly via the console or start spyder via the console everything is fine. It seems that the bash_profile is not loaded when spyder is loaded but requires the console to do so</p>
| 0 | 2016-08-17T13:53:52Z | [
"python",
"bash",
"osx"
] |
Python 2.7 - How do I use an Observer in a Tkinter GUI, where you switch between frames? | 38,978,182 | <p>I'm currently working on a GUI which is based on the thread <a href="http://stackoverflow.com/questions/32212408/how-to-get-variable-data-from-a-class">How to get variable data from a class</a>. Since there will be a lot of data to handle, I would like to use a Model-Class, which get's its updates via Observer.</p>
<p>Right now, changes in the <code>ttk.Combobox</code> on Page One are registered via <code><<ComboboxSelect>></code>, pulled into the variable <code>self.shared_data</code> of the <code>Controller</code> and passed to the <code>Model</code>. This way, no Oberserver/Observable logic is used. Instead, the data in <code>Model</code> is changed, whenever the user takes a corresponding action in the GUI.</p>
<p>I, however, would love not to have to use bindings like <code><<ComboboxSelect>></code> to change the corresponding data in the <code>Model</code>, but an Observer/Observable logic, which detects, that i.e. the entry <code>"Inputformat"</code> in the dictionary <code>self.shared_data</code> within the <code>Controller</code> was changed, which in turn refreshes the data in the <code>Model</code>, i.e. <code>self.model_data</code>, where the actual state of the <code>ttk.Combobox</code> is saved.</p>
<p>In short, I want to achieve the following, by using an Observer: </p>
<p>User selects i.e. "Entry 01" in the <code>ttk.Combobox</code> --> self.shared_data["Inputformat"] in the <code>Controller</code> is now filled with "Entry 01" --> an Observer/Observable logic detects this --> the corresponding variable in the <code>Model</code> is beeing changed.</p>
<p>For you to have something to work with, here is the code.</p>
<pre><code># -*- coding: utf-8 -*-
import csv
import Tkinter as tk # python2
import ttk
import tkFileDialog
# Register a new csv dialect for global use.
# Its delimiter shall be the semicolon:
csv.register_dialect('excel-semicolon', delimiter = ';')
font = ('Calibri', 12)
'''
###############################################################################
# Model #
###############################################################################
'''
class Model:
def __init__(self, *args, **kwargs):
# There shall be a variable, which is updated every time the entry
# of the combobox is changed
self.model_keys = {}
self.model_directories = {}
def set_keys(self, keys_model):
self.model_keys = keys_model
keys = []
keyentries = []
for key in self.model_keys:
keys.append(key)
for entry in self.model_keys:
keyentries.append(self.model_keys[entry].get())
print "model_keys: {0}".format(keys)
print "model_keyentries: {0}".format(keyentries)
def get_keys(self):
keys_model = self.model_keys
return(keys_model)
def set_directories(self, model_directories):
self.model_directories = model_directories
print "Directories: {0}".format(self.model_directories)
def get_directories(self):
model_directories = self.model_directories
return(model_directories)
'''
###############################################################################
# Controller #
###############################################################################
'''
# controller handles the following: shown pages (View), calculations
# (to be implemented), datasets (Model), communication
class PageControl(tk.Tk):
''' Initialisations '''
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs) # init
tk.Tk.wm_title(self, "MCR-ALS-Converter") # title
# initiate Model
self.model = Model()
# file dialog options
self.file_opt = self.file_dialog_options()
# stores checkboxstatus, comboboxselections etc.
self.shared_keys = self.keys()
# creates the frames, which are stacked all over each other
container = self.create_frame()
self.stack_frames(container)
#creates the menubar for all frames
self.create_menubar(container)
# raises the chosen frame over the others
self.frame = self.show_frame("StartPage")
''' Methods to show View'''
# frame, which is the container for all pages
def create_frame(self):
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = ttk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
return(container)
def stack_frames(self, container):
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent = container, controller = self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
# overarching menubar, seen by all pages
def create_menubar(self, container):
# the menubar is going to be seen by all pages
menubar = tk.Menu(container)
menubar.add_command(label = "Quit", command = lambda: app.destroy())
tk.Tk.config(self, menu = menubar)
# function of the controller, to show the desired frame
def show_frame(self, page_name):
#Show the frame for the given page name
frame = self.frames[page_name]
frame.tkraise()
return(frame)
''' Push and Pull of Data from and to Model '''
# calls the method, which pushes the keys in Model (setter)
def push_keys(self):
self.model.set_keys(self.shared_keys)
# calls the method, which pulls the key data from Model (getter)
def pull_keys(self):
pulled_keys = self.model.get_keys()
return(pulled_keys)
# calls the method, which pushes the directory data in Model (setter)
def push_directories(self, directories):
self.model.set_directories(directories)
# calls the method, which pulls the directory data from Model (getter)
def pull_directories(self):
directories = self.model.get_directories()
return(directories)
''' Keys '''
# dictionary with all the variables regarding widgetstatus like checkbox checked
def keys(self):
keys = {}
keys["Inputformat"] = tk.StringVar()
keys["Outputformat"] = tk.StringVar()
return(keys)
''' Options '''
# function, which defines the options for file input and output
def file_dialog_options(self):
#Options for saving and loading of files:
options = {}
options['defaultextension'] = '.csv'
options['filetypes'] = [('Comma-Seperated Values', '.csv'),
('ASCII-File','.asc'),
('Normal Text File','.txt')]
options['initialdir'] = 'C//'
options['initialfile'] = ''
options['parent'] = self
options['title'] = 'MCR-ALS Data Preprocessing'
return(options)
''' Methods (bindings) for PageOne '''
def open_button(self):
self.get_directories()
''' Methods (functions) for PageOne '''
# UI, where the user can selected data, that shall be opened
def get_directories(self):
# open files
file_input = tkFileDialog.askopenfilenames(** self.file_opt)
file_input = sorted(list(file_input))
# create dictionary
file_input_dict = {}
file_input_dict["Input_Directories"] = file_input
self.push_directories(file_input_dict)
'''
###############################################################################
# View #
###############################################################################
'''
class StartPage(ttk.Frame):
''' Initialisations '''
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
self.labels()
self.buttons()
''' Widgets '''
def labels(self):
label = tk.Label(self, text = "This is the start page", font = font)
label.pack(side = "top", fill = "x", pady = 10)
def buttons(self):
button1 = ttk.Button(self, text = "Go to Page One",
command = lambda: self.controller.show_frame("PageOne"))
button2 = ttk.Button(self, text = "Go to Page Two",
command = lambda: self.controller.show_frame("PageTwo"))
button_close = ttk.Button(self, text = "Close",
command = lambda: app.destroy())
button1.pack(side = "top", fill = "x", pady = 10)
button2.pack(side = "top", fill = "x", pady = 10)
button_close.pack(side = "top", fill = "x", pady = 10)
class PageOne(ttk.Frame):
''' Initialisations '''
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
self.labels()
self.buttons()
self.combobox()
''' Widgets '''
def labels(self):
label = tk.Label(self, text = "On this page, you can read data", font = font)
label.pack(side = "top", fill = "x", pady = 10)
def buttons(self):
button_open = ttk.Button(self, text = "Open",
command = lambda: self.controller.open_button())
button_forward = ttk.Button(self, text = "Next Page >>",
command = lambda: self.controller.show_frame("PageTwo"))
button_back = ttk.Button(self, text = "<< Go back",
command = lambda: self.controller.show_frame("StartPage"))
button_home = ttk.Button(self, text = "Home",
command = lambda: self.controller.show_frame("StartPage"))
button_close = ttk.Button(self, text = "Close",
command = lambda: app.destroy())
button_open.pack(side = "top", fill = "x", pady = 10)
button_forward.pack(side = "top", fill = "x", pady = 10)
button_back.pack(side = "top", fill = "x", pady = 10)
button_home.pack(side = "top", fill = "x", pady = 10)
button_close.pack(side = "top", fill = "x", pady = 10)
def combobox(self):
entries = ("", "Inputformat_01", "Inputformat_02", "Inputformat_03")
combobox = ttk.Combobox(self, state = 'readonly', values = entries,
textvariable = self.controller.shared_keys["Inputformat"])
combobox.current(0)
combobox.bind('<<ComboboxSelected>>', self.updater)
combobox.pack(side = "top", fill = "x", pady = 10)
''' Bindings '''
# wrapper, which notifies the controller, that it can update keys in Model
def updater(self, event):
self.controller.push_keys()
class PageTwo(ttk.Frame):
''' Initialisations '''
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
self.labels()
self.buttons()
self.combobox()
''' Widgets '''
def labels(self):
label = tk.Label(self, text = "This is page 2", font = font)
label.pack(side = "top", fill = "x", pady = 10)
def buttons(self):
button_back = ttk.Button(self, text = "<< Go back",
command = lambda: self.controller.show_frame("PageOne"))
button_home = ttk.Button(self, text = "Home",
command = lambda: self.controller.show_frame("StartPage"))
button_close = ttk.Button(self, text = "Close",
command = lambda: app.destroy())
button_back.pack(side = "top", fill = "x", pady = 10)
button_home.pack(side = "top", fill = "x", pady = 10)
button_close.pack(side = "top", fill = "x", pady = 10)
def combobox(self):
entries = ("Outputformat_01", "Outputformat_02")
combobox = ttk.Combobox(self, state = 'readonly', values = entries,
textvariable = self.controller.shared_keys["Outputformat"])
combobox.bind('<<ComboboxSelected>>', self.updater)
combobox.pack(side = "top", fill = "x", pady = 10)
''' Bindings '''
# wrapper, which notifies the controller, that it can update keys in Model
def updater(self, event):
self.controller.push_keys()
if __name__ == "__main__":
app = PageControl()
app.mainloop()
</code></pre>
| 1 | 2016-08-16T14:55:19Z | 39,120,531 | <p>Since I wasn't able to implement an Observer to watch widgets like the ttk.Combobox, I've decided to create a workaround. Here are the steps I took, in order to achieve a MVC architecture from Bryan Oakleys example (link is in the question), which refreshes its model class via the controller class, whenever a user takes an action in the view (GUI). </p>
<p><strong>Step 1: Add a model class</strong></p>
<p>First, in order to use a MVC architecture, we have to seperate the code into model, view and control. In this example, model is <code>class Model:</code>, control is <code>class PageControl(tk.Tk):</code> and view are the pages <code>class StartPage(tk.Frame)</code>, <code>PageOne(tk.Frame)</code> and <code>PageTwo(tk.Frame)</code>.</p>
<p><strong>Step 2: Set up your model class</strong></p>
<p>Now we have to decide on which variables we want to have in the model class. In this example, we have directories and keys (status of the comboboxes), which we want to save in dictionaries. After setting them up empty, all we have to do is add setters and getters for each variable, so we can refresh data in model and also retrieve some, if we want. Additionally, we could implement delet methods for each variable, if we wanted to.</p>
<p><strong>Step 3: Add push and pull methods to the control class</strong></p>
<p>Now that there is a model class, we can refrence it via e. g. <code>self.model = Model()</code> in <code>PageControl(tk.Tk)</code> (control). Now we have the basic tools to set data in <code>Model</code> via e. g. <code>self.model.set_keys(self.shared_keys)</code> and also get data from <code>Model</code>. Since we want our control class to do that, we need some methods, that can achieve this. So we add the push and pull methods to the <code>PageControl</code> (e. g. <code>def push_key(self)</code>), which in turn can be refrenced from view (StartPage, PageOne, PageTwo) via controller.</p>
<p><strong>Step 4: Add your widgets to the view class</strong></p>
<p>Now we have to decide on which widgets shall be on which page and what you want them to do. In this example, there are buttons for navigation, which for the sake of the task can be ignored, two comboboxes and a button, which opens a file dialog. </p>
<p>Here, we want the comboboxes to refresh their status whenever it is changed and send the new status via controller to the model. Whereas the <code>Open</code> button of <code>PageOne</code> shall open a file dialog, where the user then selects files he/she wants to open. The directories we got from this interaction then shall be send via controller to model.</p>
<p><strong>Step 5: Get all your functionality into the controller class</strong></p>
<p>Since there is a controller variable, we can use it to refrence methods, which are in the controller class. This way, we can outsource all our methods from the pages into the controller and reference them via self.controller.function_of_controller_class. But we have to be aware, that methods, which are bound to commands via <code>lambda:</code> can't return any values, but they are also not called on programme startup. So keep that in mind.</p>
<p><strong>Step 6: Set up your bindings and wrappers</strong></p>
<p>Here we have to set up the <code>.bind()</code> for our comboboxes. Since the controller allready is set up to store data and the comboboxes have a textvariable, we can use this to gather information about the status of the comboboxes via <code>combobox.bind(<<ComboboxSelect>>)</code>. All we have to do is to set up a wrapper which is called, whenever <code>combobox.bind(<<ComboboxSelect>>)</code> is throwing an event.</p>
<p><strong>Closing statement</strong></p>
<p>Now we have it, a programme based on Bryan Oakleys example of "How to get variable data from a class", which utilises a model, which is updated via controller whenever the user takes a corresponding action in the view. Unfortunately it doesn't utilise a Observer class, as first intended, but I'll keep working on it and update this, when I've found a satisfying solution.</p>
| 0 | 2016-08-24T10:18:04Z | [
"python",
"model-view-controller",
"tkinter",
"event-handling",
"observer-pattern"
] |
Merge a list of dataframes to create one dataframe | 38,978,214 | <p>I have a list of 18 data frames:</p>
<pre><code>dfList = [df1, df2, df3, df4, df5, df6.....df18]
</code></pre>
<p>All of the data frames have a common id column so it's easy to join them each together with pd.merge 2 at a time. Is there a way to join them all at once so that dfList comes back as a single dataframe?</p>
| 0 | 2016-08-16T14:56:39Z | 38,978,237 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>, but first set index of each <code>DataFrame</code> by common column:</p>
<pre><code>dfs = [df.set_index('id') for df in dfList]
print pd.concat(dfs, axis=1)
</code></pre>
<p>If need join by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow"><code>merge</code></a>:</p>
<pre><code>df = reduce(lambda df1,df2: pd.merge(df1,df2,on='id'), dfList)
</code></pre>
| 1 | 2016-08-16T14:57:34Z | [
"python",
"python-3.x",
"pandas"
] |
Should I create a volume for project files when using Docker with git? | 38,978,228 | <p>I want to Dockerize a project.
I have my project files in a git repo. The project is written in python, and requires a virtual environment to be activated and a pip installation of requirements after the git clone from the repo. The container is going to be a development container, so I would need a basic set of software. Of course I also need to modify the project files, push and pull to git as I prefer.</p>
<p><strong>Solution A</strong><br>
This solution build everything on runtime, and nothing is kept if the container is restarted. It would require the machine to install all the requirements, clone the project every time the container is started. </p>
<ul>
<li>Use the Dockerfile for installing python, virtualenv, etc. </li>
<li>Use the Dockerfile for cloning the project from git, installing pip requirements. </li>
<li>Use docker compose for setting up the environment, memory limits, cpu shares, etc. </li>
</ul>
<p><strong>Solution B</strong><br>
This solution clones the project from git once manually, then the project files are kept in a volume, and you can freely modify them, regardless of container state. </p>
<ul>
<li>Use the Dockerfile for installing python, virtualenv, etc. </li>
<li>Use docker compose for setting up the environment, memory limits, cpu shares, etc. </li>
<li>Create a volume that is mounted on the container </li>
<li>Clone the project files into the volume, set up everything <strong>once</strong>.</li>
</ul>
<p><strong>Solution C</strong><br>
There might be a much better solution that I have not thought of, if there is, be sure to tell.</p>
| 0 | 2016-08-16T14:57:11Z | 38,978,850 | <p>The best solution is B except you will not use a volume in production.</p>
<p>Docker-compose will also allow you to easily mount your code as a volume but you only need this for dev. </p>
<p>In production you will COPY your files into the container.</p>
| 0 | 2016-08-16T15:28:07Z | [
"python",
"git",
"docker",
"docker-compose",
"devops"
] |
How to exec periodically a function in CherryPy | 38,978,299 | <p>This code generate 3 webpages using CheryPy. It's works but now i need to execute periodically the function "PageWeb" to have last informations from a query.
How to use threading in CherryPy:</p>
<pre><code>from Widget import showLine
from Widget import SocketLivestatus
import cherrypy
import threading
def PageWeb(cluster):
# Open Socket
table = SocketLivestatus(['host1','host2'], 50000, cluster)
# Result
Line = showLine(table)
HTML = '''<!doctype html>
<html lang="en">
<head><meta charset="utf-8">
<title>Widget</title>
<link rel="stylesheet" href="css/font-awesome.min.css">
</head>
<body style="background-color: #1F1F1F">'''+Line+'''</body>
</html>'''
return HTML
#BEFORE
re7 = PageWeb("re7")
prod1 = PageWeb("prod1")
prod2 = PageWeb("prod2")
#MY GOAL
re7 = threading.Timer(5.0, PageWeb("re7")).start()
prod1 = threading.Timer(5.0, PageWeb("prod1")).start()
prod2 = threading.Timer(5.0, PageWeb("prod2")).start()
class HelloWorld(object):
@cherrypy.expose
def re7(self):
return re7
@cherrypy.expose
def prod1(self):
return prod1
@cherrypy.expose
def prod2(self):
return prod2
if __name__ == '__main__':
cherrypy.config.update(
{'server.socket_host': '0.0.0.0'} )
cherrypy.quickstart(HelloWorld(),config={
'/':
{ 'tools.staticdir.on':True,
'tools.staticdir.dir': "/app"
}
# '/fonts':
# { 'tools.staticdir.on':True,
# 'tools.staticdir.dir': "/app"
# }
})
</code></pre>
<p>The problem is about threading.Timer(5.0, PageWeb("...")).start() return an error:</p>
<pre><code>Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 1083, in run
self.function(*self.args, **self.kwargs)
TypeError: 'str' object is not callable
</code></pre>
<p>I would like help to use threading function in CherryPy.</p>
| 1 | 2016-08-16T15:00:35Z | 38,983,996 | <p>A <a href="https://docs.python.org/2/library/threading.html#timer-objects" rel="nofollow"><code>threading.Timer</code></a> only runs once:</p>
<blockquote>
<p>This class represents an action that should be run only after a certain amount of time has passed</p>
</blockquote>
<p>After some experimentation, it appears that <code>cherrypy</code> does not work well with threads. The following code uses the <code>multiprocessing</code> library to create a separate <code>Process</code>. The <code>HTML</code> is shared by storing it as the first entry of a managed <code>list</code>:</p>
<pre><code>import cherrypy
import multiprocessing
import time
def PageWeb(cluster, sleep_interval, lock, shared_result):
counter = 0
while True:
HTML = '''<!doctype html>
<html lang="en">
<head><meta charset="utf-8">
<title>Widget</title>
<link rel="stylesheet" href="css/font-awesome.min.css">
</head>
<body style="background-color: #1F1F1F">'''+str(counter)+'''</body>
</html>'''
counter += 1
with lock:
shared_result[0] = HTML
time.sleep(sleep_interval)
class HelloWorld(object):
def __init__(self):
self.re7_lock = multiprocessing.Lock()
self.manager = multiprocessing.Manager()
self.re7_result = self.manager.list()
self.re7_result.append('')
arg_list = ("re7", 5.0, self.re7_lock, self.re7_result)
self.re7_process = multiprocessing.Process(target=PageWeb, args=arg_list)
self.re7_process.daemon = True
self.re7_process.start()
@cherrypy.expose
def re7(self):
with self.re7_lock:
return str(self.re7_result[0])
cherrypy.quickstart(HelloWorld())
</code></pre>
<p>This code is a <a href="http://stackoverflow.com/help/mcve">minimal, complete, and verifiable example</a>. You should be able to integrate it with your code.</p>
| 0 | 2016-08-16T20:34:16Z | [
"python",
"cherrypy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.