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 |
|---|---|---|---|---|---|---|---|---|---|
Fixing return format for my function | 39,945,808 | <p>The code for my function works correctly, but it is not returning the function in the format I would like. The function counts seed values in a 2nd sequence and then is supposed to return the seed counts as a list of integers. It is returning the seed counts but on separate lines rather then in a list. Here is my co... | 1 | 2016-10-09T16:23:02Z | 39,946,076 | <p>You are almost done, but if you want to print the output in a list you must first create list.Here try this:</p>
<pre><code>def count_each(seeds,xs):
output = []
for c in seeds:
count=0
for d in xs:
if c==d:
count=count+1
output.append(count)
print (ou... | 2 | 2016-10-09T16:51:34Z | [
"python",
"list",
"format",
"sequence"
] |
No Output from checkboxes in Python | 39,945,848 | <p>I'm a newbie to Python and this forum. So I'll try to explain my issue the best I can.<br>
I'm trying to get the results of check boxes to appear along with their corresponding data from fields in an SQLite database. I get in my code if I simply have "print selectedbooks" I get the checkbox results but in order to g... | 0 | 2016-10-09T16:26:46Z | 39,948,579 | <p>Ahh the faithful c.execute operation. Ok. Give the print of </p>
<pre><code>print c.execute("SELECT * FROM BOBBOOKLIST where TITLE=(?)", (TITLE, ))
</code></pre>
<p>then you would be knowing the answer. When c.execute is triggered, the data is new and the cursor is no longer valid to the old one.
You could always ... | 0 | 2016-10-09T21:11:13Z | [
"python",
"forms",
"variables",
"for-loop",
"cgi"
] |
Caesar Cipher Program | 39,946,000 | <pre><code>def caesar_cipher(message):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
... | -1 | 2016-10-09T16:44:50Z | 39,946,690 | <pre><code>def caesar_cipher(message):
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
position = po... | 0 | 2016-10-09T17:52:40Z | [
"python"
] |
Caesar Cipher Program | 39,946,000 | <pre><code>def caesar_cipher(message):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
newmessage = ""
for letter in message:
if letter in alphabet:
positionnumber = alphabet.index(letter) + 13
... | -1 | 2016-10-09T16:44:50Z | 39,946,718 | <p>This can be done very efficiently using the <code>ord</code> function. It gives you the ASCII value of a character. Regardless of how you define the alphabet, you simply do separate ciphers for uppercase and lowercase.</p>
<pre><code>def rot13(char):
"""
Calculate the ROT13 substitute for `char`
:param... | 0 | 2016-10-09T17:55:19Z | [
"python"
] |
how can we define (1,2,3,4,5,6,7,8,9) so *args take 1,2,3,7,8 | 39,946,043 | <p>Suppose we have a function with variable length parameter but i want some specific values to taken by variable length parameter ??</p>
<p>example :</p>
<pre><code>def hello(a,*args,b=10):
pass
hello(1,2,3,4,5,6,7,8,9)
</code></pre>
<blockquote>
<p>how can we define (1,2,3,4,5,6,7,8,9) so *args take 1,2,3,7,... | -2 | 2016-10-09T16:49:01Z | 39,946,128 | <p>If you want <code>*args</code> to be the 1st, 2nd, 3rd, 7th and 8th argument, you should make the function just take <code>*args</code> and then make the other args into a seperate variable.</p>
<pre><code>def hello(*args, b=10):
other_args = args[3:6] + args[8:] # Takes the fourth, fifth, sixth and ninth and o... | 0 | 2016-10-09T16:58:31Z | [
"python",
"python-2.7",
"python-3.x"
] |
Chained Conditions that require order to not produce order | 39,946,049 | <p>Whenever I <strong>chain conditions</strong> in Python (or any other language tbh) I stumble upon asking myself this, kicking me out of the productive "Zone".
When I chain conditions I can, by ordering them correctly, check conditions that without checking for the other conditions first, may produce an Error.</p>
... | 0 | 2016-10-09T16:49:25Z | 39,946,106 | <p>A more Pythonic way is to "ask for forgivness rather than permission". In other words, use a try-except block:</p>
<pre><code>try:
if some_value in some_dictionary["attr"]:
print("Woohoo")
except KeyError:
pass
</code></pre>
| 2 | 2016-10-09T16:55:03Z | [
"python",
"condition",
"keyerror"
] |
Chained Conditions that require order to not produce order | 39,946,049 | <p>Whenever I <strong>chain conditions</strong> in Python (or any other language tbh) I stumble upon asking myself this, kicking me out of the productive "Zone".
When I chain conditions I can, by ordering them correctly, check conditions that without checking for the other conditions first, may produce an Error.</p>
... | 0 | 2016-10-09T16:49:25Z | 39,946,630 | <p>Python is a late binding language, which is reflected in these kind of checks. The behavior is called <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">short-circuiting</a>. One thing I often do is:</p>
<pre><code>def do(condition_check=None):
if condition_ch... | 1 | 2016-10-09T17:47:29Z | [
"python",
"condition",
"keyerror"
] |
How to coroutine IPython <-> a callback() | 39,946,052 | <p>In an IPython terminal, I want a function deep in <code>main()</code>
to go back to IPython, where I can print, set ... as usual, then keep running <code>main()</code>:</p>
<pre><code>IPython
run main.py
...
def callback( *args ):
...
try:
back_to_ipython() # <-- how to d... | 0 | 2016-10-09T16:49:35Z | 39,946,229 | <p>You could insert a breakpoint, which would give similar outcome:</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p><a href="https://docs.python.org/3.6/library/pdb.html" rel="nofollow">https://docs.python.org/3.6/library/pdb.html</a></p>
<p>Alternative here (<code>embed()</code> function within iPython)... | 0 | 2016-10-09T17:07:26Z | [
"python",
"scipy",
"ipython",
"coroutine"
] |
How to coroutine IPython <-> a callback() | 39,946,052 | <p>In an IPython terminal, I want a function deep in <code>main()</code>
to go back to IPython, where I can print, set ... as usual, then keep running <code>main()</code>:</p>
<pre><code>IPython
run main.py
...
def callback( *args ):
...
try:
back_to_ipython() # <-- how to d... | 0 | 2016-10-09T16:49:35Z | 39,947,930 | <p>Adapting the answer in <a href="http://stackoverflow.com/a/24827245/901925">http://stackoverflow.com/a/24827245/901925</a>, I added an Ipython <code>embed</code> (<a href="https://ipython.org/ipython-doc/3/api/generated/IPython.terminal.embed.html" rel="nofollow">https://ipython.org/ipython-doc/3/api/generated/IPyth... | 0 | 2016-10-09T19:57:34Z | [
"python",
"scipy",
"ipython",
"coroutine"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,946,300 | <p>Totally silly of course, but for fun:</p>
<pre><code>s = '34 3 542 11'
n = ""; total = 0
for c in s:
if c == " ":
total = total + int(n)
n = ""
else:
n = n + c
# add the last number
total = total + int(n)
print(total)
> 590
</code></pre>
<p>This assumes all characters (apart fr... | 5 | 2016-10-09T17:13:39Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,946,311 | <p>You've definitely put some effort in here, but one part of your approach definitely won't work as-is: you're iterating over the <em>characters</em> in the string, but you keep trying to treat each character as its own number. I've written a (very commented) method that accomplishes what you want without using any li... | 2 | 2016-10-09T17:14:56Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,946,356 | <p>Try this:</p>
<pre><code>def sum_numbers(s):
sum = 0
#This string will represent each number
number_str = ''
for i in s:
if i == ' ':
#if it is a whitespace it means
#that we have a number so we incease the sum
sum += int(number_str)
number_str... | 0 | 2016-10-09T17:18:55Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,946,415 | <p>No lists were used (nor harmed) in the production of this answer:</p>
<pre><code>def sum_string(string):
total = 0
if len(string):
j = string.find(" ") % len(string) + 1
total += int(string[:j]) + sum_string(string[j:])
return total
</code></pre>
<p>If the string is noisier than the O... | 1 | 2016-10-09T17:25:24Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,946,519 | <p>You could write a generator:</p>
<pre><code>def nums(s):
idx=0
while idx<len(s):
ns=''
while idx<len(s) and s[idx].isdigit():
ns+=s[idx]
idx+=1
yield int(ns)
while idx<len(s) and not s[idx].isdigit():
idx+=1
>>> list(nums... | 0 | 2016-10-09T17:36:33Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,946,554 | <pre><code>def sum_numbers(s):
total=0
gt=0 #grand total
l=len(s)
for i in range(l):
if(s[i]!=' '):#find each number
total = int(s[i])+total*10
if(s[i]==' ' or i==l-1):#adding to the grand total and also add the last number
gt+=total
total=0
return... | 0 | 2016-10-09T17:39:26Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 39,996,547 | <p>If you want to be able to handle floats and negative numbers:</p>
<pre><code>def sum_numbers(s):
sm = i = 0
while i < len(s):
t = ""
while i < len(s) and not s[i].isspace():
t += s[i]
i += 1
if t:
sm += float(t)
else:
i +... | 1 | 2016-10-12T10:39:59Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
How to convert numbers in a string without using lists? | 39,946,092 | <p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>
<p>The function should look like this when operating:</p>
<pre><code>>>> sum_numbers('34 3 542 11')
590
</code></pre>
<p>Usually a function like this would be easy to crea... | 4 | 2016-10-09T16:53:05Z | 40,029,760 | <p>If we omit the fact <a href="https://docs.python.org/3/library/functions.html#eval" rel="nofollow"><code>eval</code></a> is <a href="http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">evil</a>, we can solve that problem with it.</p>
<pre><code>def sum_numbers(s):
s = s.replace(' ... | 0 | 2016-10-13T19:51:49Z | [
"python",
"string",
"python-3.x",
"for-loop"
] |
Setting up Environment Variable for GCP | 39,946,130 | <p>I read <a href="https://developers.google.com/identity/protocols/application-default-credentials" rel="nofollow">this</a> article but I still don't understand how I have to set up the environment variable with the <code>.json</code> file with the credentials. Do I have to enter something in the Terminal or write som... | 0 | 2016-10-09T16:58:50Z | 39,967,090 | <p>You can do either: the key part is that the environmental variable must be present for the SDK to pick up in the code that you're running. You could set it programmatically in Python (<a href="http://stackoverflow.com/questions/5971312/how-to-set-environment-variables-in-python">example</a>) or in your terminal (<a ... | 0 | 2016-10-10T21:33:31Z | [
"python",
"environment-variables",
"google-cloud-platform"
] |
Using python-docx to batch print the name of the last user to modify | 39,946,249 | <p>I'm trying to use Python to print the names of the last users to modify a bunch of documents (docx). In reality, this script should return a bunch of different names. I'm having to mix a bunch of different modules, but either I'm doing something wrong, or docx doesn't like the batch work. Has anybody got more experi... | 0 | 2016-10-09T17:09:03Z | 39,947,778 | <p>The main problem seems to be a lack of indenting. Python uses indentation (instead of curly braces) to determine what the block of your loop should be. So in this case it's only running through once. What you need is this:</p>
<pre><code>import glob, os
from docx import Document
for filename in glob.glob('/Users/o... | 0 | 2016-10-09T19:40:47Z | [
"python",
"ms-office",
"batch-processing",
"python-docx"
] |
tkinter won't quit when I press quit button, it just changes location | 39,946,260 | <p>This is the code and when I run it the quit button doesn't work:</p>
<pre class="lang-py prettyprint-override"><code>def quit2():
menu.destroy()
def menu1():
menu=Tk()
global menu
play=Button(menu, text='play', command =main)
play.pack()
quit1=Button(menu, text='quit', command=quit2)
q... | -2 | 2016-10-09T17:10:14Z | 39,946,355 | <p>You use <code>while True</code> so after you close window <code>while True</code> opens new window.</p>
<p>Use last line <code>menu1()</code> without <code>while True</code></p>
<p><strong>EDIT:</strong></p>
<pre><code>from tkinter import *
def quit2():
menu.destroy()
def menu1():
global menu
menu ... | 1 | 2016-10-09T17:18:51Z | [
"python",
"tkinter"
] |
Problems while calling NLTK with Python 3.5.2_2? | 39,946,273 | <p>When I try to import nltk in python 3.5.2_2 I get the following message:</p>
<pre><code>>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/nltk/__init__.py", line 117, in <module>
from nltk.align impo... | 0 | 2016-10-09T17:11:01Z | 39,946,966 | <p>This might work</p>
<ol>
<li>Go to <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></li>
<li>Download nltk-3.2.1-py2.py3-none-any.whl </li>
<li>Change folder in command line to where you downloaded that whl file</li>
<li>Now write <code>C:/windows/py... | 0 | 2016-10-09T18:19:10Z | [
"python",
"python-3.x",
"nltk",
"python-3.5"
] |
Problems while calling NLTK with Python 3.5.2_2? | 39,946,273 | <p>When I try to import nltk in python 3.5.2_2 I get the following message:</p>
<pre><code>>>> import nltk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/nltk/__init__.py", line 117, in <module>
from nltk.align impo... | 0 | 2016-10-09T17:11:01Z | 39,959,599 | <p>I solved this issue by upgrading with pip3 nltk and sklearn:</p>
<pre><code>user@MacBook-Pro-de-User:~$ pip3 install nltk --upgrade
Collecting nltk
Downloading nltk-3.2.1.tar.gz (1.1MB)
100% |ââââââââââââââââââââââââââââââââ| 1.1MB 675kB/s
Buildi... | 0 | 2016-10-10T13:36:04Z | [
"python",
"python-3.x",
"nltk",
"python-3.5"
] |
Does the Order of Conditions affect Performance? | 39,946,279 | <p>Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest. </p>
<p>In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if ... | 0 | 2016-10-09T17:11:34Z | 39,946,334 | <p>Yes, the order of conditions matters. They are evaluated left-to-right unless you change that by using parentheses, for example.</p>
<p>And yes, conditions are only evaluated if the outcome of the expression isn't already clear. For example, in</p>
<pre><code>if 1==0 and foo**10000 > 2:
</code></pre>
<p>Python... | 5 | 2016-10-09T17:16:49Z | [
"python",
"performance",
"condition"
] |
Does the Order of Conditions affect Performance? | 39,946,279 | <p>Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest. </p>
<p>In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if ... | 0 | 2016-10-09T17:11:34Z | 39,946,341 | <p>Python will not reorder your conditions like in SQL, but it will <a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation" rel="nofollow">short circuit</a>. What this means is that it will stop evaluating as soon as possible. So if you have <code>if True == True or long_function_call():</code>, <code>long_fun... | 2 | 2016-10-09T17:17:28Z | [
"python",
"performance",
"condition"
] |
Does the Order of Conditions affect Performance? | 39,946,279 | <p>Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest. </p>
<p>In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if ... | 0 | 2016-10-09T17:11:34Z | 39,946,498 | <p>Boolean operators in Python are <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">short-circuiting</a> - as soon as the result of an expression is clear, evaluation stops. This plays an important role in Python's late-binding.</p>
<p>For example, this is a common... | 1 | 2016-10-09T17:34:19Z | [
"python",
"performance",
"condition"
] |
Apply transform of your own function in Pandas dataframe | 39,946,287 | <p>I have pandas dataframe on which I need to some data manipulation, the following code provide me the average of column "Variable" group by "Key":</p>
<pre><code>df.groupby('key').Variable.transform("mean")
</code></pre>
<p>The advantage of using "transform" is that it return back the result with the same index whi... | 0 | 2016-10-09T17:12:36Z | 39,946,424 | <p>Don't call transform against <code>Variable</code>, call it on the grouper and then call your variables against the dataframe the function receives as argument:</p>
<pre><code>df.groupby('key').transform(lambda x: (x.Variable + x.Variable1)/x.Variable2)
</code></pre>
| 0 | 2016-10-09T17:26:43Z | [
"python",
"pandas",
"dataframe",
"aggregation"
] |
PyQt: Progress bar and label disappear | 39,946,413 | <p>I am new to Python and PyQt. When I start my program, after a few seconds, the progress bar and label disappear. The progress bar starts appearing and disappearing (the label is gone) when the mouse hovers over the progress bar, showing up once more before disappearing. But if I comment the line where I set up the p... | 0 | 2016-10-09T17:25:09Z | 39,948,819 | <p>First of all you don't need the separate class tmp(). Delete it and just move the main() function in MainWindow class. After doing this name,test variables should not be global any more. Define them in your <strong>init</strong> (for example self.test = 0, self.name='something') and refer to them in the rest of the ... | 1 | 2016-10-09T21:38:27Z | [
"python",
"multithreading",
"python-2.7",
"pyqt"
] |
Selecting checkboxes using selenium web driver with python | 39,946,419 | <p>I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome a... | 1 | 2016-10-09T17:25:44Z | 39,950,187 | <p>You should try using <code>xpath</code> as below :-</p>
<pre><code>self.browser.find_element_by_xpath(".//div[normalize-space(.)='Books']/input[@type='checkbox']").click()
</code></pre>
<p>Or</p>
<pre><code>self.browser.find_element_by_xpath(".//div[contains(@class,'checkbox') and contains(., 'Books')]/input[@typ... | 0 | 2016-10-10T01:23:02Z | [
"python",
"selenium",
"xpath",
"checkbox"
] |
Selecting checkboxes using selenium web driver with python | 39,946,419 | <p>I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome a... | 1 | 2016-10-09T17:25:44Z | 39,968,894 | <p>I have solved my problem with a very simple line of code using the right xpath:</p>
<pre><code>self.browser.find_element_by_xpath("(//input[@name=''])[8]").click()
</code></pre>
<p>and it perfectly worked!</p>
| 0 | 2016-10-11T00:52:19Z | [
"python",
"selenium",
"xpath",
"checkbox"
] |
Selecting checkboxes using selenium web driver with python | 39,946,419 | <p>I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome a... | 1 | 2016-10-09T17:25:44Z | 39,970,729 | <p>I have modified your code and now it's working</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest... | 0 | 2016-10-11T04:57:13Z | [
"python",
"selenium",
"xpath",
"checkbox"
] |
cmake osx deployment target is '10.11' but CMAKE_OSX_SYSROOT error | 39,946,504 | <p>I'm getting this cmake error while installing a python file related to openAI gym. The error log which is bugging me is the below lines..</p>
<pre><code>CMake Error at /usr/local/Cellar/cmake/3.5.2/share/cmake/Modules/Platform/Darwin.cmake:76 (message):
CMAKE_OSX_DEPLOYMENT_TARGET is '10.11' but CMAKE_OSX_S... | 1 | 2016-10-09T17:34:54Z | 40,004,078 | <p>Expanding on comment. As error text suggests:</p>
<pre><code>is not set to a MacOSX SDK with a recognized version. Either set
CMAKE_OSX_SYSROOT to a valid SDK or set CMAKE_OSX_DEPLOYMENT_TARGET to
empty.
</code></pre>
<p>You can unset CMAKE_OSX_DEPLOYMENT_TARGET to let cmake chose defaults. You can add following... | 1 | 2016-10-12T16:48:13Z | [
"python",
"osx",
"cmake"
] |
compare two lists (python) | 39,946,508 | <p>I need to compare two lists in a program to see if there are matching strings. One of them is a txt document that I already imported. Thats what I did</p>
<pre><code> def compareLists(self, listA, listB):
sameWords = list()
for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
... | 1 | 2016-10-09T17:35:21Z | 39,946,617 | <p>I am assuming the indentation is correct in your code. Continuing with your strategy, this code should work.</p>
<pre><code>def compareLists(self, listA, listB):
sameWords = list()
for a in xrange(0,len(listA)):
for b in xrange(0,len(listB)):
if listA[a] == listB[b]:
sam... | 1 | 2016-10-09T17:45:48Z | [
"python",
"list"
] |
Regular Expression to replace dot with space before parentheses | 39,946,538 | <p>I am working on some customer comments that some of them did not follow grammatical rules. For Example <code>(Such as s and b.)</code> in the following text that provides more explanation for previous sentence is surrounded by two dots. </p>
<pre><code> text = "I was initially scared of ANY drug after my experien... | 2 | 2016-10-09T17:38:00Z | 39,946,590 | <p>The sample provided does not make much sense because the only change is that the ` character is moved one position to the left.</p>
<p>However, this might do the trick (to keep the dot inside the paranthesis):</p>
<pre><code>text = re.sub(r'\.\s*\)\s*\.', '.)', text)
</code></pre>
<p>Or this to have it outside:</... | 1 | 2016-10-09T17:43:01Z | [
"python",
"regex"
] |
Regular Expression to replace dot with space before parentheses | 39,946,538 | <p>I am working on some customer comments that some of them did not follow grammatical rules. For Example <code>(Such as s and b.)</code> in the following text that provides more explanation for previous sentence is surrounded by two dots. </p>
<pre><code> text = "I was initially scared of ANY drug after my experien... | 2 | 2016-10-09T17:38:00Z | 39,946,657 | <p>I would suggest this to remove a dot before parentheses when there is another one following them:</p>
<pre><code>text = re.sub(r'\.(\s*?\([^)]*\)\s*\.)', r'\1', text)
</code></pre>
<p>See it run on <a href="https://repl.it/DrvM/3" rel="nofollow">repl.it</a></p>
| 1 | 2016-10-09T17:49:41Z | [
"python",
"regex"
] |
How to eval() a string in a dictionary Python2.7 | 39,946,562 | <p>I have a dictionary:</p>
<pre><code>key = {'K_z':'K_w'}
</code></pre>
<p>I want to get K_w as a value name instead of a string, I heard that the eval() function can convert strings to value names.</p>
<p>But when I type:</p>
<pre><code>print(eval(key['K_z']))
</code></pre>
<p>I get 'K_z' instead of having the K... | -2 | 2016-10-09T17:40:22Z | 39,946,706 | <pre><code>import pygame
key = {'K_z':'K_w',}
print (getattr(pygame,key['K_z']))
</code></pre>
<p>Using this <a href="http://claude.segeral.pagesperso-orange.fr/qwerazer/" rel="nofollow">azerty and qwerty </a> you can easily create the key dictionary by copying and editing the html table into excel and then some ... | -1 | 2016-10-09T17:54:05Z | [
"python",
"dictionary",
"pygame",
"eval"
] |
How to eval() a string in a dictionary Python2.7 | 39,946,562 | <p>I have a dictionary:</p>
<pre><code>key = {'K_z':'K_w'}
</code></pre>
<p>I want to get K_w as a value name instead of a string, I heard that the eval() function can convert strings to value names.</p>
<p>But when I type:</p>
<pre><code>print(eval(key['K_z']))
</code></pre>
<p>I get 'K_z' instead of having the K... | -2 | 2016-10-09T17:40:22Z | 39,988,649 | <p>Is this what you are looking for?</p>
<pre><code>key = {'K_z':'K_w'}
print(key['K_z'])
</code></pre>
<p>K_w</p>
<p>I don't think that <code>eval()</code> will help as it evaluates arguments. In pygame you could use <code>if key[pygame.K_w] or key[pygame.K_z]</code> do something.</p>
| 0 | 2016-10-12T00:14:43Z | [
"python",
"dictionary",
"pygame",
"eval"
] |
How to Convert to Seconds from Data Time using Tableau or Excel | 39,946,614 | <p>I have a data CSV file where the Time Duration is expressed with a "regular" datetime syntax such as <code>12/30/99 00:00:55 AM</code>.</p>
<p>Since this value represents the time duration (and not the date and time) I need to translate it to a number that would represent the the duration in minutes such as <code>5... | 1 | 2016-10-09T17:45:43Z | 39,947,332 | <p>This would be a very crude way of doing it and would rely on the format being the same.</p>
<pre><code>=(MID(E3,10,2)Ã60Ã60)+(MID(E3,13,2)Ã60)+(MID(E3,16,2))
</code></pre>
<p>MID - (Cell Reference, Start Position, No. of Characters to Extract)</p>
<p>This assumes the value is in E3, this should be changed to w... | 0 | 2016-10-09T18:55:57Z | [
"python",
"excel",
"tableau"
] |
How to Convert to Seconds from Data Time using Tableau or Excel | 39,946,614 | <p>I have a data CSV file where the Time Duration is expressed with a "regular" datetime syntax such as <code>12/30/99 00:00:55 AM</code>.</p>
<p>Since this value represents the time duration (and not the date and time) I need to translate it to a number that would represent the the duration in minutes such as <code>5... | 1 | 2016-10-09T17:45:43Z | 39,947,340 | <p>If you wanted to do it just in an Excel formula to get to seconds would be similar to Python:-</p>
<pre><code>=HOUR(A1)*3600+MINUTE(A1)*60+SECOND(A1)
</code></pre>
<p>assuming the value can be read from the CSV file into an Excel datetime value in cell A1.</p>
<p>Another way of doing it (using the fact that time ... | 1 | 2016-10-09T18:56:38Z | [
"python",
"excel",
"tableau"
] |
How to Convert to Seconds from Data Time using Tableau or Excel | 39,946,614 | <p>I have a data CSV file where the Time Duration is expressed with a "regular" datetime syntax such as <code>12/30/99 00:00:55 AM</code>.</p>
<p>Since this value represents the time duration (and not the date and time) I need to translate it to a number that would represent the the duration in minutes such as <code>5... | 1 | 2016-10-09T17:45:43Z | 39,947,671 | <p>After linking CSV file Tableau goes ahead and auto assigns the data type to each column based on its own assumptions. The original CSV's <strong>Duration</strong> column field value was actually <code>00:00:00:55</code>. But since Tableau considered it as datetime type it converted in on a fly to <code>12/30/99 00:0... | 0 | 2016-10-09T19:29:23Z | [
"python",
"excel",
"tableau"
] |
ReactorNotRestartable error in while loop with scrapy | 39,946,632 | <p>I get <code>twisted.internet.error.ReactorNotRestartable</code> error when I execute following code:</p>
<pre><code>from time import sleep
from scrapy import signals
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from scrapy.xlib.pydispatch import dispatcher
result ... | 0 | 2016-10-09T17:47:46Z | 39,955,395 | <p>By default, <a href="https://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess" rel="nofollow"><code>CrawlerProcess</code></a>'s <a href="https://doc.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess.start" rel="nofollow"><code>.start()</code></a> will stop the Twisted reactor i... | 0 | 2016-10-10T09:38:34Z | [
"python",
"python-2.7",
"scrapy",
"twisted"
] |
Removing punctuation/symbols from a list with Python except periods, commas | 39,946,660 | <p>In Python, I need to remove almost all punctuation from a list but save periods and commas. Should I create a function to do this or a variable? Basically I want to delete all symbols except letters (I've already converted uppercase letters to lowercase) and periods and commas (and maybe apostrophes). </p>
<pre><co... | 1 | 2016-10-09T17:49:52Z | 39,946,713 | <p>You can build a set of unwanted punctuation from <a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow"><code>string.punctuation</code></a> - which provides a string containing punctuation, and then use a <em>list comprehension</em> to filter out the letters contained in the set:</... | 0 | 2016-10-09T17:54:53Z | [
"python",
"normalization"
] |
Removing punctuation/symbols from a list with Python except periods, commas | 39,946,660 | <p>In Python, I need to remove almost all punctuation from a list but save periods and commas. Should I create a function to do this or a variable? Basically I want to delete all symbols except letters (I've already converted uppercase letters to lowercase) and periods and commas (and maybe apostrophes). </p>
<pre><co... | 1 | 2016-10-09T17:49:52Z | 39,946,762 | <pre><code>import string
# Create a set of all allowed characters.
# {...} is the syntax for a set literal in Python.
allowed = {",", "."}.union(string.ascii_lowercase)
# This is our starting string.
lc_tokens = 'hello, "world!"'
# Now we use list comprehension to only allow letters in our allowed set.
# The result ... | 0 | 2016-10-09T17:59:43Z | [
"python",
"normalization"
] |
Descriptor protocol implementation of property() | 39,946,666 | <p>The Python <a href="https://docs.python.org/3.5/howto/descriptor.html#properties" rel="nofollow">descriptor How-To</a> describes how one could implement the <code>property()</code> in terms of descriptors. I do not understand the reason of the first if-block in the <code>__get__</code> method. Under what circumstanc... | 2 | 2016-10-09T17:50:38Z | 39,947,061 | <p>From the <a href="https://docs.python.org/3.5/howto/descriptor.html#invoking-descriptors" rel="nofollow">descriptor documentation</a>:</p>
<blockquote>
<p>The details of invocation depend on whether <code>obj</code> is an object or a class.</p>
</blockquote>
<p>Basically, instances call descriptors as <code>type... | 1 | 2016-10-09T18:29:09Z | [
"python"
] |
Descriptor protocol implementation of property() | 39,946,666 | <p>The Python <a href="https://docs.python.org/3.5/howto/descriptor.html#properties" rel="nofollow">descriptor How-To</a> describes how one could implement the <code>property()</code> in terms of descriptors. I do not understand the reason of the first if-block in the <code>__get__</code> method. Under what circumstanc... | 2 | 2016-10-09T17:50:38Z | 39,947,066 | <p>You can see what the effect is by making another version that leaves that test out. I made a class Property that uses the code you posted, and another BadProperty that leaves out that <code>if</code> block. Then I made this class:</p>
<pre><code>class Foo(object):
@Property
def good(self):
print("... | 2 | 2016-10-09T18:29:25Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not pa... | 0 | 2016-10-09T17:56:44Z | 39,946,764 | <p>The classic solution:</p>
<pre><code>def palindrome(n):
start = 0
end = len(n) - 1
while (start < end):
if (n[start] != n[end]):
return False
start = start + 1
end = end - 1
return True
</code></pre>
| 0 | 2016-10-09T17:59:58Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not pa... | 0 | 2016-10-09T17:56:44Z | 39,946,801 | <p>Use raw_input:</p>
<pre><code>n = str(raw_input('Enter the string:'))
</code></pre>
| 1 | 2016-10-09T18:02:48Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not pa... | 0 | 2016-10-09T17:56:44Z | 39,946,846 | <pre><code>def palindrome(my_string):
reverse_string = my_string[::-1]
if list(my_string)==list(reverse_string):
return True
else:
return False
my_string = input("ENTER THE STRING ")
if(palindrome(my_string)):
print("Palindrome")
else:
print("Not Palindrome")
</code></pre>
| 2 | 2016-10-09T18:07:16Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not pa... | 0 | 2016-10-09T17:56:44Z | 39,946,914 | <pre><code>while index < int(len(n) / 2):
if n[index] != n[len(n) - index - 1]:
return False
index+=1
return True
</code></pre>
| 0 | 2016-10-09T18:13:51Z | [
"python"
] |
Returning result of palindrome program using while-loop | 39,946,732 | <pre><code>n = str(input('Enter the string:'))
def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1
return True
break
return False
if palindrome(n)==True:
print('palindrome')
else:
print('not pa... | 0 | 2016-10-09T17:56:44Z | 39,947,109 | <p>Your check is broken. Look at <code>return True</code>:</p>
<pre><code>def palindrome(n):
index = 0
check = True
while index<int(len(n)/2):
if n[index]==n[-1-index]:
index+=1 # only increment on match !!!
return True # return True on *first* match !!!
bre... | 0 | 2016-10-09T18:33:39Z | [
"python"
] |
What is the Python equivalent to C# LINQ Sum() | 39,946,748 | <p>In C# I can get the sum of some values like so:</p>
<pre><code>new List<Tuple<string, int>>().Sum(x => x.Item2);
</code></pre>
<p>How can I achieve the same result in Python? Assuming I have a list of tuples</p>
| 1 | 2016-10-09T17:58:22Z | 39,946,784 | <p>The equivalent is a <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">comprehension</a> inside a <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum()</code></a>.</p>
<pre><code>sum(x[1] for x in tuples)
</code></pre>
<p>For example, we can def... | 5 | 2016-10-09T18:01:48Z | [
"c#",
"python"
] |
Falcon parsing json error | 39,946,770 | <p>I'm trying out Falcon for a small api project. Unfortunate i'm stuck on the json parsing stuff and code from the documentation examples does not work.</p>
<p>I have tried so many things i've found on Stack and Google but no changes.
I've tried the following codes that results in the errors below</p>
<pre><code>imp... | 0 | 2016-10-09T18:00:16Z | 39,954,948 | <p>your code should work if other pieces of code are in place . a quick test(filename app.py):</p>
<pre><code>import falcon
import json
class JSON_Middleware(object):
def process_request(self, req, resp):
raw_json = json.loads(req.stream.read())
print raw_json
class Test:
def on_post(self,req,r... | 0 | 2016-10-10T09:14:11Z | [
"python",
"python-3.x",
"falconframework"
] |
finding pattern within csv file | 39,946,798 | <p>I have a CSV Excel file example:</p>
<pre><code>Receipt Name Address Date Time Items
25007 A ABC pte ltd 4/7/2016 10:40 Cheese, Cookie, Pie
.
.
25008 B CCC pte ltd 4/7/2016 12:40 Cheese, Cookie
</code></pre>
<p>What is a simple way to compare the 'Items' column and find o... | 2 | 2016-10-09T18:02:38Z | 39,946,925 | <p>Presuming you have comma separated values, you can use a <em>frozenset</em> of the pairings and use a <em>Counter</em> dict to get the counts:</p>
<pre><code>from collections import Counter
import csv
with open("test.csv") as f:
next(f)
counts = Counter(frozenset(tuple(row[-1].split(",")))
... | 0 | 2016-10-09T18:15:05Z | [
"python",
"regex",
"csv"
] |
finding pattern within csv file | 39,946,798 | <p>I have a CSV Excel file example:</p>
<pre><code>Receipt Name Address Date Time Items
25007 A ABC pte ltd 4/7/2016 10:40 Cheese, Cookie, Pie
.
.
25008 B CCC pte ltd 4/7/2016 12:40 Cheese, Cookie
</code></pre>
<p>What is a simple way to compare the 'Items' column and find o... | 2 | 2016-10-09T18:02:38Z | 39,947,519 | <p>Suppose after processing the CSV file you find the list of items from the CSV file to be:</p>
<pre><code>>>> items=['Cheese,Cookie,Pie', 'Cheese,Cookie,Pie', 'Cake,Cookie,Cheese',
... 'Cheese,Mousetrap,Pie', 'Cheese,Jam','Cheese','Cookie,Cheese,Mousetrap']
</code></pre>
<p>First determine all possible pa... | 2 | 2016-10-09T19:15:46Z | [
"python",
"regex",
"csv"
] |
All lowest common ancestor with NetworkX | 39,946,894 | <p>I want to get all LCA nodes from node"a" and node"o".</p>
<p>In this DiGraph, node"l" and node"m" are LCA nodes.</p>
<p>The following is the code.</p>
<pre><code>import networkx as nx
def calc_length(Graph, node1, node2, elem):
length1 = nx.shortest_path_length(Graph, node1, elem)
length2 = nx.shortest_p... | 1 | 2016-10-09T18:11:32Z | 39,967,777 | <p>There are several issues here, some of which I have pointed out in the comments. Part of the problem is that the nomenclature is confusing: the lowest common ancestor (<a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" rel="nofollow">as defined on wikipedia</a> and presumably in computer science in gener... | 0 | 2016-10-10T22:35:06Z | [
"python",
"algorithm",
"networkx",
"lowest-common-ancestor"
] |
Kivy does not find fonts in Cygwin | 39,947,005 | <p>I use <code>Kivy</code> in <code>Cygwin.</code></p>
<p>Per <strong>Vasilkov, Mark. <em>Kivy Blueprints</em>. Birmingham:Packt Publishing, 2015. pp. 17</strong>, I wanted to use the <code>Roboto</code> fonts in the following code:</p>
<pre><code># File: main.py
from kivy.app import App
from kivy.core.text import L... | 0 | 2016-10-09T18:23:37Z | 39,964,402 | <p>You have to provide the path of your fonts in your <code>LabelBase.register()</code>. Do you have those font files in your directory?</p>
| 0 | 2016-10-10T18:19:49Z | [
"python",
"fonts",
"cygwin",
"kivy",
"x11"
] |
Sort a csv with python from standard input | 39,947,024 | <p>This is my python script for sorting by column a csv file read from stdin:</p>
<pre><code>with sys.stdin as csvfile:
reader = csv.reader(csvfile, delimiter=',')
sortedlist = sorted(reader, key=operator.itemgetter(2))
for row in sortedlist:
print(','.join(row)),
print('\n'),
</code></pre>
<p>I run ... | 0 | 2016-10-09T18:26:03Z | 39,947,307 | <blockquote>
<p>This sorts alphabetically not numerically</p>
</blockquote>
<p>You'll have to <em>cast</em> the sort column values to integer in order to sort numerically. I have replaced the sort function with a <code>lambda</code> that includes the conversion to <code>int</code>:</p>
<pre><code>sortedlist = sorte... | 1 | 2016-10-09T18:53:34Z | [
"python",
"sorting",
"csv"
] |
How to continue the object in django get_next/previous_by_date_created and published? | 39,947,041 | <p>Anyone can help me how to continue the object in Django by <code>get_next/previous_by_date_created</code> and published only?</p>
<pre><code>>>> obj_4 = Post.objects.get(pk=4)
>>> obj_4.publish
True
>>> obj_4.get_previous_by_date_created()
<Post: Title Post 3>
>>> obj_4.get... | 0 | 2016-10-09T18:27:58Z | 39,947,399 | <p>An implementation which will work is:</p>
<pre><code>def get_previous_by_created_and_published(self):
prev = Post.objects.filter(created__lte=self.created,
published=True
).order_by('-created').first()
return prev
</code></pre>
<p>Though I'm ass... | 1 | 2016-10-09T19:02:41Z | [
"python",
"django",
"django-templates"
] |
Tensorflow: method to save and restore TensorFlowEstimator() | 39,947,044 | <p>How to save and load this object (<code>regressor</code>)? </p>
<pre><code>from tensorflow.contrib import learn
regressor = learn.TensorFlowEstimator()
</code></pre>
<p>I could not use tensorflow's default Saver() to save it.</p>
<p>How to do incremental learning with this model? I am confused about <code>continu... | 1 | 2016-10-09T18:28:04Z | 39,947,135 | <p>According to this <a href="https://github.com/tensorflow/skflow#saving--restoring-models" rel="nofollow">TF tutorial</a>, the following should work: </p>
<p>for saving:</p>
<pre><code>regressor.save('/tmp/tf_examples/my_model_1/')
</code></pre>
<p>for restoring:</p>
<pre><code>new_regressor = TensorFlowEstimator... | 1 | 2016-10-09T18:36:12Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow",
"lstm"
] |
One line python code to return all sublists of list containing specific substring in a particluar column | 39,947,119 | <p>I want to return all the sublists of lists which contains specific substring in a particular column:</p>
<p>For eg:</p>
<pre><code>List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
</code></pre>
<p>Search Criteria : Return all sublists which contains substr... | 0 | 2016-10-09T18:34:44Z | 39,947,151 | <p>Your list comprehension approach is good and gives the correct result. Are you sure your code is the same from which you pasted the output because it works for me:</p>
<pre><code>>>> List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
>>> [sub... | 1 | 2016-10-09T18:37:44Z | [
"python",
"python-2.7",
"python-3.x",
"filter",
"nested-lists"
] |
Python: How to create nested dictionaries out of lists with specific values | 39,947,137 | <p>I apologize in advance for the long post, but I've made sure it's easy to follow and very clear. </p>
<p>My question is this:</p>
<blockquote>
<p>How can I create a nested dictionary out of lists, with specified duplicate keys? </p>
</blockquote>
<p>Here's an example of what I'd like to make, using data for a f... | 0 | 2016-10-09T18:36:14Z | 39,947,916 | <p>Consider a dictionary comprehension:</p>
<pre><code>newsdict = {v: {'Title': k,
'Source': 'Reuters',
'Thumbnail': 'http://logok.org/wp-content/uploads/2014/04/Reuters-logo.png'}
for k, v in reuters_dictionary.items()}
</code></pre>
| 2 | 2016-10-09T19:56:34Z | [
"python",
"python-3.x",
"list-comprehension",
"dict-comprehension"
] |
Python: How to create nested dictionaries out of lists with specific values | 39,947,137 | <p>I apologize in advance for the long post, but I've made sure it's easy to follow and very clear. </p>
<p>My question is this:</p>
<blockquote>
<p>How can I create a nested dictionary out of lists, with specified duplicate keys? </p>
</blockquote>
<p>Here's an example of what I'd like to make, using data for a f... | 0 | 2016-10-09T18:36:14Z | 39,947,955 | <p>This should give you the result you want:</p>
<pre><code>def build_dict():
""" Combine everything into a tidy dictionary. """
full_urls = [i if i.startswith('http') else url + i for i in get_link()]
reuters_dictionary = {}
for (headline, url) in zip(get_headline(), full_urls):
reuters_dictio... | 0 | 2016-10-09T20:00:50Z | [
"python",
"python-3.x",
"list-comprehension",
"dict-comprehension"
] |
Python processing how to link with Meteor | 39,947,179 | <p>I have a python script that do some processing over a database of files, the script produce some plots and other relevant numbers as consequence of the analysis. I'm building a Meteor App and what i want , is show the results from my python script inside a Meteor template.</p>
<p>what i wnat is that the entire app ... | 0 | 2016-10-09T18:41:24Z | 39,947,569 | <p>In the Meteor Method use the following code :</p>
<pre><code>'methodName':function(){
new Fiber(function(){
console.log('test python file');
var file_path = process.env.PWD + "/path_to_file/hello.py";
exec("python " + file_path, function (error, stdout, stderr) {
... | 1 | 2016-10-09T19:19:39Z | [
"javascript",
"python",
"meteor"
] |
Find all combinations of a list | 39,947,298 | <p>The function scoreList(Rack) takes in a list of letters. You are also given a global variable Dictionary: ["a", "am", "at", "apple", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"].</p>
<p>Using a list of letters find all possible words that can be made with the letters that are in the Dictionary.... | -2 | 2016-10-09T18:52:52Z | 39,947,397 | <p>Apparently you're asking the same question repeatedly (according to a comment on your question). So I'm going to answer this as thoroughly as possible</p>
<p>You seem to have a scrabble dictionary in a list called <code>Dictionary</code>. I'm going to move forward from that point:</p>
<pre><code>import itertools
... | 0 | 2016-10-09T19:02:29Z | [
"python",
"list"
] |
Incremental training using TensorFlowEstimator | 39,947,322 | <p>I am using tensorflow for my machine learning model. </p>
<pre><code>from tensorflow.contrib import learn
regressor = learn.TensorFlowEstimator()
</code></pre>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard4/tf.contrib.learn.TensorFlowE... | 0 | 2016-10-09T18:55:24Z | 39,947,532 | <p>You can just use fit() with continue_training; partial_fit will eventually get deprecated.</p>
| 2 | 2016-10-09T19:16:42Z | [
"python",
"python-3.x",
"machine-learning",
"tensorflow"
] |
Big files containing several columns, export all the columns by naming them with the file name and a value | 39,947,344 | <p>Thank you in advance for your answer !
I have lot of files wich contain columns.
I want to export all the columns separately in multiple files.
Moreover, I want to use the first value of each column to be the index of the file name.</p>
<p>For example. If I have the file "test_.dat" which contains 3 columns :</p>
... | 0 | 2016-10-09T18:57:02Z | 39,947,607 | <p>An easy way is to read the large file with <code>pandas</code>, it is designed for big data handling.</p>
<p>To read the data use the following:</p>
<pre><code>import pandas as pd
df = pd.read_csv('test.bat', sep='\s', engine='python', header=None)
</code></pre>
<p>to save the columns as individual files you can... | 1 | 2016-10-09T19:23:36Z | [
"python"
] |
Big files containing several columns, export all the columns by naming them with the file name and a value | 39,947,344 | <p>Thank you in advance for your answer !
I have lot of files wich contain columns.
I want to export all the columns separately in multiple files.
Moreover, I want to use the first value of each column to be the index of the file name.</p>
<p>For example. If I have the file "test_.dat" which contains 3 columns :</p>
... | 0 | 2016-10-09T18:57:02Z | 39,948,146 | <pre><code>fps_out = []
with open('test_.dat', 'r') as fp_in:
for line in fp_in:
if not fps_out:
for data in line.split():
fps_out.append(open('test_%s.dat' % data, 'w'))
else:
for pos, data in enumerate(line.split()):
fps_out[pos].write(data +... | 0 | 2016-10-09T20:19:51Z | [
"python"
] |
Subset Sum : Why is DFS + pruning faster than 2 for loop? | 39,947,395 | <p>This issue is leetcode 416 Partition Equal Subset Sum.</p>
<pre><code>#2 for loop, which got TLE
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
allsum = sum(nums)
if allsum % 2 == 1:
... | 1 | 2016-10-09T19:02:16Z | 39,947,827 | <p>Just because you are using two loops it doesn't mean that your algorithm is in <em>O(n<sup>2</sup>)</em> or polynomial. The complexity of the algorithm depends on how many times each loop executes.
In this part of code:</p>
<pre><code> for each in nums:
for subset in subsets:
....
</code></pr... | 0 | 2016-10-09T19:45:48Z | [
"python",
"algorithm",
"loops",
"recursion",
"time-complexity"
] |
Django multiple one to many join | 39,947,477 | <p>I have one to many relationship in many places in my Django app.
For example I have user, home and key:</p>
<pre><code>class User(Model):
id_user = models.AutoField(primary_key=True)
class Home(Model):
id_home = models.AutoField(primary_key=True)
id_user = models.ForeignKey('user.User', models.DO_NOTHIN... | 0 | 2016-10-09T19:11:52Z | 39,947,854 | <p>What you are looking for is <code>Key.objects.filter(id_home__id_user=user)</code>. This creates 2 joins such that <code>Key x Home x User</code> and filters on <code>id_user</code>.</p>
<p>You can inspect generated sql with:</p>
<p><code>print(Key.objects.filter(id_home__id_user=user).query)
</code></p>
| 3 | 2016-10-09T19:50:03Z | [
"python",
"django",
"join"
] |
Dimension Error while feeding data in an AlexNet implemented using TensofFlow | 39,947,484 | <p>I am trying to feed my own data using TensorFlow in an AlexNet. I'm using (227 x 227) rgb images while training and the <code>BATCH_SIZE</code> is 50. The following is a part of the code. I'm always getting an error in the line <code>train_accuracy = accuracy.eval( ... )</code></p>
<pre><code>x = tf.placeholder(tf.... | 0 | 2016-10-09T19:12:46Z | 39,950,787 | <p>The problem is you set batch_size to 50, but trying to reshape x to the form as if you had batch size equal to one. To fix that problem, change 1 in the shape to -1, it would preserve total size of the input.</p>
| 0 | 2016-10-10T03:09:47Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow",
"conv-neural-network"
] |
How to display ndarray images inline during loop in IPython? | 39,947,551 | <p>The following code</p>
<pre><code>%matplotlib inline
for i in range(0, 5):
index = np.random.choice(len(dataset))
print('index:', index)
image = dataset[index, :, :]
print('image shape:', np.shape(image))
plt.imshow(image)
</code></pre>
<p>display five printouts and one single image at the end... | 0 | 2016-10-09T19:18:08Z | 39,953,765 | <p>Try:</p>
<pre><code>for i in range(0, 5):
...
plt.figure()
plt.imshow(image)
plt.show()
</code></pre>
<p>With out show the figures are only rendered and displayed after the cell finishes being executed (i.e. exits the <code>for</code> loop). With <code>plt.show()</code> you force rendering after every ... | 1 | 2016-10-10T08:02:21Z | [
"python",
"matplotlib",
"jupyter-notebook"
] |
Fastest way to compute vector in Python | 39,947,565 | <p>I have the following (using Python's pandas):</p>
<p>y: n by 1 dataframe</p>
<p>x: n by k dataframe</p>
<p>theta: k by 1 dataframe</p>
<p>Each of the elements in the above dataframes contains a real number.</p>
<p>I need a dataframe w, where w = y'x (' denotes transpose), but w only contains the observations fo... | 1 | 2016-10-09T19:19:15Z | 39,948,799 | <p>Use <code>.values</code> to access underlying numpy arrays</p>
<pre><code>Y = y.values
X = x.values
Th = theta.values
W = Y.T.dot(X)
mask = Y * X.dot(Th) < 1
w = pd.DataFrame(W[mask], y.index[mask])
</code></pre>
| 3 | 2016-10-09T21:36:32Z | [
"python",
"pandas"
] |
Depth-First Search runtime measuring | 39,947,594 | <p>I'm currently studying the Depth-First Search algorithm and although i've confirmed that it does run in O(N+M) it still doesn't show up very well when i measure runtime, since in a graph with 2000 to 16000 nodes, and a constant 50000 edges. The runtime remains almost constant (close to 0,5 seconds), as if the nodes ... | 0 | 2016-10-09T19:22:35Z | 39,947,670 | <p>The problem may be that Python has relatively high overhead (reading and analyzing the program). Check out this question: <a href="http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script">How can you profile a Python script?</a>.</p>
<p>More specifically, </p>
<pre><code>python -m cProfile my... | 1 | 2016-10-09T19:29:17Z | [
"python",
"algorithm",
"time-complexity"
] |
Explain the use of __setattr__ | 39,947,633 | <p>Can you please explain the use of the <code>__setattr__</code> method in the below code :</p>
<pre><code>class Human(object):
def __setattr__(self,name,value):
if name == 'gender':
if value in ('male', 'female'):
self.gender = value
else :
raise At... | -4 | 2016-10-09T19:25:53Z | 39,947,690 | <p>In your code, <code>__setattr__()</code> function is making a validation that while assigning the value of <code>self.gender</code>, it's value should be only between <code>male</code> and <code>female</code>. In case of any other value, it will raise <code>AttributeError</code> exception.</p>
<p><em>Note:</em> In ... | 0 | 2016-10-09T19:31:47Z | [
"python"
] |
Renaming model breakes migration history | 39,947,634 | <p>I have two models in two different apps:</p>
<pre><code># app1 models.py
class App1Model(models.Model):
pass
# app2 models.py
from app1.models import App1Model
class App2Model(App1Model):
pass
</code></pre>
<p>And I want to rename App1Model and then recreate App2Model to have explicit <code>OneToOneFiel... | 0 | 2016-10-09T19:25:59Z | 39,948,244 | <p>Just found solution:</p>
<p>Need to add last migration of <code>app2</code> where I deleted <code>App2Model</code> as dependency to migration of <code>app1</code> where I renamed <code>App1Model</code> so project state will be built in correct order. Actually error message itself has something related to it but I f... | 2 | 2016-10-09T20:31:47Z | [
"python",
"django",
"database-migration"
] |
PYTHON - How do I remove a function after it's been executed? | 39,947,645 | <p>I'm a bit new to Python programming and I'm trying to create a text-adventure game. I assume I'm using ver 2.7.3?</p>
<p>2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3]</p>
<p>I want to make an inventory system that has a max size. I'm currently using a list for my inventory.</p>
<p>I also want to make some f... | -1 | 2016-10-09T19:27:02Z | 39,948,449 | <p>Here's some code to get your game started, that includes a nice class-based solution to your problem, and cleans up your code so that you don't have a bunch of random logic everywhere that will be illegible to you next week. I'm sure there will be a gazillion things in here that you don't understand. Google them a... | 2 | 2016-10-09T20:57:20Z | [
"python",
"python-2.7",
"adventure"
] |
Webscraper in Python - How do I extract exact text I need? | 39,947,699 | <p>Good day</p>
<p>I am trying to write my first webscraper. I have managed to write the following:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
s = requests.Session()
r = s.get("http://www.sharenet.co.za/v3/quickshare.php?scode=BTI")
r = s.post("http://www.sharenet.co.za/v3/quickshare.php?scode=BT... | 0 | 2016-10-09T19:32:27Z | 39,947,719 | <p>Tags have a <code>get_text()</code> method. <code>find_all</code> returns a list of tags.</p>
<pre><code>for cell_tag in soup.find_all("td"):
print(cell_tag.get_text())
</code></pre>
| 4 | 2016-10-09T19:34:25Z | [
"python",
"beautifulsoup"
] |
Most efficient way to find the number of possible unique fixed length permutations? | 39,947,858 | <p>I've got this dictionary:</p>
<pre><code>num_dict = {
(2, 3): [(2, 2), (4, 4), (4, 5)],
(2, 2): [(2, 3), (4, 4), (4, 5)],
(4, 5): [(4, 4)],
(1, 0): [(1, 1), (2, 2), (2, 3), (4, 4), (4, 5)],
(4, 4): [(4, 5)],
(1, 1): [(1, 0), (2, 2), (2, 3), (4, 4), (4, 5)],
}
</code></pre>
<p>I need to ... | 0 | 2016-10-09T19:50:27Z | 39,947,997 | <p>If i get you right:</p>
<pre><code>from itertools import combinations
num_dict = {
(2, 3): [(2, 2), (4, 4), (4, 5)],
(2, 2): [(2, 3), (4, 4), (4, 5)],
(4, 5): [(4, 4)],
(1, 0): [(1, 1), (2, 2), (2, 3), (4, 4), (4, 5)],
(4, 4): [(4, 5)],
(1, 1): [(1, 0), (2, 2), (2, 3), (4, 4), (4, 5)]
}... | 1 | 2016-10-09T20:05:24Z | [
"python",
"algorithm"
] |
OpenCV: Save frame matrix to text file (Python) | 39,947,903 | <p>I have got a USB connected webcam and want to save captured frame to text file. Frame is numpy array and i need to get only red color values. So, here's my code: </p>
<pre><code>vc = cv2.VideoCapture(1)
if vc.isOpened():
rval, frame = vc.read()
frame = imutils.resize(frame, width=640, height=480)
print... | 1 | 2016-10-09T19:55:39Z | 39,947,957 | <p><code>savetxt</code> default format is <code>'%.18e'</code> which explains the format you're getting.</p>
<pre><code>numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ')[source]¶
</code></pre>
<p>Change the format specifier with <code>fmt</code> parameter to print... | 1 | 2016-10-09T20:00:51Z | [
"python",
"osx",
"opencv",
"numpy"
] |
TypeError remains: Str object is not callable | 39,947,940 | <p>I'm trying to make a python program that converts a 24-hour notation to a 12-hour notation, but the linux shell keeps saying: 'Str' object is not callable.
I'm looking for hours now but can't find the solution?
Do you people see it?</p>
<p>def time(time, hours, minutes):</p>
<pre><code> """ Changes time from 24... | -6 | 2016-10-09T19:59:03Z | 39,947,972 | <p>In the main loop you are using same name for the Function and the String i.e "time".
This is causing ambiguity. Give them a different name and it will work fine.
Use Like this.</p>
<pre><code>for timeString in sys.stdin:
hours, minutes = timeString.split(':')
y = time(timeString,hours, minutes)
... | 0 | 2016-10-09T20:02:08Z | [
"python",
"string",
"object",
"typeerror"
] |
Block tag inside url_for() in Jinja2 | 39,947,941 | <p>I'm using Jinja2 to render my frontend (and python is on the backend). Each page will have a different image on its top, like this:</p>
<pre><code><header>
<img src="static/img/pic1.png">
</header>
</code></pre>
<p>I used <em>url_for()</em> to get the correct path of my static folder:</p>
<p... | 0 | 2016-10-09T19:59:05Z | 39,948,209 | <p>What you need is a <strong>macro</strong> to define a kind of function in your template. See this topic in
<a href="http://jinja.pocoo.org/docs/dev/templates/" rel="nofollow">http://jinja.pocoo.org/docs/dev/templates/</a></p>
<pre><code>{% macro header_img(name) -%}
<img src="{{ url_for('static', filename=n... | 2 | 2016-10-09T20:27:45Z | [
"python",
"frontend",
"jinja2"
] |
"Int" object not iterable for a leap year program | 39,947,965 | <p>I am making a program to calculate if the given input is a leap year or not. I am using Python 2.7 on Windows 10 with Anaconda Shell.
It's a silly program and I dont understand why I am getting this error. There are a couple of solutions to this particular program online but I want to make my version work. Please he... | -3 | 2016-10-09T20:01:20Z | 39,948,149 | <p>I think you try to write</p>
<pre><code>for i in range(0,9):
for j in range(0,9):
</code></pre>
<p>But I think you try to check two last digits in <code>user_input</code> so you don't need <code>for</code>. </p>
<p>If <code>number</code> has <code>00</code> at the end then <code>number % 100 == 0</code> (here ... | 3 | 2016-10-09T20:20:26Z | [
"python",
"python-2.7",
"int",
"iterable"
] |
counting back generations of a number | 39,947,975 | <p>I am trying to reverse engineer a set of numbers given to me (f,m) I need to go through and find how many generations it takes starting from 1,1 using the algorithm below for each generation:</p>
<pre><code>x = 1
y = 1
new_generation = y+x
x OR y = new_generation
</code></pre>
<p>IE, I do not know if X, or Y is ch... | 3 | 2016-10-09T20:02:15Z | 39,948,580 | <p>Try a form of recursion:</p>
<p>(Python 2.7.6)</p>
<pre><code>def back():
global f,m,i
if f<m:
s=m//f
i+=s
m-=s*f
elif m<f:
s=f//m
i+=s
f-=s*m
else:
return False
return True
while True:
f=int(raw_input('f = '))
m=int(raw_inpu... | 0 | 2016-10-09T21:11:24Z | [
"python",
"loops",
"recursion",
"mathematical-optimization"
] |
counting back generations of a number | 39,947,975 | <p>I am trying to reverse engineer a set of numbers given to me (f,m) I need to go through and find how many generations it takes starting from 1,1 using the algorithm below for each generation:</p>
<pre><code>x = 1
y = 1
new_generation = y+x
x OR y = new_generation
</code></pre>
<p>IE, I do not know if X, or Y is ch... | 3 | 2016-10-09T20:02:15Z | 39,948,598 | <p>This is not a Python question, nor is it really a programming question. This is a problem designed to make you <em>think</em>. As such, if you just get the answer from somebody else, you will gain no knowledge or hindsight from the exercise.</p>
<p>Just add a <code>print(m, f)</code> in your <code>while</code> loop... | 2 | 2016-10-09T21:13:37Z | [
"python",
"loops",
"recursion",
"mathematical-optimization"
] |
counting back generations of a number | 39,947,975 | <p>I am trying to reverse engineer a set of numbers given to me (f,m) I need to go through and find how many generations it takes starting from 1,1 using the algorithm below for each generation:</p>
<pre><code>x = 1
y = 1
new_generation = y+x
x OR y = new_generation
</code></pre>
<p>IE, I do not know if X, or Y is ch... | 3 | 2016-10-09T20:02:15Z | 39,948,688 | <p>You are on the right track with the top-down approach you posted. You can speed it up by a huge factor if you use integer division instead of repeated subtraction.</p>
<pre><code>def answer(m, f):
m = int(m)
f = int(f)
counter = 0
while m != 0 and f != 0:
if f > m:
m, f = f, m... | 1 | 2016-10-09T21:23:30Z | [
"python",
"loops",
"recursion",
"mathematical-optimization"
] |
CPLEX finds optimal LP solution but returns no basis error | 39,948,095 | <p>I am solving a series of LP problems using the CPLEX Python API.
Since many of the problems are essentially the same, save a hand full of parameters. I want to use a warm start with the solution of the previous problem for most of them, by calling the function <code>cpx.start.set_start(col_status, row_status, col_pr... | 0 | 2016-10-09T20:14:09Z | 39,965,160 | <p>I'm not sure why you're getting the <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refcallablelibrary/macros/CPXERR_NO_BASIS.html" rel="nofollow">CPXERR_NO_BASIS</a>. See my comment.</p>
<p>You may have better luck if you provide the values for <code>row_primal</code>, <code... | 0 | 2016-10-10T19:10:15Z | [
"python",
"cplex"
] |
Detect the input number of signs in python and use it in a loop for encryption | 39,948,119 | <p>I am writing a very easy encryption program. I just shift the ASCII order number of a sign with a key. My code looks as following:</p>
<pre><code>#Type in sign or text and key
clear_text = input("Text? ")
key = int(input("Key? "))
# saves ASCII order number of the sign
ord_number = ord(clear_text)
#shift ASCII od... | 0 | 2016-10-09T20:16:57Z | 39,948,152 | <p>You want to use a string for your sentence, from which you can extract individual characters to do your encryption on. In fact, <code>clear_text</code> is already a string, but (presumably) since you only entered a single character, it is only 1 character long.</p>
<p>To get the length of a string, you can use <co... | 1 | 2016-10-09T20:20:46Z | [
"python"
] |
Detect the input number of signs in python and use it in a loop for encryption | 39,948,119 | <p>I am writing a very easy encryption program. I just shift the ASCII order number of a sign with a key. My code looks as following:</p>
<pre><code>#Type in sign or text and key
clear_text = input("Text? ")
key = int(input("Key? "))
# saves ASCII order number of the sign
ord_number = ord(clear_text)
#shift ASCII od... | 0 | 2016-10-09T20:16:57Z | 39,948,305 | <p>Iterate over the string with the <code>for</code> loop and use your encryption logic with in the loop. </p>
<p>Making minimal changes to your original code, below is the sample code to achieve it:</p>
<pre><code>clear_text = input("Text? ")
key = int(input("Key? "))
new_list = []
for c in clear_text:
# saves ... | 1 | 2016-10-09T20:38:42Z | [
"python"
] |
sklearn FeatureHasher parallelized | 39,948,138 | <p>sklearn's <code>Featurehasher</code> feature extractor has several advantages compared to its <code>DictVectorizer</code> counter-part, thanks to using the hashing trick.</p>
<p>One advantage which seems harder to tap is its ability to run in parallel.</p>
<p>My question is, how can I easily make <code>FeatureHash... | 1 | 2016-10-09T20:18:56Z | 39,951,415 | <p>You could implement a parallel version of <code>FeatureHasher.transform</code> using <code>joblib</code> (the library favoured by scikit-learn for parallel processing):</p>
<pre><code>from sklearn.externals.joblib import Parallel, delayed
import numpy as np
import scipy.sparse as sp
def transform_parallel(self, X,... | 1 | 2016-10-10T04:43:59Z | [
"python",
"machine-learning",
"scikit-learn",
"feature-extraction"
] |
How to use sendAudio in Telegram bot (Python) | 39,948,163 | <p>I have a Telegram bot, it replies with text and images, but I have a problem with sending an MP3 file in the reply. Can anyone please help?</p>
<p>This part of code defines the reply:</p>
<pre><code> def reply(msg=None, img=None, aud=None):
if msg:
resp = urllib2.urlopen(BASE_URL + 'send... | 1 | 2016-10-09T20:22:19Z | 39,950,861 | <p>I think the issue is with <code>output = StringIO.StringIO()</code></p>
<p>you should use
<code>io.BytesIO()</code></p>
<p>Here is a working code I am using: </p>
<pre><code>def sendTelegramAudio(self, file_url, text):
url = "https://api.telegram.org/botxxx:yyyy/sendAudio";
remote_file = requests.get(fil... | 0 | 2016-10-10T03:21:45Z | [
"python",
"json",
"mp3",
"telegram",
"telegram-bot"
] |
How to get values from my python file to my form using Flask? | 39,948,223 | <p>I'm trying to extract "address" from my python file "get interfaces.py" display it into my form using flask, but my code is not working, and may be I'm doing it wrong. I'm new in Flask </p>
<p>Here's my python file get_interfaces.py</p>
<pre><code>with open('/etc/network/interfaces', 'r+') as f:
for line in f:... | -3 | 2016-10-09T20:29:01Z | 39,948,311 | <p>In <code>get_interfaces.py</code> create function (ie. <code>get_info()</code>)<br>
with your code and with <code>return address</code> at the end.</p>
<p>In flask file run</p>
<pre><code>import get_interfaces
address = get_interfaces.get_info()
</code></pre>
<hr>
<p>BTW: if your code can return more than one ... | 0 | 2016-10-09T20:39:16Z | [
"python",
"html",
"django",
"python-2.7",
"flask"
] |
How to get values from my python file to my form using Flask? | 39,948,223 | <p>I'm trying to extract "address" from my python file "get interfaces.py" display it into my form using flask, but my code is not working, and may be I'm doing it wrong. I'm new in Flask </p>
<p>Here's my python file get_interfaces.py</p>
<pre><code>with open('/etc/network/interfaces', 'r+') as f:
for line in f:... | -3 | 2016-10-09T20:29:01Z | 39,948,454 | <p>First, I dont see the need for you to write a separate python file to manipulate address from a textfile. You can do the same as a method inside the flask code itself without any decorators.</p>
<pre><code>def getIPAddress():
...
...
return address
</code></pre>
<... | 0 | 2016-10-09T20:57:27Z | [
"python",
"html",
"django",
"python-2.7",
"flask"
] |
apache mod_wsgi error with django in virtualenv | 39,948,367 | <p>I can't seem to find a good answer to this. Who needs to own the virtualenv when running it as a WSGIDaemon? I assume on my OS (Ubuntu 16) www-data, but I want to be sure. Trying some new things to get this thing working based off of the answer from this post...</p>
<p><a href="http://stackoverflow.com/questions... | 0 | 2016-10-09T20:47:04Z | 39,949,355 | <p>You should not have need to change anything in the original <code>wsgi.py</code> generated by Django for you. It is generally sufficient to have:</p>
<pre><code>import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "servicesite.settings")
application = get_wsgi_... | 1 | 2016-10-09T22:56:49Z | [
"python",
"django",
"apache",
"ubuntu",
"mod-wsgi"
] |
python nested if statements not working | 39,948,410 | <p>I'm trying to make a game using pygame, and I've set up a couple of functions that I've tested and they work fine. However, in the code below, when I add a print statement to show if my code works, it prints on the first one but not the second. Any help?</p>
<pre><code>for square in row:
tile_x = row.index(squ... | -3 | 2016-10-09T20:51:46Z | 39,948,483 | <p>I would first have a dict vs all those if statements:</p>
<pre><code>di={'G':'Grass',
'T':'Tree',
'B':'Bush',
'R':'Rock',
'S':'Stone'}
</code></pre>
<p>Then you can do <code>display(di[square],tile_x,tile_y)</code></p>
| -1 | 2016-10-09T21:00:14Z | [
"python",
"if-statement"
] |
python nested if statements not working | 39,948,410 | <p>I'm trying to make a game using pygame, and I've set up a couple of functions that I've tested and they work fine. However, in the code below, when I add a print statement to show if my code works, it prints on the first one but not the second. Any help?</p>
<pre><code>for square in row:
tile_x = row.index(squ... | -3 | 2016-10-09T20:51:46Z | 39,948,628 | <p>I have just thought of something</p>
<p>I am using <code>row.index(square)</code>, which is finding the <strong>first</strong> 'g' square and using the tile_x of <strong>that</strong> first square. This means it thinks the square I'm looking for is not in the correct range to show on the map, so the first if statem... | 1 | 2016-10-09T21:18:17Z | [
"python",
"if-statement"
] |
Getting BlockingIOError (WinError 10035) when accepting a socket | 39,948,411 | <p>I've gotten a chance to work again with Python, but this time I decided to take Python 3.5 to my journey.</p>
<p>I had to port a working non-blocking socket server using <a href="http://www.tornadoweb.org/en/stable/" rel="nofollow">Tornado</a>, from Python 2.7 to 3.5. Used same source code, but this time it doesn't... | 0 | 2016-10-09T20:52:16Z | 39,950,119 | <p>This error is harmless and expected. The problem is that the gist you linked to doesn't know about windows-specific error codes (on line 24 it checks for EWOULDBLOCK and EAGAIN, but it should also use WSAEWOULDBLOCK).</p>
<p>Since that gist was written, Tornado has gained some new utilities to make this easier. If ... | 1 | 2016-10-10T01:12:53Z | [
"python",
"sockets",
"tornado",
"nio"
] |
PyLdaVis : TypeError: cannot sort an Index object in-place, use sort_values instead | 39,948,442 | <p>I am trying to visualize LDA topics in Python using PyLDAVis but I can't seem to get it right. My model has a vocab size of 150K words and about 16 Million tokens were taken to train it.</p>
<p>I am doing it outside of an iPython notebook and this is the code that I wrote to do it.</p>
<pre><code>model_filename = ... | 0 | 2016-10-09T20:56:26Z | 39,998,684 | <p>There was a problem with the LDAVis Code and upon reporting the issue, it has been resolved.</p>
| 0 | 2016-10-12T12:30:24Z | [
"python",
"visualization",
"lda",
"gensim",
"topic-modeling"
] |
How to connect a client to a server through an HTTP proxy in Python? | 39,948,448 | <p>I'm really new to coding using sockets.</p>
<p>I like the socket library, I get to understand a big part of what's happening in my program, so i you don't mind i would like to stick with it.</p>
<p>So as the title says, I have a socket based client and server and I would like to exchange content through an HTTP pr... | 0 | 2016-10-09T20:57:10Z | 39,951,627 | <pre><code>POST http://127.0.0.1:3001 HTTP/1.1\r\n
Host: 127.0.0.1:3001\r\n
Proxy-Connection: keep-alive\r\n
Content-Length: 5 \r\n\r\n
hello\r\n
</code></pre>
<p>The body of your HTTP response consists of 7 bytes not 5 as you've stated in your <code>Content-length</code>. The <code>\r\n</code> after the 5 byte still ... | 0 | 2016-10-10T05:12:16Z | [
"python",
"sockets",
"proxy",
"server",
"client"
] |
python how to use subprocess pipe with linux shell | 39,948,459 | <p>I have a python script search for logs, it continuously output the logs found and I want to use linux pipe to filter the desired output. example like that:</p>
<p>$python logsearch.py | grep timeout</p>
<p>The problem is the sort and wc are blocked until the logsearch.py finishes, while the logsearch.py will conti... | 0 | 2016-10-09T20:57:52Z | 39,948,807 | <p>And why use grep? Why don't do all the stuff in Python?</p>
<pre><code>from subprocess import Popen, PIPE
p = Popen(['ping', 'google.com'], shell=False, stdin=PIPE, stdout=PIPE)
for line in p.stdout:
if 'timeout' in line.split():
# Process the error
print("Timeout error!!")
else:
pr... | 0 | 2016-10-09T21:37:18Z | [
"python",
"linux",
"shell",
"pipe",
"subprocess"
] |
How can I convert Python boolean object to C int (or C++ boolean) (Python C API) | 39,948,485 | <p>I have a variable <code>PyObject</code> that I know is a Python bool. It either is <code>True</code> or <code>False</code> (eg. <code>Py_True</code> or <code>Py_False</code>). Now I would like to convert it to C++ somehow.</p>
<p>Doing this with strings isn't so hard, there is a helper function for that - <code>PyB... | 2 | 2016-10-09T21:00:18Z | 39,949,255 | <p>The answer is in Python headers but may not be obvious.</p>
<p>Python headers declare 2 somewhat static objects here, with couple of macros:</p>
<pre><code>/* Don't use these directly */
PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct;
/* Use these macros */
#define Py_False ((PyObject *) &_Py_... | 0 | 2016-10-09T22:40:08Z | [
"python",
"c"
] |
Find range of arguments that return the same result for a linear function | 39,948,543 | <p>Consider the <code>y = round(300000/x**2)</code>. I would like to find the ranges of <code>x</code> that return the same <code>y</code> for <code>100 < x < 40000</code>.</p>
<p>How would I do that with python/numpy?</p>
| 2 | 2016-10-09T21:07:20Z | 39,948,612 | <p>All values between <code>100</code> and <code>40000</code> return <code>0</code> for <code>y = round(300/x**2)</code>.</p>
<p>I assume you meant the following</p>
<pre><code>def y(x):
return round((300/x)**2)
</code></pre>
<p>In which case you can use <a href="https://docs.python.org/3.6/library/itertools.htm... | 2 | 2016-10-09T21:15:09Z | [
"python",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.