Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
8,200 | 29,653,162 | Difference between memory usage when importing modules | <p>I'd like to know whats is the difference between the memory usage when importing modules in these ways:</p>
<pre><code>import Mod1
from Mod1 import *
from Mod1 import a,b,c
</code></pre>
<p>Mainly between the first two.</p> | <p>The first uses the least memory since it only creates a single name in the module scope.</p>
<p>The second uses the most (assuming <code>Mod1</code> contains more than just <code>a</code>, <code>b</code>, and <code>c</code> either explicitly or in <code>__all__</code>) since all names are recreated.</p>
<p>In all ... | python|memory|import-module | 5 |
8,201 | 46,509,740 | Python: mix the letter of each word and reverse | <p>Given the strings <code>s1</code> and <code>s2</code> that are of the same length, creating a new string consisting of the last character of <code>s1</code> followed by the last character of <code>s2</code>, followed by the second to last character of <code>s1</code>, followed by the second to last character of <cod... | <pre><code>>>> str1 = 'hello'
>>> str2 = 'world'
>>> my_str = ''.join(y for x in zip(str1[::-1], str2[::-1]) for y in x)
>>> my_str
odlllreohw
</code></pre>
<p>...you can use <code>reversed()</code>, as well.</p> | python | 3 |
8,202 | 46,228,338 | convert python dictionary to string | <p>I have a list of python dictionaries. How to convert python dictionary from </p>
<pre><code>{'foo1':['bar1','bar2'] , 'foo2':['bar3']}
{'foo3':['bar4','bar5','bar6'] , 'foo4':['bar7','bar8','bar9']}
.
.
.
{'foo5':['bar10'] , 'foo6':['bar11','bar12']}
{'foo7':['bar13','bar14'] , 'foo8':['bar15','bar16','bar17','bar1... | <p>You can iterate over the keys and values, then join them with a <code>,</code> and surround them with <code>{}</code>:</p>
<pre><code>def icinga_form(d):
items = ', '.join(
'{} = {}'.format(key, value) for key, value in d.items()
)
return '{%s}' % (items,)
</code></pre>
<p>And then apply it to ... | python|dictionary|icinga | 1 |
8,203 | 46,540,504 | How to use make_scorer Custom scoring function in sklearn | <p>I am trying to implement a top decile recall/precision scoring function to insert into gridsearchCV. However, I am unable to figure out what is wrong. What I would like to do is to have my scoring function take in the probability prediction, actual label and ideally the decile threshold in percentage. I would then r... | <p>The solution is in adding a parameter called needs_proba=True in the make_scorer function! This works ok.</p>
<pre><code>def top_decile_conversion_rate(y_prob, y_actual):
# Function goes in here
print "---prob--"
print y_prob
print "---actual--"
print y_actual
print "---end--"
return 0.... | python|machine-learning|scikit-learn|scoring|grid-search | 4 |
8,204 | 49,485,851 | Python find closest turtle via mouse click | <p>I'm in the process of creating a minesweeper style game using a turtle-based grid setup. I need to find the closest cell within the grid and reveal the icon located under it whether that be a bomb or a number icons. I'm not looking to make it exact, I just need the mouse click to find the nearest cell in the grid ev... | <p>I believe you're approaching this problem the wrong way. You're activating <code>screen.onclick()</code> and trying to map it to a turtle. Instead, activate <code>turtle.onclick()</code> on the individual turtles, deactivating it when a turtle is selected. Then you don't have to search for the turtle in question,... | python|turtle-graphics|python-turtle|minesweeper | 0 |
8,205 | 53,799,572 | Python str.islower() method doesn't seem to be working in my code? | <p>I'm analyzing the text of Macbeth through the Project Gutenberg website, and I'm trying to create a list of the characters by mention of their names. I know there is a way to do this with nltk but I am trying to avoid that at this point. I'm getting the names by finding all instances of 'Enter' in the text, and th... | <p>You remove one item from list in one for loop, the list also have changed. So in this <code>for string in sublist</code>, the string will not loop as the order of original sublist.</p> | python|python-requests|lowercase | 1 |
8,206 | 53,457,074 | Enable Webiopi CORS request | <p>I'd like to call the Webiopi REST API from my angular application in a browser running on the Raspberry. As Webiopi HTTP server doesn't allow CORS request, I have created a proxy with apache that sends the <code>Header add "Access-Control-Allow-Origin" "*"</code> header.</p>
<p>This is working fine, however the cal... | <p>I had to enable all headers to the http server:</p>
<pre><code>def do_OPTIONS(self):
self.send_response(200,"ok")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.end_headers()
</... | python|angular|http|webiopi | 0 |
8,207 | 46,099,648 | pandas from 2D data to 1D with multiindex columns | <p>I have a simple 2D dataframe with index and columns. I need to export it to an excel file by using my colleague's layout, e.g. a single row with a multiindex columns of 2 levels. The first level corresponds to my dataframe index, the second level corresponds to my dataframe column.</p>
<p>What I have:</p>
<pre><co... | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="noreferrer"><code>stack</code></a> to move the column index into a new row index level:</p>
<pre><code>In [61]: df.stack()
Out[61]:
C-Rate
1C Ah-Step -30.133791
T[°C] 30.8635... | python|python-3.x|pandas | 8 |
8,208 | 46,102,543 | Autotools - Use Python 2.7 when Python 3 is available | <p>I use Arch Linux. <code>python --version</code> returns Python 3.6.2, <code>python2 --version</code> (and <code>python2.7 --version</code>) returns Python 2.7.13. Automake searches for a python newer than 2.4 and finds <code>python</code> (3.6). The project doesn't work with python 3, though. <code>AM_PATH_PYTHON(&l... | <p><code>PYTHON</code> is setup by <code>AM_PATH_PYTHON</code> as a <a href="https://www.gnu.org/software/autoconf/manual/autoconf-2.64/html_node/Setting-Output-Variables.html" rel="nofollow noreferrer">precious variable</a> and you can override its choice at configure time:</p>
<pre><code>$ PYTHON=python2 ./configure... | python|linux|python-2.7|archlinux|automake | 3 |
8,209 | 46,004,949 | Bootstrap form in modal cannot resolve file | <p>I want to link my deleteview URL to the 'yes' button on my modal, however, it is not deleting and in pycharm, it is showing up as: 'cannot resolve file'. I have checked my urls and view and they all seem to be correct. Any help is much appreciated. note: I am new to bootstrap</p>
<pre><code>{% for patient in all_pa... | <p>In button type put <code>type="submit"</code></p> | jquery|python|html|django|twitter-bootstrap | 1 |
8,210 | 45,821,352 | windows: unable to install kivy on virtual enviroment | <p>I have kivy installed on my system but I need an older version for my virtual env.
I am getting the following error:</p>
<blockquote>
<p>command <code>cl.exe</code> failed: No such file or directory.</p>
</blockquote>
<p><code>cl.exe</code> is already been added to my system <code>PATH</code>. I have already in... | <blockquote>
<p>cl.exe is already been added to my system path</p>
</blockquote>
<p>definitely nope otherwise you'd get a different error. Maybe you have a custom loader for Python (<code>.bat</code> file for example). You write you use <code>virtualenv</code>, therefore you need to add the <strong>folder</strong> w... | windows|kivy|virtualenv|python-3.5 | 1 |
8,211 | 55,081,561 | Converting from R to Python, trying to understand a line | <p>I have a fairly simple question. I have been converting some statistical analysis code from R to Python. Up until now, I have been doing just fine, but I have gotten stuck on this particular line:</p>
<pre><code>nlsfit <- nls(N~pnorm(m, mean=mean, sd=sd),data=data4fit,start=list(mean=mu, sd=sig), control=list(ma... | <p>As you can see from <code>?nls</code>: the first argument in <code>nsl</code> is <code>formula</code>:</p>
<blockquote>
<p>formula: a nonlinear model formula including variables and parameters.
Will be coerced to a formula if necessary</p>
</blockquote>
<p>Now, if you do <code>?formula</code>, we can read this... | python|r | 1 |
8,212 | 54,731,757 | How to Give Sequential Names to DataFrames Using Loops? | <p>I've succeed on splitting a <code>DataFrame</code> into several smaller <code>DataFrames</code>. I'm now working on giving these <code>DataFrames</code> sequential names, and can be called independently.</p>
<pre><code>shuffled = df.sample(frac=1)
result = np.array_split(shuffled, 3)
for part in result:
print... | <pre><code>df_dict = {}
for index, splited in enumerate(result):
df_name = "df_{}".format(index)
# if you want to set name of the dataframe
splited.name = df_name
# if you want to set the variable name to dataframe
df_dict[df_name] = splited
print(df_dict)
</code></pre>
<pre><code>{'df_0': movie... | python|python-3.x|pandas|dataframe|jupyter-notebook | 1 |
8,213 | 33,515,700 | Downloading csv file from a website using python | <p>I have the following website <a href="https://in.finance.yahoo.com/q/hp?s=%5EBSESN&a=03&b=3&c=1997&d=10&e=4&f=2015&g=d" rel="nofollow">yahoo finance</a>. I want to set a date range on that page for e.g April 3rd 1997 to 4th November 2015. Once I set the date range I get a link to download... | <p>This might be helpful : </p>
<pre><code>import requests
import shutil
def callme():
url = "http://real-chart.finance.yahoo.com/table.csv?s=%5EBSESN&a=03&b=3&c=1997&d=10&e=4&f=2015&g=d&ignore=.csv"
r = requests.get(url, verify=False,stream=True)
if r.status_code!=200:
... | python|csv | 8 |
8,214 | 33,486,224 | Python Tkinter set widgets frame with grid() | <p>My problem is this. I create a tkinter widget and later down the road I create a new frame that I want to add this widget to. When I call .grid() on the widget the widget is placed on the first frame, not the newer one that I want it to be on.</p> | <p>By default a widget is managed by its parent. If you don't want that, use the parameter <code>in_</code> when calling <code>pack</code>, <code>place</code> or <code>grid</code>. </p>
<p>For example:</p>
<pre><code>self.f1 = tk.Frame(...)
self.label = tk.Label(self.f1, ...)
self.label.pack(...)
...
self.f2 = tk.Fra... | python|tkinter | 1 |
8,215 | 33,079,366 | Python - How to display two counters in for loops | <p>Im trying to achieve next effect:</p>
<p>I have two counters, one should be "Current" counter that should count from 1 to 123, while there should be also counter named "Total" on bottom of console that should display total count for example 234.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import sys
i... | <p>If you really want two lines, you can make use of the <code>CPL</code> (Cursor Previous Line) <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">ANSI escape code</a> to move the cursor to the beginning of the previous line.</p>
<pre><code>import sys
import time
import colorama
print('')
total ... | python|python-3.x|for-loop|counter | 1 |
8,216 | 73,760,534 | Remove common in two list | <p>I have problem with Python function uncommon(l1,l2) that takes two lists sorted in ascending order as arguments and returns the list of all elements that appear in exactly one of the two lists. The list returned should be in ascending order. All such elements should be listed only once, even if they appear multiple ... | <p>Using sets is a good start - sets have good logic regarding group operations.<br />
If we think using venn diagrams we can see that "uncommon" elements are everything that is in the <em>Union</em> of the two lists minus the <em>intersection</em> of the two lists (the part in white is the intersection):
<a ... | python|list|set | 3 |
8,217 | 73,524,569 | Python How to make a number triangle | <p>So I've recently started learning python and my friend gave me a changllege. How to make a number triangle. So basically, I need to make python let me input a number, for example 5. After I do that, I want python to print</p>
<pre><code>54321
4321
321
21
1
</code></pre>
<p>But because I am new to python, I don't kno... | <p>Here is a sample code for you.</p>
<p>Short version (suggest learning about <strong>list comprehension</strong> and <strong>join</strong> functions):</p>
<pre><code>x = int(input('Enter a Number: '))
for i in range(x, 0, -1):
print(''.join([str(j) for j in range(i, 0, -1)]))
</code></pre>
<p>Longer version which... | python|numbers|triangle | 2 |
8,218 | 12,849,437 | How to call file name in this Python Socket? | <p>I am working on a Python Socket-based file transfer script. The server can have 10 clients connected to it, all sending it files. The problem is, it only sends a file named 'libroR.pdf', if possible, I'd like the user to be able to specify the name and location of a custom file to send to the server. If it's possibl... | <p>Try this:</p>
<pre><code>import socket
import sys
s = socket.socket()
s.connect((raw_input("Enter a host name"),9999))
f = open(raw_input("Enter the file to send to the server: "), "rb") # On this line, you were getting a file allways named libroR.pdf, but the user can input the file now
l = f.read(1024)
while (l):... | python|sockets|network-programming | 0 |
8,219 | 21,508,255 | How to use custom template during alembic initialization | <p>According to the docs, alembic's template can be specified as <code>alembic init --template pylons ./scripts</code>. But alembic searches for templates in only one folder in its root (<code>python_path/lib/python2.7/site-packages/alembic/templates</code>).</p>
<p>Is there any way to run custom templates? The idea o... | <p>As I can see in Alembic sources there is no way to customize template directory location. Template directory is gotten by <a href="https://bitbucket.org/zzzeek/alembic/src/aeeb24bbf863c3e95455677c937c9b22160671a4/alembic/config.py?at=master#cl-120" rel="nofollow">Config.get_template_directory()</a> and is used by <a... | python|sqlalchemy|alembic | 3 |
8,220 | 24,918,800 | Print multiple pieces of a string at different times on a single line with formatting | <p>I would like to print out some text on a single line dynamically, and format it to have 2 distinct columns that line up and have a minimum of 4 spaces in between them. I have seen the questions for formatting this when you can print everything out at the same time, but in this instance I will be copying files to a s... | <pre><code>print("Copying {:<30}".format("'{}' ...".format(filename)), end = "")
</code></pre> | python-3.x | 0 |
8,221 | 40,858,111 | filter queryset returned from ManyRelatedManager | <p>I have a queryset of model "A" that I'm attempting to do some values/annotate computation on. Model "A" has a ManyToMany relationship with model B. From model "A", I would like to be able to access a filtered subset of "B" models based on a field in "B". How would I change my model "A" to support this sort of patter... | <p>Read about <a href="https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions/#conditional-aggregation" rel="nofollow noreferrer">conditional aggregation</a>.</p>
<pre><code>from django.db.models import Sum, Case, When, IntegerField
Article.objects.annotate(
total_readership=Sum(
Case(
... | python|django | 1 |
8,222 | 38,405,248 | Packaging a Python library with an executable | <p>I just finished a module and want to package it. I've read the documentation and this question <a href="https://stackoverflow.com/questions/7156333/packaging-a-python-application">packaging a python application</a> but I am not sure about how to proceed when I don't have a package to import but a script to launch in... | <p>Generally, you only distribute python packages as modules when the entire project fits in a single module file. If your project is more complex than that, it's usually best to structure your project as a package with an <code>__init__.py</code> file. Here is what your project would look like converted to a package... | python|packaging|setup.py | 15 |
8,223 | 31,104,019 | Compare lists of strings regarding the suffixes of their respective elements | <p>Suppose I have a list like this</p>
<pre><code>myList = ['A_x','B_x','C_x','D_x']
</code></pre>
<p>and a list of lists like this</p>
<pre><code>myListOfList = [['A_x','B_y','C_x','D_z'],
['A_y','B_y','C_y','D_y'],
['A_u','B_y','C_y','D_y'],
['A_y','C_y','B_y','D_y',... | <p>Here's my stab at it using sets. Note that I'm using string subindexing instead of splitting on '_' or regexes since I'm assuming a very rigid format.</p>
<pre><code>myList = ['A_x','B_x','C_x','D_x']
myListOfList = [['A_x','B_y','C_x','D_z'],
['A_y','B_y','C_y','D_y'],
['A_u','B_y'... | python|performance|list|string-comparison | 1 |
8,224 | 30,925,413 | How to reattach sys.stdout to console window in python? | <p>My python 3 doodling went like this:</p>
<pre><code>import io, sys
sys.stdout = io.StringIO()
# no more responses to python terminal funnily enough
</code></pre>
<p>My question is how to reattach so when I pass in <code>1+1</code> for example it'll return with <code>2</code> to the console?</p>
<p>This is in the ... | <p>You're looking for <a href="https://docs.python.org/3/library/sys.html#sys.__stdout__" rel="nofollow"><code>sys.__stdout__</code></a>:</p>
<blockquote>
<p>It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred w... | python|io|stdout|stringio|redirectstandardoutput | 4 |
8,225 | 40,329,753 | logistic regression ValueError: Found input variables with inconsistent numbers of samples: [699, | <p>I'm new to Python and trying to perform linear regression using sklearn on a pandas dataframe. This is what I did:</p>
<p>first i label my data frame </p>
<pre><code> # imports
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_... | <p>my code was correct except that i had a typo when i am trying to assign
y so i changed </p>
<pre><code>y=[['Type']]
</code></pre>
<p>to </p>
<pre><code>y=d[['Type']]
</code></pre>
<p>also note that scikit learn will throw warning because i am passing column vector instead of id array but you can solve this by ... | python|pandas|scikit-learn | 1 |
8,226 | 29,155,324 | how can i color specific pixels in matplotlib imshow? | <p>I am plotting a <code>numpy</code> matrix with <code>imshow</code> and nearest neighbor interpolation in blue scale.</p>
<p>How can i color specific pixels in the plot so that they would be, say red?</p>
<pre><code>pyplot.imshow(matrix, interpolation='nearest',cmap = cm.Blues)
pyplot.show()
</code></pre> | <p>You can't directly color pixels red with a colormap that doesn't have red in it. You could pick a red-blue colormap and norm your matrix data into the blue part, but you can also just plot over an imshow image:</p>
<pre><code>from matplotlib import pyplot
from numpy.random import random
matrix = random((12,12))
fr... | numpy|matplotlib|imshow | 4 |
8,227 | 58,964,351 | where Environment variables for python are saved | <p>I know to set an environment variable in python is to use os.environ['API_USER'] but where this variable is saved, I supposed this environment variable is saved in .env file but it wasn't.</p>
<p>on the console to retrieve all the environment variables use command: os.environ
but don't know where are saved.
need y... | <p>Environment variables live in the memory, not on the disk. People usually save environment variables in files only for not having to do the same exporting of them by hand repetitively.</p>
<p>Also note that, environment variables are properties of operating system processes, and the process specific ones are passed... | python|django|environment-variables | 5 |
8,228 | 52,353,860 | How ro read mutli lined input into 2d arrays in python | <p>I've been across a problem in python,
the input format of the 2d array to be read is</p>
<pre><code>3 # number of rows and columns of a square matrix
1 2 3 # first row
3 4 6 # second row
4 6 3 # third row
</code></pre>
<p>how do I read 2d array from the console like the above</p>
<p>... | <pre><code>n = int(input())
matrix = dict()
for i in range(n):
matrix["row"+str(i)] = input().split() # i assume you want the numbers seperated too
</code></pre>
<p>this take the number of lines input you want makes a dictionary with the number of inputs you initialy said</p>
<p>so matrix the dicitonary is now</p... | python|python-3.x | 2 |
8,229 | 52,197,359 | Sending back a file stream from GRPC Python Server | <p>I have a service that needs to return a filestream to the calling client so I have created this proto file.</p>
<pre><code>service Sample {
rpc getSomething(Request) returns (stream Response){}
}
message Request {
}
message Response {
bytes data = 1;
}
</code></pre>
<p>When the server receives this, it... | <p>That looks mostly correct, though it's hard to be sure since you haven't shared with us all of your service-side code. A few tweaks I'd suggest would be (1) reading the file as binary content in the first place, (2) exiting the <code>with</code> statement as early as possible, (3) constructing the response message o... | python|grpc|grpc-python | 6 |
8,230 | 51,818,914 | Bokeh shows plot blurred on windows | <p>I am using bokeh for plotting. With my current settings, bokeh shows some text and lines kind of blurred (anti-aliased?). This is not really noticeable on my monitor, but on some projectors, especially when doing screenshots and inserting them into presentations, it looks weird.</p>
<p>As requested, a minimum worki... | <p>Regarding the text, it is rendered on to a raster HTML canvas, and the details of how this is done are entirely dependent on the browser canvas implementation. (FWIW things look better on any browser on OSX than the above image.) There's not anything we can to change how a specific browser renders text, and not much... | python|windows|plot|alias|bokeh | 1 |
8,231 | 19,212,508 | Plotting a histogram from pre-counted data in Matplotlib | <p>I'd like to use Matplotlib to plot a histogram over data that's been pre-counted. For example, say I have the raw data</p>
<pre><code>data = [1, 2, 2, 3, 4, 5, 5, 5, 5, 6, 10]
</code></pre>
<p>Given this data, I can use </p>
<pre><code>pylab.hist(data, bins=[...])
</code></pre>
<p>to plot a histogram.</p>
<p>I... | <p>You can use the <code>weights</code> keyword argument to <code>np.histgram</code> (which <code>plt.hist</code> calls underneath)</p>
<pre><code>val, weight = zip(*[(k, v) for k,v in counted_data.items()])
plt.hist(val, weights=weight)
</code></pre>
<p>Assuming you <em>only</em> have integers as the keys, you can ... | python|matplotlib|histogram | 34 |
8,232 | 18,860,271 | Logging ping successes and failures in linux | <p>Here's a short version of my situation. My current ISP is not working properly, and as a result, I'd like to log ping successes and failures as proof it isn't working. I'll be on Linux, but Windows would be fine too. I've been reading, and as far as I can tell, a shell script or Python code would work best.</p>
<p>... | <p>If you really want to make the whole loop take no more than 5 seconds, you have to know how long ping took, then subtract that from 5, and sleep the difference.</p>
<p>You can do this from bash either by recording the time before and after ping and subtracting, or by using the <code>time -p</code> command to run th... | python|linux|shell|ping | 1 |
8,233 | 68,999,680 | Checking if a number has any repeated elements | <p>I have been working on spliting integers into the digits they are comprised of and then checking whether there are any repeated numbers in the list. However the code seems to always say there are no repeated numbers, even if there are.</p>
<p>My Code:</p>
<pre><code>def repeatCheck(myList, repeatedNumber):
seen ... | <p>When you call the function <code>repeatCheck()</code> you don't pass a reference to the variable <code>repeatedNumber</code>, so any changes to the variable do not affect the original definition of <code>repeatedNumber</code>. Therefore, the <code>repeatedNumber</code> defined in <code>numberWorks()</code> is never ... | python|math|split|integer | 2 |
8,234 | 67,346,290 | How to calculate the Jacobian of a vector function with tensorflow | <p>I am new to TensorFlow. I would like to know what's wrong with the following code to calculate a Jacobian:</p>
<pre><code>w1, w2 = tf.Variable(1.), tf.Variable(1.)
with tf.GradientTape() as tape:
z1 = w1*w2 + w1**2
z2 = w1 + w2
tape.jacobian(tf.Variable([z1, z2]), [w1, w2])
# output: [None, None]
</... | <p>It should be</p>
<pre><code>w1, w2 = tf.Variable(1.), tf.Variable(1.)
with tf.GradientTape(persistent=True) as tape:
z1 = w1*w2 + w1**2
z2 = w1 + w2
tape.jacobian(z1, (w1, w2))
(<tf.Tensor: shape=(), dtype=float32, numpy=3.0>,
<tf.Tensor: shape=(), dtype=float32, numpy=1.0>)
tape.jacobian(z2,... | python|tensorflow | 0 |
8,235 | 36,361,361 | Python 3 tkinter treeview get NAME of selected item | <p>So basically I have <a href="http://i.stack.imgur.com/ZgjPL.jpg" rel="nofollow">this</a> tree:</p>
<p>And I want to have the name of the item selected back by pressing the "aggiungi" button.
For example when I select Pomodori and then press the button I want "Pomodori" back as string, If I select Frutta I want "Fru... | <p>Virtual event <code><<TreeviewSelect>></code> and method <code>ttk.Treeview.selection</code> might be what you need,</p>
<pre><code>import tkinter as tk
from tkinter import ttk
class Frame(ttk.Frame):
def __init__(self, *args, **kw):
ttk.Frame.__init__(self, *args, **kw)
self.tree =... | python-3.x|tkinter|treeview|selected | 3 |
8,236 | 13,503,348 | encode sound wave to image and text in Python? | <p>So i wrote the following code which converts an image input to a sound wave output and it works just fine. </p>
<pre><code>import wave
try:
#change the file's name and format
image_file = 'image.png'
fin = open(image_file, "rb") #binary read
data = fin.read()
fin.close()
except IOError:
pri... | <p>PNG is a structured format; convert to a bitmap format to produce an arbitrary image out of a lump of bits. But then just switching the filename extension from .wav to .bmp would accomplish the same thing; no actual conversion is useful or necessary ... except you probably want to tack on a small header with metadat... | python|image|audio | 0 |
8,237 | 22,257,665 | import pygr into jython failing on C library | <p>I am trying to <code>import pygr</code>:</p>
<p>It fails on: </p>
<pre><code>>>> import seqfmt
ImportError: No module named seqfmt
</code></pre>
<p>The program that uses this works fine in Python. However its calling a C library called <code>seqfmt</code> (which has a <code>C</code> file and a <code... | <p><code>.PYX</code> is the file extension used by cython, a tool for writing C extensions for python in a python-like syntax. Cython creates an intermediate file (that's presumably the <code>.C</code> file you see, at least it's not in the <a href="https://github.com/cjlee112/pygr/tree/master/pygr">git repository</a>)... | python|c|jython|bioinformatics | 6 |
8,238 | 21,962,593 | Subtract or add time to web-scraped times | <p>I'm working on a one-off script for myself to get sunset times for Friday and Saturday, in order to determine when Shabbat and Havdalah start. Now, I was able to scrape the times from timeanddate.com -- using BeautifulSoup -- and store them in a list. Unfortunately, I'm stuck with those times; what I would like to d... | <p>You should use the datetime.timedelta() function.</p>
<p>In example:</p>
<blockquote>
<p>time_you_want = datetime.datetime.now() + datetime.timedelta(minutes = 18)</p>
</blockquote>
<p>Also see here: </p>
<p><a href="https://stackoverflow.com/questions/2775864/python-create-unix-timestamp-five-minutes-in-the-f... | python|time | 1 |
8,239 | 58,039,575 | Is this a correct universal __repr__ definition? | <p>For a long time I have been puzzled by Alex Martelli's <a href="https://stackoverflow.com/questions/1436703/difference-between-str-and-repr/1436756#1436756">remark</a> about: </p>
<blockquote>
<p>(...) the fuzzy unattainable goal of making <strong>repr</strong>'s returned value
acceptable as input to <strong>ev... | <p>What the quote means is that, when a string returned from the <code>__repr__</code> method is ran on a python interpreter, it should evaluate to the object at its initialization stage.</p>
<p>The code you provided has a couple of faults.
Any object encoded in the <code>__repr__</code> return string, should also be ... | python | 1 |
8,240 | 71,344,583 | Why doesn't the import in the following Jupytor Notebook work? | <p><a href="https://i.stack.imgur.com/6n3XS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6n3XS.png" alt="enter image description here" /></a></p>
<p>So I used ! sys instead of use "pip" directly. From what I searched, this should be the best practice.</p>
<p>But the second cell doesn't p... | <p>There shouldn't be a space between <code>-</code> and <code>m</code>:</p>
<pre><code>python -m pip install thing
python - m pip install thing # NOT this
</code></pre>
<p>Otherwise the dash <code>-</code> will be treated as "read input from <code>stdin</code>", I presume.</p> | python|pip|jupyter-notebook|spell-checking | 2 |
8,241 | 9,376,249 | Gevent exceptions in Django when patching Python modules | <p>I have installed the <code>gevent</code> and <code>greenlet</code> libraries and in the <code>__init__.py</code> file of my Djano application I dumped in these two lines:</p>
<pre><code>from gevent import monkey
monkey.patch_all()
</code></pre>
<p>Now it's very often I see errors in my Django console that read:</p... | <p>Yesterday has been fixed a bug in monkey module related to <code>patch_item</code>. Any further testing is recommended with the fixed version.</p>
<p>If it does not help, you can make the problem narrower by calling <code>patch_all</code> with some arguments set to False and find which module is the problematic for... | python|django|gevent|greenlets | 2 |
8,242 | 52,797,461 | Imputation of missing value with median | <p>I want to impute a column of a dataframe called Bare Nuclei with a median and I got this error
('must be str, not int', 'occurred at index Bare Nuclei')
the following code represents the unique value of the column data['Bare Nuclei]</p>
<pre><code>data['Bare Nuclei'].unique()
array(['1', '10', '2', '4', '3', '9'... | <p>The error you got is because the values stored in the <code>'Bare Nuclei'</code> column are stored as strings, but the <code>mean()</code> function requires numbers. You can see that they are strings in the result of your call to <code>.unique()</code>.</p>
<p>After replacing the <code>'?'</code> characters, you ca... | python | 1 |
8,243 | 52,594,984 | Split lists into lists in Python | <p>I have a list with more listen inside. The list can contain unlimited lists.
I would like to divide these lists in different lists.
Here's an example:</p>
<pre><code>data = [[1538406000000, 6569.9680123, 6559.8, 6570, 6551.8, 301.21301548], [1538402400000, 6570, 6569.9, 6572.6, 6500, 1796.34637855], [1538398800000,... | <pre><code>var1 = [sublist[0] for sublist in data]
var2 = [sublist[1] for sublist in data]
</code></pre> | python|list|loops | 0 |
8,244 | 52,727,940 | subtract single value from part of the column data frame pandas | <p>I have a table like: </p>
<pre><code>username result sum
user_c 0.20 10
user_a 0.70 100
user_b 0.40 100
user_l 0.43 120
user_e 0.30 130
user_j 0.72 130
user_f 0.25 140
user_h 0.47 140
user_k 0.65 150
user_g 0.43 170
user_d 0.60 200
</code></pre>
<p>And I want to subs... | <p>IUC: </p>
<pre><code>df.iloc[1:5,2] = df.iloc[1:5,2] - 2
</code></pre>
<p>output:</p>
<pre><code> username result sum
0 user_c 0.20 10
1 user_a 0.70 98
2 user_b 0.40 98
3 user_l 0.43 118
4 user_e 0.30 128
5 user_j 0.72 130
6 user_f 0.25 140
7 user_h 0.47... | python|pandas|dataframe | 2 |
8,245 | 47,648,280 | Scrapy response.css /xpath with broken HTML. Any tips? | <p>I am still learning scrapy and am trying to scrape some information from this page: <a href="https://www.schlotzskys.com/find-your-schlotzskys/arkansas/fayetteville/2146/" rel="nofollow noreferrer">Schlotzskys store</a></p>
<p>However, after parsing the page with scrapy through the scrapy shell I run into some issu... | <p>I couldn't find element on page by CSS selector given in first expression. All your expressions are missing the <code>extract()</code> or <code>extract_first()</code> method call, so you are working with <code>Selector</code>s.</p>
<p>Try this:</p>
<pre><code>address = [
response.xpath('normalize-space(//div[@... | python|scrapy | 1 |
8,246 | 34,057,777 | Changing Single Digit Integer Input to Ordinal Numbers | <p>Problem 2 of Lesson Nine on Computer Science Circles asks the user to change a single digit number input to its ordinal adjective using only 4 separate if / elif cases. Here is my following code which is giving me '1th' instead of '1st'..</p>
<pre><code>x = input()
if x == 1:
print (1+'st')
elif x == 2:
pri... | <p>As the comments suggest, you cannot combine a integer with a string.
However, you <em>can</em> add a string to another string.</p>
<p>Here is what I mean:</p>
<p>When you try to combine an number with string, i.e. <code>1 + 'st'</code>, you get a<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'<... | python | 1 |
8,247 | 34,228,259 | ValueError: How to iterate through a tuple of Boolean True/False statements? | <p>I have a numpy ndarray <code>tup1</code> of statements <code>True</code> and <code>False</code></p>
<pre><code>print(tup1)
array([[ True, False, False, False],
[ True, False, False, False],
[False, False, False, False],
[ True, True, False, False]], dtype=bool)
</code></pre>
<p>I would like ... | <p>you have a 2-d array so just make a nested for loop that first iterates through each row, THEN iterates through the values:</p>
<pre><code>for row in tup1:
for item in row:
if item: #equivalent to `if item == True`
pass
else:
dosomething()
</code></pre>
<p>OR simplifly t... | python|numpy|boolean|iteration|tuples | 3 |
8,248 | 66,286,962 | Python lxml.html xpath doesn't return any element | <p>I'm using requests with lxml to grab some content from my website, but sometimes it doesn't return the elements it should. I just tried it on a Wikipedia page and 20% of the time, it doesn't work, here is the code to reproduce the "bug" :</p>
<pre><code>import requests
import lxml.html
url= "https://e... | <p>thanks to @jackFeeting comment, I updated lxml and my code worked just fine.
<code>pip3 install --upgrade lxml</code> updated from version <code>4.4.1</code> to <code>4.6.2</code></p> | python|xpath|python-requests|lxml | 0 |
8,249 | 16,120,801 | Matplotlib animate fill_between shape | <p>I am trying to animate a fill_between shape inside matplotlib and I don't know how to update the data of the PolyCollection. Take this simple example: I have two lines and I am always filling between them. Of course, the lines change and are animated.</p>
<p>Here is a dummy example:</p>
<pre><code>import matplotli... | <p>Ok, as someone pointed out, we are dealing with a collection here, so we will have to delete and redraw. So somewhere in the <code>update_data</code> function, delete all collections associated with it:</p>
<pre class="lang-py prettyprint-override"><code>axes_dummy.collections.clear()
</code></pre>
<p>and draw the... | python|animation|matplotlib|plot | 11 |
8,250 | 32,130,131 | Bug in StringIO module python using numpy | <p>Very simple code:</p>
<pre><code>import StringIO
import numpy as np
c = StringIO.StringIO()
c.write("1 0")
a = np.loadtxt(c)
print a
</code></pre>
<p>I get an empty array + warning that c is an empty file.</p>
<p>I fixed this by adding:</p>
<pre><code>d=StringIO.StringIO(c.getvalue())
a = np.loadtxt(d)
</code></... | <p>It's because the 'position' of the file object is at the end of the file after the write. So when numpy reads it, it reads from the end of the file to the end, which is nothing.</p>
<p>Seek to the beginning of the file and then it works:</p>
<pre><code>>>> from StringIO import StringIO
>>> s = St... | python|stringio | 2 |
8,251 | 38,604,125 | custom authentication not working in django-tastypie | <p>My question is, how do i write my own custom authentication correctly??</p>
<p>i have tried to follow this:
<a href="http://django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization" rel="nofollow">http://django-tastypie.readthedocs.org/en/latest/authenticatio... | <p>You missed <code>return</code> and You don't call parent <code>is_authenticated</code> function:</p>
<pre><code>def is_authenticated(self, request, **kwargs):
super(CustomBasicAuthentication, self).is_authenticated(request, **kwargs)
if 'admin' == request.user.username:
return prepareResponce({'log... | python|django|authentication|tastypie | 1 |
8,252 | 38,625,387 | Assign a integer identifier to strings in a 1-d array | <p>need code that inputs array of strings & outputs list of integers that represent the string numerically</p>
<p>ex. </p>
<pre><code>input: array( 'a', 'b', 'a', 'c', 'c')
output: [0, 1, 0, 2, 2]
</code></pre>
<p>need most efficient way bc there are <strong>10000 strings</strong>; using <strong>numpy arrays</... | <pre><code>_, ids = np.unique(input, return_inverse=True)
</code></pre> | arrays|string|list|numpy|int | 0 |
8,253 | 9,978,679 | django-notification emit_notices extra sql queries? | <p>So I've been trying to figure out why django-notification emit_notices prints out multiple extra queries that dont have to do anything with my notices queue</p>
<p>i run in the interpreter:</p>
<pre><code>notification.queue([to_user], "new_msg", {"from_user": from_user}, sender=from_user)
</code></pre>
<p>then</p... | <p>I bet these queries are generated by the notification template rendering.</p> | python|django | 0 |
8,254 | 2,006,115 | Python Encoding Issue | <p>I am really lost in all the encoding/decoding issues with Python. Having read quite few docs about how to handle incoming perfectly, i still have issues with few languages, like Korean. Anyhow, here is the what i am doing.</p>
<pre><code>korean_text = korean_text.encode('utf-8', 'ignore')
korean_text = unicode(kore... | <p>Even having read some docs, you seem to be confused on how unicode works.</p>
<ul>
<li>Unicode is not an encoding. Unicode is the absence of encodings.</li>
<li><code>utf-8</code> is not unicode. <code>utf-8</code> is an encoding. </li>
<li>You <strong>decode</strong> utf-8 bytestrings to get unicode. You <strong>e... | python|encoding|utf-8 | 11 |
8,255 | 2,007,786 | Python decorator with instantiation-time variable? | <p>I want to make a decorator that creates a new function/method that makes use of an object <code>obj</code>. If the decorated object is a function, <code>obj</code> must be instantiated when the function is created. If the decorated object is a method, a new <code>obj</code> must be instantiated and bound to each ins... | <p>Since a decorator is just syntactic sugar for saying</p>
<pre><code>def func():
...
func = decorator(func)
</code></pre>
<p>Why not do that in the object constructor?</p>
<pre><code>class A(object):
def __init__(self):
# apply decorator at instance creation
self.f = dec(self.f)
def f(s... | python|decorator | 2 |
8,256 | 1,676,835 | How to get a reference to a module inside the module itself? | <p>How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?</p> | <pre><code>import sys
current_module = sys.modules[__name__]
</code></pre> | python|self-reference | 247 |
8,257 | 32,367,613 | averaging datasets of varying length | <p>I have a series of datasets outputted from a program. My goal is to plot an average of the datasets as a line graph in pyplot or numpy. My problem is that the length of the outputted datasets is not controllable. </p>
<p>For example, I have four data sets of lengths varying between 200 and 400 points with x values ... | <p>so the solution that I used was to interpolate as suggested above, I've included a simplified version of the code below:</p>
<p>first the data is imported as a dictionary for ease of access and manipulation:</p>
<pre><code>def average(files, newfile):
import csv ... | python|numpy | 0 |
8,258 | 44,024,535 | Graphite: sumSeries function not working | <p>I am struck in a problem:</p>
<p>I am sending data via command line using this command in every 1 second.</p>
<pre><code>set -x; while true; do echo "System.monitoring.notification.like.1.failure $((RANDOM%1+1)) date +%s" | nc 127.0.0.1 2003; sleep 1; done
</code></pre>
<p>My data is going to graphite and metric ... | <p><code>sumSeries(System.monitoring.notification.like.1.failure)</code> will not return total count, and that's expected. Please see its <a href="https://graphite.readthedocs.io/en/latest/functions.html#graphite.render.functions.sumSeries" rel="nofollow noreferrer">documentation</a>:</p>
<p>"This will add metrics tog... | python|metrics|graphite|grafana | 4 |
8,259 | 33,025,891 | Returning ranked search results using gin index with sqlalchemy | <p>I have a GIN index set up for full text search. I would like to get a list of records that match a search query, ordered by rank (how well the record matched the search query). For the result, I only need the record and its columns, I do not need the actual rank value that was used for ordering.</p>
<p>I have the f... | <p>You can use SQL functions in your queries by using SQLAlchemy <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/sqlelement.html?highlight=func#sqlalchemy.sql.expression.func" rel="noreferrer">func</a> </p>
<pre><code>from sqlalchemy.sql.expression import func
(db.session.query(User, func.ts_rank('{0.1,0.1,0.1,0.... | python|postgresql|sqlalchemy|full-text-search|rdbms | 6 |
8,260 | 54,321,014 | Python use generator without destroying it | <p>Hi I have a generator object.
I want to count how many of each element there are in it. Without destroying the generator/changing (i want to use it again later).</p>
<p>Here is an example. </p>
<pre><code>def create(n):
items = ["a", "b", "c"]
for i in range(n):
yield items[random.randint(0,2)]
de... | <p>Unless I am fundamentally misunderstanding how Python generators work, this isn't possible and you should return in your create method rather than yield a generator.</p>
<pre><code>def create(n):
items = ["a", "b", "c"]
return [items[random.randint(0,2)] for i in range(n)]
</code></pre>
<p>The above list c... | python|generator|yield | 1 |
8,261 | 34,752,812 | Getting Error in Django API? | <p>When using Nginx and Gunicorn server I am getting the following error when sending both <code>GET</code> and <code>POST</code> requests.</p>
<pre><code>POST net::ERR_EMPTY_RESPONSE
</code></pre>
<p>I got this error while sending a <code>POST</code> request to fetch a bunch of data, nearly 20000 records. The same r... | <p>For my above issue. i checked CPU process using htop. while hitting particular API which is actually a big data collections my cpu process went 100% and RAM increasing so only it occurs. for that kill some not used process which occupy RAM. so you won't get EMPTY RESPONSE after that. but it is not a best solution. i... | python|django|nginx|django-views|gunicorn | 0 |
8,262 | 34,523,748 | Cannot find Violations plugin in Jenkins Manage Plugins tab | <p>I have recently installed and configured Jenkins 1.643 on an AWS instance running Ubuntu 14.04. I'm in the process of configuring a python project and would like to add a few plugins. To install each plugin I navigate to Manage Jenkins -> Manage plugins -> Available and then search for the appropriate one. I however... | <p>I have no problem with finding this plugin in my Manage Jenkins panel, but since you do you can download .hpi file from here:
<a href="http://mirrors.jenkins-ci.org/plugins/violations/0.7.11/" rel="nofollow">http://mirrors.jenkins-ci.org/plugins/violations/0.7.11/</a>
and go to advenced options <a href="http://local... | python|jenkins | 2 |
8,263 | 34,689,114 | Where is the external code (unsupported/Eigen/CXX11/Tensor) for TensorFlow github: | <p>I would like to get the TensorFlow GitHub code and compile it on my local Windows machine.</p>
<p>I currently have problems with the following include: </p>
<pre><code>#include "external/eigen_archive/eigen-eigen-ce5a455b34c0/unsupported/Eigen/CXX11/Tensor"
</code></pre>
<p>Where can this file be found?</p> | <p>please run the shell below first</p>
<p>tensorflow/contrib/makefile/build_all_%os_name%.sh</p> | tensorflow | 0 |
8,264 | 26,992,257 | Pylab plot shows no plot points | <p>i wanted to plot my graphics card temps from a file to a plot</p>
<pre><code>import matplotlib.pylab as pylab
temperature = 0.0
timestep = 0
logfile = file('sensorlog.txt','r')
pylab.figure(1)
pylab.xlabel('Time Steps')
pylab.ylabel('Fan Temperature')
for line in logfile:
if line[0].isdigit():
pylab.f... | <p>It appears you want to plot one point at the time. Don't do that: collect all the data into an array (from the logfile), then plot that all at once. So, do all the plotting outside your for loop:</p>
<pre><code>import matplotlib.pylab as pylab
logfile = file('sensorlog.txt','r')
pylab.figure(1)
pylab.xlabel('Time ... | python|matplotlib|plot | 0 |
8,265 | 12,287,199 | how to output xlsx generated by Openpyxl to browser? | <p>I was using stackoverflow for a while now and it helped me very often. Now I have a problem I couldn't solve myself or through searching.
I'm trying to output my excel file generated by openpyxl in browser as I was doing it with phpexcel. The method appears to be the same, but I only get broken file. My code looks l... | <p>this is work for me. I use <code>python 2.7</code> and latest <code>openpyxl</code> and <code>send_file</code> from flask</p>
<pre><code>... code ...
import StringIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active # worksheet
ws.title = "Excel Using Openpyxl"
c = ws.cell(row=5, column=5)
c.value = "Hi... | python|excel|browser|cgi|openpyxl | 6 |
8,266 | 23,442,530 | Using ellipsis as text-overflow doesn't work, except if text is "float"ed | <p>[I've read the multitude of SO threads on this subject, to no avail... ]</p>
<p>I've written a Python script that creates an HTML file. The file contains a set of links, which when rendered by the browser, are arranged in a list vertically on the page. There's no explicit styling to create this arrangement.</p>
<p... | <p>'a' is an inline element, You should apply <code>display: block;</code> so the max-width can be applied.</p>
<pre><code>a {
display: block;
white-space: nowrap;
max-width: 70%;
overflow: hidden;
text-overflow: ellipsis;
border 1px solid #000000;
}
</code></pre>
<p>An example: <a href="http://jsfiddl... | python|html|css|ellipsis | 0 |
8,267 | 23,123,155 | Python's str() function not actually a function? | <p>I was under the impression that something like <code>str(5)</code> is calling the <code>str</code> function on the integer <code>5</code>. But when you type <code>str</code> into the interpreter:</p>
<pre><code>>>> str
<class 'str'>
</code></pre>
<p>So <code>str</code> is actually a class, which mak... | <p>Listing it as a function is a bit of a simplification, yes. But remember that classes are callable* — that's how you create an instance of a class!</p>
<p>If it helps you any, think of <code>str(5)</code> as <strong>constructing</strong> a string from the number <code>5</code>.</p>
<p>Note that all of the other bu... | python | 10 |
8,268 | 8,164,809 | unable to use "d2xx" library for FTDI chips in python | <p><a href="https://picasaweb.google.com/lh/photo/h33CzWSEdo7Wju9EEk3wUg?feat=directlink" rel="nofollow">Downloaded the d2xx library from this site</a>
Works fine on Windows7 with python2.6</p>
<p><a href="https://picasaweb.google.com/lh/photo/h33CzWSEdo7Wju9EEk3wUg?feat=directlink" rel="nofollow">List of extracted fi... | <p>The libftdi drivers which use libusb have python bindings which will work in linux.
The function api's are slightly different but will accomplish the same thing. libftdi and libusb can also be used on windows if that's important.</p>
<p><a href="http://idle-logic.com/2010/12/13/libftdi-v0-18-with-ubuntu-lucid-lynx... | python|ftdi | 3 |
8,269 | 825,955 | Changing case (upper/lower) on adding data through Django admin site | <p>I'm configuring the admin site of my new project, and I have a little doubt on how should I do for, on hitting 'Save' when adding data through the admin site, everything is converted to upper case...</p>
<p>Edit: Ok I know the .upper property, and I I did a view, I would know how to do it, but I'm wondering if ther... | <p>If your goal is to only have things converted to upper case when saving in the admin section, you'll want to <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="noreferrer">create a form with custom validation</a> to make the case change:</p>
<pre><code>class... | python|django|admin|case | 19 |
8,270 | 41,869,446 | Nested serializer does not serialize the second serializer | <p>I want to use nested serializer. I have followed the doc <a href="http://www.django-rest-framework.org/api-guide/relations/" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/relations/</a>.</p>
<p>I am using Django REST 3.5.3 and Django 1.9.12.</p>
<p>Here is my <code>models</code> and <cod... | <p>If you look at the documentation of <a href="http://www.django-rest-framework.org/api-guide/relations/#reverse-relations" rel="nofollow noreferrer"><code>Reverse Relations</code></a>:</p>
<blockquote>
<p>Note that reverse relationships are not automatically included by the <code>ModelSerializer</code> and <code>Hype... | python|django|serialization|django-rest-framework | 1 |
8,271 | 41,705,519 | Correctly using banner_timeout in paramiko | <p>I'm trying to have many clients send files to a server all at once (or as fast as possible) but the server is getting too many requests at once as in the question <a href="https://stackoverflow.com/questions/25609153/paramiko-error-reading-ssh-protocol-banner" title="here">Paramiko: Error reading SSH protocol banne... | <p>You can set it like <code>transport.banner_timeout = 60</code> <em>before</em> connecting.</p> | python|server|client|paramiko | 2 |
8,272 | 47,523,097 | scrapy selenium login then search pages | <p>I'm wrapping up a project to learn more about scrapy and selenium, I'm very new to scrapy and python in general.</p>
<p>I'm trying to scrape grocery.walmart.com in an effort to check prices on local grocery items. grocery.walmart.com requires either a zipcode or a login. When I attempt to use the form request scrap... | <p>You can open the url by adding <code>self.br.add_cookie({'': ''})</code> with your login information before <code>self.br.get(response.url)</code> , or you can finish all the process in parse() that you should login by selenium directly, using code like
the example:</p>
<pre><code>driver = webdriver.Chrome(chromed... | python|selenium|scrapy | 0 |
8,273 | 47,145,693 | Python, setting a variable to None | <p>What is the reason for setting variable <code>prize</code> to <code>None</code>?</p>
<pre><code>def which_prize2(points):
prize = None
if points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a wafer-thin mint"
elif points >= 181:
prize = "a... | <p>A <code>NameError</code> exception will be raised if variable <code>prize</code> does not exist.<br />
It does not matter if variable prize is set to <code>None</code> or <code>""</code> (empty string) or <code>0</code>, because all these values are falsy in Python.</p>
<p>In this particular example prize ... | python | 4 |
8,274 | 47,303,601 | InvalidArgumentError while using tf-Faster-RCNN for object detection | <p>I am facing the following error when using tensorflows Faster-RCNN for object detection:</p>
<pre><code>"InvalidArgumentError : ValueError: attempt to get argmax of an empty sequence [[Node: model/rpn/target/PyFunc = PyFunc[Tin=[DT_FLOAT, DT_INT32, DT_INT32, DT_INT32, DT_INT32], Tout=[DT_FLOAT, DT_FLOAT, DT_FLOAT,... | <p><strong>TL;DR:</strong> remove zero-width bounding boxes from your data and <strong>also from <a href="https://github.com/endernewton/tf-faster-rcnn/blob/0f23e3d726c665b95471d940b921c8d0785fd0cd/lib/datasets/pascal_voc.py#L104" rel="nofollow noreferrer">the caches</a></strong></p>
<hr>
<p>I was using the <a href="... | tensorflow|object-detection | 0 |
8,275 | 57,627,102 | PySpark - Error when checking if I have NaN in some columns | <p>Try to check if I have NaN value in some columns with </p>
<pre><code>ddf_temp = ddf.select('col1', 'col2' ...) # all int type
ddf_temp.select([count(when(isnull(c), c)).alias(c) for c in ddf_temp.columns]).show()
</code></pre>
<p>I could isolate which columns gives me those error but I cannot find out why I got t... | <p>You have Nones in your dataframe and by applying the UDF it will execute <code>None[1:]</code> which gives you the error <code>TypeError: 'NoneType' object is not subscriptable</code> (you can try it in a python shell). </p>
<p>When using built-in pyspark functions it will always map null->null. If you would want ... | python-3.x|apache-spark|pyspark|apache-spark-sql | 1 |
8,276 | 58,509,143 | How to solve fix 'list index out of range' while accessing large amount of data from file? | <p>I am working on a classifier that will access 200000 data items from a dataset but it only accesses about 1400 data correctly and shows <code>list index out of range</code>.</p>
<p>How can I access all of the items from the dataset? </p>
<p>Here the structure of the dataset. </p>
<pre class="lang-py prettyprint-... | <p>You are assuming that you always have 7 or more lines in each block. Perhaps your file ends in <code>\n\n</code>, or you have some blocks that are corrupted.</p>
<p>Simply test for the length and skip the block: </p>
<pre><code>for news_item in news:
lines = news_item.split("\n")
if len(lines) < 7:
... | python|file|text-classification|filewriter | 1 |
8,277 | 33,614,781 | Python: add a number of random letters (A-Z; a-z) after each letter in a given word? | <p>I need to write a program that will add a number of random letters after each letter in the supplied word. </p>
<p>Here is what I have: </p>
<pre><code>import random
import string
def add_letters(word,number):
for i in range(number):
letters=''.join(random.choice(string.ascii_letters))
... | <p>Your logic is not correct. I would suggest adding some debugging printout inside your loop and see what you get, something like the following:</p>
<pre><code>for i in range(number):
letters=''.join(random.choice(string.ascii_letters))
new_word=(letters.join(word))
print i, letters, word, new_wo... | python|string|random | 1 |
8,278 | 46,859,322 | Compute variance on GroupedData | <p>I am trying to compute the variance on a GroupedData object in PySpark 2. Looking at <a href="http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.GroupedData" rel="nofollow noreferrer">http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.GroupedData</a>, I don't see any b... | <p>The built-in functions are <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.var_pop" rel="nofollow noreferrer">here</a>; There are two methods <code>var_pop</code> and <code>var_samp</code> in the <code>pyspark.sql.functions</code> module calculating population variance ... | python|pyspark|apache-spark-sql|pyspark-sql | 2 |
8,279 | 46,792,079 | How to locate the four elements using selenium in python | <p>I am trying to post several parameters to this [url][1] and press 'submit' to download a csv file generated. </p>
<p>I think 5 steps are needed at least.</p> | <p>Unfortunately, I don't think you're going to be able to do this via requests. As far as I can tell, there is no POST being made when you click "Submit". It appears as though all the data is being generated by JavaScript, which requests can't deal with.</p>
<p>You could try using something like <a href="http://selen... | python|selenium|web-scraping | 1 |
8,280 | 47,008,252 | How I can read specific words from txt files in pycharm | <p>im trying to find a word in a txt file, something like a string input. Im new to python and pycharm so I don't know what to do, I want something where with an input I can find a word or a name in a txt file.</p>
<p>I got a txt file with names and values, and I want to make an input where when I type in a name, that... | <p>Things to do is
1: Open the text file you want to search for
2:Then check the each line in the text file with your search word
3:If your search word found in the line,print the line</p>
<p>Code is:</p>
<pre><code>a = With open('filename.txt','r')
For b in a:
c = "Your search word"
If c in b:
... | python|pycharm | 0 |
8,281 | 37,708,407 | Python double simultaneous 'IF' conditions | <p>Is it possible to loop through a list and, for each item in the list, go down two conditional IF paths?</p>
<p>For example, consider the below pseduocode:</p>
<pre><code>for item in some_list:
if some_variable == item:
some_variable += 1
else:
some_variable -= 1
andif some_other_varible... | <p>If I understand the question, you simply need:</p>
<pre><code>for item in list:
if some_variable == item:
some_variable += 1
else:
some_variable -= 1
# Start new IF block
if some_other_varible == item:
some_other_variable += 1
else:
some_other_variable -= 1
</cod... | python|loops|if-statement | 3 |
8,282 | 68,005,021 | Is dot notation between two separate instance variables allowed? How does it work? | <p>I am working on my first python project, a tower defense game called Ants vs Bees. I need some assistance understanding one aspect of the starter code, namely the implementation of tracking the entrances of a specific place.</p>
<pre><code>import random
from ucb import main, interact, trace
from collections import O... | <p>Here is an example :</p>
<pre class="lang-py prettyprint-override"><code>class Place:
def __init__(self, name, exit=None):
self.name = name
self.exit = exit
self.entrance = None
# if this place is connected to another one, it means that exiting this place leads to the other
... | python|python-3.x | 1 |
8,283 | 57,197,491 | Checking aliveness of a long running Python process | <p>How can I check the aliveness of a Python process (not a 24*7 running server process)? I am thinking to build following solution,</p>
<p>Send a heartbeat from the python process on a regular basis to a file. Externally we can deploy a system that can check if the entry (last updated time) is there in a file or not,... | <p>What about RPC? Using <code>rpyc</code> or <code>pyro</code>? You could expose a single remote method named <code>get_heartbeat()</code> which would fetch a timestamp. If the method locks, errors or the value is old you then signal that something is wrong. No need for file checking and any of that just a simple memo... | python|monitoring | 2 |
8,284 | 65,657,444 | ValueError: Incompatible indexer with Series when trying to add rows dynamically in the dataframe | <p>I am very new to Python and am trying to understand how this piece of code is adding rows to the dataframe dynamically. But upon trying I am observing issue</p>
<blockquote>
<p>ValueError: Incompatible indexer with Series</p>
</blockquote>
<p>what am I doing wrong here?</p>
<pre><code>def return_most_common_venues(r... | <p>There may be a more elegant way to order the venues and map to the dataframe, but this works. First get the dictionary of venues, reverse sort by values, then add to the new dataframe.</p>
<pre><code>import io
df = pd.read_csv(io.StringIO(''' Neighborhood Trail Theatre Ice-CreamShop
A 1 2 3
B 5 1 ... | python|python-3.x|pandas | 0 |
8,285 | 36,957,828 | Attaching an s3 file to an smtplib lib email using MIMEApplication | <p>I have a django application that would like to attach files from an S3 bucket to an email using smtplib and email.mime libraries. </p>
<pre><code>import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# This takes the fi... | <p>Have you considered using S3 get_object instead of smtplib?</p>
<pre><code>from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import boto3
msg = MIMEMultipart()
new_body = "asdf"
text_part = MIMEText(new_body, _subtype="html")
msg.... | python|django|amazon-s3|mime | 4 |
8,286 | 36,732,219 | Get one related object in single request for Django ORM | <p>I have this models</p>
<pre><code>class Book(models.Model):
title = models.CharField(max_length=255, blank=False, null=False)
class Like(models.Model):
user = models.ForeignKey(User, related_name="like_user", blank=False, null=False)
book = models.ForeignKey(Book, related_name="like_book", blank=False,... | <p><strong>* Updated to address comments *</strong></p>
<p>So roughly speaking, I think this is what you would use:</p>
<pre><code>Book.objects.annotate(is_liked=Case(When(like__user=self.request.user, then=True), default=False))
</code></pre> | python|django|django-models|django-orm|django-related-manager | 2 |
8,287 | 20,040,431 | What is the regex to remove the content inside brackets? | <p>I want to do something like this, </p>
<pre><code>Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5
</code></pre>
<p>to </p>
<pre><code>Alice in the Wonderland Rating 4.5/5
</code></pre>
<p>What is the regex command to achieve this ?</p> | <p>You want to escape the the brackets and use the non-greed modifier <code>?</code> with the catch-all expression <code>.+</code>. </p>
<pre><code>>>> s = 'Alice in the Wonderland [1865] [Charles Lutwidge Dodgson] Rating 4.5/5'
>>> re.sub(r'\[.+?\]\s*', '', s)
'Alice in the Wonderland Rating 4.5/5'
... | python|regex | 4 |
8,288 | 19,848,703 | How to select a subset from Python for parsing purpose | <p>I am working on assignment and need to develop a python to openmodelica translator. For which I am using flex and bison in initial stages. Initially I need to define a subset of python language on which I could perform a whole demo. I am new to Python language, Can anybody suggest how can I define a subset of python... | <p>Well as you are probably not interested in writing it in Python itself, I guess the <a href="http://docs.python.org/3/reference/index.html" rel="nofollow">language reference</a> is the best starting point. It defines the whole grammar of the language. So this is likely a good starting point to find some features of ... | python|parsing|bison|subset|openmodelica | 1 |
8,289 | 4,192,675 | how to filled the data in django templates | <p>I want to <code>email</code> a template in django. The template has one variable say <code>name</code>. I want to filled this value. How to do that. context is not working because i don't need to render the page.</p> | <p>Of course you need to render the template - and you do that via the context. How is it not working?</p> | python|django | 1 |
8,290 | 48,104,635 | Sum Values in a Nested Dictionary Containing Duplicates | <p>I've a <code>defaultdict(int)</code> of tuples (it contains 2 inner keys) and I'd like to sum the values of <strong>only</strong> those inner keys which have the same 1st element of the tuple.</p>
<p>For example:</p>
<pre><code>dict = defaultdict(lambda: defaultdict(int))
dict[key][elem_one, elem_two] += 1 # def... | <p>I suggest you use another <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow noreferrer"><code>defaultdict</code></a> and take advantage of the fact that the default value for an integer is <code>0</code>, and therefore, you will be able to add to a newly declared (and... | python|sum|tuples|defaultdict | 1 |
8,291 | 48,243,168 | Password Reset only by Username | <p>I Implimented django password reset using email but currently want to restrict to only username so that user can change password only by using username. tried <a href="https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html" rel="nofollow noreferrer">django built-in</a> and <... | <p>Write your own reset password code. Pretty much the only code you need to write is the first step that gets the user, generates one-only link for resetting password and sends email.</p>
<p>Django does that with PasswordResetForm. Source code is <a href="https://github.com/django/django/blob/master/django/contrib/au... | python|django|django-authentication | 2 |
8,292 | 51,316,333 | pandas Series to json array | <p>I am trying to prepare json array in python for processing in PHP. I derived results fom the 'for' loop:</p>
<pre><code>for Pr in range(150,370,20):
for Te in range(250,320,10):
maxvGuess = np.array([0.04])
y = fsolve(F_vol, maxvGuess, Pr)*1000
forphp = pd.Series({'Volume': str(y).lstrip('['... | <p>I am not sure what you really want but try doing this:</p>
<pre><code>l=[]
for Pr in range(150,370,20):
for Te in range(250,320,10):
maxvGuess = np.array([0.04])
y = fsolve(F_vol, maxvGuess, Pr)*1000
forphp = pd.Series({'Volume': str(y).lstrip('[').rstrip(']'), 'Pressure': Pr, 'Temperatu... | python|json | 0 |
8,293 | 51,424,439 | Python and a list index error | <p>i begin learning Python and i have a problem at my first steps.
I have the following code:</p>
<pre><code>f=open("C:\$%$%$%$.csv","r")
data=f.read()
rows = data.split('\n')
final_data = []
for row in rows:
split_list = row.split(',')
final_data.append(split_list)
</code></pre>
<p>Until now all good. The re... | <p>As was told in the comments, you have empty string at the end of the data. You can filter all empty strings out in loading phase like this:</p>
<pre><code>f=open("C:\$%$%$%$.csv","r")
data=f.read()
rows = data.split('\n')
final_data = []
for row in rows:
split_list = row.split(',')
if len(split_list) == 1:
... | python | 0 |
8,294 | 64,183,366 | TemplateDoesNotExist at /groups/ .....groups/group_base.html; Template-loader postmortem | <p>i keep getting this error:</p>
<pre><code> TemplateDoesNotExist at /groups/
groups/group_base.html
Template-loader postmortem
Error during template rendering
</code></pre>
<p>As a note, this is from a tutorial wherein the tutorial is using an older version of django and python but I am using t... | <p>In line 1 of <code>group_list.html</code> try using:</p>
<p><code>{% extends "group_base.html" %}</code></p>
<p>And tell me if it works.</p> | python|django | 0 |
8,295 | 70,712,229 | Will functions run twice with asyncio.gather(create_task(task)) | <p>What will be happened, if I run:</p>
<pre class="lang-py prettyprint-override"><code>tasks = []
for item in items:
tasks.append(asyncio.create_task(f(item)))
res = asyncio.gather(*tasks)
</code></pre>
<p>Will functions run twice? After <code>create_task</code> and after <code>gather</code></p> | <p>First, note that you must <strong>await</strong> <code>asyncio.gather()</code> for them to run at all.</p>
<p>Once that is fixed, the functions will run only once. <code>create_task()</code> submits them to the event loop. After that, they will run during the next <code>await</code>. <code>asyncio.gather()</code> si... | python|asynchronous|python-asyncio | 0 |
8,296 | 70,606,755 | Calculated column based on secondary key in Pandas Dataframe | <p>My data looks somewhat like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>key</th>
<th>city</th>
<th>currentCityKey</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Boston</td>
<td>NaN</td>
</tr>
<tr>
<td>2</td>
<td>New York</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Concord</td>
<... | <p>Create a mapper with the <code>'key'</code> and <code>'city'</code> columns and use <code>map</code> on <code>'currentCityKey'</code> column to obtain <code>'currentCity'</code> column:</p>
<pre><code>df['currentCity'] = df['currentCityKey'].map(df.set_index('key')['city'])
</code></pre>
<p>Output:</p>
<pre><code> ... | python|pandas|dataframe|numpy | 1 |
8,297 | 55,585,469 | Data fetch from Database for TransmogrifAI | <p>Could you please someone help me for fetching data directly from any MySQL Database instead of using any dataset for TransmogrifAI.
If possible can I get the code regarding this or any reference?</p> | <p><a href="https://docs.databricks.com/spark/latest/data-sources/sql-databases.html" rel="nofollow noreferrer">Here is a guide</a> on how you can connect to MySQL from Apache Spark. </p>
<p>Once you have you Dataset / RDD materialized you can plug it into TransmogrifAI:</p>
<ol>
<li>Either by automatically materiali... | python|database|transmogrifai | 1 |
8,298 | 66,617,690 | Creating a calculator, but the order of operations always defaults to addition | <p>So to start coding I decided to create a simple calculator which takes the input from the user, turns it into two separate lists, then asks which operations you want to use, and does the equation. The problem is though is that I will say I want to use subtraction, for example, my two numbers are 10 and 5, then the o... | <p>Your issue is the if statement.</p>
<p><code>if type_of_computing == 'A' or 'a':</code></p>
<p>should be <code>if type_of_computing == 'A' or type_of_computing == 'a'</code></p>
<p>since you are checking for two different conditions. 'a' is a defined character, so it will always return true, which is why your code a... | python|calculator | 1 |
8,299 | 66,535,154 | Django Unable to access LiveServerTestCase (code 500) | <p>I was following Django docs, but am still having problem with this example - I get <code>500 Internal server error</code> when accesing the live server with Selenium.</p>
<p>My code:</p>
<pre><code>import os
try:
browser_driver = os.environ['BROWSER_DRIVER']
except KeyError:
raise ValueError("BROWSER_D... | <p>your home page view is probably the problem. template_name might be incorrect.</p>
<p>I have a similar problem, was able to access but the LiverServerTestCase/live_server_url couldn't load my context variable to display on the page...it seems like this is a django 3 problem...not many people got this problem yet</p> | python|django|selenium | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.