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 |
|---|---|---|---|---|---|---|
2,300 | 55,073,163 | English dictionary library in Python3 | <p>I need a library in Python 3 to define terms (vocabulary words), building a English dictionary. Input a term and the output will be the definition of this term.</p> | <p>Have you tried PyDictionary?</p>
<pre><code>from PyDictionary import PyDictionary
dictionary=PyDictionary("dog","cat","tree")
print(dictionary.printMeanings()) #This prints the definitions
</code></pre>
<p><a href="https://pypi.org/project/PyDictionary/" rel="nofollow noreferrer">https://pypi.org/project/PyDictio... | python|python-3.x|dictionary|libraries | 3 |
2,301 | 33,081,792 | Error message when installing scipy with pip install | <p>I am attempting to use pip install to install the scipy library through the command prompt.</p>
<p>When I type:</p>
<pre><code>pip install scipy
</code></pre>
<p>I get a wall of white text, ending with a section of red text, shown below.</p>
<pre><code>Command "C:\Python27\python.exe -c "import setuptools, token... | <p>It seems that a fortran compiler may be needed to install scipy through pip - I used the .exe installer from sourceforge and it went through fine.</p>
<p><a href="http://sourceforge.net/projects/scipy/files/scipy/0.11.0/" rel="nofollow">http://sourceforge.net/projects/scipy/files/scipy/0.11.0/</a></p> | python|scipy|pip | 1 |
2,302 | 73,672,921 | using pandas dataframes fill rows based on condition if both values are same in two dataframes | <p>am having two dataframes , first dataframe has 3 columns user_id, value, year_month columns
second dataframe has 4 columns sep_month,01,02,03 .</p>
<p>extract & create month from year_month column, now with month column need to create & fill rows from other dataframe based on condition if sep_month & mon... | <p>You can first split the date_month field and do join</p>
<pre><code>df_1[['year','month']] = df_1['date_month'].str.split('-',expand=True)
result = pandas.df_1.merge(df_1,df_2, on='month', how='left')
</code></pre> | python|python-3.x|pandas|dataframe | 0 |
2,303 | 73,786,727 | Creating Memory game (flipping tiles game) | <p>I am having trouble with coordinates and flipping the cards separately. This is my first time handling with coordinates in python.</p>
<p>When trying to flip the cards separately, the code registers the rows of cards as lists. I did use a list of lists to display the cards.</p>
<p>The code is shown below.</p>
<pre... | <p>Your code needs to be rewritten for clarity</p>
<p>Here's a template you can use, then you just need to implement each function</p>
<p>Test each function with test cases to ensure it works properly, then move to the next one</p>
<pre><code>def main():
# create your deck
cards = initialize_cards()
# iter... | python|memory | 0 |
2,304 | 12,931,338 | Sphinx code validation for Django projects | <p>I have a Django project with a couple of apps - all of them with 100% coverage unit tests. And now I started documenting the whole thing in a new directory using ReST and Sphinx. I create the html files using the normal approach: <code>make html</code>.</p>
<p>Since there are a couple of code snippets in these ReST... | <p>Turned out that I had some python paths wrong. Everything works as expected - as noted by bmu in his comment. (I'm writing this answer so I can close the question in a normal way)</p> | django|testing|python-sphinx | 1 |
2,305 | 21,774,103 | Regex pattern to match two datetime formats | <p>I am doing a directory listening and need to get all directory names that follow the pattern: <code>Feb14-2014</code> and <code>14022014-sometext</code>. The directory names must not contain dots, so I dont want to match <code>14022014-sometext.more</code>. Like you can see I want to match just the directories that ... | <p>That's quite easy.
The best one I can make is:</p>
<pre><code>((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\d\d-\d\d\d\d)|(\d\d\d\d\d\d\d\d-\w+)
</code></pre>
<p>The first part <code>((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\d\d-\d\d\d\d)</code> matches the first kind of dates and the second part <co... | python|regex | 0 |
2,306 | 21,607,896 | How can I download my Google API key as PEM file? | <p>I'm trying to do a simple python script that pulls data from Google BigQuery. I've found many posts and google documents on Bigquery, but I've yet to have any success. My current problem is that I need to read my API key from a PEM file, but I can't find any way to download my API key from the google dev console. ... | <p>You have to create a new client Id with a type of "service account" this will download a new p12 file.</p>
<p><img src="https://i.stack.imgur.com/Y5rEU.png" alt="enter image description here"></p> | python-2.7|google-api|google-api-python-client | 2 |
2,307 | 41,003,876 | Index out of range error when comparing values | <pre><code>a=[8,24,3,20,1,17]
r=[]
for i in a:
for j in a:
s=a[i]-a[j]
r.append(s)
print r
</code></pre>
<p>When I run this program
Why the index out of range error for this question?</p> | <p>Use <code>s = i - j</code> instead of <code>s = a[i] - a[j]</code>:</p>
<pre><code>a=[8,24,3,20,1,17]
r=[]
for i in a:
for j in a:
s = i - j
r.append(s)
print r
</code></pre>
<p>Output:</p>
<pre><code>[0, -16, 5, -12, 7, -9, 16, 0, 21, 4, 23, 7, -5, -21, 0, -17, 2, -14, 12, -4, 17, 0, 19, 3, -... | python | 2 |
2,308 | 30,973,060 | trying to understand LSH through the sample python code | <p>the concise python code i study for is <a href="https://gist.github.com/greeness/94a3d425009be0f94751" rel="nofollow noreferrer">here</a></p>
<p><strong>Question A @ line 8</strong> </p>
<p>i do not really understand the syntax meaning for "<em>res = res << 1</em>" for the purpose of "get_signature"</p>
<p>... | <p>a. It's a left shift: <a href="https://docs.python.org/2/reference/expressions.html#shifting-operations" rel="nofollow">https://docs.python.org/2/reference/expressions.html#shifting-operations</a> It shifts the bits one to the left.</p>
<p>b. Note that <code>^</code> is not the "to the power of" but "bitwise XOR" i... | python|similarity|locality-sensitive-hash | 1 |
2,309 | 29,148,355 | How to assess Random Forests classifier performance? | <p>I recently started using a random forest implementation in Python using the scikit learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html" rel="nofollow">sklearn.ensemble.RandomForestClassifier</a>. There is a sample script that I found on <a href="https://www.k... | <p>After training, if you have test data and labels, you could check accuracy and generate an ROC plot/ AUC score via: </p>
<pre><code>from sklearn.metrics import classification_report
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
# overall accuracy
acc = clf.score(X_test,Y_test)
# get r... | python|machine-learning|scikit-learn|random-forest | 3 |
2,310 | 8,458,737 | Python lxml, matching attributes | <p>I'm having some troubles wrapping my head around lxml. I have some html I want to parse, and I managed to do it, but it doesn't feel like the best way to do it.</p>
<p>I want to extract the value of the value attribute, but only if the value of name is "myInput"</p>
<pre><code><input name="myInput" value="This ... | <p>You could do it with an XPath:</p>
<pre><code>import lxml.html as LH
content='<input name="myInput" value="This is what i want"/>'
doc=LH.fromstring(content)
for val in doc.xpath("//input[@name='myInput']/@value"):
print(val)
</code></pre>
<p>yields</p>
<pre><code>This is what i want
</code></pre>
<p... | python|lxml | 3 |
2,311 | 8,845,435 | using base layout templates in chameleon | <p>In the pyramid docs there is a nice tutorial on UX stuff here:</p>
<p><a href="http://docs.pylonsproject.org/projects/pyramid_tutorials/en/latest/humans/creatingux/step07/index.html" rel="nofollow">http://docs.pylonsproject.org/projects/pyramid_tutorials/en/latest/humans/creatingux/step07/index.html</a></p>
<p>One... | <p>The indirect way (via view) gives you more flexibility. The benefits are not so obvious in a small project, but this approach surely pays off in a larger one. The "load:" is harcoding your main_template (in Zope/Plone-speak) to be here. With the view, it can come from anywhere and changed independently of your templ... | python|pyramid|chameleon|template-tal | 5 |
2,312 | 8,799,440 | To send threekeys using send_keys() in selenium python webdriver | <p>I am trying to type a float number into a textbox with default value 0.00.But it tries to get appended instead of overwriting it.I tried with .clear() and then send_keys('123.00') but still it gets appended.
Then i tried with send_keys(Keys.CONTROL+'a','123.00').It updates 0.00 only.</p>
<p>Any help is really app... | <p>I've had good results with:</p>
<pre><code>from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.CONTROL, 'a')
element.send_keys('123.00')
</code></pre>
<p>If that doesn't work it may have something to do with the code in the web page.</p> | python|selenium|webdriver | 17 |
2,313 | 52,281,671 | How do I created nested JSON object with Python? | <p>I have the following code:</p>
<pre><code>data = {}
data['agentid'] = 'john'
data['eventType'] = 'view'
json_data = json.dumps(data)
</code></pre>
<p>print json_date = {"eventType":"view,"agentid":"john"}</p>
<p>I would like to create a nested JSON object- for example::</p>
<pre><code>{
"agent": { "agentid",... | <p>You could nest the dictionaries as follows:</p>
<pre><code>jsondata = {}
agent={}
content={}
agent['agentid'] = 'john'
content['eventType'] = 'view'
content['othervar'] = "new"
jsondata['agent'] = agent
jsondata['content'] = content
print(json.dumps(jsondata))
</code></pre>
<p>Output:</p>
<blockquote>
<p>print... | python|json|python-2.7|flask | 24 |
2,314 | 51,848,383 | How to access a pickled model file saved in desktop to Jupiter notebook? | <p>I have a pickled model file on my desktop on Mac. I want to load it to my Jupyter notebook. However, when I try this code:</p>
<pre><code>import pickle
file_1 = open('RFonevsrest2_model.sav', 'r')
loaded_model = pickle.load(file_1)
</code></pre>
<p>I get an error saying there is No such file or directory. I do not... | <p>Specifying the path where the model resides and then using Joblib to access it does the trick:</p>
<p><code>RFmodel=open("/Users/sayontimondal/Desktop/RFonevsrest2_model.sav")
loaded_model = joblib.load(RFmodel)</code></p> | python|upickle | 0 |
2,315 | 59,721,959 | Pandas can't find columns, ValueError | <pre><code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
symbols = ["AAPL", "GLD", "TSLA", "GBL", "GOOGL"]
def compare_security(symbols):
start_date = "01-01-2019"
end_date = "01-12-2020"
dates = pd.date_range(start_date, end_date)
df1 = pd.DataFrame(index=dates)
df_SPY =... | <p>You're hitting the API limit with a standard key. The standard key is allowed 5 API calls / minute and 500 / day, that's why it works sometimes. </p>
<p>You can see that if you paste your URL into your browser and refresh it 5 - 10 times in 60 seconds you'll manually hit the limit. </p>
<p>You can either:</p>
<ol... | python|pandas|alpha-vantage | 0 |
2,316 | 18,984,373 | Compare lists, the order of content within a given column is unimportant | <p>I want to compare lists, while the below code does this it doesn't exactly do what I want to achieve.</p>
<p>Currently it will output:</p>
<pre><code>Lines only found in TEST_1:
4 6034 L LAL,LALLAL
5 4231 N AD
Lines only found in TEST_2:
4 6034 L LALLAL,LAL
5 4231 N PL
6 5231 T ... | <p>Given</p>
<pre><code>TEST_1 = [['1', '1231', 'L', 'LA'],['1', '1234', 'L', 'T'],
['2', '1434', 'A', 'C'],['3', '1634', 'L', 'T'],
['4', '6034', 'L', 'LAL,LALLAL'],['5', '4231', 'N', 'AD']]
</code></pre>
<p>you want them to be sets so you can do set operations (<code>{1, 2, 3, 4} - {3, 4, 5, 6} == {1, 2}</c... | python|python-2.7 | 1 |
2,317 | 19,278,661 | Python 2: global variable being changed in a function isn't updating to the new value | <p>Sorry if the title is confusing. And if I'm using the wrong terms. I just started coding last week. </p>
<p>I'm writing a dice roll function for the boss battle of a text adventure game and while I can get the the dice function to use the original global variable outside the function, subtract a number and report i... | <p>You never returned <code>whohealth</code> back; Python passes objects by reference, but you are rebinding the reference in the function:</p>
<pre><code>whohealth = whohealth - 1
</code></pre>
<p>That assigns a new value only to the local name <code>whohealth</code>; the original reference is not updated.</p>
<p>T... | python-2.7 | 0 |
2,318 | 68,917,327 | how to melt on multiple level in pandas | <p>I have this excel data:</p>
<pre><code> x1 x2 x3
id a b a b a b
foo 1 2 3 4 2 4
</code></pre>
<p>Column x1, x2, and x3 are made for both a and b and there are possibility where the number of x will keep increasing, so before going to the database I decided ... | <p>If there is <code>MultiIndex</code> in columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unstack</code></a>:</p>
<pre><code>print (df.columns)
MultiIndex([('x1', 'a'),
('x1', 'b'),
('x2', 'a'... | python|pandas | 2 |
2,319 | 69,192,905 | Seaborn fails to plot heatmap for a particular feature (titanic dataset) | <p>I am working with some neural networks and I am struggling to plot a correlation heatmap for the titanic dataset using seaborn. To be concise: it seems that there is a problem with the 'n_siblings_spouses' features during the plotting. I don't know if the problem is due to the feature itself (spacing, maybe?) or if ... | <p>To solve this problem, I came across <a href="https://learnsharewithdp.wordpress.com/2020/05/08/latex-matplotlib-google-colab/" rel="nofollow noreferrer">this information</a> that Colab needs a Tex-related module. There was also an excellent answer to <a href="https://stackoverflow.com/questions/55746749/latex-equat... | tensorflow|matplotlib|seaborn | 0 |
2,320 | 67,372,387 | Can classmethod/staticmethod access attributes of initial caller? | <p>I am learning and try to write python api client for some third-party API
For simplicity:<br />
I have 2 classes: Session, EndpointGroup:</p>
<pre class="lang-py prettyprint-override"><code>class Session:
def __init__(self, token=None):
self.token = token
self.group1 = EndpointGroup
class Endpoi... | <pre><code>class Session:
def __init__(self, token=None):
self.token = token
self.group1 = EndpointGroup
def __getattribute__(self, item):
attribute = super(Session, self).__getattribute__(item)
if isinstance(attribute, type(EndpointGroup)):
return ProxyEndpointGroup... | python|oop|async-await | 1 |
2,321 | 67,299,753 | IronPython.Runtime.Exceptions.ImportException: 'No module named 'pyodbc'' | <p>I am trying to run a python script from VB.Net using IronPython. So far, I have installed Python and IronPython. I have the ExecPython method shown below. It works fine when I call a simple print/hello world type of script. This DBTest.py script is just using pyodbc and connecting to the database and executing a... | <p>It's been a while, probably you already found a solution.</p>
<p>But in general, for being able to use the 'module' you need to import clr and use the addReference function. Then you must do an import of the namespace with the python style.</p>
<p>Example:</p>
<pre><code>import clr
clr.AddReference('System')
from Sy... | python|vb.net|module|pyodbc|ironpython | 0 |
2,322 | 19,475,607 | Django API how validation message back to user | <p>I'm using TastyPie to register a new user. I would like to display any validation messages back to the user in an alert box. I have noticed that TastyPie gives me the following back: <code>responseJSON</code> and <code>responseText</code>.</p>
<pre><code>responseJSON Object { accounts/create={...}}
accounts/create... | <p>Your error seems to be on the jQuery side. The <em>error</em> key points to a function defined differently (see <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow">here</a>).</p>
<blockquote>
<p>error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the ... | jquery|python|ajax|django|json | 2 |
2,323 | 22,149,132 | Plot the search volume over time | <blockquote>
<p>Plot the search volume over time. Verify that your result looks similar to <a href="http://www.google.dk/trends/explore#q=android,%20iphone" rel="nofollow">THIS</a></p>
</blockquote>
<p>First, I should import some data and print the 2 first lines. I did that successfully, but I can't figure out how t... | <p>You can use pygame to plot the data.</p>
<p>A short example:</p>
<pre><code>import pygame,sys
pygame.init()
screen = pygame.display.set_mode((640,360),0,32)
lines = list(zip(data,data[1::]))
while True:
screen.fill((255,255,255))
for x,(start,end) in enumerate(lines):
pygame.draw.line(screen,(0,0... | python | 0 |
2,324 | 16,804,477 | Oracle Stored Procedure and PyODBC | <p>I am having some trouble with getting PyODBC to work with a proc in Oracle. </p>
<p>Below is the code and the output</p>
<p>db = pyodbc.connect('DSN=TEST;UID=cantsay;PWD=cantsay')</p>
<pre><code>print('-' * 20)
try:
c = db.cursor()
rs = c.execute("select * from v$version where banner like 'Oracle%'")
... | <p>Not 100% sure, The procedure name is Get_SC_From_Comp_Ven_Job or GET_SC_FROM_COMP_VEN_JOB?</p>
<ol>
<li>check the userspace is correct or not.</li>
<li>check the name case-sensitive, if we create procedure Get_SC_From_Comp_Ven_Job, actually it is GET_SC_FROM_COMP_VEN_JOB. but if we create procedure "Get_SC_From_Com... | python|oracle|pyodbc | 0 |
2,325 | 54,610,791 | Updating "To:" Email-Header in a while loop in python | <p>Below is a code to send multiple emails to contacts loaded from a text file.</p>
<pre><code>import time
from time import sleep
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
uname = #testmail@gmail.com
name = "KTester"
password = #pas... | <p>This behaviour is by design.</p>
<p>Reassigning to <code>msg['to']</code> doesn't overwrite the existing mail header, it adds another. To send the existing message to a new address you need to delete the 'to' header before setting it.</p>
<pre><code>del msg['to']
msg['to'] = 'spam@example.com'
</code></pre>
<p>T... | python|python-2.7|mime|multipart|smtplib | 1 |
2,326 | 71,398,610 | How to remove GPU prints in TensorFlow? | <p>I use this code to use GPU in TensorFlow:</p>
<pre><code>gpus = tf.config.list_physical_devices('GPU')
print("Num GPUs Available: ", len(gpus))
if gpus:
tf.debugging.set_log_device_placement(True)
</code></pre>
<p>but when I execute this cell:</p>
<pre><code>model=keras.Sequential([
keras.Input(( ... | <p>You just need to remove the debugging line <strong>...and remember to restart your kernel!</strong></p>
<pre><code>tf.debugging.set_log_device_placement(True)
</code></pre> | python|tensorflow | 0 |
2,327 | 71,239,644 | im getting json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) | <pre><code>import json
import re
import scrapy
import ast
class Scraper(scrapy.spiders.Spider):
name = 'scraper'
#mandatory=None
def __init__(self, page=None, config=None, *args, **kwargs):
self.page =page
self.config = json.loads(config)
print(type(self.config))
#self.mandat... | <p>This means that you are trying to convert a variable into dict that <code>loads</code> method cannot convert.</p>
<p><b>json.loads() converts a string into a dictionary.</b></p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>>>> import json
>>>
>>> my_str = '{"ke... | python|json|scrapy | 0 |
2,328 | 55,147,868 | Python Selenium not clicking <a> | <p>I am trying to get my selenium script to click a <code><a></code> link that is in a modal.
So this is the html;</p>
<pre><code><div class="modal-btns">
<a href="" id="confirm-btn" class="btn-primary-md">Get Now</a>
<a href="" id="decline-btn" class=... | <p>Try this:</p>
<pre><code>driver.execute_script("document.getElementById('confirm-btn').click()")
</code></pre> | python|python-3.x|selenium|selenium-webdriver|selenium-firefoxdriver | 1 |
2,329 | 52,674,311 | Plotly Bar Chart Based on Pandas dataframe grouped by year | <p>I have a pandas dataframe that I've tried to group by year on 'Close Date' and then plot 'ARR (USD)' on the y-axis against the year on the x-axis. </p>
<p>All seems fine after grouping:</p>
<pre><code>sumyr = brandarr.groupby(brandarr['Close Date'].dt.year,as_index=True).sum()
ARR (USD)
Close Date
2017... | <p>In your groupby function you have used <code>as_index=True</code> so <code>Close Date</code> is now an <em>index</em>. If you want to have access to an index, use pandas <code>.loc</code> or <code>.iloc</code>.
To have access to the index values directly, use:</p>
<pre><code>sumyr.index.tolist()
</code></pre>
<p>C... | pandas|plotly | 1 |
2,330 | 52,564,903 | Adding values to non zero elements in a Sparse Matrix | <p>I have a sparse matrix in which I want to increment all the values of non-zero elements by one. However, I cannot figure it out. Is there a way to do it using standard packages in python? Any help will be appreciated.</p> | <p>I cannot comment on it's performance but you can do (Scipy 1.1.0);</p>
<pre><code>>>> from scipy.sparse import csr_matrix
>>> a = csr_matrix([[0, 2, 0], [1, 0, 0]])
>>> print(a)
(0, 1) 2
(1, 0) 1
>>> a[a.nonzero()] = a[a.nonzero()] + 1
>>> print(a)
(0, 1) ... | python|machine-learning|sparse-matrix | 4 |
2,331 | 52,556,616 | Websocket message handler in Python | <p>I have successfully subscribed to a websocket and am receiving data. Like:</p>
<pre><code>Received '[0, 'hb']'
Received '[1528, 'hb']'
Received '[1528, [6613.2, 21.29175815, 6613.3, 37.02985217, 81.6, 0.0125, 6611.6, 33023.06141807, 6826.41966538, 6491]]'
Received '[1528, 'hb']'
Received '[0, 'hb']'
</code></pre>
... | <p>this may be help</p>
<pre><code>import json
import hmac
import hashlib
import time
from websocket import create_connection
key = ""
secret = ""
class Bitfinex(object):
def __init__(self, secret, key):
self.secret = secret
self.key = key
self.url = 'wss://api.bitfinex.com/ws/2'
... | python|websocket|handler | 0 |
2,332 | 52,746,589 | Is Python byte-code, interpreter independent? | <p>This is an obvious question, that I haven't been able to find a concrete answer to. </p>
<p>Is the Python Byte-Code and Python Code itself interpreter independent, </p>
<p>Meaning by this, that If I take a CPython, PyPy, Jython, IronPython, Skulpt, etc, Interpreter, and I attempt to run, the same piece of code in ... | <blockquote>
<p>If so, is there is a benchmark, or place where I can compare
performance comparison from many interpreters?</p>
</blockquote>
<p>speed.pypy.org compares pypy to cpython</p> | python|pypy|pythoninterpreter | 0 |
2,333 | 47,550,664 | How can i ignore the characters between brackets? | <p>Example:
The hardcoded input in the system:</p>
<pre><code>Welcome to work {sarah} have a great {monday}!
</code></pre>
<p>The one i get from an api call might differ by the day of the week or the name example:</p>
<pre><code>Welcome to work Roy have a great Tuesday!
</code></pre>
<p>I want to compare these 2 l... | <p><a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">Regular expressions</a> are good for matching text.</p>
<p>Convert your template into a regular expression, using a regular expression to match the <code>{}</code> tags:</p>
<pre><code>>>> import re
>>> template = 'Wel... | python|assert | 1 |
2,334 | 66,094,941 | How do I retrieve all the elements from an xml to a pandas DataFrame? PYTHON | <p>this is my fist time asking a question, thanks in advance!</p>
<p>So, I am trying to process hundreds of XML files which have a very particular format (python script, xml outputs, pandas output, and original XML below)</p>
<p>I was able to capture a specific part of the XML,by stripping the CDATA tag, which is aweso... | <p>It is only partial solution.</p>
<p><strong>EDIT:</strong></p>
<p>I added version which uses recursion to get all children, subchildren, etc.<br />
So now it seems full solution.</p>
<hr />
<p>First: <code>find('detalle')</code> search direct child <code>'detalle'</code> but not nested in other nodes - ie. in <code>... | python|xml|pandas | 1 |
2,335 | 72,612,024 | Plotly: How to display different color/line segments on a line chart for specified condition? | <p>I'm trying to plot a line chart that differentiates the line color and the line itself(i.e. using a dash or dotted lines) based on a specific condition.
The figure isn't showing the lines/change in line color but I could see the change in the color of data points on the plot when I hovered over the chart and also in... | <p>There are certainly better ways to do this, but here is one code where I separate a list into many increasing and decreasing curves and then plot them with different styles:</p>
<pre><code>import plotly.graph_objects as go
import random
xs = [i for i in range(100)]
ys = [random.randint(1,30) for i in range(100)]
#... | plotly|plotly-dash|linechart|plotly-python | 0 |
2,336 | 31,682,798 | Python pandas.read_csv split column into multiple new columns using comma to separate | <p>I've used pandas.read_csv to load in a file.</p>
<p>I've stored the file into a variable.
The first column is a series of numbers separated by a comma (,)
I want to split these numbers, and put each number to a new column. </p>
<p>I can't seem to find the write functionality for pandas.dataframe.</p>
<p>Side Not... | <p>If the CSV data looks like</p>
<pre><code>"[2014, 8, 26, 5, 30, 0.0]",0,0.25
</code></pre>
<p>then </p>
<pre><code>import pandas as pd
import json
df = pd.read_csv('data', header=None)
dates, df = df[0], df.iloc[:, 1:]
df = pd.concat([df, dates.apply(lambda x: pd.Series(json.loads(x)))], axis=1,
... | python|pandas|split | 3 |
2,337 | 38,729,099 | What does an empty parenthesis "()" in logging config dictionary mean? | <p>I am playing around with the <a href="https://github.com/exoscale/python-logstash-formatter" rel="nofollow">Python Logstash Formatter</a> and <a href="https://github.com/exoscale/python-logstash-formatter/wiki/Configuration-and-making-it-work-in-Python" rel="nofollow">in its wiki</a> it recommended setting the follo... | <p>If you check out the <a href="https://docs.python.org/3.4/library/logging.config.html#user-defined-objects" rel="nofollow">python docs for logging</a>, you'll see this:</p>
<blockquote>
<p>Objects to be configured are described by dictionaries which detail their configuration. In some places, the logging system w... | python|logging|logstash | 4 |
2,338 | 38,664,613 | How to combine 3 tuples together in Python | <p>I tried to count the character combine in the list. In my script, I can count the tuples, but I don't know how I can count the total of characters in my list.</p>
<p>This is the script I have used. </p>
<pre><code>def count(num):
character = 0
for i in num:
character += 1
return character
cou... | <p>I'd prefer James' method since it feels more idiomatic, but this is what a functional approach would look like:</p>
<pre><code>def count(num):
return sum(map(len, num))
</code></pre>
<p>If you want this to work by calling <code>count('1234', '1234', '1234')</code> instead of <code>count(('1234', '1234', '1234'... | python|python-2.7|python-3.x | 3 |
2,339 | 38,821,310 | How to parse a 'JSON string' file in Python? | <p>I am working on something that is quite similar to <a href="https://stackoverflow.com/questions/13938183/python-json-string-to-list-of-dictionaries-getting-error-when-iterating">this topic</a>.I downloaded a file which seems like to be a JSON file. But when I open it in notepad, I found that it is a very long list o... | <p>Use <code>json.load</code>:</p>
<pre><code>with open('data.json') as data_file:
data = json.load(data_file)
</code></pre>
<p>The primary difference between <code>json.load</code> and <code>json.loads</code> is that <code>json.load</code> accepts a file (or file-like object) to read and load JSON from, whereas ... | python|json|file|import|io | 2 |
2,340 | 40,507,313 | Transform a list | <p>The input:</p>
<pre><code> lst=[ ' 22774080.570 7 1762178.392 7 1346501.808 8 22774088.434 8\n',
' 20194290.688 8 -2867460.044 8 -2213132.457 9 20194298.629 9\n']
</code></pre>
<p>The desired output:</p>
<pre><code>['22774080.570 7','none','1762178.392 7','1346501.80... | <p>I will not answer your question right away because it is not how stackoverflow works but I will give you some hints.</p>
<p><strong>HINTS</strong></p>
<ul>
<li><p>First, you can iterate over each line of your first list <code>lst</code> using a <a href="https://docs.python.org/3/reference/compound_stmts.html#the-f... | python|list|indexing|split|satellite | 0 |
2,341 | 40,444,787 | Why doesn't .strip() remove whitespaces? | <p>I have a function that begins like this:</p>
<pre><code>def solve_eq(string1):
string1.strip(' ')
return string1
</code></pre>
<p>I'm inputting the string <code>'1 + 2 * 3 ** 4'</code> but the return statement is not stripping the spaces at all and I can't figure out why. I've even tried <code>.replace()</co... | <p><code>strip</code> does not remove whitespace everywhere, only at the beginning and end. Try this:</p>
<pre><code>def solve_eq(string1):
return string1.replace(' ', '')
</code></pre>
<p>This can also be achieved using regex:</p>
<pre><code>import re
a_string = re.sub(' +', '', a_string)
</code></pre> | python | 21 |
2,342 | 68,304,158 | how to get desired output in python from following output | <p>I am getting this output as pasted below .</p>
<blockquote>
<p><code>[{'accel-world-infinite-burst-2016': 'https://yts.mx/torrent/download/92E58C7C69D015DA528D8D7F22844BF49D702DFC'}, {'accel-world-infinite-burst-2016': 'https://yts.mx/torrent/download/3086E306E7CB623F377B6F99261F82CC8BB57115'}, {'accel-world-infinit... | <p>you can try this,</p>
<pre><code># input = your list of dict
otp_dict = {}
for l in input:
for key, value in l.items():
if key not in otp_dict:
otp_dict[key] = list([value])
else:
otp_dict[key].append(value)
print(otp_dict)
</code></pre>
<p>otp: <code>{'accel-world-infinite-burst-2016':[link1,... | python|dictionary|data-structures | 0 |
2,343 | 60,179,707 | I have to create a function that returns True or False if a list is sorted | <p>I have to create a function called <code>isSorted()</code> and test if a list is sorted or not in Python 3.7. Said function has to return either <code>True</code> or <code>False</code> for whatever case may occur.</p>
<p>This is my code</p>
<pre><code>def isSorted(newList):
for x in newList:
if newList... | <p>Two issues:</p>
<p>(1) You should compare each element with the previous one, not with the first element.</p>
<p>(2) You immediately return <code>True</code> if the first check succeeds in the loop. Your code doesn't even process the 9th element.</p>
<p>A fixed implementation could be:</p>
<pre><code>def isSorte... | python|python-3.x | 2 |
2,344 | 1,571,047 | Choose Python version for egg installation or install parallel versions of site-package | <p>Via <code>fink install</code> I put the following Python version on my Mac OS X computer:</p>
<ul>
<li><code>python2.3</code>,</li>
<li><code>python2.4</code>,</li>
<li><code>python2.5</code>,</li>
<li><code>python2.6</code>.</li>
</ul>
<p>Further, <code>python</code> is alias for <code>python2.6</code> on my syst... | <p><code>easy_install</code> is part of the <code>setuptools</code> package. <code>Fink</code> has separate <code>setuptools</code> packages for python 2.5 and python 2.6:</p>
<pre><code>fink install setuptools-py25 setuptools-py26
</code></pre>
<p>You can then download and install <code>networkx</code> to both vers... | python|easy-install|egg | 3 |
2,345 | 2,173,592 | How do I encode WSGI output in UTF-8? | <p>I want to send an HTML page to the web browser encoded as UTF-8. However the following example fails:</p>
<pre><code>from wsgiref.simple_server import make_server
def app(environ, start_response):
output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8')
sta... | <p>You need to return the page as a list:</p>
<pre><code>def app(environ, start_response):
output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8')
start_response('200 OK', [
('Content-Type', 'text/html; charset=utf-8'),
('Content-Length', str(l... | python|python-3.x|wsgi|wsgiref | 5 |
2,346 | 28,106,991 | Remove duplicates from subsequences of the list | <p>For part of log parser I need to filter occurrences of baud rate in the log. </p>
<p>First I get all occurrences using <code>re.findall</code>, then I'm trying to remove duplicates in subsequences in its result. Results are like <code>[10000,10000,10000,10000,0,0,0,10000,10000]</code>, the list can contain several... | <p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p>
<pre><code>>>> rates = [10000,10000,10000,10000,0,0,0,10000,10000]
>>> from itertools import groupby
>>> [e for e, g in groupby(rates)]
[10000, 0, 10000]... | python | 5 |
2,347 | 32,951,940 | Beautiful Soup: Parsing only one element | <p>I keep running into walls, but feel like I'm close here.</p>
<p>HTML block being harvested:</p>
<pre><code>div class="details">
<div class="price">
<h3>From</h3>
<strike data-round="true" data-currency="USD" data-price="148.00" title="US$148 ">€136</strike>
<span dat... | <p><code>price</code> in your case is a <code>ResultSet</code> - list of <code>div</code> tags having <code>price</code> class. Now you need to locate a <code>span</code> tag inside every result (assuming there are multiple prices you want to match):</p>
<pre><code>prices = item.find_all("div", {"class": "price"})
for... | python|html|parsing|beautifulsoup|html-parsing | 5 |
2,348 | 34,661,410 | Multiple initialisation with given input parameter | <p>I am trying to make my class to be executed a given number of times according to passed parameter. My class converts dictionary into some desired data. </p>
<p>Let me show You a quick example of what i mean exactly:</p>
<p>First class <code>A</code> just offers common methods for derivative classes.
</p>
<pre><co... | <pre><code>class C(B, E):
def do_magic(self):
for _ in range(self.iters):
A.do_magic(self.c_stuff)
</code></pre> | python|oop | 1 |
2,349 | 34,540,017 | What does clf mean in machine learning? | <p>When doing fitting, I always come across code like</p>
<pre><code>clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)
</code></pre>
<p>(from <a href="http://scikit-learn.org/stable/modules/cross_validation.html#k-fold" rel="noreferrer">http://scikit-learn.org/stable/modules/cross_validation.html#k-fold</a>)<... | <p>In the <a href="http://scikit-learn.org/stable/tutorial/basic/tutorial.html#learning-and-predicting" rel="noreferrer"><code>scikit-learn</code> tutorial</a>, it's short for classifier.:</p>
<blockquote>
<p>We call our estimator instance <code>clf</code>, as it is a classifier.</p>
</blockquote> | python|machine-learning|scikit-learn | 63 |
2,350 | 27,113,772 | Iterate through data frame to generate random number in python | <p>Starting with this dataframe I want to generate 100 random numbers using the hmean column for loc and the hstd column for scale</p>
<p>I am starting with a data frame that I change to an array. I want to iterate through the entire data frame and produce the following output.</p>
<p>My code below will only return t... | <p>Dedent <code>return list1</code> so it is not in the for-loop.
Otherwise, the function returns after only one pass through the loop.</p>
<p>Also move <code>list1 = []</code> outside the <code>for-loop</code> so <code>list1</code> does not get re-initialized with every pass through the loop:</p>
<pre><code>import ... | python|python-2.7|pandas|scipy | 1 |
2,351 | 23,273,858 | Using QT (PySide) to get user input with QInputDialog | <p>I did a small script on python to do some stuff, and I want to ask user input first. This is my current code:</p>
<pre><code>import sys
from PySide import QtGui
app = QtGui.QApplication(sys.argv)
gui = QtGui.QWidget()
text, ok = QtGui.QInputDialog.getText(gui, "question",
"""please put the thing I need... | <p>Just don't call app.exec_()</p>
<p>The problem here is that this is a toy example. In real life, usually you will show some UI and then call app.exec() to let the user interact with it.</p> | python|qt|pyside | 3 |
2,352 | 23,320,358 | Torrent tracker proxy | <p>I'm trying to implement a scipt on OpenShift, which works to bypass a very basic firewall in my college.</p>
<p>The aim is that I add the OpenShift address to the tracker list in any torrent I am running.</p>
<p>The client requests the script for peers.</p>
<p>The script accepts the peer list request and then ask... | <p>I think part of it is that your university may be blocking the connection back to your computer from OpenShift. My guess is your university blocks incoming connections on port 6969 </p>
<p>Just putting it here so you can mark it answered</p> | python|proxy|flask|openshift|bittorrent | 0 |
2,353 | 23,374,437 | Comparing Difference between Values within Python List | <p>Let's say I have a list of integers:</p>
<pre><code>list = [1,2,3,5,6,7,10,11,12]
</code></pre>
<p>And I'd like to divide the list in to three separate lists, with the split occurring between consecutive integers with a difference >=2, which would give me</p>
<pre><code>list1 = [1, 2, 3]
list2 = [5, 6, 7]
list3 =... | <p>Take a look at <a href="https://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list">this StackOverflow question</a>. The answers there show you how to divide a list into sublists of consecutive integers.</p>
<p>From the accepted answer there:</p>
<pre><code>>>> data = [ 1, 4,5,6, 1... | python|list|slice | 4 |
2,354 | 60,152 | Automate firefox with python? | <p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p> | <p>You could try <a href="http://selenium.openqa.org/" rel="noreferrer">selenium</a>.</p> | python|linux|firefox|ubuntu|automation | 5 |
2,355 | 41,871,942 | How to grouping and transform in pandas | <p>Now I have below dataframe</p>
<pre><code>A B C
1 1 1
1 2 1
1 3 2
2 4 2
2 5 2
2 6 3
</code></pre>
<p>I would like to grouping by df.A, and sum up in df.B</p>
<p>But, I would like to transform C as first of each group elements.</p>
<p>So I would like to get results below.</p>
<pre><code>A B C
1 6 1
2 15 2
</c... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-different-functions-to-dataframe-columns" rel="nofollow noreferrer"><code>agg</code></a> and pass a dict of funcs to perform on the cols of interest:</p>
<pre><code>In [115]:
df.groupby('A').agg({'B':'sum','C':'first'}).reset_ind... | python|pandas|dataframe | 3 |
2,356 | 47,267,724 | Filling a shape with color in python turtle | <p>I'm trying to fill a shape with a color but when I run it, it does not show.
Am I not supposed to use classes for this? I am not proficient with python-3 and still learning how to use classes</p>
<pre><code>import turtle
t=turtle.Turtle()
t.speed(0)
class Star(turtle.Turtle):
def __init__(self, x=0, y=0):
... | <p>Issues with your program: you create and set the speed of a turtle that you don't actually use; turtle.py already has a <code>shape()</code> method so don't override it to mean something else, pick a new name; you don't want the <code>begin_fill()</code> and <code>end_fill()</code> inside the loop but rather surroun... | python|python-3.x|turtle-graphics | 3 |
2,357 | 47,207,331 | iterate over two numpy arrays return 1d array | <p>I often have a function that returns a single value such as a maximum or integral. I then would like to iterate over another parameter. Here is a trivial example using a parabolic. I don't think its broadcasting since I only want the 1D array. In this case its maximums. A real world example is the maximum power poin... | <p>Extend one of those arrays to <code>2D</code> and then let <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> do those outer additions in a vectorized way -</p>
<pre><code>maximums = (-x**2 + parameters[:,None]).max(1).astype(param... | python|python-3.x|loops|numpy | 1 |
2,358 | 47,393,978 | Python: change something inside a string respecting length constrains | <p>I am looking for a smarter solution to do what my code does.
I have to explore a text file. There are many Materials inside this text, and I want to change some material properties by replacing these values with new ones.
This is the Material structure:</p>
<pre><code> Material,
PLASTERBOARD-1, !- Nam... | <p><strong>Temporary Solution</strong>:</p>
<pre><code> if material in line:
check = True
if check:
if '!- Conductivity {W/m-K}' in line:
line = ' '+ str(capacity).ljust(25) + '!- Conductivity {W/m-K}\n'
check= False
... | python|string|python-3.x|replace|formatting | 0 |
2,359 | 71,086,283 | Parallel processing of large dataframes | <p>I have a large Pandas DataFrame with columns a and b (kind of coordinates in floats) and column c (values), which has to be binned and summarized over a certain interval of steps in the columns a and b. The order of the result is relevant, since a and b simulate coordinates where samples have been taken with the val... | <p>This is my solution. The results are not ordered, because I don't understand which is the right sorting to apply. However, each element of the list of results is a tuple composed of: (mean, A, B) where A and B are the values you specify. A posteriori, you can sort the values based on A and B, or by mean if you need ... | python|dataframe|multiprocessing | 0 |
2,360 | 70,971,980 | "AttributeError: 'function' object has no attribute 'get'" in SQLAlchemy ORM Object contructor - Flask | <p><strong>EDIT</strong> <em>Found my error! Leaving problem description as is, but appending answer bellow.</em></p>
<p>In my registration function, I want to create a new User object.
I've defined a User Table like this:</p>
<pre><code>class User(_USERDB.Model, UserMixin):
"""
User defining Dat... | <p><strong>Answer</strong></p>
<p>The reason it fails is thanks to the <code>__dict__</code> method. Since the removal of it, everything works fine.</p>
<p>Of course this leads to the next question: <em>How to define custom dict functions for those classes</em></p>
<p>I couldn't find an answer to this but still want to... | python|sqlalchemy | 1 |
2,361 | 58,605,348 | TypeError: Can't convert 'list' object to str implicitly - Python | <p>following is a code to get the emails into the stdin, and do some filtering to extract the ticket-id from email then send it to telegram.
but when i run the code it returns the following error type.</p>
<blockquote>
<p>TypeError: Can't convert 'list' object to str implicitly</p>
</blockquote>
<p>I have made the ... | <p>Solved the issue.
By using ' '.join</p>
<pre><code>import re
import sys
import requests
def telegram_bot_sendtext(bot_message):
bot_token = 'mytoken_id_here'
bot_chatID = 'my_chatid_here'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Ma... | python|python-3.x | 0 |
2,362 | 33,650,188 | Efficient pairwise correlation for two matrices of features | <p>In Python I need to find the pairwise correlation between all features in a matrix <code>A</code> and all features in a matrix <code>B</code>. In particular, I am interesting in finding the strongest Pearson correlation that a given feature in <code>A</code> has across all features in <code>B</code>. I do not care w... | <p>Seems <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.pearsonr.html" rel="noreferrer"><code>scipy.stats.pearsonr</code></a> follows this definition of Pearson Correlation Coefficient Formula applied on column-wise pairs from <code>A</code> & <code>B</code> -</p>
<p><a href="http... | python|numpy|matrix|vectorization|correlation | 11 |
2,363 | 33,755,092 | Stanford NER with python NLTK fails with strings containing multiple "!!"s? | <p>Suppose this is my <code>filecontent</code>:</p>
<blockquote>
<p>When they are over 45 years old!! It would definitely help Michael Jordan.</p>
</blockquote>
<p>Below is my code for tagging setences.</p>
<pre><code>st = NERTagger('stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz', 'stanford-ner/st... | <p>If you follow my solution from the other question instead of using nltk you will get JSON that properly splits this text into two sentences.</p>
<p>Link to previous question: <a href="https://stackoverflow.com/questions/33748554/how-to-speed-up-ne-recognition-with-stanford-ner-with-python-nltk">how to speed up NE r... | python|nltk|stanford-nlp|named-entity-recognition | 1 |
2,364 | 67,638,278 | Sqlite Database Access : No such table (Within Django no models) | <p>I have a django & docker server running on my computer and I have created a database with code from outside this server. I am trying to access this database ('test.sqlite3') within the server.</p>
<p>I made sure the path was the correct one and that the file name was correct as well. When I open the database wit... | <p>Had a similar issue, possibly something about leaving Django Model metadata files outside of the image. I needed to synchronize the model with the DB using a run-syncdb</p>
<pre><code>RUN ["python", "manage.py", "migrate"]
RUN ["python", "manage.py", "migrate&qu... | python|sqlite | 0 |
2,365 | 30,131,581 | Trouble accessing data multiple objects in JSON with Python | <p>I am trying to parse through a web-service and retrieve certain records, however I am consistently receiving a KeyError for responses with more than one object. These records are returned in intervals, so sometimes I might receive one record and others I might receive 300. If I receive one record, the logic of my ... | <p>I solved this, this thread was a huge reference.<br>
<a href="https://stackoverflow.com/questions/16548917/decoding-nested-json-with-multiple-for-loops">Decoding nested JSON with multiple 'for' loops</a></p>
<p><code>for sr in ElectronicType:
for illegaldump in ElectronicType['La311ElectronicWas... | python|json | 0 |
2,366 | 30,007,571 | How to return a value from tuple | <p>Okay, so say I have a tuple like this</p>
<pre><code>values = ('1', 'cat', '2', 'bat', '3', 'rat', '4', 'hat', '5', 'sat')
</code></pre>
<p>What loop function would I have to write to ask for a user input for the integer and have it return the word. ie. user inputs 1 and it returns cat. or user inputs 123 and it r... | <p>As you say, this is much better done via dictionary. But since you insist: you can look up the index for the number in the tuple, and then print the element at the next index:</p>
<pre><code>for char in message:
print values[values.index(char)+1],
</code></pre>
<p>With input <code>'123'</code>, will print:</p>... | python|list|for-loop|while-loop|tuples | 0 |
2,367 | 61,451,168 | Text Detection of Labels using PyTesseract | <p>A label detection tool that automatically identifies and alphabetically sorts the images based on equipment number (19-V1083AI). I used the pytesseract library to convert the image to a string after the contours of the equipment label were identified. Although the code runs correctly, it never outputs the equipment ... | <p>I found using a particular configuration option for PyTesseract will find your text -- and some noise. Here are the configuration options explained: <a href="https://stackoverflow.com/a/44632770/42346">https://stackoverflow.com/a/44632770/42346</a> </p>
<p>For this task I chose: "Sparse text. Find as much text as p... | python|opencv|image-processing|python-tesseract|feature-detection | 0 |
2,368 | 27,764,845 | How do I package and add my Python app to my launchpad repository? | <p>I have a launchpad account and an activated ppa but I have no idea how to package my app and upload. I write programs with Python using Tkinter. May someone explain ?</p> | <p>You'll need to package your project into a .deb. Here's a good tutorial:</p>
<p><a href="https://wiki.debian.org/Python/Packaging" rel="nofollow">https://wiki.debian.org/Python/Packaging</a></p>
<p>And here is an example packaged app which has TKinter as a dependency:</p>
<p><a href="http://packages.ubuntu.com/tr... | python|ubuntu|package|launchpad | 3 |
2,369 | 65,631,100 | How to sort the top scores from an external text file with the names of the people who achieved those scores still linked? Python | <p>I have managed to write the scores and names of anybody who wins a simple dice game I created to an external text document. How would I sort the top scores from this document and display them on the console alongside the name that achieved that score?</p>
<p>Code used to write score and name to the text document:</... | <p>First, the write operation should be cleaner:</p>
<pre><code>with open('winners.txt', 'w') as f:
for p1_username, p1_score in [('foo', 1), ('bar', 2), ('foobar', 0)]:
print(f'{p1_username}\n{p1_score}', file=f)
</code></pre>
<p>Content of <code>winners.txt</code>:</p>
<pre class="lang-none prettyprint-ov... | python | 1 |
2,370 | 37,058,976 | Trying to repeat the regex breaks the regex | <p>I have a working regex that matches ONE of the following lines:</p>
<ul>
<li>A punctuation from the following list <code>[.,!?;]</code></li>
<li>A word that is preceded by the beginning of the string or a space.</li>
</ul>
<p>Here's the regex in question <code>([.,!?;] *|(?<= |\A)[\-'’:\w]+)</code></p>
<p>What... | <p><strong>What is wrong with your approach</strong></p>
<p>The <code>([.,!?;] *|(?<= |\A)[\-'’:\w]+)</code> pattern matches a single "unit" (either a word or a single punctuation from the specified set <code>[.,!?;]</code> followed with 0+ spaces. Thus, when you fed this pattern to the <code>regex.findall</code>, ... | python|regex|python-3.5 | 1 |
2,371 | 48,856,030 | Parameters undefined using lmfit | <p>I am trying to fit a curve to the equation below with the given data. The equation is <code>Rate=k*Concentration^n</code>. I am having trouble as the <code>n</code> when fitted is <code>-6</code>, which is not possible so I am trying to set a bound at <code>min=0</code>. However, I am getting a undefined term parame... | <p><code>parameters</code> is undefined because you do not define it anywhere. You use it as <code>params = parameters()</code>, probably implying a function call, but you do not define or import that function.... Similarly, <code>par</code> is undefined because you do not define it anywhere.</p>
<p>You almost certa... | python|numpy|matplotlib|lmfit | 0 |
2,372 | 48,609,055 | splitting list, extracting an element and adding it in python | <p>I am new in python.</p>
<p>I have a list with seperator of "::" and it seems like that;</p>
<blockquote>
<p>1::Erin Burkovich (2000)::Drama<br>
2::Assassins (1995)::Thriller</p>
</blockquote>
<p>I want to split them by "::" and extract the year from name and add it into the end of the line. Each movie has it ... | <p>You're having <em>infinite loop</em>, because when you add an item, your loop needs to iterate on more items, and then you're adding another item...</p>
<p>You should create a new list with the result.</p>
<p>Also, you can extract the list in a much easier way:</p>
<pre><code>movie_year = re.findall('\d+', '(2000... | python|list|join|split|add | 1 |
2,373 | 20,321,218 | Python Logical Operation | <p>I'm pretty new to python and I'm working on a web scraping project using the Scrapy library. I'm not using the built in domain restriction because I want to check if any of the links to pages outside the domain are dead. However, I still want to treat pages within the domain differently from those outside it and am ... | <p><code>or</code> doesn't work that way. Try <code>any</code>:</p>
<pre><code>if 'domainName.com' in response.url and any(name in response.url for name in ('siteSection1', 'siteSection2', 'siteSection3')):
</code></pre>
<p>What's going on here is that <code>or</code> returns a logical <code>or</code> of its two argu... | python|operators|logic|scrapy | 6 |
2,374 | 4,323,908 | Set timezone to EST in Google App Engine (Python) | <p>Can anyone advise how I change the timezone for my google app engine application? It's running python, I need to set the timezone so all datetime.now() etc work on EST timezone instead of the default?</p>
<p>Thanks!</p> | <p>Have a look at <a href="http://timezones.appspot.com/" rel="nofollow noreferrer">http://timezones.appspot.com/</a> </p>
<p>You can not make <code>datetime.now()</code> to use your custom time zone but you can convert time as per your requirements.</p> | python|google-app-engine | 8 |
2,375 | 4,731,572 | Django counter in loop to index list | <p>I'm passing two lists to a template. Normally if I was iterating over a list I would do something like this</p>
<pre><code>{% for i in list %}
</code></pre>
<p>but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list. My thought was to loo... | <p>You can't. The simple way is to preprocess you data in a <a href="http://docs.python.org/library/functions.html#zip" rel="noreferrer">zipped list</a>, like this</p>
<p>In your view</p>
<pre><code>x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
</code></pre>
<p>Then in you template :</p>
<pre><code>{% for x, y in ... | python|django | 25 |
2,376 | 48,222,378 | SegmentNotFoundException in AWS Xray with Lambda | <p>I am trying to write a Lambda function to copy files from one s3 bucket to another integrated with AWS Xray. Below is the code for Lambda function. I am getting the error </p>
<blockquote>
<p>aws_xray_sdk.core.exceptions.exceptions.SegmentNotFoundException: cannot find the current segment/subsegment, please make ... | <p>the context management for a Lambda environment would never throw a <code>SegmentNotFoundException</code>. If there is no active segment/subsegment in thread local storage, it constructs a segment based on environment variables set in Lambda container. See <a href="https://github.com/aws/aws-xray-sdk-python/blob/mas... | python|amazon-s3|aws-lambda|aws-xray | 3 |
2,377 | 48,137,522 | Mocking python subprocess.call function and capture its system exit code | <p>Writing test cases to handle successful and failed python subprocess calls, I need to capture <code>subprocess.call</code> returning code.</p>
<p>Using python <code>unittest.mock module</code>, is it possible to patch the <code>subprocess.call</code> function and capture its real system exit code?</p>
<p>Consider ... | <p>About <a href="https://docs.python.org/3/library/subprocess.html#subprocess.call" rel="nofollow noreferrer">subprocess.call</a>, the documentation says:</p>
<blockquote>
<p>Run the command described by <em>args</em>. Wait for command to complete, then return the <em>returncode</em> attribute.</p>
</blockquote>
<... | python|unit-testing|mocking|subprocess | 1 |
2,378 | 48,071,828 | Python matched the value on json response based on user input, and pass the value to variable | <p>please give the solution based on my code below, and also can you help me, so in order to enter the country name, user must see the country list first, i mean in first step user must input 'country' and then it gives response the 'c_list' like in the screenshot, and then user can input the country they choose, so it... | <p>Here are some snippets to give you a good start.</p>
<p>Say user response is <code>rv</code> holding country name. Check if country exists in 'c_list'.</p>
<pre><code>country_lower = rv.lower()
is_in_country_list = country_lower in map(str.lower, c_list)
</code></pre>
<p>Parse country code from JSON sample.</p>
... | python|json|python-3.x|list|request | 0 |
2,379 | 51,520,655 | Downloading gensim models behind a proxy | <p>I am trying to download gensim pretrained word2vec models behind a proxy. I receive this error.</p>
<blockquote>
<p>urllib.error.URLError: urlopen error [Errno 11004] getaddrinfo failed </p>
</blockquote>
<p>for the following code </p>
<pre><code>import gensim.downloader as api
api.info()
</code></pre>
<p>I h... | <p>You can use command line on terminal to download instead of run code:</p>
<pre><code>export https_proxy=https://username:xxxxxx@myproxy.com
python -m gensim.downloader --download text8
</code></pre> | python|python-3.x|gensim|http-proxy | 0 |
2,380 | 51,216,002 | Python equivalent for nested c++ style for loop | <p>In c++ </p>
<pre><code>for (auto i = min; i < sqrt_max; i++ ) {
for (auto j = i; i*j <= sqrt_max; j++) {
</code></pre>
<p>I am trying to do the exact same thing in python</p>
<pre><code>for i in enumerate(range(min, sqrt_max + 1)):
for j in enumerate(range(min, i * j < sqrt_max + 1)):
</code></... | <ol>
<li>Do not use <code>enumerate(..)</code> in both your loops. <code>enumerate</code> takes something that returns a pair of <code>index, element</code> for each <code>element</code> in its argument.</li>
<li>You can not use <code>j</code> the way you do because it is defined only within the for-loop body.</li>
</o... | python|python-3.x|iterator | 0 |
2,381 | 73,646,178 | how to get a uniform white balance on a set of images (timelapse) | <p>As I am realising a timelapse film, I've taken thousands of photos of a set and due to the different weather and light conditions the pictures are very differently exposed from sunshine to haze and rain.</p>
<p>I am looking for a way to generalise the white balance of all the images in order to have a timelapse as s... | <p>For a visually pleasing time lapse, there are many things you can try. I'd additionally recommend a temporal blur (motion blur) to even out local lighting changes and fast-moving objects. That also reproduces the impression of a normal video, which always has some non-zero exposure time, i.e. motion blur.</p>
<p>Thi... | python|image-processing|video-processing|timelapse | 2 |
2,382 | 64,473,359 | Setting Azure EnvironmentCredential() | <p>I am on an Azure VM with a dynamic IP adress. When I am logged in, I am able to retrieve secrets using the following python code without any issues;</p>
<pre><code>from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
credential = DefaultAzureCredential()
secret_client = ... | <blockquote>
<p>How can correct this or what am I doing wrong?</p>
</blockquote>
<p>The error means your service principal does not have the correct secret permission in your keyvault -> <code>Access policies</code>, to solve the issue, add the application(service principal) mentioned in the error message to the <co... | python-3.x|azure|python-requests|azure-active-directory|azure-keyvault | 1 |
2,383 | 70,719,407 | Concatenate columns based on certain group | <p>I have dataframe df1 ike this:</p>
<pre><code> Schema table Name temp
0 schema1 table1 col1 INT(1,2) NOT NULL
1 schema1 table1 col2 INT(3,2) NOT NULL
2 schema1 table1 col3... | <p>Use <code>groupby</code> and f-strings:</p>
<pre><code>df2 = df.groupby(['Database/Schema Name', 'entity Name'])['temp'] \
.apply(lambda x: f"create table {x.name[0]}.{x.name[1]} ({', '.join(x)})") \
.reset_index(drop=True).to_frame('ddl_statement')
</code></pre>
<p>Output:</p>
<pre><code>&... | python-3.x|pandas | 2 |
2,384 | 70,639,689 | How to use the Anaconda environment on blender? | <p>I'm having problems to use some modes like numpy and pandas on blender, apparently the blender's python do not allow us to install packages using pip; so I thought that I could resolve this issue changing its environment to the Anaconda or something like that. I looked for solutions, but all I founded worked on wind... | <p>after struggling with this several times, and coming across it right now, I figured I'd share my solution.</p>
<p>long story short: just install things into the default blender environment or install <code>bpy</code> into an anaconda environment</p>
<p>On linux you may be able to follow Failxxx's answer, or using <c... | python|linux|anaconda|blender|environment | 0 |
2,385 | 69,875,131 | Check for password before accessing content in django | <p>I am trying to build a functionality where users have to enter the passcode to access the site.</p>
<p>If you go to this site it will ask for a password (123) before showing you the content:
<a href="https://www.protectedtext.com/djangoproj" rel="nofollow noreferrer">https://www.protectedtext.com/djangoproj</a></p>
... | <p>If I were you (and didn't want to use <a href="https://www.django-rest-framework.org/" rel="nofollow noreferrer">DRF</a>), I would make something like this:</p>
<pre><code>def check_password(*args, **kwargs): # decorator function for checking password
def wrapper(func):
if kwargs.get('password', None) ==... | python|django|django-views|django-templates | 1 |
2,386 | 73,145,220 | Update and replace values in columns based on conditions in Python | <p>I wish to update and replace values based on the dates within my dataframe, while removing data in other specific columns.</p>
<p><strong>Data</strong></p>
<pre><code>id date location status value1 value2
CC 1/1/2022 ny new 12 1
CC 4/1/2022 ny new 1 1
CC 7/... | <p>Unfortunately, snapping a cell out of existence does not seem to work with Pandas. Similarly, Pandas expects a value for each cell of every column when setting up a dataframe.</p>
<p>Therefore, <code>nan</code> (not a number) seems to be the exact placeholder appropriate for your case. In turn, consider, importing <... | python|pandas|numpy | 2 |
2,387 | 55,599,738 | Can you import Python libraries with PL/Python in PostgreSQL? | <p>I was wondering if it was possible to use Python libraries inside PL/Python. </p>
<p>What I want to do is remove one node in our setup. Right now we have a sensor publishing data to RabbitMQ using Mosquitto and MQTT.</p>
<p>On the other side, we have PostgreSQL and we want to build a database. I know that we need ... | <p>Sure, you can import any module into PL/Python. <a href="https://www.postgresql.org/docs/11/plpython.html" rel="nofollow noreferrer">The documentation</a> states:</p>
<blockquote>
<p>PL/Python is only available as an “untrusted” language, meaning it does not offer any way of restricting what users can do in it an... | python|postgresql|rabbitmq|mqtt|plpython | 1 |
2,388 | 55,604,438 | Python/Pandas: How to Merge Data Frames and Reshape to Long Form? | <p>I have data in dataframes of the kind (names of columns and values are dummies):</p>
<pre><code>frame1 =
AA BB
Date_Time
2001 1 5
2002 2 6
2017 3 7
2018 4 8
frame2 =
AA BB
Date_Time ... | <p>Well, <a href="https://stackoverflow.com/a/55604520/4518857">Ravishankar</a> pointed me in the right direction. With some searching I found (almost) how to do it, using <code>concat</code> with group keys and double stacking:</p>
<pre><code>foo = pds.concat(dict(f1 = frame1, f2 = frame2), axis=1)
foo.stack().stack... | python|dataframe|seaborn | 3 |
2,389 | 49,989,794 | Find snappy compressed files | <p>given an AWS S3 bucket with a lot of files in it, is there a way that I can filter out only the snappy compressed files among all of these?</p> | <p>Do they end with <code>.sz</code>? If they aren't marked in the filename, then one will have to inspect the start of each file, and check if they start with the <a href="https://github.com/google/snappy/blob/master/framing_format.txt" rel="nofollow noreferrer">stream identifier</a>: 0xff 0x06 0x00 0x00 0x73 0x4e 0x6... | python|amazon-web-services | 1 |
2,390 | 65,046,259 | Python gnupg "Type Error: a bytes-like object is required, not 'str'" | <p>I am just making a simple sign in agent that creates an account and locks it using the gnupg module. Unfortunately, I get this error <code>TypeError: a bytes-like object is required, not 'str</code>. I have tried all sorts of different ways to convert my password into bytes but nothing seems to work.</p>
<p>Here is ... | <p>Did you try with any of this??:</p>
<pre><code>pass_in_bytes = bytes(self.password, 'utf-8')
or
pass_in_bytes = self.password.encode('utf-8')
or
pass_in_bytes = str.encode(self.password)
</code></pre>
<p>Always ensure if it's byte representation. I'm not sure if the "key" param or the "passphrase"... | python | 1 |
2,391 | 56,856,169 | QMessageBox add custom button and keep open | <p>I want to add a custom button to QMessagebox that opens up a matplotlib window, along with an Ok button for user to click when they want to close it</p>
<p>I currently have it somewhat working, but I want the two buttons to do separate things and not open the window.</p>
<p>I know I can just create a dialog window... | <p>A bit hacky IMO, but after you add the <code>View Graphs</code> button you could disconnect its <code>clicked</code> signal and reconnect it to your slot of choice, e.g.</p>
<pre><code>import sys
from PyQt5 import QtCore, QtWidgets
def show_graph():
print('Show Graph')
def main():
app = QtWidgets.QApplica... | python|python-3.x|pyqt|pyqt5|qmessagebox | 3 |
2,392 | 56,749,332 | Combine distinct list of dict with ansible | <p>I have two list in ansible:</p>
<pre><code>toto:
- name: titi
- name: tata
titi:
- name: titi
ack: true
</code></pre>
<p>Is it possible to combine these two lists by the name key to get the following:</p>
<pre><code>new_list:
- name: titi
ack: true
- name: tata
</code></pre>
<p>I found the way... | <p>Q: <code>Is it possible to combine these two lists by the name key?</code></p>
<p>A: Yes. It is possible with the filter <a href="http://jinja.pocoo.org/docs/dev/templates/#selectattr" rel="nofollow noreferrer">selectattr</a>. The tasks below</p>
<pre><code>- set_fact:
new_list: "{{ new_list|default([]) +
... | python|ansible | 1 |
2,393 | 18,163,455 | program that will send a magic packet to a certian ip | <p>I need to code a C, C++, .bat, or Python program. It should detect if there is a person trying to connect to a certain IP address(192.168.1.149) through a certain port(25570) from outside the router/ fire wall. The program will then send a magic packet to an IP address (192.168.1.149). The magic packet will then wak... | <p>Here's some Python code I use on one of my network machines to wake up another. Not sure where I got it originally, but it works great. Hopefully you can adapt it for your purposes.</p>
<pre><code>#!/usr/bin/env python
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, ... | c++|python|c|router | 0 |
2,394 | 60,813,729 | How to assign values from a DataFrame using np.where | <p>I am trying to use np.where using 2 DataFrames, but I getting a error saying that there's a problem with the column.</p>
<p>Following my code:</p>
<pre><code>sum_d = source.groupby('Country')['Deaths'].sum()
sum_c = source.groupby('Country')['Confirmed'].sum()
Deaths = pd.DataFrame(sum_d)
Confirmed = pd.Data... | <p>If there are unique countries:</p>
<pre><code>source['Mortality Rate Country'] = source['Deaths']/source['Confirmed']
</code></pre>
<p>If there are duplicated countries:</p>
<p>Your code should be simplify by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.... | python|pandas|numpy | 1 |
2,395 | 63,143,020 | Do add_roles and remove_roles "hit" the discord service if they wouldn't result in a change? | <p>Question about <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.add_roles" rel="nofollow noreferrer"><code>Member.add_roles</code></a> and <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.remove_roles" rel="nofollow noreferrer"><code>Member.remove_roles</code></a... | <p>Yes. The underlying implementation is actually to create a list of the roles you should have and send that to Discord via <code>member.edit</code>. <a href="https://github.com/Rapptz/discord.py/blob/b77af199392209017e59eff366b46354fa210f64/discord/member.py#L605" rel="nofollow noreferrer">You can see the code for <... | python|roles|discord.py | 1 |
2,396 | 58,807,487 | Filter many to many set from models instance | <p>I have a product model that has tags, the tags can be in multiple languages. when I get a instance of the product, i have a <code>product.tags</code> manager.</p>
<p>I was wondering if there was a way to filter the tags connected to the product <strong>instance</strong>, that when I pass it to the <strong>serialize... | <p>No, you can't do that through the serializers.
You can do like this:</p>
<pre><code>tags_query = product.tags.filter(language=lang)
tag_serializer = TagSerializer(tags_query, many=True)
</code></pre> | python|django|python-3.x|django-models|django-rest-framework | 1 |
2,397 | 24,968,222 | Python 3 DictWriter csv BytesIO TypeError | <p>I'm using python 3 trying to generate a csv on the file.
I want to ensure that I'm writing utf8 so I'm converting values of my list of dicts into byte strings</p>
<pre><code>field_order = ['field1', 'field2', 'field3', 'field4']
stats = ... # list of dicts
output = io.BytesIO()
writer = csv.DictWriter(output, field... | <p><code>csv</code> mdoule operates on strings according to <a href="https://docs.python.org/3/library/csv.html#writer-objects" rel="noreferrer">the documentation</a>:</p>
<blockquote>
<p>Writer objects (DictWriter instances and objects returned by the
writer() function) have the following public methods. A row mu... | python|string|csv|python-3.x|encoding | 10 |
2,398 | 67,887,055 | Send Message If A Message Has A Key Word. Discord Py | <p>So I wanted the bot to reply with 'hi' every time someone mentions its name in a sentence.
I wrote this but it's not working, could someone please help :)</p>
<pre><code>@client.event
async def on_message(msg, ctx):
if 'astro' in msg.content:
await ctx.send('hi there!')
</code></pre>
<p><a href="https://... | <p><code>on_message</code> doesn't take a <code>ctx</code> argument:</p>
<pre class="lang-py prettyprint-override"><code>@client.event
async def on_message(msg):
if 'astro' in msg.content:
channel = msg.channel
await channel.send('Hi there!')
</code></pre> | python|discord|discord.py | 3 |
2,399 | 67,710,936 | How to get stacked barh-plot using column of pandas dataframe to stack the bars? | <p>I have two dataframes:</p>
<p>The first dataframe <code>df1</code>:</p>
<pre><code>Name Group
Abc A
Bcd A
Cde B
Def C
</code></pre>
<p>The second dataframe <code>df2</code>:</p>
<pre><code>Name Group
Efg A
Fgh B
Ghi C
Hij C
</code></pre>
<p><strong>First Step</strong></p>
<p>What I did was to create a new dataframe ... | <p>Create a group for each dataframe using the column <code>Group</code>, then, use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer"><code>agg</code></a> <code>count</code> to count the number of rows with the same <code>Group</code> type on each group, change t... | python|pandas|bar-chart | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.