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 |
---|---|---|---|---|---|---|---|---|---|
Python - EOF while scanning triple-quoted string literal
| 39,543,231 |
<p>I am trying to write a basic Hangman game and whenever I try to execute it, I get the same error mentioned in the title. I have combed over my code a ton, and while I have fixed some issues I noticed, I still get the same error. Any help? Thanks.</p>
<pre><code>import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
o |
|
|
|
=========''', '''
+---+
| |
o |
| |
|
|
=========''', '''
+---+
| |
o |
/|\ |
|
|
=========''', '''
+---+
| |
o |
/|\ |
/ |
|
=========''', '''
+---+
| |
o |
/|\ |
/ \ |
|
=========''', '''
</code></pre>
<p>words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra' .split()</p>
<pre><code>def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print(HANGMANPICS[len(missedLetters)])
print ()
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks:
print(letter, end=' ')
print()
def getGuess(alreadyGuessed):
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyGuessed:
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a LETTER.')
else:
return guess
def playAgain():
print('Do you want to play again? (yes or no)')
return input().1ower().startswith('y')
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(-HANGMANPICS, missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print('Yes! The secret word is "' + secretWord + '"! You have won!')
gameIsDone = True
else:
missedLetters = missedLetters + guess
if len(missedLetters) == len(HANGMANPICS) - 1:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
if gameIsDOne:
if playAgain():
missedLetters = ''
correctLetters = ''
gameisDone = False
secretWord = getRandomWord(words)
else:
break
</code></pre>
| 0 |
2016-09-17T05:38:10Z
| 39,543,435 |
<p>You don't end the list of HANGMANPICS - your code appears to be</p>
<pre><code> #\/ starts a new list entry which never ends
HANGMANPICS = ['''first''', '''second''', '''
words = 'ant baboon badger' .split()
</code></pre>
<p>and it needs to be</p>
<pre><code> # \/ list ends
HANGMANPICS = ['''first''', '''second''']
words = 'ant baboon badger'.split()
#^ and incidentally, no space here
</code></pre>
| 0 |
2016-09-17T06:11:02Z
|
[
"python",
"string",
"syntax",
"eof"
] |
Python selenium - modifying the source code of a webpage
| 39,543,237 |
<p>I am using Python selenium to automate my attendance entry. It was working fine, now I wanted to try by modifying the source code. I have seen few posts stating that it can be modified using <code>driver.execute_script()</code> and it works for JavaScript, but in my case I need to modify a source code under the <code>select</code> tag. I was able to modify the source code using the <code>inspect element</code>. The following is <code>select</code> tags source code:</p>
<pre><code><select name="date1">
<option value="2016-09-17">2016-09-17</option>
<option value="2016-09-16">2016-09-16</option>
<option value="2016-09-14">2016-09-14</option>
</select>
</code></pre>
<p>I tried to do it with <code>driver.execute_script()</code>. The following was my code:</p>
<pre><code>sel = driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select')
input_list = sel.find_element_by_tag_name('option')
cmd = "input_list.value = '2016-09-07'"
driver.execute_script(cmd)
</code></pre>
<p>But the above code is giving me the following error:</p>
<blockquote>
<p>selenium.common.exceptions.WebDriverException: Message: input_list is not defined</p>
</blockquote>
<p>I am able to modify the source code using the <code>inspect element</code> window. Is there any way to modify the source code using selenium? </p>
| 2 |
2016-09-17T05:39:08Z
| 39,543,372 |
<p>The problem is that <code>execute_script</code> executes JavaScript inside the browser [1], which knows nothing about python variables in python script. In particuar <code>input_list</code> is not defined for JavaScript, since it's a python variable.</p>
<p>To fix this, you can select the element inside the JavaScript file. To do this, you can set your cmd to something like this [2]:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
getElementByXpath("/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select/option[1]").value = '2016-09-07';</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div></div>
<div></div>
<div>
<div>
<div></div>
<div>
<form>
<table>
<tbody>
<tr></tr>
<tr>
<td></td>
<td></td>
<td>
<select name="date1">
<option value="2016-09-17">2016-09-17</option>
<option value="2016-09-16">2016-09-16</option>
<option value="2016-09-14">2016-09-14</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</code></pre>
</div>
</div>
</p>
<p>[1] <a href="https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script" rel="nofollow">https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script</a></p>
<p>[2] <a href="https://stackoverflow.com/questions/10596417/is-there-a-way-to-get-element-by-xpath-using-javascript-in-selenium-webdriver">Is there a way to get element by Xpath using JavaScript in Selenium WebDriver?</a></p>
| 2 |
2016-09-17T06:01:45Z
|
[
"python",
"selenium"
] |
Python selenium - modifying the source code of a webpage
| 39,543,237 |
<p>I am using Python selenium to automate my attendance entry. It was working fine, now I wanted to try by modifying the source code. I have seen few posts stating that it can be modified using <code>driver.execute_script()</code> and it works for JavaScript, but in my case I need to modify a source code under the <code>select</code> tag. I was able to modify the source code using the <code>inspect element</code>. The following is <code>select</code> tags source code:</p>
<pre><code><select name="date1">
<option value="2016-09-17">2016-09-17</option>
<option value="2016-09-16">2016-09-16</option>
<option value="2016-09-14">2016-09-14</option>
</select>
</code></pre>
<p>I tried to do it with <code>driver.execute_script()</code>. The following was my code:</p>
<pre><code>sel = driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/form/table/tbody/tr[2]/td[3]/select')
input_list = sel.find_element_by_tag_name('option')
cmd = "input_list.value = '2016-09-07'"
driver.execute_script(cmd)
</code></pre>
<p>But the above code is giving me the following error:</p>
<blockquote>
<p>selenium.common.exceptions.WebDriverException: Message: input_list is not defined</p>
</blockquote>
<p>I am able to modify the source code using the <code>inspect element</code> window. Is there any way to modify the source code using selenium? </p>
| 2 |
2016-09-17T05:39:08Z
| 39,543,399 |
<p>Try following solution and let me know if any issues occurs:</p>
<pre><code>driver.execute_script("""document.querySelector("select[name='date1'] option").value="2016-09-07";""")
</code></pre>
<p>P.S. I advise you not to use absolute <code>XPath</code> in your selectors, but relative instead</p>
| 0 |
2016-09-17T06:06:03Z
|
[
"python",
"selenium"
] |
ValueError: too many values to unpack, while trying to unpack a simple.txt file
| 39,543,296 |
<p>I have this simple code to read and plot a .txt file </p>
<pre><code>import sys
import os
import numpy
import matplotlib.pyplot as plt
from pylab import *
exp_sum = 'exponential_sum.txt'
Term, Absolute_error, Relative_error= numpy.loadtxt(exp_sum, unpack =True)
plt.semilogy(Term,Absolute_error, 'm^-')
plt.semilogy(Term,Relative_error, 'g-')
xlabel('Number of terms N')
ylabel('Absolute and Relative approximation error')
legend(['Absolute error', 'relative error'], loc = 'upper right')
title('Testing convergence of exponential series with respect to error vs iteration terms')
show()
</code></pre>
<p>which worked fine so far, now it just gives me this weird error while trying to plot this simple text file. please help me how to resolve this value error, the .txt file is also attached.</p>
<pre><code>#Term Exponential_sum Absolute_error Relative_error
0 1.0 1.71828182846 0.632120558829
1 2.0 0.718281828459 0.264241117657
2 2.5 0.218281828459 0.0803013970714
3 2.66666666667 0.0516151617924 0.0189881568762
4 2.70833333333 0.00994849512571 0.00365984682734
5 2.71666666667 0.00161516179238 0.000594184817582
6 2.71805555556 0.00022627290349 8.3241149288e-05
7 2.71825396825 2.78602050767e-05 1.02491966745e-05
8 2.71827876984 3.05861777505e-06 1.12520259784e-06
9 2.71828152557 3.02885852843e-07 1.11425478283e-07
10 2.71828180115 2.73126605776e-08 1.00477663102e-08
11 2.7182818262 2.26055218988e-09 8.31610676352e-10
12 2.71828182829 1.72876379878e-10 6.35976660213e-11
13 2.71828182845 1.22857279905e-11 4.51966674753e-12
14 2.71828182846 8.14903700075e-13 2.99786317792e-13
15 2.71828182846 5.01820807131e-14 1.84609558095e-14
16 2.71828182846 2.22044604925e-15 8.1685645175e-16
17 2.71828182846 4.4408920985e-16 1.6337129035e-16
18 2.71828182846 4.4408920985e-16 1.6337129035e-16
19 2.71828182846 4.4408920985e-16 1.6337129035e-16
</code></pre>
| 1 |
2016-09-17T05:48:44Z
| 39,544,112 |
<p>You're trying to unpack four columns into three variables -- the <code>Exponential_sum</code> variable is missing!</p>
| 1 |
2016-09-17T07:29:13Z
|
[
"python",
"numpy"
] |
How to mock class used in separate namespace?
| 39,543,335 |
<p>Package Structure:</p>
<pre><code>pqr/pq.py
test.py
</code></pre>
<p><code>pqr/pq.py</code> has following structure</p>
<p>Where lmn is globally installed pip module</p>
<p>Structure of <code>pq.py</code></p>
<pre><code>from lmn import Lm
class Ab():
def __init__(self):
self.lm = Lm()
def echo(self, msg):
print msg
</code></pre>
<p><code>test.py</code> has following structure</p>
<pre><code>from pqr.pq import Ab
</code></pre>
<p>How to mock <code>Lm()</code> class over here so to test all method from Ab class?</p>
| 2 |
2016-09-17T05:55:19Z
| 39,576,275 |
<p>It doesn't really matter where <code>Lm</code> came from. You imported <code>Lm</code> into the <code>pqr.pq</code> namespace as a global <em>there</em>, so you'd only have replace that name there and nowhere else. That's because the <code>Ab.__init__</code> method will look for it 'locally' in it's own module.</p>
<p>So using the <a href="https://pypi.python.org/pypi/mock" rel="nofollow"><code>mock</code> library</a> all you need to do is patch the name <code>pqr.pq.Lm</code>:</p>
<pre><code>import mock
from pqr.pq import Ab
with mock.patch('pqr.pq.Lm') as mock_lm:
# within this block, `Lm` in the `pqr.pq` namespace has been replaced
# by a mock object
test_instance = Ab()
# assert that the patch succeeded; .return_value is used because
# Ab.__init__ *calls* Lm()
assert test_instance.lm is mock_lm.return_value
</code></pre>
<p>Also see the <a href="https://docs.python.org/dev/library/unittest.mock.html#where-to-patch" rel="nofollow"><em>Where to patch</em> section</a> of the <code>mock</code> documentation.</p>
| 3 |
2016-09-19T14:58:43Z
|
[
"python",
"python-2.7",
"namespaces",
"mocking",
"python-unittest"
] |
How to mock class used in separate namespace?
| 39,543,335 |
<p>Package Structure:</p>
<pre><code>pqr/pq.py
test.py
</code></pre>
<p><code>pqr/pq.py</code> has following structure</p>
<p>Where lmn is globally installed pip module</p>
<p>Structure of <code>pq.py</code></p>
<pre><code>from lmn import Lm
class Ab():
def __init__(self):
self.lm = Lm()
def echo(self, msg):
print msg
</code></pre>
<p><code>test.py</code> has following structure</p>
<pre><code>from pqr.pq import Ab
</code></pre>
<p>How to mock <code>Lm()</code> class over here so to test all method from Ab class?</p>
| 2 |
2016-09-17T05:55:19Z
| 39,576,637 |
<p>For testing, you can use the <code>mock</code> module (standard in newer python 3, downloadable from pypi for older versions) to create "fake" classes. There is a great article on the mock library that explains how to do this, which I will link <a href="https://www.toptal.com/python/an-introduction-to-mocking-in-python" rel="nofollow">here</a>, that helped me a lot. You will want your test.py file to look something like the code below.</p>
<pre><code>from pqr import pq
import mock
class TestLm(unittest.Testcase):
@mock.patch(pq.LM)
def test_lm(self, mock_lm):
my_ab = pq.AB()
my_ab.echo()
</code></pre>
<p>Using the <code>mock</code> module, you can create a mock version of a module/class that you can use for testing methods, simply by "patching" it in with a decorator above your test method. This replaces the original version of the specified module/class with a MagicMock object, that is then passed into the test method as a second argument. This MagicMock does not actually execute any functionality of <code>Lm</code>, but allows you to make assertions about how it is supposed to work. You can override functionality later, should you need to. However, there is a catch, which is explained in the guide I linked. You need to make sure that you import <code>Lm</code> <strong>from the module in which it is used, not in the traditional manner.</strong> For imports, Python creates module objects that are specific to the module they are imported into, so you need to mock the specific <code>Lm</code> object from the <code>pq</code> module in order to test its functionality. The library is a little complicated to use at first, and contains far more information than is appropriate to cover in a single StackOverflow answer, so I would recommend doing some reading.</p>
<p>Documentation for the <code>mock</code> module can be found <a href="https://docs.python.org/dev/library/unittest.mock.html" rel="nofollow">here</a>.
The download for the Python 2.7 version can be found <a href="https://pypi.python.org/pypi/mock" rel="nofollow">here</a>.</p>
<p>I am fairly new to the <code>mock</code> library myself, so feel free to correct me if I'm wrong!</p>
<p>EDIT: Upon seeing Martijn's answer, I realized I forgot parenthesis in the my_ab constructor!</p>
| 0 |
2016-09-19T15:16:36Z
|
[
"python",
"python-2.7",
"namespaces",
"mocking",
"python-unittest"
] |
How to properly implement trees with n-branching factor in python?
| 39,543,347 |
<p>I am trying to implement a minimax algorithm in python, but I am having some issues creating the branching tree structure. I am still an amateur programmer so please don't mind if my code seems bad. Here is my Node Structure </p>
<pre><code>class Node:
parent = None
state = None
pmax = 0 #this represents the MAX player symbol; i.e. SELF
pmin = 0 #this represents the MIN player symbol; i.e. OPPONENT
stateCost = 0 #this represents utility cost of leaf nodes based on the matrix state
bestCost = None #this represents the chosen path in the minimax algorithm
children = []
def __init__(self,mat,up,mx,mn):
self.parent = up
self.state = mat
self.pmax = mx
self.pmin = mn
stateCost = 0
def addChild(self,newState,up):
n = Node(newState,up,self.pmax,self.pmin)
self.children.append(n)
def evaluateChildren(self,minmax):
ln = len(self.state[0])
for x in range(ln):
#newState = insertIntoSink(self.state[0],x)
cloneState = cloneMatrix(self.state)
newState = insertIntoSink(cloneState,x,minmax)
print "state being added"
for list in newState:
print list
self.addChild(newState,self)
print "done Evaluating CHILDREN"
def evaluateSubChildren(self,minimax):
ln = len(self.state[0])
for l in self.children:
for x in range(ln):
cloneState = cloneMatrix(self.state)
newState = insertIntoSink(cloneState,x,minimax)
l.addChild(newState,l)
</code></pre>
<p>In the case of what I'm doing, there must be 7 children for the root node, and each child should have 7 children of itself. Each child will have a modified clone of the initial matrix in the parent node.</p>
<p>The error occurring is that after adding the subchildren (i.e. second level children) do not get added to the children list, but rather they get added to the root node instead. </p>
<p>The creation of children is being called as follows.</p>
<pre><code> def getBestMove(self):
move =0
maxVal = -1;
i=-1;
#evaluate all the 7 children
self.evaluateChildren(2)
self.evaluateSubChildren(1)
#more calculations go here
</code></pre>
<p>I first tried calling the same evaluateChildren() function as below: </p>
<pre><code> def getBestMove(self):
move =0
maxVal = -1;
i=-1;
#evaluate all the 7 children
self.evaluateChildren(2)
#evaluate second level children
for n in self.children:
print "evaluating SECOND LEVEL CHILDREN"
n.evaluateChildren()
</code></pre>
<p>If I check the number of children of the root node after evaluation, it SHOULD be 7, but it keeps adding more level-2 children to it, which is throwing my program in an infinite loop.</p>
<p>Please let me know where I'm going wrong. Please ask if there are any more information is required. </p>
| 0 |
2016-09-17T05:56:39Z
| 39,543,554 |
<p>You're hitting the common trip-up with lists and variable bindings in Python - you make <code>children = []</code> a class variable, and that makes it <em>the same list</em> in every Node. There's one list in memory and every Node points to it. Change it, and all Nodes see the change. Move that into <code>__init__</code> to make it a new one for each instance. </p>
<pre><code>Class Node:
def __init__(self,mat,up,mx,mn):
self.children = []
</code></pre>
<p>All sorts of people tripping over the same problem 'many things referencing the exact same list by mistake', tons of discussions of what's happening, why, how to avoid it:</p>
<p><a href="http://stackoverflow.com/questions/11216783/python-strange-behavior-with-list-append">Python Strange Behavior with List & Append</a> </p>
<p><a href="http://stackoverflow.com/questions/18263374/weird-list-behavior-in-python">Weird list behavior in python</a></p>
<p><a href="http://stackoverflow.com/questions/12995679/python-array-weird-behavior">Python array weird behavior</a></p>
<p><a href="http://stackoverflow.com/questions/16102777/some-strange-behavior-python-list-and-dict">Some strange behavior Python list and dict</a></p>
<p><a href="http://stackoverflow.com/questions/10191749/strange-behavior-of-lists-in-python">Strange behavior of lists in python</a></p>
<p><a href="http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly">Python list of lists, changes reflected across sublists unexpectedly</a></p>
<p><a href="http://stackoverflow.com/questions/17702937/generating-sublists-using-multiplication-unexpected-behavior">Generating sublists using multiplication ( * ) unexpected behavior</a></p>
<p><a href="http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly">Python list of lists, changes reflected across sublists unexpectedly</a></p>
<p><a href="http://stackoverflow.com/questions/13058458/python-list-index">Python List Index</a></p>
<p><a href="http://stackoverflow.com/questions/17686596/function-changes-list-values-and-not-variable-values-in-python">Function changes list values and not variable values in Python</a></p>
<p><a href="http://stackoverflow.com/questions/16626013/why-does-my-original-list-change">Why does my original list change?</a></p>
<p><a href="http://stackoverflow.com/questions/11993878/python-why-does-my-list-change-when-im-not-actually-changing-it">Python: why does my list change when I'm not actually changing it?</a></p>
<p><a href="http://stackoverflow.com/questions/14301560/python-list-changes-when-global-edited">python: list changes when global edited</a></p>
<p><a href="http://stackoverflow.com/questions/19951816/python-changes-to-my-copy-variable-affect-the-original-variable">python: changes to my copy variable affect the original variable</a></p>
| 0 |
2016-09-17T06:27:55Z
|
[
"python",
"algorithm",
"minimax"
] |
Implement timeit() in extended class in python
| 39,543,357 |
<p>Naive programmer: I'm trying to use the timeit module but I don't know how. I have extended the class:</p>
<pre><code>class Pt:
def __init__(self, x,y):
self.x = x
self.y = y
class pt_set(Pt):
def __init__(self):
self.pts = []
def distance(self):
...
...
return d,(pt1,pt2)
</code></pre>
<p>And I have made an object:</p>
<pre><code>new_points = Pt_set()
</code></pre>
<p>then calling distance:</p>
<pre><code>new_points.distance()
</code></pre>
<p>How can I use the timeit() function on the distance() function?</p>
| 0 |
2016-09-17T05:59:10Z
| 39,543,577 |
<p>It is all explained in the <a href="https://docs.python.org/2/library/timeit.html" rel="nofollow">docs</a>, and this is an example taken from there:</p>
<pre><code> def test():
"""Stupid test function"""
L = []
for i in range(100):
L.append(i)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", setup="from __main__ import test"))
</code></pre>
<p>for complete ref please read the docs.</p>
| 0 |
2016-09-17T06:30:24Z
|
[
"python",
"ipython",
"timeit"
] |
Is there a way to include the same Mixin more than once in a subclass in Python?
| 39,543,420 |
<p>Normally a Python mixin would only be included once, like:</p>
<pre><code>class MyMixin:
pass
class Child(Base, MyMixin):
pass
</code></pre>
<p>However, in some situation it would be handy if we can use the same Mixin twice.
For example, I have a Mixin in SQLAlchemy defining some Columns as follow:</p>
<pre><code>class MyNoteMixin:
note = Column(String)
by_who = Column(String)
</code></pre>
<p>Now I have a subclass that inherits from the above Mixin, but needs two different columns both are of a note nature. Can I do something like:</p>
<pre><code>class Child(Base, MyNoteMixin as "Description", MyNoteMixin as "Quote"):
pass
</code></pre>
<p>So that the resolved table would contain a column named Description that is exactly a MyNoteMixin copy except for the name, AND also has another column named Quote with the same nature.</p>
<p>Is this possible with SQLAlchemy? Or generally speaking, is such usage of Mixin even possible in Python? Thanks.</p>
| 2 |
2016-09-17T06:08:33Z
| 39,552,507 |
<p>I would recommend using <a href="https://docs.python.org/2/glossary.html#term-decorator" rel="nofollow">python decorator</a>. </p>
<p>Here is an example how to get this using plan python class:</p>
<pre><code>def custom_fields(**kwargs):
def wrap(original_class):
"""
Apply here your logic, could be anything!
"""
for key, val in kwargs.items():
setattr(original_class, key, val)
return original_class
return wrap
@custom_fields(quote='String here, can be SQLAlchemy column object')
class Child:
pass
print(Child.quote)
</code></pre>
<p>Output:</p>
<pre><code>>>> String here, can be SQLAlchemy column object
</code></pre>
<p>You will have to adapt it for sqlalchemy, like connect the <code>setattr</code> to your <code>MyNoteMixin</code>.</p>
| 1 |
2016-09-17T22:56:53Z
|
[
"python",
"sqlalchemy",
"mixins"
] |
Python 3 Regex and Unicode Emotes
| 39,543,720 |
<p>Using Python 3, a simple script like the following should run as intended, but appears to choke on unicode emote strings:</p>
<pre><code>import re
phrase = "(â¯Â°â¡Â°)⯠︵ â»ââ»"
pattern = r'\b{0}\b'.format(phrase)
text = "The quick brown fox got tired of jumping over dogs and flipped a table: (â¯Â°â¡Â°)⯠︵ â»ââ»"
if re.search(pattern, text, re.IGNORECASE) != None:
print("Matched!")
</code></pre>
<p>If I substitute the word "fox" for the contents of the phrase variable, the pattern does indeed match. I've been puzzled as to why it doesn't like this particular string though, and my expeditions into the manual and Stack Overflow haven't illuminated the issue. From all I can tell, Python 3 should handle this without issue.</p>
<p>Am I missing something painfully obvious?</p>
<p>Edit: Also, dropping the boundaries (\b) doesn't affect the ability to match the string either.</p>
| 2 |
2016-09-17T06:47:33Z
| 39,543,786 |
<pre><code>(â¯Â°â¡Â°)⯠︵ â»ââ»
</code></pre>
<p>This expression has brackets in them, you need to escape them. Otherwise they are interpreted as group.</p>
<pre><code>In [24]: re.search(r'\(â¯Â°â¡Â°\)⯠︵ â»ââ»', text, re.IGNORECASE)
Out[24]: <_sre.SRE_Match object; span=(72, 85), match='(â¯Â°â¡Â°)⯠︵ â»ââ»'>
In [25]: re.findall(r'\(â¯Â°â¡Â°\)⯠︵ â»ââ»', text, re.IGNORECASE)
Out[25]: ['(â¯Â°â¡Â°)⯠︵ â»ââ»']
</code></pre>
<p><a href="https://docs.python.org/3/library/re.html#re.escape" rel="nofollow">Escape the regex string</a> properly and change your code to:</p>
<pre><code>import re
phrase = "(â¯Â°â¡Â°)⯠︵ â»ââ»"
pattern = re.escape(phrase)
text = "The quick brown fox got tired of jumping over dogs and flipped a table: (â¯Â°â¡Â°)⯠︵ â»ââ»"
if re.search(pattern, text, re.IGNORECASE) != None:
print("Matched!")
</code></pre>
<p>And then it will work as expected:</p>
<pre><code>$ python3 a.py
Matched!
</code></pre>
| 2 |
2016-09-17T06:55:25Z
|
[
"python",
"regex",
"python-3.x",
"unicode"
] |
Cannot import installed python package
| 39,543,747 |
<p>I'm trying to install <strong>python-numpy</strong> package on my ubuntu 14.04 machine. I ran <code>sudo apt-get install python-numpy</code> command to install it and it says the package has been installed but when i try to access it, i'm unable to do so. </p>
<p><a href="http://i.stack.imgur.com/HFgza.png" rel="nofollow"><img src="http://i.stack.imgur.com/HFgza.png" alt="enter image description here"></a></p>
| 0 |
2016-09-17T06:51:53Z
| 39,543,891 |
<p>When you type:</p>
<pre><code>sudo pip install package-name
</code></pre>
<p>It will default install <strong>python2</strong> version of package-name some packages might be supported in both python3 and python3 some might work might not</p>
<p>I would suggest</p>
<pre><code>sudo apt-get install python3-pip
sudo pip3 install MODULENAME
</code></pre>
<p>or can even try this</p>
<pre><code>sudo apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py | sudo python3
sudo pip3 install MODULENAME
</code></pre>
<p>Many python packages require also the dev package, so install it too:</p>
<pre><code>sudo apt-get install python3-dev
</code></pre>
<p>Also check for the sys.path [ make sure module is in the python path ]</p>
| 0 |
2016-09-17T07:06:18Z
|
[
"python"
] |
Remove similar numbers in a list
| 39,543,779 |
<p>How do I remove numbers like 86.1 and 90.1 (or 86.2 and 90.2) from the following list?</p>
<pre><code>86.1 86.2 90.1 90.2
</code></pre>
| -1 |
2016-09-17T06:54:48Z
| 39,543,874 |
<p>Define a threshold, iterate over the sorted numbers and add up the numbers within the threshold:</p>
<pre><code>numbers = [86.1, 86.2, 90.1,90.2]
threshold = 1
numbers = iter(numbers)
amount = last = next(numbers)
count = 1
result = []
for number in sorted(numbers):
if number - last > threshold:
result.append(amount/count)
amount = count = 0
amount += number
count += 1
last = number
</code></pre>
<p>result.append(amount/count)</p>
| 0 |
2016-09-17T07:04:28Z
|
[
"python",
"list",
"python-2.7"
] |
Remove similar numbers in a list
| 39,543,779 |
<p>How do I remove numbers like 86.1 and 90.1 (or 86.2 and 90.2) from the following list?</p>
<pre><code>86.1 86.2 90.1 90.2
</code></pre>
| -1 |
2016-09-17T06:54:48Z
| 39,544,504 |
<p>Try this:</p>
<pre><code>base = [86.1, 86.2, 90.1, 90.2]
# remove = [86.2, 90.2]
remove = [86.1, 90.1]
new_list = [item for item in base if item not in remove]
print(new_list)
</code></pre>
<p>In Stack Overflow post <em><a href="http://stackoverflow.com/questions/11434599/remove-list-from-list-in-python">Remove list from list in Python</a></em> you have more information.</p>
| 0 |
2016-09-17T08:09:45Z
|
[
"python",
"list",
"python-2.7"
] |
Remove similar numbers in a list
| 39,543,779 |
<p>How do I remove numbers like 86.1 and 90.1 (or 86.2 and 90.2) from the following list?</p>
<pre><code>86.1 86.2 90.1 90.2
</code></pre>
| -1 |
2016-09-17T06:54:48Z
| 39,545,464 |
<pre><code>inputList=[86.1, 86.2, 90.1, 90.2]
tolerance=1.0
out=[]
for num in inputList:
if all([abs(num-outAlready)>tolerance for outAlready in out]):
out.append(num)
print out
</code></pre>
| 0 |
2016-09-17T10:00:52Z
|
[
"python",
"list",
"python-2.7"
] |
Converting String of Tuple into Tuple
| 39,543,811 |
<p>How to convert a string in Python into a Tuple without splitting the words into characters?</p>
<p>String: <code>"('name','value')"</code></p>
<p>Expected Output: <code>('name', 'value')</code></p>
| 1 |
2016-09-17T06:58:27Z
| 39,543,842 |
<p>you can use module <code>ast</code></p>
<pre><code>>>> a = "('name','value')"
>>> import ast
>>> ast.literal_eval(a)
('name', 'value')
</code></pre>
| 1 |
2016-09-17T07:01:18Z
|
[
"python"
] |
how do i skip part of each line while reading from file in python
| 39,543,828 |
<p>I am new to python and not able to figure out how do i accomplish this.</p>
<p>Suppose file.txt contains following</p>
<pre><code>iron man 1
iron woman 2
man ant 3
woman wonder 4
</code></pre>
<p>i want to read this file into dictionary in the below format</p>
<pre><code>dict = { 'iron' : ['man', 'woman'], 'man' : ['ant'], 'woman' : ['wonder'] }
</code></pre>
<p>That is the last part in each line being omitted while writing to dictionary.</p>
<p>My second question is can i read this file to dictionary in a way such that</p>
<pre><code>dict2 = { 'iron' : [('man', '1'), ('woman', '2')], 'man' : [('ant', '3')], 'woman' : [('wonder', '4')] } .
</code></pre>
<p>That is key <em>iron</em> will have 2 values but these 2 values being individual tuple.</p>
<p>Second question is for implementation of uniform cost search so that i can access <em>iron</em> child <em>man</em> and <em>woman</em> and cost for these children being 1 and 2</p>
<p>Thank you in advance</p>
| 0 |
2016-09-17T07:00:11Z
| 39,543,962 |
<p>you can use <code>collections.defaultdict</code>:</p>
<p>you 1st answer</p>
<pre><code>import collections.defaultdict
my_dict = cillections.defaultdict(list)
with open('your_file') as f:
for line in f:
line = line.strip().split()
my_dict[line[0]].append(line[1])
print my_dict
</code></pre>
<p>Taking above example, you might able to solve 2nd question.</p>
| 0 |
2016-09-17T07:14:21Z
|
[
"python"
] |
how do i skip part of each line while reading from file in python
| 39,543,828 |
<p>I am new to python and not able to figure out how do i accomplish this.</p>
<p>Suppose file.txt contains following</p>
<pre><code>iron man 1
iron woman 2
man ant 3
woman wonder 4
</code></pre>
<p>i want to read this file into dictionary in the below format</p>
<pre><code>dict = { 'iron' : ['man', 'woman'], 'man' : ['ant'], 'woman' : ['wonder'] }
</code></pre>
<p>That is the last part in each line being omitted while writing to dictionary.</p>
<p>My second question is can i read this file to dictionary in a way such that</p>
<pre><code>dict2 = { 'iron' : [('man', '1'), ('woman', '2')], 'man' : [('ant', '3')], 'woman' : [('wonder', '4')] } .
</code></pre>
<p>That is key <em>iron</em> will have 2 values but these 2 values being individual tuple.</p>
<p>Second question is for implementation of uniform cost search so that i can access <em>iron</em> child <em>man</em> and <em>woman</em> and cost for these children being 1 and 2</p>
<p>Thank you in advance</p>
| 0 |
2016-09-17T07:00:11Z
| 39,544,060 |
<p>For the first question, what you want to do is read each line, split it using white spaces and use a simple if rule to control how you add it to your dictionary:</p>
<pre><code>my_dict = {}
with open('file.txt', 'r') as f:
content = f.read()
for line in content.split('\n'):
item = line.split()
if item[0] not in my_dict:
my_dict[item[0]] = [item[1]]
else:
my_dict[item[0]].append(item[1])
</code></pre>
<p>The second question is pretty much the same, only with a slightly different assignment:</p>
<pre><code>my_dict2 = {}
for line in content.split('\n'):
item = line.split()
if item[0] not in my_dict:
my_dict[item[0]] = [(item[1], item[2])]
else:
my_dict[item[0]].append((item[1], item[2]))
</code></pre>
| 0 |
2016-09-17T07:24:10Z
|
[
"python"
] |
how do i skip part of each line while reading from file in python
| 39,543,828 |
<p>I am new to python and not able to figure out how do i accomplish this.</p>
<p>Suppose file.txt contains following</p>
<pre><code>iron man 1
iron woman 2
man ant 3
woman wonder 4
</code></pre>
<p>i want to read this file into dictionary in the below format</p>
<pre><code>dict = { 'iron' : ['man', 'woman'], 'man' : ['ant'], 'woman' : ['wonder'] }
</code></pre>
<p>That is the last part in each line being omitted while writing to dictionary.</p>
<p>My second question is can i read this file to dictionary in a way such that</p>
<pre><code>dict2 = { 'iron' : [('man', '1'), ('woman', '2')], 'man' : [('ant', '3')], 'woman' : [('wonder', '4')] } .
</code></pre>
<p>That is key <em>iron</em> will have 2 values but these 2 values being individual tuple.</p>
<p>Second question is for implementation of uniform cost search so that i can access <em>iron</em> child <em>man</em> and <em>woman</em> and cost for these children being 1 and 2</p>
<p>Thank you in advance</p>
| 0 |
2016-09-17T07:00:11Z
| 39,544,065 |
<p>Here you go both the parts of your question...Being new to python just spend some time with it like your grilfriend and you will know how it behaves</p>
<pre><code>with open ('file.txt','r') as data:
k = data.read()
lst = k.splitlines()
print lst
dic = {}
dic2 = {}
for i in lst:
p=i.split(" ")
if str(p[0]) in dic.keys():
dic[p[0]].append(p[2])
dic2[p[0]].append((p[1],p[2]))
else:
dic[p[0]] = [p[1]]
dic2[p[0]] = [(p[1],p[2])]
print dic
print dic2
</code></pre>
| 0 |
2016-09-17T07:24:37Z
|
[
"python"
] |
Django Task/Command Execution Best Practice/Understanding
| 39,543,851 |
<p>I've got a little problem with understanding the django management commands. I've got an Webapplication which displays some network traffic information through eth0. Therefore I've created a python class which analyse the traffic and create/update the specific data in the database. Something like this:</p>
<pre><code>class Analyzer:
def doSomething(self):
#analyze the traffic create/update data in db
def startAnalyzing(self):
while 1:
self.doSomething()
</code></pre>
<p>Then I create a management command which creates this class instance and runs <code>startAnalyzing()</code>.</p>
<p><strong>Now my question:</strong></p>
<p>Is this the correct way to do that over management command because the task is not terminating (run the whole time) and not started/stopped via webapplication? Or what is the correct way?</p>
<p>Is it probably better to start the "Analyzer" not via django? Im new to django and wan't to do it the right way. </p>
<p>Is it possible to start sniffing the traffic when i run: manage.py runserver 0.0.0.0:8080? </p>
<p>Many thanks in advance.</p>
| 0 |
2016-09-17T07:01:57Z
| 39,545,353 |
<p>What you're doing is not intended to do with management commands. In fact management commands are what the name implies, a command to manage something, do a quick action. Not keep a whole process running for the entire life time of the web app.</p>
<p>To achieve what you want, you should write a simple python script and keep it running with a process manager (supervisor ?). You just then have to <em>setup</em> django in the beginning of the script so can have access to Django's ORM, which probably is the reason you've chosen Django.</p>
<p>So all in all, you're script would look something like the following:</p>
<pre><code>import sys, os
sys.path.insert(0, "/path/to/parent/of/project") # /home/projects/django-proj
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'proj.settings')
import django
django.setup()
from proj.app.models import DBModel
</code></pre>
<p>This way you can use django's ORM as you would use in a normal Django application. You can also provide templates and views of the Database as you normally would.</p>
<p>The only thing that remains is to keep the script running, and that you can simply do with <a href="http://supervisord.org/" rel="nofollow">supervisord</a>.</p>
| 0 |
2016-09-17T09:48:28Z
|
[
"python",
"django",
"django-manage.py",
"django-management-command"
] |
Python/Pygame: Can you run a program whilst having a Pygame window that can still update?
| 39,543,888 |
<p>this is my first question. What I would like to achieve is in a normal window for the text-based game to be running, however I would also like to have a pygame window running as well that shows a map that updates. Thank you in advance.</p>
| 0 |
2016-09-17T07:06:08Z
| 39,545,057 |
<p>Pygame only supports one display. However, you could divide the screen into multiple <a href="http://www.pygame.org/docs/ref/surface.html" rel="nofollow">Surfaces</a> where one Surface is for the map and the other for the game.</p>
<p>Something like this:</p>
<pre><code>screen = pygame.display.set_mode((100, 100))
top_rect = pygame.Rect((0, 0), (screen.get_width(), screen.get_height() // 2))
bottom_rect = pygame.Rect((0, screen.get_height() // 2), (screen.get_width(), screen.get_height() // 2))
top_screen = screen.subsurface(top_rect)
bottom_screen = screen.subsurface(bottom_rect)
</code></pre>
<p>And update them:</p>
<pre><code>screen.blit(top_screen)
screen.blit(bottom_screen)
pygame.display.update()
</code></pre>
| 0 |
2016-09-17T09:16:07Z
|
[
"python",
"pygame"
] |
Python/Pygame: Can you run a program whilst having a Pygame window that can still update?
| 39,543,888 |
<p>this is my first question. What I would like to achieve is in a normal window for the text-based game to be running, however I would also like to have a pygame window running as well that shows a map that updates. Thank you in advance.</p>
| 0 |
2016-09-17T07:06:08Z
| 39,551,714 |
<p>The only way to have the text entries separate to the pygame window is to use <code>someVar = input("A string")</code> so the text input is in the python shell or the command window/Linux terminal and then have pygame reference that var.</p>
| 0 |
2016-09-17T21:02:36Z
|
[
"python",
"pygame"
] |
Python/Pygame: Can you run a program whilst having a Pygame window that can still update?
| 39,543,888 |
<p>this is my first question. What I would like to achieve is in a normal window for the text-based game to be running, however I would also like to have a pygame window running as well that shows a map that updates. Thank you in advance.</p>
| 0 |
2016-09-17T07:06:08Z
| 39,552,335 |
<p>By <em>normal window</em>, I guess you mean the console window from which your program runs.<br> You need a <em>thread</em>.<br> In the following example, that thread is the one reading the standard input from the command line. </p>
<pre><code>from threading import Thread
userInput= None
def readInput():
while True:
userInput = raw_input (" where to ? ")
print("%s ok."%userInput)
t = Thread( target=readInput )
t.start()
</code></pre>
<p>You could also have the while loop as the main loop of your program, and the thread would run the pygame loop. Or even have two threads, one for both.</p>
| 0 |
2016-09-17T22:33:06Z
|
[
"python",
"pygame"
] |
Python/Pygame: Can you run a program whilst having a Pygame window that can still update?
| 39,543,888 |
<p>this is my first question. What I would like to achieve is in a normal window for the text-based game to be running, however I would also like to have a pygame window running as well that shows a map that updates. Thank you in advance.</p>
| 0 |
2016-09-17T07:06:08Z
| 39,573,442 |
<p>Likely in the case of Pygame, you can have simultaneous output to the graphical window and the standard text output.</p>
<p>The challenge will be how to obtain user input asynchronously (without blocking).</p>
<p>While <code>threads</code> are a good solution, there are others.</p>
<p>There are several solutions to that particular challenge in the following question: <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python?rq=1">Non-blocking read on a subprocess.PIPE in python</a></p>
<p>Another idea is to get the input in the graphical window.</p>
| 1 |
2016-09-19T12:39:52Z
|
[
"python",
"pygame"
] |
Python exercise: last letter / first letter
| 39,543,899 |
<p>I'm a newbie Python student and I'm going through some simple (but now, for me, complicated) exercises. I tried in many ways, but I decided to stop guessing, because I believe it won't be a sane routine of learning.</p>
<p>I have to solve the following exercise:</p>
<blockquote>
<p>Write a <code>lastfirst(lst)</code> function, that, given a list, returns the
first word in the list that starts with a different character from the
last character of the previous word. If there isn't such a word,
return <code>None</code>.</p>
<p>Example:</p>
<p><code>lst = ['sole','elmo','orco','alba','asta']</code> returns <code>'alba'</code></p>
<p><code>lst = ['sky','you','use','ear','right']</code> returns <code>None</code></p>
</blockquote>
<p>I've tried to solve it, and what I had is this:</p>
<pre><code>lst = ['sole','elmo','orco','alba','asta']
def lastfirst(lst):
cont = 0
d = 1
for a in lst[cont:]:
for b in lst[d:]:
if a[-1] != b[0]:
return lst[d]
else:
cont = cont + 1
d = d + 1
print(lastfirst(lst))
</code></pre>
<p>The problem I detected is:</p>
<p>The program doesn't make a distinction between taking the first letter of the first word and the last letter of the second word, or the last letter of the first word and the first letter of the second word.</p>
<p>PS: Sorry for my English :)</p>
| 1 |
2016-09-17T07:06:47Z
| 39,544,021 |
<p>I think it will work (in python 3):</p>
<pre><code>lst = ['sole','elmo','orco','alba','asta']
def lastfirst(lst):
for i in range(len(lst)-1):
if lst[i][-1] != lst[i+1][0] :
return lst[i+1]
return None
print(lastfirst(lst))
</code></pre>
<p>Output:</p>
<pre><code>alba
</code></pre>
<blockquote>
<p><strong>Explanation(Modifications needed in your code) :</strong></p>
<ul>
<li>We don't need two for loops we can do it in single for loop.</li>
<li>Although you do increment <code>cont</code> variable in <code>else</code> statement but it will always compare it with same string which is <code>a</code>.</li>
</ul>
</blockquote>
<p>Another Input :</p>
<pre><code>lst = ['sky','you','use','ear','right']
</code></pre>
<p>Output: </p>
<pre><code>None
</code></pre>
<p>Hope it will help you.</p>
| 2 |
2016-09-17T07:20:17Z
|
[
"python",
"list",
"function",
"for-loop"
] |
Python exercise: last letter / first letter
| 39,543,899 |
<p>I'm a newbie Python student and I'm going through some simple (but now, for me, complicated) exercises. I tried in many ways, but I decided to stop guessing, because I believe it won't be a sane routine of learning.</p>
<p>I have to solve the following exercise:</p>
<blockquote>
<p>Write a <code>lastfirst(lst)</code> function, that, given a list, returns the
first word in the list that starts with a different character from the
last character of the previous word. If there isn't such a word,
return <code>None</code>.</p>
<p>Example:</p>
<p><code>lst = ['sole','elmo','orco','alba','asta']</code> returns <code>'alba'</code></p>
<p><code>lst = ['sky','you','use','ear','right']</code> returns <code>None</code></p>
</blockquote>
<p>I've tried to solve it, and what I had is this:</p>
<pre><code>lst = ['sole','elmo','orco','alba','asta']
def lastfirst(lst):
cont = 0
d = 1
for a in lst[cont:]:
for b in lst[d:]:
if a[-1] != b[0]:
return lst[d]
else:
cont = cont + 1
d = d + 1
print(lastfirst(lst))
</code></pre>
<p>The problem I detected is:</p>
<p>The program doesn't make a distinction between taking the first letter of the first word and the last letter of the second word, or the last letter of the first word and the first letter of the second word.</p>
<p>PS: Sorry for my English :)</p>
| 1 |
2016-09-17T07:06:47Z
| 39,544,110 |
<p>You would use a double <code>for</code> loop when you need to test every word in <code>lst</code> against every other word in <code>lst</code>, but that's not what we want here. We just need a single <code>for</code> loop, and we need to store the previous word so we can test it against the current word. Like this:</p>
<pre><code>def lastfirst(lst):
if not lst:
return None
prev = lst[0]
for word in lst[1:]:
if word[0] != prev[-1]:
return word
prev = word
return None
data = [
['sole', 'elmo', 'orco', 'alba', 'asta'],
['sky', 'you', 'use', 'ear', 'right'],
[],
['help', 'please', 'everybody', 'thanks'],
]
for lst in data:
print(lastfirst(lst))
</code></pre>
<p><strong>output</strong></p>
<pre><code>alba
None
None
thanks
</code></pre>
<p>My function first does</p>
<pre><code>if not lst:
return None
</code></pre>
<p>so we return immediately if we get passed an empty list. Otherwise, the program will crash when it attempts to do <code>prev = lst[0]</code></p>
<hr>
<p>Here's an efficient way to do the test using a single line. </p>
<pre><code>def lastfirst(lst):
return next((v for u, v in zip(lst, lst[1:]) if u[-1] != v[0]), None)
</code></pre>
<p>This code is obviously more compact than my previous version, and it <em>might</em> be a little faster. But it <em>is</em> harder to understand, especially if you are new to Python. Some people think that "one-liners" like this are more Pythonic, but actually it is more Pythonic to make your code as readable as possible. :)</p>
| 1 |
2016-09-17T07:29:05Z
|
[
"python",
"list",
"function",
"for-loop"
] |
Python exercise: last letter / first letter
| 39,543,899 |
<p>I'm a newbie Python student and I'm going through some simple (but now, for me, complicated) exercises. I tried in many ways, but I decided to stop guessing, because I believe it won't be a sane routine of learning.</p>
<p>I have to solve the following exercise:</p>
<blockquote>
<p>Write a <code>lastfirst(lst)</code> function, that, given a list, returns the
first word in the list that starts with a different character from the
last character of the previous word. If there isn't such a word,
return <code>None</code>.</p>
<p>Example:</p>
<p><code>lst = ['sole','elmo','orco','alba','asta']</code> returns <code>'alba'</code></p>
<p><code>lst = ['sky','you','use','ear','right']</code> returns <code>None</code></p>
</blockquote>
<p>I've tried to solve it, and what I had is this:</p>
<pre><code>lst = ['sole','elmo','orco','alba','asta']
def lastfirst(lst):
cont = 0
d = 1
for a in lst[cont:]:
for b in lst[d:]:
if a[-1] != b[0]:
return lst[d]
else:
cont = cont + 1
d = d + 1
print(lastfirst(lst))
</code></pre>
<p>The problem I detected is:</p>
<p>The program doesn't make a distinction between taking the first letter of the first word and the last letter of the second word, or the last letter of the first word and the first letter of the second word.</p>
<p>PS: Sorry for my English :)</p>
| 1 |
2016-09-17T07:06:47Z
| 39,544,262 |
<p>Here's a solution using itertools.</p>
<p>First, define a function that returns a boolean if your condition is met:</p>
<pre><code>def check_letters(apair):
"In a pair, check last letter of first entry with first letter of second"
return apair[0][-1] == apair[1][0]
</code></pre>
<p>Now we use the pairwise function from the <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code> module</a> recipes:</p>
<pre><code>import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
</code></pre>
<p>And finally:</p>
<pre><code>lst = ['sole','elmo','orco','alba','asta']
lstlast = [item[1] for item in pairwise(lst) if not check_letters(item)]
# returns ['alba']
</code></pre>
| 0 |
2016-09-17T07:43:32Z
|
[
"python",
"list",
"function",
"for-loop"
] |
Streaming mp3 files in Django through Nginx
| 39,543,946 |
<p>I have a website based on Django framework. I am running website via Nginx webserver (uWSGI,Django,Nginx). I want to stream mp3 files on my website with Accept-Ranges header. I want to serve my mp3 files with Nginx. I need my API to look like this</p>
<pre><code>http://192.168.1.105/stream/rihanna
</code></pre>
<p>This must return mp3 file with partial download (Accept-Ranges).
My mp3 files are stored in : /home/docker/code/app/media/data/
When I run the server with these configurations and browse to 192.168.1.105/stream/rihanna , Django returns 404.</p>
<p>My Nginx conf:</p>
<pre><code># mysite_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
server unix:/home/docker/code/app.sock; # for a file socket
# server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on, default_server indicates that this server block
# is the block to use if no blocks match the server_name
listen 80 default;
include /etc/nginx/mime.types;
# the domain name it will serve for
server_name .example.com; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
autoindex on;
sendfile on;
sendfile_max_chunk 1024m;
internal;
#add_header X-Static hit;
alias /home/docker/code/app/media/; # your Django project's media files - amend as required
}
location /static {
alias /home/docker/code/app/static/; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /home/docker/code/uwsgi_params; # the uwsgi_params file you installed
}
}
</code></pre>
<p>My views.py :</p>
<pre><code>def stream(request, offset):
try:
mp3_path = os.getcwd() + '/media/data/' + offset + '.mp3'
mp3_data = open(mp3_path, "r").read()
except:
raise Http404()
response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = mp3_path
response['X-Accel-Buffering'] = 'no'
response['Content-Length'] = os.path.getsize(mp3_path)
response['Content-Dispostion'] = "attachment; filename=" + mp3_path
response['Accept-Ranges'] = 'bytes'
</code></pre>
<p>I want Nginx serve this files. And I really need Accept-Ranges enabled.</p>
<p>My Settings.py :</p>
<pre><code># Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.105', '0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'beats.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'beats.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = os.path.join(BASE_DIR, 'media/')
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
</code></pre>
<p>My problem is: It doesn't work, and Django return 404 Error webpage.</p>
| 0 |
2016-09-17T07:12:58Z
| 39,614,152 |
<p>First of all, I did not copy the Nginx configuration file to the available-sites path. And because of it,It didn't work.
And in my views.py :</p>
<pre><code>response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = mp3_path
</code></pre>
<p>these 2 lines must be changed to:</p>
<pre><code>response= HttpResponse('', content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = '/media/data/' + offset + '.mp3'
</code></pre>
<p>I hope it helps anybody else who has this problem.</p>
| 0 |
2016-09-21T10:35:24Z
|
[
"python",
"django",
"nginx",
"http-headers",
"uwsgi"
] |
Python 3: How to call function from another file and pass arguments to that function ?
| 39,543,961 |
<p>I want to call a function from another file and pass arguments from current file to that file. With below example, In file <strong>bye.py</strong> I want to call function "<strong>me</strong>" from "<strong>hi.py</strong>" file and pass "<strong>goodbye</strong>" string to function "<strong>me</strong>". How to do that ? Thank you :)</p>
<p>I have file hi.py</p>
<pre><code>def me(string):
print(string)
me('hello')
</code></pre>
<p>bye.py</p>
<pre><code>from hi import me
me('goodbye')
</code></pre>
<p>What I got:</p>
<pre><code>hello
goodbye
</code></pre>
<p>What I would like: </p>
<pre><code>goodbye
</code></pre>
| 1 |
2016-09-17T07:14:10Z
| 39,543,981 |
<p>Generally when you create files to be imported you must use <code>if __name__ == '__main__'</code> which evaluates to false in case you are importing the file from another file. So your hi.py may look as:</p>
<pre><code>def me(string):
print(string)
if __name__ == '__main__':
# Do some local work which should not be reflected while importing this file to another module.
me('hello')
</code></pre>
| 1 |
2016-09-17T07:16:14Z
|
[
"python",
"function",
"python-3.x"
] |
How can I access Python code from JavaScript in PyQT 5.7?
| 39,544,089 |
<p>I used to do it by attaching an object</p>
<pre><code>self.page().mainFrame().addToJavaScriptWindowObject("js_interface", self.jsi)
</code></pre>
<p>In 5.7 I do:</p>
<pre><code>self.page().setWebChannel(self.jsi)
</code></pre>
<p>But I understandibly get a JavaScript error when I try to access exposed functions:</p>
<pre><code>js: Uncaught ReferenceError: js_interface is not defined
</code></pre>
<p>Googling around I found that I should use qwebchannel.js, but I couldn't find the file or instructions on how to use it anywhere (there was some info, but only in some examples provided when installing QT, not PyQT).</p>
| 0 |
2016-09-17T07:27:01Z
| 39,593,748 |
<p>Take a look at <a href="http://doc.qt.io/qt-5/qtwebchannel-standalone-example.html" rel="nofollow">this page</a>. It contains a useful example (in c++ but easily translatable into python).</p>
<p>First of all, you have to use a websocket to communicate from html to your app and viceversa.</p>
<p>Then you can set up your QWebChannel.</p>
| 1 |
2016-09-20T12:11:01Z
|
[
"javascript",
"python",
"qt",
"pyqt"
] |
Python setting global variables in different ways in 2.7
| 39,544,100 |
<p>I was trying to practice a concept related to setting global variables using diff methods , but the following example is not working as per my understanding .</p>
<pre><code>#Scope.py
import os
x = 'mod'
def f1() :
global x
x = 'in f1'
def f2() :
import scope
scope.x = 'in f2'
def print_x() :
print x
def f3() :
import sys
sc = sys.modules['scope']
sc.x = 'in f3'
if __name__ == "__main__" :
f1()
print_x()
f2()
print_x()
f3()
print_x()
</code></pre>
<p>It gives the following result </p>
<pre><code>in f1
in f1
in f1
</code></pre>
<p>While as per my understanding it shd result in</p>
<pre><code>in f1
in f2
in f3
</code></pre>
<p>Can someone help me in understanding what am i doing wrong ??</p>
| 0 |
2016-09-17T07:28:11Z
| 39,545,627 |
<p>Check out this modified piece of code.</p>
<pre><code>x = 'mod'
def f1():
global x
x = 'in f1'
def f2():
import scope
scope.x = 'in f2'
return scope
def print_x():
print(x)
def f3():
import sys
sc = sys.modules['__main__']
sc.x = 'in f3'
return sc
if __name__ == "__main__":
f1()
print_x()
sc = f2()
print_x()
print(sc.x)
sc = f3()
print_x()
print(sc.x)
</code></pre>
<p>The thing is that in the original <code>f2()</code> you actually import your <code>scope</code> module under name <code>scope</code> and modify its variable. And in following <code>print_x()</code> you refer to an unchanged <code>x</code> in <code>__main__</code>. In <code>f3()</code>, you reference your module by wrong name: to modify it, you should use <code>__main__</code> here. With <code>scope</code>, you're actually referencing the module that was imported in <code>f2()</code> (Try removing <code>f2()</code> call)... Which is clearly not what you want.</p>
| 1 |
2016-09-17T10:17:53Z
|
[
"python",
"scope"
] |
collect text from web pages of a given site
| 39,544,123 |
<p>There is a site that I frequenly visit and read the "best advice". Here is how I can easily extract the text that I want...</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
mylist=list()
myurl='http://www.apartmenttherapy.com/carols-east-side-cottage-house-tour-194787'
s=urllib2.urlopen(myurl)
soup = BeautifulSoup(s)
hello = soup.find(text='Best Advice: ')
mylist.append(hello.next)
</code></pre>
<p>But how do I collect the text snippets from all the pages?</p>
<hr>
<p>I can search for all pages using this simple google query...</p>
<p>site:<a href="http://www.apartmenttherapy.com" rel="nofollow">http://www.apartmenttherapy.com</a></p>
<p>Does google search has API that can be used in python?
I am looking for one time simple solution for this problem. So I will prefer not to install too many packages to get this task done.</p>
| -2 |
2016-09-17T07:30:26Z
| 39,695,818 |
<p>You have to use a js-enabled scraping like the way explained here :
<a href="http://koaning.io/dynamic-scraping-with-python.html" rel="nofollow">http://koaning.io/dynamic-scraping-with-python.html</a></p>
| 0 |
2016-09-26T06:14:46Z
|
[
"python",
"beautifulsoup",
"google-search-api"
] |
collect text from web pages of a given site
| 39,544,123 |
<p>There is a site that I frequenly visit and read the "best advice". Here is how I can easily extract the text that I want...</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
mylist=list()
myurl='http://www.apartmenttherapy.com/carols-east-side-cottage-house-tour-194787'
s=urllib2.urlopen(myurl)
soup = BeautifulSoup(s)
hello = soup.find(text='Best Advice: ')
mylist.append(hello.next)
</code></pre>
<p>But how do I collect the text snippets from all the pages?</p>
<hr>
<p>I can search for all pages using this simple google query...</p>
<p>site:<a href="http://www.apartmenttherapy.com" rel="nofollow">http://www.apartmenttherapy.com</a></p>
<p>Does google search has API that can be used in python?
I am looking for one time simple solution for this problem. So I will prefer not to install too many packages to get this task done.</p>
| -2 |
2016-09-17T07:30:26Z
| 39,735,886 |
<p>You may read the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> manual first and also learn to use web developper tool to inspect network flow.</p>
<p>Once done, you may see that you can get the list of house with a GET request <a href="http://www.apartmenttherapy.com/search?page=1&q=House+Tour&type=all" rel="nofollow">http://www.apartmenttherapy.com/search?page=1&q=House+Tour&type=all</a> </p>
<p>Assuming that, we can iterate from page 1 to X to get all houses index page.</p>
<p>On each index page you get exactly 15 urls to add to a list.</p>
<p>Once you got the complete urls list, you may scrap each url to get "best advice" text on each of them.</p>
<p>Please see the following code which do the job :</p>
<pre><code>import time
import requests
import random
from bs4 import BeautifulSoup
#here we get a list of all url to scrap
url_list=[]
max_index=2
for page_index in range(1,max_index):
#get index page
html=requests.get("http://www.apartmenttherapy.com/search?page="+str(page_index)+"&q=House+Tour&type=all").content
#iterate over teaser
for teaser in BeautifulSoup(html).findAll('a',{'class':'SimpleTeaser'}):
#add link to url list
url_list.append(teaser['href'])
#sleep a litte to avoid overload/ to be smart
time.sleep(random.random()/2.) # respect server side load
#here I break because it s just an example (it does not required to scrap all index page)
break #comment this break in production
#here we show list
print url_list
#we iterate over url to get the advice
mylist=[]
for url in url_list:
#get teaser page
html=requests.get(url).content
#find best advice text
hello = BeautifulSoup(html).find(text='Best Advice: ')
#print advice
print "advice for",url,"\n","=>",
#try to add next text to mylist
try:
mylist.append(hello.next)
except:
pass
#sleep a litte to avoid overload/ to be smart
time.sleep(random.random()/2.) # respect server side load
#show list of advice
print mylist
</code></pre>
<p>output are:</p>
<pre><code>['http://www.apartmenttherapy.com/house-tour-a-charming-comfy-california-cottage-228229', 'http://www.apartmenttherapy.com/christinas-olmay-oh-my-house-tour-house-tour-191725', 'http://www.apartmenttherapy.com/house-tour-a-rustic-refined-ranch-house-227896', 'http://www.apartmenttherapy.com/caseys-grown-up-playhouse-house-tour-215962', 'http://www.apartmenttherapy.com/allison-and-lukes-comfortable-and-eclectic-apartment-house-tour-193440', 'http://www.apartmenttherapy.com/melissas-eclectic-austin-bungalow-house-tour-206846', 'http://www.apartmenttherapy.com/kates-house-tour-house-tour-197080', 'http://www.apartmenttherapy.com/house-tour-a-1940s-art-deco-apartment-in-australia-230294', 'http://www.apartmenttherapy.com/house-tour-an-art-filled-mid-city-new-orleans-house-227667', 'http://www.apartmenttherapy.com/jeremys-light-and-heavy-home-house-tour-201203', 'http://www.apartmenttherapy.com/mikes-cabinet-of-curiosities-house-tour-201878', 'http://www.apartmenttherapy.com/house-tour-a-family-dream-home-in-illinois-227791', 'http://www.apartmenttherapy.com/stephanies-greenwhich-gemhouse-96295', 'http://www.apartmenttherapy.com/masha-and-colins-worldly-abode-house-tour-203518', 'http://www.apartmenttherapy.com/tims-desert-light-box-house-tour-196764']
advice for http://www.apartmenttherapy.com/house-tour-a-charming-comfy-california-cottage-228229
=> advice for http://www.apartmenttherapy.com/christinas-olmay-oh-my-house-tour-house-tour-191725
=> advice for http://www.apartmenttherapy.com/house-tour-a-rustic-refined-ranch-house-227896
=> advice for http://www.apartmenttherapy.com/caseys-grown-up-playhouse-house-tour-215962
=> advice for http://www.apartmenttherapy.com/allison-and-lukes-comfortable-and-eclectic-apartment-house-tour-193440
=> advice for http://www.apartmenttherapy.com/melissas-eclectic-austin-bungalow-house-tour-206846
=> advice for http://www.apartmenttherapy.com/kates-house-tour-house-tour-197080
=> advice for http://www.apartmenttherapy.com/house-tour-a-1940s-art-deco-apartment-in-australia-230294
=> advice for http://www.apartmenttherapy.com/house-tour-an-art-filled-mid-city-new-orleans-house-227667
=> advice for http://www.apartmenttherapy.com/jeremys-light-and-heavy-home-house-tour-201203
=> advice for http://www.apartmenttherapy.com/mikes-cabinet-of-curiosities-house-tour-201878
=> advice for http://www.apartmenttherapy.com/house-tour-a-family-dream-home-in-illinois-227791
=> advice for http://www.apartmenttherapy.com/stephanies-greenwhich-gemhouse-96295
=> advice for http://www.apartmenttherapy.com/masha-and-colins-worldly-abode-house-tour-203518
=> advice for http://www.apartmenttherapy.com/tims-desert-light-box-house-tour-196764
=> [u"If you make a bad design choice or purchase, don't be afraid to change it. Try and try again until you love it.\n\t", u" Sisal rugs. They clean up easily and they're very understated. Start with very light colors and add colors later.\n", u"Bring in what you love, add dimension and texture to your walls. Decorate as an individual and not to please your neighbor or the masses. Trends are fun but I love elements of timeless interiors. Include things from any/every decade as well as mixing styles. I'm convinced it's the hardest way to decorate without looking like you are living in a flea market stall. Scale, color, texture, and contrast are what I focus on. For me it takes some toying around, and I always consider how one item affects the next. Consider space and let things stand out by limiting what surrounds them.", u'You don\u2019t need to invest in \u201cdecor\u201d and nothing needs to match. Just decorate with the special things (books, cards, trinkets, jars, etc.) that you\u2019ve collected over the years, and be organized. I honestly think half the battle of having good home design is keeping a neat house. The other half is just displaying stuff that is special to you. Stuff that has a story and/or reminds you of people, ideas, and places that you love. One more piece of advice - the best place to buy picture frames is Goodwill. Pick a frame in decent condition, and just paint it to complement your palette. One last piece of advice\u2014 decor need not be pricey. I ALWAYS shop consignment and thrift, and then I repaint and customize as I see fit.\n', u'From my sister \u2014 to use the second bedroom as my room, as it is dark and quiet, both of which I need in order to sleep.\n', u'Collect things that you love in your travels throughout life. I tend to purchase ceramics when travelling, sometimes a collection of bowls\u2026 not so easy transporting in the suitcase, but no breakages yet!\n\t', u'Keep things authentic to the character of your home and to the character of your family. Then, you can never go wrong!\n\t', u'Contemporary architecture does not require contemporary furnishings.\n']
</code></pre>
| 1 |
2016-09-27T23:37:00Z
|
[
"python",
"beautifulsoup",
"google-search-api"
] |
Regexing help in python
| 39,544,125 |
<p>I am wondering if there is an efficient way to check if a number is in the format 1_2_3_4_5_6_7_8_9_0 , where the '_' is a number.
For Example,</p>
<p><strong>1</strong>9<strong>2</strong>9<strong>3</strong>7<strong>4</strong>2<strong>5</strong>4<strong>6</strong>2<strong>7</strong>4<strong>8</strong>8<strong>9</strong>0<strong>0</strong></p>
<p>My initial though was string indexing, but I quickly discovered that it was too slow. Is there a better way using regexing in python? </p>
<p>Thanks in advance,
Arvind</p>
| 0 |
2016-09-17T07:30:44Z
| 39,544,156 |
<blockquote>
<p>My initial thought was string indexing, but I quickly discovered that
it was too slow</p>
</blockquote>
<p>Most possibly you are not using the right approach</p>
<p>You can always use regex but, string indexing with strides can have better performance than using regex</p>
<pre><code>st = "1929374254627488900"
st[::2] == "1234567890"
Out[93]: True
</code></pre>
| 0 |
2016-09-17T07:33:32Z
|
[
"python",
"regex",
"string"
] |
Regexing help in python
| 39,544,125 |
<p>I am wondering if there is an efficient way to check if a number is in the format 1_2_3_4_5_6_7_8_9_0 , where the '_' is a number.
For Example,</p>
<p><strong>1</strong>9<strong>2</strong>9<strong>3</strong>7<strong>4</strong>2<strong>5</strong>4<strong>6</strong>2<strong>7</strong>4<strong>8</strong>8<strong>9</strong>0<strong>0</strong></p>
<p>My initial though was string indexing, but I quickly discovered that it was too slow. Is there a better way using regexing in python? </p>
<p>Thanks in advance,
Arvind</p>
| 0 |
2016-09-17T07:30:44Z
| 39,544,167 |
<p>Let's define a string to test:</p>
<pre><code>>>> q = '1929374254627488900'
</code></pre>
<p>Now, let's test it:</p>
<pre><code>>>> q[::2] == '1234567890'
True
</code></pre>
<p>That matches. Now, let's try one that doesn't match:</p>
<pre><code>>>> q = '1929374254627488901'
>>> q[::2] == '1234567890'
False
</code></pre>
<p>This works because <code>q[::2]</code> returns every other character in the string and those are the characters that you are interested in testing.</p>
<h3>Additional tests</h3>
<p>Suppose we are unsure if the string is all numbers. In that case, we add a test. This should pass:</p>
<pre><code>>>> q = '1929374254627488900'
>>> q[::2] == '1234567890' and q.isdigit()
True
</code></pre>
<p>While, because of the <code>a</code>, this should fail:</p>
<pre><code>>>> q = '19293742546274889a0'
>>> q[::2] == '1234567890' and q.isdigit()
False
</code></pre>
<p>We can also test for correct length:</p>
<pre><code>>>> q = '1929374254627488900'
>>> q[::2] == '1234567890' and q.isdigit() and len(q) == 19
True
</code></pre>
| 1 |
2016-09-17T07:34:30Z
|
[
"python",
"regex",
"string"
] |
Regexing help in python
| 39,544,125 |
<p>I am wondering if there is an efficient way to check if a number is in the format 1_2_3_4_5_6_7_8_9_0 , where the '_' is a number.
For Example,</p>
<p><strong>1</strong>9<strong>2</strong>9<strong>3</strong>7<strong>4</strong>2<strong>5</strong>4<strong>6</strong>2<strong>7</strong>4<strong>8</strong>8<strong>9</strong>0<strong>0</strong></p>
<p>My initial though was string indexing, but I quickly discovered that it was too slow. Is there a better way using regexing in python? </p>
<p>Thanks in advance,
Arvind</p>
| 0 |
2016-09-17T07:30:44Z
| 39,544,190 |
<p>Here you go, indexing is fast O(1)</p>
<pre><code>>>> my_number = 1929374254627488900
>>> int(str(my_number)[1::2])
997242480 # actual number
>>> int(str(my_number)[0::2])
1234567890 #format
</code></pre>
| 0 |
2016-09-17T07:36:27Z
|
[
"python",
"regex",
"string"
] |
Continuously attempt to connect bluetooth socket until connection is successful
| 39,544,127 |
<p>I want to keep trying to connect to a bluetooth device until the connection is successful. The code below uses a recursive call, and this could lead to the maximum level of recursion being met.</p>
<p>Does <code>BluetoothSocket.connect()</code> return a value for success or failure?</p>
<pre><code>def connect(self):
# the bluetooth device uses port 1
port = 1
if not self.quit:
try:
print 'Attempting Connection...'
# Create the client socket
self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
self.socket.connect((self.bt_mac, port))
except bluetooth.btcommon.BluetoothError:
self.connect()
return self.SUCCESS
</code></pre>
<p>The documentation states the following:</p>
<pre><code>connect(self, addrport)
connect(addrport)
</code></pre>
<p>availability: GNU/Linux, Windows XP</p>
<p>Connect the socket to a remote device. For L2CAP sockets, <code>addrport</code> is a <code>(host,psm)</code> tuple. For RFCOMM sockets, <code>addrport</code> is a <code>(host,channel)</code> tuple. For SCO sockets, <code>addrport</code> is just the host.</p>
| 1 |
2016-09-17T07:30:48Z
| 39,582,778 |
<p><code>BluetoothSocket.connect()</code> does not explicitly return a value that signals success or failure. However, this can be achieved by returning an error flag when <code>bluetooth.btcommon.BluetoothError</code> exception is caught.</p>
<p>So in the except block, instead of trying to connect again right there, we can return an error flag (e.g. <code>self.ERROR = -1</code>)</p>
<pre><code>def connect(self):
# the bluetooth device uses port 1
port = 1
try:
print 'Attempting Connection...'
# Create the client socket
self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
self.socket.connect((self.bt_mac, port))
except bluetooth.btcommon.BluetoothError:
return self.ERROR
return self.SUCCESS
</code></pre>
<p>The above connect method would be called inside of an infinite loop (code shown below) that is broken only when success is returned from the connect function. Otherwise, the connect method will continuously be called.</p>
<pre><code>while True:
# connect to device
res = mydevice.connect()
# print connection status -1=fail, 0=success
if res == SUCCESS:
print "Success"
# break out of connection loop if success
break
if res == ERROR:
print "Failed"
</code></pre>
| 0 |
2016-09-19T21:59:42Z
|
[
"python",
"bluetooth"
] |
Setting values of an array without a loop
| 39,544,152 |
<p>I have arrays called <code>rad</code>, <code>relative_x</code>, <code>relative_y</code>, where <code>rad</code> is not of the same size as the other two. I want to create an array called <code>masking</code>, that will have the length of <code>rad</code> in the following way:</p>
<pre><code>masking[i] = (relative_x**2 + relative_y**2 <= (rad[i])**2) & (relative_x**2 + relative_y**2 >= (rad[i]*0.9)**2)
</code></pre>
<p>but I want to do it without a loop. Is there a way to do this in python?</p>
| 0 |
2016-09-17T07:33:18Z
| 39,544,295 |
<p><code>zip()</code> and a list comprehension pretty much does it. You still have a loop, but it's somewhat hidden.</p>
<pre><code>>>> rad = [1.42, 4, 8]
>>> relative_x = [1, 2, 3, 4, 5]
>>> relative_y = [1, 2, 3, 4, 5]
>>>
>>> masking = [rad_**2 >= relative_x_**2 + relative_y_**2 >= (rad_*0.9)**2
for (rad_, relative_x_, relative_y_) in zip(rad, relative_x, relative_y)]
>>> print masking
[True, False, False]
</code></pre>
<p>Note that in python, you're allowed to do <code>1 < 2 < 3</code>.</p>
| 0 |
2016-09-17T07:47:32Z
|
[
"python",
"arrays"
] |
IOError: [Errno 13] when installing virtualwrapper
| 39,544,184 |
<p>After successfully installling virtualenv in terminal with 'pip install virtualenv', I tried installing virtualwrapper with 'pip install virtualenvwrapper' and something seems to have gone wrong with some code presenting in red instead of the usual white. There was about 20-30 lines of code in essence it said the following:</p>
<p>Installing collected packages: virtualenv-clone, pbr, stevedore, virtualenvwrapper</p>
<p>Exception:</p>
<p>Traceback (most recent call last):</p>
<p>Then there is a list of file paths shown, followed by..</p>
<blockquote>
<p>IOError: [Errno 13] Permission denied:
'/usr/local/lib/python2.7/dist-packages/clonevirtualenv.py'</p>
</blockquote>
<p><img src="http://i.stack.imgur.com/ekllf.png" alt="see screenshot of the code for more detail"></p>
<p>Does anyone know what could have gone wrong and how I can fix it?</p>
<p>Thanks</p>
| 0 |
2016-09-17T07:35:55Z
| 39,544,523 |
<p>when it's about permission problem you have try with sudo(super user).</p>
<p>if Linux,</p>
<p><code>$ sudo pip install virtualenvwrapper</code></p>
<p>if Windows,</p>
<p>open cmd with administration privilege and then,</p>
<p><code>pip install virtualenvwrapper</code></p>
| 0 |
2016-09-17T08:12:26Z
|
[
"python",
"virtualenvwrapper",
"errno",
"ioerror"
] |
IOError: [Errno 13] when installing virtualwrapper
| 39,544,184 |
<p>After successfully installling virtualenv in terminal with 'pip install virtualenv', I tried installing virtualwrapper with 'pip install virtualenvwrapper' and something seems to have gone wrong with some code presenting in red instead of the usual white. There was about 20-30 lines of code in essence it said the following:</p>
<p>Installing collected packages: virtualenv-clone, pbr, stevedore, virtualenvwrapper</p>
<p>Exception:</p>
<p>Traceback (most recent call last):</p>
<p>Then there is a list of file paths shown, followed by..</p>
<blockquote>
<p>IOError: [Errno 13] Permission denied:
'/usr/local/lib/python2.7/dist-packages/clonevirtualenv.py'</p>
</blockquote>
<p><img src="http://i.stack.imgur.com/ekllf.png" alt="see screenshot of the code for more detail"></p>
<p>Does anyone know what could have gone wrong and how I can fix it?</p>
<p>Thanks</p>
| 0 |
2016-09-17T07:35:55Z
| 39,568,398 |
<p>First, uninstall virtualenv</p>
<pre><code># you might need to use sudo depending on how you installed it
pip uninstall virtualenv
</code></pre>
<p>Then, install virtualenvwrapper with sudo</p>
<pre><code>sudo pip install virtualenwrapper
</code></pre>
<p>Since virtualenvwrapper has virtualenv among its dependencies, it will take care of installing it - no need to do it manually.</p>
| 0 |
2016-09-19T08:19:36Z
|
[
"python",
"virtualenvwrapper",
"errno",
"ioerror"
] |
IOError: [Errno 13] when installing virtualwrapper
| 39,544,184 |
<p>After successfully installling virtualenv in terminal with 'pip install virtualenv', I tried installing virtualwrapper with 'pip install virtualenvwrapper' and something seems to have gone wrong with some code presenting in red instead of the usual white. There was about 20-30 lines of code in essence it said the following:</p>
<p>Installing collected packages: virtualenv-clone, pbr, stevedore, virtualenvwrapper</p>
<p>Exception:</p>
<p>Traceback (most recent call last):</p>
<p>Then there is a list of file paths shown, followed by..</p>
<blockquote>
<p>IOError: [Errno 13] Permission denied:
'/usr/local/lib/python2.7/dist-packages/clonevirtualenv.py'</p>
</blockquote>
<p><img src="http://i.stack.imgur.com/ekllf.png" alt="see screenshot of the code for more detail"></p>
<p>Does anyone know what could have gone wrong and how I can fix it?</p>
<p>Thanks</p>
| 0 |
2016-09-17T07:35:55Z
| 39,568,497 |
<p>You should install virtualenvwrapper via system package manager.</p>
<p>Either <code>dnf install python-virtualenvwrapper</code> on Fedora or <code>apt-get install virtualenvwrapper</code> on Debian/Ubuntu.</p>
| 0 |
2016-09-19T08:24:20Z
|
[
"python",
"virtualenvwrapper",
"errno",
"ioerror"
] |
Remove emojis from python string
| 39,544,235 |
<p>I need to remove emoji's from some strings using a python script. I found that someone already asked this <a href="http://stackoverflow.com/questions/33404752/removing-emojis-from-a-string-in-python">question</a>, and one of the answers was marked as successful, namely that the following code would do the trick:</p>
<pre><code>#!/usr/bin/env python
import re
text = u'This dog \U0001f602'
print(text) # with emoji
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
print(emoji_pattern.sub(r'', text)) # no emoji
</code></pre>
<p>I inserted this code into my script, and changed it only to be acting on the strings in my code rather than the sample text. When I run the code, though, I get some errors I don't understand:</p>
<pre><code>Traceback (most recent call last):
File "SCRIPT.py", line 31, in get_tweets
"]+", flags=re.UNICODE)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework /Versions/2.7/lib/python2.7/re.py", line 194, in compile
return _compile(pattern, flags)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: bad character range
</code></pre>
<p>I get what the error is saying, but since I grabbed this code from Stackexchange, I cannot figure out why it apparently worked for the people in this discussion but not for me. I'm using Python 2.7 if that helps. Thank you!</p>
| 1 |
2016-09-17T07:40:05Z
| 39,544,664 |
<p>Your Python build uses <a href="https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates" rel="nofollow">surrogate pairs</a> to represent unicode characters that can't be represented in 16 bits -- it's a so-called "narrow build". This means that any value at or above <code>u"\U00010000"</code> is being stored as two characters. Since even in unicode mode, the regular expression parser works character-by-character, this can lead to incorrect behavior if you try to use characters in that range.</p>
<p>In this particular case, Python is only seeing the first "half" of the emoji character code as the end of a range, and that "half" is less than the start value of the range, making it invalid.</p>
<pre><code>Python 2.7.10 (default, Jun 1 2015, 09:44:56)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.maxunicode
65535
>>> tuple(u"\U00010000")
(u'\ud800', u'\udc00')
</code></pre>
<p>Basically, you need to get a "wide build" of Python for this to work:</p>
<pre><code>Python 3.5.2 (default, Jul 28 2016, 21:28:00)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.maxunicode
1114111
>>> tuple(u"\U00010000")
('í í°',)
</code></pre>
<p>The character isn't showing up correctly for me in the browser, but it does show only one character, not two.</p>
| 0 |
2016-09-17T08:33:52Z
|
[
"python",
"python-2.7"
] |
Changing values in column selectively. Python Pandas
| 39,544,270 |
<p>for example i have a fruit dataset that contains the name and colour. How do i change the values in colour column based on the fruit name that i select?</p>
<pre><code> Name Color
Apple NaN
Pear Green
Pear Green
Banana Yellow
Watermelon Green
</code></pre>
<p>I have a rough idea but i have no idea how to code it.</p>
<pre><code> df[Name] == Apple then df[color] == Red
</code></pre>
| 0 |
2016-09-17T07:44:44Z
| 39,544,291 |
<p>One way is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">.apply()</a>:</p>
<pre><code>In [83]: df
Out[83]:
Name Color
0 Apple NaN
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
In [84]: df['Color'] = df.apply(lambda x: 'Red' if x.Name == 'Apple' else x.Color, 1)
In [85]: df
Out[85]:
Name Color
0 Apple Red
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
</code></pre>
<p>Another simpler way is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow">.ix</a>:</p>
<pre><code>In [94]: df
Out[94]:
Name Color
0 Apple NaN
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
In [95]: df.ix[df.Name == 'Apple', 'Color'] = 'Red'
In [96]: df
Out[96]:
Name Color
0 Apple Red
1 Pear Green
2 Pear Green
3 Banana Yellow
4 Watermelon Green
</code></pre>
| 1 |
2016-09-17T07:47:14Z
|
[
"python",
"pandas"
] |
ConfigParser instance has no attribute '__setitem__'
| 39,544,331 |
<p>i'm trying to initialize the config file
</p>
<pre><code>import ConfigParser
config = ConfigParser.ConfigParser()
config['Testing'] = {"name": "Yohannes", "age": 10}
with open("test.ini", "w") as configFile:
config.write(configFile)
</code></pre>
<p>but it keeps throwing this error </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\user\workspace\ObjectDetection\src\confWriter.py", line 9, in <module>
config['Testing'] = {"name": "Yohannes", "age": 10}
AttributeError: ConfigParser instance has no attribute '__setitem__'
</code></pre>
<p>I searched everywhere but didn't find anything</p>
| -1 |
2016-09-17T07:52:06Z
| 39,544,402 |
<pre><code>config.Testing = {"name": "Yohannes", "age": 10}
</code></pre>
| -1 |
2016-09-17T07:59:15Z
|
[
"python",
"python-2.7",
"file",
"configuration"
] |
ConfigParser instance has no attribute '__setitem__'
| 39,544,331 |
<p>i'm trying to initialize the config file
</p>
<pre><code>import ConfigParser
config = ConfigParser.ConfigParser()
config['Testing'] = {"name": "Yohannes", "age": 10}
with open("test.ini", "w") as configFile:
config.write(configFile)
</code></pre>
<p>but it keeps throwing this error </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\user\workspace\ObjectDetection\src\confWriter.py", line 9, in <module>
config['Testing'] = {"name": "Yohannes", "age": 10}
AttributeError: ConfigParser instance has no attribute '__setitem__'
</code></pre>
<p>I searched everywhere but didn't find anything</p>
| -1 |
2016-09-17T07:52:06Z
| 39,544,488 |
<p>You are simply not using it right. <a href="https://docs.python.org/2/library/configparser.html#examples" rel="nofollow">Here</a> you can find examples.</p>
<pre><code>config = ConfigParser.ConfigParser()
config.add_section('Testing')
config.set('Testing', 'name', 'Yohannes')
config.set('Testing', 'age', 10)
</code></pre>
<p>About the error you are getting you can read <a href="https://docs.python.org/3/reference/datamodel.html#object.%5F%5Fsetitem%5F%5F" rel="nofollow">here</a>:</p>
<blockquote>
<p><code>object.__setitem__(self, key, value)</code>
Called to implement assignment to <code>self[key]</code>.</p>
</blockquote>
| 0 |
2016-09-17T08:08:18Z
|
[
"python",
"python-2.7",
"file",
"configuration"
] |
Python Regex matching any order
| 39,544,344 |
<p>Lets say I have datetime in the format</p>
<pre><code>12 September, 2016
September 12, 2016
2016 September, 12
</code></pre>
<p>I need regex like it should return match in same order always for any dateformat given above</p>
<pre><code>match-1 : 12
match-2 : September
match-3 : 2016
</code></pre>
<p>I need results in the same order always. </p>
| 0 |
2016-09-17T07:53:13Z
| 39,544,382 |
<p>You cannot change group orderings. You need to do a "or" of 3 patterns and then pass through the result to determine which group mapped to what, which should be pretty simple.</p>
| 0 |
2016-09-17T07:57:34Z
|
[
"python",
"regex",
"datetime",
"match"
] |
Python Regex matching any order
| 39,544,344 |
<p>Lets say I have datetime in the format</p>
<pre><code>12 September, 2016
September 12, 2016
2016 September, 12
</code></pre>
<p>I need regex like it should return match in same order always for any dateformat given above</p>
<pre><code>match-1 : 12
match-2 : September
match-3 : 2016
</code></pre>
<p>I need results in the same order always. </p>
| 0 |
2016-09-17T07:53:13Z
| 39,546,729 |
<p>You can't switch the group order but you can name your groups:</p>
<pre><code>(r'(?P<day>[\d]{2})(?:\s|,|\?|$)|(?P<month>[a-zA-Z]+)|(?P<year>[\d]{4})')
</code></pre>
<ul>
<li><p><code>(?P<day>[\d]{2})(?:\s|,|\?|$)</code>: matches a day, can be accessed in python with <code>l.group("day")</code></p></li>
<li><p><code>(?P<month>[a-zA-Z]+)</code>: matches a month, can be accessed in python with <code>l.group("month")</code></p></li>
<li><p><code>(?P<year>[\d]{4})</code>: matches a year, can be accessed in python with <code>l.group("year")</code></p></li>
</ul>
<p>Example:</p>
<pre><code>import re
data = """
12 September, 2016
September 12, 2016
2016 September, 12
September 17, 2012
17 October, 2015
"""
rgx = re.compile(r'(?P<day>[\d]{2})(?:\s|,|\?|$)|(?P<month>[a-zA-Z]+)|(?P<year>[\d]{4})')
day = ""
month = ""
year = ""
for l in rgx.finditer(data):
if(l.group("day")):
day = l.group("day")
elif(l.group("month")):
month = l.group("month")
elif(l.group("year")):
year = l.group("year")
if(day != "" and month != "" and year != ""):
print "{0} {1} {2}".format(day, month, year)
day = ""
month = ""
year = ""
</code></pre>
<p><a href="https://ideone.com/4o0vfQ" rel="nofollow">Demo</a></p>
| 0 |
2016-09-17T12:18:22Z
|
[
"python",
"regex",
"datetime",
"match"
] |
Python Regex matching any order
| 39,544,344 |
<p>Lets say I have datetime in the format</p>
<pre><code>12 September, 2016
September 12, 2016
2016 September, 12
</code></pre>
<p>I need regex like it should return match in same order always for any dateformat given above</p>
<pre><code>match-1 : 12
match-2 : September
match-3 : 2016
</code></pre>
<p>I need results in the same order always. </p>
| 0 |
2016-09-17T07:53:13Z
| 39,546,970 |
<p>Named groups as suggested below is a good way of doing it (especially if you already have the regexes set up) but for completion's sake here's how to handle it with the <code>datetime</code> module.</p>
<pre><code>from datetime import datetime as date
def parse_date(s):
formats = ["%d %B, %Y",
"%B %d, %Y",
"%Y %B, %d"]
for f in formats:
try:
return date.strptime(s, f)
except ValueError:
pass
raise ValueError("Invalid date format!")
arr = ["12 September, 2016",
"September 12, 2016",
"2016 September, 12",
"12/9/2016"]
for s in arr:
dt = parse_date(s)
print(dt.year, dt.strftime("%B"), dt.day)
"""
2016 September 12
2016 September 12
2016 September 12
Traceback (most recent call last):
File "C:/Python33/datetest.py", line 22, in <module>
dt = parse_date(s)
File "C:/Python33/datetest.py", line 19, in parse_date
raise ValueError("Invalid date format!")
ValueError: Invalid date format!
"""
</code></pre>
<p>For more information, see the <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow">datetime documentation page</a>.</p>
| 2 |
2016-09-17T12:44:52Z
|
[
"python",
"regex",
"datetime",
"match"
] |
Input and Output of function in pyspark
| 39,544,499 |
<p>I'd like to get some lesson about the input grammar in pyspark.</p>
<p>My platform is below.</p>
<pre><code>Red Hat Enterprise Linux Server release 6.8 (Santiago)
spark version 1.6.2
python 2.6
</code></pre>
<p>I have def defined in module <strong>basic_lib.py</strong> as below.</p>
<pre><code>def selectRowByTimeStamp(x,y):
if x._1 > y._1:
return x
return y
</code></pre>
<p>Below is my snippet of the main code</p>
<pre><code> df2 = df2.map(lambda x: (x._2, x))
rdd = df2.reduceByKey(basic_lib.selectRowByTimeStamp)
</code></pre>
<p>Why does above <strong>basic_lib.selectRowByTimeStamp</strong> work without clearly
specifying the input parameter?</p>
<p>For example , something like below is more easy to understand.</p>
<pre><code>var1 = 1
var2 = 2
rdd = df2.reduceByKey(basic_lib.selectRowByTimeStamp(var1, var2))
</code></pre>
| 1 |
2016-09-17T08:09:16Z
| 39,546,601 |
<p>It looks like you're slightly confused about what exactly is the purpose of <code>lambda</code> expressions. In general <code>lambda</code> expression in Python are used to create anonymous, single expression functions. Other than than that, as far as we care here, there are not different than any other function you define. To quote the docs:</p>
<blockquote>
<p>Small anonymous functions can be created with the lambda keyword. (...) Lambda functions can be used wherever function objects are required. <strong>Semantically, they are just syntactic sugar for a normal function definition.</strong> </p>
</blockquote>
<p>Since lambda functions are not special in Python in general there cannot be special in PySpark (well, they may require some serialization tricks due to their scope but it is only about their scope). No matter if function is defined by <code>lambda</code> or not (or if it is even a function*) Spark applies it in exactly the same way. So when you call:</p>
<pre><code>df2.map(lambda x: (x._2, x))
</code></pre>
<p>lambda expression is simply evaluated and what is received by <code>map</code> is just another function object. It wouldn't be different if you assigned if first:</p>
<pre><code>foo = lambda x: (x._2, x) # Yup, this is against style guide (PEP 8)
</code></pre>
<p>or created a standalone function:</p>
<pre><code>def bar(x):
return x._2, x
</code></pre>
<p>In all three cases function object is functionally pretty much the same:</p>
<pre><code>import dis
dis.dis(foo)
## 1 0 LOAD_FAST 0 (x)
## 3 LOAD_ATTR 0 (_2)
## 6 LOAD_FAST 0 (x)
## 9 BUILD_TUPLE 2
## 12 RETURN_VALUE
dis.dis(bar)
## 2 0 LOAD_FAST 0 (x)
## 3 LOAD_ATTR 0 (_2)
## 6 LOAD_FAST 0 (x)
## 9 BUILD_TUPLE 2
## 12 RETURN_VALUE
dis.dis(lambda x: (x._2, x))
## 1 0 LOAD_FAST 0 (x)
## 3 LOAD_ATTR 0 (_2)
## 6 LOAD_FAST 0 (x)
## 9 BUILD_TUPLE 2
## 12 RETURN_VALUE
</code></pre>
<p>On a side note if input is a <code>DataFrame</code> here it is much more efficient to solve this using Spark SQL. Also it is better to extract <code>rdd</code> before you use <code>map</code> to ensure forward compatibility. Finally <code>Row</code> is just a tuple. </p>
<p>So optimally you could:</p>
<pre><code>df.groupBy("_2").max()
</code></pre>
<p>but if you really want to use RDD API:</p>
<pre><code>df.select("_2", "_1").rdd.reduceByKey(max)
</code></pre>
<hr>
<p>* In practice any callable object will work as long as it accepts given arguments. For example (not that it makes much sense here) you could replace function with an object of a class defined as follows:</p>
<pre><code>class FooBar(object):
def __call__(self, x):
return x._2, x
df2.rdd.map(FooBar())
</code></pre>
| 2 |
2016-09-17T12:04:51Z
|
[
"python",
"apache-spark",
"pyspark"
] |
Python 3 installing tweepy
| 39,544,517 |
<p>I have looked at all the forums, but nothing has worked so far. I have spent hours trying to install it so any help would be appreciated.
i have downloaded and unzipped tweepy, went on to the command prompt, typed "cd tweepy-master". This works, but when i type "python setup.py install" or "python setup.py build".</p>
<p>When i type "python setup.py install" the error says.</p>
<p>Traceback (most recent call last):
File "setup.py", line 4, in
from setuptools import setup, find_packages
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools__init__.py", line 2, in
from setuptools.extension import Extension, Library
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\extension.py", line 5, in
from setuptools.dist import _get_unpatched
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\dist.py", line 103
except ValueError, e:
^
SyntaxError: invalid syntax</p>
<p>When i type "python setup.py build"</p>
<p>Traceback (most recent call last):
File "setup.py", line 4, in
from setuptools import setup, find_packages
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools__init__.py", line 2, in
from setuptools.extension import Extension, Library
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\extension.py", line 5, in
from setuptools.dist import _get_unpatched
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\dist.py", line 103
except ValueError, e:
^
SyntaxError: invalid syntax</p>
<p>I saw alot of people saying to use pip, but i am struggling to install that to.
Thanks for the help</p>
| 0 |
2016-09-17T08:12:05Z
| 39,544,668 |
<p><code>pip</code> is the good way to install a package. If you are not interested then you can install from source.</p>
<p>But you have to remember that, If you are using <code>virtualenv</code> or <code>virtualenvwrapper</code> then you can use <code>python setup.py install</code> otherwise you should use <code>sudo python setup.py install</code>. </p>
<p>If you are windows user then, open your <code>cmd</code> with administator privilege and type <code>python setup.py install</code>.</p>
| 0 |
2016-09-17T08:34:13Z
|
[
"python",
"python-3.x",
"tweepy"
] |
Python 3 installing tweepy
| 39,544,517 |
<p>I have looked at all the forums, but nothing has worked so far. I have spent hours trying to install it so any help would be appreciated.
i have downloaded and unzipped tweepy, went on to the command prompt, typed "cd tweepy-master". This works, but when i type "python setup.py install" or "python setup.py build".</p>
<p>When i type "python setup.py install" the error says.</p>
<p>Traceback (most recent call last):
File "setup.py", line 4, in
from setuptools import setup, find_packages
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools__init__.py", line 2, in
from setuptools.extension import Extension, Library
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\extension.py", line 5, in
from setuptools.dist import _get_unpatched
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\dist.py", line 103
except ValueError, e:
^
SyntaxError: invalid syntax</p>
<p>When i type "python setup.py build"</p>
<p>Traceback (most recent call last):
File "setup.py", line 4, in
from setuptools import setup, find_packages
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools__init__.py", line 2, in
from setuptools.extension import Extension, Library
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\extension.py", line 5, in
from setuptools.dist import _get_unpatched
File "C:\Users\Sam Terrett\Documents\Portable Python 3.2.5.1\App\lib\site-packages\setuptools\dist.py", line 103
except ValueError, e:
^
SyntaxError: invalid syntax</p>
<p>I saw alot of people saying to use pip, but i am struggling to install that to.
Thanks for the help</p>
| 0 |
2016-09-17T08:12:05Z
| 39,544,778 |
<p>Have you installed Python using the Windows installer from <a href="https://www.python.org/downloads/windows/" rel="nofollow">python.org</a>?</p>
<p>Cause this comes with pip already bundled into it. (I can not check the exact location atm, as I am on a Mac, but according to this <a href="http://stackoverflow.com/questions/25328818/python-2-7-cannot-pip-on-windows-bash-pip-command-not-found">SO</a> post it should be located under <code>C:\PythonX.X\Scripts</code>, if you kept the default install location - otherwise it should be located in <code><path-to-python>\Scripts</code> of course).</p>
<p>Otherwise pip can easily installed using <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">this</a> script. Simply call <code>python get-pip.py</code> in the script location and pip should be available afterwards (if not directly from commandline with <code>pip</code>, than at least by using <code>python -m pip</code>.)
Having pip finally available, you should be able to easily install tweepy calling <code>pip install tweepy</code> (or <code>python -m pip install tweepy</code> respectively).</p>
<p>For further information on pip and the other options to install it, check <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">https://pip.pypa.io/en/stable/installing/</a>.</p>
<p>PS. If installing the package via pip does not work, this may be a compatibility issue. According to the <a href="https://github.com/tweepy/tweepy" rel="nofollow">tweepy github-page</a> python 3.2 is <strong>not</strong> amongst the supported python versions. So if your portable python really has an interpreter versioned 3.2.... (you can check the version of your interpreter running python from cmd, which should print something like <code>> Python 3.X.X</code>), the package may not run properly at all (even if you can install it without a problem).</p>
<p>As the portable python apparently is no longer supported anyways, it may be worth trying a different solution. There are plenty suggested on the <a href="http://portablepython.com" rel="nofollow">portable python</a> website (I just know about Anaconda, but this works flawlessly). But if you only want to use python with tweepy and don't need anything like scipy or numpy, I'd suggest simply downloading the installer from the official website. As said, pip gets shipped with the standard installation and can be used to easily install most of the packages you will need. (Except for e.g. the abovementioned scipy/numpy, which require additional non-python libraries whose "manual" installation may not be worth the trouble and hence legitimates the use of a more comprehensive environment like Anaconda).</p>
| 0 |
2016-09-17T08:46:27Z
|
[
"python",
"python-3.x",
"tweepy"
] |
TypeError in Python Programming
| 39,544,553 |
<p>I wrote the following program for square each digit of a number. But, it is showing an error as "int" object is not iterable.</p>
<pre><code>def square_digits(num):
a = 1
for i in num:
a = i * i
return a
result = square_digits(12)
print(result)
</code></pre>
| -2 |
2016-09-17T08:17:57Z
| 39,544,592 |
<p>You're looking for the <code>range(num)</code> function.</p>
<p>You probably also want to use a <code>list</code> (denoted by <code>[brackets, and, commas]</code>).</p>
<p>Try this for example:</p>
<pre><code>my_list = [] # empty list
for char in 'aword':
my_list.append(char * 2)
print(my_list)
</code></pre>
<p>Or to be really pythonic you can step through the data and create your list at the same time with a list comprehension. Think of it like an in-line <code>for</code> loop that returns a <code>list</code>:</p>
<pre><code>result = [char * 2 for char in 'aword']
print(result)
</code></pre>
<p>The first part (<code>char * 2</code>) tells what you want in each entry of the list. In your case that would be a squaring operation on some source data. The second part (<code>for char in 'aword'</code>) tells you where to get the source data from. In your case it would be <code>range(num)</code>.</p>
| 2 |
2016-09-17T08:21:51Z
|
[
"python"
] |
TypeError in Python Programming
| 39,544,553 |
<p>I wrote the following program for square each digit of a number. But, it is showing an error as "int" object is not iterable.</p>
<pre><code>def square_digits(num):
a = 1
for i in num:
a = i * i
return a
result = square_digits(12)
print(result)
</code></pre>
| -2 |
2016-09-17T08:17:57Z
| 39,545,176 |
<p>first off, this is how to fix your code:</p>
<p>If you want a list of squared numbers beginning from 1 to num:</p>
<pre><code>`
def square_digits(num):
# initialize an empty list
a = []
# why num + 1 when you want numbers until num? check out this link for an explanation
# on how to use and the different uses of the range() function
# http://pythoncentral.io/pythons-range-function-explained/
for i in range(1, num + 1):
# square the numbers beginning from 1,
squared_i = i * i
# and then add the result to the list that we have
a.append(squared_i)
# after everything is done, return the list
return a
result = square_digits(12)
print(result)
`
</code></pre>
<p>In your earlier example, you were basically trying to make this work:</p>
<pre><code>`
for i in 12:
square_result = i * i
print ("the square of " + str(i) + " is " + str(square_result))
`
</code></pre>
<p>which isn't going to work because you're trying to iterate on 12, which is an int</p>
<p>However if you do this:</p>
<pre><code>`
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]:
square_result = i * i
print ("the square of " + str(i) + " is " + str(square_result))
`
</code></pre>
<p>then you're going to have better results, because you're iterating on a list.</p>
<p>the shorter way of doing the above example is:</p>
<pre><code>`
num = 12
for i in range(1, num + 1):
square_result = i * i
print ("the square of " + str(i) + " is " + str(square_result))
`
</code></pre>
<p>which should also work because <code>range(1, num + 1)</code> should return the list <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]</code> if <code>num = 12</code>
in python2. In python3 however, the range function will not return a list, instead it will return something that can be iterated upon like a list for the purpose of this question.</p>
<p>However, I'm not certain if it's a list your looking for as a result, if not, feel free to clarify your question, hopefully others can also chime in.</p>
| 1 |
2016-09-17T09:31:29Z
|
[
"python"
] |
Convert Python generated protobuf to java without .proto file
| 39,544,595 |
<p>Today I receive some Python files (.py) generated from Protocol Buffer (v2). Is there anyway i can convert them to Java version without the original .proto file ? I know it sounds silly but it's just that i'm working on a project for a new client and this happens.</p>
| 3 |
2016-09-17T08:21:57Z
| 39,550,933 |
<p>Use the <a href="http://www.jython.org/archive/21/docs/jythonc.html" rel="nofollow">jythonc</a> tool supplied with Jython.</p>
| 0 |
2016-09-17T19:34:02Z
|
[
"java",
"python",
"protocol-buffers",
"reverse-engineering",
"google-protobuf"
] |
Custom parameter in Flask-WTFoms field
| 39,544,715 |
<p><strong><em>forms.py</em></strong></p>
<pre><code>my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])
</code></pre>
<p><strong><em>my_form.html</em></strong></p>
<pre><code><table>
<tr>
<td colspan="4">
{{form.my_field(placeholder= form.my_field.label.text, class_="form-control")}}
{% for error in form.my_field.errors %}
<span>{{error}}</span>
{% endfor %}
</td>
</tr>
</table>
</code></pre>
<p>This is a simple code. But I want to follow kind of <a href="http://stackoverflow.com/questions/16687520/jinja2-template-for-loop">this</a> to render all the input fields in a loop instead of writing the code for each of them. But each field will have a different <code>colspan</code> value in the corresponding <code><td></code>. </p>
<p>How can I add a custom parameter for colspan which I can use in the <code><td></code>?</p>
<p>Something like: (just the <code>diff</code> from above code)</p>
<p><strong><em>forms.py</em></strong></p>
<pre><code>my_field = TextField(colspan="4")
</code></pre>
<p><strong><em>my_form.html</em></strong></p>
<pre><code><td colspan={{form.my_field.colspan}}>
</code></pre>
| 1 |
2016-09-17T08:40:16Z
| 39,545,633 |
<p>You need to create a <a href="http://wtforms.simplecodes.com/docs/0.6.1/fields.html#custom-fields" rel="nofollow">custom field</a> with an extra <code>colspan</code> attribute.</p>
<p>First define the custom field sub classing <code>TextField</code>:</p>
<pre><code>class MyCustomTextField(TextField):
def __init__(self, colspan=4, *args, **kwargs):
super(MyCustomTextField, self).__init__(*args, **kwargs)
self.colspan = colspan
</code></pre>
<p>Now use the custom field in your form:</p>
<pre><code>class MyForm(Form):
my_field = MyCustomTextField(4, u"Enter a number", validators=[Required('This Field is Required')])
</code></pre>
<p>See that first parameter (a <code>4</code> in this case) for <code>MyCustomTextField</code>? That's your colspan attribute.</p>
<p>Finally, access the attribute in your template like so:</p>
<pre><code><td colspan="{{form.my_field.colspan}}">
</code></pre>
| 1 |
2016-09-17T10:18:20Z
|
[
"python",
"flask",
"jinja2",
"flask-wtforms"
] |
How to implement a Telegram bot program that could handle multiple steps of input?
| 39,544,757 |
<p>I'm programming a telegram bot in Python3 using the Telegram bot API. I'm facing the problem of handling requests that need multiple steps to couplet.
For example, for an airline search bot:</p>
<ol>
<li>the bot ask for departure city, </li>
<li>the user input a name,</li>
<li>the bot ask for destination,</li>
<li>the user input another name,</li>
<li>after a bunch of questions, the bot returns the result to the user.</li>
</ol>
<p>What can I do?</p>
| 0 |
2016-09-17T08:44:37Z
| 39,546,618 |
<p>You need to have a question tree that users can traverse it. you can use a linked list for it and saved this tree in the database. For each question there is a method that take some actions (like store in database) and send a question/result to the user. Each user has a <code>CurrentState</code> that contain state of user in the question tree. User sent an answer to the bot and the bot will run corresponding method and responds to the user.</p>
<pre><code>method = //Fetch user CurrentState from db e.g. airlineBot.doSomething
method(TelegramMessage)
</code></pre>
| 0 |
2016-09-17T12:06:34Z
|
[
"python",
"api",
"python-3.x",
"telegram"
] |
pyspark,spark: how to select last row and also how to access pyspark dataframe by index
| 39,544,796 |
<p>from a pyspark sql dataframe like </p>
<pre><code>name age city
abc 20 A
def 30 B
</code></pre>
<p>How to get the last row.(Like by df.limit(1) I can get first row of dataframe into new dataframe).</p>
<p>And how can I access the dataframe rows by index.like row no. 12 or 200 .</p>
<p>In pandas I can do</p>
<pre><code>df.tail(1) # for last row
df.ix[rowno or index] # by index
df.loc[] or by df.iloc[]
</code></pre>
<p>I am just curious how to access pyspark dataframe in such ways or alternative ways.</p>
<p>Thanks</p>
| 2 |
2016-09-17T08:48:10Z
| 39,548,362 |
<blockquote>
<p>How to get the last row.</p>
</blockquote>
<p>Long and ugly way which assumes that all columns are oderable:</p>
<pre><code>from pyspark.sql.functions import (
col, max as max_, struct, monotonically_increasing_id
)
last_row = (df
.withColumn("_id", monotonically_increasing_id())
.select(max(struct("_id", *df.columns))
.alias("tmp")).select(col("tmp.*"))
.drop("_id"))
</code></pre>
<p>If not all columns can be order you can try:</p>
<pre><code>with_id = df.withColumn("_id", monotonically_increasing_id())
i = with_id.select(max_("_id")).first()[0]
with_id.where(col("_id") == i).drop("_id")
</code></pre>
<p>Note. There is <code>last</code> function in <code>pyspark.sql.functions</code>/ `o.a.s.sql.functions but considering <a href="https://github.com/apache/spark/blob/68b4020d0c0d4f063facfbf4639ef4251dcfda8b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Last.scala#L26-L29" rel="nofollow">description of the corresponding expressions</a> it is not a good choice here.</p>
<blockquote>
<p>how can I access the dataframe rows by index.like</p>
</blockquote>
<p>You cannot. Spark <code>DataFrame</code> and accessible by index. <a href="http://stackoverflow.com/q/32760888/1560062">You can add indices using <code>zipWithIndex</code></a> and filter later. Just keep in mind this <em>O(N)</em> operation. </p>
| 2 |
2016-09-17T15:10:19Z
|
[
"python",
"apache-spark",
"pyspark",
"pyspark-sql"
] |
Get Flask to serve index.html in a directory
| 39,544,862 |
<p>I have 2 static directories in Flask.</p>
<h3>static/</h3>
<ul>
<li><code>css/</code></li>
<li><code>js/</code></li>
</ul>
<h3>results/</h3>
<ul>
<li><code>1/</code>
<ul>
<li><code>index.html</code></li>
<li><code>details.json</code></li>
</ul></li>
<li><code>2/</code>
<ul>
<li><code>index.html</code></li>
<li><code>details.json</code></li>
</ul></li>
</ul>
<p>I followed along a few other answers and glanced through <a href="http://flask.pocoo.org/docs/0.11/quickstart/#static-files" rel="nofollow">the documentation for serving static files</a>.</p>
<pre><code>app = Flask(__name__)
app.config['RESULT_STATIC_PATH'] = "results/"
@app.route('/results/<path:file>')
def serve_results(file):
# Haven't used the secure way to send files yet
return send_from_directory(app.config['RESULT_STATIC_PATH'], file)
</code></pre>
<p>With the following code I can now request for files in the <code>results</code> directory. </p>
<p>I'm more familiar with PHP and Apache. Say if a directory has an <code>index.php</code> or <code>index.html</code> file, it is served automatically.</p>
<p><em>My requirement:-</em></p>
<ul>
<li>Access any file in the results directory</li>
<li>If I send a request for <code>localhost:3333/results/1</code> I should be served <code>index.html</code></li>
</ul>
<p>I can do the same with Flask by adding a route and checking if index.html exists withing the sub directory and then serving it. I found a few more similar pointers <a href="http://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask">here</a> </p>
<p>I currently use two routes to get the functionality. There certainly is a better way. </p>
<p><em>Why did I include details about the static directory?</em><br>
It is highly possible that I may be doing something wrong. Please let me know. Thanks :)</p>
| 1 |
2016-09-17T08:53:42Z
| 39,545,134 |
<p>Try this:</p>
<pre><code>@app.route('/results/<path:file>', defaults={'file': 'index.html'})
def serve_results(file):
# Haven't used the secure way to send files yet
return send_from_directory(app.config['RESULT_STATIC_PATH'], file)
</code></pre>
<p>This is how you pass a default value for that argument. However, I don't agree to this, if you want to serve static content just set a rule in your web server (apache in your case).</p>
| 2 |
2016-09-17T09:25:17Z
|
[
"python",
"flask"
] |
Get Flask to serve index.html in a directory
| 39,544,862 |
<p>I have 2 static directories in Flask.</p>
<h3>static/</h3>
<ul>
<li><code>css/</code></li>
<li><code>js/</code></li>
</ul>
<h3>results/</h3>
<ul>
<li><code>1/</code>
<ul>
<li><code>index.html</code></li>
<li><code>details.json</code></li>
</ul></li>
<li><code>2/</code>
<ul>
<li><code>index.html</code></li>
<li><code>details.json</code></li>
</ul></li>
</ul>
<p>I followed along a few other answers and glanced through <a href="http://flask.pocoo.org/docs/0.11/quickstart/#static-files" rel="nofollow">the documentation for serving static files</a>.</p>
<pre><code>app = Flask(__name__)
app.config['RESULT_STATIC_PATH'] = "results/"
@app.route('/results/<path:file>')
def serve_results(file):
# Haven't used the secure way to send files yet
return send_from_directory(app.config['RESULT_STATIC_PATH'], file)
</code></pre>
<p>With the following code I can now request for files in the <code>results</code> directory. </p>
<p>I'm more familiar with PHP and Apache. Say if a directory has an <code>index.php</code> or <code>index.html</code> file, it is served automatically.</p>
<p><em>My requirement:-</em></p>
<ul>
<li>Access any file in the results directory</li>
<li>If I send a request for <code>localhost:3333/results/1</code> I should be served <code>index.html</code></li>
</ul>
<p>I can do the same with Flask by adding a route and checking if index.html exists withing the sub directory and then serving it. I found a few more similar pointers <a href="http://stackoverflow.com/questions/20646822/how-to-serve-static-files-in-flask">here</a> </p>
<p>I currently use two routes to get the functionality. There certainly is a better way. </p>
<p><em>Why did I include details about the static directory?</em><br>
It is highly possible that I may be doing something wrong. Please let me know. Thanks :)</p>
| 1 |
2016-09-17T08:53:42Z
| 39,566,101 |
<p>I couldn't find a solution which only used one route. I ended up using this.</p>
<pre><code>@app.route('/results/<path:filename>')
def serve_static(filename):
return send_from_directory("results/", filename)
@app.route('/results/<guid>')
def index(guid):
return send_from_directory("results/" + guid, 'index.html')
</code></pre>
<h2>Other suggestions</h2>
<p>@ipinak suggested using <code>defaults={'file': 'index.html'}</code> as another parameter. That <strong>doesn't</strong> solve this problem as it results in some security issue which @ipinak has been kind enough to research about.
<code>defaults</code> is a neat option which I'll try using in other places of my application as well.</p>
<p>@dirn suggested in the comments to use Apache/Nginx to serve static files. It would save time as I wouldn't have to implement stuff in Flask. Since static files don't have to passed to the the Python interpreter, we can serve them via another server with hardly any extra work.</p>
| 0 |
2016-09-19T05:44:40Z
|
[
"python",
"flask"
] |
Python 3.5.2 variable Error
| 39,544,890 |
<p>I have installed python 3.5.2 but when i try to get the value from user it doesn't work it only shows the message but never get the value from user how can i solve this problem??</p>
<p><img src="http://i.stack.imgur.com/ehBYZ.jpg" alt="enter image description here"></p>
| -1 |
2016-09-17T08:57:17Z
| 39,545,369 |
<p>Like @Moses said, you have to use the <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow">input()</a> function:</p>
<pre><code>>>> d = input('Enter the num here: ')
Enter the num here: 222
>>> d
'222'
>>> int(d)
222
</code></pre>
| 0 |
2016-09-17T09:49:22Z
|
[
"python",
"python-3.x"
] |
Check if an string has an integer in an if condition
| 39,544,924 |
<pre><code>file = open('Name.txt', 'r')
name = str(file.read())
file.close()
</code></pre>
<p>In the file called 'Name.txt', the user will input a name. The program is to check whether or not the name is valid.</p>
<p>E.g:</p>
<p>1bob - is not valid</p>
<p>bob - is valid</p>
<p>Is it possible to do this with an if condition? </p>
| -1 |
2016-09-17T09:01:07Z
| 39,545,000 |
<pre><code>def validate(my_file):
return not any(x.isdigit() for x in open(my_file).read().strip())
</code></pre>
<p>The above function will return True when name is valid else False.</p>
| 2 |
2016-09-17T09:10:28Z
|
[
"python"
] |
Check if an string has an integer in an if condition
| 39,544,924 |
<pre><code>file = open('Name.txt', 'r')
name = str(file.read())
file.close()
</code></pre>
<p>In the file called 'Name.txt', the user will input a name. The program is to check whether or not the name is valid.</p>
<p>E.g:</p>
<p>1bob - is not valid</p>
<p>bob - is valid</p>
<p>Is it possible to do this with an if condition? </p>
| -1 |
2016-09-17T09:01:07Z
| 39,545,110 |
<p>You could use regular expression : </p>
<p>i.e : </p>
<pre><code>>>> import re
>>> regex = re.compile(r'.*[0-9]')
>>> names = ['Bob', 'John', '1Bob', 'John2']
>>> for name in names:
... if not regex.match(name):
... print name
...
Bob
John
</code></pre>
<p><code>.*</code> matches any character (except newline) </p>
<p>Quantifier: <code>*</code> Between zero and unlimited times</p>
<p><code>[0-9]</code> match a single character present in the list below</p>
<p><code>0-9</code> a single character in the range between 0 and 9</p>
<p>Hope it helps.</p>
| -1 |
2016-09-17T09:22:54Z
|
[
"python"
] |
CancelledError: RunManyGraphs while running distributed tensorflow
| 39,544,926 |
<p>I am trying to distribute TensorBox ReInspect implementation (<a href="https://github.com/Russell91/TensorBox" rel="nofollow">https://github.com/Russell91/TensorBox</a>) over one ps and two workers. I have added the training code in a <code>sv.managed_session</code>.</p>
<pre><code>def train(H, test_images, server):
'''
Setup computation graph, run 2 prefetch data threads, and then run the main loop
'''
if not os.path.exists(H['save_dir']): os.makedirs(H['save_dir'])
ckpt_file = H['save_dir'] + '/save.ckpt'
with open(H['save_dir'] + '/hypes.json', 'w') as f:
json.dump(H, f, indent=4)
x_in = tf.placeholder(tf.float32)
confs_in = tf.placeholder(tf.float32)
boxes_in = tf.placeholder(tf.float32)
q = {}
enqueue_op = {}
for phase in ['train', 'test']:
dtypes = [tf.float32, tf.float32, tf.float32]
grid_size = H['grid_width'] * H['grid_height']
shapes = (
[H['image_height'], H['image_width'], 3],
[grid_size, H['rnn_len'], H['num_classes']],
[grid_size, H['rnn_len'], 4],
)
q[phase] = tf.FIFOQueue(capacity=30, dtypes=dtypes, shapes=shapes)
enqueue_op[phase] = q[phase].enqueue((x_in, confs_in, boxes_in))
def make_feed(d):
return {x_in: d['image'], confs_in: d['confs'], boxes_in: d['boxes'],
learning_rate: H['solver']['learning_rate']}
def thread_loop(sess, enqueue_op, phase, gen):
for d in gen:
sess.run(enqueue_op[phase], feed_dict=make_feed(d))
(config, loss, accuracy, summary_op, train_op,
smooth_op, global_step, learning_rate, encoder_net) = build(H, q)
saver = tf.train.Saver(max_to_keep=None)
writer = tf.train.SummaryWriter(
logdir=H['save_dir'],
flush_secs=10
)
init_op = tf.initialize_all_variables()
#Assigning the first worker as supervisor
sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0),
#logdir="/tmp/train_logs",
init_op=init_op,
summary_op=summary_op,
saver=saver,
global_step=global_step,
save_model_secs=600)
#Starting training in managed session distributed across the cluster
# with tf.Session(config=config) as sess:
with sv.managed_session(server.target) as sess:
tf.train.start_queue_runners(sess=sess)
for phase in ['train', 'test']:
# enqueue once manually to avoid thread start delay
gen = train_utils.load_data_gen(H, phase, jitter=H['solver']['use_jitter'])
d = gen.next()
sess.run(enqueue_op[phase], feed_dict=make_feed(d))
t = tf.train.threading.Thread(target=thread_loop,
args=(sess, enqueue_op, phase, gen))
t.daemon = True
t.start()
tf.set_random_seed(H['solver']['rnd_seed'])
# sess.run(tf.initialize_all_variables())
writer.add_graph(sess.graph)
weights_str = H['solver']['weights']
if len(weights_str) > 0:
print('Restoring from: %s' % weights_str)
saver.restore(sess, weights_str)
# train model for N iterations
start = time.time()
max_iter = H['solver'].get('max_iter', FLAGS.iter)
for i in xrange(max_iter):
display_iter = H['logging']['display_iter']
adjusted_lr = (H['solver']['learning_rate'] *
0.5 ** max(0, (i / H['solver']['learning_rate_step']) - 2))
lr_feed = {learning_rate: adjusted_lr}
if i % display_iter != 0:
# train network
batch_loss_train, _ = sess.run([loss['train'], train_op], feed_dict=lr_feed)
else:
# test network every N iterations; log additional info
if i > 0:
dt = (time.time() - start) / (H['batch_size'] * display_iter)
start = time.time()
(train_loss, test_accuracy, summary_str,
_, _) = sess.run([loss['train'], accuracy['test'],
summary_op, train_op, smooth_op,
], feed_dict=lr_feed)
writer.add_summary(summary_str, global_step=global_step.eval(session=sess))
print_str = string.join([
'Step: %d',
'lr: %f',
'Train Loss: %.2f',
'Test Accuracy: %.1f%%',
'Time/image (ms): %.1f'
], ', ')
print(print_str %
(i, adjusted_lr, train_loss,
test_accuracy * 100, dt * 1000 if i > 0 else 0))
if global_step.eval(session=sess) % H['logging']['save_iter'] == 0 or global_step.eval(session=sess) == max_iter - 1:
saver.save(sess, ckpt_file, global_step=global_step)
sv.stop()
</code></pre>
<p>The training starts but before printing the final iteration, I get the following error on the supervisor (worker:1):</p>
<pre><code>W tensorflow/core/kernels/queue_base.cc:294] _0_fifo_queue: Skipping cancelled enqueue attempt with queue not closed
W tensorflow/core/kernels/queue_base.cc:294] _1_fifo_queue_1: Skipping cancelled enqueue attempt with queue not closed
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "distributed-train.py", line 461, in thread_loop
sess.run(enqueue_op[phase], feed_dict=make_feed(d))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 717, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 915, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 965, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 985, in _do_call
raise type(e)(node_def, op, message)
CancelledError: RunManyGraphs
*** Error in `python': corrupted double-linked list: 0x00007f9a702b8eb0 ***
Aborted (core dumped)
</code></pre>
<p>How can this problem be solved?</p>
| 0 |
2016-09-17T09:01:36Z
| 39,577,790 |
<p>The <code>CancelledError</code> is relatively benign: I suspect that your main thread exits the <code>with sv.managed_session() as sess:</code> block, which closes the session and cancels all pending requests, including those made by your two pre-fetching threads.</p>
<p>To avoid seeing this error, I'd recommend that you use the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#coordinator-and-queuerunner" rel="nofollow"><code>tf.train.Coordinator</code> and <code>tf.train.QueueRunner</code></a> classes to manage the threads used for prefetching. These can ensure that you shut down the threads cleanly when the training ends. (In particular, there's an experimental <a href="https://github.com/tensorflow/tensorflow/blob/a6c5f8e4e013e54fed8dfcf49fb6de365f018022/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py" rel="nofollow"><code>FeedingQueueRunner</code></a> that seems ideal for your application.)</p>
<p>The cause of the core dump is less clear, and it may reveal a bug in the session-closing or distributed session code. For that bug, can you please try to make a minimal example that reproduces the bug (without relying on any input data, etc.) and submit a <a href="https://github.com/tensorflow/tensorflow/issues" rel="nofollow">GitHub issue</a>?</p>
| 1 |
2016-09-19T16:25:08Z
|
[
"python",
"tensorflow"
] |
Installing PyAutoGUI Error in pip.exe install pyautogui
| 39,544,944 |
<p>I have been installing PyautoGui on my WIN10 PC. But I am getting the following error, i have been getting a lot of errors jut to get this far. </p>
<p>i have been reinstalling python so its destination folder is in <strong>C:\Python</strong> instead of <strong>C:\Users\Home\AppData\Local\Programs\Python\Python35-32</strong> mabye thats why ? How do i fix this ? </p>
<blockquote>
<p>C:\Python\Scripts>pip.exe install pyautogui Collecting pyautogui<br>
Using cached PyAutoGUI-0.9.33.zip Collecting pymsgbox (from pyautogui)
Using cached PyMsgBox-1.0.3.zip Collecting PyTweening>=1.0.1 (from
pyautogui) Using cached PyTweening-1.0.3.zip Collecting Pillow (from
pyautogui) Using cached Pillow-3.3.1-cp35-cp35m-win32.whl Collecting
pyscreeze (from pyautogui) Using cached PyScreeze-0.1.8.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\Home\AppData\Local\Temp\pip-build-kxm3249e\pyscreeze\setup.py",
line 6, in
version=<strong>import</strong>('pyscreeze').<strong>version</strong>,
File "c:\users\home\appdata\local\temp\pip-build-kxm3249e\pyscreeze\pyscreeze__init__.py",
line 21, in
from PIL import Image
ImportError: No module named 'PIL'</p>
<p>Command "python setup.py egg_info" failed with error code 1 in
C:\Users\Home\AppData\Local\Temp\pip-build-kxm3249e\pyscreeze\</p>
</blockquote>
| 0 |
2016-09-17T09:03:30Z
| 39,563,987 |
<p>I encountered the same error message as you did. This workaround worked for me. Try these steps in order...</p>
<ol>
<li><p>Install PyScreeze 0.1.7. </p></li>
<li><p>Update PyScreeze to 0.1.8.</p></li>
<li>Install PyAutoGui.</li>
</ol>
<p>I hope this helps.</p>
| 0 |
2016-09-19T00:50:26Z
|
[
"python",
"pip",
"pyautogui"
] |
Installing PyAutoGUI Error in pip.exe install pyautogui
| 39,544,944 |
<p>I have been installing PyautoGui on my WIN10 PC. But I am getting the following error, i have been getting a lot of errors jut to get this far. </p>
<p>i have been reinstalling python so its destination folder is in <strong>C:\Python</strong> instead of <strong>C:\Users\Home\AppData\Local\Programs\Python\Python35-32</strong> mabye thats why ? How do i fix this ? </p>
<blockquote>
<p>C:\Python\Scripts>pip.exe install pyautogui Collecting pyautogui<br>
Using cached PyAutoGUI-0.9.33.zip Collecting pymsgbox (from pyautogui)
Using cached PyMsgBox-1.0.3.zip Collecting PyTweening>=1.0.1 (from
pyautogui) Using cached PyTweening-1.0.3.zip Collecting Pillow (from
pyautogui) Using cached Pillow-3.3.1-cp35-cp35m-win32.whl Collecting
pyscreeze (from pyautogui) Using cached PyScreeze-0.1.8.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\Home\AppData\Local\Temp\pip-build-kxm3249e\pyscreeze\setup.py",
line 6, in
version=<strong>import</strong>('pyscreeze').<strong>version</strong>,
File "c:\users\home\appdata\local\temp\pip-build-kxm3249e\pyscreeze\pyscreeze__init__.py",
line 21, in
from PIL import Image
ImportError: No module named 'PIL'</p>
<p>Command "python setup.py egg_info" failed with error code 1 in
C:\Users\Home\AppData\Local\Temp\pip-build-kxm3249e\pyscreeze\</p>
</blockquote>
| 0 |
2016-09-17T09:03:30Z
| 39,574,692 |
<p>I also encountered the same error (albeit on Ubuntu 14.04). The missing module PIL is named Pillow (As said in <a href="http://stackoverflow.com/a/34512881/4335271">this answer</a>). So what I tried was (same in MacOS I think):</p>
<pre><code>sudo pip3 install pillow
</code></pre>
<p>That translated to Windows would be:</p>
<pre><code>pip.exe install pillow
</code></pre>
<p>Hope this helps you further.</p>
| 0 |
2016-09-19T13:41:30Z
|
[
"python",
"pip",
"pyautogui"
] |
Installing PyAutoGUI Error in pip.exe install pyautogui
| 39,544,944 |
<p>I have been installing PyautoGui on my WIN10 PC. But I am getting the following error, i have been getting a lot of errors jut to get this far. </p>
<p>i have been reinstalling python so its destination folder is in <strong>C:\Python</strong> instead of <strong>C:\Users\Home\AppData\Local\Programs\Python\Python35-32</strong> mabye thats why ? How do i fix this ? </p>
<blockquote>
<p>C:\Python\Scripts>pip.exe install pyautogui Collecting pyautogui<br>
Using cached PyAutoGUI-0.9.33.zip Collecting pymsgbox (from pyautogui)
Using cached PyMsgBox-1.0.3.zip Collecting PyTweening>=1.0.1 (from
pyautogui) Using cached PyTweening-1.0.3.zip Collecting Pillow (from
pyautogui) Using cached Pillow-3.3.1-cp35-cp35m-win32.whl Collecting
pyscreeze (from pyautogui) Using cached PyScreeze-0.1.8.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\Home\AppData\Local\Temp\pip-build-kxm3249e\pyscreeze\setup.py",
line 6, in
version=<strong>import</strong>('pyscreeze').<strong>version</strong>,
File "c:\users\home\appdata\local\temp\pip-build-kxm3249e\pyscreeze\pyscreeze__init__.py",
line 21, in
from PIL import Image
ImportError: No module named 'PIL'</p>
<p>Command "python setup.py egg_info" failed with error code 1 in
C:\Users\Home\AppData\Local\Temp\pip-build-kxm3249e\pyscreeze\</p>
</blockquote>
| 0 |
2016-09-17T09:03:30Z
| 40,112,934 |
<p>Instead of letting <strong>PyautoGUI</strong> get all the packages for you.</p>
<p>Install all of them individually. Then, run the <code>pip install --upgrade _packageName_</code> </p>
<p>Then run <code>pip install pyautogui</code>.</p>
<p>Hope this helps. </p>
| 0 |
2016-10-18T15:59:49Z
|
[
"python",
"pip",
"pyautogui"
] |
Shifting Column to the left Pandas Dataframe
| 39,544,975 |
<p>I have a fruit dataset that contains Name, Colour, Weight, Size, Seeds</p>
<pre><code> Fruit dataset
Name Colour Weight Size Seeds Unnamed
Apple Apple Red 10.0 Big Yes
Apple Apple Red 5.0 Small Yes
Pear Pear Green 11.0 Big Yes
Banana Banana Yellow 4.0 Small Yes
Orange Orange Orange 5.0 Small Yes
</code></pre>
<p>The problem is that, the colour column is a duplicated column of name and the values are shifted 1 column to the right, creating a useless column (Unnamed) that contains values that belong to column Seeds. Is there a easy way to remove the duplicated values in Colour and shift back the rest of the column values 1 column to the left from weight onwards. I hope i am not confusing anyone here. </p>
<p>Desire result</p>
<pre><code> Fruit dataset
Name Colour Weight Size Seeds Unnamed(will be dropped)
Apple Red 10.0 Big Yes
Apple Red 5.0 Small Yes
Pear Green 11.0 Big Yes
Banana Yellow 4.0 Small Yes
Orange Orange 5.0 Small Yes
</code></pre>
| 1 |
2016-09-17T09:07:39Z
| 39,545,062 |
<p>you can do it this way:</p>
<pre><code>In [23]: df
Out[23]:
Name Colour Weight Size Seeds Unnamed
0 Apple Apple Red 10.0 Big Yes
1 Apple Apple Red 5.0 Small Yes
2 Pear Pear Green 11.0 Big Yes
3 Banana Banana Yellow 4.0 Small Yes
4 Orange Orange Orange 5.0 Small Yes
In [24]: cols = df.columns[:-1]
In [25]: cols
Out[25]: Index(['Name', 'Colour', 'Weight', 'Size', 'Seeds'], dtype='object')
In [26]: df = df.drop('Colour', 1)
In [27]: df.columns = cols
In [28]: df
Out[28]:
Name Colour Weight Size Seeds
0 Apple Red 10.0 Big Yes
1 Apple Red 5.0 Small Yes
2 Pear Green 11.0 Big Yes
3 Banana Yellow 4.0 Small Yes
4 Orange Orange 5.0 Small Yes
</code></pre>
| 1 |
2016-09-17T09:16:51Z
|
[
"python",
"pandas",
"dataframe"
] |
Multiple characters in a string return a false boolean when trying to find a character in the string
| 39,544,976 |
<pre><code>#Function takes a character and a string and returns a boolean reflecting if
#the character is found in the string.
def isItThereS(letter, word):
letInWord = 0
for l in word:
if l == letter:
letInWord += 1
return letInWord == True
</code></pre>
<p>When I put it in the operator like </p>
<blockquote>
<blockquote>
<blockquote>
<p>isItThereS("h","hello world")
True</p>
</blockquote>
</blockquote>
</blockquote>
<p>but when I go to find a character that repeats like "l" or "o" it returns false.</p>
<blockquote>
<blockquote>
<blockquote>
<p>isItThereS("l","hello world")
False</p>
</blockquote>
</blockquote>
</blockquote>
<p>How would I go about getting that to not return false, but instead return True since the character is technically in the string?</p>
| 0 |
2016-09-17T09:07:43Z
| 39,545,023 |
<p>you can simply use the in operator</p>
<pre><code>def isItThereS(letter, word):
return letter in word
</code></pre>
| 2 |
2016-09-17T09:12:06Z
|
[
"python",
"string",
"python-3.x",
"character"
] |
Multiple characters in a string return a false boolean when trying to find a character in the string
| 39,544,976 |
<pre><code>#Function takes a character and a string and returns a boolean reflecting if
#the character is found in the string.
def isItThereS(letter, word):
letInWord = 0
for l in word:
if l == letter:
letInWord += 1
return letInWord == True
</code></pre>
<p>When I put it in the operator like </p>
<blockquote>
<blockquote>
<blockquote>
<p>isItThereS("h","hello world")
True</p>
</blockquote>
</blockquote>
</blockquote>
<p>but when I go to find a character that repeats like "l" or "o" it returns false.</p>
<blockquote>
<blockquote>
<blockquote>
<p>isItThereS("l","hello world")
False</p>
</blockquote>
</blockquote>
</blockquote>
<p>How would I go about getting that to not return false, but instead return True since the character is technically in the string?</p>
| 0 |
2016-09-17T09:07:43Z
| 39,545,046 |
<p>If you <strong>really</strong> want to use a custom function for that, change your return to <code>return letInWord >= 1</code>. As everything but <code>1 == True</code> will evaluate to <code>False</code>. (So a more appropriate name for the function as is would be <code>is_it_there_only_once</code>).</p>
<p>Otherwise please use the solution provided by armak.</p>
| 0 |
2016-09-17T09:14:49Z
|
[
"python",
"string",
"python-3.x",
"character"
] |
How to automate interactive console applications in Python?
| 39,544,997 |
<p>I want to control running process/program by script in Python.
I have a program `linphonec´ (You can install: apt-get install linphonec).
My task is:</p>
<ol>
<li>Run <code>linphonec</code> (I'm using subprocess at the moment)</li>
<li>When <code>linphonec</code> is running it has many commands to control this and I want to e.g use <code>proxy list</code> (command in <code>linphonec</code>).</li>
</ol>
<p>Simple flow:</p>
<pre><code>test@ubuntu$ > linphonec
linphonec > proxy list
</code></pre>
<p>How can I do this?</p>
| 0 |
2016-09-17T09:09:47Z
| 39,545,162 |
<p>There are actually 2 ways to communicate:</p>
<p>Run your program with <code>myprogram.py | linphonec</code> to pass everything you <code>print</code> to linphonec</p>
<p>Use <a href="https://docs.python.org/3/library/subprocess.html#popen-constructor" rel="nofollow">subprocess.Popen</a> with <a href="https://docs.python.org/3/library/subprocess.html#subprocess.PIPE" rel="nofollow">subprocess.PIPE</a> in constructor via keywrod-args for stdin (propably stdout and stderr, too) and then <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow">communicate</a> for a single command or use <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stdin" rel="nofollow">stdin</a> and <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stdout" rel="nofollow">stdout</a> (<a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stderr" rel="nofollow">stderr</a>) as files</p>
<pre><code>import subprocess
p=subprocess.Popen("linphonec",
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True) #this is for text communication
p.stdin.write("proxy list\n")
result_first_line=p.stdout.readline()
</code></pre>
| 0 |
2016-09-17T09:28:55Z
|
[
"python",
"linux",
"shell",
"subprocess",
"linphone"
] |
How to repeat an action in Python
| 39,545,031 |
<p>I want to repeat an action for n times. I've tried "if" but it does not work. </p>
<pre><code>If actiontimes == n:
Print text*n
</code></pre>
<p>Thanks for any advice</p>
| -5 |
2016-09-17T09:13:17Z
| 39,545,038 |
<p>You have to write:</p>
<pre><code>for x in range(times):
#action to repeat
</code></pre>
| 0 |
2016-09-17T09:13:58Z
|
[
"python"
] |
Why and how am i supposed to use socket.accept() in python?
| 39,545,199 |
<p>This <code>accept()</code> method return a tuple with a new socket and an address but why do i need a new socket if i already have one, so why don't use it?</p>
<pre><code>import socket
sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
print 'connected:', addr
while True:
data = conn.recv(1024)
if not data:
break
conn.send(data.upper())
conn.close()
</code></pre>
<p>ps: When i program sockets in Java, i don't really have this kind of <em>accepting</em> stuff and i only need one socket per client and one per server, which makes sense.</p>
| 1 |
2016-09-17T09:33:33Z
| 39,545,528 |
<p>Seems like you haven't implemented TCP in Java before.</p>
<p>The example you are providing with, uses a default <code>AF_INET</code> and <code>SOCK_STREAM</code> which <em>by default</em> is TCP:</p>
<blockquote>
<p>socket.socket([family[, type[, proto]]])
Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted in that case.</p>
</blockquote>
<p>If you were implemented <code>SOCK_DGRAM</code> which is UDP, you wouldn't need to be using <code>sock.accept()</code></p>
| 1 |
2016-09-17T10:07:48Z
|
[
"java",
"python",
"sockets"
] |
Why and how am i supposed to use socket.accept() in python?
| 39,545,199 |
<p>This <code>accept()</code> method return a tuple with a new socket and an address but why do i need a new socket if i already have one, so why don't use it?</p>
<pre><code>import socket
sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
print 'connected:', addr
while True:
data = conn.recv(1024)
if not data:
break
conn.send(data.upper())
conn.close()
</code></pre>
<p>ps: When i program sockets in Java, i don't really have this kind of <em>accepting</em> stuff and i only need one socket per client and one per server, which makes sense.</p>
| 1 |
2016-09-17T09:33:33Z
| 39,545,588 |
<p>You have one listening socket active while the server is running and one new connected socket for each accepted connection which is active until the connection is closed.</p>
| 2 |
2016-09-17T10:14:06Z
|
[
"java",
"python",
"sockets"
] |
Calculate the average value of the numbers in a file
| 39,545,203 |
<p>I am having a problem of calculating the average value of numbers in a file.
So far i have made a function that reads in files and calculate the number of lines.
The file consists of many columns of numbers, but the column 8 is the one i need to calculate from. </p>
<pre><code>def file_read():
fname = input("Input filname: ")
infile = open(fname,'r')
txt = infile.readlines()
print("opens",fname,"...")
num_lines = sum(1 for line in open(fname))
#The first line in the file is only text, so i subtract 1
print("Number of days:",(num_lines-1))
</code></pre>
<p>The numbers are also decimals, so i use float.</p>
<p>This is my try on calculating the sum of numbers,
which shall be divided by the number of lines , but i comes an error, cuz the first line is text. </p>
<pre><code>with open(fname) as txt:
return sum(float(x)
for line in txt
for x in line.split()[8]
</code></pre>
<p>Is there a way i can get python to ignore the first line and just concentrate about the numbers down under? </p>
| 0 |
2016-09-17T09:33:42Z
| 39,545,255 |
<p>You could use <code>txt.readline()</code> to read the first line, but to stick with iterators way to do it, just drop the first line using iteration on file with <code>next</code></p>
<pre><code>with open(fname) as txt:
next(txt) # it returns the first line, we just ignore the return value
# your iterator is now on the second line, where the numbers are
for line in txt:
...
</code></pre>
<p>Side note: this is also very useful to skip title lines of files open with the <code>csv</code> module, that's where <code>next</code> is better than <code>readline</code> since csv title can be on multiple lines.</p>
| 0 |
2016-09-17T09:39:00Z
|
[
"python",
"file",
"numbers"
] |
Calculate the average value of the numbers in a file
| 39,545,203 |
<p>I am having a problem of calculating the average value of numbers in a file.
So far i have made a function that reads in files and calculate the number of lines.
The file consists of many columns of numbers, but the column 8 is the one i need to calculate from. </p>
<pre><code>def file_read():
fname = input("Input filname: ")
infile = open(fname,'r')
txt = infile.readlines()
print("opens",fname,"...")
num_lines = sum(1 for line in open(fname))
#The first line in the file is only text, so i subtract 1
print("Number of days:",(num_lines-1))
</code></pre>
<p>The numbers are also decimals, so i use float.</p>
<p>This is my try on calculating the sum of numbers,
which shall be divided by the number of lines , but i comes an error, cuz the first line is text. </p>
<pre><code>with open(fname) as txt:
return sum(float(x)
for line in txt
for x in line.split()[8]
</code></pre>
<p>Is there a way i can get python to ignore the first line and just concentrate about the numbers down under? </p>
| 0 |
2016-09-17T09:33:42Z
| 39,546,814 |
<p>Try this</p>
<pre><code>import re
#regular expression for decimals
digits_reg = re.compile(r"\d+\.\d+|\d+")
with open('''file name''', "r") as file:
allNum = []
#find numbers in each line and add them to the list
for line in file:
allNum.extend(digits_reg.findall(line))
#should be a list that contains all numbers in the file
print(alNum)
</code></pre>
| 0 |
2016-09-17T12:27:21Z
|
[
"python",
"file",
"numbers"
] |
Why isn't IDLE in the folder with the Python program?
| 39,545,314 |
<p>I am a complete beginner to programming. I downloaded Python 3.4.3. 64 bit for my Windows 10 OS. The download specified that it included IDLE. I opened Python with no issue, but IDLE was not in that folder. I searched for it on my C drive and it didn't match any file names.</p>
<p>Did it save somewhere else? </p>
| 0 |
2016-09-17T09:44:24Z
| 39,545,380 |
<p>If you installed IDLE correctly, it will appear in your menu with a folder for IDLE. Look there. If not, attempt to reinstall IDLE. It will not affect anything.</p>
| 0 |
2016-09-17T09:50:30Z
|
[
"python",
"installation"
] |
Trying to run a python script via PHP button hosted on raspberry pi but failing
| 39,545,452 |
<p>I have a php script that should (I think) run a python script to control the energenie radio controlled plug sockets depending on which button is selected. It seems to work in that it echos back the correct message when the button is pressed but the python scripts don''t appear to run. I have added the line:</p>
<p>www-data ALL=NOPASSWD: /usr/bin/python /home/pi/lampon.py</p>
<p>which should give the apache user privileges to run the python script at least for turning on the power socket but it doesn't work. The script itself does work when run via the pi command line itself. Any suggestions? (the code for the php is below)</p>
<pre><code><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>LED Control</title>
</head>
<body>
LED Control:
<form method="get" action="energenie.php">
<input type="submit" value="ON" name="on">
<input type="submit" value="OFF" name="off">
</form>
<?php
if(isset($_GET['on'])){
shell_exec("python /home/pi/lampon.py");
echo "LED is on";
}
else if(isset($_GET['off'])){
shell_exec("python /home/pi/lampoff.py");
echo "LED is off";
}
?>
</body>
</html>
</code></pre>
| 0 |
2016-09-17T09:58:43Z
| 39,545,497 |
<p>Have you tried setting the permissions of the <code>lampoff.py</code> and <code>lampon.py</code> to 777?</p>
<p><code>chmod 777 /home/pi/lampoff.py && chmod 777 /home/py/lampon.py</code></p>
| 0 |
2016-09-17T10:04:44Z
|
[
"php",
"python",
"raspberry-pi"
] |
Trying to run a python script via PHP button hosted on raspberry pi but failing
| 39,545,452 |
<p>I have a php script that should (I think) run a python script to control the energenie radio controlled plug sockets depending on which button is selected. It seems to work in that it echos back the correct message when the button is pressed but the python scripts don''t appear to run. I have added the line:</p>
<p>www-data ALL=NOPASSWD: /usr/bin/python /home/pi/lampon.py</p>
<p>which should give the apache user privileges to run the python script at least for turning on the power socket but it doesn't work. The script itself does work when run via the pi command line itself. Any suggestions? (the code for the php is below)</p>
<pre><code><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>LED Control</title>
</head>
<body>
LED Control:
<form method="get" action="energenie.php">
<input type="submit" value="ON" name="on">
<input type="submit" value="OFF" name="off">
</form>
<?php
if(isset($_GET['on'])){
shell_exec("python /home/pi/lampon.py");
echo "LED is on";
}
else if(isset($_GET['off'])){
shell_exec("python /home/pi/lampoff.py");
echo "LED is off";
}
?>
</body>
</html>
</code></pre>
| 0 |
2016-09-17T09:58:43Z
| 39,552,286 |
<p>I think you need add "sudo" the python script for it to work which means you have to add the www-data user to /etc/sudoers.</p>
<pre><code>shell_exec("sudo python /home/pi/lampon.py");
</code></pre>
<p>or</p>
<pre><code>exec("sudo python /home/pi/lampon.py");
</code></pre>
<p>There was another post that deal with this recently on <a href="http://stackoverflow.com/questions/31811253/execute-python-script-from-php">Execute Python script from Php</a></p>
| 0 |
2016-09-17T22:27:00Z
|
[
"php",
"python",
"raspberry-pi"
] |
PyGame - Take a screenshot of a certain part of the display
| 39,545,469 |
<p>How can I take a screenshot of a certain part of the pygame screen?</p>
<p>For example, this is my screen</p>
<p><a href="http://i.stack.imgur.com/VyEEY.png" rel="nofollow"><img src="http://i.stack.imgur.com/VyEEY.png" alt="screen"></a></p>
<p>and I want to take a screenshot of the area between the top-left dot, and the bottom-right dot (the coordinate are (20, 100), (480, 480), and the whole display is 500x50).</p>
<p>This is my best result so far (but it's still not good):</p>
<pre><code>def screenshot(obj, file_name, position, size):
img = pygame.Surface(size_f)
img.blit(obj, (0, 0), (position, size))
pygame.image.save(img, file_name)
...
...
...
screenshot(game, "test1.png", (0, 100), (500, 400))
</code></pre>
<p><a href="http://i.stack.imgur.com/82uKP.png" rel="nofollow"><img src="http://i.stack.imgur.com/82uKP.png" alt="screen"></a></p>
<p>I added the black border to show the image border, because the image is white.</p>
<p>---------- EDIT ----------</p>
<p>with this function call</p>
<pre><code>screenshot(game, "test1.png", (20, 100), (480, 400))
</code></pre>
<p>i'm getting a better result - now both the top and the left sides are ok, (because the top-left is the point where the x and y starts) but still - both the right and the bottom sides aren't good</p>
<p>i.imgur.com/prH2WOB.png</p>
<hr>
| 0 |
2016-09-17T10:01:26Z
| 39,561,058 |
<p>Your function has an error (size_f is not defined) but otherwise it's working. The function</p>
<pre><code>def screenshot(obj, file_name, position, size):
img = pygame.Surface(size)
img.blit(obj, (0, 0), (position, size))
pygame.image.save(img, file_name)
</code></pre>
<p>takes the the topleft position and the size of the rectangle. You said yourself that the topleft red dot is at <code>(20, 100)</code>, so the <em>position</em> argument should be at <code>(20, 100)</code> (that's why your second attempt fixes the padding to the left and top).</p>
<p>The bottomright point is determined by the size of the rectangle. We're trying to get from <code>(20, 100)</code>to <code>(480, 480)</code>, so some quick math will give us the size:</p>
<pre><code>width = 480 - 20 = 460
height = 480 - 100 = 380
</code></pre>
<p>Your function should give the right result if you do like this:</p>
<pre><code>screenshot(game, "test1.png", (20, 100), (460, 380))
</code></pre>
<p>You could do this if you want to change the function to take two positions instead:</p>
<pre><code>def screenshot(obj, file_name, topleft, bottomright):
size = bottomright[0] - topleft[0], bottomright[1] - topleft[1]
img = pygame.Surface(size)
img.blit(obj, (0, 0), (topleft, size))
pygame.image.save(img, file_name)
</code></pre>
<p>Here's an example demonstrating both functions:</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
def screenshot(obj, file_name, position, size):
img = pygame.Surface(size)
img.blit(obj, (0, 0), (position, size))
pygame.image.save(img, file_name)
def screenshot2(obj, file_name, topleft, bottomright):
size = bottomright[0] - topleft[0], bottomright[1] - topleft[1]
img = pygame.Surface(size)
img.blit(obj, (0, 0), (topleft, size))
pygame.image.save(img, file_name)
a = pygame.Surface((10, 10))
a.fill((255, 0, 0))
while 1:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
screenshot(screen, "test1.png", (20, 100), (460, 380))
screenshot2(screen, "test2.png", (20, 100), (480, 480))
print("PRINTED")
elif event.type == pygame.QUIT:
quit()
screen.blit(a, (20, 100))
screen.blit(a, (480, 480))
pygame.display.update()
</code></pre>
| 0 |
2016-09-18T18:16:11Z
|
[
"python",
"python-3.x",
"pygame"
] |
Unreachable code when using cython.inline
| 39,545,501 |
<p>I'm using Cython to compile a function to C, but get a "Unreachable code" warning. When I inspect the <code>pyx</code> file, I see an additional <code>return locals()</code> which I don't quite understand how it got there.</p>
<p>The code is generated by <code>cython.inline</code>:</p>
<pre><code>cython.inline('return a * b + c if a > b else 0.0', a=1, b=2, c=3)
</code></pre>
<p>which produces a pyx file that looks like this:</p>
<pre><code>def __invoke(double a, double b, double c):
return a * b + c if a > b^2 else 0.0
return locals()
</code></pre>
<p>The reason I am cythonizing this function is to improve performance. The above function is a simplification, but the basic elements are the same. Note that the inline function is not using <code>numpy</code> arrays. If anyone can think of a faster way to evaluate the expression, I am happy to try it out (the syntax for the original expression is a bit different, but I can compile it to any format).</p>
<p>Anyway, the main point of this question is to understand why and additional <code>return</code> statement has been added and how to remove it.</p>
<p><strong>Update</strong></p>
<p>This is the overhead I've noticed from the <code>cython.inline</code> calls (refers to conversation with @DavidW).</p>
<p><a href="http://i.stack.imgur.com/rQxIA.png" rel="nofollow"><img src="http://i.stack.imgur.com/rQxIA.png" alt="enter image description here"></a></p>
| 0 |
2016-09-17T10:05:06Z
| 39,580,017 |
<p>I think it's so that if you don't add a return statement you get back a dictionary of local variables. E.g.</p>
<pre><code>cython.inline('''x = a*b
y = b+c
z = a-c
''', a=1, b=2, c=3)
</code></pre>
<p>will give you back a dictionary of <code>x</code>, <code>y</code>, and <code>z</code>. Obviously it's a bit unnecessary since you could do that manually yourself, but it makes some use-cases easy (and would break compatibility with existing code if removed).</p>
<p>Cython accomplishes those features by adding <code>return locals()</code> to the end of everything it compiles. You can find it in the <a href="https://github.com/cython/cython/blob/499d262250f7f4d8f392bb2165a2692937d1c4fa/Cython/Build/Inline.py#L216" rel="nofollow">source code</a>.</p>
<p>I don't think you can get rid of it, but it also costs you nothing (except a compiler warning) - it's obvious to the C compiler that the code is unreachable so it never gets generated.</p>
<hr>
<p>To answer your secondary question about improving performance - this kind of calculation presumably only matters if it's called repeatedly? I'd try to get the loop in Cython too if at all possible, otherwise I'd be surprised if you gained much.</p>
| 1 |
2016-09-19T18:42:43Z
|
[
"python",
"cython"
] |
What is the GCS equivalent of the blobstore "Create_upload_url"?
| 39,545,529 |
<p>We currently use blobstore.create_upload_url to create upload urls to be used on the frontend see <a href="https://cloud.google.com/appengine/docs/python/blobstore/#Python_Uploading_a_blob" rel="nofollow">Uploading a blob</a>.
However, with the push toward Google Cloud Storage (GCS) by Google, I'd like to use GCS instead of the blobstore. We use currently blobstore.create_upload_url but I can't find anything equivalent in the GCS documentation. Am I missing something? Is there a better way to upload files to GCS from the frontend?</p>
<p>Thanks
Rob</p>
| 1 |
2016-09-17T10:07:52Z
| 39,546,064 |
<p>If you will provide <code>gs_bucket_name</code> to <code>blobstore.create_upload_url</code> file will be stored in GCS instead of blobstore, this is described in official documentation: <a href="https://cloud.google.com/appengine/docs/python/blobstore/" rel="nofollow">Using the Blobstore API with Google Cloud Storage</a></p>
<pre><code>blobstore.create_upload_url(
success_path=webapp2.uri_for('upload'),
gs_bucket_name="mybucket/dest/location")
</code></pre>
<p>You can take a look at simple upload handler implementation made in webapp2 </p>
<pre><code>from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import webapp2
import cloudstorage as gcs
class Upload(blobstore_handlers.BlobstoreUploadHandler):
"""Upload handler
To upload new file you need to follow those steps:
1. send GET request to /upload to retrieve upload session URL
2. send POST request to URL retrieved in step 1
"""
def post(self):
"""Copy uploaded files to provided bucket destination"""
fileinfo = self.get_file_infos()[0]
uploadpath = fileinfo.gs_object_name[3:]
stat = gcs.stat(uploadpath)
# remove auto generated filename from upload path
destpath = "/".join(stat.filename.split("/")[:-1])
# copy file to desired location with proper filename
gcs.copy2(uploadpath, destpath)
# remove file from uploadpath
gcs.delete(uploadpath)
def get(self):
"""Returns URL to open upload session"""
self.response.write(blobstore.create_upload_url(
success_path=uri_for('upload'),
gs_bucket_name="mybucket/subdir/subdir2/filename.ext"))
</code></pre>
| 2 |
2016-09-17T11:04:31Z
|
[
"python",
"google-app-engine",
"google-cloud-storage"
] |
Python Combinations
| 39,545,543 |
<p>Suppose I have a Python list that looks like:</p>
<pre><code>[1, 2, 3, 4]
</code></pre>
<p>I would like to be able to return a list of lists containing all combinations of two or more numbers. The order of the values doesn't matter so 1,2 is the same as 2,1. I would also like to return another list that contains the values that do not feature in each combination. For example:</p>
<pre><code>Combination 1,2 / Remainder 3,4
Combination 2,3 / Remainder 1,4
Combination 1,2,3 / Remainder 4
Combination 1,2,3,4/ Remainder -
</code></pre>
<p>The returned lists for the above would be</p>
<pre><code>combination = [[1,2], [2,3], [1,2,3], [1,2,3,4]]
remainder = [[3,4], [1,4], [4], []]
</code></pre>
<p>I've only shown a few examples...</p>
<p>I realise that the first part can probably be achieved using <code>itertools.combinations</code> but how can I return those values not used in the combination without looping?</p>
| 1 |
2016-09-17T10:09:33Z
| 39,545,613 |
<p>You can take the set difference:</p>
<pre><code>l = set([1, 2, 3, 4])
for i in range(len(l)+1):
for comb in itertools.combinations(l, i):
print(comb, l.difference(comb))
() {1, 2, 3, 4}
(1,) {2, 3, 4}
(2,) {1, 3, 4}
(3,) {1, 2, 4}
(4,) {1, 2, 3}
(1, 2) {3, 4}
(1, 3) {2, 4}
(1, 4) {2, 3}
(2, 3) {1, 4}
(2, 4) {1, 3}
(3, 4) {1, 2}
(1, 2, 3) {4}
(1, 2, 4) {3}
(1, 3, 4) {2}
(2, 3, 4) {1}
(1, 2, 3, 4) set()
</code></pre>
| 2 |
2016-09-17T10:16:23Z
|
[
"python",
"python-2.7",
"combinations",
"itertools"
] |
Python Combinations
| 39,545,543 |
<p>Suppose I have a Python list that looks like:</p>
<pre><code>[1, 2, 3, 4]
</code></pre>
<p>I would like to be able to return a list of lists containing all combinations of two or more numbers. The order of the values doesn't matter so 1,2 is the same as 2,1. I would also like to return another list that contains the values that do not feature in each combination. For example:</p>
<pre><code>Combination 1,2 / Remainder 3,4
Combination 2,3 / Remainder 1,4
Combination 1,2,3 / Remainder 4
Combination 1,2,3,4/ Remainder -
</code></pre>
<p>The returned lists for the above would be</p>
<pre><code>combination = [[1,2], [2,3], [1,2,3], [1,2,3,4]]
remainder = [[3,4], [1,4], [4], []]
</code></pre>
<p>I've only shown a few examples...</p>
<p>I realise that the first part can probably be achieved using <code>itertools.combinations</code> but how can I return those values not used in the combination without looping?</p>
| 1 |
2016-09-17T10:09:33Z
| 39,545,624 |
<p>Suppose you have this vector [1 6 3]</p>
<p>You can generate all of the numbers from 0 to 2^3-1 where 3 is <code>len([1 6 3])</code></p>
<pre><code>0
1
2
3
4
5
6
7
</code></pre>
<p>After you can convert this numbers to binary:</p>
<pre><code> 0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code></pre>
<p>Put your vector at the top of the sequence generated:</p>
<pre><code>[1 6 3]
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code></pre>
<p>for each line append in combination the number that are in the same position of the 1s and in the remainder that one that are in the position of the 0s.</p>
<p>so, for instance, looking at the 4th line:</p>
<pre><code>Combination: [6,3]
Remainder: [1]
</code></pre>
<p>At the end:</p>
<pre><code>Combination: [],[3],[6],[6,3],[1],[1,3],[1,6],[1,6,3]
Remainder: [1,6,3],[1,3],[1],[6,3],[6],[3],[]
</code></pre>
<p>Here the code:</p>
<pre><code>vec=[1,3,6]
binary_vec = [format(i,'b').zfill(len(vec)) for i in range(2**len(vec))]
print([[vec[i] for i,y in enumerate(x) if y != "0"] for x in binary_vec])
print([[vec[i] for i,y in enumerate(x) if y == "0"] for x in binary_vec])
</code></pre>
<p>Output:</p>
<p><a href="http://i.stack.imgur.com/wfmPn.png" rel="nofollow"><img src="http://i.stack.imgur.com/wfmPn.png" alt="enter image description here"></a></p>
<p>Look also at my answer in this post:</p>
<p><a href="http://stackoverflow.com/questions/39428179/determine-list-of-all-possible-products-from-a-list-of-integers-in-python/39428550#39428550">Determine list of all possible products from a list of integers in Python</a></p>
| 1 |
2016-09-17T10:17:46Z
|
[
"python",
"python-2.7",
"combinations",
"itertools"
] |
Python Combinations
| 39,545,543 |
<p>Suppose I have a Python list that looks like:</p>
<pre><code>[1, 2, 3, 4]
</code></pre>
<p>I would like to be able to return a list of lists containing all combinations of two or more numbers. The order of the values doesn't matter so 1,2 is the same as 2,1. I would also like to return another list that contains the values that do not feature in each combination. For example:</p>
<pre><code>Combination 1,2 / Remainder 3,4
Combination 2,3 / Remainder 1,4
Combination 1,2,3 / Remainder 4
Combination 1,2,3,4/ Remainder -
</code></pre>
<p>The returned lists for the above would be</p>
<pre><code>combination = [[1,2], [2,3], [1,2,3], [1,2,3,4]]
remainder = [[3,4], [1,4], [4], []]
</code></pre>
<p>I've only shown a few examples...</p>
<p>I realise that the first part can probably be achieved using <code>itertools.combinations</code> but how can I return those values not used in the combination without looping?</p>
| 1 |
2016-09-17T10:09:33Z
| 39,547,832 |
<p>Building upon the idea by <a href="http://stackoverflow.com/a/39545624/1639625">Nunzio</a>, but instead of converting numbers in a certain range to binary, you can just use <code>itertools.product</code> to get all combinations of <code>1</code> and <code>0</code> (or <code>True</code> and <code>False</code>) and then use that as a mask for filtering the "ins" and "outs".</p>
<pre><code>>>> lst = [1,2,3]
>>> products = list(product([1,0], repeat=len(lst)))
>>> [[lst[i] for i, e in enumerate(p) if e] for p in products]
[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
>>> [[lst[i] for i, e in enumerate(p) if not e] for p in products]
[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
</code></pre>
<p>You could also define a function for that <code>enumerate</code> comprehension and do both parts in one go:</p>
<pre><code>>>> mask = lambda lst, p, v: [lst[i] for i, e in enumerate(p) if e == v]
>>> [(mask(lst, p, 1), mask(lst, p, 0)) for p in product([1,0], repeat=len(lst))]
[([1, 2, 3], []),
([1, 2], [3]),
([1, 3], [2]),
([1], [2, 3]),
([2, 3], [1]),
([2], [1, 3]),
([3], [1, 2]),
([], [1, 2, 3])]
</code></pre>
<p>If you only want combinations with 2 or more in the "in" list, you can add a condition:</p>
<pre><code>>>> [(mask(lst, p, 1), mask(lst, p, 0)) for p in product([1,0],repeat=len(lst)) if sum(p) >= 2]
</code></pre>
<p>Or use <code>numpy</code> arrays and make use of <code>numpy</code>'s advanced indexing:</p>
<pre><code>>>> arr = np.array([1,2,3])
>>> [(arr[p==1], arr[p==0]) for p in map(np.array, product([1,0], repeat=len(arr)))]
[(array([1, 2, 3]), array([])),
(array([1, 2]), array([3])),
(array([1, 3]), array([2])),
(array([1]), array([2, 3])),
(array([2, 3]), array([1])),
(array([2]), array([1, 3])),
(array([3]), array([1, 2])),
(array([]), array([1, 2, 3]))]
</code></pre>
| 2 |
2016-09-17T14:18:31Z
|
[
"python",
"python-2.7",
"combinations",
"itertools"
] |
How do I create a new text file after every loop in a while loop?
| 39,545,549 |
<p>I have a piece of text which I want to write in different text files, so I'm using a while loop to create a new txt file after every loop. However I don't know how to create a new text file AFTER every loop has been completed. For the text, I have a variable outside the loop, so the text is not an issue. I just don't know how to create new multiple files, without rewriting the existing txt file. Can someone please help?</p>
| -1 |
2016-09-17T10:10:23Z
| 39,545,578 |
<p>just generate a different filename every time you open the file for writing that would do.
Or best would be not to create multiple files. Just write into one file and create (no_of_copies-1) symlinks with different names. This would be efficient. </p>
| 0 |
2016-09-17T10:12:51Z
|
[
"python",
"while-loop",
"createfile"
] |
Get same value for predictions by a Neural network implemented using python
| 39,545,562 |
<p>I want to predict whether a given passenger is survived or not, in the titanic disaster. I give 0 to the unsurvived ones and 1 to the survived ones. I used python scikit learn library and implemented the following neural network for classification. When predicting, I get only 0 for all the passengers. Can anyone help me to solve this problem. </p>
<pre><code>from sklearn.neural_network import MLPClassifier
>>> clf = MLPClassifier(solver='lbgfs', alpha=1e-5,
... hidden_layer_sizes=(5, 2), random_state=1)
...
>>> clf.fit(train_data)
MLPClassifier(activation='relu', alpha=1e-05, batch_size='auto',
beta_1=0.9, beta_2=0.999, early_stopping=False,
epsilon=1e-08, hidden_layer_sizes=(5, 2), learning_rate='constant',
learning_rate_init=0.001, max_iter=200, momentum=0.9,
nesterovs_momentum=True, power_t=0.5, random_state=1, shuffle=True,
solver='lbgfs', tol=0.0001, validation_fraction=0.1, verbose=False,
warm_start=False)
</code></pre>
| 0 |
2016-09-17T10:11:17Z
| 39,549,765 |
<p>Maybe it is related to the format of your training data, if you are using 2 output layers for a binary classification you will need to apply "one hot encoding" for your output variable, have you tried a logistic activation to see if it returns values between 0 and 1?</p>
| 0 |
2016-09-17T17:28:44Z
|
[
"python",
"machine-learning",
"scikit-learn",
"neural-network",
"prediction"
] |
Get same value for predictions by a Neural network implemented using python
| 39,545,562 |
<p>I want to predict whether a given passenger is survived or not, in the titanic disaster. I give 0 to the unsurvived ones and 1 to the survived ones. I used python scikit learn library and implemented the following neural network for classification. When predicting, I get only 0 for all the passengers. Can anyone help me to solve this problem. </p>
<pre><code>from sklearn.neural_network import MLPClassifier
>>> clf = MLPClassifier(solver='lbgfs', alpha=1e-5,
... hidden_layer_sizes=(5, 2), random_state=1)
...
>>> clf.fit(train_data)
MLPClassifier(activation='relu', alpha=1e-05, batch_size='auto',
beta_1=0.9, beta_2=0.999, early_stopping=False,
epsilon=1e-08, hidden_layer_sizes=(5, 2), learning_rate='constant',
learning_rate_init=0.001, max_iter=200, momentum=0.9,
nesterovs_momentum=True, power_t=0.5, random_state=1, shuffle=True,
solver='lbgfs', tol=0.0001, validation_fraction=0.1, verbose=False,
warm_start=False)
</code></pre>
| 0 |
2016-09-17T10:11:17Z
| 39,560,713 |
<p>This type of problem is typically observed when data is not normalized/ standardized (at least I can not see that in your code). Neural net techniques are very susceptible of scale difference between different feature so standardization of data [mean =0 std =1] for all columns is a good practice. </p>
| 0 |
2016-09-18T17:37:54Z
|
[
"python",
"machine-learning",
"scikit-learn",
"neural-network",
"prediction"
] |
An error appears saying a function was referenced before it was assigned but only when I enter the year above 2005 or 2004
| 39,545,565 |
<pre><code>x = 2
while x>1:
from random import randint
import time
fn = input("Hello, what is your first name?")
while any (ltr.isdigit() for ltr in fn):
fn = input("Sorry an integer was entered, please try again")
firstname = (fn[0].upper())
ln = input("Hello, what is your last name?")
while any (ltr.isdigit() for ltr in ln):
ln = input("Sorry an integer was entered, please try again")
lastname = (ln.lower())
def main():
dob = input("Please enter the year you were born")
if dob > ("2005"):
main()
elif dob < ("2004"):
main()
else:
def mob():
if dob == ("2005"):
age = 11
elif dob == ("2004"):
month = input("Please enter the first three letters of the month you were born")
while month not in ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul","Aug","AUG","aug","Sep","SEP","sep","Oct","OCT","oct","Nov","NOV","nov","Dec","DEC","dec"):
month = input("Sorry that was incorrect, please enter the first three letters of the month you were born")
if month in ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
age = 12
elif month in ("Aug","AUG","aug"):
day = input("Please input the day you were born")
while day not in("31","30","29","28","27","26","25","24","23","22","21","20","19","18","17","16","15","14","13","12","11","10","9","8","7","6","5","4","3","2","1"):
day = input("Please input the day you were born")
if day == ("28","27","26","25","24","23","22","21","20","19","18","17","16","15","14","13","12","11","10","9","8","7","6","5","4","3","2","1"):
age = 12
elif day in ("29","30","31"):
age = 11
else:
age = 12
else:
age = 11
else:
age = 11
usernames = []
age = int(age)
age2 = age + randint(1,9)
age2 = str(age2)
print("Thank you for taking the time to enter your details, your username is now being generated")
time.sleep(1)
print("Generating...")
time.sleep(2)
username = (dob[2]+''+dob[3]+''+firstname+''+lastname+''+age2)
print("This is your username:" +''+username)
usernames.append(username)
age = str(age)
with open("Import Usernames.txt", "w") as text_file:
print("The usernames are: {}".format(usernames), file=text_file)
mob()
main()
</code></pre>
<p>An error only appears when I enter a year higher than 2005 or lower than 2004 but I don't know why, my question is, what have I done wrong?</p>
<p>This is the error that pops up:</p>
<p>UnboundLocalError: local variable 'mob' referenced before assignment</p>
| 0 |
2016-09-17T10:11:26Z
| 39,545,619 |
<p>This whole programs is structured wrong...</p>
<p>Anyway, <code>mob</code> is declared only inside the <code>else</code> scope and is called right after the <code>if-elif-else</code> statements.<br>
You should declare it in each these scopes, or right before them.</p>
<p>Beside that, I really suggest you read about <a href="http://www.diveintopython.net/getting_to_know_python/indenting_code.html" rel="nofollow">Python identation</a>.</p>
| 0 |
2016-09-17T10:17:16Z
|
[
"python",
"python-3.x"
] |
Variable n as an upper bound of a for loop
| 39,545,597 |
<p>I wanted to calculate the sum of (1+1+1+...+1)^2 with a for loop, but with a variable n as the upper bound so that the sum results in a function f(n) = n^2. With a non-negative integer x as the input, the loop could easily be coded as</p>
<pre><code>p==0
def f(x):
global p
for i in range(0,x):
p=p+1
return p**2
</code></pre>
<p>I wanted to feed a string n to this sort of loop. Is this doable (with or without modification)? Do I have to do string-converting hijinks a la SymPy?</p>
<p>edit: wow I worded this problem <strong>really</strong> poorly. guess sleep is important after all</p>
<p>Suppose I have a function f(x), where</p>
<pre><code>f(1) = 1
f(2) = f(1+1) = (1+1)^2 = 4
f(3) = f(1+2*1) = (1+2)^2 = 9
</code></pre>
<p>Then, f(n) would be</p>
<pre><code>f(n) = f(1+(n-1)*1) = (1+(n-1))^2 = n^2
</code></pre>
<p>If I were to calculate the result with a for loop above (which is a mess due to sleep deprivation), I'd enter f(1), f(2), f(3),... to the for loop above. I'm asking if I can enter n to the for loop above, with or without modification, and get n^2.</p>
<p>(The relation between f(1), f(2),... here isn't the same as the problem I have right now - I'm just wondering whether this idea is possible or not, and if so, how. I wouldn't learn anything if I ask the question directly, would I?)</p>
<p>edit2: An example of input/output with the algorithm above:</p>
<p>(Integer input)</p>
<pre><code>f(1) = 1^2
f(2) = 2^2
f(423) = 423^2
</code></pre>
<p>(Float input)</p>
<pre><code>f(0.5) = (0.5)^2
f(1.5) = (1.5)^2
f(234.23) = (234.23)^2
</code></pre>
<p>(String input - without assigning integer/float values to these strings first)</p>
<pre><code>f(a) = a^2
f(df) = (df)^2
f(the_speed_of_an_unladen_swallow) = (the_speed_of_an_unladen_swallow)^2
</code></pre>
<p>What I'm aiming for is a modification for the loop above so that I can do this, for f(a) where f is the function above:</p>
<pre><code>def g(a):
return f(a)
</code></pre>
<p>or the equivalent thereof.</p>
<p>I'm just going to leave this here since I look less like a sleep-deprived uni student and more like a sleep-deprived retarded uni student right now.</p>
| -1 |
2016-09-17T10:14:46Z
| 39,545,653 |
<p>Do you want to do something like <code>def('123')</code>?</p>
<p>If so, cast the string to int before using it in <code>range</code>, as such:</p>
<pre><code>for i in range(0,int(x)):
</code></pre>
| 0 |
2016-09-17T10:19:53Z
|
[
"python",
"iteration"
] |
Variable n as an upper bound of a for loop
| 39,545,597 |
<p>I wanted to calculate the sum of (1+1+1+...+1)^2 with a for loop, but with a variable n as the upper bound so that the sum results in a function f(n) = n^2. With a non-negative integer x as the input, the loop could easily be coded as</p>
<pre><code>p==0
def f(x):
global p
for i in range(0,x):
p=p+1
return p**2
</code></pre>
<p>I wanted to feed a string n to this sort of loop. Is this doable (with or without modification)? Do I have to do string-converting hijinks a la SymPy?</p>
<p>edit: wow I worded this problem <strong>really</strong> poorly. guess sleep is important after all</p>
<p>Suppose I have a function f(x), where</p>
<pre><code>f(1) = 1
f(2) = f(1+1) = (1+1)^2 = 4
f(3) = f(1+2*1) = (1+2)^2 = 9
</code></pre>
<p>Then, f(n) would be</p>
<pre><code>f(n) = f(1+(n-1)*1) = (1+(n-1))^2 = n^2
</code></pre>
<p>If I were to calculate the result with a for loop above (which is a mess due to sleep deprivation), I'd enter f(1), f(2), f(3),... to the for loop above. I'm asking if I can enter n to the for loop above, with or without modification, and get n^2.</p>
<p>(The relation between f(1), f(2),... here isn't the same as the problem I have right now - I'm just wondering whether this idea is possible or not, and if so, how. I wouldn't learn anything if I ask the question directly, would I?)</p>
<p>edit2: An example of input/output with the algorithm above:</p>
<p>(Integer input)</p>
<pre><code>f(1) = 1^2
f(2) = 2^2
f(423) = 423^2
</code></pre>
<p>(Float input)</p>
<pre><code>f(0.5) = (0.5)^2
f(1.5) = (1.5)^2
f(234.23) = (234.23)^2
</code></pre>
<p>(String input - without assigning integer/float values to these strings first)</p>
<pre><code>f(a) = a^2
f(df) = (df)^2
f(the_speed_of_an_unladen_swallow) = (the_speed_of_an_unladen_swallow)^2
</code></pre>
<p>What I'm aiming for is a modification for the loop above so that I can do this, for f(a) where f is the function above:</p>
<pre><code>def g(a):
return f(a)
</code></pre>
<p>or the equivalent thereof.</p>
<p>I'm just going to leave this here since I look less like a sleep-deprived uni student and more like a sleep-deprived retarded uni student right now.</p>
| -1 |
2016-09-17T10:14:46Z
| 39,546,045 |
<p>You wrote:</p>
<blockquote>
<p>(String input - without assigning integer/float values to these strings first)</p>
<pre><code>f(a) = a^2
f(df) = (df)^2
f(the_speed_of_an_unladen_swallow) = (the_speed_of_an_unladen_swallow)^2
</code></pre>
</blockquote>
<p>So, you have variables (<code>a</code>, <code>df</code>, <code>the_speed_of_an_unladen_swallow</code>), which do not yet contain a (good) value at the time you call <code>f</code>. Later, they would have a numerical value, and you'd like to loop that many times in your function.</p>
<p>As variables with a primitive data type are passed by value, you would have to pass the name of the variable instead, to do something similar.</p>
<p>Maybe this is something you are looking for?</p>
<pre><code>def f(x):
def localF():
return globals()[x]**2 # loop could be here, but this is the essence
return localF
# n does not have its value yet
n = None
# call f: it should not produce the result yet, as n is not correctly set yet
g = f('n')
# set n to its intended value
n = 5;
# Call the function we got from f:
print (g());
# output is 25.
</code></pre>
| 0 |
2016-09-17T11:02:56Z
|
[
"python",
"iteration"
] |
How to write a regex in Python with named groups to match this?
| 39,545,646 |
<p>I have a file which would contain the following lines.</p>
<p>comm=adbd pid=11108 prio=120 success=1 target_cpu=001</p>
<p>I have written the following regex to match.</p>
<pre><code>_sched_wakeup_pattern = re.compile(r"""
comm=(?P<next_comm>.+?)
\spid=(?P<next_pid>\d+)
\sprio=(?P<next_prio>\d+)
\ssuccess=(?P<success>\d)
\starget_cpu=(?P<target_cpu>\d+)
""", re.VERBOSE)
</code></pre>
<p>But now I've lines like the following also where the success component isn't there.</p>
<p>comm=rcu_preempt pid=7 prio=120 target_cpu=007</p>
<p>How do I modify my regex here to match both the cases? I tried by putting a * everywhere in that line containing "success", but it throws errors.</p>
| 1 |
2016-09-17T10:19:36Z
| 39,546,070 |
<p>Matching <code>0</code> or <code>1</code> repetitions do <code>(your_string)?</code>.</p>
<pre><code>_sched_wakeup_pattern = re.compile(r"""
comm=(?P<next_comm>.+?)
\spid=(?P<next_pid>\d+)
\sprio=(?P<next_prio>\d+)
\s?(success=(?P<success>\d))?
\starget_cpu=(?P<target_cpu>\d+)
""", re.VERBOSE)
</code></pre>
<p>There you go
Here it looks for the whole string so, it also print <code>success=</code>:</p>
<pre><code>output =>
('rcu_preempt', '7', '120', '', '', '007')
('kworker/u16:2', '73', '120', '', '', '006')
('kworker/u16:4', '364', '120', '', '', '005')
('adbd', '11108', '120', 'success=1', '1', '001')
('kworker/1:1', '16625', '120', 'success=1', '1', '001')
('rcu_preempt', '7', '120', 'success=1', '1', '002')
</code></pre>
<p>now we need to figure out a way to remove that <code>"success="</code>. That doesn't seem difficult.</p>
<p>[edited]<br>
<code>(?:\ssuccess=)?(?P<success>\d)?</code> works just nicely.<br>
by <a href="http://stackoverflow.com/users/3185459/romanperekhrest">RomanPerekhrest</a></p>
| 2 |
2016-09-17T11:05:20Z
|
[
"python",
"regex",
"regex-group"
] |
How to write a regex in Python with named groups to match this?
| 39,545,646 |
<p>I have a file which would contain the following lines.</p>
<p>comm=adbd pid=11108 prio=120 success=1 target_cpu=001</p>
<p>I have written the following regex to match.</p>
<pre><code>_sched_wakeup_pattern = re.compile(r"""
comm=(?P<next_comm>.+?)
\spid=(?P<next_pid>\d+)
\sprio=(?P<next_prio>\d+)
\ssuccess=(?P<success>\d)
\starget_cpu=(?P<target_cpu>\d+)
""", re.VERBOSE)
</code></pre>
<p>But now I've lines like the following also where the success component isn't there.</p>
<p>comm=rcu_preempt pid=7 prio=120 target_cpu=007</p>
<p>How do I modify my regex here to match both the cases? I tried by putting a * everywhere in that line containing "success", but it throws errors.</p>
| 1 |
2016-09-17T10:19:36Z
| 39,546,636 |
<p>The solution using regex <em>non-capturing group</em> and <code>regex.findAll</code> function:</p>
<pre><code>import regex
...
fh = open('lines.txt', 'r'); // considering 'lines.txt' is your initial file
commlines = fh.read()
_sched_wakeup_pattern = regex.compile(r"""
comm=(?P<next_comm>[\S]+?)
\spid=(?P<next_pid>\d+)
\sprio=(?P<next_prio>\d+)
(?:\ssuccess=)?(?P<success>\d)?
\starget_cpu=(?P<target_cpu>\d+)
""", regex.VERBOSE)
result = regex.findall(_sched_wakeup_pattern, commlines)
template = "{0:15}|{1:10}|{2:9}|{3:7}|{4:10}" # column widths
print(template.format("next_comm", "next_pid", "next_prio", "success", "target_cpu")) # header
for t in result:
print(template.format(*t))
</code></pre>
<p><strong>Beautified</strong> output:</p>
<pre><code>next_comm |next_pid |next_prio|success|target_cpu
rcu_preempt |7 |120 | |007
kworker/u16:2 |73 |120 | |006
kworker/u16:4 |364 |120 | |005
adbd |11108 |120 |1 |001
kworker/1:1 |16625 |120 |1 |001
rcu_preempt |7 |120 |1 |002
</code></pre>
| 2 |
2016-09-17T12:09:34Z
|
[
"python",
"regex",
"regex-group"
] |
Intergrating 2 dataframes based on specific column values
| 39,545,655 |
<p>I am not sure if my question is correct or not, but I will try to explain it clearly here.</p>
<p>I have two dataframes, df and df2.</p>
<p>df consist of country names and their short names</p>
<pre><code> Country | Shortname
England ENG
United States USA
China CN
Thailand TH
</code></pre>
<p>df2 consists of multiple country names including duplicates:</p>
<pre><code>Country
England
England
China
China
China
Thailand
England
</code></pre>
<p>I want to integrate Shortname from df in to a new column Shortname in df2 by comparing Country in both dataframes.
This is my desired result:</p>
<p>df2</p>
<pre><code>Country | Shortname
England ENG
England ENG
China CN
China CN
China CN
Thailand TH
England ENG
</code></pre>
<p>Thank you very much.</p>
| 0 |
2016-09-17T10:19:59Z
| 39,545,685 |
<p>I'd use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> method in this case:</p>
<pre><code>In [49]: df
Out[49]:
Country Shortname
0 England ENG
1 United States USA
2 China CN
3 Thailand TH
In [50]: df2
Out[50]:
Country
0 England
1 England
2 China
3 China
4 China
5 Thailand
6 England
In [52]: df2['Shortname'] = df2.Country.map(df.set_index('Country').Shortname)
In [53]: df2
Out[53]:
Country Shortname
0 England ENG
1 England ENG
2 China CN
3 China CN
4 China CN
5 Thailand TH
6 England ENG
</code></pre>
| 1 |
2016-09-17T10:22:51Z
|
[
"python",
"pandas",
"dataframe"
] |
Intergrating 2 dataframes based on specific column values
| 39,545,655 |
<p>I am not sure if my question is correct or not, but I will try to explain it clearly here.</p>
<p>I have two dataframes, df and df2.</p>
<p>df consist of country names and their short names</p>
<pre><code> Country | Shortname
England ENG
United States USA
China CN
Thailand TH
</code></pre>
<p>df2 consists of multiple country names including duplicates:</p>
<pre><code>Country
England
England
China
China
China
Thailand
England
</code></pre>
<p>I want to integrate Shortname from df in to a new column Shortname in df2 by comparing Country in both dataframes.
This is my desired result:</p>
<p>df2</p>
<pre><code>Country | Shortname
England ENG
England ENG
China CN
China CN
China CN
Thailand TH
England ENG
</code></pre>
<p>Thank you very much.</p>
| 0 |
2016-09-17T10:19:59Z
| 39,548,018 |
<p>Alternatively, consider <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">merge</a>:</p>
<pre><code>df2 = pd.merge(df2, df, on='Country')
</code></pre>
<p>Or join:</p>
<pre><code>df2 = df2.join(df, on='Country')
</code></pre>
| 0 |
2016-09-17T14:38:38Z
|
[
"python",
"pandas",
"dataframe"
] |
Django Slugfield removing articles ('the', 'a', 'an', 'that')
| 39,545,657 |
<p>I'm using django 1.10 and I have this setup:</p>
<pre><code>class Chapter(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True)
date_completed = models.DateTimeField(blank=True, null=True)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
</code></pre>
<p>In the admin, I have :</p>
<pre><code>class ChapterAdmin (admin.ModelAdmin):
list_display = ('title','slug', 'date_completed',)
list_filter = ['title', 'date_completed']
prepopulated_fields = {"slug": ("title",)}
</code></pre>
<p>I noticed that when I create a chapter with a title like "A boy and the pig", I get "boy-and-pig" as the slug. Django is stripping of the articles from my slug. Why is this so and what's the way around it?</p>
| 1 |
2016-09-17T10:20:18Z
| 39,545,843 |
<p><strong>Why is this so?</strong></p>
<p>Well, that's the default behaviour of the <a href="http://stackoverflow.com/questions/427102/what-is-a-slug-in-django">Slugfield,</a> in Django. Why is it like that? Because generally, <a href="http://stackoverflow.com/questions/9734970/better-seo-to-remove-stop-words-from-an-articles-url-slug">it's been considered better for SEO</a>. </p>
<p><em>(I say considered, as the article linked mentions this might be dated thinking. The premise is that articles and the like are usually considered <a href="https://en.wikipedia.org/wiki/Stop_words" rel="nofollow">Stop Words</a>, the most common words in a language; they're so common that they are unhelpful for a search engine to index, as they feature in most, if not all titles. )</em></p>
<p><strong>What's the Way Around It?</strong></p>
<p>Firstly - why do you <em>want</em> to get around it? What's the use case?</p>
<p>But if you're satisified you really want to do it, then it's quite simple:</p>
<pre><code>from django.template.defaultfilters import slugify
would_be_slug = 'This is one of those rarest of things: A blog that uses article.'
slugify(would_be_slug)
>>>u'this-is-one-of-those-rarest-of-things-a-blog-that-uses-article'
</code></pre>
<p><a href="http://stackoverflow.com/questions/3816307/how-to-create-a-unique-slug-in-django">This answer has some great advice</a> on overriding standard fields and slugfields. </p>
<p><a href="https://pypi.python.org/pypi/django-autoslug" rel="nofollow">There's also a nice package</a> that will do this for you if you don't want to roll your own.</p>
| 1 |
2016-09-17T10:39:33Z
|
[
"python",
"django"
] |
Display Dictionaries in Tkinter Python
| 39,545,732 |
<p>I am written a simple Tkinter program and i am trying to display both my stock name and stock Quantity, but i find that only my stock name displays. My code is as follows:</p>
<pre><code>import sys
from tkinter import *
from tkinter import ttk
import time
from datetime import datetime
now= datetime.now()
x = []
d = dict()
def quit():
print("Have a great day! Goodbye :)")
sys.exit(0)
def display():
x_var.set(list(d))
def add(*args):
global stock
global d
global Quantity
stock = stock_Entry.get()
Quantity = int(Quantity_Entry.get())
if stock not in d:
d[stock] = Quantity
else:
d[stock] += Quantity
root = Tk()
root.title("Homework 5 216020088")
x_var = StringVar()
x_var.set(x)
mainframe = ttk.Frame(root, padding="6 6 20 20")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
ttk.Label(mainframe, text="you are accesing this on day %s of month %s of %s" % (now.day,now.month,now.year)+" at exactly %s:%s:%s" % (now.hour,now.minute,now.second), foreground="yellow", background="Black").grid(column=0, row = 0)
stock_Entry= ttk.Entry(mainframe, width = 60, textvariable="stock")
stock_Entry.grid(column=0, row = 1, sticky=W)
ttk.Label(mainframe, text="Please enter the stock name").grid(column=1, row = 1, sticky=(N, W, E, S))
Quantity_Entry= ttk.Entry(mainframe, width = 60, textvariable="Quantity")
Quantity_Entry.grid(column=0, row = 2, sticky=W)
ttk.Label(mainframe, text="Please enter the quantity").grid(column=1, row = 2, sticky=(N, W, E, S))
ttk.Button(mainframe, text="Add", command=add).grid(column=0, row=3, sticky=W)
ttk.Button(mainframe, text="Display", command=display).grid(column=0, row=3, sticky=S)
ttk.Button(mainframe, text="Exit", command=quit).grid(column=0, row=3, sticky=E)
ttk.Label(mainframe, textvariable= x_var).grid(column=0, row= 4, sticky=W)
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
root.mainloop()
</code></pre>
<p>Now this is only displaying my stock and not the Quantity, can you please help me or recommend what i should do?</p>
| 1 |
2016-09-17T10:27:09Z
| 39,545,804 |
<p>Currently, in your <code>display()</code> function you are only changing <code>x_var</code> which refers to the stock.<br>
Have you tried adding another <code>tk.Label</code> and bind a quantity variable to it?</p>
| 0 |
2016-09-17T10:35:35Z
|
[
"python",
"tkinter"
] |
How to I pass values into dependent models with Factory Boy in Django?
| 39,545,950 |
<p>Im' working on an open source django web app, and I'm looking to use Factory Boy to help me setting up models for some tests, but after a few hours reading the docs and looking at examples, I think I need to accept defeat and ask here.</p>
<p>I have a Customer model which looks a bit like this:</p>
<pre><code>class Customer(models.Model):
def save(self, *args, **kwargs):
if not self.full_name:
raise ValidationError('The full_name field is required')
super(Customer, self).save(*args, **kwargs)
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
related_name='customer',
null=True
)
created = models.DateTimeField()
created_in_billing_week = models.CharField(max_length=9)
full_name = models.CharField(max_length=255)
nickname = models.CharField(max_length=30)
mobile = models.CharField(max_length=30, default='', blank=True)
gocardless_current_mandate = models.OneToOneField(
BillingGoCardlessMandate,
on_delete=models.SET_NULL,
related_name='in_use_for_customer',
null=True,
)
</code></pre>
<p>I am also using the standard Django User Model, from django.contrib.auth.</p>
<p>Here's my factory code:</p>
<pre><code>class UserFactory(DjangoModelFactory):
class Meta:
model = get_user_model()
class CustomerFactory(DjangoModelFactory):
class Meta:
model = models.Customer
full_name = fake.name()
nickname = factory.LazyAttribute(lambda obj: obj.full_name.split(' ')[0])
created = factory.LazyFunction(timezone.now)
created_in_billing_week = factory.LazyAttribute(lambda obj: str(get_billing_week(obj.created)))
mobile = fake.phone_number()
user = factory.SubFactory(UserFactory, username=nickname,
email="{}@example.com".format(nickname))
</code></pre>
<p>In my case, I want to be able to generate a customer like so</p>
<pre><code>CustomerFactory(fullname="Joe Bloggs")
</code></pre>
<p>And have the corresponding user generated, with the correct username, and email address.</p>
<p>Right now, I'm getting this error:</p>
<pre><code> AttributeError: The parameter full_name is unknown. Evaluated attributes are {'email': '<factory.declarations.LazyAttribute object at 0x111d999e8>@example.com'}, definitions are {'email': '<factory.declarations.LazyAttribute object at 0x111d999e8>@example.com', 'username': <DeclarationWrapper for <factory.declarations.LazyAttribute object at 0x111d999e8>>}.
</code></pre>
<p>I think this is because I'm relying on a lazy attribute here in the customer, which isn't called before the user factory is created.</p>
<p>How <em>should</em> I be doing this if I want to be able to use a factory to create the Customer model instance, with a corresponding user as described above?</p>
<p>For what it's worth the full model is visible <a href="https://github.com/productscience/blue-world-lite/blob/master/join/models.py#L226" rel="nofollow">here on the github repo</a></p>
| 0 |
2016-09-17T10:51:23Z
| 39,549,418 |
<p>In that case, the best way is to pick values from <a href="http://factoryboy.readthedocs.io/en/latest/reference.html#parents" rel="nofollow">the customer declarations</a>:</p>
<pre><code>class CustomerFactory(DjangoModelFactory):
class Meta:
model = models.Customer
full_name = factory.Faker('name')
nickname = factory.LazyAttribute(lambda obj: obj.full_name.split(' ')[0])
created = factory.LazyFunction(timezone.now)
created_in_billing_week = factory.LazyAttribute(lambda obj: str(get_billing_week(obj.created)))
mobile = factory.Faker('phone_number')
user = factory.SubFactory(
UserFactory,
username=factory.SelfAttribute('..nickname'),
email=factory.LazyAttribute(lambda u: "{}@example.com".format(u.username)))
)
</code></pre>
<p>Also, use <code>factory.Faker('field_name')</code> to get random values for each instance: the line <code>fullname = fake.name()</code> <strong>in the class declaration</strong> is equivalent to:</p>
<pre><code>DEFAULT_FULL_NAME = fake.name()
class CustomerFactory(DjangoModelFactory):
full_name = DEFAULT_FULL_NAME
class Meta:
model = models.customer
</code></pre>
<p>Whereas <code>factory.Faker('name')</code> is equivalent to:</p>
<pre><code>class CustomerFactory(DjangoModelFactory):
full_name = factory.LazyFunction(fake.name)
class Meta:
model = models.customer
</code></pre>
<p>i.e <code>fake.name()</code> will provide a different name to each model built with this factory.</p>
| 0 |
2016-09-17T16:56:57Z
|
[
"python",
"django",
"factory-boy"
] |
odoo: write function save old data
| 39,546,019 |
<p>I created an onchange function that link some object lines to the current one</p>
<pre><code>mo_lines_g1 = fields.One2many(comodel_name='object.order', inverse_name='mo_id1', copy=False )
@api.onchange('date')
def change_date(self):
if self.date:
g1=self.env['object.order'].search(['&'('date_order','>=',self.date),('date_order','<=',self.date)])
self.mo_lines_g1 = [(6,0, g1.ids )]
</code></pre>
<p>here everything is ok, but when I save the view, Odoo try to delete the linked lines from the <code>object.order</code>
<br/>
so I tried to see what the write function send I found it send the old records :<br/>
<code>vals[ 'mo_lines_g1'] = [[2, 61, False], [2, 62, False], [2, 63, False]]</code>
<br/>
normaly it must be :<br/> <code>vals['mo_lines_g1']=[] # or [(6,0,[])]</code>
<br/>
any ideas ?</p>
| 0 |
2016-09-17T10:59:18Z
| 39,546,534 |
<p>The documentation on writing to related fields <a href="https://www.odoo.com/documentation/8.0/reference/orm.html" rel="nofollow">ORM Documentation</a> speaks of the (2,_,ids) as a method which cant be used in create. If you are writing you can do the following.</p>
<p>If you overwrite the write() function you could probably put some logging in as well as (depending on the reason for Odoo's behaviour) force the record to write the way you are hoping to.</p>
<pre><code>@api.multi
def write(self, vals):
_logger = logging.getLogger(__name__)
_logger.info("PREPARING TO WRITE RECORD")
_logger.info("WRITING VALS: " + str(vals))
return super(Schedule, self).write(vals)
</code></pre>
| 0 |
2016-09-17T11:56:32Z
|
[
"python",
"openerp",
"edit",
"v8"
] |
odoo: write function save old data
| 39,546,019 |
<p>I created an onchange function that link some object lines to the current one</p>
<pre><code>mo_lines_g1 = fields.One2many(comodel_name='object.order', inverse_name='mo_id1', copy=False )
@api.onchange('date')
def change_date(self):
if self.date:
g1=self.env['object.order'].search(['&'('date_order','>=',self.date),('date_order','<=',self.date)])
self.mo_lines_g1 = [(6,0, g1.ids )]
</code></pre>
<p>here everything is ok, but when I save the view, Odoo try to delete the linked lines from the <code>object.order</code>
<br/>
so I tried to see what the write function send I found it send the old records :<br/>
<code>vals[ 'mo_lines_g1'] = [[2, 61, False], [2, 62, False], [2, 63, False]]</code>
<br/>
normaly it must be :<br/> <code>vals['mo_lines_g1']=[] # or [(6,0,[])]</code>
<br/>
any ideas ?</p>
| 0 |
2016-09-17T10:59:18Z
| 39,546,842 |
<p><code>(6, _, ids)</code> can not be used with One2many field. </p>
<p>It is described at <a href="http://odoo-development.readthedocs.io/en/latest/dev/py/x2many.html#x2many-values-filling" rel="nofollow">x2many values filling</a>. </p>
| 0 |
2016-09-17T12:31:26Z
|
[
"python",
"openerp",
"edit",
"v8"
] |
odoo: write function save old data
| 39,546,019 |
<p>I created an onchange function that link some object lines to the current one</p>
<pre><code>mo_lines_g1 = fields.One2many(comodel_name='object.order', inverse_name='mo_id1', copy=False )
@api.onchange('date')
def change_date(self):
if self.date:
g1=self.env['object.order'].search(['&'('date_order','>=',self.date),('date_order','<=',self.date)])
self.mo_lines_g1 = [(6,0, g1.ids )]
</code></pre>
<p>here everything is ok, but when I save the view, Odoo try to delete the linked lines from the <code>object.order</code>
<br/>
so I tried to see what the write function send I found it send the old records :<br/>
<code>vals[ 'mo_lines_g1'] = [[2, 61, False], [2, 62, False], [2, 63, False]]</code>
<br/>
normaly it must be :<br/> <code>vals['mo_lines_g1']=[] # or [(6,0,[])]</code>
<br/>
any ideas ?</p>
| 0 |
2016-09-17T10:59:18Z
| 39,550,815 |
<p>I think there is a bug on v8, it doesn't work automaticly <br/>
I replaced the <code>(2,id,_)</code> in the vals with <code>(3,id,_)</code> on the <strong>write</strong> funciton </p>
<pre><code>@api.multi
def write(self, vals):
if vals.has_key('mo_lines_g1'):
g1=[]
for line in vals['mo_lines_g1']:
if line[0] == 2:
line[0]=3
g1.append(line)
return super(object_order, self).write( vals)
</code></pre>
| 0 |
2016-09-17T19:21:18Z
|
[
"python",
"openerp",
"edit",
"v8"
] |
Python list comprehensions with regular expressions on a text
| 39,546,069 |
<p>I have a text file which includes integers in the text. There are one or more integers in a line or none. I want to find these integers with regular expressions and compute the sum.</p>
<p>I have managed to write the code:</p>
<pre><code>import re
doc = raw_input("File Name:")
text = open(doc)
lst = list()
total = 0
for line in text:
nums = re.findall("[0-9]+", line)
if len(nums) == 0:
continue
for num in nums:
num = int(num)
total += num
print total
</code></pre>
<p>But i also want to know the list comprehension version, can someone help?</p>
| 0 |
2016-09-17T11:05:07Z
| 39,546,123 |
<p>Since you want to calculate the sum of the numbers after you find them It's better to use a generator expression with <code>re.finditer()</code> within <code>sum()</code>. Also if the size of file in not very huge you better to read it at once, rather than one line at a time. </p>
<pre><code>import re
doc = raw_input("File Name:")
with open(doc) as f:
text = f.read()
total = sum(int(g.group(0)) for g in re.finditer(r'\d+', text))
</code></pre>
| 1 |
2016-09-17T11:11:22Z
|
[
"python",
"list-comprehension"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.