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 |
|---|---|---|---|---|---|---|---|---|---|
df.mean is not the real mean of the Series? | 38,947,278 | <p>I'm debugging and run into the following strange behavior.
I'm calculating the mean of a pandas series which contains all exactly the same numbers. However, the <code>pd.mean()</code> gives a different number.</p>
<p>question1: why mean of this Series is a different number?</p>
<p>question2: <code>tmm[-1]== tmm.me... | 1 | 2016-08-14T22:46:30Z | 38,948,126 | <p>Try using <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html" rel="nofollow">np.isclose()</a></p>
<pre><code>tmm[20]== tmm.mean()
False
np.isclose(tmm[20], tmm.mean())
True
</code></pre>
| 1 | 2016-08-15T01:18:10Z | [
"python",
"pandas"
] |
python script that imports matplotlib succeeds butfrozen binary of script fails | 38,947,330 | <p>My script needed to import <code>numpy</code>, <code>sklearn</code>, and <code>matplotlib</code> but I couldn't install sklearn. A very helpful response to my question <a href="http://http://stackoverflow.com/questions/38733220/difference-between-scikit-learn-and-sklearn" rel="nofollow">http://http://stackoverflow.... | 0 | 2016-08-14T22:55:19Z | 38,961,350 | <p>The issue with the frozen binary turned out to be "RuntimeError: Python is not installed as a framework."</p>
<p>Several posts discussed that issue and suggested adding these two lines before "import matplotlib.pyplot as plt":</p>
<p>import matplotlib<br>
matplotlib.use('TkAgg')</p>
<p>That did not work, but this... | 0 | 2016-08-15T19:04:19Z | [
"python",
"matplotlib"
] |
Pandas: Loop through dataframe with out counter | 38,947,347 | <p>I have a data frame <code>df</code> which has dates in it:</p>
<pre><code>df['Survey_Date'].head(4)
Out[65]:
0 1990-09-28
1 1991-07-26
2 1991-11-23
3 1992-10-15
</code></pre>
<p>I am interested in calculating a metric between two of the dates, using a separate data frame <code>flow_df</code>. </p>
<... | 0 | 2016-08-14T22:57:17Z | 38,947,462 | <p>You can use <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow"><code>zip()</code></a>:</p>
<pre><code>for early_date, current_date in zip(df['Survey_Date'], df['Survey_Date'][1:]):
#do whatever yo want.
</code></pre>
<p>Of course you can put it into a <a class='doc-link' href="http... | 0 | 2016-08-14T23:16:35Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: Loop through dataframe with out counter | 38,947,347 | <p>I have a data frame <code>df</code> which has dates in it:</p>
<pre><code>df['Survey_Date'].head(4)
Out[65]:
0 1990-09-28
1 1991-07-26
2 1991-11-23
3 1992-10-15
</code></pre>
<p>I am interested in calculating a metric between two of the dates, using a separate data frame <code>flow_df</code>. </p>
<... | 0 | 2016-08-14T22:57:17Z | 38,947,738 | <p>Since the question is unclear, I'm posting this idea of using filters:</p>
<pre><code>flow_df[(flow_df["Date"] <= '1991-07-26' ) & (flow_df["Date"] >= '1990-09-26' ) ].max()
current_date = '1991-07-26'
early_date = '1990-09-28'
flow_df[(flow_df["Date"] <= current_date) & (flow_df["Date"] >= ... | -1 | 2016-08-15T00:06:38Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: Loop through dataframe with out counter | 38,947,347 | <p>I have a data frame <code>df</code> which has dates in it:</p>
<pre><code>df['Survey_Date'].head(4)
Out[65]:
0 1990-09-28
1 1991-07-26
2 1991-11-23
3 1992-10-15
</code></pre>
<p>I am interested in calculating a metric between two of the dates, using a separate data frame <code>flow_df</code>. </p>
<... | 0 | 2016-08-14T22:57:17Z | 38,948,404 | <p>You can define a new variable that identifies survey period and use <code>pandas.DataFrame.groupby</code> to avoid <code>for</code> loop. It should be much faster when <code>flow_df</code> is large.</p>
<pre><code>#convert both to datetime, if they are not
df['Survey_Date'] = pd.to_datetime(df['Survey_Date'])
flow_... | 2 | 2016-08-15T02:08:35Z | [
"python",
"pandas",
"dataframe"
] |
How to selectively iterate over files with Python | 38,947,428 | <p>I would like to iterate through files in a specified directory which are bigger then 100 kb and end with a *.zip.</p>
<p>How can this be done in a efficient way?</p>
<p>Will go through any zip files but not necessarily files which are bigger than 100kb;</p>
<pre><code>for i in os.listdir(os.getcwd()):
if i.en... | 0 | 2016-08-14T23:11:09Z | 38,947,618 | <p>You could try something like this...</p>
<pre><code>for i in os.listdir(os.getcwd()):
if i.endswith(".zip"):
if os.path.getsize(i) > 10240:
print i
continue
else:
continue
</code></pre>
| 1 | 2016-08-14T23:45:44Z | [
"python"
] |
How to selectively iterate over files with Python | 38,947,428 | <p>I would like to iterate through files in a specified directory which are bigger then 100 kb and end with a *.zip.</p>
<p>How can this be done in a efficient way?</p>
<p>Will go through any zip files but not necessarily files which are bigger than 100kb;</p>
<pre><code>for i in os.listdir(os.getcwd()):
if i.en... | 0 | 2016-08-14T23:11:09Z | 38,947,660 | <p><code>endswith</code> and <code>os.path.getsize</code> are the two functions you want.</p>
<pre><code>import os
file_names = [os.path.join(path, file_name) for file_name in os.listdir(path)]
for file_name in file_names:
if file_name.endswith('zip') and os.path.getsize(file_name) >= 100*1024:
pass
... | 0 | 2016-08-14T23:53:49Z | [
"python"
] |
Chrome Not Starting When Using ChromeDriver | 38,947,469 | <p>I'm trying to use Selenium and ChromeDriver to write a scraping job. When I run the following code though nothing happens, in the sense that Chrome doesn't appear to start, but I don't get an error.</p>
<pre><code>import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(r"http://www.pytho... | 1 | 2016-08-14T23:17:45Z | 38,947,851 | <p>You need to download chromedriver from <a href="https://sites.google.com/a/chromium.org/chromedriver/" rel="nofollow">here</a> and put it in your path. I also see that you have a typo in driver.get, make sure you have a correct URL as well</p>
<p>Below is the typo I was talking about </p>
<pre><code>driver.get(r"h... | 1 | 2016-08-15T00:29:57Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
Run python-rq worker process on application start | 38,947,480 | <p>I hosted my Django app on Heroku but due to few limitations I moved from Heroku to cloud based server. I followed this <a href="https://devcenter.heroku.com/articles/python-rq" rel="nofollow">tutorial</a> on running background tasks in Python. Everything is running fine except that I have to manually run <code>pytho... | 0 | 2016-08-14T23:19:24Z | 38,951,814 | <p>Use a process manager like upstart, systemd or supervisor.</p>
| 0 | 2016-08-15T08:33:27Z | [
"python",
"django",
"heroku",
"python-rq"
] |
Run python-rq worker process on application start | 38,947,480 | <p>I hosted my Django app on Heroku but due to few limitations I moved from Heroku to cloud based server. I followed this <a href="https://devcenter.heroku.com/articles/python-rq" rel="nofollow">tutorial</a> on running background tasks in Python. Everything is running fine except that I have to manually run <code>pytho... | 0 | 2016-08-14T23:19:24Z | 38,951,911 | <p>I ended up using upstart. I created a new config file <code>rqworker.py</code> using <code>sudo nano \etc\init\rqworker.conf</code> with the following code:</p>
<pre><code>description "Job queues for directory"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
setuid myuser
setgid www-data
exec python3.5... | 1 | 2016-08-15T08:41:20Z | [
"python",
"django",
"heroku",
"python-rq"
] |
Repeating elements in a list | 38,947,499 | <p>I have a list with elements:</p>
<pre><code>a = ['Monica', 'Mark', 'Nick', 'Margaret']
</code></pre>
<p>and I'd like to obtain the following list of names:</p>
<pre><code>['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']
</code></pre>
<p>The simplest solution I came up with is:</p>
<p... | -4 | 2016-08-14T23:24:40Z | 38,947,581 | <p>Try this</p>
<pre><code>def repeat(collection, count):
for x in collection:
for i in range(count):
yield x
a = ['Monica', 'Mark', 'Nick', 'Margaret']
print [x for x in repeat(a, 2)]
</code></pre>
<p>prints</p>
<pre><code>['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'M... | 1 | 2016-08-14T23:36:58Z | [
"python",
"pandas"
] |
Repeating elements in a list | 38,947,499 | <p>I have a list with elements:</p>
<pre><code>a = ['Monica', 'Mark', 'Nick', 'Margaret']
</code></pre>
<p>and I'd like to obtain the following list of names:</p>
<pre><code>['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']
</code></pre>
<p>The simplest solution I came up with is:</p>
<p... | -4 | 2016-08-14T23:24:40Z | 38,947,662 | <p>Here's a working example:</p>
<pre><code>import itertools
a = ['Monica', 'Mark', 'Nick', 'Margaret']
num_repeats = 2
lnames2 = list(itertools.chain(*[[x] * num_repeats for x in a]))
print(lnames2)
</code></pre>
| 1 | 2016-08-14T23:54:06Z | [
"python",
"pandas"
] |
How to make a specific type of python face tracker | 38,947,519 | <p>Recently I have been working on a face tracker using python 3 and opencv and my laptops webcam, I've made it so that a window will pop up and display the webcam feed when you run the .pyw script, and I've mad a python script that detects a face on a frozen image with haarcascades, but I cant seem to combine the two,... | 0 | 2016-08-14T23:27:06Z | 38,964,472 | <p>Never mind, I already fixed it.</p>
<pre><code>import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
vc = cv2.VideoCapture(0)
while -1:
... | 0 | 2016-08-15T23:26:43Z | [
"python",
"python-3.x",
"opencv"
] |
Convert pandas (python) categorical x-axis to continuous values when plotting | 38,947,522 | <p>I am plotting a pandas series in python using the matplotlib <code>plot</code> command (i.e. <code>series.plot()</code>, where <code>series</code> is my series). Part of the series is as follows:</p>
<pre><code>(1, 1.1] 0.000000
(1.1, 1.2] 0.000000
(1.2, 1.3] 0.000000
(1.3, 1.4] 0.003115
(1.4, 1.5] ... | 1 | 2016-08-14T23:27:19Z | 38,948,031 | <p>Where does the series come from? Usually, I have a big dataframe of continuous-valued columns <code>X</code> and <code>Y</code>, and then define <code>X-bins</code>s according to <code>X</code> values. After that, group by <code>X-bins</code> to calculate average (or weighted average, or sum, or any other aggregatio... | 0 | 2016-08-15T00:59:11Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Convert pandas (python) categorical x-axis to continuous values when plotting | 38,947,522 | <p>I am plotting a pandas series in python using the matplotlib <code>plot</code> command (i.e. <code>series.plot()</code>, where <code>series</code> is my series). Part of the series is as follows:</p>
<pre><code>(1, 1.1] 0.000000
(1.1, 1.2] 0.000000
(1.2, 1.3] 0.000000
(1.3, 1.4] 0.003115
(1.4, 1.5] ... | 1 | 2016-08-14T23:27:19Z | 38,948,056 | <p>Based on our discussion, your series has an index that is a string of the intervals, eg. <code>'(1,1.1]'</code> is the index of the first item in the series. </p>
<p>I was able to reproduce your issue using the following code:</p>
<pre><code>import pandas as pd
import numpy as np
x1 = np.arange(0,5,.1)
x2 = np.a... | 1 | 2016-08-15T01:04:28Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
imshow() giving error in Python for image | 38,947,627 | <pre><code>import cv2
import numpy as np
img=cv2.imread("drop.jpg",cv2.IMREAD_GRAYSCALE)
cv2.imshow("blue", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>The <code>imshow</code> function is giving error, the rest of the code is working fine.</p>
<p>Error message:</p>
<blockquote>
<p>OpenCV Error: ... | 0 | 2016-08-14T23:47:14Z | 39,305,527 | <p><code>cv2.imread()</code> couldn't locate your image file i.e drop.jpg</p>
| 1 | 2016-09-03T09:47:36Z | [
"python",
"opencv"
] |
Avoid Nesting If Statements? (Python 2.7) | 38,947,628 | <p>I got the idea for this guessing game from a book, Invent With Python. I didn't like that the original script didn't cover the possibilities of re-guessing a number or incorrectly using a number not in 1 - 20, so I modified it. The program works great, however, I'm just wrapping my head around if/elif/else code bloc... | 1 | 2016-08-14T23:47:15Z | 38,947,762 | <p>Just change the nested if statements to elif like so:</p>
<pre><code>from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_numbe... | 1 | 2016-08-15T00:11:15Z | [
"python",
"nested"
] |
Avoid Nesting If Statements? (Python 2.7) | 38,947,628 | <p>I got the idea for this guessing game from a book, Invent With Python. I didn't like that the original script didn't cover the possibilities of re-guessing a number or incorrectly using a number not in 1 - 20, so I modified it. The program works great, however, I'm just wrapping my head around if/elif/else code bloc... | 1 | 2016-08-14T23:47:15Z | 38,947,941 | <p>Try it like this, using <code>continue</code> to exit the current iteration of the loop and start again at the top of the loop. </p>
<p>You also had a logic bug here:</p>
<pre><code>if guess <= 1 and guess >= 20 and guess not in already_guessed:
</code></pre>
<p>A number cannot possibly be both less than or... | 4 | 2016-08-15T00:43:42Z | [
"python",
"nested"
] |
Get the Key and Value of a dictionary while using random | 38,947,650 | <p>I'm new to python and I'm trying to make a simple "Game"
I'm trying to get the health of the monsters but only the names come up.
I can do <code>(random.choice(list(Monster.health.keys())))</code> and <code>(random.choice(list(Monster.health.Values())))</code> to store both the name and health in a variable but I'm... | 0 | 2016-08-14T23:51:31Z | 38,947,881 | <p>You only need to call <code>choice</code> once, like so:</p>
<pre><code>class Monster:
health = {'goblin': 15, 'giant': 50}
class EncounterM(Monster):
def __init__(self):
self.random_mon_name = ''
self.random_mon_health = 0
def basic_monster(self):
import random
self.ra... | 0 | 2016-08-15T00:34:04Z | [
"python",
"dictionary",
"random"
] |
Get the Key and Value of a dictionary while using random | 38,947,650 | <p>I'm new to python and I'm trying to make a simple "Game"
I'm trying to get the health of the monsters but only the names come up.
I can do <code>(random.choice(list(Monster.health.keys())))</code> and <code>(random.choice(list(Monster.health.Values())))</code> to store both the name and health in a variable but I'm... | 0 | 2016-08-14T23:51:31Z | 38,947,886 | <p>If you want to store both key an value at <code>self.random_mon_name_health</code> you can change your method to something like that and it will return a tuple with the monster name and its associated health.</p>
<pre><code>def basic_monster(self):
import random
random_key = (random.choice(list(Monster.heal... | 0 | 2016-08-15T00:35:09Z | [
"python",
"dictionary",
"random"
] |
TypeError when writing to .txt file Python | 38,947,656 | <p>I'm taking data from a website, and writing it to a .txt file. </p>
<pre><code>head = 'mpg123 -q '
tail = ' &'
url = 'http://www.ndtv.com/article/list/top-stories/'
r = requests.get(url)
soup = BeautifulSoup(r.content)
g_data = soup.find_all("div",{"class":"nstory_intro"})
log = open("/home/pi/logs/newslog.tx... | 0 | 2016-08-14T23:53:07Z | 38,948,521 | <p><code>ResultSet</code> is type of your <code>g_data</code>:</p>
<pre><code>In [8]: g_data = soup.find_all('div',{'class':'nstory_intro'})
In [9]: type(g_data)
Out[9]: bs4.element.ResultSet
</code></pre>
<p>With your write code, DON'T use <code>open</code> then <code>close</code>. Use <a href="https://www.python.o... | 0 | 2016-08-15T02:25:47Z | [
"python",
"text-files",
"typeerror"
] |
TensorFlow saving into/loading a graph from a file | 38,947,658 | <p>From what I've gathered so far, there are several different ways of dumping a TensorFlow graph into a file and then loading it into another program, but I haven't been able to find clear examples/information on how they work. What I already know is this:</p>
<ol>
<li>Save the model's variables into a checkpoint fil... | 2 | 2016-08-14T23:53:27Z | 38,950,073 | <p>There are many ways to approach the problem of saving a model in TensorFlow, which can make it a bit confusing. The <a class='doc-link' href="http://stackoverflow.com/documentation/tensorflow/5000/saving-and-restoring-a-model-in-tensorflow#t=201608150606555812336">documentation on this topic</a> is taking shape, but... | 4 | 2016-08-15T06:07:47Z | [
"python",
"tensorflow",
"protocol-buffers"
] |
python reduce: find total size of all lists inside list of tuples | 38,947,667 | <p>my data structure looks as below</p>
<pre><code>itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
</code></pre>
<p>I want to find total number of items in the list of tuples above. For above example, len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9 </p>
<pre><code>reduce(lambda x,y: len(... | 2 | 2016-08-14T23:55:16Z | 38,947,696 | <p>You could simply try:</p>
<pre><code>sum([len(elem[1]) for elem in itemsData])
</code></pre>
<p>E.g.</p>
<pre><code>>>> itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
>>> sum([len(elem[1]) for elem in itemsData])
9
</code></pre>
| 4 | 2016-08-14T23:58:57Z | [
"python",
"lambda",
"reduce"
] |
python reduce: find total size of all lists inside list of tuples | 38,947,667 | <p>my data structure looks as below</p>
<pre><code>itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
</code></pre>
<p>I want to find total number of items in the list of tuples above. For above example, len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9 </p>
<pre><code>reduce(lambda x,y: len(... | 2 | 2016-08-14T23:55:16Z | 38,947,745 | <p>I will explain why your code does not work</p>
<p>from <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow">https://docs.python.org/2/library/functions.html#reduce</a>,</p>
<blockquote>
<p>The left argument, x, is the accumulated value and the right argument, y, is the update value fr... | 4 | 2016-08-15T00:08:16Z | [
"python",
"lambda",
"reduce"
] |
How to reassign object to a variable in python? | 38,947,715 | <p>If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the ... | 0 | 2016-08-15T00:02:34Z | 38,947,748 | <p>Save a reference somewhere with another assignment.</p>
<pre><code>b = tk.Button(root, text="button b")
saved = b
b = 1
saved.pack()
</code></pre>
| 1 | 2016-08-15T00:08:51Z | [
"python",
"tkinter"
] |
How to reassign object to a variable in python? | 38,947,715 | <p>If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the ... | 0 | 2016-08-15T00:02:34Z | 38,947,749 | <blockquote>
<p>... then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? </p>
</blockquote>
<p>Short answer: you can't. In order to refer to something you must keep a reference. That being said,tkinter provides some alternatives.</p>
<p>If you'r... | 1 | 2016-08-15T00:08:54Z | [
"python",
"tkinter"
] |
How to reassign object to a variable in python? | 38,947,715 | <p>If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the ... | 0 | 2016-08-15T00:02:34Z | 38,947,937 | <p>You can access all widgets of the root window with the method:</p>
<pre><code>list_of_widgets = root.pack_slaves()
</code></pre>
<p>and then check for the type of the object. ( Which is not a good practice ... )
Thus, i would recommend you to save the required references in a separeate object, for clearly seperati... | 1 | 2016-08-15T00:43:26Z | [
"python",
"tkinter"
] |
wxPython, using a field from an imported class | 38,947,725 | <p>First important to state that I am an amateur programmer.</p>
<p>Building a personal software in python/wxPython connected to a MySQL DB</p>
<p>My problem:</p>
<p>trying to write one form that will access classes from an imported file.
The form accesses at any one time 4 related tables on the database.</p>
<p>Th... | 0 | 2016-08-15T00:04:13Z | 38,948,164 | <p>Check out sqlite3 library: I used it to do something similar:</p>
<pre><code>import sqlite3
def insert_user(cursor,username,password,port,steps,lat,long):
try:
cursor.execute("INSERT INTO mydb VALUES(?,?,?,?,?,?)", (username,password,port,steps,lat,long))
return "Success"
e... | 0 | 2016-08-15T01:27:34Z | [
"python",
"wxpython"
] |
Re-initialize variables in Tensorflow | 38,947,754 | <p>I am using a Tensorflow <code>tf.Saver</code> to load a pre-trained model and I want to re-train a few of its layers by erasing (re-initializing to random) their appropriate weights and biases, then training those layers and saving the trained model. I can not find a method that re-initializes the variables. I tried... | 0 | 2016-08-15T00:09:35Z | 38,949,245 | <p><code>initialize_all_variables</code> should work to re-initialize previously initialized var.</p>
<p>Just did this sanity check in 0.10</p>
<pre><code>tf.reset_default_graph()
a = tf.Variable(tf.ones_initializer(()))
init_op = tf.initialize_all_variables()
modify_op = a.assign(5.0)
sess = tf.InteractiveSession()... | 1 | 2016-08-15T04:15:04Z | [
"python",
"machine-learning",
"computer-vision",
"neural-network",
"tensorflow"
] |
Code works but does not work the correct way-python | 38,947,809 | <p>I am trying to create this modified version of road trip in python 3.4.3 and it is not working like I want. The problem is that when the player selects anything but a "y" when taking a hit for getting stuck, it assumes the player wants to take a chance when he/she doesn't. I have tried use the else statement and I ... | -4 | 2016-08-15T00:21:37Z | 38,948,101 | <p>You should be able to fix your issue by changing the second nested if statement to elif like so:</p>
<pre><code>import random
import time
import math
print("Welcome to ATV Road Trip!!!")
time.sleep(1)
stuck=0
print("Good luck because your gonna need it...")
time.sleep(1)
first_round=0
second_round=0
third_round=0
w... | 0 | 2016-08-15T01:13:14Z | [
"python"
] |
Code works but does not work the correct way-python | 38,947,809 | <p>I am trying to create this modified version of road trip in python 3.4.3 and it is not working like I want. The problem is that when the player selects anything but a "y" when taking a hit for getting stuck, it assumes the player wants to take a chance when he/she doesn't. I have tried use the else statement and I ... | -4 | 2016-08-15T00:21:37Z | 38,949,985 | <p>Tests like this don't work:</p>
<pre><code>if lose_choice_1 == 'y' or 'Y':
</code></pre>
<p>It's always true. You need to do:</p>
<pre><code>if lose_choice_1 == 'y' or lose_choice_1 == 'Y':
</code></pre>
<p>or you can do:</p>
<pre><code>if lose_choice_1.lower() == 'y':
</code></pre>
<p>Other than that, your ... | 0 | 2016-08-15T05:57:18Z | [
"python"
] |
Conditional comprehension in Julia | 38,947,840 | <p>In Python, there is the option to provide a condition for whether or not to include a specific item in a comprehension.</p>
<pre><code>[x**2 for x in range(10) if x > 5]
# [36, 49, 64, 81]
</code></pre>
<p>It is possible to conditionally use function, but I have not yet found a way to entirely exclude values, o... | 6 | 2016-08-15T00:27:35Z | 38,947,888 | <p>It is possible in the latest Julia.</p>
<pre><code>julia> [x^2 for x in 0:9 if x > 5]
4-element Array{Int64,1}:
36
49
64
81
</code></pre>
<p>Otherwise, yes, if you're using pre 0.5 you're stuck with:</p>
<pre><code>[x^2 for x in filter((x) -> x > 5, 0:9)]
</code></pre>
| 12 | 2016-08-15T00:35:53Z | [
"python",
"if-statement",
"filter",
"list-comprehension",
"julia-lang"
] |
Sort nested dictionaries then sort outer dictionary | 38,947,841 | <p>I have a dictionary of states and counties:</p>
<pre><code>{
'WI': {'CountyZ': 0,
'CountyC': 0,
'CountyD': 0},
'IL': {'CountyM': 0,
'CountyW': 0,
'CountyA': 0}
}
</code></pre>
<p>I would like to sort the inner dictionaries of counties based on keys and then sort the oute... | 0 | 2016-08-15T00:27:36Z | 38,947,989 | <p>You can get the sorted list of tuples like so:</p>
<pre><code>d = {
'WI': {'CountyZ': 0,
'CountyC': 0,
'CountyD': 0},
'IL': {'CountyM': 0,
'CountyW': 0,
'CountyA': 0}
}
print sorted((key, sorted(inner_dict.items())) for key, inner_dict in d.iteritems())
</code></pre>
| 1 | 2016-08-15T00:53:21Z | [
"python",
"sorting",
"dictionary"
] |
Copy between arrays by indexing | 38,947,916 | <p>I'd like to copy elements of an array (<code>a</code>) to a result array <code>b</code> according to some rules that define which element from <code>a</code> goes where in <code>b</code>. I created an example below.</p>
<p>Is it possible (by some smart indexing?) to perform the last step (<code>b[x,mask] = a[mask]<... | 1 | 2016-08-15T00:41:03Z | 38,948,792 | <p>I don't know if it improves it or not, but it is possible to do the copy in one step if we construct raveled indexes:</p>
<p>Start with a list of the masks:</p>
<pre><code>In [1934]: m=[m1,m2,m3,m4]
</code></pre>
<p>Make an index list by joining the individual list - adjusted to work with a flat or raveled 1d ver... | 0 | 2016-08-15T03:08:16Z | [
"python",
"arrays",
"numpy"
] |
Reshaping numpy array from list | 38,947,926 | <p>I have the following problem with shape of ndarray:</p>
<pre><code>out.shape = (20,)
reference.shape = (20,0)
norm = [out[i] / np.sum(out[i]) for i in range(len(out))]
# norm is a list now so I convert it to ndarray:
norm_array = np.array((norm))
norm_array.shape = (20,30)
# error: operands could not be broadcast ... | 0 | 2016-08-15T00:41:33Z | 38,948,220 | <p>I am not sure what you are trying to do exactly, but here is some information on numpy arrays.</p>
<p>A 1-d numpy array is a row vector with a shape that is a single-valued tuple:</p>
<pre><code>>>> np.array([1,2,3]).shape
(3,)
</code></pre>
<p>You can create multidimensional arrays by passing in nested... | 2 | 2016-08-15T01:39:07Z | [
"python",
"arrays",
"numpy",
"reshape"
] |
Reshaping numpy array from list | 38,947,926 | <p>I have the following problem with shape of ndarray:</p>
<pre><code>out.shape = (20,)
reference.shape = (20,0)
norm = [out[i] / np.sum(out[i]) for i in range(len(out))]
# norm is a list now so I convert it to ndarray:
norm_array = np.array((norm))
norm_array.shape = (20,30)
# error: operands could not be broadcast ... | 0 | 2016-08-15T00:41:33Z | 38,948,579 | <p>If I make 2 arrays with the shapes you describe, I get an error</p>
<pre><code>In [1856]: norm_array=np.ones((20,30))
In [1857]: reference=np.ones((20,0))
In [1858]: norm_array-reference
...
ValueError: operands could not be broadcast together with shapes (20,30) (20,0)
</code></pre>
<p>But it's different from yo... | 0 | 2016-08-15T02:34:26Z | [
"python",
"arrays",
"numpy",
"reshape"
] |
Manipulating data frame in R | 38,947,967 | <p>I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A.</p>
<p>Below is a reproducible example.</p>
<pre><code>set.seed(10)
fooDF <- data.frame(A = sample(1:4, 10, replace=... | 1 | 2016-08-15T00:49:27Z | 38,948,115 | <p>First paste columns B and C together (into column "z"):</p>
<pre><code>fooDF$z = paste0(fooDF$B,fooDF$C)
A B C D z
1 3 d c 3 dc
2 1 b d 3 bd
3 1 a a 2 aa
4 2 d a 1 da
5 4 d c 1 dc
6 2 d b 2 db
7 4 b d 3 bd
8 2 c d 3 cd
9 1 a b 2 ab
10 4 a b 2 ab
</code></pre>
<p>Then I'll remove columns B and C</p>
... | 3 | 2016-08-15T01:16:14Z | [
"python"
] |
Manipulating data frame in R | 38,947,967 | <p>I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A.</p>
<p>Below is a reproducible example.</p>
<pre><code>set.seed(10)
fooDF <- data.frame(A = sample(1:4, 10, replace=... | 1 | 2016-08-15T00:49:27Z | 38,948,508 | <p>In <code>R</code>, this can be done with <code>tidyr</code></p>
<pre><code>library(tidyr)
fooDF %>%
unite(BC, B, C, sep="") %>%
spread(BC, D)
# A ab ad ba bd ca cb da dc
#1 1 NA 4 NA 2 NA NA NA NA
#2 2 4 NA 3 NA NA NA NA 2
#3 3 NA NA NA NA 1 NA NA NA
#4 4 3 NA 2 NA NA 2 2 NA
</code></pre... | 3 | 2016-08-15T02:23:27Z | [
"python"
] |
bash on Ubuntu on windows Linux, folder recognition, and running Python scripts | 38,948,021 | <p>I'm new to Linux. I recently downloaded Bash on Ubuntu on Windows 10 (after the Anniversary edition update to Windows 10). Since this update is relatively new, there is not much online regarding troubleshooting. There are two things I need help on:</p>
<p>(1) When I go to the home folder, which seems to be "C:\User... | 0 | 2016-08-15T00:57:58Z | 39,723,038 | <p>Looks like you are having permissions issues.
To see everything on your home folder try
<strong>ls -al</strong>
to change permissions check out the <strong>chmod</strong> command </p>
| 0 | 2016-09-27T11:05:15Z | [
"python",
"linux",
"bash",
"ubuntu",
"wsl"
] |
Using searchsorted for 2D array | 38,948,042 | <p>I would like to have the index like function :<code>np.searchsorted([1,2,3,4,5], 3)</code> returns 2 but in case 2-D dimension: <code>np.searchsorted([[1,2],[3,4],[5,6]], [5,6])</code> should return 2. How can I do that?</p>
| 2 | 2016-08-15T01:01:44Z | 38,948,098 | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow">documentation for <code>searchsorted</code></a> indicates that it only works on 1-D arrays.</p>
<p>You can find the index location in a list using built-in methds:</p>
<pre><code>>>> a = [[1,2],[3,4],[... | 1 | 2016-08-15T01:12:46Z | [
"python",
"numpy"
] |
Using searchsorted for 2D array | 38,948,042 | <p>I would like to have the index like function :<code>np.searchsorted([1,2,3,4,5], 3)</code> returns 2 but in case 2-D dimension: <code>np.searchsorted([[1,2],[3,4],[5,6]], [5,6])</code> should return 2. How can I do that?</p>
| 2 | 2016-08-15T01:01:44Z | 38,948,106 | <pre><code>a = np.array([[1,2],[3,4],[5,6]])
b = np.array([5,6])
np.where(np.all(a==b,axis=1))
</code></pre>
| 3 | 2016-08-15T01:14:09Z | [
"python",
"numpy"
] |
Why doesn't Pycharm show dictionary methods in this case? | 38,948,132 | <p>I am trying to do a very simple service to collect and print data from a RESTfull API, in Python.
This is the code I have:</p>
<pre><code>import requests
import json
response = requests.get("url")
data2 = response.json()
print type(data2)
</code></pre>
<p>Here is my issue: when I print data2 type, it tells me it'... | 1 | 2016-08-15T01:19:45Z | 39,334,190 | <p>As it was mentioned in comments PyCharm doesn't know type because <code>requests</code> doesn't declare return type. But it's possible to use type comments here (see <a href="https://www.python.org/dev/peps/pep-0484/#type-comments" rel="nofollow">PEP-484</a>):</p>
<pre><code>response = requests.get("url")
data2 = r... | 2 | 2016-09-05T16:02:49Z | [
"python",
"dictionary",
"pycharm"
] |
Why doesn't Pycharm show dictionary methods in this case? | 38,948,132 | <p>I am trying to do a very simple service to collect and print data from a RESTfull API, in Python.
This is the code I have:</p>
<pre><code>import requests
import json
response = requests.get("url")
data2 = response.json()
print type(data2)
</code></pre>
<p>Here is my issue: when I print data2 type, it tells me it'... | 1 | 2016-08-15T01:19:45Z | 39,334,842 | <p>PyCharm's inability to display the methods you mention indicate inability to infer the variable's type from the code alone. Which often indicates that the code might not be prepared to handle that variable's data properly in all cases (in many cases that means buggy code).</p>
<p>The fact that your code prints the ... | 0 | 2016-09-05T16:51:05Z | [
"python",
"dictionary",
"pycharm"
] |
Fill django-tables2 with "special" queryset | 38,948,143 | <p>I'm trying django-tables2 to display some data, it looks like a nice tool, but I can't figure out how to use a queryset that uses fields from more than one model, at least not in an easy way. I built a queryset that shows data of five models, is the next:</p>
<pre><code>resultado=Producto.objects.filter(codigobarra... | 0 | 2016-08-15T01:21:53Z | 38,948,618 | <p>I figured out, the same elements that I wrote inside "values", I used them in "field" definitions of the meta class of the table.</p>
| 0 | 2016-08-15T02:40:15Z | [
"python",
"django"
] |
Python MySQL queries time out where MySQL workbench works fine | 38,948,144 | <p>I recently had my website moved to a new server. I have some basic python scripts with access data in a MySQL database. On the old server we had no problems. On the new server :</p>
<ul>
<li>MySQLWorkbench can connect no trouble and perform all queries</li>
<li>The same (SELECT) queries with python work 5% of the t... | 3 | 2016-08-15T01:21:53Z | 39,007,790 | <p>You might get better performance using a server side cursor:</p>
<pre><code>import MySQLdb.cursor
con = MySQLdb.connect(host=host,
user=user,
passwd=pwd,
charset=charset,
port=port,
cursorclass=MySQLdb.cursors.SSDictCursor);
... | 2 | 2016-08-17T23:33:02Z | [
"python",
"mysql",
"mysql-workbench",
"mysql-connector-python"
] |
Position of widgets in GridLayout | 38,948,174 | <p>I'm trying to create a grid of widgets with each "cell" widget having a rectangle I can change the color of later. When I run the code below with the line <code>grid.add_widget(Button(text=str(i)))</code> the buttons fill the window (as in the docs). However, when I use my <code>Cell</code> widget as in <code>grid... | 4 | 2016-08-15T01:30:16Z | 38,959,832 | <p>I will show an example on how you can achieve this.
I will create a grid class, and add the cell widgets to it.
But I will only use one canvas (the gridlayouts canvas).
So the cell class will contain an <a href="https://kivy.org/docs/api-kivy.graphics.instructions.html" rel="nofollow">InstructionGroup</a>, rather th... | 1 | 2016-08-15T17:23:37Z | [
"python",
"kivy"
] |
Python Selenium with Chrome. How to switch between different tabs | 38,948,190 | <p>I click a button which opens a new tab. How to I then navigate around the new tab?</p>
<p>This sounds like a simple task but after several hours trying to find a solution I'm not any closer. Is there a simple way of doing this?</p>
<p>Tried using keys for CONTROL + 'T' and read other suggestions but nothing seems ... | 0 | 2016-08-15T01:32:43Z | 39,149,217 | <p>I just implemented my solution and it worked for my case, which looks very similar to yours.</p>
<p>First you need to check the <code>window_handles</code>:</p>
<pre><code>len(driver.window_handles) > 1
</code></pre>
<p>If you have more than one, you can try to switch to your second handler:</p>
<pre><code>dr... | 0 | 2016-08-25T15:28:36Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start ... | 0 | 2016-08-15T01:45:25Z | 38,948,305 | <p>Use the python built in 'reduce' like below. Also what you want can be achieved when you start from 1 and iterate till 6.</p>
<pre><code>reduce(lambda x, y: x+y, range(1, 6))
</code></pre>
| 1 | 2016-08-15T01:51:30Z | [
"python"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start ... | 0 | 2016-08-15T01:45:25Z | 38,948,308 | <p>This could be done with a 1 liner but i'll help you out with a solution in the format that you're attempting.</p>
<pre><code>def sum_nums(number):
total = 0
for i in range(number + 1):
total += i
print total
</code></pre>
<p>Input <code>5</code></p>
<p>Output <code>15</code></p>
<p>Also, some... | 0 | 2016-08-15T01:52:16Z | [
"python"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start ... | 0 | 2016-08-15T01:45:25Z | 38,948,349 | <p>You can do this in a one liner with:</p>
<pre><code>def sum_range_inclusive(number):
return sum(range(number + 1))
</code></pre>
<p>To break this down:</p>
<pre><code># assume number is 5 for now
number = 5
# exclusive, doesn't include the number
range(number)
# returns [0, 1, 2, 3, 4]
# inclusive, incl... | 1 | 2016-08-15T01:59:23Z | [
"python"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start ... | 0 | 2016-08-15T01:45:25Z | 38,948,391 | <p>This question would be amiss if someone didn't mention that <code>sum(range(n))</code> is always <code>n*(n-1)/2</code>. If you wish to do this inclusive of the value <code>n</code>, the expressions are <code>sum(range(n+1))</code> and <code>n*(n+1)/2</code>.</p>
| 2 | 2016-08-15T02:06:21Z | [
"python"
] |
how to work around yahoo data issue? Not enough volume to fill | 38,948,348 | <p>I am working on a MACD strategy backtest, and sometimes I came across this warning:</p>
<pre><code>2015-02-19 00:00:00 broker.backtesting [DEBUG] Not enough volume to fill 1988.HK market order [1] for 55258 share/s
Then I checked the csv data source and found:
Date Open High Low Close Volume Adj Cl... | 0 | 2016-08-15T01:59:20Z | 38,964,948 | <p>Try this in the strategy constructor:</p>
<pre><code>self.getBroker().getFillStrategy().setVolumeLimit(None)
</code></pre>
| 0 | 2016-08-16T00:33:10Z | [
"python",
"pyalgotrade"
] |
Using shift operator for LFSR in python | 38,948,430 | <p>Let's say I want to write a 16bit linear feedback shift register LFSR in Python using its native shift operator.</p>
<ol>
<li>Does the operator itself have a feature to specify the bit to shifted into the new MSB position? </li>
<li>Does the operator have a carry flag or the like to catch the LSB falling out of the... | 0 | 2016-08-15T02:12:34Z | 38,948,543 | <p>Python does not have registers and you cannot declare the type of anything. </p>
<p>The shift operators operate on unlimited-precision integers. If you shift left, the number will continue to get larger indefinitely (or until out of memory). If you shift right, the least-significant bit is dropped as you would expe... | 0 | 2016-08-15T02:29:13Z | [
"python",
"bit-shift"
] |
Parsing string as boolean? | 38,948,483 | <p>Is it possible to parse a string in a <code>if</code> statement as a string? Something like</p>
<pre><code>if "1 > 2":
print "1 is greater than 2"
</code></pre>
<p>But is parsed as</p>
<pre><code>if 1 > 2:
print "1 is greater than 2"
</code></pre>
<p>Is this possible? Is the a program out there tha... | 1 | 2016-08-15T02:19:20Z | 38,948,537 | <p>That's what <code>eval</code> is for.</p>
<pre><code>if eval("1 > 2"):
print "1 is greater than 2"
</code></pre>
<p>Be careful with <code>eval</code>, though. It will call <em>any</em> function supplied to it. Like <code>os.system('rm -rf /')</code> :/</p>
| 3 | 2016-08-15T02:28:17Z | [
"python",
"string",
"boolean"
] |
Parsing string as boolean? | 38,948,483 | <p>Is it possible to parse a string in a <code>if</code> statement as a string? Something like</p>
<pre><code>if "1 > 2":
print "1 is greater than 2"
</code></pre>
<p>But is parsed as</p>
<pre><code>if 1 > 2:
print "1 is greater than 2"
</code></pre>
<p>Is this possible? Is the a program out there tha... | 1 | 2016-08-15T02:19:20Z | 38,949,050 | <p>If you are only comparing numerical values this approach would be safer in general.</p>
<p>This could also be made to work for non-numerical values.</p>
<pre><code>from operator import gt, ge, lt, le, eq, ne
def compare(expression):
parts = expression.split()
if len(parts) != 3:
raise Exception("C... | 0 | 2016-08-15T03:47:05Z | [
"python",
"string",
"boolean"
] |
pip and and installing mysql-python. | 38,948,496 | <p>I'm trying to install MySQL-Python through pip with pip <code>install MySQL-Python</code>. But I'm getting a couple of error messages. Here's the console log:</p>
<pre><code>C:\WINDOWS\system32>pip install mysql-python
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected pa... | 0 | 2016-08-15T02:21:10Z | 38,948,830 | <p>It seems your pip version is outdated. </p>
<ol>
<li><p>So first do <code>python -m pip install --upgrade pip</code></p></li>
<li><p>Then use your downloaded wheel, but do <code>python3 -m pip install [.whl_location]</code> if python3 is in your path, else navigate to python3 folder and do the same.</p></li>
</ol>
... | 1 | 2016-08-15T03:13:21Z | [
"python"
] |
How to change locals() result from other function? | 38,948,541 | <p>I have some code like this:</p>
<pre><code>def f():
i = 5
g(locals())
print 'in f:', i, j
def g(env):
env['j'] = env['i'] + 1
print 'in g:', env['i'], env['j']
f()
</code></pre>
<p>I get:</p>
<pre><code>in g: 5 6
in f: 5------------------------------------------------------------------------... | -2 | 2016-08-15T02:28:48Z | 38,948,604 | <p>According to the <a href="https://docs.python.org/2/library/functions.html#locals" rel="nofollow">docs</a> regarding <code>locals</code>:</p>
<blockquote>
<p>Note The contents of this dictionary should not be modified; changes
may not affect the values of local and free variables used by the
interpreter.</p>
... | 3 | 2016-08-15T02:37:59Z | [
"python",
"python-2.7",
"function",
"scope",
"local-variables"
] |
PySpark LogisticRegressionWithLBFGS Import error | 38,948,617 | <p>I am trying to use the pysoark LogisticRegression library.Below is part of my code:</p>
<pre><code> from pyspark.mllib.linalg import Vectors
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel, LogisticRegressio... | 1 | 2016-08-15T02:40:08Z | 38,952,426 | <p>I'd say your version of pyspark is outdated.</p>
<p>Try :</p>
<pre><code>pip freeze | grep pyspark
</code></pre>
<p><code>LogisticRegressionWithLBFGS</code> class was introduced in pyspark 1.2.0.</p>
<p>To upgrade your version of pyspark you can use <code>pip</code> as well :</p>
<pre><code>pip install pyspark ... | 0 | 2016-08-15T09:19:21Z | [
"python",
"machine-learning",
"pyspark",
"logistic-regression"
] |
Call variable into a sqlite row | 38,948,729 | <p>I have a python script that reads a conf file and prints out matches. <br>These matches are all stored in a varialbe. <br>
I want to be able to insert the values into a sqlite table.. <br>
<br>
File reads: <br>
Hello Asia <br>
World Mumbai <br>
Hello America <br>
World Chicargo <br>
Hello Australia <br>
World Sydney... | 1 | 2016-08-15T02:58:14Z | 38,949,546 | <p>The syntax to insert values from Python variables is as follows:</p>
<pre><code>cur.execute("INSERT INTO table1 (`Continent`,`City`) VALUES (?,?)",(Continent,City));
</code></pre>
<p><code>?</code> represents a parameter and the second argument of the <code>execute</code> function is an iterable (tuple, list) of y... | 0 | 2016-08-15T05:02:14Z | [
"python",
"sql",
"sqlite"
] |
python append folder name to filenames in all sub folders | 38,948,774 | <p>I am trying to append the name of a folder to all filenames within that folder. I have to loop through a parent folder that contain sub folders. I have to do this in Python and not a bat file.</p>
<p>Example is, take these folders:</p>
<pre><code>Parent Folder
Sub1
example01.txt
example01.jpg
example01.tif
... | 0 | 2016-08-15T03:05:51Z | 38,948,934 | <p>You can use <a href="https://docs.python.org/3.5/library/os.html#os.walk" rel="nofollow"><code>os.walk</code></a> to iterate over the directories and then <a href="https://docs.python.org/3.5/library/os.html#os.rename" rel="nofollow"><code>os.rename</code></a> to rename all the files:</p>
<pre><code>from os import ... | 0 | 2016-08-15T03:29:53Z | [
"python",
"file-processing"
] |
python append folder name to filenames in all sub folders | 38,948,774 | <p>I am trying to append the name of a folder to all filenames within that folder. I have to loop through a parent folder that contain sub folders. I have to do this in Python and not a bat file.</p>
<p>Example is, take these folders:</p>
<pre><code>Parent Folder
Sub1
example01.txt
example01.jpg
example01.tif
... | 0 | 2016-08-15T03:05:51Z | 38,948,949 | <p>I would use <code>os.path.basename</code> on the root to find your prefix.</p>
<pre><code>import os
for root, dirs, files in os.walk("Parent"):
if not files:
continue
prefix = os.path.basename(root)
for f in files:
os.rename(os.path.join(root, f), os.path.join(root, "{}_{}".format(prefi... | 1 | 2016-08-15T03:32:31Z | [
"python",
"file-processing"
] |
Python BeautifulSoup Referencing Tag with space in XML tag | 38,948,813 | <p>Apologies for my poorly formatted post and written code, first post! I'm sure this is a simple fix but cannot seem to figure it out.</p>
<p>Question 1: I'm Writing an XML scraper for an Eve Online API. I have a need to iterate on an HTML tag that has a space in it (<code>type id="X"</code>) with <code>*BeautifulSou... | -1 | 2016-08-15T03:10:55Z | 38,948,983 | <p><code>type id=</code> is not a tag. The tag name of the element is <code>type</code> and <code>id</code> is an <em>attribute</em> of that element.</p>
<pre><code>for item in Data.find_all('type'):
print item.get('id')
</code></pre>
<p>For the URL that you reference this code will output:</p>
<pre>
34
35
</pre... | 1 | 2016-08-15T03:36:58Z | [
"python",
"xml",
"beautifulsoup",
"lxml"
] |
Python BeautifulSoup Referencing Tag with space in XML tag | 38,948,813 | <p>Apologies for my poorly formatted post and written code, first post! I'm sure this is a simple fix but cannot seem to figure it out.</p>
<p>Question 1: I'm Writing an XML scraper for an Eve Online API. I have a need to iterate on an HTML tag that has a space in it (<code>type id="X"</code>) with <code>*BeautifulSou... | -1 | 2016-08-15T03:10:55Z | 38,953,311 | <p>You have a couple of issues, you seem to be mixing up <em>bs4</em> and <em>lxml</em> syntax, <em>iter</em> is an lxml method, <em>type</em> is the node and <em>id</em> is an attribute of the node.</p>
<p>Since you are using lxml just forget about bs4 and getting the data is quite simple:</p>
<pre><code>from lxml i... | 0 | 2016-08-15T10:21:49Z | [
"python",
"xml",
"beautifulsoup",
"lxml"
] |
Shifting the location of tensor3 elements based on an offset vector | 38,948,862 | <p>I have a Theano <code>tensor3</code> (i.e., a 3-dimensional array) <code>x</code>:</p>
<pre><code>[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
</code></pre>
<p>as well as a Theano vector (i.e., a 1-dimensional array) <code>y</code>, which we will refer as an "... | 0 | 2016-08-15T03:19:34Z | 38,980,184 | <p>I couldn't find any dedicated function for that purpose, so I simply ended up using <a href="http://deeplearning.net/software/theano/tutorial/loop.html" rel="nofollow"><code>theano.scan</code></a>:</p>
<pre><code>import theano
import theano.tensor
from theano import shared
import numpy as np
y = shared(np.array([... | 0 | 2016-08-16T16:37:32Z | [
"python",
"multidimensional-array",
"theano"
] |
Import csv to django model using csvImporter | 38,948,917 | <p>I am trying to import data from a csv file to a django model. I found <a href="http://stackoverflow.com/questions/2459979/how-to-import-csv-data-into-django-models">this</a> thread, which lead me to the documentation for <a href="http://django-csv-importer.readthedocs.io/en/latest/" rel="nofollow">CSVImporter</a>. S... | 1 | 2016-08-15T03:27:25Z | 38,949,109 | <p>This syntax is incompatible with python 3. The correct syntax in Python3 is </p>
<pre><code>except ValueError as e:
...
</code></pre>
<p>This library doesn't support python 3, but exists pull request to make support <a href="https://github.com/anthony-tresontani/csv_importer/pulls" rel="nofollow">https://githu... | 1 | 2016-08-15T03:56:32Z | [
"python",
"django",
"csv-import"
] |
Get the selected text content from other programs | 38,948,947 | <p>When I am using other programs (e.g. opening a pdf or word), I will select some text contents (like a word or paragraph) by using the mouse. I want my python program to get this text content. How to do this using PyQt, or some other Python library?</p>
| -1 | 2016-08-15T03:32:05Z | 38,963,809 | <p>This is an easy task, you haven't specified the pyqt version, so I'll post the solution for PyQt4, here you go:</p>
<pre><code>from PyQt4.QtCore import QObject, pyqtSlot, SIGNAL, SLOT
from PyQt4.QtGui import QApplication, QMessageBox
import sys
class MyClipboard(QObject):
@pyqtSlot()
def changedSlot(self... | 0 | 2016-08-15T22:09:41Z | [
"python",
"linux",
"pyqt",
"clipboard"
] |
How do I make part of the script asynchronous with dask? | 38,948,956 | <p>Suppose I am given a collection of documents. I am required to tokenize them, and then turn them into vectors for further work. As I find elasticsearch's tokenizer works much better than my own solution, I am switching to that. However, it is considerably slower. Then the end result is expected to be fed into the ve... | 1 | 2016-08-15T03:33:23Z | 38,949,233 | <p>Using just <code>concurrent.futures</code> for the work</p>
<pre><code>from concurrent.futures import ProcessPoolExecutor
def loader():
conn = psycopg2.connect()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute('''
SELECT document, ... FROM ...
'... | 1 | 2016-08-15T04:12:10Z | [
"python",
"python-3.x",
"dask"
] |
How do I make part of the script asynchronous with dask? | 38,948,956 | <p>Suppose I am given a collection of documents. I am required to tokenize them, and then turn them into vectors for further work. As I find elasticsearch's tokenizer works much better than my own solution, I am switching to that. However, it is considerably slower. Then the end result is expected to be fed into the ve... | 1 | 2016-08-15T03:33:23Z | 38,975,189 | <p>A simple solution would be to load data locally on your machine (it's hard to partition a single SQL query) and then send the data to the dask-cluster for the expensive tokenization step. Perhaps something as follows:</p>
<pre><code>rows = cur.execute(''' SELECT document, ... FROM ... ''')
from toolz import parti... | 1 | 2016-08-16T12:39:28Z | [
"python",
"python-3.x",
"dask"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></p... | 0 | 2016-08-15T03:37:23Z | 38,949,122 | <p>you can modify this a bit for accepting input from a text file</p>
<pre><code>var letterArray = "asdf\njkasdf\nthe\nsadf".split('\n');
function count(letterArray) {
let mapping = {};
for (let i=0; i < letterArray.length; i++){
if (mapping[letterArray[i]] !== undefined){ // if the letter alread... | 0 | 2016-08-15T03:58:15Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></p... | 0 | 2016-08-15T03:37:23Z | 38,949,141 | <p>I used python approach to get what you expected</p>
<pre><code>import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
def wordcount(data):
cv = CountVectorizer(min_df=0, strip_accents="ascii", decode_error ="ignore")
counts = cv.fit_transform([data]).toarray().ravel()
words = n... | 0 | 2016-08-15T04:00:32Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></p... | 0 | 2016-08-15T03:37:23Z | 38,949,164 | <p>I'd recommend doing this is java. It has better tools than javascript, but this can also be done in javascript. Load the whole list into an array. Then use a sort method to sort the entire list. In js its just .sort(). This will put words that are the same next to each other in the list. Then use a loop to wal... | -2 | 2016-08-15T04:03:39Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></p... | 0 | 2016-08-15T03:37:23Z | 38,949,183 | <p>In Node.js and after doing <code>npm i split2 through2 -S</code></p>
<pre><code>const fs = require('fs')
const split = require('split2')
const through = require('through2')
const words = {}
fs.createReadStream('words.txt')
.pipe(split())
.pipe(through(write, end))
function write (buf, enc, next) {
const w... | 5 | 2016-08-15T04:05:53Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></p... | 0 | 2016-08-15T03:37:23Z | 38,957,792 | <p>You can use <code>Counter</code> from <code>collections</code> module for that:</p>
<pre><code>content = open("textfile.txt").read()
from collections import Counter
c = Counter(content.splitlines())
for x in c.most_common():
print("{}: {} times".format(x[0], x[1]))
</code></pre>
<p>Usage:</p>
<pre><code>In [7... | 0 | 2016-08-15T15:09:11Z | [
"javascript",
"python"
] |
creating a dictionary of words in string whose values are words following that word | 38,948,999 | <p>I would like to create a dictionary from a text file using each unique word as a key and a a dictionary of the words that follow the key with the count of that word as the value. For example something that looks like this:</p>
<pre><code>>>>string = 'This is a string'
>>>word_counts(string)
{'this... | 0 | 2016-08-15T03:38:14Z | 38,949,059 | <p>You can make use of <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow"><code>Counter</code></a> to achieve what you want:</p>
<pre><code>from collections import Counter, defaultdict
def get_tokens(string):
return string.split() # put whatever token-parsing algorithm yo... | 1 | 2016-08-15T03:48:51Z | [
"python",
"dictionary",
"word-count"
] |
creating a dictionary of words in string whose values are words following that word | 38,948,999 | <p>I would like to create a dictionary from a text file using each unique word as a key and a a dictionary of the words that follow the key with the count of that word as the value. For example something that looks like this:</p>
<pre><code>>>>string = 'This is a string'
>>>word_counts(string)
{'this... | 0 | 2016-08-15T03:38:14Z | 38,949,102 | <p>Actually, the <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow"><code>collections.Counter</code></a> class isn't always the best choice to count something. You can use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>c... | 2 | 2016-08-15T03:55:09Z | [
"python",
"dictionary",
"word-count"
] |
creating a dictionary of words in string whose values are words following that word | 38,948,999 | <p>I would like to create a dictionary from a text file using each unique word as a key and a a dictionary of the words that follow the key with the count of that word as the value. For example something that looks like this:</p>
<pre><code>>>>string = 'This is a string'
>>>word_counts(string)
{'this... | 0 | 2016-08-15T03:38:14Z | 38,949,156 | <p>Just to give an alternative option (I imagine the other answers are more suitable for your needs) you could use the <code>pairwise</code> recipe from <code>itertools</code>:</p>
<pre><code>from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)... | 0 | 2016-08-15T04:02:04Z | [
"python",
"dictionary",
"word-count"
] |
Linear and Quadratic terms in CPLEX Objective Function | 38,949,055 | <p>I would like to minimize an objective function which is rather simple, but I am somehow having problems making the correct calls to from the Python API to CPLEX</p>
<p>I looked at how to use <code>set_quadratic</code> and <code>set_quadratic_coefficients</code> <a href="http://www.ibm.com/support/knowledgecenter/SS... | 0 | 2016-08-15T03:48:12Z | 38,959,192 | <p>If you're calling <code>set_quadratic</code> with a quadratic objective function that is separable, it corresponds to <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refcallablelibrary/qpapi/copyqpsep.html?pos=3" rel="nofollow">CPXXcopyqpsep</a>. If you're calling <code>set_qu... | 1 | 2016-08-15T16:39:23Z | [
"python",
"linear-programming",
"cplex",
"quadratic-programming"
] |
Linear and Quadratic terms in CPLEX Objective Function | 38,949,055 | <p>I would like to minimize an objective function which is rather simple, but I am somehow having problems making the correct calls to from the Python API to CPLEX</p>
<p>I looked at how to use <code>set_quadratic</code> and <code>set_quadratic_coefficients</code> <a href="http://www.ibm.com/support/knowledgecenter/SS... | 0 | 2016-08-15T03:48:12Z | 38,960,501 | <p>I solved the problem by adding the quadratic terms first, setting their coefficients, and then adding the linear terms in a separate call see below.</p>
<pre><code>problem.objective.set_sense(problem.objective.sense.minimize)
varLower = [0]*len(target.v)
varNames = ["s%s"%x for x in range( len(target.v) )]
proble... | 0 | 2016-08-15T18:07:33Z | [
"python",
"linear-programming",
"cplex",
"quadratic-programming"
] |
How to submit a POST request to the Calls resource? (making outgoing calls in Twilio) | 38,949,066 | <p>I'm having trouble with making outgoing calls using Twilio and I believe I skipped this step where I should submit a POST request to the Calls resource. I don't really understand what to do with this and I need someone to explain it for me since I'm just a beginner. And by the way, my Twilio account is just free tri... | 0 | 2016-08-15T03:50:07Z | 38,952,309 | <p>Twilio developer evangelist here.</p>
<p>Best place for you to start would be the <a href="https://www.twilio.com/docs/quickstart/python/rest" rel="nofollow">Python making calls quick start</a>. Follow that tutorial through and you should understand how to make a call with Python.</p>
<p>Though, as you say, the ke... | 0 | 2016-08-15T09:11:39Z | [
"python",
"twilio",
"twilio-click-to-call"
] |
Overriding get_queryset leads to caching headache in ListView, where data remains stale | 38,949,071 | <p>Could someone explain why overriding <code>get_queryset</code> and referencing the queryset via <code>self</code> completely caches the page? I need to wait 5 minutes or more before updates made to the database display.</p>
<p>I'm trying to save a temporary value to the each object and pass it to the template.</p>
... | 1 | 2016-08-15T03:50:44Z | 38,950,201 | <p>The behavior you're seeing is how Python evaluates your code. Below is a simplified example that explains what you're seeing.</p>
<pre><code>import random
class Example1(object):
roll = random.randint(1, 6) # this is evaluated immediately!
def get_roll(self):
return self.roll
ex1 = Example1()
# t... | 1 | 2016-08-15T06:22:20Z | [
"python",
"django",
"django-templates",
"django-queryset"
] |
python lxml.html.soupparser.fromstring raising annoying warning | 38,949,091 | <p>My code...</p>
<pre><code>foo = fromstring(my_html)
</code></pre>
<p>it raises this warning...</p>
<pre><code>UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or i... | 3 | 2016-08-15T03:52:35Z | 38,950,833 | <p>You can pass the <em>features</em> keyword which will set the parser.</p>
<pre><code>tree = lxml.html.soupparser.fromstring("<p>foo</p>", features="html.parser" )
</code></pre>
<p>What happens in <em>fromstring</em> is <em>_parser</em> gets called but I think there is a bug in the line <em>bsargs['feat... | 3 | 2016-08-15T07:20:00Z | [
"python",
"beautifulsoup",
"lxml"
] |
Why does running `airflow clear` using the -t option raise a thread error? | 38,949,147 | <p>I've constructed an Airflow DAG with default settings as the tutorial. When I run the DAG, some tasks failed. When I attempt to clear the failed tasks using <code>airflow clear my_dag -s 2016-08-03 -t my_task_name -fd</code>, I get the following exception:</p>
<pre><code>TypeError: object.__new__(thread.lock) is no... | -1 | 2016-08-15T04:01:26Z | 38,963,444 | <p>Don't use deepcopy (it is almost always certainly wrong). deepcopy will copy all referred to objects; in this case your object graph has some locks; they are not copiable by deepcopy and thus you get the error.</p>
<p><a href="http://stackoverflow.com/questions/29267261/object-new-thread-lock-is-not-safe-use-thread... | 0 | 2016-08-15T21:36:35Z | [
"python",
"airflow"
] |
Why does running `airflow clear` using the -t option raise a thread error? | 38,949,147 | <p>I've constructed an Airflow DAG with default settings as the tutorial. When I run the DAG, some tasks failed. When I attempt to clear the failed tasks using <code>airflow clear my_dag -s 2016-08-03 -t my_task_name -fd</code>, I get the following exception:</p>
<pre><code>TypeError: object.__new__(thread.lock) is no... | -1 | 2016-08-15T04:01:26Z | 38,964,621 | <p>Looks like this is an open issue for Airflow: <a href="https://issues.apache.org/jira/browse/AIRFLOW-351" rel="nofollow">https://issues.apache.org/jira/browse/AIRFLOW-351</a></p>
| 0 | 2016-08-15T23:45:36Z | [
"python",
"airflow"
] |
How to create a code that will append items to a list in python | 38,949,161 | <p>Hi I am trying to create a code that will append items to a list in python through the program itself inside of terminal. </p>
<p>Whenever I use this code it works but when I stop running the code and rerun the new item in the list is gone.</p>
<p>This is currently my code. 'Calc' is a list that has multiple strin... | -2 | 2016-08-15T04:03:24Z | 38,949,201 | <p>When you re-run, the list is re-initiazing and clearing itself. </p>
<p>One way to save the contents of the list for multiple runs of the code would be to write the contents of the list to a text file and save that. </p>
<p>You can read <a href="http://www.pythonforbeginners.com/files/reading-and-writing-files-in-... | 1 | 2016-08-15T04:08:30Z | [
"python"
] |
pandas DataFrame sort rows by duplicate | 38,949,190 | <p>How can I sort a DataFrame so that rows in the duplicate column are "recycled". </p>
<p>For example, my original DataFrame looks like this:</p>
<pre><code>In [3]: df
Out[3]:
A B
0 r1 0
1 r1 1
2 r2 2
3 r2 3
4 r3 4
5 r3 5
</code></pre>
<p>I would like it to turn to:</p>
<pre><code>In [3]: df_sort... | 3 | 2016-08-15T04:06:35Z | 38,949,542 | <p>You can formulate your need as taking the first row of each group, then the second line, then the thrid, etc. So this is equivalent to group your results by row per group and then per <code>'A'</code> .</p>
<p>You can number your rows per key in <code>'A'</code> with the function <a href="http://pandas.pydata.org/... | 4 | 2016-08-15T05:01:48Z | [
"python",
"sorting",
"pandas",
"dataframe",
"duplicates"
] |
pandas DataFrame sort rows by duplicate | 38,949,190 | <p>How can I sort a DataFrame so that rows in the duplicate column are "recycled". </p>
<p>For example, my original DataFrame looks like this:</p>
<pre><code>In [3]: df
Out[3]:
A B
0 r1 0
1 r1 1
2 r2 2
3 r2 3
4 r3 4
5 r3 5
</code></pre>
<p>I would like it to turn to:</p>
<pre><code>In [3]: df_sort... | 3 | 2016-08-15T04:06:35Z | 38,949,547 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> for counting duplicates in column <code>A</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="... | 2 | 2016-08-15T05:02:29Z | [
"python",
"sorting",
"pandas",
"dataframe",
"duplicates"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r... | -1 | 2016-08-15T04:10:19Z | 38,949,300 | <p>I think the problem is that you are changing the value of variable <code>l</code> instead of the <code>line1</code> in <code>lst</code> or variable <code>l1</code> itself. Following codes should help you do the trick:</p>
<pre><code>lst = [line1,line2,line3,line4,line5,line6,line7]
for i in range(len(lst)):
lst[... | 0 | 2016-08-15T04:24:46Z | [
"python"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r... | -1 | 2016-08-15T04:10:19Z | 38,949,361 | <p>Changing the string in the for-loop won't change the <code>line1</code> variable. Also, you should probably find a better way to read from the file in the first place which could help you to avoid this problem. I suggested one way below but there are numerous other ways you can accomplish essentially the same thing.... | 0 | 2016-08-15T04:33:12Z | [
"python"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r... | -1 | 2016-08-15T04:10:19Z | 38,949,373 | <p>Basically, you're overwriting a temporary variable (line) which only exists in the scope of the loop, so you're not seeing any changes to your other variables (line1, line2, etc.). So you need to store the replaced values in a separate list outside the loop, like so:</p>
<pre><code>replacedLines = []
for line in ls... | 0 | 2016-08-15T04:35:00Z | [
"python"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r... | -1 | 2016-08-15T04:10:19Z | 38,949,375 | <p>I ended up fixing it thanks to Evert and cuongnv</p>
<pre><code>f = open("Exiting.txt","r") #opens the exitng.txt which has 7 lines
line1 = (f.readline())
line2 = (f.readline())
line3 = (f.readline())
line4 = (f.readline())
line5 = (f.readline())
line6 = (f.readline())
line7 = (f.readline())
f.close()
ext = input(... | 0 | 2016-08-15T04:35:20Z | [
"python"
] |
Selenium. Upload a file on a new chrome open file pop up (or how to simulate ctrl+v on python) | 38,949,261 | <p>Im doing a python selenium script for chrome webdriver, and I need to upload a file. When I hit the upload buttom, a open file dialog pops up, and I haven't been able to actually upload the file. Aproaches I have tried: </p>
<p>Using selenium ide, and recording me uploading the file. It yeilds this result:</p>
<pr... | 1 | 2016-08-15T04:17:58Z | 38,949,325 | <p>Try following code:</p>
<pre><code>driver.find_element_by_xpath("//input[@type='file']").clear()
driver.find_element_by_xpath("//input[@type='file']").send_keys("/path/to/file")
</code></pre>
<p>This should work if there is only one button for file uploading. </p>
<p>Also you can try this <code>XPath</code>:</p>
... | 1 | 2016-08-15T04:28:31Z | [
"python",
"selenium",
"keyboard"
] |
TypeError: a float is required PYTHON | 38,949,294 | <p>My current python script:</p>
<pre><code>import ftplib
import hashlib
import httplib
import pytz
from datetime import datetime
import urllib
from pytz import timezone
import os.path, time
import glob
def ftphttp():
dataset_path='Desktop'
files = glob.glob(dataset_path+"/images/*.png")
ts = files.sort(key=... | 0 | 2016-08-15T04:24:02Z | 38,949,493 | <p>This occurs because the function glob.glob, returns an array of strings, and you are trying to pass this result to "datetime.fromtimestamp" function, that expects a number. </p>
<p>Any moment you "store" the modified date, to use after.</p>
<p>You needs to manipulate the files one by one. Example (I didn't test):<... | 1 | 2016-08-15T04:55:03Z | [
"python",
"python-2.7"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in<... | 0 | 2016-08-15T04:25:15Z | 38,949,414 | <p>You can do this by performing a <code>sum</code> on a list comprehension that collects all the "scores":</p>
<pre><code>sum( [x['score'] for x in MyListOfDictionaries] )
</code></pre>
<p>(PS. Numpy is not necessary here)
<br></p>
<p><br>
<strong><em>Edit:</em></strong> as pointed out by @sebastian in the comments... | 2 | 2016-08-15T04:42:06Z | [
"python",
"numpy",
"dictionary"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in<... | 0 | 2016-08-15T04:25:15Z | 38,949,689 | <p><code>NumPy</code> is a library for numerical arrays processing. You use numbers as columns names, convert your collection to matrix and use <code>NumPy</code> to make your calculations if you want to use exactly <code>NumPy</code> and its performance.</p>
<p>I suggest you to try <a href="http://pandas.pydata.org/"... | 0 | 2016-08-15T05:22:16Z | [
"python",
"numpy",
"dictionary"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in<... | 0 | 2016-08-15T04:25:15Z | 38,949,821 | <pre><code>In [1963]: ll=[{
...: 'name': 'John',
...: 'score': 30
...: }, {
...
...: }]
</code></pre>
<p>First the obvious iterative solution</p>
<pre><code>In [1965]: sum([d['score'] for d in ll])
Out[1965]: 87
</code></pre>
<p>I can turn it into an object array with:</p>
<pre><code>In [1966]: np.arr... | 2 | 2016-08-15T05:38:21Z | [
"python",
"numpy",
"dictionary"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in<... | 0 | 2016-08-15T04:25:15Z | 38,954,749 | <pre><code>lst = [{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
sum(map(lambda x: x['score'], lst))
</code></pre>
| 1 | 2016-08-15T12:04:47Z | [
"python",
"numpy",
"dictionary"
] |
Find the nth time a specific value is exceeded in numpy array | 38,949,308 | <p>This is an extension of the question asked here:
<a href="http://stackoverflow.com/questions/16243955/numpy-first-occurence-of-value-greater-than-existing-value">Numpy first occurence of value greater than existing value</a></p>
<pre><code>N = 10000
aa = np.arange(-N,N)
</code></pre>
<p>In this numpy array, I want... | 1 | 2016-08-15T04:25:52Z | 38,949,335 | <p>You can work from the same principles as the "first time" case, just with a slightly more complicated middle step.</p>
<p>Start with the boolean array representing your condition:</p>
<pre><code>cond = aa > 0
</code></pre>
<p>Convert the True/False values in the array to counts:</p>
<pre><code>counts = np.cum... | 2 | 2016-08-15T04:29:49Z | [
"python",
"arrays",
"numpy"
] |
(Python code not working in loop) pandas.DataFrame.apply() not working in loop | 38,949,320 | <p>I have a piece of code which works fine alone, but when I put it in loop (or use <code>df.apply()</code> method), it does not work.
The code is:</p>
<pre><code>import pandas as pd
from functools import partial
datadf=pd.DataFrame(data,columns=['X1','X2'])
for i in datadf.index.values.tolist():
row=datadf.loc[i]... | 2 | 2016-08-15T04:27:27Z | 38,951,306 | <p>Probably because there're multiple definitions of <code>row</code>, one as an argument of the function <code>def idlist1(row,var1):</code> and one defined as <code>row=datadf.loc[i]</code>, you can try to rename one and see if it helps.</p>
| 1 | 2016-08-15T07:55:40Z | [
"python",
"loops",
"pandas"
] |
Code doesnt print anything | 38,949,350 | <pre><code># -*- coding: utf-8 -*-
"""
fill-in-the-blanks1.py
"""
# -*- coding: utf-8 -*-
"""
p1
"""
level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can a... | 0 | 2016-08-15T04:31:46Z | 38,949,506 | <p>The only issue was you were using if level == "1": , replace it with if level == 1: and it worked.</p>
<pre><code> """
fill-in-the-blanks1.py
"""
# -*- coding: utf-8 -*-
"""
p1
"""
level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be
called out ... | 0 | 2016-08-15T04:57:11Z | [
"python",
"printing"
] |
Code doesnt print anything | 38,949,350 | <pre><code># -*- coding: utf-8 -*-
"""
fill-in-the-blanks1.py
"""
# -*- coding: utf-8 -*-
"""
p1
"""
level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can a... | 0 | 2016-08-15T04:31:46Z | 38,949,620 | <p>When you get over the hurdle of making level 1 work, I believe the structure of your program makes it difficult to get the other levels to work as well without a lot of redundant code. I've reworked it a bit below to enable the other levels -- see if this gives you any ideas with respect to moving forward with your... | 1 | 2016-08-15T05:13:14Z | [
"python",
"printing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.