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 |
|---|---|---|---|---|---|---|
9,100 | 41,069,101 | Class with method that applies any function to the arguments? | <p>I need a class with a mmethod that takes a function as argument and applies the function to each element of a list</p>
<pre><code>class matrix:
def __init__(self,xs):
self.xs=xs #xs is a list
def map(self,function): ??? I don't know how to implent this one
</code></pre>
<p>The result should be so... | <p>you can call the function normally even if passed as a parameter. I would call it in a list comprehension on <code>self.xs</code>:</p>
<pre><code>from math import sqrt
class matrix:
def __init__(self,xs):
self.xs=xs #xs is a list
def map(self,function):
return [function(x) for x in self.x... | python | 2 |
9,101 | 38,225,948 | How to get the plot of clusters in this python code? ValueError: x and y must have same first dimension | <pre><code>Error:
Traceback (most recent call last):
File "/Users/ankitchaudhari/PycharmProjects/Learn/datascience/gg.py", line 33, in <module> plt.plot(a, k)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/pyplot.py", line 3154, in plot
ret = ax.plot(*args, **kwar... | <p>Your indentation is broken</p>
<pre><code>sse = 0
for i in k:
label = kmeans(data, i)
cluster_mean = df.mean()
d = np.zeros([], dtype=float)
# for i in k has finished here
# label, cluster_mean and d frozen in their last state
for j in range(len(label)):
sse += sum(pow((data[j]) - cluster_mean, 2))
a = np... | python|python-3.x|matplotlib|scikit-learn|scatter-plot | 1 |
9,102 | 38,352,040 | Python, Postgres, and integers with blank values? | <p>So I have some fairly sparse data columns where most of the values are blank but sometimes have some integer value. In Python, if there is a blank then that column is interpreted as a float and there is a .0 at the end of each number.</p>
<p>I tried two things:</p>
<ul>
<li>Changed all of the columns to text and t... | <p>You could take advantage of the fact you are using POSTGRESQL (9.3 or above), and implement a "poor man's sparse row" by converting your data into Python dictionaries and then using a JSON datatype (JSONB is better).</p>
<p>The following Python snippets generate random data in the format you said you have yours, co... | python|postgresql|sqlalchemy | 1 |
9,103 | 30,809,165 | HTML not being rendered in a Flask blog that accepts Markdown | <p>Using a simple blog engine written on Flask (<a href="https://github.com/dmaslov/flask-blog" rel="nofollow noreferrer">https://github.com/dmaslov/flask-blog</a>) that accepts markdown for writing posts.</p>
<p>Markdown should support HTML. For some reason, my HTML is not being recognized, and my tags are rendered l... | <p>This engine escapes html tags. Unfortunately or luckily you may use only wysiwyg editor.</p>
<p>In <code>post.py</code> file </p>
<p>line 162</p>
<p><code>cgi.escape(post_data['body'], quote=True)</code></p>
<p>More info about escaping <a href="https://docs.python.org/2/library/cgi.html#cgi.escape" rel="nofollow... | python|flask|markdown | 1 |
9,104 | 30,959,197 | 'str' object has no attribute 'save' | Django Views: Having a button that triggers a global setting variable to be saved to a Model field | <p>I am working on a terms and conditions functionality for my app. Unfortunately I am pretty new to django and need some help.</p>
<p>I am getting the following error when I submit my form in the /terms template:</p>
<pre><code>'str' object has no attribute 'save'
</code></pre>
<p>This is my terms.html template:</p... | <p>If <code>TERMS</code> is a string (as it appears to be), then the error makes complete sense. You assign a string to <code>Profile.filed_terms</code>, then in the very next line attempt to call a <code>.save()</code> method on it. Strings do not have a <code>save()</code> method, hence the error.</p> | python|django | 1 |
9,105 | 40,032,276 | spark dataframe keep most recent record | <p>I have a dataframe similar to: </p>
<pre><code>id | date | value
--- | ---------- | ------
1 | 2016-01-07 | 13.90
1 | 2016-01-16 | 14.50
2 | 2016-01-09 | 10.50
2 | 2016-01-28 | 5.50
3 | 2016-01-05 | 1.50
</code></pre>
<p>I am trying to keep the most recent values for each id, like this:</p>
<pre>... | <p>The window operator as suggested works very well to solve this problem:</p>
<pre><code>from datetime import date
rdd = sc.parallelize([
[1, date(2016, 1, 7), 13.90],
[1, date(2016, 1, 16), 14.50],
[2, date(2016, 1, 9), 10.50],
[2, date(2016, 1, 28), 5.50],
[3, date(2016, 1, 5), 1.50]
])
df = r... | python|apache-spark | 13 |
9,106 | 40,024,643 | Regular expression to match a specific pattern | <p>I have the following string:</p>
<pre><code>s = "<X> First <Y> Second"
</code></pre>
<p>and I can match any text right after <code><X></code> and <code><Y></code> (in this case "First" and "Second"). This is how I already did it:</p>
<pre><code>import re
s = "<X> First <Y> Seco... | <p>How about something like: <code><?[XY]>? ([^<>XY$ ]+)</code></p>
<p>Example in javascript:</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 re = /<?[XY... | python|regex | 2 |
9,107 | 40,083,266 | Replace comma with dot Pandas | <p>Given the following array, I want to replace commas with dots:</p>
<pre><code>array(['0,140711', '0,140711', '0,0999', '0,0999', '0,001', '0,001',
'0,140711', '0,140711', '0,140711', '0,140711', '0,140711',
'0,140711', 0L, 0L, 0L, 0L, '0,140711', '0,140711', '0,140711',
'0,140711', '0,140711', ... | <p>If you are reading in with <code>read_csv</code>, you can specify how it interprets decimals with the <code>decimal</code> parameter.</p>
<p>e.g.</p>
<pre><code>your_df = pd.read_csv('/your_path/your_file.csv',sep=';',decimal=',')
</code></pre>
<p>From the <a href="https://pandas.pydata.org/pandas-docs/stable/refere... | python|pandas | 46 |
9,108 | 28,921,997 | Ren'Py with Renpygame for Android | <p>I have this game which I have coded in python with pygame.</p>
<p>When I launch my game through the renpy launcher, it works just fine. </p>
<p>When I emulate my game through the renpy android emulator, it works just fine.</p>
<p>When I go through each of the build steps (install sdk, configure, build package, in... | <p>I e-mailed PyTom, the creator of Ren'py, and he responded back instantly:</p>
<p>"Edit the rapt/blacklist.txt file, and delete the line that says **.py. "</p>
<p>It worked! Thanks, PyTom.</p> | python|android|pygame|renpy | 1 |
9,109 | 8,369,678 | Is the "profile" package part of python standard distribution? | <p>I just noticed that the <code>import profile</code> fails on my Ubuntu Linux box that has Python 2.6.4 installed. This surprised me because I thought it was part of the standard Python distribution.</p>
<p>It turned out I needed to install the <code>python-profiler</code> Debian package to get the <code>profile</co... | <p>The <code>profile</code> module is part of standard Python (and is different from <code>cProfile</code> as it is implemented purely in Python), but Ubuntu doesn't install it by default likely because of its Debian lineage. <code>profile</code> isn't default included in Debian either, because <code>profile.py</code> ... | python|profiler | 4 |
9,110 | 8,783,578 | Why doesn't recv block until it receives all of the data? | <p>Why doesn't the <code>recv</code> system call just block until all the data is received? Every time I have seen a <code>recv</code> call, it's in a while loop which just keeps on calling <code>recv</code> until all the data is there. Why not just have <code>recv</code> block in the first place?</p> | <p>You can request that recv block until all data is received, with the <code>MSG_WAITALL</code> flag. However, if a signal arrives, a system call that has performed some work (ie, receiving part of the data) <em>cannot</em> be automatically restarted to receive the rest. As such, even with <code>MSG_WAITALL</code>, th... | python|c|sockets|network-programming | 9 |
9,111 | 52,409,426 | Sort list of complex numbers and get sorting indexes | <p>I need to sort a <code>list</code> of complex numbers by the imaginary parts. I found the solution on the question “<a href="https://bytes.com/topic/python/answers/852540-sorting-list-complex-numbers" rel="nofollow noreferrer">sorting list of complex numbers</a>”.</p>
<p>Simply using the sorted command with the app... | <p>The <a href="https://stackoverflow.com/a/6422754/550094">second answer to the question you linked</a> can easily be adapted:</p>
<pre><code>complexes = [1, 2+3j, 1-2j, 6+1j]
[i[0] for i in sorted(enumerate(complexes), key=lambda x:x[1].imag)]
# [2, 0, 3, 1]
</code></pre> | python|sorting|complex-numbers | 1 |
9,112 | 51,700,756 | Why relay in graphene-django? | <p>I would like to know why Relay spec is in graphene-django? I understand that using relay in graphene-django we get pagination and filters by default. </p>
<p>My requirement is to call graphql apis from React (for Web) and use Apollo client for Android and iOS.</p>
<ol>
<li><p>Will there be a problem for clients to... | <ol>
<li><p>There isn't any problem with consuming Relay-compliant graphene-django API. My team at work is currently using <a href="https://github.com/tannerlinsley/react-query" rel="nofollow noreferrer">react-query library</a>, and it works fabulously!</p>
</li>
<li><p>As mentioned in this graphene-django <a href="htt... | django|graphql|graphene-python | 1 |
9,113 | 59,818,977 | Convert a json file to a multi row with a matrix of all the nested objects | <p>In order to use the Extended Choice Parameter Jenkins plugin, I need to create a file containing a matrix with several options, such as:</p>
<pre><code> Country State City
USA FL Miami
USA FL Tampa
USA FL Jacksonville
USA NY NYC
USA ... | <p>The native language of Jenkins and it's plugins is Groovy. And it's always your best bet for general programming. Given that you have your states and towns correctly formatted in a JSON format you can use Groovy, json to process it. Here is the example code:</p>
<pre><code>import groovy.json.*
str="""
{
"countr... | python|json|bash|jenkins|groovy | 1 |
9,114 | 18,878,728 | Error: Could not import settings | <p>I'm switching a very large multi-package, multi-app Django (1.4.5) project from using Django's native test runner to py.test (2.3.5). The tests for the lowest level package, web-framework, were discovered and run with no errors after creating a setup.cfg (to manage the py.test options) and a conftest.py (to ignore s... | <p>in order to have it work you either need to have a develop-install of the worktree, or add . to the PYTHONPATH env var</p> | django|python-2.7|pytest | 1 |
9,115 | 19,145,645 | .ceil() math function not working? | <p>Python interpreter say that paintRequiredCeiling is undefined. I was unable to find any errors in the code. The objective is for the program to take input from the user, then calculate the costs/ hours needed for a paint job. ... | <p>The variable <code>paintRequiredCeiling</code> is only available in your calculate function. It doesn't exist in you <code>printFunction</code>. Similarly with other variables. You'll need to move them outside of the functions, or pass them, to get this to work. </p> | python|python-3.x | 1 |
9,116 | 69,288,211 | Select multiple directories and display the contents | <p>The purpose of the code below is to select a directory. The issue with this code is that it doesn't display the content of the selected folder.
example: Folder A has files B,C,D.
I would like files of B,C,D to be displayed in the text box using tkinter.</p>
<pre><code>from tkinter import *
from tkinter import filedi... | <p>I have written an example for you. As you can see my code shows the files and directories separately in the selected folder (You can remove the directory part if it's not needed).</p>
<p><strong>Code:</strong></p>
<pre><code>from tkinter import *
from tkinter import filedialog
from os import listdir
from os.path imp... | python|python-3.x|tkinter|pycharm | 1 |
9,117 | 62,154,869 | Multi-threading and Single-threading performance issues in CPU-bound task | <p>The two following single-threading and multi-threading scripts are taking the same time when I give as input a big number like <code>555550000</code></p>
<p><strong>single thread</strong></p>
<pre><code>import threading, time
a=[]
def print_factors(x):
for i in range(1, x + 1):
if x % i == 0:
... | <p>Your problem is GIL, the Global Interpreter Lock. </p>
<blockquote>
<p>The Python Global Interpreter Lock or GIL, in simple words, is a mutex
(or a lock) that allows only one thread to hold the control of the
Python interpreter.</p>
</blockquote>
<p>You can found detailed informations about GIL here (just a... | python|multithreading|gil | 3 |
9,118 | 62,196,017 | Python raspberry Image.open image from request.get(url) | <p>I'm trying to open an image from an URL to then process the image.</p>
<p>The image I'm fetching comes from one raspberry cam through this endpoint</p>
<pre><code>@app.route('/image')
def getImage():
frame = video_camera.get_frame()
return Response((b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + ... | <p>In my case I needed to change my </p>
<pre><code>@app.route('/image')
def getImage():
frame = video_camera.get_frame()
return Response((b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n'),
mimetype='multipart/x-mixed-replace; boundary=frame')
</code></pre>
<... | python|raspberry-pi | 1 |
9,119 | 62,307,874 | How do you check if a variable is numeric (without isnumeric) and raise error if it is not in Python? | <p>I don't understand why the following does not operate correctly and raises errors when radius or height are float numbers. </p>
<pre><code>def cone(radius, height):
if isinstance(radius, int) or isinstance(radius,float) == False:
raise TypeError("Error: parameters radius and height must be numeric.")
... | <p>Seems like you want</p>
<pre><code>if not (isinstance(radius, int) or isinstance(radius,float)):
</code></pre>
<p>Or actually </p>
<pre><code>if not isinstance(radius, (float, int)):
</code></pre>
<p>Currently your logic is this</p>
<pre><code>if isinstance(radius, int) or (isinstance(radius,float) == False):
<... | python|python-3.x|isinstance | 2 |
9,120 | 63,617,528 | How to write this in comprehension list Python | <p>I got a list of list and retrieving the first sublist (element to element) to the others sublist.</p>
<pre><code>ListA=[[2,3,4],[4,5,6],[7,8,9]]
</code></pre>
<p>would give <code>ListB=[[0,0,0],[2,2,2],[5,5,5]]</code></p>
<p>How code this in a comprehension list?
Thanks</p> | <pre><code>ListA=[[2,3,4],[4,5,6],[7,8,9]]
ListB = [[sublist[i] - ListA[0][i] for i in range(len(sublist))] for sublist in ListA]
print (ListB)
</code></pre>
<p>This prints:</p>
<pre><code>[[0, 0, 0], [2, 2, 2], [5, 5, 5]]
</code></pre>
<p>Also, make sure that all sub-lists in <code>ListA</code> are of the same lengt... | python|list | 2 |
9,121 | 16,647,131 | How to empty DBM file in Python efficiently? | <p>There is a command in DBM module to delete the value stored at a key.</p>
<pre><code>del d[key] # delete data stored at key (raises KeyError # if no such key)
</code></pre>
<p>But I cannot even iterate with this command, because the Runtime error occurs.(RuntimeError: dictionary changed size during iteratio... | <pre><code>for key in list(db):
del db[key]
</code></pre>
<p>should work.</p>
<p><strong>EDIT:</strong> If the goal is just to empty the database completely, you can also close the database and re-open it with <code>dbm.open('filename', 'n')</code>. The <code>'n'</code> flag means "Always create a new, empty dat... | python|python-3.x|dbm | 2 |
9,122 | 16,776,209 | Python - How to clear spaces from a text | <p>In Python, I have a lot of strings, containing spaces.
I would like to clear all spaces from the text, except if it is in quotation marks.</p>
<p>Example input:</p>
<pre><code>This is "an example text" containing spaces.
</code></pre>
<p>And I want to get:</p>
<pre><code>Thisis"an example text"containingspaces.
... | <p>For the simple case that only <code>"</code> are used as quotes:</p>
<pre><code>>>> import re
>>> s = 'This is "an example text" containing spaces.'
>>> re.sub(r' (?=(?:[^"]*"[^"]*")*[^"]*$)', "", s)
'Thisis"an example text"containingspaces.'
</code></pre>
<p><strong>Explanation:</strong... | python|string | 5 |
9,123 | 17,097,258 | Flask 0.10 giving unicode error on session cookie | <p>After upgrading to Flask 0.10, I get this error:</p>
<pre><code>flask.debughelpers.UnexpectedUnicodeError
UnexpectedUnicodeError: A byte string with non-ASCII data was passed to the session system which can only store unicode strings. Consider base64 encoding your string (String was 'iB\rOU#\xf7BO\x08^\xa6\xd1)v\x... | <p>That's currently an issue with <a href="https://github.com/maxcountryman/flask-login" rel="nofollow">Flask-Login</a>. As far as I know it's fixed in the git version of the extension.</p> | python|flask|flask-login | 10 |
9,124 | 71,270,785 | i want to kill my sprite. how to kill it? | <pre><code> import pygame as pygame , sys,time
pygame.init()
size = (700,500)
window_game = pygame.display.set_mode(size)
_run_ = True
white = (255,255,255)
mouse_pos = pygame.mouse.get_pos()
class mySprite(pygame.sprite.Sprite):
def ... | <p>You use <code>kill()</code> in wrong moment.</p>
<p><code>kill()</code> works when <code>Sprite</code> is inside <code>Group</code> but you first create <code>Sprite</code> which try to use <code>kill()</code> and later you add this sprite to <code>Group</code>.</p>
<p>You should first create <code>Sprite</code>, ne... | python|pygame|sprite|kill | 0 |
9,125 | 9,279,629 | Loading file in python | <p>I'm having some problems with the following code:</p>
<pre><code>with open('townhall.map', 'r') as f:
for line in f:
for character in line:
if character == "x":
print "WALL"
else:
if character == "a":
print "LAND"
... | <p>Change this line:</p>
<pre><code>for character in line.rstrip():
</code></pre>
<p>And you can also make the if/else structure flatter:</p>
<pre><code>with open('townhall.map', 'r') as f:
for line in f:
for character in line.rstrip():
if character == "x":
print "WALL"
... | python|load|newline | 5 |
9,126 | 52,794,154 | Blocked while scraping goodreads.com | <p>I am trying to scrape a large sample (100k+) of the books available at "<a href="https://www.goodreads.com/book/show/" rel="nofollow noreferrer">https://www.goodreads.com/book/show/</a>", but I get continuously blocked.
So far I have tried to implement the following solutions in my code:</p>
<ul>
<li><p>Check the r... | <p>If you really want to scrape large database then i will recommend selenium, chances of being blocked will be low, and stable. NO need <code>time.sleep()</code>(time delay but you can add to make it more stable). Check the code below...</p>
<pre><code>import time
from bs4 import BeautifulSoup
from selenium import we... | python|web-scraping|proxy|http-headers|robots.txt | 3 |
9,127 | 47,606,214 | Stop the loop in sounddevice audio output | <p>The problem is when I am using sounddevice's loop option to loop a playback, I cannot get it to stop. </p>
<pre><code>import soundfile as sf
import sounddevice as sd
weight = 1.4
data, fs = sf.read('sound.wav')
sd.play(data * weight, fs, blocking=True,loop=True)
sd.stop()
</code></pre>
<p>How to stop the loop, a... | <p>The problem is that you are setting <code>blocking=True</code> which does not allow for any other functions to be run before this exits. Combined with <code>loop=True</code>, this produces an infinite loop.</p>
<p>What you want is:</p>
<pre><code>import soundfile as sf
import sounddevice as sd
weight = 1.4
data,... | python|loops|audio|python-sounddevice | 2 |
9,128 | 34,139,655 | Logentries - Python example return UnicodeDecodeError | <p>i'm trying to setup a "logentries" account to log my python development events.
But I get the following error even with the most simple test available in the documentation. Any thoughts?</p>
<pre><code>Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on wi
n32
Type "help", "copyright", "cr... | <p>Thanks to Nikita's comment I could find the problem.</p>
<p>Helpers.py lib from logentries are not prepared for latin languages OS, whose timestamp label have special letters as "á".</p>
<p>Replacing </p>
<pre><code>unicode(ch,'utf8')
</code></pre>
<p>with</p>
<pre><code>unicode(ch,'utf8','replace')
</code></pr... | python|python-2.7|logging|logentries | 1 |
9,129 | 7,679,557 | Python and Opswat | <p>I need to trigger my AntiVirus (McAfee) when accessing a test-virus URL (http://eicar.org/download/eicar.com) via python. If I use IE, Firefox or even wget for windows, the AntiVirus detects that a virus URL was accessed, which is the expected behavior. However, when using urllib or urllib2, the virus URL is success... | <p>Write the output to disk- the virus scanner will see it then.</p> | python|windows | 2 |
9,130 | 7,303,252 | How to define a python string (quasi-)constant that has dynamic inputs? | <p>For example:</p>
<pre><code>MY_MESSAGE = 'Dear %s, hello.'
# ...
name = "jj"
print MY_MESSAGE % name
</code></pre>
<p>Does python have a feature for accomplishing something like my above code?</p> | <p>Yes, the exact way you wrote it. Your code is fine.</p> | python|string|constants | 5 |
9,131 | 72,492,465 | Fail to use GLPK solver when python executable triggered with VBA Macros | <p>I am trying to develop an Mixed Integer Linear Programming (MILP) optimization tool with Excel and Python. Pyomo with GLPK solver are being used for MILP optimization. Python program reads inputs from the excel file and write output to an excel file. I used Pyinstaller to create exe file. The program works when exe ... | <p>I figured out the problem. VBA triggers exe file from the cmd default folder. Python/Pyomo looks for the solver in the same folder. From VBA, by going to the folder in which exe and GLPK solver are from cmd and triggering the exe make the program work. Following is the change</p>
<pre><code>With CreateObject("W... | python|excel|vba|pyomo|glpk | 0 |
9,132 | 39,848,809 | Filtering and displaying mySQL Data on Webpage via Python? PHP? | <p>I'd like to build a website that reads data from a database, lets me filter that data with different Frontend dropdown-filters and presents me the filtered data in a table shown on the Webpage.</p>
<p>In addition I'd like to have the possibility to use that data further to store it into some file, or use it in a py... | <p>It depends on how familiar you are with PHP or Python. If you are new to both, I recommend you to start with <a href="http://www.w3schools.com/php/" rel="nofollow">PHP</a>. If you are familiar with Python, I recommend you to use <a href="http://flask.pocoo.org/docs/0.11/tutorial/" rel="nofollow">Flask</a> or <a href... | php|python|mysql | 1 |
9,133 | 16,320,710 | converting dates and times with list comprehension | <p>I have a whole bunch of data and there are two lists consisting of dates and times that look as such:</p>
<p>dates: year-month-day</p>
<p>times: hour:minute:second</p>
<p>so I take them appart and put each into a separate list:</p>
<pre><code>year,month,day = [i.split("-")[0] for i in date], [i.split("-")[1] for... | <p>You are making things too complicated for yourself. Zip the <code>date</code> and <code>time</code> lists, then use <a href="http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime"><code>datetime.datetime.strptime()</code></a>:</p>
<pre><code>datetime_column = [datetime.datetime.strptime('{} {}'.... | python|list|datetime|list-comprehension | 6 |
9,134 | 31,759,011 | How to pass a Tkinter Entry through a function | <p>is there any reasonable way to convert my <code>while</code> loop into a <code>for</code> loop? I tried to create this, but I never got far cause the <code>range</code>'s and/or <code>xrange</code>'s broke because the number was too large or they don't take a <code>float</code>. Here's my <code>while</code> loop tha... | <p>If you want infinite loop, you can use <a href="https://docs.python.org/2/library/itertools.html#itertools.repeat" rel="nofollow"><code>itertools.repeat(1)</code></a> which will yield infinitely:</p>
<pre><code>import itertools
....
for _ in itertools.repeat(1): # instead of `while integral == integral`
...
... | python | 0 |
9,135 | 38,645,060 | What is the equivalent of Serial.available() in pyserial? | <p>When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom:</p>
<pre><code>String message = "";
while (Serial.available()){
message = message + serial.read()
}
</code></pre>
<p>In Arduino C, <code>Serial.available()</code> returns the number of bytes available to be read fr... | <p>The property <a href="https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.in_waiting" rel="noreferrer"><code>Serial.in_waiting</code></a> returns "the number of bytes in the receive buffer".</p>
<p>This seems to be the equivalent of <a href="https://www.arduino.cc/en/Serial/Available" rel="no... | python|serial-port | 23 |
9,136 | 38,616,237 | Pandas: Create aggregation table with percentages | <p>I have a data</p>
<pre><code>Third party unique identifier Qsex
9ea3e3cb6719f3d336d324c446f486bd 1
d1b69bc4cccf0afef66debf4e3f0643e 2
f574fc585db0cddef88306ef6f32da59 1
8bc0a586bf0abec653c29cf4160753f9 1
7c22b56929378ec2eb3a536b4f4bc4e0 2
23d8433168c46d57a271a6b979037094 1
5743b7eec1b018572b6c5b... | <p>Here's an answer that uses <code>pandas</code> API.</p>
<p>I've done my best in building up the function calls so that you can follow the logic. Answer inspired by <a href="https://stackoverflow.com/questions/23377108/pandas-percentage-of-total-with-groupby#23377232">this post</a>.</p>
<pre><code>In [1]: import pa... | python|pandas | 0 |
9,137 | 40,676,641 | Sum different elements of a list of lists using one dictionary (Python) | <p>I have this list of lists:</p>
<pre><code> [Racing, 100]
[Crossi, 100]
[Racing, 120]
[Racing, 130]
[Marcas, 105]
[Marcas, 109]
[Crossi, 130]
[Crossi, 104]
</code></pre>
<p>I want the total sum for Racing, Marcas and Crossi. I want do it with a dictionary on python if it's possible. L... | <p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow noreferrer"><code>collections.defaultdict</code></a> for this</p>
<pre><code>from collections import defaultdict
l = [['Racing', 100],
['Crossi', 100],
['Racing', 120],
['Racing', 130],
... | python|list|dictionary|sum | 1 |
9,138 | 68,421,125 | huggingface transformer with tensorflow saves two files as model weights | <p>This is how I build the model for classification task:</p>
<pre><code> def bert_for_classification(transformer_model_name, max_sequence_length, num_labels):
config = ElectraConfig.from_pretrained(
transformer_model_name,
num_labels=num_labels,
output_hidden_states=False... | <p>You have 2 possibilities to save a model, either in keras <code>h5</code> format or in tensorflow <code>SavedModel</code> format.</p>
<p>You can determine the format by passing the <code>save_format</code> argument and set it to either <code>"h5"</code> or <code>"tf"</code>. If you don't specify ... | python|tensorflow|tensorflow2.0|huggingface-transformers | 2 |
9,139 | 59,970,121 | In Python, how do I take a string of averages and sort them? | <p><code>player_avg</code> is a string that contains batting averages for baseball players separated by commas:</p>
<pre><code>player_avg = "0.209,0.305,0.265,0.175,0.324,0.215,0.362,0.178,0.273,0.309"
</code></pre>
<p>How do I write code to compute the number of players that batted greater than 0.299, and store the ... | <p>This is an alternative with list comprehension:</p>
<pre><code>player_avg = "0.209,0.305,0.265,0.175,0.324,0.215,0.362,0.178,0.273,0.309"
num_players_over_300 = len([float(i) for i in player_avg.split(',') if float(i) > 0.299])
</code></pre>
<p>Output:
4</p> | python | 1 |
9,140 | 28,316,891 | Running Python script from Python shell | <p>In a batch file residing in a remote desktop I have simply written "python jwRelay.py"</p>
<p>I want to run the batch file using psexec using the following command:</p>
<pre><code>psexec -s -i 2 \\135.20.230.160 -u administrator -p force cmd.exe /c "C:\Users\Administrator\Desktop\jwRelayCDV16\SampleCode\Python\rel... | <p>Python 2</p>
<pre><code>execfile("./filename")
</code></pre>
<p>Python 3</p>
<pre><code>exec(open("./filename").read())
</code></pre>
<p>There are probably also several ways to execute code and specific commands, using Python 2 <code>commands</code> or better for both <code>subprocess</code> which replaced it. ... | python|windows|python-2.7|python-3.x|psexec | 1 |
9,141 | 44,121,517 | Beautiful Soup: extracting picture url from webpage | <p>So currently I'm having some issues trying to extract a picture URL from a web page using beautiful soup. I'm quite inexperienced with beautiful soup and would appreciate any feedback you have for me. Here is a snippet of the HTML I'm trying to extract the picture link from (more specifically, the data-srcset URL in... | <p>Have you tried using the <code>.select()</code> function for a bs4 instance? The <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer">documentation</a> says that this is the prefered method for finding css elements in your HTML soup. So in this case use <code>page_soup.select(... | python|html|python-2.7|beautifulsoup|html-parsing | 0 |
9,142 | 44,186,182 | Regarding Binning of the values in python | <p>I have a set of values as :-</p>
<pre><code>1.2
1.0
2.6
2.4
2.8
5.1
2.5
5.4
1.3
1.1
10.3
4.1
3.4
3.2
6.1
6.3
9.0
8.6
7.1
3.2
4.3
15.0
12.3
13.1
17.4
10.2
11.7
14.6
16.3
</code></pre>
<p>Now, how can i bin them into groups such that the decimal values will go to the nearest integer value... | <pre><code>from collections import Counter
c = Counter(round(f) for f in values)
</code></pre>
<p>alternatively (if numpy is available),</p>
<pre><code>import numpy as np
minval = int(min(values))
maxval = int(max(values)) + 1.
bins = np.arange(minval, maxval + 1, 1.)
hist, edges = np.histogram(values, bins)
</code... | python|integer|decimal|bins | 1 |
9,143 | 43,928,765 | Reduce inner points in numpy coordinate dataset (speed up concave hull) | <p>I have a 2D numpy array representing a point cloud of x,y coordinates: </p>
<pre><code>[[ 247.68512 182.67136]
[ 248.71936 182.67136]
[ 249.74336 182.67136]
...,
[ 253.85984 269.1072 ]
[ 254.89408 269.1072 ]
[ 255.91808 269.1072 ]]
</code></pre>
<p><a href="https://i.stack.imgur.com/gf7Ms.png" rel="no... | <p>The simplest way to deal with this is to run the operation in parallel. Either across multiple cores or multiple machines. It's simplest because it means rather than trying to make your operation run more efficiently, you can take a large queue of operations and simply do them all at once, at a time cost of a single... | python|numpy|coordinates|data-analysis|data-science | 0 |
9,144 | 32,740,577 | How do you send a message using pyOSC? | <p>I'm very new to python and even less familiar with pyOSC. Can someone post a simple example of how to send a string message from my computer to another computer? I viewed this <a href="https://stackoverflow.com/questions/22135511/a-plethora-of-python-osc-modules-which-one-to-use">pyOSC link</a> which has given me so... | <p>OSC has the concept of an message address that is distinct from the network address of the device to which you're connecting. The idea is that the message you are sending could be routed to one of many different handlers at the other end of the network connection. Each handler has its own address which is usually ... | python | 11 |
9,145 | 32,938,487 | Count frequency of words in lists and remove unpopular words | <p>My data are in lists.</p>
<pre><code>data = [['Biz_Innovations', '#socialmedia'],
['ChantalGrange', '#aws'],
['beyonddevops', '#aws'],
['beyonddevops', '#socialmedia'],
['IBMNetezza', '#ibm'],
['IBMNetezza', '#analytics'],
['SandraFeinsmith', '#ibm'],
['SandraFeinsmith', '#analytics'],
['fleejack', '#healhc... | <pre><code>>>> import collections, operator
>>> words = collections.Counter(map(operator.itemgetter(1), data))
>>> populars = [p for p in data if words[p[1]] >= 3]
</code></pre> | python | 2 |
9,146 | 14,141,218 | Django Tutorial 1: cannot fix error "File "<console>", line 1, in <module>ImportError: cannot import name Choice" | <p>I am working through the Django tutorial found at <a href="https://docs.djangoproject.com/en/1.3/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/1.3/intro/tutorial01/</a>.</p>
<p>I have made it through the initial setup and am at the section "Playing with the API"... when I enter the first line ... | <p>I believe that your file structure is wrong. It should be:</p>
<pre><code>--mysite
|--manage.py
|--polls
|--models.py
|--mysite
|--settings.py
|--urls.py
</code></pre>
<p>Instead do you have this?</p>
<pre><code>--mysite
|--manage.py
|--mysite
|--polls
|--models.py
|--settings.py
|--ur... | python|django|django-models | 1 |
9,147 | 27,030,716 | Python how to exclude exceptions from "catch all" | <p>Lets say I have this:</p>
<pre><code>try:
result = call_external_service()
if not result == expected:
raise MyException()
except MyException as ex:
# bubble up
raise ex
except Exception:
# unexpected exceptions from calling external service
do_some_logging()
</code></pre>
<p>Due to ... | <p>Your problem seems to be that you are wrapping too much code in your try block. What about this?:</p>
<pre><code>try:
result = call_external_service()
except Exception:
# unexpected exceptions from calling external service
do_some_logging()
if result != expected:
raise MyException()
</code></pre> | python|exception | 2 |
9,148 | 23,178,727 | Following users who tweets a specific hashtag with tweepy for python? | <p>can some one show me the code of how can I follow all users who tweet about a specific hashtag?</p> | <p>I guess you could use <a href="https://github.com/ryanmcgrath/twython" rel="nofollow">twython</a> and start with a search <a href="https://github.com/ryanmcgrath/twython/blob/master/examples/search_results.py" rel="nofollow">example</a> wich you can modify to suit your needs .</p>
<pre><code>from twython import Tw... | python|twitter|tweepy | 2 |
9,149 | 41,955,138 | How can I create a shell script through a python code? | <p>I have written a python code inside which at a certain line I want to write a file xyz.sh but its saying permission denied. I tried to use os.rename() also but it didn't work. Thanks in advance.</p> | <p>Since we don't know your code, we can't give an exact answer. But here are some hints:</p>
<p>If you are new to linux, you may want to check that if you want to use a relative path, you are not allowed to start the path with a <code>/</code> at the beginning. </p>
<p>Further we don't know which part fails (executi... | python|shell | 0 |
9,150 | 41,912,594 | How to speed up Numpy sum and Python for-loop? | <p>I have 2 codes that do almost the same thing.</p>
<p>code 1:</p>
<pre><code>from __future__ import division
import numpy as np
m = 1
gamma = 1
lam = 1
alpha = 1
step_num = 2 ** 16
dt = 0.02
def E_and_x(x0):
xi = x0
vi = 0
f = 0
xsum = 0
Ei, xavg = 0, 0
for i in range(step_num):
v... | <p>You did something wrong with your timings, just testing your first code (slightly modified):</p>
<pre><code>from __future__ import division
def E_and_x(x0):
m = 1
gamma = 1
lam = 1
alpha = 1
step_num = 2 ** 13 # much less iterations!
dt = 0.02
xi = x0
vi = 0
f = 0
xsum =... | python|numpy|for-loop|jit | 4 |
9,151 | 47,254,188 | Percentage Calculations on Lists | <p>I have created a quiz system which tests the user on two different topics. They are can choose whih topics they would like to do and a difficulty they wish to complete it in. If they get the question correct they get a point if they don't it will display the correct answer.</p>
<p>I am struggling to calculate the p... | <p>The following seems to work. Note there are a couple of issues with your code snippet:</p>
<ul>
<li>The <code>elif</code> in the <code>for</code> loop needs to be an <code>else</code>.</li>
<li>You need to initialize <code>score</code> to zero before entering the <code>for</code> loop.</li>
</ul>
<p>I've fixed the... | python | 0 |
9,152 | 47,116,712 | Python (Alternate two messages) | <p>I have some code, and my goal is to make it so that when left button is clicked it will post text saying "Programming is fun!" and when it is pressed again, it will change that text to "It is fun to program", my idea was to make x = 0 if I wanted the first statement, and x = 1 if I wanted the second statement, but i... | <p>I found a way to do this below, the down low is that it's creating the text through that function, and then it's rebinding the key to do other function and then that function deletes previous text, creates the new text and then rebinds to the previous function, and the cycle continues. Here's the code.</p>
<pre><co... | python | 0 |
9,153 | 47,408,154 | How to import or install pre-built python extension module (C++) (i.e. library not compiled via setuptools)? | <p>I have a C++ project for which I am developing a Python interface. For now I am using <a href="https://github.com/pybind/pybind11" rel="nofollow noreferrer">pybind11</a> since it seems pretty neat, and has some nice tools for building the extension module with CMake, which is how the main C++ project is built.</p>
... | <p>If you need to install just one binary module you can create an simple installer just for that module. Let's assume that you have a binary module <code>foo.so</code> (or <code>foo.pyd</code> if you are working on Windows) that is already built with your cmake-generated build script. Then you can create a simple setu... | python|c++|setuptools|pybind11|extension-modules | 5 |
9,154 | 71,039,013 | Loop through Python dictionary and add different values with same keys to a new dictionary | <p>I am really stuck with this exercise. How can I with a for loop add the same keys with a new values to a different dictionary in Python?</p>
<p>Goal is to loops through student grades and replace them with "Excellent", "Bad", etc.</p>
<p>This is as far as I could get:</p>
<pre class="lang-py pret... | <p>You can add values to a dictionary by simply assigning the value to the dictionary indexed by the key. For example, <code>student_grades["Harry"] = "Excellent"</code></p>
<p>You can do the same in your loop:</p>
<pre><code>for key, value in student_scores.items():
student_grades[key] = "... | python|loops|dictionary | 0 |
9,155 | 70,909,559 | list won't change values for pygame rectangles | <p>I have been trying to recreate snake in pygame for fun but the list won't update for the rectangle positions, anyone know what I'm doing wrong with this code???</p>
<p>I passed in a list within a list (snake_body) to a function with this code however the list within a list doesn't change its integer values</p>
<pre>... | <p>See <a href="https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-for-equality-against-a-single-value">How to test multiple variables for equality against a single value?</a>. A condition like</p>
<blockquote>
<pre class="lang-py prettyprint-override"><code>if event.key == pygame.K_UP or pygam... | python|pygame | 2 |
9,156 | 70,763,527 | The for loop in my python function is not running | <p>My for loop inside the function "play()" is not getting executed at runtime.</p>
<pre><code>def play():
print("1")
for files in os.listdir(os.getcwd()):
if files.endswith("mp3"):
print("2")
pygame.mixer.Sound.play(files)
else:
... | <p><code>pygame</code> seems a poor choice for a media player, unless you have it loaded for another reason.<br />
I'd suggest you look on SO for <code>vlc.py</code> or <code>Gstreamer</code> examples.<br />
That said, the player can only play one thing at a time, so you can't just throw the contents of your disk at it... | python|pygame|logic | 0 |
9,157 | 11,647,348 | Find next siblings until a certain one using beautifulsoup | <p>The webpage is something like this:</p>
<pre><code><h2>section1</h2>
<p>article</p>
<p>article</p>
<p>article</p>
<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>
</code></pre>
<p>How can I find each sect... | <p>I think you can do something like this:</p>
<pre><code>for section in soup.findAll('h2'):
nextNode = section
while True:
nextNode = nextNode.nextSibling
try:
tag_name = nextNode.name
except AttributeError:
tag_name = ""
if tag_name == "p":
... | python|find|beautifulsoup|scrape|siblings | 11 |
9,158 | 58,366,448 | Python how to fix syntax error during runtime | <p>If I receive a string below with syntax error from a noSQL db that stores it in this exact format, how can I assign it to a variable and "correct" the syntax error during runtime. With assumptions that I cannot change how it is stored on a database.</p>
<p>Since this is a syntax error I can't even use string functi... | <p>That string assignment indeed throws a <code>SyntaxError</code> if executed as part of your code, but it's not an error for that string to be read from from a database.</p>
<p>In which case it works just as if you had single-quoted the string:</p>
<pre class="lang-py prettyprint-override"><code>string = 'John Do... | python|syntax-error | 2 |
9,159 | 58,312,793 | I tried to write a program that loops the question until the user types stop but I keep on getting the invalid syntax error | <p>I am trying to make it loop the question until the user types stop, but I get invalid syntax error.</p>
<p>Code:</p>
<pre><code>while True:
inp = input("Enter a Number: ")
if inp == "Stop":
break
num = int
if num > 1:
for zzz in range(2,num):
if (num % zzz) == 0:
... | <p>This solves your syntax error and fixes the code;</p>
<pre><code>while True:
inp = input("Enter a Number: ")
if inp == "Stop":
break
num = int(inp)
if num > 1:
for zzz in range(1,num):
if (num % zzz) == 0:
print(num,"is not a prime number")
print(zzz,"times... | python | 0 |
9,160 | 58,481,844 | Iterating over two lists A and B | <p>I am trying to iterate over two lists A and B. Where the B is equal to A - A[i], where i = 1:</p>
<blockquote>
<p>For E.g. listA = ['A', 'B', 'C', 'D'].
For first Item, 'A' in List A, I
want the List B to have ['B', 'C', 'D'] For second Item 'B' in List A,
I want the List B to have ['A', 'C', 'D']</p>
</blo... | <p>Try this,</p>
<pre><code>>>> la = ['A', 'B', 'C', 'D']
>>> for i in la:
_temp = la.copy()
_temp.remove(i)
print(_temp)
</code></pre>
<hr>
<p><strong>Output:</strong></p>
<pre><code>['B', 'C', 'D']
['A', 'C', 'D']
['A', 'B', 'D']
['A', 'B', 'C']
</code></pre>
<p><sub>*If you want to... | python|list-comprehension | 2 |
9,161 | 58,542,886 | SQL LIKE multiple values | <p>I am running the following sql code in python : </p>
<pre><code>SELECT
FIN AS 'LIN',
CUSIP,
Borrower_Name,
Alias,
DS_Maturity,
Spread,
Facility,
Facility_Size,
Log_date
FROM
[Main].[FacilityInformation]
WHERE
CUSIP IN ('00485GAC2', 'N1603LAD9')
OR (YEAR(DS_Ma... | <p>You can join using <code>VALUES</code> and <code>LIKE</code>:</p>
<pre><code>-- Test data
DECLARE @s TABLE (mytext NVARCHAR(20))
INSERT INTO @s VALUES ('abc'), ('def'), ('ghi')
-- Select
SELECT
s.mytext
FROM @s s
INNER JOIN (VALUES ('a%'),('%h%')) n(wildcard) ON s.mytext LIKE n.wildcard
</code></pre>
<p>Or yo... | python|sql|sql-server | 1 |
9,162 | 46,713,907 | Search for a row in a dataframe containing a string from a list | <p>I am trying to search for the <code>row</code> of which contains a string within a list.</p>
<p><code>df</code>:</p>
<pre><code> Column1 Out1
0 ['x', 'y'] (0, 2)
1 ['a', 'b'] (3, 0)
etc.
</code></pre>
<p>I have attempted the following to search for the row th... | <p>Need <code>in</code> for check values in lists:</p>
<pre><code>df = df[df['Column1'].apply(lambda x: 'a' in x)]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'Column1':[['x','y'], ['a','b']],
'Out1':[(0,2), (3,0)]})
print (df)
Column1 Out1
0 [x, y] (0, 2)
1 [a, b] (3, 0)
... | python|regex|python-2.7|pandas | 3 |
9,163 | 46,995,270 | How set a particular cell value in pandas? | <p>I am trying to set a value in panda dataframe.</p>
<pre><code>ZEROS = np.zeros((4,4), dtype=np.int)
df = pd.DataFrame(ZEROS, columns=['A1','B1','C1','D1'])
df.at[2,3] = 32
df
</code></pre>
<p><a href="https://i.stack.imgur.com/arkbI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/arkbI.png" alt="enter ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iat.html" rel="noreferrer"><strong><code>pd.DataFrame.iat</code></strong></a> to reference and/or assign to the ordinal location of a single cell.</p>
<pre><code>ZEROS = np.zeros((4,4), dtype=np.int)
df = pd.DataFrame(ZEROS, colu... | python|pandas|numpy | 15 |
9,164 | 37,900,988 | Pandas: read_table remove comment lines with '##' but not '#<string>'? | <p>I have some large tab separated data sets that have long commented sections, followed by the table header, formatted like this:</p>
<pre><code>##FORMAT=<ID=AMQ,Number=.,Type=Integer,Description="Average mapping quality for each allele present in the genotype">
##FORMAT=<ID=SS,Number=1,Type=Integer,Descript... | <p>you can easily calculate the number of header lines, that must be skipped when reading your CSV file:</p>
<pre><code>fn = '/path/to/file.csv'
skip_rows = 0
with open(fn, 'r') as f:
for line in f:
if line.startswith('##'):
skip_rows += 1
else:
break
df = pd.read_table(f... | python|pandas | 2 |
9,165 | 37,693,154 | How to use virtualenv inside a folder? | <p>I try to use <code>virtualenv</code> inside a folder using the command <code>virtualenv .</code> and getting the error <code>-bash: virtualenv: command not found</code>. However, I installed <code>virtualenv</code> using pip <code>pip installed virtualenv</code> and also, upgraded it earlier with <code>sudo pip inst... | <p>This is pretty simple<br>Just goto environment folder<br>
Try: <code>Scripts/activate</code><br>
This will activate the environment<br>
Try:<code>Scripts/deactivate</code><br>
This will deactivate current environment</p> | python|virtualenv | 0 |
9,166 | 37,630,071 | Get All Functions, Classes, datatypes from Python | <p>I am developing a small python learning app. where student simply searches for keywords like, <code>list</code>, <code>date</code> my app gives output as help text for keyword.</p>
<p>first i want to extract all python builtins, classes help text using help() into json file.
I tried:</p>
<pre><code>>>> im... | <p><code>datetime</code> is part of the standard library; its <code>datetime.datetime</code> type is not as built-in as list, which is a <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow">built-in type</a>.</p>
<p>If you still insist on iterating through <code>sys.modules</code> rather than <a hr... | python | 3 |
9,167 | 29,884,859 | Using Python and the Pillow Library and CGI for file upload | <p>I've been having hard time importing Image, and CGI together. So, basically I want to upload a gif image, and then display the output which is a thumbnail of the image. I'm getting bunch of errors. I'm unable to use from PIL import Pillow and cgi at the same time. Here is the code below. Your help is highly apprecia... | <p>I figured it out. There must be a try statement at the end after the print html, and then I would use from PIL import Image</p> | python|pillow | 0 |
9,168 | 61,376,188 | Calculating the sum of a column if it contains a string stored in another dataframe | <p>I have a large dataframe (prices) that contains a long description and a price associated to that description. I generated another dataframe (words) that keeps all the unique words that those long descriptions has. What I'm trying to do is calculate the sum of the price of a particular word from the prices dataframe... | <p>Since I answered your last question, it's quite easy for me to see the problem. The reason you get a higher sum, is because a word can occur multiple times in a sentence. So use <code>DataFrame.drop_duplicates</code> before <code>GroupBy</code>:</p>
<pre><code>matches = (
prices['TEXT'].str.extractall(f'({"|".j... | python|pandas|dataframe | 1 |
9,169 | 61,551,623 | How to make the functions be aware of each other when they are called, e.g. when using the ElementTree package | <p>If the title question is not worded clearly, the code below will explain it better. This code works fine:</p>
<pre><code>#!/usr/bin/python3
import sys
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import *
country_arg = 'usa'
transport_name_arg = 'train'
route_data = "some route"
world =... | <p>This code works, thank you all, good learning experience:</p>
<pre><code>#!/usr/bin/python3
import sys
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import *
country_arg = 'usa'
transport_name_arg = 'train'
route_data = "some route"
def function_1():
global world
global country
... | python-3.x|xml|function|elementtree | 0 |
9,170 | 27,666,958 | How does Python allocate memory for objects of classes derived from C types? | <p>Suppose we have created a Python module in C <code>_xxx</code> that contains an extension object <code>xxx</code>, and we do following:</p>
<pre><code>import _xxx
class derived(_xxx.xxx):
# ...
d = derived()
</code></pre>
<p>How does Python allocate memory for <code>d</code> behind the scenes?</p>
<p>Eli Be... | <p>Supplying an answer so that this doesn't appear as an unanswered question (I believe SO's machinery promotes visibility for unanswered questions).</p>
<p>For the answer, please follow the link at the bottom of the question.</p>
<p>If the author relocates the answer here I will delete this stub.</p> | python|memory-management|derived-class|c-api | 0 |
9,171 | 27,523,493 | POSTGRES - Efficient SELECT or INSERT with multiple connections | <p>tl;dr I'm trying to figure out the most efficient way to SELECT a record or INSERT it if it doesn't already exist that will work with multiple concurrent connections.</p>
<p><strong>The situation:</strong>
I'm constructing a Postgres database (9.3.5, x64) containing a whole bunch of information associated with a cu... | <p>I managed to rewrite the function into plain SQL, changing the order (avoiding the <code>IF</code> and the <em>potential</em> race condition)</p>
<pre><code>CREATE OR REPLACE FUNCTION get_or_insert_customer
( p_system_id customers.system_id%TYPE
, p_name customers.name%TYPE
) RETURNS custom... | python|sql|database|postgresql|concurrency | 1 |
9,172 | 65,626,843 | Int is not subscriptable | <p>I'm trying to make a password system is python but when I tried to compere the user password to the right password I get an exception</p>
<pre><code>'int' object is not subscriptable
</code></pre>
<pre><code>import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u ent... | <p>A couple of things here;</p>
<p>Firstly you need to indent your <code>if not i.isdigit()</code> block:</p>
<pre><code>if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
</code></pre>
<p>You will probably get an exception otherwise.</p>
<... | python | 1 |
9,173 | 65,574,747 | How to filter a list based on ascending values? | <p>I have the following 3 lists:</p>
<pre><code>minimal_values = ['0,32', '0,35', '0,45']
maximal_values = ['0,78', '0,85', '0,72']
my_list = [
['Morocco', 'Meat', '190,00', '0,15'],
['Morocco', 'Meat', '189,90', '0,32'],
['Morocco', 'Meat', '189,38', '0,44'],
['Morocco', 'Meat', '188,94', '0,60'],
... | <p>pandas solution:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
# create input dataframe
my_list = [
['Morocco', 'Meat', '190,00', '0,15'],
['Morocco', 'Meat', '189,90', '0,32'],
['Morocco', 'Meat', '189,38', '0,44'],
['Morocco', 'Meat', '188,94', '0,60'... | python|pandas|list|if-statement|floating-point | 2 |
9,174 | 72,330,077 | How to "double pop"? | <p>I'm sorry if my title is a bit unclear, I wasn't sure how to express my problem better. I will give a quick code snippet to illustrate what I am trying to do:</p>
<pre><code>for data_file in data_files:
analyze(data_file)
def analyze(data_file):
for _ in np.arange(n_steps):
foo(data_file)
do som... | <p>What you can do is to return a <code>truthy</code> value (assuming all the other routes out of <code>foo()</code> are the default <code>return None</code>) and test for it:</p>
<pre class="lang-py prettyprint-override"><code>def analyze(data_file):
for _ in np.arange(n_steps):
if foo(data_file):
... | python|for-loop|nested-for-loop | 1 |
9,175 | 43,353,826 | How to set different arrays as minor index for dataframe with pandas multiindex | <p>Two q's:</p>
<p>1) Is it possible to create a MultiIndex Pandas DataFrame with different "minor" indices e.g.:</p>
<pre><code> Col1 Col2
0
a 0.1 0.01
b 0.2 0.02
c 0.3 0.03
1
m 0.8 0.00
n 0.9 0.01
v 0.7 0.10
</code></pre>
<p>When using Pandas MultiIndex I can ... | <p>Yes and yes.</p>
<p>Create Multilevel index data:</p>
<pre><code>array = list(zip([0]*3,list('abc')))+list(zip([1]*5,list('vwxyz')))
array
</code></pre>
<p>output:</p>
<pre><code>[(0, 'a'),
(0, 'b'),
(0, 'c'),
(1, 'v'),
(1, 'w'),
(1, 'x'),
(1, 'y'),
(1, 'z')]
</code></pre>
<p>Use pd.MutliIndex to create ... | pandas|dataframe|mean|hierarchical-data|multi-index | 1 |
9,176 | 43,090,438 | PyQT: When relaunching plugin I don't get the main window I get the pop up window | <p>I am developing a python plugin on <strong>QGIS</strong> using <strong>PyQT</strong>. My plugin contains a main window and a pop-up window which will be launched when clicking on a button on the main window.</p>
<p>My problem is when I relaunch again the plugin, the pop-up window will be displayed instead of the ma... | <p>I have solved my problem, in my main window in method show() I delete self.activate_launch_button()
self.launch_options_TRANUS()</p> | python|pyqt|popup|pyqt4|qgis | 0 |
9,177 | 37,055,508 | Closures, Partials and Decorators | <p>I am confused between the three. I understand that closures are functions returned by another functions and have access to the local variables form an enclosing scope</p>
<p>example:</p>
<pre><code>def add_nums(one):
def adder(two):
return one+two
return adder
a_10 = add_nums(10)
print a_10(5)
15
... | <p>Short answer: <em>closure</em> is the mechanism, while <code>functools.partial</code> and decorators are typical uses of that mechanism.</p>
<p>The key difference between a closure and more typical namespaces is that the names and values in the "closed-over" namespace don't vanish when control flow leaves the top-... | python | 10 |
9,178 | 48,817,114 | Why does Beautifulsoup's contents method return text with brackets and quotes, whereas the text method returns just plain text | <p>I am scraping company names from a webpage using Python3 and Beautifulsoup. When I use the "contents" method to pull the contents of a tag, it returns the text with brackets and single quotes (e.g. ['Company A']) whereas the "text" method returns simply Company A. Why do the functions behave this way? I realize this... | <p><code>contents</code> gives you a list with the tag childrens, while <code>text</code> gives you the text of a tag.</p> | python-3.x|beautifulsoup | 0 |
9,179 | 48,392,267 | Why is this Popen call returning a "io.UnsupportedOperation: fileno" error in Django 2.0? | <p>I recently upgraded my project to Django 2.0, and an error started cropping up. First off, I use <code>django_gulp</code> to start a gulp process whenever I start the django runserver. I'm using the <a href="https://github.com/beaugunderson/django-gulp/tree/runserver-plus" rel="nofollow noreferrer"><code>runserver_p... | <p>The reason why you're seeing this error is that file-like objects are a Python abstraction. The operating system and other processes don't know about this abstraction, they only know about file descriptors. Therefore you <em>must</em> pass a valid file descriptor to Popen.</p>
<p>You can access the stream wrapped b... | python|django|gulp|subprocess | 7 |
9,180 | 48,354,764 | Django not a valid value for a primary key error in ModelMultipleChoiceField | <p>I created a form consisting of two ModelMultipleChoiceFields of all the countries in the world.</p>
<p>But after a POST request, Django doesn't deem the form valid with the error: </p>
<p>"Algeria" is not a valid value for a primary key </p>
<p>(or whichever country I select). Here is my form:</p>
<pre><code>cla... | <p>My two cents (haven't tested): 1. remove <code>.values_list('name',flat=True)</code></p>
<pre><code>country_1 = forms.ModelMultipleChoiceField(
queryset=WorldBorder.objects.all()
)
country_2 = forms.ModelMultipleChoiceField(
queryset=WorldBorder.objects.all()
)
</code></pre>
<ol start="2">
<li>specify a <c... | python|django|forms | 0 |
9,181 | 48,196,080 | How to pipe JSON output of curl to query a JSON value using python | <p>I am writing a bash script where the curl command returns a JSON array of objects and then I need to filter the required values out of those objects. So I need to iterate through the objects to check then and parse them and finally get the result.</p>
<p>But inside my bash script if I do something like,</p>
<pre><... | <p>In <code>bash</code> (and other shells), variables are not expanded when put inside single quotes.</p>
<p>Better approach than my original (as @chepner pointed out), pass the shell variable as command line argument to <code>python</code> command itself:</p>
<pre><code>curl ... | python -c \
'import sys, json; p... | python|json|bash|curl|gitlab-ci | 1 |
9,182 | 51,328,784 | What's the pythonic way to do a complex initialization | <p>Suppose I have a class <code>Point</code>:</p>
<pre><code>class Point:
def __init__(self, x, y):
self.x = x
self.y = y
</code></pre>
<p>Suppose that I always create Points by using a string of the form <code>x_y</code>:</p>
<pre><code>x, y = my_string.split('_')
p = Point(x, y)
</code></pre>
... | <p>The <code>__init__</code> function can take whatever arguments make sense for your application. If your <code>Point</code> class is used by others, they might be wondering why they can only instantiate the class by providing a formatted string. You can allow both ways of initialization by using a static method like ... | python|python-3.x|oop|initialization | 1 |
9,183 | 51,396,167 | python property referring to property/attribute of member attribute? | <p>I'm wondering if I have:</p>
<pre><code>class A(object):
def __init__(self):
self.attribute = 1
self._member = 2
def _get_member(self):
return self._member
def _set_member(self, member):
self._member = member
member = property(_get_member, _set_member)
class B(object... | <p>I find the question a bit unclear, however I try to explain some context.</p>
<blockquote>
<p>Where the get/setters do logic, its of course needed, but if I simply wan't to expose the member/attributes of a member attribute</p>
</blockquote>
<p>If there is no logic in getter/setters, then there is no need to def... | python-3.x|class|properties | 2 |
9,184 | 73,763,944 | pandas, transforming dataframe & combining duplicates with counts | <p>Current dataframe is as follows:</p>
<pre><code>df = pd.read_csv('filename.csv', delimiter=',')
print(df)
idx uniqueID String CaseType
0 1 'hello1' 1.0
1 1 'hello2' 1.0
2 1 'goodbye1' 1.0
3 1 'goodbye2' 1.0
4 ... | <p>You could try the following:</p>
<pre class="lang-py prettyprint-override"><code>df_res = df[["String"]].rename(columns={"String": "Source"})
df_res["Destination"] = (
df.groupby("uniqueID")["String"].transform("shift", -1)
.fillna(df[&q... | python|pandas|dataframe | 1 |
9,185 | 69,802,563 | Pygame dialog box: using transparent surface and gradual typing simulaneously | <p>So I'm trying to make a text box for character dialog with the box transparent, and the text characters to show up one at a time. I can do one or the other separately, but when I try to combine them it doesn't make the transparency until after the typing is finished. The text is also transparent, which I don't want ... | <p><code>textbox_surf.set_alpha(100)</code> makes the entire <em>Surface</em> and its entire content transparent. When you don't clear the background (fill gray), you are continuously stacking transparent surfaces. As a result, the rectangle appears opaque and the text has a slight fading effect from older text to newe... | python|pygame | 1 |
9,186 | 73,447,836 | cannot put the output in the written txt file in python | <p>I am new to python and I tried to firstly create a new empty file with the help of python, for example:</p>
<pre><code>f=open('new.txt','x')
</code></pre>
<p>After creating this file, I wanted to write my output, which appears after running the code below, inside of the new.txt file:</p>
<pre><code>for i in range(1,... | <pre><code>with open("new.txt", "w") as f: # opens a new file and gets you ready to write to it (hence the 'w', it stands for write)
for i in range(1,5):
for j in range(0,i):
print(i,end=' ')
f.write(f"{i} ") # write what you wanted to print
pr... | python|file-io|jupyter-notebook|fwrite | 0 |
9,187 | 50,029,574 | Dropbox API - trying to upload a file | <p>I've just rebuilt my Raspberry Pi and hence installed the latest version of the Dropbox API and now my program doesn't work. I think this is due to point 1 in these breaking changes: <a href="https://github.com/dropbox/dropbox-sdk-python/releases/tag/v7.1.0" rel="nofollow noreferrer">https://github.com/dropbox/drop... | <p>You need to supply <code>bytes</code>, but you're supplying <code>str</code>.</p>
<p>You can get <code>bytes</code> by changing the file mode to binary. I.e., instead of:</p>
<pre><code>f = open(sourcefile, "r")
</code></pre>
<p>do:</p>
<pre><code>f = open(sourcefile, "rb")
</code></pre> | python|python-3.x|dropbox-api | 2 |
9,188 | 66,592,977 | Parse block name and instanace name from the text with regex | <p>I am trying to parse following text</p>
<pre><code>`ifndef abc
`define abc
module xyz(
block
#(
.BLK (def::a)
)
inst
(/*AUTOINST*/
</code></pre>
<p>This is the regex I tried:</p>
<pre><code>(\w+)\s*.*?(\w+)\n*\s*\(\n*\/\*AUTOINST\*\/
</code></pre>
<p>Expected ... | <p>This one worked for me:</p>
<pre><code>(\w+)([\r\n]+)
</code></pre>
<p>Here is a live <a href="https://regex101.com/r/FBMPV4/1" rel="nofollow noreferrer">Demo</a></p> | python|regex | 1 |
9,189 | 52,915,640 | python pandas - merge multiple column with complementary row | <p>The dataframe example: </p>
<pre><code> col1, col2, col3
1 v1
2 v2
3 v3
4 v4
5 v5
6 v6
</code></pre>
<p>I want to merge <strong>col1, col2, col3</strong> to the new column like the following:</p>
<pre><code> col_new
1 v1
2 v2
3 v3
4 ... | <p>You can use :</p>
<pre><code>df = df.fillna('').sum(axis=1)
# 0 v1
# 1 v2
# 2 v3
# 3 v4
# 4 v5
# 5 v6
</code></pre> | python|pandas | 1 |
9,190 | 65,422,744 | Averaging data of dataframe columns based on redundancy of another column | <p>I want to average the data of one column in a pandas dataframe is they share the same 'id' which is stored in another column in the same dataframe. To make it simple i have:</p>
<p><a href="https://i.stack.imgur.com/BeWGT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BeWGT.png" alt="enter image ... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with specify columns names in list for aggregates and assign back:</p>
<pre><code>cols = ['nx','ny']
df[cols] = df.groupby('nodes')... | python|pandas | 4 |
9,191 | 71,603,391 | Status for Sentinel-2 Products always returns False (0) even when they should return True (1) | <p>I'm trying to use python to check if Satellite Image Products from Sentinel-2 are 'online' or 'offline' on the ESA servers. I'm using GNU Wget to achieve this.</p>
<p>As seen in the documentation (<a href="https://scihub.copernicus.eu/userguide/DataRestoration" rel="nofollow noreferrer">https://scihub.copernicus.eu/... | <blockquote>
<p>Does someone know how to solve this?</p>
</blockquote>
<p>Note that <code>subprocess.call</code> does return returncode of command, generally <code>0</code> denotes that command was executed without errors. If it so <code>wget</code> should create file, which you should be able to inspect in order to de... | python|subprocess|wget|sentinel2 | 0 |
9,192 | 61,984,992 | Combine dictionaries based on custom conditions | <p>I have 2 (or more dictionaries), each dictionary extracted and processed from a source. </p>
<p>The dictionary is of the format <code>word : count</code></p>
<p>Let us say, from document No. 1, this is the dictionary that I extract:</p>
<pre><code>dic1 = {'hello' : 1, 'able' : 3, 'of' : 9, 'advance' : 2, 'occurre... | <p>(1) Use <code>defaultdict</code> to handle a dictionary of lists, and use <code>Counter</code> to count,</p>
<pre><code>from collections import defaultdict, Counter
dic_list = [dic1, dic2]
df_dict = {'Count':Counter(), 'DocsOccuredIn':defaultdict(list)}
for i, dic in enumerate(dic_list, 1):
for key, val in d... | python|pandas|dictionary | 2 |
9,193 | 71,160,018 | How to Filter SQL data in Python Program? | <p>I have this code, which takes data from MSSQL database and shows it in a table in my program.
My question is: How could I make a filter button so I could only show items containing "this persons name" or "this date" or "this order nr" etc if I wish?</p>
<pre><code>
def View():
for i... | <p>I would suggest to define a potential SQL query as an f string:</p>
<pre><code>sql_query = f"SELECT {criterion1} FROM PROD_MachiningEvents WHERE {criterion2};"
</code></pre>
<p>You can then design buttons that will, when clicked, assign values to the variables <code>criterion1</code> and <code>criterion2</... | python|sql-server|tkinter | 2 |
9,194 | 71,392,329 | Test not working whilst testing pandas dataframes | <p>Hey I am building tests for a small data cleaning script and am having a lot of problems with how to test my dataframes. I have tried using pandas.testing.assert_frame_equl and am currently trying to use df.equals(other_df). However, it does not work, even though I get the result I am looking for if I print the dat... | <p><code>assert cleaning.df.equals(expected_df)</code> raises <strong>AssertionError</strong> because your dataframes' columns order is not identical:</p>
<ul>
<li>"PARAMETER_NAME" is the last column of <em>cleaning.df</em></li>
<li>but the second one of <em>expected_df</em></li>
</ul>
<p>If you add the follo... | python-3.x|pandas|testing | 1 |
9,195 | 63,459,550 | How to split a string into text and number using re library or any other method in an Excel sheet? | <p>I need to convert the first column of the Excel sheet into an integer value. Need to remove the string (say <code>LP001005</code>, remove <code>LP</code> and get the rest of the number).</p>
<p>I am able to achieve this on a single variable. But, I need to achieve this on the Excel sheet. I mean to convert the entir... | <p>You can use the <code>.extract()</code> method to pull out the numeric part of the Loan ID:</p>
<pre><code>df = pd.DataFrame({'LoanID': 'LP1401 LP2102 LP3203'.split(),
'Name': 'Shubhra Ankit Sowmya'.split()})
df['LoanID'] = df['LoanID'].str.extract( r'\w(\d+)', expand=False ).astype(int)
print(df... | python|python-3.x|excel|python-re | 0 |
9,196 | 63,538,120 | Error while using tabulate "TypeError: 'int' object is not iterable" | <p>so, I was using tabulate to format my data in my latest project. But, it keeps giving this error and I'm not able to understand the reason behind it. Here's the code:</p>
<pre><code> from datetime import date
from tabulate import tabulate
records = []
sno = [0,1]
jades = [0,1]
events = ['0',1]
da... | <p>According to the <a href="https://pypi.org/project/tabulate/" rel="nofollow noreferrer">documentation</a>, the first parameter to tabulate is an iterable of iterables or similar, like a spreadsheet. You need both rows and columns. What you passed in was just one list, so internally, it first grabs the first element ... | python|python-3.x|tabulate | 3 |
9,197 | 62,959,549 | How to read items in a text file and overwrite it based on the user's inputs | <p>Please let me know if my question is correct
Context:
This function view_mine(), needs to be able to</p>
<ol>
<li><p>List the tasks of the user that is currently logged. It reads the information from a task.txt and checks if the username that has been input at the beginning (login) matches with the corresponding tas... | <p>When updating files, the more secure way to go is to create a temporal file where you write the content, while you keep the original safe and untouched. Then, when the writing process is done, you can remove the original and rename the temporal file.</p>
<p>Also, I think you should have some sort of unique ID that i... | python|function | 1 |
9,198 | 59,813,433 | How to store Google Auth Credentials object in Django? | <p>I'm trying integrate Google Tag Manager into my project. In official document, Google suggests oauth2client library. Unfortunately, this library deprecated. I used google_auth_oauthlib. I can get token and send request to Google Tag Manager API with this token. But I don't decide how can I store credentials object i... | <p>Just switch over to Django 2
<strong>pip install Django==2.2.12</strong>
I did it and works fine</p> | django|python-3.x|google-tag-manager|google-authentication|oauth2client | 0 |
9,199 | 67,771,469 | How to use "model.trt" in Python | <p>I have a pytorch model that I exported to ONNX and converted to a tensorflow model with the following command:</p>
<pre><code>trtexec --onnx=model.onnx --batch=400 --saveEngine=model.trt
</code></pre>
<p>All of this works, but how do I now load this <code>model.trt</code> in python and run the inference?</p> | <p>The official documentation has a lot of <a href="https://docs.nvidia.com/deeplearning/tensorrt/sample-support-guide/index.html" rel="nofollow noreferrer">examples</a>. The basic steps to follow are:</p>
<ul>
<li>ONNX parser: takes a trained model in ONNX format as input and populates a network object in TensorRT</li... | python|pytorch|onnx|tensorrt | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.