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 |
|---|---|---|---|---|---|---|---|---|---|
Easiest Way to Poll A Web Server | 39,235,715 | <p>I have a job that I want to run a specific time each day. The job should look at a web server to see if a file exists. If it exists, I want to download the file and do something with it. If it doesn't, then I want to wait a minute and then try again. </p>
<p>At the moment I just have a <code>try-except</code> stat... | 1 | 2016-08-30T19:33:31Z | 39,235,821 | <pre><code>import requests
import sleep
while True:
r = requests.get("http://www.domain.com/fileYouAreMonitoring.bin")
if r.status_code == 200:
# we got the file!
# exit or wait until next day, use break to escape while loop
else:
time.sleep(60)
</code></pre>
| 1 | 2016-08-30T19:39:24Z | [
"python"
] |
Sort a list of objects based on second value of list attribute | 39,235,718 | <p>I have a list of Car objects, each object being defined as follows:</p>
<pre><code>class Car:
def __init__(self, vin, name, year, price, weight, desc, owner):
self.uid = vin
self.name = name
self.year = year
self.price = price
self.weight = weight
self.desc = desc... | 1 | 2016-08-30T19:33:34Z | 39,235,748 | <p>You can instead use a lambda in order to access the exact value you want on which to sort:</p>
<pre><code>car_list.sort(key=lambda x: x.depreciation_values[1])
</code></pre>
| 10 | 2016-08-30T19:35:07Z | [
"python",
"sorting"
] |
Sort a list of objects based on second value of list attribute | 39,235,718 | <p>I have a list of Car objects, each object being defined as follows:</p>
<pre><code>class Car:
def __init__(self, vin, name, year, price, weight, desc, owner):
self.uid = vin
self.name = name
self.year = year
self.price = price
self.weight = weight
self.desc = desc... | 1 | 2016-08-30T19:33:34Z | 39,238,156 | <p>You could define a <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__" rel="nofollow"><code>__lt__()</code> (less than) method</a> and other comparison methods to return a boolean based on your desired sort attribute then you could use the built-in sorted() or <code>list.sort()</code>. <a href... | 0 | 2016-08-30T22:39:26Z | [
"python",
"sorting"
] |
Python - insert HTML content tp WordPress using xmlrpc api | 39,235,760 | <p>I'm trying to insert HTML content in my WordPress blog via XMLRPC but if i insert HTML - i got an error: </p>
<blockquote>
<p>raise TypeError, "cannot marshal %s objects" % type(value) TypeError:
cannot marshal objects</p>
</blockquote>
<p>If i use bleach (for clean tags) - i got text with tags on my page</p>... | 0 | 2016-08-30T19:35:38Z | 39,244,806 | <p>Use .replace after bleach and fixed issue. </p>
<p>My code </p>
<pre><code>...
post_content_insert = bleach.clean(post_content)
post_content_insert = post_content_insert.replace('&lt;','<')
post_content_insert = post_content_insert.replace('&gt;','>')
post = WordPressPost()
post.title = post_title... | 0 | 2016-08-31T08:44:33Z | [
"python",
"wordpress",
"beautifulsoup",
"xml-rpc"
] |
Python test using selenium cannot perform simple test | 39,235,795 | <p>I am trying to learn about Selenium but I am not able to get even a simple program to test. Selenium webdriver seems to not be cooperating with Firefox and I am very frustrated, so I come to Stack Overflow for help.</p>
<p>For background, I use Python, can install with pip, and know command line.
I am on windows 10... | 1 | 2016-08-30T19:37:51Z | 39,564,042 | <p>Firefox 48+ doesn't support <code>webdriver.Firefox()</code>. </p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
caps["binary"] = "path/to/your/firefox"
browser = webdriver.F... | 0 | 2016-09-19T00:59:08Z | [
"python",
"python-3.x",
"selenium-webdriver"
] |
Pyserial - Embedded Systems | 39,235,868 | <p>I am not expecting a code here, but rather to pick up on knowledge of the folks out there. </p>
<p>I have a python code - which uses pyserial for serial communication with an Micro Controller Unit(MCU). My MCU is 128byte RAM and has internal memory. I use ser.write command to write to the MCU and MCU responds with ... | 2 | 2016-08-30T19:42:17Z | 39,236,047 | <p>So, ultimately you're looking for advice on how to debug this sort of time dependent problem.
Somehow, state is getting created somewhere in your computer, your python process, or the microcontroller that affects things. (It's also theoretically possible that an external environmental factor is affecting things. A... | 3 | 2016-08-30T19:55:07Z | [
"python",
"multithreading",
"embedded",
"pyserial"
] |
ln (Natural Log) in Python | 39,235,906 | <p>In this assignment I have completed all the problems except this one. I have to create a python script to solve an equation (screenshot).</p>
<p><a href="http://i.stack.imgur.com/vFEwQ.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vFEwQ.gif" alt="formula"></a></p>
<p>Unfortunately, in my research all over... | -1 | 2016-08-30T19:44:52Z | 39,235,942 | <p><code>math.log</code> is the natural logarithm:</p>
<p><a href="https://docs.python.org/2/library/math.html" rel="nofollow">From the documentation:</a></p>
<blockquote>
<p>math.log(x[, base]) With one argument, return the natural logarithm of
x (to base e).</p>
</blockquote>
<p>Your equation is therefore:</p>... | 2 | 2016-08-30T19:47:51Z | [
"python",
"python-2.7",
"natural-logarithm"
] |
Why is my code returning "name 'Button' is not defined"? | 39,235,974 | <p>my code is giving me this error and I can't for the life of me figure out why it's telling me "NameError: name 'Button' is not defined." In Tkinter I thought Button was supposed to add a button?</p>
<pre><code>import Tkinter
gameConsole = Tkinter.Tk()
#code to add widgets will go below
#creates the "number 1" But... | -1 | 2016-08-30T19:49:51Z | 39,235,991 | <p>Use </p>
<pre><code>import Tkinter
b1 = Tkinter.Button(win,text="One")
</code></pre>
<p>or</p>
<pre><code>from Tkinter import Button
b1 = Button(win,text="One")
</code></pre>
| 0 | 2016-08-30T19:50:46Z | [
"python",
"tkinter",
"pycharm"
] |
Why is my code returning "name 'Button' is not defined"? | 39,235,974 | <p>my code is giving me this error and I can't for the life of me figure out why it's telling me "NameError: name 'Button' is not defined." In Tkinter I thought Button was supposed to add a button?</p>
<pre><code>import Tkinter
gameConsole = Tkinter.Tk()
#code to add widgets will go below
#creates the "number 1" But... | -1 | 2016-08-30T19:49:51Z | 39,235,994 | <p>A few options available to source the namespace:</p>
<ul>
<li><p><code>from Tkinter import Button</code> Import the specific class.</p></li>
<li><p><code>import Tkinter</code> -> <code>b1 = Tkinter.Button(win,text="One")</code> Specify the the namespace inline.</p></li>
<li><p><code>from Tkinter import *</code> Imp... | 1 | 2016-08-30T19:51:09Z | [
"python",
"tkinter",
"pycharm"
] |
How do I move project folders in Pycharm Project View? | 39,236,006 | <p>I'm using Pycharm to do a few django projects and I have them all open in the Project View to the left. I'd like to move the project I'm currently working on to the bottom of the list to avoid confusion. Pycharm does not let me do this by default. Are there some settings that need tweaking before I can do this? Take... | 4 | 2016-08-30T19:52:19Z | 39,278,771 | <p>AFAIK the display order in the file navigator panel (any of them - <code>Project</code>, <code>Project Files</code>, etc.) is not arbitrarily user-selectable.</p>
<p>To avoid the confusion it would probably be a better idea to actually split your django projects into <strong>separate</strong> PyCharm projects - wha... | 0 | 2016-09-01T18:44:20Z | [
"python",
"django",
"pycharm"
] |
how to install libhdf5-dev? (without yum, rpm nor apt-get) | 39,236,025 | <p>I want to use h5py which needs libhdf5-dev to be installed. I installed hdf5 from the source, and thought that any options with compiling that one would offer me the developer headers, but doesn't look like it.</p>
<p>Anyone know how I can do this? Is there some other source i need to download? (I cant find any tho... | 1 | 2016-08-30T19:53:33Z | 39,236,064 | <p>Can you use pip?</p>
<pre><code>pip install h5py
</code></pre>
| 1 | 2016-08-30T19:56:19Z | [
"python",
"linux",
"install",
"hdf5"
] |
how to install libhdf5-dev? (without yum, rpm nor apt-get) | 39,236,025 | <p>I want to use h5py which needs libhdf5-dev to be installed. I installed hdf5 from the source, and thought that any options with compiling that one would offer me the developer headers, but doesn't look like it.</p>
<p>Anyone know how I can do this? Is there some other source i need to download? (I cant find any tho... | 1 | 2016-08-30T19:53:33Z | 39,246,665 | <p>If you've built hdf5 library to a non-standard directory that is not included in your <code>PATH</code>, than you have basically two options. Either add this directory to you <code>PATH</code> and <code>LD_LIBRARY_PATH</code> or you can specify these paths to <code>pip</code>. Something like this works:</p>
<pre><c... | 0 | 2016-08-31T10:08:02Z | [
"python",
"linux",
"install",
"hdf5"
] |
Why do I get the PHONE_NUMBER_UNOCCUPIED error when calling auth.signIn in telegram? | 39,236,105 | <p>I've gotten to the point of sending the <code>auth.sendCode</code> method, with the following response:</p>
<pre><code>('sentCode: ', {u'req_msg_id': 6324698204597889024L, u'result': {u'type': {u'len
gth': 5}, u'phone_registered': False, u'flags': 6, u'timeout': 120, u'next_type'
: {}, u'phone_code_hash': '52eb4ab0... | 1 | 2016-08-30T19:58:50Z | 39,237,741 | <p>from <a href="https://core.telegram.org/api/auth" rel="nofollow">https://core.telegram.org/api/auth</a></p>
<blockquote>
<p>The auth.sendCode method will also return the phone_registered field,
which indicates whether or not the user with this phone number is
registered in the system. If phone_registered == b... | 1 | 2016-08-30T21:59:18Z | [
"python",
"api",
"telegram"
] |
Syntax error with a while loop in python | 39,236,125 | <p>This is my script, its a script that works like a calculator, however when i run it, it gives me invalid syntax for the while loop? i am new to python help me please.</p>
<pre><code>import functools
numbers=[]
def mean():
end_mean = functools.reduce(lambda x, y: x + y, numbers) / len(numbers)
print(end_mea... | -2 | 2016-08-30T20:00:01Z | 39,236,201 | <p>Just before the <code>while</code> loop, there is missing <code>]</code> with the usage of <code>numbers</code> list</p>
<p>That line should be:</p>
<pre><code>numbers[int(len(numbers))+1/2]
</code></pre>
| 0 | 2016-08-30T20:05:11Z | [
"python"
] |
Syntax error with a while loop in python | 39,236,125 | <p>This is my script, its a script that works like a calculator, however when i run it, it gives me invalid syntax for the while loop? i am new to python help me please.</p>
<pre><code>import functools
numbers=[]
def mean():
end_mean = functools.reduce(lambda x, y: x + y, numbers) / len(numbers)
print(end_mea... | -2 | 2016-08-30T20:00:01Z | 39,236,223 | <p>Before the while loop add the closing bracket to the line:</p>
<p><code>numbers[int(len(numbers))+1/2]</code></p>
<p>Usually it is a good idea to always check the lines above where the error occurred, if python is telling you that is found a <code>SyntaxError</code> but your syntax seems valid.</p>
| 2 | 2016-08-30T20:06:32Z | [
"python"
] |
Gtk.Widget.destroy() is necessary on Python? | 39,236,245 | <p>When reading the <a href="http://lazka.github.io/pgi-docs/index.html#Gtk-3.0/classes/Builder.html#Gtk.Builder" rel="nofollow">documentation</a> about GtkBuilder, I came across this passage:</p>
<blockquote>
<p>A <code>Gtk.Builder</code> holds a reference to all objects that it has
constructed and drops these re... | 0 | 2016-08-30T20:07:53Z | 39,241,013 | <p>Well, sort of. You generally don't have to call <code>destroy()</code> on the window manually because it happens automatically when the user clicks the window's close button.</p>
| 3 | 2016-08-31T04:54:45Z | [
"python",
"python-3.x",
"gtk",
"gtk3"
] |
How to concat linear models in TensorFlow | 39,236,284 | <p>I'm trying to build a model in tensor flow with models like f_i(x) = m_ix + b_i such that: </p>
<pre><code>f(x) = [f_1(x), f_2(x)]^T [x, x] + b
</code></pre>
<p>this is just an exercise. My difficulty is in understanding how to concatenate two tensors:</p>
<pre><code># Model 1
f1 = tf.add(tf.mul(X, W), b)
# Model... | 0 | 2016-08-30T20:10:22Z | 39,240,620 | <p>One way to achieve a similar result without the headache of <code>tf.concat</code> is</p>
<pre><code>pred = tf.add(tf.add(f1, f2), b3)
</code></pre>
| 1 | 2016-08-31T04:13:56Z | [
"python",
"tensorflow"
] |
How to resolve this IndexError out of range? | 39,236,580 | <p>Why am I getting this list index out of range error? And how can I fix it?</p>
<p>I tried entering into after the <em>else</em> in the logic, but the result was the same. </p>
<pre><code>if int_list_repost is '':
int_list_repost = [0]
</code></pre>
<p>but the result was the same</p>
<blockquo... | 0 | 2016-08-30T20:30:02Z | 39,237,090 | <p>The message is pretty straightforward <code>'pinned_retweets': int_list_repost[0] Index Out Of Range</code>... And if you check your script output, it shows an empty array: <code>raw int only list []</code>, so you need to check the array length before the last step, like this:</p>
<pre><code>if len(int_list_repost... | 0 | 2016-08-30T21:06:12Z | [
"python",
"indexing"
] |
How to resolve this IndexError out of range? | 39,236,580 | <p>Why am I getting this list index out of range error? And how can I fix it?</p>
<p>I tried entering into after the <em>else</em> in the logic, but the result was the same. </p>
<pre><code>if int_list_repost is '':
int_list_repost = [0]
</code></pre>
<p>but the result was the same</p>
<blockquo... | 0 | 2016-08-30T20:30:02Z | 39,237,275 | <p>You've initialized an array, which is an object. When you ask if the variable is null, that will always be false. It's not null, it's an object. </p>
<p>If you want to test to see if your array is empty use this code:</p>
<pre><code>is len(int_list_repost) == 0:
print("int_list_repost is empty")
</code></pr... | 1 | 2016-08-30T21:21:45Z | [
"python",
"indexing"
] |
How to deploy Flask app with Supervisor/Nginx/Gunicorn on Ubuntu server | 39,236,595 | <p>I am trying to deploy a Flask app on an Ubuntu server. I referenced <a href="http://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html?highlight=flask" rel="nofollow">this</a>, <a href="https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/" rel="nofollow">this</a> and <a href="ht... | 2 | 2016-08-30T20:30:51Z | 39,237,012 | <p>You have errors in <code>nginx</code> config:</p>
<p>Instead of:</p>
<pre><code>upstream flask_siti {
server 127.0.0.1:8008 fail_timeout=0;
server {
...
</code></pre>
<p>try:</p>
<pre><code>upstream flask_siti {
server 127.0.0.1:8080 fail_timeout=0;
}
server {
...
</code></pre>
<p>You mus... | 2 | 2016-08-30T21:00:12Z | [
"python",
"nginx",
"flask",
"uwsgi",
"gunicorn"
] |
How to deploy Flask app with Supervisor/Nginx/Gunicorn on Ubuntu server | 39,236,595 | <p>I am trying to deploy a Flask app on an Ubuntu server. I referenced <a href="http://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html?highlight=flask" rel="nofollow">this</a>, <a href="https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/" rel="nofollow">this</a> and <a href="ht... | 2 | 2016-08-30T20:30:51Z | 39,251,473 | <p>Was able to get it working with the following changes:</p>
<p>/etc/supervisor/conf.d/siti.conf (Supervisor config):</p>
<pre><code>[program:webapp_siti]
command=/webapps/patch/venv/bin/gunicorn -b :8118 views:app # didn't use uwsgi.ini after all
directory=/webapps/patch/src
user=nobody
autostart=true
autorestart=... | 2 | 2016-08-31T13:47:40Z | [
"python",
"nginx",
"flask",
"uwsgi",
"gunicorn"
] |
(Python type hints) How to specify type being currently defined as the returned type from a method? | 39,236,606 | <p>I would like to specify (as a type hint) the currently defined type as the return type from a method.</p>
<p>Here's an example:</p>
<pre class="lang-py prettyprint-override"><code>class Action(Enum):
ignore = 0
replace = 1
delete = 2
@classmethod
# I would like something like
# def idToObj... | 0 | 2016-08-30T20:31:30Z | 39,236,677 | <p>This case is mentioned in official <a href="https://www.python.org/dev/peps/pep-0484/#id27" rel="nofollow">type hints PEP</a>:</p>
<blockquote>
<p>When a type hint contains names that have not been defined yet, that
definition may be expressed as a string literal, to be resolved later.</p>
</blockquote>
<pre><... | 2 | 2016-08-30T20:36:58Z | [
"python",
"type-hinting"
] |
User input and retrieving it in Python | 39,236,645 | <p>I am currently trying using two modules in python, I am trying to have one module take user input and store it. But I cannot figure how to retrieve the data from the input module. I have imported everything but this only runs my input again from the def in the input module. Below is an example of my input module. Ho... | 0 | 2016-08-30T20:34:59Z | 39,236,787 | <p>I assume you mean you use two files, and you need to use the information from the test function on the other file. Then, assuming you test file name is <code>testfile.py</code>, I would go with:</p>
<pre><code>import testfile
num = testfile.test() # This will store the number recieved in the test() function in the ... | 3 | 2016-08-30T20:44:39Z | [
"python",
"python-2.7",
"python-3.x"
] |
Count the number of occurrences of two characters in python column | 39,236,816 | <p>I have a dataframe (df) with variable Area representing the Area code. I need to find the number of occurences for Z followed by X
In the following example Z->X is repeated twice which means count is 2</p>
<pre><code>Area
Z
A
B
Z
X
A
B
Z
X
</code></pre>
<p>I have tried the following to find True/False</p>
<pre><c... | 0 | 2016-08-30T20:46:27Z | 39,236,882 | <p>You need the <code>shift()</code> function, specify the <code>period</code> parameter to be <code>-1</code> to shift the series one step forward, and this guarantees that <code>Z</code> is followed by <code>X</code>:</p>
<pre><code>((df.Area == "Z") & (df.Area.shift(-1) == "X")).sum()
# 2
</code></pre>
<p>A cl... | 2 | 2016-08-30T20:50:42Z | [
"python",
"string",
"find-occurrences"
] |
Python IDLE 3.5 invalid literal for int() with base 10 | 39,236,874 | <p>I'm new to python, and I can't figure out how to make this work, it just wont work. (other answers won't help me)</p>
<p>Here's my code:</p>
<pre><code># My First Python Game Thing
# Aka Endless Walking Simulator
game_temp1 = True
def choiceroom_thing1():
while game_temp1:
directionchoice = input('L(le... | 0 | 2016-08-30T20:50:12Z | 39,237,909 | <p>you do not need to convert <code>directionchoice</code> to an <code>int</code>.<br>
<code>direction</code> should be equal to <code>directionchoice</code>.<br>
Then test if <code>direction</code> is not in the wanted choices: </p>
<pre><code>if direction not in ['L', 'R','B', 'F']:
</code></pre>
| 0 | 2016-08-30T22:15:46Z | [
"python",
"traceback"
] |
ImportError: No module named caffe - I don't know how to install caffe for Anaconda on Windows | 39,236,924 | <p>i have been attempting to follow <a href="http://thirdeyesqueegee.com/deepdream/2015/07/19/running-googles-deep-dream-on-windows-with-or-without-cuda-the-easy-way/" rel="nofollow">this tutorial</a> to install Google DeepDream, but unfortunately i have run into many problems. My first being that i needed to create a ... | 0 | 2016-08-30T20:53:40Z | 39,757,381 | <p>Based on your question I'm noticing two likely issues with your installation. The first is that </p>
<p>Caffe is not really intended to be installed. The normal usecase is to compile it locally after tweaking it's settings to best match your system. I believe the tutorial you are using comes with a precompiled vers... | 0 | 2016-09-28T20:48:31Z | [
"python",
"anaconda",
"caffe"
] |
Receiving an SMS on an Arduino Yun with the Twilio service | 39,236,967 | <p>I'm trying to create a project with an Arduino Yun that will allow it to receive text messages and process commands based on the text. I've followed the tutorial for sending SMS messages with the Yun (<a href="https://www.twilio.com/blog/2015/02/send-sms-and-mms-from-your-arduino-yun.html" rel="nofollow">https://ww... | 1 | 2016-08-30T20:56:58Z | 39,344,287 | <p>In general , you can always receive an SMS on a SMS capable Twilio number you buy from the console . What should be done on the receipt of that SMS is usually required to be programmed.</p>
<p>In your case , twilio_phone_number used to send SMS out could receive the replies.</p>
<p>For programming the replies ,
(... | 2 | 2016-09-06T08:35:01Z | [
"python",
"arduino",
"twilio",
"arduino-yun"
] |
Retrieve value of last key in dictionary | 39,237,041 | <p>I'm trying to extract financial figures from an API that returns a JSON object. The API does not explicitly state that the dictionaries returned are OrderedDicts however the output is always sorted thus I'm going to make the assumption that it is. </p>
<p>I need to retrieve the value of the last key in the dictiona... | 1 | 2016-08-30T21:02:13Z | 39,237,186 | <p>After reconsidering the problem I realize that because the date is in a format that they are correctly comparable as strings, you can just do <code>k,v = max(data.items())</code> however if you (or someone else looking at this thread) uses a date format that doesn't work like that my original answer is below.</p>
<... | 4 | 2016-08-30T21:13:53Z | [
"python",
"sorting",
"dictionary",
"key",
"key-value"
] |
Iterating over large line separated file without freezing | 39,237,054 | <p>I'm trying to implement a Strongly Connected Graph search algorithm and am trying to load a large file with edges of the graph into memory to do it.</p>
<p>The file comes as:</p>
<blockquote>
<p> 1 2 // i.e. a directed edge from 1 to 2 </p>
<p> 1 3 </p>
<p> 2 3 </p>
<p> 3 1 </p>
<p>...</p>
</... | 0 | 2016-08-30T21:02:48Z | 39,237,192 | <p>Not much to be done, but since it's a little too complex, speed suffers.
You can improve the program speed like this:</p>
<pre><code>def begin():
graph = {}
for line in open('/home/edd91/Documents/SCC.txt'):
# consider only first 2 fields: avoids the loop and the append: that's the best saver
... | 0 | 2016-08-30T21:14:18Z | [
"python",
"graph"
] |
Iterating over large line separated file without freezing | 39,237,054 | <p>I'm trying to implement a Strongly Connected Graph search algorithm and am trying to load a large file with edges of the graph into memory to do it.</p>
<p>The file comes as:</p>
<blockquote>
<p> 1 2 // i.e. a directed edge from 1 to 2 </p>
<p> 1 3 </p>
<p> 2 3 </p>
<p> 3 1 </p>
<p>...</p>
</... | 0 | 2016-08-30T21:02:48Z | 39,237,325 | <p>You can save some time by getting <code>tempArray</code> at once for each line and unpacking, if, of course, each line consists of a pair of numbers, and also use a <code>defaultdict</code>:</p>
<pre><code>import collections
graph = collections.defaultdict(lambda: {'g': [], 's': False, 't': None, 'u': None })
for ... | 1 | 2016-08-30T21:25:28Z | [
"python",
"graph"
] |
BeautifulSoup adding unwanted linebreaks to strings Python3.5 | 39,237,093 | <p>I've been having some trouble with what appear to be hidden newline characters in strings gotten with the BeautifulSoup .find function. The code I have scans an html document and pulls out name, title, company, and country as strings. I type checked and saw they were strings and when I print them and check their l... | 1 | 2016-08-30T21:06:19Z | 39,237,470 | <p>Most likely you need to <em>strip</em> the whitespace, there is nothing in your code that adds it so it has to be there:</p>
<pre><code>outputWriter.writerow([name.strip(),title.strip(),company.strip(),country.strip()])
</code></pre>
<p>You can verify what us there by seeing the <em>repr</em> outpout:</p>
<pre><c... | 0 | 2016-08-30T21:37:17Z | [
"python",
"string",
"csv",
"beautifulsoup",
"python-3.5"
] |
Python Structuring Nested Try Except Statements | 39,237,162 | <p>I have a list of ints called companyNumbers. These are being checked against an online API to test they are valid. </p>
<p>Some company numbers have an incorrect first digit, so I would like to check the number, then if an HTTP error is received (Indicating an invalid number) to recheck the number minus its first d... | 1 | 2016-08-30T21:11:53Z | 39,237,649 | <p><code>try</code> runs the code under its nest until an error occurs. So you should put the output into that layer as well. </p>
<pre><code>for companyNumber in companyNumbers:
try:
r = s.profile(companyNumber).json()
correctNumbers.append(r)
except HTTPError:
try:
r = s... | 1 | 2016-08-30T21:51:48Z | [
"python",
"nested",
"escaping",
"try-catch"
] |
Exporting results of median blur into a class and exporting to TIFF | 39,237,173 | <p>I'm working on a program which applies a median blur onto a multiframe tiff file. My goal is to filter through every frame in the tiff sequence and then save the result as the same sequence, just filtered. However, anytime I run it, it only saves the last frame, as I don't know how to properly save the data into a s... | 0 | 2016-08-30T21:13:05Z | 39,237,587 | <pre><code>depth = len(ImageSequence(im))
target_array = np.zeros((width, height, depth))
for index, frame in enumerate(ImageSequence(im)):
imarray = np.array(frame)
Blur = cv2.medianBlur(imarray,5)
target_array[:, :, index] = Blur
</code></pre>
<p>That gives you a nice array of matrices, I would think you... | 1 | 2016-08-30T21:46:05Z | [
"python",
"image-processing",
"python-imaging-library",
"tiff"
] |
Is result of sys.exc_info() "stable" when its origin thread finishes? | 39,237,180 | <p>Supposing I catch an exception inside a thread and store exc_info tuple somewhere. Then thread finishes. Is my exc_info content still accessible and correct, so I can interpret it later in other thread?</p>
| 0 | 2016-08-30T21:13:19Z | 39,237,267 | <p>The tuple you receive from <code>sys.exc_info()</code> can safely be passed to and used from other threads, even after the death of the thread the tuple came from. The references from the tuple keep things like stack state alive even when the thread is dead.</p>
<p>(You won't be able to access the tuple as <code>sy... | 1 | 2016-08-30T21:20:53Z | [
"python"
] |
Scrapy - TypeError: Cannot convert unicode body - HtmlResponse has no encoding | 39,237,259 | <p>When I try to construct a <code>HtmlResponse</code> object in Scrapy like this:</p>
<pre><code>scrapy.http.HtmlResponse(url=self.base_url + dealer_url[0], body=dealer_html)
</code></pre>
<p>I got this error:</p>
<pre><code>Traceback (most recent call last):
File "d:\kerja\hit\python~1\oliver~1\machin~2\lib\sit... | 0 | 2016-08-30T21:20:22Z | 39,245,851 | <p><a href="http://doc.scrapy.org/en/latest/topics/request-response.html#htmlresponse-objects" rel="nofollow">HtmlResponse</a> is trying to detect encoding:</p>
<blockquote>
<p>The HtmlResponse class is a subclass of TextResponse which adds
encoding auto-discovering support by looking into the HTML meta
http-equ... | 1 | 2016-08-31T09:32:38Z | [
"python",
"python-2.7",
"encoding",
"scrapy",
"scrapy-spider"
] |
Django use Integer Field as ForeignKey field | 39,237,280 | <p>To support old (legacy) db we have to create a table that using <strong>integer field</strong> as a <strong>foreignkey</strong> to <strong>User</strong> table: This is how our model look like:</p>
<pre><code>class UserHistory():
user_id = models.IntegerField(null=True, blank=True)
# ..... (other fields) ...... | 1 | 2016-08-30T21:22:12Z | 39,237,433 | <p>You can use a <code>ForeignKey</code> field with <code>db_constraint=False</code>. See the <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.db_constraint" rel="nofollow">docs</a> for warnings, but legacy invalid data is one of the cases where this is reasonable.</p>
| 1 | 2016-08-30T21:34:09Z | [
"python",
"django",
"django-models",
"orm",
"django-admin"
] |
Django use Integer Field as ForeignKey field | 39,237,280 | <p>To support old (legacy) db we have to create a table that using <strong>integer field</strong> as a <strong>foreignkey</strong> to <strong>User</strong> table: This is how our model look like:</p>
<pre><code>class UserHistory():
user_id = models.IntegerField(null=True, blank=True)
# ..... (other fields) ...... | 1 | 2016-08-30T21:22:12Z | 39,250,159 | <p>Add a second column to your database and null out the fields that do not have a corresponding object in the other table using SQL. Then define your django model on this new field.</p>
| 0 | 2016-08-31T12:50:09Z | [
"python",
"django",
"django-models",
"orm",
"django-admin"
] |
Downloading PDFs from links scraped with Beautiful Soup | 39,237,311 | <p>I'm trying to write a script which will iterate through a list of landing page urls from a csv file, append all PDF links on the landing page to a list, and then iterate through the list downloading the PDFs to a specified folder. </p>
<p>I'm a bit stuck on the last step- I can get all the PDF urls, but can only do... | 0 | 2016-08-30T21:24:13Z | 39,237,366 | <p>The simplest thing is to just add a number to each filename using enumerate:</p>
<pre><code>for ind, url in enumerate(link_list, 1):
response = requests.get(url)
with open('C:/Users/Desktop/CompaniesHouse/report_{}.pdf'.format(ind), 'wb') as f:
f.write(response.content)
</code></pre>
<p>But presu... | 0 | 2016-08-30T21:28:57Z | [
"python",
"pdf",
"beautifulsoup"
] |
Call function the moment before script crashes? | 39,237,314 | <p>I am solving the following problem:</p>
<p>I have a script which should be running as a service 24/7. Because it is quite important, I would like it to send me an email in case it crashes. I found <a href="https://docs.python.org/3/library/atexit.html" rel="nofollow">atexit</a> module, but the docs specifically say... | 0 | 2016-08-30T21:24:17Z | 39,237,422 | <p>I mean to do what you ask in the first part just wrap the main part of the script with a try/except.</p>
<p>myscript.py:</p>
<pre><code>def main():
long_running_process()
if __name__ == '__main__':
try:
main()
except:
send_email()
</code></pre>
| 0 | 2016-08-30T21:33:22Z | [
"python",
"crash",
"crash-reports"
] |
How do I remove consecutive duplicates from a list? | 39,237,350 | <p>How do I remove consecutive duplicates from a list like this in python?</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>
<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>
<p>I want the result to be like this:</p>
... | 1 | 2016-08-30T21:27:54Z | 39,237,452 | <p><a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby()</a> is your solution.</p>
<pre><code>newlst = [k for k, g in itertools.groupby(lst)]
</code></pre>
<hr>
<p>If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4],... | 6 | 2016-08-30T21:35:50Z | [
"python"
] |
How do I remove consecutive duplicates from a list? | 39,237,350 | <p>How do I remove consecutive duplicates from a list like this in python?</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>
<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>
<p>I want the result to be like this:</p>
... | 1 | 2016-08-30T21:27:54Z | 39,237,468 | <p>You'd probably want something like this.</p>
<pre><code>lst = [1, 1, 2, 2, 2, 2, 3, 3, 4, 1, 2]
prev_value = None
for number in lst[:]: # the : means we're slicing it, making a copy in other words
if number == prev_value:
lst.remove(number)
else:
prev_value = number
</code></pre>
<p>So, we'... | 0 | 2016-08-30T21:37:09Z | [
"python"
] |
How do I remove consecutive duplicates from a list? | 39,237,350 | <p>How do I remove consecutive duplicates from a list like this in python?</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>
<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>
<p>I want the result to be like this:</p>
... | 1 | 2016-08-30T21:27:54Z | 39,237,542 | <pre><code>newlist=[]
prev=lst[0]
newlist.append(prev)
for each in lst[:1]: #to skip 1st lst[0]
if(each!=prev):
newlist.append(each)
prev=each
</code></pre>
| 0 | 2016-08-30T21:42:41Z | [
"python"
] |
How do I remove consecutive duplicates from a list? | 39,237,350 | <p>How do I remove consecutive duplicates from a list like this in python?</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>
<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>
<p>I want the result to be like this:</p>
... | 1 | 2016-08-30T21:27:54Z | 39,237,571 | <p>If you want to use the <code>itertools</code> method @MaxU suggested, a possible code implementation is:</p>
<pre><code>import itertools as it
lst=[1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
unique_lst = [i[0] for i in it.groupby(lst)]
print(unique_lst)
</code></pre>
| 1 | 2016-08-30T21:44:45Z | [
"python"
] |
How do I remove consecutive duplicates from a list? | 39,237,350 | <p>How do I remove consecutive duplicates from a list like this in python?</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>
<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>
<p>I want the result to be like this:</p>
... | 1 | 2016-08-30T21:27:54Z | 39,237,793 | <pre><code>st = ['']
[st.append(a) for a in [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] if a != st[-1]]
print(st[1:])
</code></pre>
| 0 | 2016-08-30T22:04:13Z | [
"python"
] |
How do I remove consecutive duplicates from a list? | 39,237,350 | <p>How do I remove consecutive duplicates from a list like this in python?</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
</code></pre>
<p>Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.</p>
<p>I want the result to be like this:</p>
... | 1 | 2016-08-30T21:27:54Z | 39,241,439 | <p>Check if the next element always is not equal to item. If so append.</p>
<pre><code>lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
new_item = lst[0]
new_list = [lst[0]]
for l in lst:
if new_item != l:
new_list.append(l)
new_item = l
print new_list
print lst
</code></pre>
| 0 | 2016-08-31T05:30:18Z | [
"python"
] |
Unable to PLOT multiple data from EXCEL using MATPLOTLIB | 39,237,399 | <p>I've an Excel file with 1000 rows & 300 columns.
I want to plot (column 1) vs (column 2 to 288); my 1st Column is my X Axis, and the rest of the columns are on the Y axis.
My code is below; I get no display.
There's no error message as such.</p>
<pre><code>from openpyxl import load_workbook
import numpy as np
... | 1 | 2016-08-30T21:31:58Z | 39,237,861 | <p>Try something like the following nested loop:</p>
<pre>
for j in range(1, 7):
for i in range(0, sheet_1.max_row):
x[i] = sheet_1.cell(row=i + 1, column=j).value
y[i] = sheet_1.cell(row=i + 1, column=j).value
#z[i] = sheet_1.cell(row=i + 1, column=3).value
... | 0 | 2016-08-30T22:10:56Z | [
"python",
"excel",
"numpy",
"matplotlib",
"xlrd"
] |
Unable to PLOT multiple data from EXCEL using MATPLOTLIB | 39,237,399 | <p>I've an Excel file with 1000 rows & 300 columns.
I want to plot (column 1) vs (column 2 to 288); my 1st Column is my X Axis, and the rest of the columns are on the Y axis.
My code is below; I get no display.
There's no error message as such.</p>
<pre><code>from openpyxl import load_workbook
import numpy as np
... | 1 | 2016-08-30T21:31:58Z | 39,248,631 | <p>I would consider using <code>pandas</code>:</p>
<pre><code>import pandas
df = pandas.read_excel('CombinedData1.xlsx', sheetname='CombinedData', header=None)
df.plot(x=0)
</code></pre>
<p>or </p>
<pre><code>plt.plot(df[0], df[1])
</code></pre>
| 0 | 2016-08-31T11:38:47Z | [
"python",
"excel",
"numpy",
"matplotlib",
"xlrd"
] |
Python 3 sys.exec_prefix wrong | 39,237,407 | <p>I'm at my wits end here with python3 on Solaris reporting the exec_prefix as <code>/usr/lib</code> instead of <code>/usr</code></p>
<p>This is leading to all sorts of bad behavior when using setup_tools and virtualenv, as they are looking for libraries in <code>/usr/lib/lib/python3.4</code> which is obviously wrong... | 3 | 2016-08-30T21:32:31Z | 39,238,354 | <p>This looks like Solaris bug:</p>
<p>21622699 Python 3.4 mangles sys.exec_prefix, breaks virtualenv</p>
<p>which was fixed in Solaris 12 but has not yet been back-ported to 11.3; I will see about making that happen.</p>
| 2 | 2016-08-30T23:02:29Z | [
"python",
"python-3.x",
"solaris"
] |
How to Thread a Tweepy Stream | 39,237,420 | <p>I am making a program that pulls live tweets using Tweepy, and runs it through a function. I am using a Tweepy Stream to accomplish the task of getting the tweets. However, what I wish is that while the function is running, Tweepy can still pull these live tweets. I believe I need to thread the Tweepy event listener... | 1 | 2016-08-30T21:33:20Z | 39,244,078 | <p>This is an example you can adapt easily...
The code will create a thread that updates a counter in the background while a loop will continuously print the value of the counter. The 'stop' variable takes care of quitting the thread when the main process is killed or exit...</p>
<pre><code>import threading
import ti... | 1 | 2016-08-31T08:09:24Z | [
"python",
"multithreading",
"python-3.x",
"twitter",
"tweepy"
] |
Code runs slow but multiple python IDEs makes it faster | 39,237,453 | <p>I have a simple webcrawler which crawls ~4 (specific) sites per second. If I run the script in tow different python IDE's I can double the speed because both programs runs the code with ~4 crawls per second.
Why does my code runs slower then It could be? Or is it faster because I use a silly way to make my script u... | 0 | 2016-08-30T21:35:54Z | 39,238,737 | <p>This sounds like a great task for a Pool of worker threads.</p>
<p>See: <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">Python: The Multiprocessing Module</a></p>
| 0 | 2016-08-30T23:51:30Z | [
"python",
"multithreading",
"performance",
"multiprocessing"
] |
Code runs slow but multiple python IDEs makes it faster | 39,237,453 | <p>I have a simple webcrawler which crawls ~4 (specific) sites per second. If I run the script in tow different python IDE's I can double the speed because both programs runs the code with ~4 crawls per second.
Why does my code runs slower then It could be? Or is it faster because I use a silly way to make my script u... | 0 | 2016-08-30T21:35:54Z | 39,241,403 | <p>It's all about threading, as explained in the comments.</p>
<p>Now there is a solution for your program :</p>
<pre><code>import requests
import threading
class Crawler:
def __init__(self, url):
self.url = url
self.session = requests.Session()
def crawl(self):
page = self.session.g... | 0 | 2016-08-31T05:27:18Z | [
"python",
"multithreading",
"performance",
"multiprocessing"
] |
Pandas getting all rows listed in one dataframe but not the other UNORDERD | 39,237,642 | <p>I cannot find an easy way to get all the rows of a data frame that are found in one dataframe but not a second dataframe if the data is unordered.</p>
<p>These two answers talk are solutions for ordered data:</p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/25946391/get-rows-that-are-present-in-on... | 2 | 2016-08-30T21:51:27Z | 39,237,680 | <p>This uses boolean indexing to locate all of the rows in <code>df1</code> where the values in <code>col_a</code> are NOT (<code>~</code>) in <code>col_a</code> of <code>df2</code>. It uses <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>isin()</code></a> to l... | 3 | 2016-08-30T21:55:10Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
Pandas getting all rows listed in one dataframe but not the other UNORDERD | 39,237,642 | <p>I cannot find an easy way to get all the rows of a data frame that are found in one dataframe but not a second dataframe if the data is unordered.</p>
<p>These two answers talk are solutions for ordered data:</p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/25946391/get-rows-that-are-present-in-on... | 2 | 2016-08-30T21:51:27Z | 39,237,804 | <p>here is a pandas equivalent for SQL (Oracle's) minus operation:</p>
<pre><code>select col1, col2 from tab1
minus
select col1, col2 from tab2
</code></pre>
<p>in Pandas:</p>
<pre><code>In [59]: df1[~df1.isin(pd.DataFrame(df2.values, columns=df1.columns).to_dict('l')).all(1)]
Out[59]:
col_a col_b
0 1325 foo
... | 3 | 2016-08-30T22:05:33Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
Pandas getting all rows listed in one dataframe but not the other UNORDERD | 39,237,642 | <p>I cannot find an easy way to get all the rows of a data frame that are found in one dataframe but not a second dataframe if the data is unordered.</p>
<p>These two answers talk are solutions for ordered data:</p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/25946391/get-rows-that-are-present-in-on... | 2 | 2016-08-30T21:51:27Z | 39,237,805 | <p>Yes, you can use merge with the <code>indicator</code> parameter:</p>
<p>I renamed the columns to avoid duplicated columns You can also pass <code>left_on</code> and <code>right_on</code></p>
<pre><code>merged = DF1.merge(DF2.rename(columns={'col_1': 'col_a', 'col_2': 'col_b'}), how='left', indicator=True)
merged
... | 3 | 2016-08-30T22:05:36Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
Generate dummies if string value matches any row in particular column using pandas.dataframe.str.contains() | 39,237,690 | <p>If string in "Language_cat" list matches any rows in "Languages" column in df_dat dataframe then generate dummies for that value corresponding to same row:</p>
<pre><code>Language_cat = ['english','french','deutsch','italian','russian','spanish']
for j in Language_cat:
df_dat[j+'lang_cat'] = df_dat['Languages'].ap... | -3 | 2016-08-30T21:56:00Z | 39,252,828 | <pre><code>Language_cat = ['english','french','deutsch','italian','russian','spanish']
for j in Language_cat:
df_dat[j+'lang_cat'] = df_dat['Languages'].str.contains(j).astype(int)
</code></pre>
| 0 | 2016-08-31T14:50:03Z | [
"python",
"string",
"pandas",
"dataframe"
] |
How to stop writing a blank line at the end of csv file - pandas | 39,237,755 | <p>When saving the data to csv, <code>data.to_csv('csv_data', sep=',', encoding='utf-8', header= False, index = False)</code>, it creates a blank line at the end of csv file. </p>
<p>How do you avoid that? </p>
<p>It's got to do with the <code>line_terminator</code> and it's default value is <code>n</code>, for new... | 0 | 2016-08-30T22:00:48Z | 39,243,675 | <p>One way would be to save data except the last entry,with default <code>line_terminator</code>(<code>\n</code>) and append the last line with <code>line_terminator=""</code> .</p>
<pre><code>data1 = data.iloc[0:len(data)-1]
data2 = data.iloc[[len(data)-1]]
data1.to_csv('csv_data', sep=',', encoding='utf-8', header= ... | 0 | 2016-08-31T07:47:54Z | [
"python",
"csv",
"pandas"
] |
How to escape @ in a password in pymongo connection? | 39,237,813 | <p>My question is a specification of <a href="http://stackoverflow.com/questions/29508162/how-can-i-validate-username-password-for-mongodb-authentication-through-pymongo">how can i validate username password for mongodb authentication through pymongo?</a>.</p>
<p>I'm trying to connect to a MongoDB instance using PyMon... | 0 | 2016-08-30T22:06:13Z | 39,283,299 | <p>You should be able to escape the password using <code>urllib.quote()</code>. Although you should only quote/escape the password, and exclude the <code>username:</code> ;
otherwise the <code>:</code> will also be escaped into <code>%3A</code>. </p>
<p>For example: </p>
<pre><code>import pymongo
import urllib
mon... | 1 | 2016-09-02T02:05:10Z | [
"python",
"mongodb",
"authentication",
"pymongo-3.x"
] |
Why recursion doesn't return value | 39,237,834 | <p>Can't understand why this function return <code>None</code> instead of <code>filename</code></p>
<pre><code>import os
def existence_of_file():
filename = str(input("Give me the name: "))
if os.path.exists(filename):
print("This file is already exists")
existence_of_file()
else:
p... | -1 | 2016-08-30T22:08:03Z | 39,237,973 | <p>You must actually return the return value when calling the function again for recursion. This way, once you stop calling, you return correctly. It's returning <code>None</code> because the call returned nothing. Take a look at this cycle:</p>
<pre><code>Asks for file -> Wrong one given -> Call again -> Rig... | 1 | 2016-08-30T22:21:45Z | [
"python"
] |
Put a 1D array into a 2D array | 39,237,848 | <p>I have a 2D array <code>x</code> in which I want to copy the content of a 1D array <code>y</code> :</p>
<pre><code>import numpy as np
x = np.array([[1, 2], [4, 5], [3, 3]], np.int32)
y = np.array([1, 2, 3, 4, 5, 6])
x[:,:] = y # i would like x to be [[1, 2], [3, 4], [5, 6]]
</code></pre>
<blockquote>
<p>Value... | 0 | 2016-08-30T22:08:58Z | 39,237,866 | <p>You have to convert the <code>y</code> to an array with a shape like <code>x</code>:</p>
<pre><code>>>> x = y.reshape(x.shape)
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
</code></pre>
<p>But note that the <code>y</code> should be reshape with <code>x</code>'s shape.</p>
| 1 | 2016-08-30T22:11:21Z | [
"python",
"arrays",
"numpy"
] |
Odoo XML RPC search and insert | 39,237,883 | <p>I want to search for customers in res.partner from xl using their names then if yes i assign their partner id in the sales order im creating in xmlrpc else insert that partner and use his id in the sales order im creating.note that the purpose is to migrate sales order from xls file to odoo,for now the actual code i... | -1 | 2016-08-30T22:13:02Z | 39,260,875 | <p>Here is a modification of your script which I think should work. I did not look into what values should be passed into the creation of a sales order. You will have to ensure you are passing the correct values. You also import a few packages that you do not use, but I left those in as I assume you plan on using them.... | 0 | 2016-09-01T00:12:40Z | [
"python",
"openerp",
"xml-rpc",
"odoo-9"
] |
TypeError: argument of type 'float' is not iterable | 39,238,057 | <p>I am new to python and TensorFlow. I recently started understanding and executing TensorFlow examples, and came across this one: <a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html</a></p>
... | 3 | 2016-08-30T22:29:04Z | 39,287,583 | <p>The program works verbatim with the latest version of pandas, i.e., 0.18.1</p>
| 0 | 2016-09-02T08:19:45Z | [
"python",
"pandas",
"tensorflow"
] |
Python - Errno 13 Permission denied when trying to copy files | 39,238,098 | <p>I am attempting to make a program in Python that copies the files on my flash drive (letter D:) to a folder on my hard drive but am getting a <em>PermissionError: [Errno 13] Permission denied: 'D:'</em>.</p>
<p>The problematic part of my code is as follows:</p>
<pre><code># Copy files to folder in current director... | 1 | 2016-08-30T22:32:44Z | 39,238,213 | <p>As I stated in my comment above, it seems as if you're trying to open the directory, <code>D:</code>, as if it was a file, and that's not going to work because it's not a file, it's a directory.</p>
<p>What you can do is use <code>os.listdir()</code> to list all of the files within your desired directory, and then ... | 0 | 2016-08-30T22:45:21Z | [
"python",
"copyfile"
] |
What does this python codes mean? | 39,238,108 | <p>What does this python codes mean? New to python. THX!</p>
<pre><code> benchmark_sets_list = [
'%s: %s' %
(set_name, benchmark_sets.BENCHMARK_SETS[set_name]['message'])
for set_name in benchmark_sets.BENCHMARK_SETS]
</code></pre>
| -5 | 2016-08-30T22:33:42Z | 39,238,276 | <p>This part...</p>
<pre><code>for set_name in benchmark_sets.BENCHMARK_SETS
</code></pre>
<p>...will grab the set names from <code>benchmark_sets.BENCHMARK_SETS</code> and it will keep them one by one into a <code>set_name</code> variable.</p>
<p>After that, it will be able to know the values from this line...</p>
... | 1 | 2016-08-30T22:53:06Z | [
"python"
] |
Python Tkinter Save Listbox Item Ordering to Sqlite Database | 39,238,138 | <p>I have a drag-and-drop listbox (<a href="https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch11s05.html" rel="nofollow">found here</a>) that lets the user drag/move items up or down to re-order them.</p>
<p>I have a <code>db.sqlite</code> file that looks like this initially:</p>
<pre><c... | 0 | 2016-08-30T22:36:41Z | 39,241,178 | <p>Highly doubt anyone will answer my question so I'm posting my solution. It uses a drag-and-drop listbox to allow the user to arrange items in the listbox and saves their item ordering to a database for next time.</p>
<pre><code>import tkinter as tk
import pandas as pd
import sqlite3
root = tk.Tk()
class Drag_and_D... | 0 | 2016-08-31T05:08:41Z | [
"python",
"tkinter",
"sqlite3",
"drag-and-drop",
"listbox"
] |
Upload data from csv to series in python | 39,238,201 | <p>I have a data in a column in a csv format and want to append it in series in python that it can be displayed like:</p>
<pre><code>series=[12,13,12,22,34,21]
</code></pre>
<p>How can it be done? Should I do it via read_csv and then somehow transform it to series or it is a another way?</p>
<p>Thanks!</p>
| 0 | 2016-08-30T22:44:09Z | 39,238,254 | <p>Try <code>pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)</code> after reading your data as data frame with <code>read_csv</code>. Pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow">documentation</a></p>
<p>Another possibi... | 0 | 2016-08-30T22:50:04Z | [
"python",
"csv",
"pandas",
"series"
] |
Upload data from csv to series in python | 39,238,201 | <p>I have a data in a column in a csv format and want to append it in series in python that it can be displayed like:</p>
<pre><code>series=[12,13,12,22,34,21]
</code></pre>
<p>How can it be done? Should I do it via read_csv and then somehow transform it to series or it is a another way?</p>
<p>Thanks!</p>
| 0 | 2016-08-30T22:44:09Z | 39,238,261 | <p>IIUC and you are talking about pandas - you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">squeeze</a> parameter:</p>
<pre><code>In [86]: import pandas as pd
In [87]: s = pd.read_csv('d:/temp/.data/1.csv', header=None, squeeze=True)
In [88]: s
Out[88]:
... | 1 | 2016-08-30T22:50:36Z | [
"python",
"csv",
"pandas",
"series"
] |
python windows interpret the values from for loop to cmd command | 39,238,234 | <p>Here is a code </p>
<pre><code> from subprocess import Popen, PIPE
saveerr = sys.stderr
fsock = open('error.log', 'w')
sys.stderr = sys.stdout = fsock
D = {}
D['\\\\aucb-net-01\\d$'] = '\\\\nasaudc01\\remote_site_sync\\aucb-net-01'
D['\\\\aupw-file-01\\e$'] = '\\\\nasaudc01\\remote_site_sync\\aupw-file-01'
... | 0 | 2016-08-30T22:47:51Z | 39,238,830 | <p>The way in Python to do it would be:</p>
<pre><code>cmd = 'robocopy {} {} /E /MIR /W:2 /R:1'.format(k, v)
</code></pre>
<p>or, in Python 3.6:</p>
<pre><code>cmd = f'robocopy {k} {v} /E /MIR /W:2 /R:1'
</code></pre>
<p><strong>However, this is wrong!</strong> It will fail if <code>k</code> and <code>v</code> have... | 0 | 2016-08-31T00:05:12Z | [
"python",
"windows",
"robocopy"
] |
Sending parameters to a remote server via python script | 39,238,298 | <p>I'm learning python these days, and I have a rather basic question. </p>
<p>There's a remote server where a webserver is listening in on incoming traffic. If I enter a uri like the following in my browser, it performs certain processing on some files for me: </p>
<pre><code>//223.58.1.10:8000/processVideo?contain... | 0 | 2016-08-30T22:55:52Z | 39,238,320 | <pre><code>import requests
requests.get("http://223.58.1.10:8000/processVideo",data={"video":"123asd","container":"videos"})
</code></pre>
<p>I guess ... its not really clear what you are asking ...</p>
<p>Im sure you could do the same with just urllib and/or urllib2</p>
<pre><code>import urllib
some_url = "http://2... | 0 | 2016-08-30T22:58:35Z | [
"python",
"linux"
] |
python array inclusive slice index | 39,238,340 | <p>I wish to write a for loop that prints the tail of an array, <strong>including the whole array</strong> (denoted by i==0) Is this task possible without a branching logic, ie a <code>if i==0</code> statement inside the loop?</p>
<p>This would be possible if there is a syntax for slicing with inclusive end index. </p... | 1 | 2016-08-30T23:00:43Z | 39,238,371 | <p>You can use <code>None</code>:</p>
<pre><code>arr=[0,1,2,3,4,5]
for i in range(0,3):
print arr[:-i or None]
</code></pre>
| 8 | 2016-08-30T23:04:14Z | [
"python",
"arrays",
"numpy"
] |
python array inclusive slice index | 39,238,340 | <p>I wish to write a for loop that prints the tail of an array, <strong>including the whole array</strong> (denoted by i==0) Is this task possible without a branching logic, ie a <code>if i==0</code> statement inside the loop?</p>
<p>This would be possible if there is a syntax for slicing with inclusive end index. </p... | 1 | 2016-08-30T23:00:43Z | 39,238,375 | <pre><code>for i in xrange(0, 3):
print arr[:(len(arr) - i)]
# Output
# [0, 1, 2, 3, 4, 5]
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3]
</code></pre>
| 5 | 2016-08-30T23:05:06Z | [
"python",
"arrays",
"numpy"
] |
python array inclusive slice index | 39,238,340 | <p>I wish to write a for loop that prints the tail of an array, <strong>including the whole array</strong> (denoted by i==0) Is this task possible without a branching logic, ie a <code>if i==0</code> statement inside the loop?</p>
<p>This would be possible if there is a syntax for slicing with inclusive end index. </p... | 1 | 2016-08-30T23:00:43Z | 39,238,376 | <p>Had a brain freeze, but this would do:</p>
<pre><code>arr=[0,1,2,3,4,5]
for i in range(0,3):
print arr[:len(arr)-i]
</code></pre>
<p>Although I still wish python had nicer syntax to do these kind of simple tasks. </p>
| 1 | 2016-08-30T23:05:32Z | [
"python",
"arrays",
"numpy"
] |
python array inclusive slice index | 39,238,340 | <p>I wish to write a for loop that prints the tail of an array, <strong>including the whole array</strong> (denoted by i==0) Is this task possible without a branching logic, ie a <code>if i==0</code> statement inside the loop?</p>
<p>This would be possible if there is a syntax for slicing with inclusive end index. </p... | 1 | 2016-08-30T23:00:43Z | 39,238,488 | <p>The awkwardness arises from trying to take advantage of the <code>:-n</code> syntax. Since there's no difference between <code>:0</code> and <code>:-0</code>, we can't use this syntax to distinguish <code>0 from the start</code> from <code>0 from the end</code>.</p>
<p>In this case it is clearer to use the <code>:... | 2 | 2016-08-30T23:19:18Z | [
"python",
"arrays",
"numpy"
] |
Create an RDD with more elements than its source | 39,238,384 | <p>I have an RDD called <code>codes</code>, which is a pair, that has a string as its 1st half and another pair as its 2nd half:</p>
<pre><code>In [76]: codes.collect()
Out[76]:
[(u'3362336966', (6208, 5320)),
(u'7889466042', (4140, 5268))]
</code></pre>
<p>and I am trying to get this:</p>
<pre><code>In [76]: code... | 0 | 2016-08-30T23:07:03Z | 39,238,566 | <p>I think what you want is the following:</p>
<pre><code>codes_in = codes.map(lambda x: [(x[0], p) for p in x[1]]).flatMap(lambda x: x)
</code></pre>
<p>If it is python 2, for legibility you could:</p>
<pre><code>codes_in = codes.map(lambda k, vs: [(k, v) for v in vs]).flatMap(lambda x: x)
</code></pre>
<p>By this... | 1 | 2016-08-30T23:28:14Z | [
"python",
"apache-spark",
"bigdata",
"distributed-computing",
"rdd"
] |
BeautifulSoup Add new tag inside a child DIV of a parent DIV | 39,238,400 | <p>I am a complete beginner with BeautifulSoup and I am now trying to insert a new tag into a children div of a parent div.</p>
<p>Basically I have this HTML snippet:</p>
<pre><code> <div class=page-content>
<div class="content-block">
//Insert here!
</div>
</div>
</code></pre>
<p>He... | 0 | 2016-08-30T23:08:49Z | 39,238,501 | <p>Found the issue, I have to use findNext instead of findChildren. now the append is working fine.</p>
| 0 | 2016-08-30T23:20:41Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
Call a function for a filtered dataframe in pyspark | 39,238,437 | <p>I am having data such as ,</p>
<p>data</p>
<pre><code>ID filter
1 A
2 A
3 A
4 A
5 B
6 B
7 B
8 B
</code></pre>
<p>I want to apply a function for the dataframe,</p>
<pre><code>def add(x):
y = x+1
return... | 0 | 2016-08-30T23:14:01Z | 39,238,851 | <p>What you need is to use <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=functions#pyspark.sql.functions.when" rel="nofollow">when</a> and <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=functions#pyspark.sql.Column.otherwise" rel="nofollow">othe... | 1 | 2016-08-31T00:08:35Z | [
"python",
"python-2.7",
"python-3.x",
"apache-spark",
"pyspark"
] |
My Python code is not outputting anything? | 39,238,469 | <p>I'm currently trying to teach myself Python with the <em>Python Crash Course</em> book by Eric Matthes and I seem to be having difficulties with excercise 5-9 regarding using if tests to test empty lists.</p>
<p><strong>Here is the question:</strong></p>
<p>5-9. No Users: Add an if test to hello_admin.py to make s... | 1 | 2016-08-30T23:17:17Z | 39,238,485 | <p>It's not outputting anything since your <code>if</code> and <code>else</code> blocks are inside the <code>for</code> loop which iterates over <code>usernames</code>. Since <code>usernames</code> is an empty list, it's not iterating over anything, hence not reaching any of those conditional blocks.</p>
<p>You might ... | 2 | 2016-08-30T23:18:52Z | [
"python"
] |
My Python code is not outputting anything? | 39,238,469 | <p>I'm currently trying to teach myself Python with the <em>Python Crash Course</em> book by Eric Matthes and I seem to be having difficulties with excercise 5-9 regarding using if tests to test empty lists.</p>
<p><strong>Here is the question:</strong></p>
<p>5-9. No Users: Add an if test to hello_admin.py to make s... | 1 | 2016-08-30T23:17:17Z | 39,238,624 | <p>The first if-else should come inside the the for loop. The second if else block should come outside. </p>
<pre><code>usernames = []
for username in usernames:
if username is 'admin':
print("Hey admin")
else:
print("Hello " + username + ", thanks!")
if usernames:
print("Hello " + usern... | 1 | 2016-08-30T23:36:27Z | [
"python"
] |
What type should I use for a methods `self` argument? | 39,238,475 | <p>If I'm using <code>mypy</code> on my project, what type should my methods self object be given?</p>
<pre><code>from typing import List
class Example:
def __init__(self, arg1: List[str]) -> None:
pass
</code></pre>
| 2 | 2016-08-30T23:18:07Z | 39,238,512 | <p>Nothing, leave it as is.</p>
<p>That is what I could tell from their documentation:
<a href="https://mypy.readthedocs.io/en/latest/class_basics.html?highlight=self" rel="nofollow">https://mypy.readthedocs.io/en/latest/class_basics.html?highlight=self</a></p>
| 3 | 2016-08-30T23:21:48Z | [
"python",
"mypy"
] |
Converting a raw list to JSON data with Python | 39,238,497 | <p>I have a raw list <code>sorteddict</code> in the form of :</p>
<pre><code>["with", 1]
["witches", 1]
["witchcraft", 3]
</code></pre>
<p>and I want to generate more legible data by making it a JSON object that looks like:</p>
<pre><code>"Frequencies": {
"with": 1,
"witches": 1,
"witchcraft": 3,
"wi... | 0 | 2016-08-30T23:20:24Z | 39,238,547 | <p>I may not be understanding you correctly - but do you just want to turn a list of [word, frequency] lists into a dictionary?</p>
<pre><code>frequency_lists = [
["with", 1],
["witches", 1],
["witchcraft", 3],
]
frequency_dict = dict(frequency_lists)
print(frequency_dict) # {'with': 1, 'witches': 1, 'wit... | 2 | 2016-08-30T23:25:56Z | [
"python",
"json"
] |
Converting a raw list to JSON data with Python | 39,238,497 | <p>I have a raw list <code>sorteddict</code> in the form of :</p>
<pre><code>["with", 1]
["witches", 1]
["witchcraft", 3]
</code></pre>
<p>and I want to generate more legible data by making it a JSON object that looks like:</p>
<pre><code>"Frequencies": {
"with": 1,
"witches": 1,
"witchcraft": 3,
"wi... | 0 | 2016-08-30T23:20:24Z | 39,238,553 | <p>You need to make a nested dict out of your current one, and use <code>json.dumps</code>. Not sure how sorteddict works, but: </p>
<pre><code>json.dumps({"Frequencies": mySortedDict})
</code></pre>
<p>should work. </p>
<p>Additionally, you say that you want something json encoded, but your example is not valid jso... | 4 | 2016-08-30T23:26:34Z | [
"python",
"json"
] |
Drop specific rows from multiindex Dataframe | 39,238,639 | <p>I have a multi-index dataframe that looks like this:</p>
<pre><code> start grad
1995-96 1995-96 15 15
1996-97 6 6
2002-03 1 1
2007-08 1 1
</code></pre>
<p>I'd like to drop by the specific values for the first level (level=0). In this case, I'd like to ... | 2 | 2016-08-30T23:38:37Z | 39,238,699 | <p><code>pandas.DataFrame.drop</code> takes level as an optional argument</p>
<p><code>df.drop('1995-96', level='start')</code></p>
<p>As of v0.18.1, its docstring says:</p>
<blockquote>
<pre><code>"""
Signature: df.drop(labels, axis=0, level=None, inplace=False, errors='raise')
Docstring: Return new object with la... | 3 | 2016-08-30T23:46:36Z | [
"python",
"pandas"
] |
Page count after using PdfFileMerger() in pypdf2 | 39,238,648 | <p>I am trying to use PdfFileMerger() in PyPDF2 to merge pdf files (see code). </p>
<pre><code>from PyPDF2 import PdfFileMerger, PdfFileReader
[...]
merger = PdfFileMerger()
if (some condition):
merger.append(PdfFileReader(file(filename1, 'rb')))
merger.append(PdfFileReader(file(filename2, 'rb')))
if (test ... | 0 | 2016-08-30T23:40:03Z | 39,247,107 | <p>I'm +- in the same case as you. I will explain my solution. I'm not opening the pdfs with <code>PdfFileReader('filename.pdf', 'rb')</code> but I'm passing the pdfs content in an array for the merge (<code>pdfs_content_array</code>). Then I'm preparing the merger and my output (don't want to save the generated file l... | 1 | 2016-08-31T10:28:09Z | [
"python",
"pypdf",
"pypdf2"
] |
Modifying global variables in doctests | 39,238,675 | <p>The doctest documentation has <a href="https://docs.python.org/3.5/library/doctest.html#what-s-the-execution-context" rel="nofollow">a section about execution context</a>.
My reading is that the globals in the module are shallow copied for the tests in each docstring, but are not reset between tests within a docstri... | 2 | 2016-08-30T23:43:39Z | 39,238,927 | <p>Not exactly. While it is true that the globals are shallow copied, what you are actually seeing is the scoping of globals (using the keyword <code>global</code>) and how it actually operates at the module level in Python. You can observe this by putting in a <a href="https://docs.python.org/library/pdb.html#pdb.se... | 0 | 2016-08-31T00:19:27Z | [
"python",
"global-variables",
"doctest"
] |
How do I download a specific service's source code off of AppEngine? | 39,238,707 | <p>I have some php source code working in an app engine production environment that won't work anywhere else. Old versions of that code don't seem to work at all either so I need to get that source and see what the heck it is doing differently.</p>
<p>This discussion outlines the challenges I'm having:
<a href="http:... | 1 | 2016-08-30T23:47:25Z | 39,238,845 | <p>From <code>appcfg.py download_app --help</code>:</p>
<blockquote>
<p>Usage: appcfg.py [options] download_app -A app_id [ -V version ]
</p>
<p>...</p>
<p>-M MODULE, --module=MODULE
Set the module, overriding the module value from
app.yaml. ...</p>
</b... | 0 | 2016-08-31T00:07:15Z | [
"php",
"python",
"google-app-engine",
"google-app-engine-php"
] |
How do I download a specific service's source code off of AppEngine? | 39,238,707 | <p>I have some php source code working in an app engine production environment that won't work anywhere else. Old versions of that code don't seem to work at all either so I need to get that source and see what the heck it is doing differently.</p>
<p>This discussion outlines the challenges I'm having:
<a href="http:... | 1 | 2016-08-30T23:47:25Z | 39,280,910 | <p>Simple enough to do:</p>
<ol>
<li><p>Switch to the directory where App Engine is installed on your computer. It is usually under the following path: </p>
<p><code>C:\Program Files\Google\google_appengine</code></p></li>
<li><p>Run the below command</p>
<p><code>appcfg.py download_app âA MyAppName -V 1 c:\AppEng... | 0 | 2016-09-01T21:11:00Z | [
"php",
"python",
"google-app-engine",
"google-app-engine-php"
] |
ImportError : cannot import name timezone pythonanywhere | 39,238,782 | <p>I am attempting to use collectstatic in the bash console to get my CSS running on a django app on pythonanywhere.</p>
<p>Unfortunately, I am getting an error:</p>
<pre><code>23:49 ~/mysite/mysite $ python manage.py collectstatic ... | 1 | 2016-08-30T23:57:56Z | 39,239,915 | <p>If I am not mistaken, pythonanywhere uses Django 1.3.7 by default. It looks like Django timezone support was not added until version 1.4:</p>
<p><a href="https://docs.djangoproject.com/en/1.10/releases/1.4/#what-s-new-in-django-1-4" rel="nofollow">https://docs.djangoproject.com/en/1.10/releases/1.4/#what-s-new-in-d... | 1 | 2016-08-31T02:38:25Z | [
"python",
"css",
"django",
"importerror",
"pythonanywhere"
] |
Is it possible to use Django models module only in my project? | 39,238,812 | <p>I am developing a small independent python application which uses Celery. I have built this using django framework but my application is back end only. This means that the users do not need to visit my site and my application is built only for the purpose of receiving tasks queue from celery and performing operation... | 0 | 2016-08-31T00:01:56Z | 39,238,855 | <p>you just need </p>
<pre><code>env['DJANGO_SETTING_MODULE'] = 'myproject.settings'
django.setup()
</code></pre>
<p>(assuming you setup your database and installed_apps stuff in settings.py)</p>
| 0 | 2016-08-31T00:08:58Z | [
"python",
"django",
"django-models",
"celery"
] |
Is it possible to use Django models module only in my project? | 39,238,812 | <p>I am developing a small independent python application which uses Celery. I have built this using django framework but my application is back end only. This means that the users do not need to visit my site and my application is built only for the purpose of receiving tasks queue from celery and performing operation... | 0 | 2016-08-31T00:01:56Z | 39,239,467 | <p>In your project's settings.py, just add this at beginning.</p>
<pre><code>import django
import os
sys.path.insert(0, your_project_path) # Ensure python can find your project
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
django.setup()
</code></pre>
<p>Then you can use django orm, remember to delete ... | 0 | 2016-08-31T01:40:45Z | [
"python",
"django",
"django-models",
"celery"
] |
Is it possible to use Django models module only in my project? | 39,238,812 | <p>I am developing a small independent python application which uses Celery. I have built this using django framework but my application is back end only. This means that the users do not need to visit my site and my application is built only for the purpose of receiving tasks queue from celery and performing operation... | 0 | 2016-08-31T00:01:56Z | 39,240,986 | <p>You have have a python script that requires some celery tasks and you need Django ORM too for the database interactions. </p>
<ol>
<li><p>You can setup the django project</p></li>
<li><p>create an app for your purpose, include in settings.py and inside your app in models.py create the required models.
ref : <a hre... | 0 | 2016-08-31T04:51:45Z | [
"python",
"django",
"django-models",
"celery"
] |
Turning results from SQL query into compact Python form | 39,238,847 | <p>I have a database schema in Postgres that looks like this (in pseudo code):</p>
<pre><code>users (table):
pk (field, unique)
name (field)
permissions (table):
pk (field, unique)
permission (field, unique)
addresses (table):
pk (field, unique)
address (field, unique)
association1 (table):
... | 0 | 2016-08-31T00:07:30Z | 39,255,796 | <p>Iterating over the groups of partial entries looks like a job for <a href="https://docs.python.org/3.5/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>.</p>
<p>But first lets put <code>relationships</code> into a format that is easier to use, prehaps a <code>back_populates... | 1 | 2016-08-31T17:37:44Z | [
"python",
"python-3.x"
] |
Django Generic Views :How does DetailView automatically provides the variable to the template ?? | 39,238,867 | <p>In the following code, How does the template <code>details.html</code> knows that <code>album</code> is passed to it by <code>views.py</code> although we have never returned or defined any <code>context_object_name</code> in <code>DetailsView</code> class in <code>views.py</code>.
Please explain how are the various... | 2 | 2016-08-31T00:10:32Z | 39,239,366 | <p>If you check the implementation of <code>get_context_name()</code>, you'll see this:</p>
<pre><code>def get_context_object_name(self, obj):
"""
Get the name to use for the object.
"""
if self.context_object_name:
return self.context_object_name
elif isinstance(obj, models.Model):
... | 3 | 2016-08-31T01:24:52Z | [
"python",
"django",
"django-generic-views"
] |
sqlalchemy syntax for using mysql constants | 39,238,942 | <p>So i am trying to call the mysql function <strong>TIMEDATEDIFF</strong> with the <strong>SECOND</strong> constant as the first parameter like so</p>
<pre><code> query = session.query(func.TIME(Log.IncidentDetection).label('detection'), func.TIMESTAMPDIFF(SECOND,Log.IncidentDetection, Log.IncidentClear).label("du... | 0 | 2016-08-31T00:21:19Z | 39,239,719 | <p>To get sqlalchemy to parse the string exactly into the query I used the <code>_literal_as_text()</code> function</p>
<p><strong>Working solution</strong></p>
<hr>
<pre><code>from sqlalchemy.sql.expression import func, _literal_as_text
# ...
query = session.query(func.TIME(Log.IncidentDetection).label('detection')... | 1 | 2016-08-31T02:16:06Z | [
"python",
"mysql",
"sqlalchemy",
"literals",
"func"
] |
split a list of strings at positions they match a different list of strings | 39,238,984 | <p>I wrote a small program to do the following. I'm wondering if there is an obviously more optimal solution:</p>
<p>1) Take 2 lists of strings. In general, the strings in the second list will be longer than in the first list, but this is not guaranteed</p>
<p>2) Return a list of strings derived from the second list ... | 3 | 2016-08-31T00:28:42Z | 39,239,120 | <p>Let's define this string, <code>s</code>, and this list <code>list1</code> of strings to remove:</p>
<pre><code>>>> s = 'NowIsTheTimeForAllGoodMenToComeToTheAidOfTheParty'
>>> list1 = 'The', 'Good'
</code></pre>
<p>Now, let's remove those strings:</p>
<pre><code>>>> import re
>>&g... | 4 | 2016-08-31T00:47:23Z | [
"python",
"string",
"split"
] |
split a list of strings at positions they match a different list of strings | 39,238,984 | <p>I wrote a small program to do the following. I'm wondering if there is an obviously more optimal solution:</p>
<p>1) Take 2 lists of strings. In general, the strings in the second list will be longer than in the first list, but this is not guaranteed</p>
<p>2) Return a list of strings derived from the second list ... | 3 | 2016-08-31T00:28:42Z | 39,239,239 | <p>Using regular expressions simplifies the code, but it may or may not be more efficient.</p>
<pre><code>>>> import re
>>> sequence_list = ['MPHSSLHPSIPCPRGHGAQKA', 'AEELRHIHSRYRGSYWRTVRA', 'KGLAPAEISAVCEKGNFNVA'],positions_list=[(0, 20), (66, 86), (136, 155)]
>>> avoid = ['SRYRGSYW']
>&... | 4 | 2016-08-31T01:04:55Z | [
"python",
"string",
"split"
] |
Run a chi square test with observation and expectation counts and get confidence interval | 39,239,087 | <p>I am new to chi squared testing and trying to figure out what the 'standard' way of running a chi-squared test and also getting a 95% confidence interval on the difference between success rates in two experiments.</p>
<p>My data looks like this:</p>
<pre class="lang-none prettyprint-override"><code>Condition A: ... | 0 | 2016-08-31T00:42:33Z | 39,239,941 | <p>You have a <a href="https://en.wikipedia.org/wiki/Contingency_table" rel="nofollow">contingency table</a>. To perform the Ï<sup>2</sup> test on this data, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html" rel="nofollow"><code>scipy.stats.chi2_contingency</c... | 2 | 2016-08-31T02:42:57Z | [
"python",
"scipy",
"statistics",
"chi-squared"
] |
List all functions in a module given fullpath | 39,239,182 | <p>I am trying to list all the functions in every encountered module to enforce the writing of test cases. However, I am having issues doing this with just the fullpath to the file as a string and not importing it. When I use <code>inspect.getmembers(fullpath, inspect.isfunction)</code> it returns an empty array. Is th... | 0 | 2016-08-31T00:55:37Z | 39,239,352 | <p>You do need to import the modules somehow but the ârecommendedâ way is a bit tricky since things kept changing with new versions of Python, see <a href="http://stackoverflow.com/a/67692/1640404">this answer</a>.</p>
<p>Here's an example based on the test runner of the <a href="https://github.com/christophercrou... | 0 | 2016-08-31T01:23:01Z | [
"python"
] |
Formatting output from print on respective lines? | 39,239,203 | <p>I am trying to format the results of a query such that results are printed on their respective lines. For example, I am querying stores by store number and obtaining the location from a JSON file, but when printing, the store number and location are printing on separate lines:</p>
<p>Code Snippet: (Searching for st... | 1 | 2016-08-31T00:59:57Z | 39,239,216 | <p>Adding <code>end=''</code> to your first print statement should fix the problem. By specifying that the end character is an empty string you will override the default <code>\n</code> character (by default print statements end with a new line character).</p>
<pre><code>for store, data in results.items():
print('... | 1 | 2016-08-31T01:01:38Z | [
"python",
"python-3.x",
"printing",
"formatting"
] |
Formatting output from print on respective lines? | 39,239,203 | <p>I am trying to format the results of a query such that results are printed on their respective lines. For example, I am querying stores by store number and obtaining the location from a JSON file, but when printing, the store number and location are printing on separate lines:</p>
<p>Code Snippet: (Searching for st... | 1 | 2016-08-31T00:59:57Z | 39,242,898 | <p>I would write all the output in a variable and print the variable only once at the end. This also allows you to save time (despite using more memory) since you need only a single access to the stdout. The code is also easier to follow (in my opinion):</p>
<pre><code>output = ''
for store, data in results.items():
... | 0 | 2016-08-31T07:06:44Z | [
"python",
"python-3.x",
"printing",
"formatting"
] |
Python - Injecting html tags into strings based on regex match | 39,239,361 | <p>I wrote a script in Python for custom HTML page that finds a word within a string/line and highlights just that word with use of following tags where instance is the word that is searched for.</p>
<pre><code><b><font color=\"red\">"+instance+"</font></b>
</code></pre>
<p>With the following ... | -1 | 2016-08-31T01:24:18Z | 39,241,045 | <p>Maybe I'm misinterpretting your question, but wouldn't re.sub be the best option?</p>
<p>Example: <a href="https://repl.it/DExs" rel="nofollow">https://repl.it/DExs</a></p>
| 0 | 2016-08-31T04:57:24Z | [
"python",
"html",
"regex",
"string",
"tags"
] |
Python - Injecting html tags into strings based on regex match | 39,239,361 | <p>I wrote a script in Python for custom HTML page that finds a word within a string/line and highlights just that word with use of following tags where instance is the word that is searched for.</p>
<pre><code><b><font color=\"red\">"+instance+"</font></b>
</code></pre>
<p>With the following ... | -1 | 2016-08-31T01:24:18Z | 39,246,418 | <p>Okay so two ways I did quickly! The second loop is definitely the way to go. It uses re.sub (as someone else commented too). It replaces with the lowercase search term bear in mind.</p>
<pre><code>import re
FILE = open("testing.txt","r")
word="port"
#THIS LOOP IS CASE SENSITIVE
for line in FILE:
newline=line.... | 0 | 2016-08-31T09:56:40Z | [
"python",
"html",
"regex",
"string",
"tags"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.