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,600 | 51,711,170 | numpy: summing along all but last axis | <p>If I have an <code>ndarray</code> of arbitrary shape and I would like to compute the sum along all but the last axis I can, for instance, achieve it by doing</p>
<pre><code>all_but_last = tuple(range(arr.ndim - 1))
sum = arr.sum(axis=all_but_last)
</code></pre>
<p>Now, <code>tuple(range(arr.ndim - 1))</code> is no... | <p>You could reshape the array so that all axes except the last are flattened (e.g. shape <code>(k, l, m, n)</code> becomes <code>(k*l*m, n)</code>), and then sum over the first axis.</p>
<p>For example, here's your calculation:</p>
<pre><code>In [170]: arr.shape
Out[170]: (2, 3, 4)
In [171]: arr.sum(axis=tuple(rang... | python|numpy | 18 |
8,601 | 51,866,280 | Finding the surrounding rectangular region given a line inside it | <p>My Question is related to OpenCV / Matplotlib only. However, to understand the problem bear with me for a few lines of ML / Computer vision side of stuff : </p>
<p>I am working on a Image segmentation problem on floor plan dataset. I would be using Fully Convolutional Networks (FCN) for the same. </p>
<p>Now, FCNs... | <p>Normally, you could use a simple "fill" algorithm for this, as suggest in Mariana's answer. However, you need to extend only so far as the given line -- you cannot continue down the west wall of that office area. I'm assuming that each end result will be a rectangle aligned to the drawing axes.</p>
<p>Instead, yo... | python|opencv|matplotlib|annotations|computer-vision | 2 |
8,602 | 51,782,114 | Python replace '\0' in string with null | <p>I'm currently facing a strange problem.
I want to replace the '\0' in strings with 'null' and read through many forums and always saw the same answer:</p>
<pre><code>text_it = "request on port 21 that begins with many '\0' characters,
preventing the affected router"
text_it.replace('\0', 'null')
</code></pre>
<p... | <p>In one single line:</p>
<pre><code>text_it = text_it.replace('\0', 'null').replace('\x00', 'null')
</code></pre> | python|replace|null-terminated | 3 |
8,603 | 51,640,910 | Syntax error: print yaml.dump( on repl.it | <p>I need help fixing this error I keep getting in repl.it, here's the error, I broke it down into its key components:</p>
<pre><code>Traceback (most recent call last):
File "python", line 3, in <module>
File "/home/runner/.site-packages/universe/__init__.py", line 227
print yaml.dump(
^
Syn... | <p>The error seems to indicate that <code>universe</code> is Python 2 only.</p> | python|repl.it | 0 |
8,604 | 19,279,960 | Constructing String Without Concatenation in Python 2.7 | <p>Is there any way to place a declared string in between unicode symbols without concatenation?
For example, I have declared a string <code>a = "house"</code>. Is there anyway I can declare <code><\house/></code> without
having to result to <code>"<\\" + a + "/>"</code> ? Concatenation may become cumbers... | <p>how about string interpolation?</p>
<pre><code>"<\\%s/>" % a
</code></pre>
<p>or for multiple items:</p>
<pre><code><"\\%s %s/>" % (a, b)
</code></pre>
<p>Also works with dictionaries:</p>
<pre><code>"<\\%(a)s/>" % {'a': a}
</code></pre>
<p>Python 3.x style interpolation is done using the bui... | python|python-2.7 | 2 |
8,605 | 19,037,673 | Why doesn't Django serialize full model relations? | <p>The question is pretty simple:
I am aware that Django won't serialize the related models when using </p>
<pre><code>serialize("json", queryset)
</code></pre>
<p>In example: If I have a book with an author:</p>
<pre><code>class Book(models.Model):
author = models.ForeignKeyField(Author)
</code></pre>
<p>When ... | <p>It is possible using natural key, a custom manager and <code>get_by_natural_key()</code>. Django doc has a full explanation, please <a href="https://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys" rel="nofollow">read here</a>. I'd rather not copy paste everything here.</p>
<p>By using this method,... | python|django|json|serialization | 1 |
8,606 | 67,441,261 | How to pretty print more than one dictionary entry per line? | <p>I have a dictionary with many entries:</p>
<pre><code>d = dict([(i, 'Data') for i in range(100)])
</code></pre>
<p>If I try to pretty print this data</p>
<pre><code>pp = PrettyPrinter(indent=4, width=999)
pp.pprint(d)
</code></pre>
<p>it only prints one entry per line:</p>
<pre><code>{ 0: 'Data',
1: 'Data',
... | <p>This doesn't really answer the question since it does not use the pretty print or other existing library. It also does not account for edge cases such as a new line in keys or values, or nested/non-string types.</p>
<pre><code>d = dict([(i, 'Data') for i in range(20)])
def print_dict(d, col_width=80, sep=','):
... | python|dictionary|printing|pretty-print | 0 |
8,607 | 13,253,510 | Using VIM for Python IDE in Windows? | <p>I am turning to Python from .NET world. And Visual Studio was something a great tool i used.</p>
<p>In python world we do have basic IDLE and another one is VIM. I have seen that a lot of developers have configured VIM to a great IDE. Using basic VIM in Windows 7 seems of less use.
So i want to moderate my VIM to a... | <p><a href="https://stackoverflow.com/questions/81584/what-ide-to-use-for-python">This question</a> addresses your low level issue: coding Python with an IDE that is not VS.</p>
<p>There are a few popular blog posts addressing your high level issue: setting up Vim for Python development. They are <a href="http://www.g... | python|django|windows|vim|ide | 11 |
8,608 | 13,775,742 | Scraping all mobiles of Flipkart.com | <p>I am trying to scrape all the mobiles from www.flipkart.com. Now, what I have thought of doing is that I can scrape all mobiles from here. </p>
<pre><code>http://www.flipkart.com/mobiles/pr?p[]=sort%3Dprice_asc&sid=tyy%2C4io&layout=grid
</code></pre>
<p>Now, the problem is that, in this website I have to ... | <p>You can play around with the get parameters. The regular URL is:</p>
<p>http://www.flipkart.com/mobiles/pr?p[]=sort%3Dprice_asc&sid=tyy%2C4io&layout=grid</p>
<p>Once you hit the 'more results' button (or scroll down) the next page is loaded using AJAX with the following url:</p>
<p><a href="http://www.fli... | python|web-scraping|beautifulsoup | 7 |
8,609 | 13,465,681 | Exposing `defaultdict` as a regular `dict` | <p>I am using <code>defaultdict(set)</code> to populate an internal mapping in a very large data structure. After it's populated, the whole structure (including the mapping) is exposed to the client code. At that point, I don't want anyone modifying the mapping. </p>
<p>And nobody does, intentionally. But sometimes, c... | <p><a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="noreferrer"><code>defaultdict</code></a> docs say for <code>default_factory</code>:</p>
<blockquote>
<p>If the default_factory attribute is None, this raises a KeyError
exception with the key as argument.</p>
</blockquote>... | python|python-3.x|wrapper|defaultdict | 59 |
8,610 | 71,442,665 | How to automatically select the digital certificate listed in a pop up window? | <p>I am experimenting with Selenium, simulating the human process of navigating a webpage with Chrome to retrieve information. The first step is:</p>
<pre><code>String baseUrl = "https://aps.bde.es/cir_www";
driver.get(baseUrl);
System.out.println(driver);
</code></pre>
<p>The destination url opens a pop up s... | <p>The solution, as pointed out in one of the comments, go through the edition of the Window's key (if Windows) AutoSelectCertificateForUrls. The easy way is using the Python winreg library. I still have some doubts associated with user permissions, but that is a different issue.</p> | python|java|selenium|popup|bots | 0 |
8,611 | 9,271,772 | Adding MySQLdb to sys.path in a virtualenv | <p>I can create a .pth file and put it in my virtualenv <code>lib\site-packages</code> to bring the MySQLdb that is installed by the windows installer into my virtualenv. But so far the only way I have been able to get this to work is if I use this path in the .pth file:</p>
<pre><code>C:\python27\lib\site-packages
<... | <p>.pth files add directories to your sys.path, so if you want to be able to 'import MySQLdb', then the directory <em>containing</em> MySQLdb has to be in the path.
The only way around it that I see is to create some other directory, something like
c:\python27\lib\site-packages\export\</p>
<p>add it to your .pth file... | python|virtualenv | 1 |
8,612 | 9,446,565 | Trouble using pip after installing Python 2.7 with Homebrew on Mac OS X 10.6.8 | <p>I just used homebrew to install Python 2.7.2 on a clean Mac OS X Snow Leopard install, but seem to be having trouble getting PIP to work with it well.</p>
<p>Here are the steps that I took:</p>
<ol>
<li>Installed python with Homebrew: <code>brew install python --framework
--universal</code> </li>
<li>Updated my pa... | <p>So, it looks like the way that I installed things I needed to use <code>/usr/local/share/python/pip-2.7</code> instead of <code>/usr/local/share/python/pip</code>. </p>
<p>Not sure why I have both pip and pip-2.7 but Aliasing my pip to the the 2-7 version seems to fix my issue.</p> | python|osx-snow-leopard|pip|homebrew | 2 |
8,613 | 9,366,650 | string splitting after every other comma in string in python | <p>I have string which contains every word separated by comma. I want to split the string by every other comma in python. How should I do this?</p>
<p>eg, <code>"xyz,abc,jkl,pqr"</code> should give <code>"xyzabc"</code> as one string and <code>"jklpqr"</code> as another string</p> | <p>It's probably easier to split on every comma, and then rejoin pairs</p>
<pre><code>>>> original = 'a,1,b,2,c,3'
>>> s = original.split(',')
>>> s
['a', '1', 'b', '2', 'c', '3']
>>> alternate = map(''.join, zip(s[::2], s[1::2]))
>>> alternate
['a1', 'b2', 'c3']
</code></p... | python|string|split | 8 |
8,614 | 39,083,865 | Django relation error when running make migrations | <p>Hey I am attempting to initialize a new database, but I am running into some issues setting up the migrations. The error I am getting appears to stem from setting up my forms. In a form I am using, I am creating a choice field as so:</p>
<pre><code>from django import forms
from ..custom_admin import widgets, choice... | <p>You cannot execute queries during the initialization of the app registry. Your <code>choices.py</code> file is indirectly imported during this time, resulting in the error. To fix this issue, you can pass a callable to <code>choices</code>:</p>
<pre><code>def get_provinces():
province_choices = []
for provi... | python|django|django-forms|django-admin|django-migrations | 9 |
8,615 | 52,732,472 | How to make a CDF in Python? | <p>I made the PDF which is this hist code below;</p>
<pre><code>plt.figure()
values1,bins1,_ = plt.hist(np.log10(fakeclusterlum),bins=20)
plt.hist(np.log10(bigclusterlum151mh),alpha = .5,bins = bins1)
</code></pre>
<p>but I am not sure how to plot this to make it into a CDF? I want to plot the fakeclusterlum and bi... | <p><a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html" rel="nofollow noreferrer">pyplot.hist</a> has an argument</p>
<blockquote>
<p><code>cumulative</code> : bool, optional<br>
If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. ... | python|matplotlib|plot|histogram|cdf | 0 |
8,616 | 52,827,625 | Pandas - Sum of first X hours of datetime index | <p>I have a dataframe with a datetime index and 100 columns.</p>
<p>I want to have a new dataframe with the same datetime index and columns, but the values would contain the sum of the first 10 hours of each day.</p>
<p>So if I had an original dataframe like this:</p>
<pre><code> A B C
----... | <p>You need <code>groupby</code> <code>df.index.date</code> and use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>transfrom</code></a> with lambda function to find sum of first 10 values as:</p>
<pre><code>df.loc[:,['A','B','C']] = df.g... | python|pandas|group-by | 3 |
8,617 | 47,771,351 | how to rotate a bullet according to the player's rotation | <p>I've finally figured out how to shoot bullets but now I want to rotate the origin of the bullets on the rotation of the players head. Now it's only shooting straight on the x line. The mobs are working fine. I only need to add in collision and the bullet that is rotating on the player's angle. I will do the collisio... | <p>You need to use trigonometry or vectors to calculate the velocity of the bullet (I use trig here). Pass the angle of the player to the <code>Bullet</code> and then use <code>math.cos</code> and <code>math.sin</code> with the negative angle to get the direction of the bullet and scale it by the desired speed. The act... | python|rotation|pygame|bullet | 2 |
8,618 | 37,264,599 | Using ptrepack to reclaim deleted nodes in hdf5 file | <p>I have written a bunch of pandas DataFrames to a h5 file using the Pytables integration in pandas. Since then I've deleted some of the groups in the h5 file and I want to repack it in order to reclaim the space. From what I've found I know I need to use the Pytables <code>ptrepack</code> tool. However I can't get it... | <p>Ok, firstly, to get the help dialog to show in the command prompt you have to do either <code>ptrepack -h</code> or <code>ptrepack --help</code>
I didn't manage to get the script working in python as it seems it has been made specially for the command line- I did however find this very helpful notebook on the subjec... | python|python-3.x|pytables | 4 |
8,619 | 66,029,194 | Best way to load images pygame | <p>Currently, I am loading all images at the start of the program. Is there a better solution for this? As some images may not be used at all throughout the entire game (I'm currently making a main menu).</p>
<p>Main.py</p>
<pre><code>import pygame as pg
from Menu import Menu
pg.init()
"""Displays scree... | <p>To give a quick and simple overview of what you could do, here's an example. You define an abstract <code>Scene</code> class. Then, every "scene" in your game inherits from it. Each scene has a <code>setup</code> method that loads everything the scene needs (or might need).</p>
<pre><code>import pygame
c... | python|pygame | 1 |
8,620 | 72,744,811 | Error: cannot import name 'SpearmanRConstantInputWarning' from 'scipy.stats' | <p>I'm getting an error when importing the <code>skbio</code> package on Google Colab. The error message is related to <code>SpearmanRConstantInputWarning</code> of the <code>scipy.stats</code> package. What should I do to solve this problem?
I've tried to uninstall and install <code>skbio</code> and <code>scipy</code>... | <p>Seems to be some issue with the version. If you run</p>
<pre><code>pip install scikit-bio==0.5.6
</code></pre>
<p>it shouldn't show that problem, at least it worked when I tried for 0.5.6 and 0.5.5 in Colab.</p> | python|scipy|google-colaboratory|skbio | 0 |
8,621 | 72,688,454 | How to pass a parameter in the string in python using format | <p>There as a url link which i have in settings.py file :</p>
<pre><code>KAVENEGAR_URL = "https://api.kavenegar.com/v1/{key}/verify/lookup.json?receptor={phone}&token={otp}".format(key,phone,otp)
</code></pre>
<p>I want to use it in service.py file inside send_otp_sms method
I dont know how to pass key, ... | <p>The problem is this that when i use parameters in the string like this :</p>
<p><code>KAVENEGAR_URL = "https://api.kavenegar.com/v1/{key}/verify/lookup.json?receptor={phone}&token={otp}" </code></p>
<p>I have to use .format like this :</p>
<p><code>.format(key=key, phone=phone, otp=otp)</code></p>
<p>a... | python|django|string.format | 1 |
8,622 | 16,050,999 | How do you upload a gzip package to PyPI on Windows | <p>On Windows, I have uploaded a package using the following command:</p>
<p><code>python setup.py sdist bdist_wininst upload</code></p>
<p>However, due to my using Python on Windows, it uploads a zip file instead of a gzip file. How can I make it send a gzip along with it?</p> | <pre><code>python setup.py sdist --formats=zip,gztar bdist_winist upload
</code></pre>
<p>Refer to <a href="http://docs.python.org/3/distutils/sourcedist.html" rel="nofollow">the documentation</a>.</p> | python|python-3.x|pypi | 1 |
8,623 | 16,397,833 | Seconds from epoch issues | <p>I am trying to plot time back on the y-axis for a 3D plot after making a grid of it. However the dates come up funny, its supposed to be at least year 2012. I think the seconds from epoch is messing things up. </p>
<p>csv file content: </p>
<pre><code>Depth (m) 15.08.2012 15:39:09 15.08.2012 16:09:10 15.08.2012 ... | <p>I think you have to use <a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.epoch2num" rel="nofollow"><code>epoch2num</code></a>. That is:</p>
<p>Instead of </p>
<pre><code>y.append(np.divide(timelist[j], 1000))
</code></pre>
<p>Try to</p>
<pre><code>from matplotlib.dates import epoch2num
y.append... | python|datetime|csv|3d|matplotlib | 1 |
8,624 | 31,949,581 | Django Download File Url in Template | <p>I find tons of somewhat similar questions and no good answers for this. I have a dashboard where users upload files and it displays the ones they uploaded. I want to have them be able to click and icon or the filename and have it download. Right now it opens the file in the browser, which for images and pdf's isn... | <p>Is <code><a href="{{ your_file_url}}" download></code> what you need?</p> | python|django | 14 |
8,625 | 51,991,764 | Finding the realpath of a file in unix | <p>I have the following code, which is expected to do the following,</p>
<ul>
<li>Directory name (dirName) and a prefix is provided as input to the function.</li>
<li>Lists out all the contents one level down from the provided input directory (dirName) and starts populating the file details within the sub directories ... | <p>Several issues:</p>
<p>1) You are returning only a single file</p>
<p>2) You are calling <code>.resolve</code> with only a file name, so where the path will be resolved depends on the current working directory. </p>
<p>3) Your spec states that you only want to descend one level in the directory tree but you are n... | python|python-3.x|pathlib | 2 |
8,626 | 60,204,169 | Need random value from last x elements in a list | <p>I'm trying to get a random number from a list within a specific range, without using any module.</p>
<p>Input list looks like
<code>li = [12,44,55,64,34,54,56,43,56,9,87,89]</code></p>
<p>I need a function where I should pass this list and <code>x</code> as inputs and get a random element from last <code>x</code> el... | <p>Use <code>random</code> module</p>
<pre><code>import random
li = [12,44,55,64,34,54,56,43,56,9,87,89]
def getRandom(ls, x):
return random.choice(ls[-x:])
print(getRandom(li, 4))
</code></pre> | python|python-3.x|list | 6 |
8,627 | 62,938,484 | 1 Script 2 Terminal in Python | <p>Is it possible to start a part of code in one terminal (for example from line 1 to 26) and another part in another terminal? (from line 27 to 48)? Thanks a lot in advance for the help!</p> | <p>You could use command line arguments.</p>
<p>In your first terminal call <code>python3 my-program first</code><br>
And in your second terminal call <code>python3 my-program second</code></p>
<p>Then in your code you will need something that looks like:</p>
<pre><code>import sys
if __name__=="__main__":
... | python | -1 |
8,628 | 32,214,223 | How to grab item outside of tag using python+beautifulsoup | <p>Using python+beautifulsoup, let's say I have a <code><class 'bs4.element.Tag'></code> object, <code>a</code>:</p>
<pre><code><div class="class1"><em>text1</em> text2</div>
</code></pre>
<p>I can use the following command to extract <code>text1 text2</code> and put it in <code>b</code>... | <p>I edited your HTML snippet slightly to have more than just one word in and outside the <code><em></code> tag so that <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>getText()</code></a> extracting all the text form your <code><div></code> container leads to t... | python|web-scraping|beautifulsoup | 2 |
8,629 | 32,512,829 | Let string act as file | <p>I am working with a library that wants me to pass it data in the form of a file name. Then it will open that file and read the data. I have the data in a string, and I don't want to write it to a file (because I don't want to have to delete it afterwards).</p>
<p>Is there a way I can convert the string to a strea... | <pre><code>import tempfile
fh = tempfile.NamedTemporaryFile() # this creates an actual file in the temp directory
fh.write(my_string)
print fh.name
call_other_thing(fh.name)
fh.close() # file is now deleted
</code></pre> | python|stream | 3 |
8,630 | 44,033,312 | Dictionary mapping not working python | <p>I am writing a lexer for my compiler.There is a function to map appropriate values when we input a token.But getting the error:</p>
<p>[pylint] E0001:invalid syntax (, line 28)</p>
<p>Lexer.py</p>
<pre><code>class Token(object):
ILLEGAL_TOKEN = -1
TOKEN_PLUS = 1
TOKEN_MULT = 2
TOKEN_DIV = 3
TO... | <p>The value of a dictionary entry, like any value, has to be an expression which evaluates to a result (and the creators of Python made sure that you cannot assign <em>and</em> return a value at the same time). So assignment statements don't qualify.</p>
<p>You could put a function (like a <code>lambda</code> or like... | python|syntax-error | 2 |
8,631 | 34,580,286 | How can write scraped content to a CSV file? | <p>I need some help to save the output from a basic web scraper to a CSV file.</p>
<p>Here is the code:</p>
<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv
html_ = urlopen("some_url")
bsObj_ = BeautifulSoup(html_, "html.parser")
nameList_ = bsObj_2.findAll("div", {"class":"row ... | <p>If the elements in <code>nameList_</code> are rows with the columns delimited by <code>','</code> try this:</p>
<pre><code>import csv
with open('out.csv', 'w') as outf:
writer = csv.writer(outf)
writer.writerows(name.get_text().split(',') for name nameList_)
</code></pre>
<p>If <code>nameList_.get_text()<... | python|csv|python-3.x|web-scraping|beautifulsoup | 1 |
8,632 | 34,505,529 | Creating binned histograms in Spark | <p>Suppose I have a dataframe (df) (Pandas) or RDD (Spark) with the following two columns: </p>
<pre><code>timestamp, data
12345.0 10
12346.0 12
</code></pre>
<p>In Pandas, I can create a binned histogram of different bin lengths pretty easily. For example, to create a histogram over 1 hr, I do the following:<... | <p><strong>Spark >= 2.0</strong></p>
<p>You can use <code>window</code> function</p>
<pre><code>from pyspark.sql.functions import window
(df
.groupBy(window("timestamp", "3 minute").alias("ts"))
.sum()
.orderBy("ts")
.show())
## +--------------------+---------... | python|pandas|apache-spark|histogram|pyspark | 3 |
8,633 | 57,559,411 | How to import to json an API url in Python | <p>I have to work with a dataset from an API. I am trying to import the data in json format but I got errors. </p>
<p>This is my code:</p>
<pre><code>import requests as rq
r = rq.get('https://api.tfl.gov.uk/BikePoint')
print(r.status_code)
print(r.headers['content-type'])
print(r.text[:1000])
</code></pre>
<p>And th... | <p>You can use the <code>read_json()</code> function in <code>pandas</code> to get it. Here is how you can retrieve data from the api.</p>
<pre><code>import pandas as pd
import requests as rq
r = rq.get('https://api.tfl.gov.uk/BikePoint')
r = r.text
df = pd.read_json(r)
print(df.head())
</code></pre>
<pre><code> ... | python|json|import | 0 |
8,634 | 70,807,989 | How to efficiently fix JSON file converted from pandas dataframe | <p>I have a JSON file that I read in pandas and converted to a dataframe. I then exported this file as a CSV so I could edit it easier. Once finished, I read the CSV file back into a dataframe and then wanted to convert it back to a JSON file. However, in that process a whole lot of extra data was automatically added t... | <p>The issue is that you are adding an index at two places.</p>
<p>Once while writing your file to csv. This adds the "Unnamed: 0" fields in the final JSON files. You can use <code>index = False</code> in the <code>to_csv</code> method while writing CSV to disk or specify the <code>index_col</code> parameter ... | python|json|pandas | 2 |
8,635 | 12,024,457 | Cache results of a time-intensive operation | <p>I have a program (<a href="http://bioinfo3d.cs.tau.ac.il/PatchDock/" rel="nofollow">PatchDock</a>), which takes its input from a parameters file, and produces an output file. Running this program is time-intensive, and I'd like to cache results of past runs so that I need not run the same parameters twice.</p>
<p>I... | <p>Hashing a sorted representation of the parsed input is actually the most straightforward way of doing this, and the one that makes sense. Your instincts were correct.</p>
<p>Basically, you're normalizing the input (by parsing it and sorting it), and then using that to construct a hash key.</p> | python|database|hash|shelve | 4 |
8,636 | 58,203,247 | Call API every 5 seconds using *.kv file | <p>I am trying to call a method every 5 seconds in *.kv file, I have found many examples online using *.py file but unfortunately not even a single using *.kv file. Please help me with this.</p>
<p><strong>*.kv file</strong></p>
<pre><code> Label:
id:time
text: root.display_time()
... | <p>You can do this by assigning the <code>Clock.schedule_interval()</code> to a property of the <code>Label</code> in the <code>kv</code>:</p>
<pre><code>#: import Clock kivy.clock.Clock
#: import ddt datetime.datetime
Label:
abba: Clock.schedule_interval(lambda dt: setattr(self, 'text', str(ddt.now())), 5)
</code... | python|kivy|kivy-language | 2 |
8,637 | 33,552,454 | Python dataframe trimming: pd.concat() vs. df.drop() vs. df2 = df1[selectCols] | <p>Dataframe <code>df1</code> contains columns <code>Week</code>, <code>Mon</code>:<code>Sun</code>, <code>Total</code>. </p>
<p>Here are 3 ways to create a new dataframe 'df2' from columns in df1:</p>
<pre><code>df2 = pd.concat(
[df1.Sun,df1.Mon,
df1.Tues, df1.Weds,
df1.Thurs, df1.Fri,
df1.Sat], ax... | <p>I figure the main advantage would be processing time. I took your examples, made some sample data, and compared them using the <a href="https://docs.python.org/2/library/timeit.html" rel="nofollow noreferrer">timeit</a> library. It looks like options 2 and 3 are a lot faster. I would use option 2 if there are a lot ... | python|pandas|dataframe|concat | 0 |
8,638 | 47,003,102 | python 3.6.1 opencv 3.3.1 cv2.imshow() not displaying image | <p>The issue: <code>imshow()</code> doesn't display anything.</p>
<pre><code>import cv2
import numpy as np
img_rgb = cv2.imread('opencv-template-matching-python-tutorial.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('opencv-template-for-matching.jpg',0)
w, h = template.shape[::-1]
... | <p>You need to give time for the <code>window</code> to <code>open</code>, and a method for <code>closing</code> it.</p>
<p>The usual way of of doing this with <code>openCV</code> is with <code>.waitKey(n)</code>. This function will <code>halt</code> the <code>execution</code> of the <code>program</code> for <code>n</... | python|opencv | 0 |
8,639 | 67,655,914 | how to make existing tensorflow 2.4 installation to use GPU | <p>I have python 3.7.6, tensorflow 2.4.1 and keras 2.4.0 successfully installed. The code is working too. I have Nvidia graphic card on my computer. I wanted to make tensorflow use GPU to speed up training. I followed all steps to install CUDA 10.2 and cuDNN 8.0.4 as given in various internet blogs. Installation is suc... | <p>According to this list (<a href="https://www.tensorflow.org/install/source#gpu" rel="nofollow noreferrer">https://www.tensorflow.org/install/source#gpu</a>) Tensorflow 2.4 requires CUDA 11.</p> | tensorflow | 0 |
8,640 | 30,139,598 | ipython forcing pandas to plot | <p>I have a loop to generate plots for each column of a DF in pandas. I use Ipython, but the plots are all displayed at the end of the loop, rather than at the place where I would like to see them displayed according to my code.</p>
<p>How could I force ipython/pandas to display the cols at the precise point on which ... | <p>Be sure to call <code>plt.show()</code> every time you plot a new graph. If you don't, iPython will automatically buffer each plot and display them once you reach the end of the cell. I think you forget to do this at the end of your loop.</p>
<p>Here is an example of some code which will correctly plot a graph with... | python|pandas|plot | 0 |
8,641 | 57,147,649 | How to return number of occurred element in list? | <p>I'm sorry for the inrelevent topic title, because I couldn't find the proper name for the problem that I have:</p>
<p>I have the following Segment IDs:</p>
<pre class="lang-py prettyprint-override"><code>SIDs = ['11','22','33','44']
</code></pre>
<p>each element of <code>SID</code> has 2 items, like the following... | <p>The answer is now more complicated. Hopefully this captures things. I've made some assumptions. (1) We don't wrap around from <code>44</code> to <code>11</code> (2) That <code>Used_Path</code> in your question has 1 too many elements.</p>
<p>So we follow a linear path, going forward if the destination is later, bac... | python | 2 |
8,642 | 27,452,775 | Editing text file with python | <p>I'm trying to write a utility in python that will list the text files in the current directory, let the user choose a file and then open that file in a text editor. How do you reference an array in the os.system command?</p>
<pre><code>import os
from os import listdir
from os.path import isfile, join
mypath = os.ge... | <pre><code>os.system('kate "{}"'.format(onlyfiles[int(choice) - 1]))
</code></pre>
<p>Better solution would be:</p>
<pre><code>subprocess.call(['vim', '{}'.format(onlyfiles[int(choice) - 1])])
</code></pre> | python | 0 |
8,643 | 27,858,134 | How to set browser cookie that expires every hour | <p>I have a website with a python backend and a javascript/html front-end, naturally. There is a certain pop-up that I want to show every hour. It does not matter on which page of the site a user is on; once the popup appears, it should wait for one hour to show up again. I can’t figure out how to create the cookie to ... | <p>You can use <code>expires</code> with your cookie.</p>
<pre><code> # Pseudocode
var d = new Date();
d.setTime(d.getTime() + 60*60*1000); // in milliseconds
document.cookie = 'foo=bar;path=/;expires='+d.toGMTString()+';';
</code></pre>
<p>also you can use <code>max-age</code> with your cookie.</p>
... | javascript|python|cookies | 1 |
8,644 | 65,852,090 | Removing Stop Word From a Text in Python Without Using NLTK | <p>I made a list of stopwords in my native language in Python. How can I remove them without using NLTK when I type a text ?</p> | <p>Check this out (This only works if the language in question can be broken on spaces, but that hasn't been clarified – Thanks to Oso) :</p>
<pre><code>import numpy as np
your_stop_words = ['something','sth_else','and ...']
new_string = input()
words = np.array(new_string.split())
is_stop_word = np.isin(words,your_sto... | python|list|stop-words | 0 |
8,645 | 43,104,877 | Passing two queues to Tensorflow training | <p>I'm trying to create a train operation based on CIFAR10 example from Tensorflow that uses <code>tf.RandomShuffleQueue</code> and my labels comes from the name of the files as mentioned in (<a href="https://stackoverflow.com/questions/34051205/accessing-filename-from-file-queue-in-tensor-flow">Accessing filename from... | <p>I changed my code to:</p>
<pre><code>filenames = [os.path.join(FLAGS.data_path, f) for f in os.listdir(FLAGS.data_path)][1:]
np.random.shuffle(filenames)
file_fifo = tf.train.string_input_producer(filenames, shuffle=False, capacity=len(filenames))
reader = tf.WholeFileReader()
key, value = reader.read(file_fifo)
im... | tensorflow | 0 |
8,646 | 36,708,265 | why do I keep getting the same answer with this conditional, python pandas | <p>This might be a really dumb problem but I've been stuck on it for awhile. </p>
<p>Here's the csv</p>
<pre><code>DATE,TIME,OPEN,HIGH,LOW,CLOSE,VOLUME
02/03/1997,09:30:00,3045.00,3045.00,3045.00,3045.00,28
02/04/1997,09:30:00,3077.00,3078.00,3077.00,3077.50,280
02/05/1997,09:30:00,3094.00,3094.50,3094.00,3094.00,50... | <p>You works with Series, so you have to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.all.html" rel="nofollow"><code>all</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.any.html" rel="nofollow"><code>any</code></a>:</p>
<pre><code>b930 = df... | python-2.7|date|pandas|dataframe | 2 |
8,647 | 48,523,634 | PyQt4 QTextEdit: Vertical text in the HTML table | <p>I found example in PyQt4/examples/demos called Textedit, that creates documents from HTML file, and I'm using it for table reports like MS Access reports. Everything works fine, but I can't set text in HTML tables vertically. I'm trying that code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-co... | <p>QTextEdit only supports a subset of attributes, see here for those supported:</p>
<pre><code>http://doc.qt.io/archives/qt-4.8/richtext-html-subset.html
</code></pre>
<p>I would recommend QTextDocument with defaultStyleSheet property: </p>
<pre><code>http://doc.qt.io/archives/qt-4.8/qtextdocument.html#defaultStyl... | html|python-2.7|pyqt4 | 0 |
8,648 | 19,919,075 | Letter to different recipients and addresses | <p>I am trying to write a program that writes the same letter to each recipient and each address, but each letter will have the different names and address.</p>
<p>This is what i have so far.</p>
<pre><code>def main():
recipients = [] #should be names
adresses = [] #letters and numbers
filename = input("... | <p>There are several issues with your code.</p>
<p>First off, you're requesting a list of names and addresses, but you only get a single string from <code>input</code>. If you expect your user to specify several values, you'll need to parse that input string somehow to split up the values. For instance, you could spli... | python|python-3.x | 2 |
8,649 | 67,085,620 | Retrieving all posts by liked post's tags | <p>I am trying to implement a feature in my Social Media WebApp . I am trying to get all tags posts according to user's liked posts</p>
<p><em>For Example ( In Brief ) :-</em></p>
<blockquote>
<p>Suppose, <code>user_1</code> liked a <code>post</code> and that post contains <code>tags of</code> #tag1 , #tag2 , #tag3. AN... | <p>You can try filtering on <code>taggit.models.Tag</code> to get the tags that are related to posts liked by the user and then filtering the posts on those tags. Which will be something like (Untested):</p>
<pre class="lang-py prettyprint-override"><code>from taggit.models import Tag
def get_post(request,user_id):
... | python|html|django|tags | 1 |
8,650 | 48,208,193 | Remove Regex from string PySpark Dataframe Column | <p>I need to remove a regular expression from a column of strings in a pyspark dataframe</p>
<pre class="lang-py prettyprint-override"><code>df = spark.createDataFrame(
[
("Dog 10H03", "10H03"),
("Cat 09H24 eats rat", "09H24"),
("Mouse 09H45 runs ... | <p>this should do the work :</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql import functions as F
df = df.withColumn("Animal_strip_time", F.regexp_replace("Animal", r"\d\dH\d\d", ""))
df.show()
+--------------------+-----+------------------+ ... | python|regex|pyspark|apache-spark-sql | 5 |
8,651 | 73,615,475 | Using a for loop to get the value in the dictionary | <p>Agnes decides that she wants to start creating targeted advertisements for people. Here is a list of customer objects with information about their name, age, job, pet, and pet name. You'll use loops to find people that meet certain requirements for Agnes' targeted marketing. Write for loops with conditional statemen... | <p>The problem statement says that you shouldn't exceed 2 iterations. However, your code has this line:</p>
<pre class="lang-py prettyprint-override"><code> if iteration_count == 2:
</code></pre>
<p>This condition tests if you've reached the second iteration, not if you've exceeded it. Try stepping through your code... | python | 0 |
8,652 | 17,562,281 | Interested in making a 16-bit styled game in python | <p>Recently I had a great idea for a 16-bit-styled 2D side-scrolling game I would like to make. I know C++ is the preferred language for game development, but I'm not too familiar with it and it seems like a hassle to learn. I'm much more comfortable using python and I rather get to work while it is fresh in my mind. I... | <p>I recommend you to go with flash/actionscript for this, because you are looking for some libraries that will help you along the way? Pygame is amazing, but you will have to build everything by yourself, collision, blocks, scrolling, and if you check pyagame.org you will find some amazing games built on top of pygam... | python|2d|pygame|libraries | 0 |
8,653 | 64,427,431 | How to solve linear equations as string using sympy | <pre><code>from sympy import symbols, Eq, solve
x, y = symbols('x y')
eq1 = Eq(x+y, 5)
eq2 = Eq(x-y, -3)
solve((eq1,eq2), (x, y))
sol_dict = solve((eq1,eq2), (x, y))
print(f'x = {sol_dict[x]}')
print(f'y = {sol_dict[y]}')
</code></pre>
<p>I am taking two linear equations as string</p>
<pre><code># x+y=5
# x-y=-3
</... | <p>This may be helpful you can try with this...</p>
<pre><code>from sympy import symbols, Eq, solve
x, y = symbols('x y')
string_1 = 'x+y=5'
string_2 = 'x-y=-3'
eq1 = Eq(eval(string_1.split('=')[0]), int(string_1.split('=')[-1]))
eq2 = Eq(eval(string_2.split('=')[0]), int(string_2.split('=')[-1]))
solve((eq1,eq2), (x... | python|sympy | 1 |
8,654 | 70,008,167 | How to set the protocol (http, ws etc.) for the end-point using Jinja2 & url_for | <p>I am trying to use the <code>url_for(...)</code> function in Python/Jinja2 to create an end-point for a web-socket.</p>
<p>How can I tell <code>url_for(...)</code> inside my template to use the 'ws' (web socket) protocol instead of 'http'?</p> | <p>The <a href="https://flask.palletsprojects.com/en/2.0.x/api/#flask.url_for" rel="nofollow noreferrer"><code>url_for</code></a> has two attributes you can use for this purpose:</p>
<ul>
<li><code>_external = True</code> for generating absolute URLs</li>
<li><code>_scheme = ''</code> for setting an empty URL scheme (<... | python|flask|jinja2|fastapi | 0 |
8,655 | 55,837,461 | Grouping queryset by column value | <p>I have a queryset that returns Tasks by client id from the following models and would like to get some more filters to receive more precised data. Models are just a example structure of what I am trying to achieve:</p>
<pre><code>class Client(models.Model):
name = models.CharField(max_length=255)
def __str_... | <p>You could use a QuerySet on <code>Area</code> with <code>prefetch_related</code>.</p>
<pre><code>areas = Area.objects.prefetch_related('task_set')
for area in areas:
area_tasks = area.task_set.all()
</code></pre> | python|django|django-orm | 1 |
8,656 | 49,800,656 | Can't import subprocess python3.6 | <p>Not sure exactly what went wrong but after installing python3-devel I can no longer import subprocess. As a result I can't use pip or some important scripts I have written for my workflow. Here is the error I'm getting:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module&... | <p>Same problem here with OpenSuse Leap while trying to create a virtual environment. I get the exact same error as you, updating the system does not fix it, neither is updating anaconda. Maybe this is related to an update of Opensuse that causes an error with subprocess?</p>
<p>[EDIT]: I solved this by removing and r... | python|linux|subprocess|python-3.6|opensuse | 1 |
8,657 | 50,193,538 | How to kill process on GPUs with PID in nvidia-smi using keyword? | <p>How to kill running processes on GPUs for a specific program (e.g. python) in terminal?
For example two processes are running with python in the top picture and kill them to see the bottom picture in nvidia-smi</p>
<p><a href="https://i.stack.imgur.com/SMzOK.png" rel="noreferrer"><img src="https://i.stack.imgur.com... | <p>The accepted answer doesn't work for me, probably because <code>nvidia-smi</code> has different formats across different versions/hardware.</p>
<p>I'm using a much cleaner command:</p>
<pre><code>nvidia-smi | grep 'python' | awk '{ print $3 }' | xargs -n1 kill -9
</code></pre>
<p>You can replace <code>$3</code> i... | python|gpu|nvidia|keyword|pid | 55 |
8,658 | 64,859,605 | How can i upload a link to a href function through the admin panel in django? | <p>i have made a models file that posts to the index template through the admin panel. I just made it <a href="https://i.stack.imgur.com/WXAaP.png" rel="nofollow noreferrer">this way </a>so you can access it by clicking the download button. But after clicking download it shows <a href="https://i.stack.imgur.com/m4p4Z.p... | <p>Your href attribute is now interpreted as a relative path. If you want it to redirect you to external site add "https://" at the start of it just like that:</p>
<pre><code>href="https://{{ i.app_download_link }}"
</code></pre> | django-models|django-templates|python-3.9 | 0 |
8,659 | 63,777,516 | Finding Duplicates In a column Except 0 in Pandas | <p>I have a Dataframe with Position varying starting from 0.
So I have to check whether the Position is having duplicate values except 0.As 0 can be present multiple times in my case.</p>
<pre><code>if df['Position'].duplicated().any():
print("Duplicate Positions found..Positions should be unique..Exiting")
... | <p>You can chain mask by test for not <code>0</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow noreferrer"><code>Series.ne</code></a>:</p>
<pre><code>df = pd.DataFrame({'Position':[0,1,2,0]})
if (df['Position'].duplicated() & df['Position'... | python|pandas | 1 |
8,660 | 52,919,722 | histogram not showing in pdf when subploting | <p>I am trying to plot in a pdf file a time series and a histogram for each of the variables in my data frame. Each action works separately, but when subploting both of them in the same page, the histogram is not showing. Any idea what I am doing wrong? Here's my code:</p>
<pre><code>with PdfPages('test.pdf') as pdf:
... | <p>I'm not quite sure if I could really reproduce your error - however, there are some things I would optimize in your code, perhaps you can think about it with this example:</p>
<pre><code>with PdfPages('test.pdf') as pdf:
for c in df:
fig, axs = plt.subplots(2)
#time series
fig.suptitle(c... | python|matplotlib|histogram|pdfpages | 0 |
8,661 | 71,999,521 | How to find the href attributes using Selenium Python | <p>I tried many of the web solution but I can't find how to find the HREF.</p>
<p>One of my code:</p>
<pre><code>driver = webdriver.Chrome(executable_path='C:\chromedriver.exe')
driver.get(("https://cordis.europa.eu/search/fr?q=contenttype%3D%27project%27%20AND%20programme%2Fcode%3D%27H2020%27&p=1&num=100&... | <p>The <em><code>href</code></em> attributes are within the following <em><code><a></code></em> nodes.</p>
<pre><code><a _ngcontent-jdx-c99="" class="c-card-search__title ng-star-inserted" href="/project/id/881603"> Graphene Flagship Core Project 3 </a>
</code></pre>
<hr ... | python|selenium|xpath|css-selectors|webdriverwait | 1 |
8,662 | 68,570,458 | Pandas split columns on first % sign, on 2nd letter | <p>We have the following dataframe</p>
<pre><code># raw_df
print(raw_df.to_dict())
{'Edge': {1: '-1.9%-2.2%', 2: '+5.8%-9.4%', 3: '+3.5%-7.2%'}, 'Grade': {1: 'D+D', 2: 'BF', 3: 'B-F'}}
</code></pre>
<p><a href="https://i.stack.imgur.com/mBQNXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mBQNXm.p... | <p>Looks like you already have your solution, but here is another idea for splitting <code>Edge</code> without regex:</p>
<ol>
<li><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.rstrip.html" rel="nofollow noreferrer"><code>strip</code></a> the trailing <code>'%'</code></li>
<li><a href="https:/... | python|pandas | 2 |
8,663 | 68,665,581 | How to find True Postive only for Data Frame while having Ground Truth? | <p>first of all, sorry for the long description but I want that everyone understands my problem with what I doing.</p>
<p>I am working on a detection model which predicts 14 different pathologies and I have made an inference file that does prediction for any new test images.
The dataset having test images of about 25k+... | <p>From your <code>DataFrame</code> :</p>
<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> df
file set label bbx Atelectasis Cardiomegaly Consolidation Edema Effusion Emphysema Fibrosis Hernia ... | python|pandas|dataframe|model|prediction | 1 |
8,664 | 71,157,139 | How to build a character-level siamise network using Keras | <p>I am trying to build a Siamese neural network on characters-level using Keras, to learn if two names are similars or not.</p>
<p>So my two <strong>inputs</strong> <strong>X1</strong> and <strong>X2</strong> are a 3-D matrices:<br />
<em>X[number_of_cases, max_length_of_name, total_number_of_chars_in_DB]</em></p>
<p>... | <p>Your model inputs were <code>[input_1, input_2]</code> and outputs were <code>predictions</code>. But <code>input_1</code> and <code>input_2</code> were not connected to <code>lstm1</code> and <code>lstm2</code>, so the input layers of the model was not connected to the output layer, that's why you are getting the e... | python|keras|siamese-network | 1 |
8,665 | 71,218,069 | How to create a filter input function with Python? | <p>I am trying to write a Python code which opens a csv file with a list of books, its authors, genre etc, and allows the user to input an ISBN number and based on that it displays the results that match the search.</p>
<p>The csv file has 500 rows and 7 columns separated by comma.</p>
<p>That's my code. Now, the code ... | <p>You can filter in an easier way:</p>
<pre><code>print(df[df["ISBN"] == "3775738193"])
</code></pre> | python|csv | 1 |
8,666 | 61,008,522 | Run multiple videos through multiprocessing using concurrent futures | <p>I am trying to run the code using concurrent.futres.ProcessPoolExecuter but facing mentioned below error while running the video in <code>while true</code> condition in <code>class get_frames</code></p>
<pre><code>concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly wh... | <p>You may stick to the <a href="http://ProcessPoolExecutor%20Example" rel="nofollow noreferrer">ProcessPoolExecutor Example</a>. </p>
<p>The example is as follows: </p>
<pre><code>def main():
with concurrent.futures.ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_pri... | python|python-3.x|opencv|multiprocessing|process-pool | 1 |
8,667 | 61,088,993 | How should I accept this text file when I am running Python from command line? | <p>This is the way that the program will be run:
<code>Python LinkState < test1.txt</code>
<code>Linkstate</code> is the name of the .py file. test1.txt is the name of the text file being accepted in the python code.
So my question is how should I handle the txt file in my code for this to work?</p>
<p>I assume thi... | <p>Actually, the way the command is setup is using soemthing called IO redirection which is a construct that is more inline with Unix-like systems than Windows for reasons I won't get into here (I would defer to this great <a href="https://unix.stackexchange.com/questions/141016/a-laymans-explanation-for-everything-is-... | python|python-3.x|command-line|file-io | 1 |
8,668 | 72,534,795 | generating random values and append the results in next columns | <p>The first thing I want to do is get four numbers from the user and put them in the first column.(For example: 10,30,60,80)
Then I need to create another columns(second), in addition to the first column, and the rows of the second column should vary as shown below.</p>
<pre><code>10 Values should range from 1-2
30 v... | <p>You can do this with pandas and <a href="https://numpy.org/devdocs/reference/random/generated/numpy.random.Generator.uniform.html" rel="nofollow noreferrer">numpy</a>:</p>
<pre><code>import pandas as pd
import numpy as np
inp_data=[10, 30, 60, 80]
# mapping dict for the ranges
ranges = {10: [1,2],
30: [3... | python|dataframe|numpy | 0 |
8,669 | 68,398,917 | How to change pandas' Datetime Index from "End of month" To just "Month" | <p>I'm using pandas to analyze some data about the House Price Index of all states from quandl:
HPI_Data = quandl.get("FMAC/HPI_AK")</p>
<p>The data looks something like this:</p>
<pre><code> HPI Alaska
Date
1975-01-31 35.105461
1975-02-28 35.465209
1975-03-31 35.843110
</code></pre>
<p... | <p>Not sure if I understand correctly. So please clarify your question if this is not correct.</p>
<p>You can convert a string to a pandas date time object using <code>pd.to_datetime</code> and use the <code>format</code> parameter to specify how to parse the string</p>
<pre><code>import pandas as pd
# Creating a dumm... | python|pandas | 1 |
8,670 | 62,964,122 | Pandas create multiple columns based on other columns | <p>I have a huge df (720 columns) with this structure:</p>
<pre><code>id A B C
1 1 0 1
2 1 0 1
3 1 1 1
</code></pre>
<p>I would like to create a new df, based on calculations such as:</p>
<pre><code>if A and B = 1 then v1 = 1
if A and C = 1 then v2 = 1
if A and D = 1 then v3 = 1
if A and XX = 1 then v719 = 1
id... | <p>For your question we can do , since 1 * 1 = 1</p>
<pre><code>s=df.loc[:,'B':].mul(df.A,axis=0)
B C
0 0 1
1 0 1
2 1 1
s.columns=np.arange(s.shape[1])+1
df=df.join(s.add_prefix('v_'))
</code></pre> | python|pandas | 3 |
8,671 | 58,946,326 | Having trouble savings links to a list variable with selenium | <p>Practicing web scraping through selenium by opening user's dating profiles through a dating site. I need selenium to save a href link for every profile on the page but unfortunately it only saves the first profile on the list, rather than creating a list variable with all the links saved. All of the profiles start w... | <p>use <code>find_elements_by_css_selector</code> instead of <code>find_element_by_css_selector</code>
<a href="https://selenium-python.readthedocs.io/locating-elements.html" rel="nofollow noreferrer">link</a></p>
<p>if you're going to loop through the whole list returned from <code>find_elements_by_css_selector</code... | python | 0 |
8,672 | 59,822,462 | kivy app runs without implementing the build() method | <p>Was wondering why the Kivy code kept on showing me the same black window despite doing some updates on the kv file. Then noticed I had a typo on the <code>buidl()</code> method.</p>
<p>From the docs "...<em>implementing its build() method so it returns a Widget instance (the root of your widget tree)</em>
...", you... | <p>Kivy apps have a default <code>build()</code> method, which you can see <a href="https://github.com/kivy/kivy/blob/master/kivy/app.py#L582" rel="nofollow noreferrer">here</a>; it just returns an empty widget. Generally kivy has two methods to create the root widget tree, either through overriding <code>build()</code... | python|kivy|kivy-language | 1 |
8,673 | 49,084,143 | OpenCV live stream video over socket in Python 3 | <p>I am trying to create a simple application to send live stream video over the socket in Python 3 with OpenCV. I am new to OpenCV and socket programming so if you can provide answer in detail I will be very grateful. Thank you.</p>
<p>Here is sender.py</p>
<pre><code>import socket
import time
import cv2
capture =... | <p>I'm the author of <a href="https://github.com/abhiTronix/vidgear" rel="nofollow noreferrer"><strong>VidGear</strong></a> Video Processing python library that now also provides <a href="https://abhitronix.github.io/vidgear/latest/gears/netgear/overview/" rel="nofollow noreferrer"><strong>NetGear API</strong></a>, whi... | python|python-3.x|sockets|opencv | 9 |
8,674 | 45,173,451 | scikit-learn: How to calculate root-mean-square error (RMSE) in percentage? | <p>I have a dataset (found in this link: <a href="https://drive.google.com/open?id=0B2Iv8dfU4fTUY2ltNGVkMG05V00" rel="nofollow noreferrer">https://drive.google.com/open?id=0B2Iv8dfU4fTUY2ltNGVkMG05V00</a>) of the following format. </p>
<pre><code> time X Y
0.000543 0 10
0.000575 0 10
0.041324 1 10
0.041331... | <p>Your implementation of <code>calculate_mape</code> is not working because you are expecting the <code>check_arrays</code> function, which was removed in <code>sklearn 0.16</code>. <code>check_array</code> is not what you want.</p>
<p><a href="https://stackoverflow.com/a/42251083/58866">This</a> StackOverflow answer... | python|python-3.x|pandas|scikit-learn|random-forest | 6 |
8,675 | 57,919,330 | File watch in the directory using Python and then send data using POST request on file modification | <p>I want to watch two different Directory for excel file modification(timestamp) and after modification I want to call one API HTTP Post request to one endpoint, I have already wrote below code using Python Watchdog and requests library, but facing two error in the same. </p>
<p>Problem 1:- event(event.event_type == ... | <p><strong>Problem 1: Event "modified" fired twice</strong> </p>
<p>This issue appears because multiple operations can occur when you save a file, data are changed, then the metadata (last modified ...). It can be hard to handle depending on what you need and the frequency of changes if there are many users. </p>
<p>... | python|python-3.x|python-requests|watchdog|python-watchdog | 1 |
8,676 | 42,308,801 | Python lucene function add field contents to document not working | <p>I am indexing url pages with python lucene. </p>
<p>I had some errors trying to add fields to the Document. I am not sure why.
The error says:</p>
<p>JavaError: , >
Java stacktrace:
java.lang.IllegalArgumentException: it doesn't make sense to have a field that is neither indexed nor stored
at org.apache.l... | <p>If a field is neither indexed nor stored, it would not be represented in the index in any way, thus it doesn't make sense for it to be there. I'm guessing that you want to index FieldType t2. To do that, you need to <a href="https://lucene.apache.org/core/6_4_0/core/org/apache/lucene/document/FieldType.html#setIndex... | java|python|lucene|document|indexwriter | 0 |
8,677 | 58,190,556 | Offset function using If else statement | <p>I have a pd df and I want to create a third column"LCC_saving" based on the following conditions.</p>
<pre><code>nvals=df['Offset_base']
for i, row in df.iterrows():
if nvals <0:
df.at[i,'LCC_savings']=df.loc[i+row['Offset_base']]['LCC']-row['LCC']
else:
df.at[i,'LCC_savings'] = 0
df
Offset_base ... | <p>Although this kind of problems can be solved with <code>iterrows</code> and <code>iat</code> or maybe even some operations implying shift, I think the easiest, fastest and most straightforward way is to do the calculation on the underlying numpy array and assign the result to the dataframe:</p>
<pre><code>import pa... | pandas | 1 |
8,678 | 28,733,478 | takes a list of lists of numbers and displays them as strings in a grid | <p>I am trying to define a function that that takes a list of lists such as [[0,1,2,3,4,5],[0,1,4,9,16,25],[0,1,8,27,64,125]] and returns a grid of the numbers using "\t" like this</p>
<pre><code>0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
</code></pre>
<p>So far all I have is:</p>
<pr... | <p>You could do as follows:</p>
<pre><code>l = [[0,1,2,3,4,5],[0,1,4,9,16,25],[0,1,8,27,64,125]]
print("\n".join("\t".join(map(str, v)) for v in l))
</code></pre>
<p>Which results in:</p>
<pre><code>0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
</code></pre>
<p>If you want to reuse this code... | python|list|python-3.x|for-loop|nested-lists | 1 |
8,679 | 53,493,289 | How to parse datetime and time from strings and how to add these parsed datetime and time values in Python | <p>I am parsing datetime objects from strings,
In these situation I faced a problem where I have to add datetime object with time object together to create combined timestamp.</p>
<p>I know there is a datetime.combine method but unfortunately I could not use it in this situation</p>
<p>e.g. there are two strings, on... | <pre><code>dt_str = "2018/11/27 14:12:32"
tm_str = "1:23:45.678"
</code></pre>
<p>First we need to import from python's standard libraries i.e. datetime, time and timedelta</p>
<pre><code>import datetime, time
from datetime import timedelta
</code></pre>
<p>Then we will parse dt_str as datetime object and tm_str as ... | python|datetime|time|timedelta | 1 |
8,680 | 43,588,442 | Merge and aggregate list entries with pandas, without removing fields | <p>I have lists of this format:</p>
<pre><code>['bear', 'brown', 'mammal', 1233],
['cat', 'black', 'mammal', 1533],
['bear', 'brown', 'mammal', 2345],
['bear', 'black', 'mammal', 2345]
</code></pre>
<p>I would like to aggregate the numbers at the end if the first three strings are identical and remove the duplicate e... | <pre><code>In [137]: pd.DataFrame(d).groupby([0,1,2]).sum().reset_index().values.tolist()
Out[137]:
[['bear', 'black', 'mammal', 2345],
['bear', 'brown', 'mammal', 3578],
['cat', 'black', 'mammal', 1533]]
</code></pre>
<p>where <code>d</code> is a list:</p>
<pre><code>In [138]: d
Out[138]:
[['bear', 'brown', 'mamma... | python|pandas | 3 |
8,681 | 46,749,037 | Can I use Train AND Test data for Imputation? | <p>Interestingly, I see a lot of different answers about this both on stackoverflow and other sites:</p>
<p>While working on my training data set, I imputed missing values of a certain column using a decision tree model. So here's my question. Is it fair to use ALL available data (Training & Test) to make a model ... | <p>Do not use any information from the Test set when doing any processing on your Training set. @Maxim and the answer linked to are correct, but I want to augment the answer. </p>
<p>Imputation attempts to reason from incomplete data to suggest likely values for the missing entries. I think it's helpful to consider th... | python-2.7|data-science|imputation | 4 |
8,682 | 70,467,838 | How do you output boolean if column containing lists have elements from another larger list? | <p>I have a column where each row contains a list of strings of varying lengths. I need to create a new column that has a list of booleans (equivalent to the original list) of whether or not each element is found in ANOTHER (larger) list.</p>
<p>This is what I am doing and well, it clearly does not work. I based it off... | <p><code>explode</code> flattens all the lists in a Series, but items that were in the same list all share the same index that the list they came from did, so after you use <code>isin</code> to check which items of <code>main_list</code> are in the Series, you can use <code>groupby</code> with <code>level=0</code> to g... | python|pandas|list-comprehension | 3 |
8,683 | 73,255,065 | Python: How can one verify that dict1 is only a subset of dict2? Values are all int and within scope | <p>I'm trying to build some efficient code that can tell if one dict is a subset of another. Both dicts have string keys and int values. For dict1 to be considered a subset, it can not contain any unique keys and all values must be less than or equal to the equivalent key's value in dict2.</p>
<p>This almost worked:
<c... | <pre><code>all(test_dict2.get(k, v-1) >= v
for k, v in test_dict.items())
</code></pre>
<p><a href="https://tio.run/##K6gsycjPM7YoKPr/vyS1uCQ@JTO5RMFWoZpLAQjUE9WtDHUgzGR1KyOuWi4uuCojrMqSgMoQOoxBOrgKijLzSjQSc3I0EJr10lNLNLJ1FMp0DTUV7GwVysB6ICAtv0gBJKWQmacA16GXWZKaW6yhqan5/z8A" rel="nofollow noreferrer" title="Pyth... | python|python-3.x | 1 |
8,684 | 50,218,600 | How to train a variable along with weights and bias in tensorfow | <p>I have a very basic doubt in tensorflow.</p>
<p>I have added a variable say 'var' in convolution layer, I want to update this variable('var') with gradient during training like our weights and bias are updated.
I have added this variable to 'trainable params' but its not updated. Can someone shed light on how to tr... | <p>The whole point of the optimization procedure is to update variables that the loss function depends on in a way to reduce the value of the loss.
Neither<code>loss</code> nor any variable that <code>loss</code> depends on does not depend on <code>var</code> (in other words <code>var</code> is not used in any computat... | tensorflow | 2 |
8,685 | 50,186,918 | Does default memory allocated for a datatype play a role in rounding? In what manner a float is rounded if it exceeds allocated memory? | <p>Having a file test2.py with the following contents:</p>
<pre><code>print(2.0000000000000003)
print(2.0000000000000002)
</code></pre>
<p>I get this output:</p>
<pre><code>$ python3 test2.py
2.0000000000000004
2.0
</code></pre>
<p>I thought lack of memory allocated for float might be causing this but ... | <p>IEEE 754 64-bit binary floating point always uses 64 bits to store a number. It can exactly represent a finite subset of the <strong>binary</strong> fractions. Looking only at the normal numbers, if <code>N</code> is a power of two in its range, it can represent a number of the form, in binary, <code>1.s*N</code> wh... | python-3.x|floating-point|rounding | 1 |
8,686 | 63,949,828 | "@" for tensor multiplication using pytorch | <p>This article <a href="https://towardsdatascience.com/understand-kaiming-initialization-and-implementation-detail-in-pytorch-f7aa967e9138" rel="nofollow noreferrer">https://towardsdatascience.com/understand-kaiming-initialization-and-implementation-detail-in-pytorch-f7aa967e9138</a> about intelligent weights initiali... | <p>It doesn't require anything as such. Just <code>import torch</code> is enough (and the two operands must be tensors). For example, I tried</p>
<pre><code>import torch
a = torch.randn((2, 2)) # tensor([[-0.3023, -1.3499], [-2.5096, -0.8977]])
b = torch.randn((2, 3)) # tensor([[-1.3319, 2.2378, -0.1892], [-0.3895, -0... | python|pytorch | 2 |
8,687 | 63,789,417 | Azure Application Insights logging for Python Application - Set Exception properties explicitly | <p>I am trying to send Exceptions from my <strong>Python application</strong> running in <strong>Azure App service</strong> to the designated <strong>Azure Application Insights</strong> instance. I am using <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/opencensus-python" rel="nofollow noreferrer">Op... | <p>You can add custom properties to your log messages (not only exception, but all other log types too like trace, event etc.) in the extra keyword argument by using the <code>custom_dimensions</code> field. These properties appear as key-value pairs in <code>customDimensions</code> in Azure Monitor. Then you can query... | python|azure-application-insights|azure-appservice|opencensus | 7 |
8,688 | 72,052,467 | Create a customer converter and validator using ATTRS | <p>I am trying to learn attrs and I have two questions. Please note that I am using the ATTRS library, not ATTR.</p>
<ol>
<li>How do I create a converter to change typ to uppercase?
---> I solved this question. The formula below is updated. :)</li>
<li>How do I create a validator to ensure that typ is contained w... | <p>For whomever needs it, here is the answer.</p>
<pre><code>from attrs import define, field, validators, setters
from datetime import datetime
typs = ['O', 'D', 'W', 'C']
@define(slots=True)
class Trans:
acct: int = field(validator=validators.instance_of(int), converter=int)
id: int = field(val... | python|python-attrs | 0 |
8,689 | 71,619,212 | Error using np.arange() in t_span with solve_ivp error in Scipy 1.8.0 but not 1.5.0 | <p>For the following input</p>
<pre class="lang-py prettyprint-override"><code>neuron_dict = {'param_set': sb.morris_lecar_defaults(V_3 = 11.96), 'time_range': (0, 10000, 0.0001), 'initial_cond': (-3.06560496e+01, 7.33832272e-03, 8.35251563e-01), 'stretch': 4.2, 'track_event': sb.voltage_passes_threshold ,'location':... | <p>According to the docs</p>
<pre><code>t_span
2-tuple of floats
Interval of integration (t0, tf). The solver starts with t=t0 and
integrates until it reaches t=tf.
</code></pre>
<p>For a 2 element tuple, these are the same:</p>
<pre><code>t0, tf = map(float, t_span)
t0, tf = float(t_span[0]), float(t_span[1])
</co... | python|numpy|scipy | 0 |
8,690 | 10,328,289 | Replace string values in lists | <p>I have a list :</p>
<pre><code>s = ["sam1", "s'am2", "29"]
</code></pre>
<p>I want to replace <code>'</code> from the whole list.<br>
I need output as </p>
<pre><code>s = ["sam1", "sam2", "30"]
</code></pre>
<p>currently I am iterating through the list.<br>
Is there any better way to achieve it?</p> | <p>You could try this:</p>
<pre><code> s = [i.replace("'", "") for i in s]
</code></pre>
<p>but as pointed out this is still iterating through the list. I can't think of any solution that wouldn't include some sort of iteration (explicit or <em>implicit</em>) of the list at some point.</p>
<p>If you have a lot of d... | python|string|list | 7 |
8,691 | 62,760,105 | Open interval (a,b) and half-open interval (a,b] using Python's linspace | <p>A half-open interval of the form [0,0.5) can be created using the following code:</p>
<p><code>rv = np.linspace(0., 0.5, nr, endpoint=False)</code></p>
<p>where nr is the number of points in the interval.</p>
<p><strong>Question:</strong> How do I use linspace to create an open interval of the form (a,b) or a half-o... | <p>Probably the simplest way (since this functionality isn't built in to <code>np.linspace()</code>) is to just slice what you want.
Let's say you're interested in the interval [0,1] with a spacing of 0.1.</p>
<pre class="lang-py prettyprint-override"><code>>>> import numpy as np
>>> np.linspace(0, 1... | python|linspace | 4 |
8,692 | 61,750,471 | Finding maximum index of a specific value where it occurs consecutively more than N times | <p>I have an array like this</p>
<pre><code>sample = np.array([[9.99995470e-01],
[9.99992013e-01],
[1.00000000e+00],
[1.00000000e+00],
[1.00000000e+00],
[1.00000000e+00],
[9.99775827e-01],
... | <p>Using groupby</p>
<p><strong>Code</strong></p>
<pre><code>import numpy as np
from itertools import groupby
def find_max_index(arr):
# consecutive runs of ones
# Use enumerate so we have the index with each value
run_ones = [list(v) for k, v in groupby(enumerate(sample.flatten()), lambda x: x[1]) if k == 1]... | python|arrays|numpy|indexing | 2 |
8,693 | 67,577,189 | Compute daily frequency on a time series | <p>Task:</p>
<p>Calculate the frequency of each ID for each month of 2021</p>
<p>Frequency formula: Activity period (Length of time between last activity and first activity) / (Number of activity Days - 1)</p>
<p>e.g. ID 1 - Month 2: Activity Period (2021-02-23 - 2021-02-18 = 5 days) / (3 active days - 1) == Frequency ... | <p>Try a <a href="https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html#pandas-pivot-table" rel="nofollow noreferrer">pivot_table</a> with a custom aggfunc:</p>
<pre><code># Create Columns For Later
dr = pd.date_range(start=df['Date'].min(),
end=df['Date'].max() + pd.offsets.MonthBegin... | python|pandas|datetime|python-datetime | 1 |
8,694 | 67,347,586 | Pandas: Groupby Fill disappear the column | <p>I have dataframe. I am doing a groupby and doing a ffill. Post this I can't see the column over which I grouped. Why? What can I do to mitigate this? My code below:</p>
<pre><code>df.groupby(["col1"], as_index=False).fillna(method="ffill")
</code></pre> | <p>Try this:</p>
<pre><code>df.groupby('col1', as_index=False).apply(lambda x: x.fillna(method="ffill"))
</code></pre>
<h3>Why applying apply method?</h3>
<p>Group by is - split-apply-combine.</p>
<p>Group by groups can be divided into 4 parts.</p>
<p><strong>Aggregation</strong></p>
<p>Aggregation functions ... | pandas | 1 |
8,695 | 71,427,254 | How is self() used in Pytorch to generate predictions? | <pre><code>class MNIST_model(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, xb):
xb = xb.reshape(-1, 28 * 28)
out = self.linear(xb)
return out
def training_step(self, batch):
images, ... | <p>This is actually nothing specific to PyTorch but rather to how Python works.
Using parenthesis on an object or directly on <em>self</em> inside that class will call a special Python function named <a href="https://docs.python.org/3/reference/datamodel.html#object.__call__" rel="nofollow noreferrer"><code>__call__</c... | python|pytorch | 1 |
8,696 | 71,229,188 | keeps failing installing aif360 package in Pycharm | <p>I'm trying to install AIF360 package in Pycharm,</p>
<p>but whatever I try, either on command line or pycharm's own package managing system,</p>
<p>it keeps failing with this message:</p>
<pre><code> Collecting aif360
Using cached aif360-0.4.0-py3-none-any.whl (175 kB)
Collecting scikit-learn>=0.22.1... | <p>For those who have faced the same issue,
I was able to resolve it by changing the python interpreter version to the matching one, which was surprisingly 3.1, which has to be at least 3.5 by requirement.
You can change the interpreter version either by creating a new project or in the settings in Pycharm.</p> | numpy|installation|pycharm|package|subprocess | 0 |
8,697 | 11,450,158 | How do I set proxy for chrome in python webdriver? | <p>I'm using this code:</p>
<pre><code>profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", "proxy.server.address")
profile.set_preference("network.proxy.http_port", "port_number")
profile.upda... | <pre><code>from selenium import webdriver
PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")
</code></pre> | python|google-chrome|proxy|webdriver | 114 |
8,698 | 56,446,148 | Algorithm to dynamically populate Javascript array with zeros before and after values | <p>I get a data of months dynamically with python/django and pass it to my template. There I use Javascript to manipulate the data </p>
<p>That means that in my template I have a javascript array, each number representing a month like so: </p>
<p><code>months = [1,2,3,4]</code></p>
<p>or so:</p>
<p><code>months = [... | <p>You could take a new array and fill it with the items on the index, if found or with zero.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const fill = m => Array.from({... | javascript|python|arrays|django | 6 |
8,699 | 18,169,405 | error in flask-peewee Admin User creation | <p>Database example.db is created but generates error !!! </p>
<hr>
<p>Traceback (most recent call last):
File "db_testing.py", line 39, in admin.save()<br>
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 2405, in save
new_pk = insert.execute()<br>
File "C:\Users\dell\Envs\surveyApp\l... | <p>Database was already created, deleting previous database solved it</p> | python|sqlite|python-2.7|orm|peewee | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.