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 |
|---|---|---|---|---|---|---|
10,200 | 56,735,023 | How to increment last number in file python | <p>I have below text in the file </p>
<pre><code>firefox-x 46.0:
google 5.1.0.1:
- request
- branch
</code></pre>
<p>I need to extract the last letter of first line and increase by one version and append to same file. My append part will be </p>
<pre><code> firefox-x 46.1:
google 5.1.0.1:
- reques... | <p>You may use</p>
<pre><code>import re
rx = r'\d+(?=:$)'
s="""firefox-x 46.0:
google 5.1.0.1:
- request
- branch"""
print(re.sub(rx, lambda x: str(int(x.group(0)) + 1), s, 1, re.M))
</code></pre>
<p>Output:</p>
<pre><code>firefox-x 46.1:
google 5.1.0.1:
- request
- branch
</code></pre>
<p>See the ... | python|regex|file|writefile | 0 |
10,201 | 56,830,905 | File Not Saving While Downloading File in Headless chrome using Selenium in python | <p>I am able to download file in normal chrome mode. where as, i am not able to see the download happening in headless chrome using selenium python.</p>
<p>I hope it is not saving the file downloaded</p>
<p>Tried with solutions provided by many users in internet but none of them works</p>
<pre><code>options = Option... | <p>Try adding <code>download.prompt_for_download</code> = <code>False</code> and <code>download.directory_upgrade</code> = <code>True</code> you car set <code>safebrowsing_for_trusted_sources_enabled</code> to <code>False</code> as well as <code>safebrowsing.enabled</code>.</p>
<p>try changing your prefs to:</p>
<pre... | python|python-3.x|selenium|selenium-webdriver|selenium-chromedriver | 1 |
10,202 | 56,718,884 | Regex to match a list of field:values | <p>I am writing a program (for python homework assignment) that searches a database based on a query</p>
<p>the queries are formatted like this (arbitrary field names)
Field:Value
And they are separated by commas for multiple</p>
<p>EG</p>
<p>Name:George Bush, Address: 1234, b-street, Email: email@email.com</p>
<p... | <p>To get the matches from your example data, you might use a <a href="https://www.regular-expressions.info/charclass.html#negated" rel="nofollow noreferrer">negated character class</a> matching not a whitespace char or a <code>:</code> to match the field as in the example data is does not contain a whitespace. </p>
... | regex|python-3.x | 2 |
10,203 | 66,276,708 | Python regular expression to identify parentheses pairs in a string; unless the parentheses are in a squared bracket? | <p>I have a strings that look like this:</p>
<pre><code>[object]-ABGF-[A-BEC(2)]-LRPG-[object]
ABCDEFGHDGSASDASR-(typ1)-ASDHASDUASIUDHAS-[object]
[object]-RLC(1)-C(2)-GF-[obj]-KSASDASD-[obj3]-ASD-[object]
[object3]-RLC(1)-C(2)-GF-[Hyp]-KSCRSRQCK-[Hyp]-HRCC-[amide]
ABCDEFGHIJK(1)-GHGSHS(2)-ABCDE
ABCDD(1)-ASDASDASD(1)-AS... | <p>You might use 2 negative lookaheads to rule out what should not be matched.</p>
<pre><code>^(?!.*?\[[^][()]*\([^()]*\))(?!.*?\((\d+)\).*?\1).+
</code></pre>
<p>The pattern matches</p>
<ul>
<li><code>^</code> Start of string</li>
<li><code>(?!</code> Negative lookahead
<ul>
<li><code>.*?\[[^][()]*\([^()]*\)</code> Ma... | python|regex | 0 |
10,204 | 69,069,313 | I want to start my countdown when my clicks per second is > 0. Sorry if my code looks bad, I just started | <p>I want to start my countdown when my clicks per second are > 0 instead of automatically starting.</p>
<p>Here is the Code:</p>
<pre><code>from Tkinter import *
import threading
import time
count = 0
def clicked(event):
global count
count = count + 1
print(count)
#countdown
def trigger():
time.... | <p>Add a bool variable called <code>countdown_started</code> and make the value <code>False</code>. When clicked, check if <code>countdown_started</code> is <code>False</code>, and if it is, start the thread / countdown.</p>
<p>Also, you should use <code>root.after</code> (for your case it's <code>window.after</code>) ... | python | 0 |
10,205 | 69,244,012 | How to transform a sine wave to square wave (0 or 1) using Python? | <p>I saw this diagram and wonder how can I transform a sine wave into a square wave using Python. Which library will help me ? How to implement "adaptiveThreshold" and "filterSignal"? Please give me idea on where to look for?</p>
<p><a href="https://i.stack.imgur.com/rcia9.png" rel="nofollow nore... | <p>I implemented a quick example in python:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pylab as plt
num_cyc, n_samples = 10, 401
x = np.linspace(-np.pi, np.pi * num_cyc, n_samples)
y = np.sin(x)
y_ = np.convolve(y, np.ones(num_cyc*20)/(num_cyc*20), mode='same')
thres = 0.... | python | 2 |
10,206 | 68,064,015 | Authenticate URL using ID and password and then move file from URL to GCS bucket using Python | <p>I have a requirement to authenticate a webpage and download the file to GCS bucket</p>
<p>I got a solution from the below link that we can directly transfer the file from URL to GCS bucket which is without authentication.</p>
<p><a href="https://stackoverflow.com/questions/54235721/transfer-file-from-url-to-cloud-st... | <p>If you log in into an external password and then you want to get the file in GCS bucket you have 2 solutions:</p>
<ul>
<li>Either the user account is a google account and you autorise it to get the file from GCS (with IAM permissions) -> But, because you log in into an external website, I assume it's not a Googl... | python|google-cloud-platform|google-cloud-functions|google-cloud-storage | 1 |
10,207 | 62,327,182 | How to avoid circular imports in Peewee when using query class methods on models? | <p>When using Peewee I follow the advice from the <a href="https://stackoverflow.com/questions/46898990/create-query-methods-in-peewee-models-python">Create "query methods" in Peewee Models Python</a> answer:</p>
<pre class="lang-py prettyprint-override"><code>class Person(Model):
name = CharField()
... | <p>I don't think you understand Python scoping. There's nothing wrong with referencing a related model inside a method body, e.g.:</p>
<pre><code># Move metric below Person.
class Person(Model):
name = CharField()
age = IntegerField()
@classmethod
def popular(cls, min_likes):
return cls.select... | python|sqlite|foreign-keys|peewee | 1 |
10,208 | 62,115,794 | Label.image shows AttributeError: 'NoneType' object has no attribute 'image' | <p>I have been trying to use the following code for showing image on labels:</p>
<pre class="lang-py prettyprint-override"><code>for i in range (0, 10):
img = Image.open("Toy Story.PNG")
img.load()
img = img.resize((100, 100), Image.ANTIALIAS)
img_title = ImageTk.PhotoImage(img)
print(img_title)
myL... | <p>Try changing last two lines to:</p>
<pre><code>myLabel_image = Label(tab_recommend, height = 90, width = 90, image = img_title)
myLabel_image.place(x=108,y=200)
myLabel_image.image = img_title
</code></pre>
<p><code>place</code> method does not return Label, but modifies it in-place, returning <code>None</code>.</... | python|label | 0 |
10,209 | 31,497,479 | how to select columns from R dataframe in rpy2 in python? | <p>I have a dataframe in rpy2 in python and I want to pull out columns from it. What is the rpy2 equivalent of this R code?</p>
<p><code>df[,c("colA", "colC")]</code></p>
<p>this works to get the first column:</p>
<p><code>mydf.rx(1)</code></p>
<p>but how can I pull a set of columns, e.g. the 1st, 3rd and 5th?</p>
... | <p>Alternatively, you can pass the R data frame into a Python pandas data frame and subset your resulting 1, 3, 5 columns:</p>
<pre><code>#!/usr/bin/python
import rpy2
import rpy2.robjects as ro
import pandas as pd
import pandas.rpy.common as com
# SOURCE R SCRIPT INSIDE PYTHON
ro.r.source('C:\\Path\To\R script.R') ... | python|r|dataframe|rpy2 | 5 |
10,210 | 31,486,577 | Is it bad to use instance methods to organize code in a large python class | <p>Below I have a dummie code, where instance methods are definied mainly for code organization. The <strong>init</strong> function sets up a chain of calls to the various instance methods in a specific order, and I am just starting to feel it is bad practice to have code organized in such a way. </p>
<p>If so are the... | <p>Is your concern that developers may call <code>do_thing</code> independent of <code>do_things</code>? While Python doesn't support private methods, you can indicate that <code>do_thing</code> should be treated as private by using the leading underscore convention:</p>
<pre><code>def _do_thing(self):
...
</code>... | python|tkinter|organization | 2 |
10,211 | 15,687,528 | Get entries by values in child model | <p>I have a following model:</p>
<pre><code>class Parent(models.Model):
title = models.CharField(max_length=255)
class Child(models.Models):
title = models.CharField(max_length=255)
parent = models.ForeignKey(Parent)
</code></pre>
<p>How can I get all entries from Parent, where count of Child equal 0? I... | <p>. from django.db.models import Count</p>
<pre><code>Parent.objects.annotate(cc=Count('child')).filter(cc=0)
</code></pre>
<ul>
<li><a href="https://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset" rel="nofollow">Documentation on annotations in general</a></... | python|django|model|filter | 2 |
10,212 | 59,578,556 | while importing seaborn i was getting this error | <pre><code>import seaborn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\HP\Anaconda3\lib\site-packages\seaborn\__init__.py", line 6, in <module>
from .rcmod import *
File "C:\Users\HP\Anaconda3\lib\site-packages\seaborn\rcmod.py", line 5, in <module... | <p>Welcome to Stackoverflow and Happy New Year!</p>
<p>I think you haven't installed <code>numpy.testing.decorators</code>.</p>
<p>Run <code>pip install numpy</code> and retry.</p> | python-3.x | -1 |
10,213 | 48,976,797 | How to make image gallery from zip archive in wagtail? | <p>I have a project and i have idea to make <code>wagtail</code> <code>Page</code> where user can upload an <code>zip</code> archive of images in the admin section. And then I want to unzip this archive and put each unzipped image to Image Gallery connected to this page:</p>
<pre><code>import urllib.parse
import os
im... | <p>I need to create <code>wagtail_hooks.py</code> file, and ,as said in the <a href="http://docs.wagtail.io/en/v2.0/reference/hooks.html#id18" rel="nofollow noreferrer">docs</a>, define hooks there: </p>
<p><strong>models.py</strong>:</p>
<pre><code>from wagtail.images.models import Image
...
class ExtenedWagtailIma... | python|python-3.x|wagtail | 3 |
10,214 | 48,902,691 | sort dataframe alphabetically | <pre><code>birth_data.sort_values(by='name',ascending = True)
</code></pre>
<ul>
<li>name numbers
<ol start="2">
<li>bruh 96570</li>
<li>gib 95095</li>
<li>mel 115195</li>
<li>nish 112055</li>
<li>raw 88018</li>
</ol></li>
</ul>
<p>I can sort the "numbers" but if i replace it with "name"... | <p>Try that:</p>
<pre><code>birth_data.sort_values(by=['name'], ascending = True)
</code></pre>
<p>Edit: Are you sure there is a column called 'name'?</p> | python|pandas|sorting | 2 |
10,215 | 48,893,732 | conda menu in jupyter notebook from any environment | <p>Trying to install <code>nb_conda</code> (as per <a href="https://stackoverflow.com/a/42585283/5576434">this answer</a>) in root environment, so I wouldn't need to install it in each environment separately, but I'm getting the error:</p>
<pre><code>Downloading and Extracting Packages
nb_conda_kernels 2.1.0: ########... | <p>Found an answer to my own question. The problem was that when I run an installation script I used <code>sudo</code>. After reinstalling Anaconda without superuser permissions everything was working as per SO answers referenced in the question:</p>
<ul>
<li><code>conda install nb_conda</code> in root environment</li... | python|ipython|anaconda|jupyter-notebook|conda | 1 |
10,216 | 48,944,437 | HDF5 :pandas: error opening file in read only mode while mode used is 'w' | <p>Hello i am trying to save the dataframe in .h5 file but while i am providing command to do that, it fails saying that file is opening in read only mode and file does not exist.</p>
<pre><code>table.to_hdf('test.h5', key= 'csdkc', mode='w')
</code></pre>
<p>I looked for question on stack over but nothing looked rel... | <p>You should try</p>
<pre><code>table.to_hdf('test.h5', 'csdkc', table=True, mode='a')
</code></pre>
<p>Take a look at this example</p>
<p>WRITE</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'jh':[9,2,3,2],'dp':[1,0,0,1]})
df2 = pd.DataFrame({'jh':[7,1,2,1],'dp':[1,8,1,1]})
df1.to_hdf('newf.h5', 'ks',tab... | python|pandas|hdf5 | 0 |
10,217 | 25,076,058 | The same regex pattern that works fine doesn't work implemented into a Class | <p>Why this code retrieves one result:</p>
<pre><code>import re
input_file = open("nota_simple.txt", mode='r', encoding='utf-8')
text_to_search = input_file.read()
pattern = re.compile("(?<=FINCA Nº: ).*")
result = pattern.search(text_to_search)
print(result.group())
</code></pre>
<p>But this other doesn't matc... | <pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Suggested tweaks.
import re
class PropertyNumber(object):
def __init__(self, str, pattern = "(?<=FINCA Nº: ).*"):
self.regex_pattern = re.compile(pattern)
self.text_to_search = str
self.text_found = ""
def search_p_number... | python|regex|oop | 1 |
10,218 | 71,048,210 | How to get all analytics from SendGrid for each email? | <p>I would like to get all analytical data from SendGrid for each email using "unique args".</p>
<p>Currently to be able to do this, i would need to:</p>
<ol>
<li>call SendGrid API to get all emails with "unique arguments"</li>
<li>from response get email ID</li>
<li>call SendGrid again based on ema... | <p>You can use Event Webhooks from <code>SendGrid</code>. Events are generated when the email is processed by SendGrid and email service providers. There are 2 types of events - delivery and engagement events.</p>
<p>Delivery events indicate the status of email delivery to the recipient. Engagement events indicate how ... | javascript|python|node.js|analytics|sendgrid | 2 |
10,219 | 60,089,229 | Pivot table with multiple aggfunc sum and normalize one column | <p>I have a pivot table. I can't find solution how to add two agg func: sum and percent (proportion to total sum)</p>
<pre><code>table = pd.pivot_table(natnl_valyuta, values='vsego_zadoljennost', index=['koridor_procent'],
columns=['yur_fiz', 'srok'], aggfunc=np.sum, margins= True)
</code></pre>
<p><a... | <p>For my tests I created the following "surrogate" DataFrame:</p>
<pre><code>txt = ''',FL,FL,YUL,YUL
,1-Kpatk,3-Dolg,1-Kpatk,3-Dolg
0-5, 0, 469532, 0, 3421599
10-15, 2, 342485, 3394, 1084686
16-20, 349, 419492, 131095, 1578722
20 i bolee, 33941, 482238, 167077, 343972
6-10, ... | python|pandas|pivot-table | 1 |
10,220 | 3,014,631 | How to expose a web appication via API? | <p>we have create a web application on top of google app engine and python. which is almost about to complete it web front phase. I would also like to make it available almost all part of it to external applications. { via , xml , json , http , as many as possible. } . what's the best way to do it ? any library either ... | <p>Maybe <a href="http://bitbucket.org/jespern/django-piston/wiki/Home" rel="nofollow noreferrer">django-piston</a> could be of interest for you. But I do not know if there are restrictions for appengine.</p> | python|api|google-app-engine | 4 |
10,221 | 67,928,669 | Is there any way to set number of variables in SQL query based on length of list? | <p>I'm trying to get the monthly values from database according to user's choice and visualize them.
I have checkboxes as you can see below;</p>
<p><a href="https://i.stack.imgur.com/tHz4W.png" rel="nofollow noreferrer">Checkboxes I used</a></p>
<p>To get the monthly sales numbers according to user's choice I'm gettin... | <p>I found a better way to do this.
I created a string and multiply it with lenght of the list that contains the values of checked checkboxes.</p>
<pre><code>query="WHERE "+"nameofmonth=(%s) OR "*self.tryn
</code></pre>
<p>For getting rid of the extra OR and space at the end;</p>
<pre><code>query=q... | python|mysql|mysql-connector | 0 |
10,222 | 30,458,225 | Django insert query results into database | <p>I have a database table, called 'Tags' like this:</p>
<pre><code> ID | Name | Uses
------------------------
1 | Python | 0
2 | Java | 0
3 | C++ | 0
4 | Ruby | 0
</code></pre>
<p>I have another table, 'TagMap', that is used to map these tags to users, who can each hav... | <p>Django will let you query your <code>TagMap</code> model (I'm assuming you have a Django model here) to fetch the number of corresponding entries for a given tag.</p>
<p>Then, you'll be able to update the counter of uses in a separate call to the ORM.</p>
<p>Using a raw SQL query, you might be able to do both in a... | python|django|postgresql | 0 |
10,223 | 30,313,124 | Python 2.7 - Tweepy - How to get rate_limit_status()? | <p>I am working on a twitter App using Python 2.7 and the latest version of the tweepy module. One thing I cannot figure out is how to use the function rate_limit_status()</p>
<p>Here is my code:</p>
<pre><code>import tweepy, time, sys, random, pickle
import pprint
# argfile = str(sys.argv[1])
#enter the correspon... | <p>As per the Tweepy <a href="http://docs.tweepy.org/en/latest/api.html#API.rate_limit_status" rel="noreferrer">documentation</a></p>
<blockquote>
<p>Returns the remaining number of API requests available to the
requesting user before the API limit is reached for the current hour.
Calls to rate_limit_status do n... | python|python-2.7|dictionary|twitter|tweepy | 12 |
10,224 | 66,979,039 | Reverse gecoding - geopy.Nominatim module throws urlopen error [SSL: UNKNOWN PROTOCOL] | <p>I am trying to get the address details from Latitude and Longitude using geopy.Nominatim module. Am getting "<'urlopen error [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:727)>" error.</p>
<pre><code>Version Details :
Python version : 2.7
geopy version : 1.23.0
geographiclib : 1.50 (Dependency wi... | <p>The error <code>UNKNOWN PROTOCOL</code> is in all probability due to the fact that your request is going via a proxy.</p>
<p>I looked into your code mentioned in <code>Workaround 2</code>. Please mention the proxy explicitly in your code. Try using below code lines:</p>
<pre><code>ctx = ssl.create_default.context()
... | ssl|python-2.x|geopy | 0 |
10,225 | 63,851,489 | How to access a part of an element from a list? | <pre><code>import cv2
import os
import glob
import pandas as pd
from pylibdmtx import pylibdmtx
import xlsxwriter
# co de for scanning
img_dir = "C:\\images" # Enter Directory of all images
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
result=[]
for f1 in files:
img = c... | <p>You need to iterate on the list and retrieve the good properties on each.</p>
<pre><code>values = [[Decoded(data=b'AZ:HP7CXNGSUFEPZCO4GS5RQPY6XY', rect=Rect(left=37, top=152, width=94, height=97))],
[Decoded(data=b'AZ:9475EFWZCNARPEJEZEMXDFHIBI', rect=Rect(left=32, top=191, width=90, height=88))],
... | python|excel|list|data-science|scrape | 1 |
10,226 | 42,984,444 | pytest_assertrepr_compare only fails | <p>I'm new at pytest and was taking a look on how to customize assertions. This example from pytest's website just fails, even if I compare Foo(1) == Foo(1). Any idea why?</p>
<p><a href="http://docs.pytest.org/en/latest/assert.html#defining-your-own-assertion-comparison" rel="nofollow noreferrer">http://docs.pytest.o... | <p>Strange, your test passes for me. It failed at first, but I had messed up the indentation of the <code>__eq__()</code> method. Check that you haven't mixed up tabs and spaces or something.</p>
<p>Assuming that's not your problem, I suggest you try running it with a debugger if you use Eclipse or PyCharm. See what v... | python|unit-testing|testing|pytest | 0 |
10,227 | 42,930,317 | Get variable to which an object is assigned from inside the object? | <p>In Python, I'd like to get the variable to which an object is being assigned to. Something like: </p>
<pre><code>class Parent(object):
def __init__(self):
print(???) # Print the variable to which the created instance of
# Parent has been assigned to.
p = Parent() # This should pri... | <p>For the various reasons presented, that is not ordinarily feasible. It is doubly unfeasible in the <code>__init__</code> or other class initialization method, since the object is not ready yet - only when it is initialization is complete, the new object will be returned to the calling context and (possibly) assigned... | python|python-3.x|class|introspection | 1 |
10,228 | 66,364,691 | Select the last part of a string in a list | <p>I have a list with the following output when I print a list:</p>
<pre><code>['/dbfs/mnt/abc/date=20210225/fsp_store_abcxyz_lmn_', '/dbfs/mnt/abc/date=20210225/fsp_store_schu_lev_bsd_s_']
</code></pre>
<p>Our requirement is:</p>
<pre><code>fsp_store_abcxyz_lmn_
fsp_store_schu_lev_bsd_s_
</code></pre>
<p>Could you ple... | <p>Example of solving your task using <a href="https://docs.python.org/3/library/stdtypes.html#str.rpartition" rel="nofollow noreferrer">str.rpartition()</a>. I had to reimplement Max() and LJust() functions because you have <code>pyspark</code> and it has different implementations for built-ins <code>max()</code> and ... | python | 1 |
10,229 | 66,409,298 | How to set permissions differently from channel to channel for several roles at a bulk? | <p>I have 5 text channels and 2 voice channels. And from channel to channel, I want to give those channels permissions for 4 seperate roles.</p>
<pre><code>text_channel_name = ['server-gateway', 'chatroom', 'gameplay-map', 'spectator-chat', 'log', 'staff-room']
voice_channel_name = ['player-voicechat','spectator-voicec... | <p>If the set of channels you need is always the same you're most likely looking to create your own set of channels with preset permissions in every guild your bot joins.</p>
<p>Channels are attributes of Guilds so that's where you'll find methods to manage them, take a look at:</p>
<p><a href="https://discordpy.readth... | python|discord|discord.py | 0 |
10,230 | 66,432,816 | how to show/hide widget in tkinter without moving other widget | <p>I'm using <code>grid_remove()</code> and <code>grid()</code> command to hide/show the widget but the result is the other widget is move out of the original position.</p>
<p>How to hide/show the widget without moving widget</p>
<p>Example:</p>
<pre><code>from tkinter import *
from tkinter import ttk
GUI = Tk()
GUI.... | <p>The problem is <code>grid()</code> does not take up empty space by default, it gives the last empty row/col to the widget(if previous rows before it are empty).</p>
<p>So what you can do is, set minimum space for your column and row so that those space will remain empty, so change your function to:</p>
<pre><code>de... | python|tkinter|ttk | 1 |
10,231 | 65,562,711 | I need to integrate python script along with libraries to spring-boot application | <p>I am developing a spring boot application, where it needs to call a python script with few arguments and get back the results from python. I need to develop the application as a single unit that is portable. I have an idea of using maven jpython/python integration (making jar file of python + libraries for python st... | <blockquote>
<p>it needs to call a python script with few arguments and get back the results from python</p>
</blockquote>
<p>Not sure if you really are familiar with <a href="https://spring.io/projects/spring-integration" rel="nofollow noreferrer">Spring Integration</a>, but since you mention that tag, I'm going to sh... | python|spring-boot|maven|spring-integration|executable-jar | 0 |
10,232 | 50,918,819 | Can't set multiple cookies in Flask | <p>I have two lists:</p>
<ol>
<li>[1, 2, 3]</li>
<li>[4, 5, 6]</li>
</ol>
<p>I iterate over them to generate a cookie like so:</p>
<pre><code>for i, j in zip(list_1, list_2):
url = 'http://www.website.com/{}'.format(i)
payload = 'encoded{}'.format(j)
headers = {...}
request = requests.request("POST",... | <p>Just put the response variable outside your loop. You instantiate it whenever the "for i, j" loop iterates. Like so:</p>
<pre><code>response = make_response()
for i, j in zip(list_1, list_2):
url = 'http://www.website.com/{}'.format(i)
payload = 'encoded{}'.format(j)
headers = {...}
request = reques... | python|python-3.x|cookies|flask|request | 3 |
10,233 | 50,804,170 | Load FLAC file in python same as scipy or librosa | <p>I would like to feed some flac sound files into a keras model. With wavfiles I can do (contrived example with one audio file used twice)</p>
<pre><code>import scipy.io.wavfile
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizer... | <p>The <a href="https://github.com/bastibe/SoundFile/" rel="noreferrer">soundfile</a> package can load flac files in a numpy array compatible format</p>
<pre><code>import numpy as np
import soundfile as sf ... | python-3.x|scipy|flac|librosa | 10 |
10,234 | 3,518,303 | Scrapy web scraper can not crawl link | <p>I'm very new to Scrapy. Here my spider to crawl twistedweb. </p>
<pre><code>class TwistedWebSpider(BaseSpider):
name = "twistedweb3"
allowed_domains = ["twistedmatrix.com"]
start_urls = [
"http://twistedmatrix.com/documents/current/web/howto/",
]
rules = (
Rule(SgmlLinkExtracto... | <p><code>rules</code> attribute belongs to <code>CrawlSpider</code>.Use <code>class MySpider(CrawlSpider)</code>.
Also, when you use <code>CrawlSpider</code> you must not override <code>parse</code> method,
instead use <code>parse_response</code> or other similar name.</p> | python|screen-scraping|scrapy | 4 |
10,235 | 3,267,580 | SQLAlchemy and max_allowed_packet problem | <p>Due to the nature of my application, I need to support fast inserts of large volumes of data into the database. Using executemany() increases performance, but there's a caveat. For example, MySQL has a configuration parameter called max_allowed_packet, and if the total size of my insert queries exceeds its value, My... | <p>I had a similar problem recently and used the - not very elegant - work-around:</p>
<ul>
<li>First I parsed my.cnf for a value for <code>max_allow_packets</code>, if I can't find it, the maximum is set to a default value.</li>
<li>All data items are stored in a list.</li>
<li>Next, for each data item I count the ap... | python|mysql|sqlalchemy|large-query | 2 |
10,236 | 3,510,374 | django grappelli, filebrowser and Tiny MCE insert image dialog | <p>So, I found django admin interface called 'grappelli'. Looked at the screenshots and decided that I like it. Went to sources page and checked out trunk. Set it up and noticed that it looks nothing like screenshots. No dashboard, no side panel, different colors of the elements and model item lists are very narrow.</p... | <p>The current grappelli version is 2.1. It should work without problems with django 1.2.1 and the current filebrowser version! I think the screenshots on the google code site come from an older version, that had bookmark support etc included, but was removed from the actual version because this functionality (also das... | python|django|tinymce|django-filebrowser|django-grappelli | 1 |
10,237 | 50,626,626 | How to save HTML5 geolocation data to python Django admin? | <p>Is it possible to save the javascript html5 geolocation latitude and longitude to the django admin when user uses the geolocation website. The web page goal is to save the user's longitude and latitude values so that the data can be accessed later on when user signs in again.</p>
<p>I found a similar question being... | <p>I have used jQuery and Ajax to submit the longitude and latitude data to any model you want to store these data in.</p>
<p>in your model.py:</p>
<pre><code> from django.contrib.auth import User
class UserGeoLocation(models.Model):
user = models.OneToOneField(User)
latitude = models.FloatF... | javascript|python|django|html|geolocation | 3 |
10,238 | 50,384,862 | Python metaprogramming: generate a function signature with type annotation | <p>I am working within a Python web framework that uses Python 3 type annotations for validation and dependency injection.</p>
<p>So I am looking for a way to generate functions with type annotations from a parameters given to the generating function:</p>
<pre><code>def gen_fn(args: Dict[str, Any]) -> Callable:
... | <p>Instead of creating a function with annotations, it's easier to create a function and then set the annotations manually.</p>
<ul>
<li><p><a href="https://docs.python.org/3/library/inspect.html#inspect.signature" rel="noreferrer"><code>inspect.signature</code></a> looks for the existence of a <code>__signature__</co... | python|metaprogramming|type-hinting | 8 |
10,239 | 50,655,078 | Assign function-local parameter to global variable with same name | <p>I have a module; say it's structured as:</p>
<pre><code>algorithms
├─ __init__.py
└─ algorithm.py
</code></pre>
<p>Inside my algorithm module, I have some global vars, and I would like to create a convenience initializer that sets them up. I would like to use the same names for the initializer's parameters as fo... | <p>If you really insist on keeping the parameter names <code>lower</code> and <code>upper</code> (why not just <code>new_lower</code>, <code>new_upper</code> or something like that?) then you could delegate the task to an inner function with alternative variable names.</p>
<pre><code>def init_range(lower, upper):
... | python|python-2.7 | 2 |
10,240 | 35,322,452 | Is there a way to sandbox test execution with pytest, especially filesystem access? | <p>I'm interested in executing potentially untrusted tests with pytest in some kind of sandbox, like docker, similarly to what continuous integration services do.</p>
<p>I understand that to properly sandbox a python process you need OS-level isolation, like running the tests in a disposable chroot/container, but in m... | <p>After quite a bit of research I didn't find any ready-made way for pytest to run a project tests with OS-level isolation and in a disposable environment. Many approaches are possible and have advantages and disadvantages, but most of them have more moving parts that I would feel comfortable with.</p>
<p>The absolut... | python|unit-testing|testing|docker|pytest | 8 |
10,241 | 65,038,652 | Celery max_tasks_per_child setting is not restarting the worker | <p>Failing on both Celery 4.4.7 and 5.0.2.</p>
<p>My task is leaking a substantial amount of memory.
I'd like to restart the worker after each task.
I'm starting the celery in a no concurrency mode <code>--concurrency=1</code> or/and <code>-P solo</code> as the memory used in a single task might be close to the total s... | <p>In your case, <a href="https://docs.celeryq.dev/en/stable/userguide/workers.html#max-tasks-per-child-setting" rel="nofollow noreferrer">the setting</a> is not honored since you specified the pool configuration of your worker as 'solo'. It works only if your configuration is 'prefork'. If you start the worker with th... | python|multiprocessing|celery | 0 |
10,242 | 65,008,422 | How to change view using pyQt and appScheduler? | <p>I'm new in python. I'm writing desktop application which should remind user each x minutes about exercises. When counter reach time application should change view to view with video.</p>
<p>In application I'm using Python 3.7, <a href="https://apscheduler.readthedocs.io/en/latest/" rel="nofollow noreferrer">appSched... | <p>Since your class does not have any internal state, and if this is the class that causes the problem, can you try this:</p>
<pre class="lang-py prettyprint-override"><code>class ExerciseTimeListener:
__view: Ui_MainWindow
def changeView(self, view):
view.page_main.setCurrentWidget(view.view_video)
... | python|pyqt5 | 1 |
10,243 | 61,390,129 | Plot simple graph with Python 2.7.5 | <p>I need to plot simple graph with default Python 2.7.5 installation. The script runs on a web server, I have no access to install additional Python packages. My initial script was using matplotlib, but apparently this is not supported. Could you please recommend a package that does the work with the mentioned Python ... | <p>I have used plotly a couple time and found it works well. It supports Python as well as JavaScript, so you should be well covered.
Check it out here: <a href="https://plotly.com/python/" rel="nofollow noreferrer">https://plotly.com/python/</a></p> | python|plot | 0 |
10,244 | 61,458,419 | Tensorflow Federated | tff.learning.from_keras_model() with a model with DenseFeature layer and multiple inputs | <p>I am trying to federate a keras model which has multiple inputs.
These some of these inputs are categorical and some of them are numerical, so I have some DenseFeature layers to embed the values.</p>
<p>The problem is that using <code>tff.learning.from_keras_model()</code> to expect as input_spec a dictionary with ... | <p>I was able to find the answer looking at the Federate Learning repository on GitHub:</p>
<p>The way to do it is to make the 'x' value of the orderedDict an orderedDict itself using as keys the name of the columns we want as input.</p>
<p>A concrete example is given here: <a href="https://github.com/tensorflow/fede... | python|tensorflow|keras|tensorflow2.0|tensorflow-federated | 2 |
10,245 | 61,588,013 | Retrieve a list element which conatins a string that starts with '(' followed by 12 alphanumeric or special charaters and ending with ')' in python | <ol>
<li>I have a .log file which contains huge no of lines, i am able to get particular lines from that file which conatins the required string through simple grep command and storing it in a .txt file</li>
<li>Now i am able to read the newly created file and split each word into a list</li>
<li>Now my requirement is ... | <p>Use <code>r'([(].{12}[)])'</code> as your regexp. Also, <code>print(elementFound.group(1))</code></p>
<p>The complete code:</p>
<pre><code>import re
with open('ss.txt', 'r') as hand:
for line in hand:
for ele in line.split():
element = re.search(r'([(].{12}[)])', ele)
if element... | python|regex | 0 |
10,246 | 60,704,578 | Cannot open python file by double clicking in windows when importing | <p>I have simple python file main.py:</p>
<pre><code>import pygame
print("Hi There")
input()
</code></pre>
<p>I have installed pygame, and the default app to open .py files is set to python.exe, but when i double click the file it won't open. If i try the same without the import line it can run with no problem.</p>
... | <p>From comment by @Jean-FrançoisFabre. The problem was that when I was just double-clicking the python file was running from different version of python than when I run it from cmd. By using of simple python script containing <code>import sys</code> and then <code>print(sys.executable)</code> I was able to change the ... | python|windows|cmd|pygame | 0 |
10,247 | 57,910,736 | Trying to insert value in list from user in for loop raises IndexError | <p>How many values he/she want to add and then he insert values using loop.</p>
<p>I use this loop for sorting:</p>
<pre><code>value = int(input("how many number u want to add"))
arr = [value]
for n in range(0, value):
arr[value] = input("Enter value")
for n in range(0, value):
print(arr[v... | <p>If you think that doing <code>arr = [value]</code> will create an array of length <code>value</code>, then you're wrong, it just creates a list that has one element, <code>value</code>, if you want to create a list that has <code>value</code> length, you can use list multiplication:</p>
<pre><code>value = int(input(... | python|python-3.x | 4 |
10,248 | 58,024,965 | zeep client exception. zeep.transport.session.cookies not propagating | <p>I tried to create a zeep client and use it by two methods.</p>
<p>1) I tried to keep everything in a single module . i created the zeep client object and it was working fine while using a payload.
2) I created a method which returns a zeep client object for a wsdl. I tried to use this a way as method 1) But ge... | <p>You must provide credentials to the session and then make a request like <a href="https://python-zeep.readthedocs.io/en/master/transport.html#http-authentication" rel="nofollow noreferrer">here</a></p>
<pre class="lang-py prettyprint-override"><code>from requests import Session
from requests.auth import HTTPBasicAu... | python|python-3.x|zeep | 0 |
10,249 | 58,047,095 | Python modifies the original variable after the function call | <p>I am wondering if someone can explain why Python modifies the original variable after assigning it to another variable and then passing the second variable the function call:
Consider the following example code:
Assume A is the original variable: </p>
<pre><code>A=np.array(([1,20,30,40,10,5,60]))
B=A
B.sort()
pri... | <p>if you say B=A where A is an Array, Python just makes a new Pointer to A
You can do</p>
<pre><code>A = B[:]
</code></pre>
<p>to copy Array</p> | python|list|sorting|variables | 1 |
10,250 | 58,156,331 | Duplicate & identify certain rows in a Pandas Dataframe - regex | <p>I did'nt find any solution about my issue.</p>
<p>I want to identify & duplicate with regex certains rows of my DataFrame.</p>
<p>For example my df :</p>
<pre><code> var1
0 House A and B
1 2 garage + garden
2 fridges
</code></pre>
<p>The result that i want in var2 (keep my var1 too) :</p>
<pre><cod... | <p>If those three cases are exhaustive, then you may use my solution, my solution uses a combination of regex matching and split.</p>
<pre><code>#the hard part
def my_scan(t):
#Split
#only '+' and 'and' are considered
cond = re.findall(r'(.+)(and|\+)(.+)' , t)
if len(cond):
t = [_.strip() for _... | python|regex|pandas | 1 |
10,251 | 18,410,295 | Python Running OS command with quotes inside | <pre><code>#!/usr/bin/python
import os
readLine = open('desktops.txt','r')
for line in readLine:
machineName = line
query = os.system('wmic -U corp.fakedomain.com/domainusername%password //192.168.1.100 "Select * from Win32_UserAccount Where LocalAccount = True"|grep "500|"|cut -d "\\" -f 2|cut -d "|"... | <p>You should escape your backslashes. Replace <code>\\</code> with <code>\\\\</code>:</p>
<pre><code>os.system('wmic -U corp.fakedomain.com/domainusername%password //192.168.1.100 "Select * from Win32_UserAccount Where LocalAccount = True"|grep "500|"|cut -d "\\\\" -f 2|cut -d "|" -f1')
</code></pre>
<p>or, make you... | python-2.7|operating-system | 0 |
10,252 | 69,511,375 | How to efficiently create a dict with key/value having the value as number of occurrences for a given key? | <p>How to efficiently create a dict with key/value, where the value is the number of occurrences for a given key?</p>
<p>I'm currently doing like this:</p>
<pre><code>dict_map = dict()
for car in data_frame["cars"]:
if car in dict_map :
dict_map.update({car : dict_counter.get(car)+1})
else:
... | <p>This is actually plenty efficient, just unidiomatic. Don't use <code>.update</code> here, and there's no need for the if-else.</p>
<pre><code>dict_map = {}
for car in data_frame['cars']:
dict_map[car] = dict_map.get(car, 0) + 1
</code></pre>
<p>But this is such a common use-case, the standard library includes <c... | python|pandas|dataframe|dictionary | 5 |
10,253 | 55,342,356 | Specify values on x axis for a mathplotlib.pyplot histogram | <p>Given a certain dataset, I would like to create three histograms in one plot. The data (just a small snippet of a huge dataset, which would break the mold) looks like this:</p>
<pre><code>x, y1, y2, y3
2.0466115, 0, 0, 0
2.349824, 0, 0, 0
2.697959, 0, 0, ... | <p>You can use <code>np.histogram</code> and then plot the values of the histogram:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
y1 = np.random.normal(3,1,10000)
y2 = np.random.normal(5,1,10000)
y3 = np.random.normal(7,1,10000)
bins = np.linspace(0, 10, 150)
x = np.linspa... | python|matplotlib|plot | 0 |
10,254 | 42,448,664 | Async generator is not an iterator? | <p>In Python you can write a generator that is iterable like:</p>
<pre><code>def generate(count):
for x in range(count):
yield x
# as an iterator you can apply the function next() to get the values.
it = generate(10)
r0 = next(it)
r1 = next(it) ...
</code></pre>
<p>When trying to use an async iterator, you... | <p>So, as @bosnjak said, you can use async for:</p>
<pre><code>async for ITEM in A_ITER:
BLOCK1
else: # optional
BLOCK2
</code></pre>
<p>But if you want to iterate manually, you can simply write:</p>
<pre><code>it = async_iterator()
await it.__anext__()
</code></pre>
<p>But I wouldn't recommend to do that.<... | python|python-asyncio | 31 |
10,255 | 42,150,001 | If statement with callable function in python | <p>In C++ if(function())
returns false or true</p>
<p>but how is done in python?
I ve tried:</p>
<pre><code>if function() == True:
</code></pre>
<p>Help!</p>
<p>Why is self needed?</p>
<pre><code>def func(self,word):
if word == 'Hello':
return True
word = 'Hello'
if func(word):
print(word)
</code>... | <p>The following code works just fine: </p>
<pre><code>def return_true():
return True
if return_true():
print("It's true!")
if return_true() == True:
print("It's also true!")
</code></pre>
<p>Just make sure you're function is correctly returning <code>True</code>, maybe modify it so the return is just <... | python|if-statement | 0 |
10,256 | 54,223,655 | Can a failed Airflow DAG Task Retry with changed parameter | <p>With Airflow, is it possible to restart an upstream task if a downstream task fails? This seems to be against the "Acyclic" part of the term DAG. I would think this is a common problem though.</p>
<p><strong>Background</strong></p>
<p>I'm looking into using Airflow to manage a data processing workflow that has bee... | <p><em>First of all: that's an excellent question, I wonder why it hasn't been discussed widely until now</em></p>
<hr>
<p>I can think of two possible approaches</p>
<ol>
<li><p><strong>Fusing <code>Operators</code></strong>: As pointed out by <a href="https://stackoverflow.com/users/6332463/kris"><strong>@Kris</str... | python|pipeline|airflow|directed-acyclic-graphs | 2 |
10,257 | 45,375,936 | Nose2 XML won't find modules, when unconfigured Nose2 will | <p>This is likely a beginners mistake, or something of the like. </p>
<h1>UPDATE</h1>
<p>I installed nose instead of nose2, and ran <code>nosetests --with-xunit</code> and it did exactly what I wanted, proving that the issue is not with my code but with how I am handling nose2. I would still like to know how I can ac... | <p>The right way to activate xunit report in nose2 is to use the <code>-X</code> or <code>--junit-xml</code> switch instead of the <code>--plugins</code> option.</p> | python-3.x|nose2 | 0 |
10,258 | 14,652,136 | boost python explicit typecast needed | <p>I have hybrid system (c++, boost python).
In my c++ code there is very simple hierarchy</p>
<pre><code>class Base{...}
class A : public Base{...}
class B : public Base{...}
</code></pre>
<p>2 more business (on c++) methods</p>
<pre><code>smart_ptr<Base> factory() //this produce instances of A and B
void co... | <p>When it comes to <code>boost::shared_ptr</code>, Boost.Python generally provides the desired functionality. In this particular case, there is no need to explicitly provide custom <code>to_python</code> converters as long as the module declaration defines that <code>Base</code> is held by <code>boost::shared_ptr<... | c++|boost-python | 4 |
10,259 | 41,625,552 | passing Python variable to triple quoted curl command | <pre><code>SIZ=100
imap_cmd="""
curl -s -X GET --insecure -u xxx https://xxxxx/_search?pretty=true -d '{
"from":0,
"size":%SIZ,
"query":{ "match_all": {} },
"_source":["userEmail"]
}' | grep -i userEmail|awk {'print $3'} | cut -d ',' -f1
"""
def run_cmd(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
output = (p... | <p>It looks like you're trying to use the <code>%</code> formatter in this line, </p>
<pre><code>"size":%SIZ,
</code></pre>
<p>try</p>
<pre><code>imap_cmd="""
curl -s -X GET --insecure -u xxx https://xxxxx/_search?pretty=true -d '{
"from":0,
"size":%d,
"query":{ "match_all": {} },
"_source":["userEmail"]
}' | grep -... | python-2.7 | 1 |
10,260 | 41,553,988 | How to extract unsupervised clusters from a Dirichlet Process in PyMC3? | <p>I just finished the <a href="https://rads.stackoverflow.com/amzn/click/com/1785883801" rel="noreferrer" rel="nofollow noreferrer">Bayesian Analysis in Python</a> book by <a href="https://github.com/aloctavodia" rel="noreferrer">Osvaldo Martin</a> (great book to understand bayesian concepts and some fancy numpy index... | <p>Using a couple of new-ish additions to <code>pymc3</code> will help make this clear. I think I updated the Dirichlet Process example after they were added, but it seems to have been reverted to the old version during a documentation cleanup; I will fix that soon.</p>
<p>One of the difficulties is that the data you... | python|machine-learning|bayesian|pymc3|unsupervised-learning | 9 |
10,261 | 6,474,724 | Inherit another object's methods | <pre><code>f = open('bobby_g.txt', 'w')
f.write('Hey bobby!')
f.close()
class BobFile:
def __init__(self, x):
self = open(x, 'r')
a = BobFile('bobby_g.txt')
print a.read()
a.close()
</code></pre>
<p>I don't want to subclass the 'file' object, I want to create a BobFile object that then becomes another o... | <p>attribute delegation?</p>
<pre><code>class BobFile:
def __init__(self, x):
self.__file = open(x,'r')
def __getattr__(self, name):
return getattr(self.__file, name)
a = BobFile('/dev/random')
print a.read(20)
a.close()
</code></pre> | python | 2 |
10,262 | 57,013,077 | How do I get specific data from this Json data? | <p>I have the following JSON data</p>
<pre><code> {
"results": [
{
"alternatives": [
{
"confidence": 0.6,
"transcript": "state radio "
}
],
"final": true
},
{
"alternat... | <p><code>"transcripts"</code> is not a direct child of <code>data</code>. It is, instead, the child of element <code>"alternatives"</code>, which is a child of each element of the list <code>"results"</code>, which is, in turn, the direct child of <code>data</code>. So, to get your contents of transcript as a list, do... | json|python-3.x | 1 |
10,263 | 44,613,191 | How to handle, when tkinter window gets focus | <p>I have this code:</p>
<pre><code>from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()
</code></pre>
<p>It prints <code>hello world</code> only once, and then it stops working. No more <code>hello world</code> Basically <code>WM_TAKE_FOCUS</code> does not work.</p> | <p>You can bind a function to the <code><FocusIn></code> event. When you bind to the root window the binding is applied to every widget in the root window, so if you only want to do something when the window as a whole gets focus you'll need to compare <code>event.widget</code> to the root window.</p>
<p>For exa... | python|tkinter|focus|protocols | 8 |
10,264 | 24,142,379 | Catch bad signature error for an specific function call | <p>I could have a code like this:</p>
<pre><code>def sum(a, b):
return a + b
# User chooses function and parameters
function = sum
params = {"a": 5, "b": 3}
try:
ret = sum(**params)
print(ret)
except TypeError:
# Function called with bad signature
print("Wrong parameters for the chosen function!"... | <p><a href="http://legacy.python.org/dev/peps/pep-0362/" rel="nofollow">PEP-0362</a> defines a signature object which can be helpful. It's included by default in Python 3.3+ but <a href="https://pypi.python.org/pypi/funcsigs" rel="nofollow">there is a backport</a> for earlier versions.</p>
<p>This would be the code us... | python|error-handling | 3 |
10,265 | 46,241,929 | When running a TF graph which functions should use CPU and which functions should GPUs when we have Multi GPUs? | <p>We can assign different devices to do different operations in a Tensorflow Graph with <strong>tf.device('cpu or gpu')</strong> , It's not clear how to divide them .
Other thing is if we use the default thing does TF always uses GPU if there's a GPU?</p>
<p><strong>UPDATE</strong> </p>
<p>When have two GPUs how to ... | <p>Finding a device in TF works as follows:</p>
<ol>
<li>Check if there are <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/common_runtime/placer.cc#L654" rel="nofollow noreferrer">devices at all</a></li>
<li>sanity-check if nodes manually assigned to devices <a href="https://github.com/t... | tensorflow|gpu | 3 |
10,266 | 49,357,332 | How to deploy pytorch in docker image? | <p>I want to deploy pytorch on a docker image. Is there a way that I can do that? I faced so much problems installing pytorch, their official installation links does not seem to be working; neither pip/conda works. Does anyone have any alternative solution in installing pytorch?</p> | <p>You can find pytorch images on <a href="https://hub.docker.com/search/?isAutomated=0&isOfficial=0&page=1&pullCount=0&q=pytorch&starCount=1" rel="nofollow noreferrer">Dockerhub</a>. </p>
<p>If those images are not sufficient, you can check their Dockerfiles to see how you can build you own custom... | docker|anaconda|pytorch | 1 |
10,267 | 70,077,683 | how to change the scale of the x-axis so that the orange and blue graphs are displayed correctly | <p>I cannot correctly depict two graphs: orange and blue. I've read the documentation, tried changing the values until nothing comes out.
How to show these graphs, as in 1 picture, together with others correctly</p>
<p><img src="https://i.stack.imgur.com/QGfPp.png" alt="enter image description here" /></p>
<p>I get it ... | <p>The red and green curve use an x-range from -15 to -4, while the orange and blue curves have a very limited range between 0.25 and 0.55. Displaying them together on the same graph will necessarily lead to the compression you see.</p>
<p>You can draw two subplots, and move them close together while sharing the y-axis... | python|matplotlib | 0 |
10,268 | 53,672,543 | Get the index of the highest value inside a numpy array for each row? | <p>I have a <code>numpy</code> array of 30 rows and 4 columns, for each row I need to get the index where the highest value is located. </p>
<p>So for an array like this</p>
<pre><code>a = np.array([[0, 1, 2],[7, 4, 5]])
</code></pre>
<p>I would like to get a list with the indices <code>2</code> for the first row an... | <p>Use the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.argmax.html" rel="nofollow noreferrer"><code>argmax</code></a> method with <code>axis=1</code> in order to work on the rows.</p>
<pre><code>>>> import numpy as np
>>> a = np.array([[0, 1, 2],[7, 4, 5]])
>>>... | python|arrays|numpy | 2 |
10,269 | 53,636,723 | Python parsing code with new line character in them using ast | <p>I have a string representation of the code, like the example given below</p>
<pre><code>code='''
print('\n')
print('hello world')
'''
import ast
ast.parse(code)
</code></pre>
<p>Throws an error</p>
<pre><code>print("
^
SyntaxError: EOL while scanning string literal
</code></pre>
<p>The new line characte... | <p>What seems to be happening is your 'code' is being interpreted by python before it can be parsed by ast. You can pass it as a raw string by putting an 'r' before the string and it seems to work;</p>
<pre><code>code=r'''
print('\n')
print('hello world')
'''
import ast
ast.parse(code)
</code></pre> | python-3.x|abstract-syntax-tree | 3 |
10,270 | 53,559,227 | is this possible to create sub-methods in python? | <p>I want to write a method to parse a site with requests library, the method should take a part of url having base_url in it and perform the get request on this, the main problem is that I do not know how to make it better;</p>
<p>What I have in mind now is:</p>
<pre><code>import requests
class Response:
# ...
de... | <p>It seems to me that what you need is another class.</p>
<pre><code>class Response:
# ... Some dark magic here ...
def site_parser(self, atom):
return ResponseParser(self, atom)
class ResponseParser:
def __init__(self, res, atom):
self.atom = atom
self.res = res
self.b... | python|class|methods|python-requests | 2 |
10,271 | 46,074,028 | Printing multiple lists using .format in Python 3.4.2 | <p>Can anyone shed light on this issue I'm having with Python 3.4.2?</p>
<p>I have two lists, and I want to print specific items within each list using the .format(). Here's the code:</p>
<pre><code>names=["Conan", "Belit", "Valeria"]
ages=[25, 21, 22]
print("{0} is {1} years old. Whereas {1} is {0} years old.".form... | <p><a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow noreferrer">Additional Unpacking</a> was added in Python 3.5, so you can't use multiple asterisks <code>*</code> in a function call in Python 3.4. It also doesn't work with <code>str.format</code> as you want, since calling </p>
<pre><code>print("{0}... | python-3.x | 0 |
10,272 | 46,100,858 | How to get frame from video by its index via OpenCV and Python? | <p>I need to access frames from video by the frame index. So far I used code like this:</p>
<pre><code>video = cv2.VideoCapture(video_path)
status, frame = video.read()
</code></pre>
<p>The code reads the first frame. If I use the code repeatedly I will get next frames. But how I can access directly any frame by its ... | <p>Use <code>VideoCapture::set()</code> with <code>CAP_PROP_POS_FRAMES</code> property id to set the position of the frame to be read.</p>
<pre><code>myFrameNumber = 50
cap = cv2.VideoCapture("video.mp4")
# get total number of frames
totalFrames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
# check for valid frame number
if m... | python|opencv|video | 28 |
10,273 | 54,737,817 | How save Tensorflow model in protobuf format? | <p>Please, help me with my problem. I want to save my neural network in protobuf (pb) format for OpenCV DNN. In input I have 3 files: .meta, .data, .index. As output I need to .pb and .pbtxt files.</p>
<p>Code, for example:</p>
<pre><code>train_data = np.load(TEST_PACK)
tf.reset_default_graph()
convnet = input_data(... | <p>The below function will freeze your model and create ".pb" file.</p>
<pre><code>def freeze_model(sess, logs_path, latest_checkpoint, model, pb_file_name, freeze_pb_file_name):
"""
:param sess : tensor-flow session instance which creates the all graph information
:param logs_path: string
... | python|opencv|tensorflow|neural-network | 0 |
10,274 | 54,775,904 | To make the bot react to the last the last message or react to a message with message ID | <p>I'm trying to make the bot react to the last message sent by a command, I've tried but except it gives me an error that <code>Message Argument must be a Message</code> In addition I've also tried to make the bot react to a message with a message id a user gives, Below is what I've tried to do</p>
<pre><code># (Most... | <p>For your first example <code>logs_from</code> is a coroutine (needs to be awaited) that <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.logs_from" rel="nofollow noreferrer">returns a generator</a> so you can do something like</p>
<pre><code>async for msg in logs:
await client.add_react... | python|python-3.x|discord|discord.py | 2 |
10,275 | 33,145,951 | If condition with operators execution in c++ and python | <p>Simple question of how execution happens in C++ and Python.<br>
If I have an if condition </p>
<pre><code>if ((b == c) and (a == b))
</code></pre>
<p>My doubt in the above condition is,<br>
if first part i.e. <code>(b == c)</code> is <strong>false</strong><br>
then the second condition i.e. <code>(a == b)</code> ... | <p>Both in c++ and python, <code>and</code> and <code>or</code> operations support <a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation" rel="nofollow">short-circuiting</a>, that is, if the left part of <code>and</code> is false, the right part is not evaluated; if the left part of <code>or</code> is true, t... | python|c++|execution | 4 |
10,276 | 33,194,489 | Mutable user defined types and sets | <p>I have a use case that requires me to create a set of mutable type
objects, something like this:</p>
<pre><code>class abc(object):
def __init__(self):
self.a = set(["a"])
def __eq__(self, o):
return self.a == o.a
a = abc()
b = abc()
print hash(a)
print hash(b)
print a == b
set([a]) == set([b... | <p>If you insert an object into a set (or any hash-based data structure in any language) and then mutate it, things will break because the new hash value may no longer correspond to its position in the array. So for example if you inserted another object which is equal to the previous object after the mutation, python ... | python|hash | 2 |
10,277 | 12,923,442 | How do I get the program to print the number of times a number occurs in the list? | <p>This is as much as I know how to do, not sure if I'm doing it correctly.</p>
<pre><code>L = [4, 10, 4, 2, 9, 5, 4 ]
n = len(L)
element = ()
if element in L:
print(element)
print("number occurs in list at the following position, if element not in list")
print("this number does not occur in the list")
</code>... | <p>The compulsory <code>defaultdict</code> post:</p>
<pre><code>from collections import defaultdict
el = [4, 10, 4, 2, 9, 5, 4 ]
dd = defaultdict(list)
for idx, val in enumerate(el):
dd[val].append(idx)
for key, val in dd.iteritems():
print '{} occurs in el at the following positions {}'.format(key, val)
#9... | python|list|element | 2 |
10,278 | 12,733,985 | Job processing via web application: real-time status updates and backend messaging | <p>I would like to implement an (open source) web application, where the user sends some kind of request via his browser to a Python web application. The request data is used to define and submit some kind of heavy computing job. Computing jobs are outsourced to a "worker backend" (also Python). During job processing, ... | <p>An option would be using WebSocket. If you go that road, you might check out <a href="http://autobahn.ws/" rel="nofollow">Autobahn</a>, which includes clients and servers for Python (Twisted), as well a an RPC+PubSub protocol on top of WebSocket (with libs for Python, JavaScript and Android). Using an RPC+PubSub sub... | python|web-applications|websocket|messaging|zeromq | 4 |
10,279 | 12,650,612 | Python3: Why does an exception needs explicit conversion while printing the message | <pre><code>class MyException(Exception):
def __str__(self):
return self.args[0]
def DoWork():
raise MyException("My hoverboard is full of eels")
pass
if __name__ == '__main__':
try:
DoWork()
except MyException as ex:
print("This will get printed: " + str(ex)) #Line1
... | <p>You have to convert it to a string because <code>x + y</code> ends up calling <code>x.__add__(y)</code>, so when <code>x</code> is a string you call <code>str.__add__</code>, which operates on two strings, not on a string and an Exception. Python's built in operators and types generally don't automatically try to fo... | python-3.x | 2 |
10,280 | 21,505,572 | Scrapy outputting the same thing hundreds of times | <p>I followed the tutorial on the scrapy page, and I tried to just edit the code to practice on wikipedia. When I do, it outputs the text in the page, but it does so hundreds of times. The JSON file as well as the console contains the same thing printed over and over. I think it may be something to do with the function... | <p>if you want second xpath to be relative to first one, instead of:</p>
<pre><code>item['title'] = sel.xpath('.//p/text()').extract()
</code></pre>
<p>do:</p>
<pre><code>item['title'] = site.xpath('.//p/text()').extract()
</code></pre>
<p>looping on <code>//div</code> create as many divs as they found in the docum... | python|scrapy | 1 |
10,281 | 21,859,405 | python https proxy error code 400, 401 | <p>I have a <code>HTTPS</code> proxy written in python. All worked until I made the proxy transparent. I redirected <code>80</code> and <code>443</code> ports to <code>8888</code>(the proxy port). Now only requests over <code>HTTP</code> works, when I request a <code>HTTPS</code> website, I get <code>400</code> and <co... | <p>Correct me if this is OT, but how do you <strong>test</strong> your HTTPS over HTTPS proxy?</p>
<p>Python does not support this!</p>
<p>Neither does <code>curl/libcurl/pycurl</code> etc.</p>
<p>You may be able to find a browser that supports it though.</p>
<p>Also, I haven't found anything in the linked github c... | python|https|proxy | 0 |
10,282 | 38,193,013 | for looping and appending into list | <pre><code>list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
</code></pre>
<p>so I have this code that gives the result of </p>
<pre><code>lecture 1
lecture 2
</code></pre>
<p>for an input of <code>lecture(3)</code>. Now, when I change the code to </p>
<pre><code>list = []
def lec... | <p>You are getting that strange notation because <code>'lecture', x</code> is a <a href="http://www.tutorialspoint.com/python/python_tuples.htm" rel="nofollow">tuple</a>. A datatype which acts like a list, but a non-flexible list. You can't change them that easily. You have to use the +-operator instead of a comma to p... | python|python-2.7 | 3 |
10,283 | 40,078,607 | Finding and extracting multiple substrings in a string? | <p>After looking <a href="https://stackoverflow.com/questions/11886815/pull-a-specific-substring-out-of-a-line-in-python">a</a> <a href="https://gis.stackexchange.com/questions/4748/python-question-how-do-i-extract-a-part-of-a-string">few</a> <a href="https://stackoverflow.com/questions/6633678/finding-words-after-keyw... | <p>Leverage (zero width) lookarounds:</p>
<pre><code>(?<!\w)PG|SG|SF|PF|C(?!\w)
</code></pre>
<ul>
<li><p><code>(?<!\w)</code> is zero width negative lookbehind pattern, making sure the desired match is not preceded by any alphanumerics</p></li>
<li><p><code>PG|SG|SF|PF|C</code> matches any of the desired patte... | python|regex|string|substring | 2 |
10,284 | 8,655,138 | easy_install with pypy while Python is installed | <p>I installed <a href="http://pypy.org/">PyPy</a> while still having Python 2.7 on my system.</p>
<ul>
<li>How do I install and then use <code>easy_install</code> with PyPy?</li>
<li>What is the syntax for distinguishing where I want to install to with <code>easy_install</code>?</li>
<li>Should I set any environment ... | <p>You need to install easy_install for pypy manually.</p>
<p>It's explained in the answer to this question :
<a href="https://stackoverflow.com/questions/5885820/installing-python-eggs-under-pypy">Installing Python eggs under PyPy</a></p> | python|setuptools|easy-install|pypy|distribute | 5 |
10,285 | 8,841,705 | Is learning Django without initial knowledge of Python possible? | <p>I am coming from procedural PHP with fair amount of knowledge on it. I want to learn Django but I don't have initial knowledge of Python. Can I learn Django at the same time also learning Python? Thank you so much!</p> | <p>No. You'll be writing Python code. In Python. You'll have to learn Python.</p>
<p>A little bit of your project will be CSS, JavaScript and HTML with template tags inserted.</p>
<p>Most of your project will be Python.</p> | python|django | 11 |
10,286 | 8,897,130 | Splitting letters and numbers to figure out and assign value in table | <p>I currently have some code in Python where I have entered the values from a table:</p>
<pre><code>rules = { "213" : ( 0.00019, 3.5, 0.00019, 3.5 ),
"222" : ( 0.00019, 4.0, 0.00019, min( 4.0, 4.1E-8 * dm**3 - 4.1E-5 * dm**2 + 0.017 * dm + 1.35 ) ),
"223" : ( 0.0003, 4.5, 0.0003, 4.5 ),
"2... | <p>This could be helpful to understand how to get the two parts from your entry</p>
<pre><code>>>> name = "11111A"
>>> ser = name[:3] # first 3 characters
>>> code = name[3:] # rest of chars after the third
>>> ser
'111'
>>> code
'11A'
>>>
</code></pre>
<p... | python|split | 2 |
10,287 | 8,844,547 | How to duplicate a file but change a few parameters inside? | <p>I am using python as an interface to several fortran files in my model. I want to duplicate a fortran file several times but at each copy, I will change the parameters that describe my model. </p>
<p>For example: I have the fortran file below</p>
<pre><code>!file.f
! This is a fortran code
!Parameters
alpha = 0.5... | <p>I think the most consistent way to go would be to use a templating engine. Python has a lot of then, usually deployed within web applications.</p>
<p>But the purpose of templating engines is exactly to allow one to have the bulk of the code, that needs nos change as static text, and through some special markup inte... | python|fortran|code-duplication|generated-code | 4 |
10,288 | 58,614,847 | Get all groups from a long line | <p>I have the following string:</p>
<p><code>aaa<a class="c-item_foot" href="/news/a/">11r11</a></div>bbb<a class="c-item_foot" href="/news/b/">222</a></div>ccgc<a class="c-item_foot" href="/news/c/">3333a333</a></div>ddd<a class="c-item_foot" href="/news/d/">... | <p>I suggest you use a html parsing library like BeautifulSoup.</p>
<pre><code>html_doc = 'aaa<a class="c-item_foot" href="/news/a/">11r11</a></div>bbb<a class="c-item_foot" href="/news/b/">222</a></div>ccgc<a class="c-item_foot" href="/news/c/">3333a333</a></div>d... | python|regex|regex-group|findall | 1 |
10,289 | 52,298,179 | Pytorch: List of layers returns 'optimizer got an empty parameter list' | <p>I have a defined model and defined layer, I add n instances of my defined layer to a list in the init function of my model as follow:</p>
<pre><code> self.layers = []
for i in range(len(nhid)-1):
self.layers.append(MyLayer(nhid[i], nhid[i+1]))
</code></pre>
<p>but when I create optimizer by</p>
<pr... | <p>I solved the problem by using <code>nn.ModuleList()</code> as follow:</p>
<pre><code>temp = []
for i in range(len(nhid)-1):
temp.append(MyLayer(nhid[i], nhid[i+1]))
self.layers = nn.ModuleList(temp)
</code></pre>
<p>I also read about <code>nn.Sequential()</code>, but I didn't find out how to use it in a correc... | python|python-3.x|pytorch | 4 |
10,290 | 52,362,047 | Axis values is not showing as in the DataFrame in python | <p>I want the Y-axis in the Graph with the Range in the Sum column. </p>
<pre><code>total_by_year.plot(kind='bar' ,x='year',y='sum',rot=0, legend=False)
plt.show()
</code></pre>
<p>DataFrame output:</p>
<pre><code> year sum
0 2010 42843534.38
1 2011 45349314.40
2 2012 35445927.76
3 2013 0.0... | <p>You can use this:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib
y = total_by_year['sum']
ax = total_by_year.plot(kind='bar' ,x='year',y='sum',rot=0, legend=False)
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter("%.2f"))
plt.yticks(y)
plt.show()
</code></pre>
<p><a href="https:... | python|matplotlib | 1 |
10,291 | 51,680,659 | Disparity between result of numpy gradient applied directly and applied using xarray.apply_ufunc | <p>I'm trying to use xarray's <code>apply_ufunc</code> to wrap numpy's <code>gradient</code> function, in order to take gradients along one dimension. However, <code>apply_ufunc</code> is returning an array with a different shape to the one which using <code>np.gradient</code> directly returns:</p>
<pre><code>import x... | <p><code>xr.apply_ufunc</code> moves the <code>input_core_dims</code> to the last position.
The dimension that gradient was computed along are moved to the last position, and therefore the resultant shape would be transposed compared with the result by <code>np.gradient</code>.</p>
<p>The problem is that in your scri... | python|numpy|python-xarray|numpy-ufunc | 1 |
10,292 | 51,657,370 | How to pass keyword argument as a key to other function in python? | <p>Code:</p>
<pre><code>def edit_properties(self, device, ssc_command="hexa", value="test")
result = self.edit_devices.edit_device_property(device, ssc_command=value)
</code></pre>
<p>I want to pass "ssc_command" as a key to self.edit_devices.edit_device_property(device, ssc_command=value) and value as a value.</... | <p>Dictionary/kwargs expansion. First, you make a dict with <code>ssc_command</code> as the key and <code>value</code> as the value, and then you use <code>**</code> to expand it into a set of keyword arguments:</p>
<pre><code>result = self.edit_device.edit_device_property(device, **{ssc_command:value})
</code></pre> | python|python-3.x | 2 |
10,293 | 62,295,758 | how to extract column name for melt function? Python | <p>I have a data set that has the following columns.</p>
<pre><code>data.columns[1:]
Index(['Fraud (i.e. fabricated or falsified results)',
'Pressure to publish for career advancement',
'Insufficient oversight/mentoring by lab principal investigator (e.g. reviewing raw data)',
'Insufficient peer r... | <p>Here's a solution: </p>
<pre><code># Create a dummy dataframe with columns similar to yours.
df = pd.DataFrame({"respid": range(5),
"Fraud (i.e. fabricated or falsified results)": range(5,10),
'Pressure to publish for career advancement': range(10, 15),
'I... | python|melt | 0 |
10,294 | 56,430,430 | How to give priority to conda package over pip one? | <p>With my virtual environment activated, I see with <code>conda list</code> that my pandas version is 0.24.0. When I do the same with <code>pip list</code>, I see the version is 0.22.0 (probably an older version that I installed before using conda). When I import pandas in python (3.6), the pandas version is 0.22.0.</... | <h1>TL;DR is in Possible Fix at the bottom</h1>
<p>A few notes, and these may or may not answer the question, but I think this is a bit better than dumping everything into comments. These assume that your environment is activated, for these examples, my environment is called <code>new36</code>. I am also on MacOS with... | python|pandas|pip|package|conda | 2 |
10,295 | 36,326,332 | How to include a link in CheckboxSelectMultiple label | <p>I am using CheckboxSelectMultiple as in the following SO link:
<a href="https://stackoverflow.com/questions/5747188/django-form-multiple-choice">Django form multiple choice</a></p>
<p>But I would like to add a link to one of the choice label. For example:</p>
<pre><code>[checkbox] Option 1
[checkbox] Option 2 (lin... | <p>You can mark you choices as safe, that'll do the trick:</p>
<pre><code>from django.utils.safestring import mark_safe
CHOICES = (('a', 'Option 1'), ('b', mark_safe('Option 2 <a href="#">link</a>')))
</code></pre> | python|django|django-crispy-forms | 2 |
10,296 | 13,425,942 | django - when is .objects.get() evaluated? | <p>Suppose i have : </p>
<pre><code>class Library(models.Model):
name = models.CharField(max_length = 100)
class Books(models.Model):
library = models.ForeignKey(Library)
book = models.CharField(max_length = 100)
</code></pre>
<p>I want to create a new <code>Books</code>, we know we can fill the library ... | <p>Yes, <code>.get()</code> is immediately evaluated. Using IDs will avoid the database query, certainly.</p>
<p><code>get</code> isn't lazy since it does not return a QuerySet - it returns a single instance of the model. QuerySets come from stuff like <code>.filter()</code>, so for example <code>Library.objects.filte... | python|django | 14 |
10,297 | 13,444,534 | Python + Django on Android | <p>I am a Django developer and wanted to know if anyone has any idea of the possibilities of installing and developing on Django using an Android tablet such as the nexus 7. This seems like a reasonably powerful device, can be hooked up with a bluetooth keyboard, and has linux at the core of the OS.</p>
<p>So - is it ... | <p>Yeah! its posible!, but you need install termux terminal on Android and later open the termux terminal and write:</p>
<pre><code>apt-update
apt-install python
pip install django
django-admin startproject demo
cd demo
python manage.py runserver 0.0.0.0:8000
</code></pre>
<p>and its all, open localhost:8000 on your ... | android|python|django | 14 |
10,298 | 16,600,397 | 2D list to numpy array, and fill remaining values of shorter sublists with -1 | <p>I have a 2-D list of sublists of different lengths, I need to covert the list to a numpy array such that all the remaining values of shorter sublists are filled with -1, and I am looking for an efficient way to do this. </p>
<p>For example I have 2-D list x:</p>
<pre><code>x = [
[0,2,3],
[],
[4],
[... | <p>Some speed improvements to your original solution:</p>
<pre><code>n_rows = len(x)
n_cols = max(map(len, x))
new_array = np.empty((n_rows, n_cols))
new_array.fill(-1)
for i, row in enumerate(x):
for j, ele in enumerate(row):
new_array[i, j] = ele
</code></pre>
<p>Timings:</p>
<pre><code>import numpy a... | python|numpy | 3 |
10,299 | 43,546,372 | Matrix (scipy sparse) - Matrix (dense; numpy array) multiplication efficiency | <p>I am a researcher working on geophysical inversion. Which can requires solving linear system: <strong>Au = rhs</strong>. Here <strong>A</strong> is often sparse matrix, but rhs and u can are either dense matrix or vector. To proceed gradient-based inversion, we need sensitivity computation, and it requires a number ... | <p>If you look at the <a href="https://github.com/scipy/scipy/blob/233c0ce63910f4eba6c31d95fa2a42ea0ac86e5b/scipy/sparse/sparsetools/csr.h#L1114" rel="nofollow noreferrer">source code</a>, you can see that <code>csr_matvec</code> (which implements matrix-vector multiplication) is implemented as a straightforward sum lo... | python|numpy|scipy | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.