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
5,500
73,030,173
How do I get plain text from an API?
<p>I'm sorry just asking like this, but I'm new to JSON and API-related Stuff.</p> <pre><code>@bot.command() async def insult(ctx): resp = requests.get(&quot;https://insult.mattbas.org/api/insult&quot;) if 300 &gt; resp.status_code &gt;= 200: content = resp.json() #We have a dict now. else: content =...
<p>You should call resp.content or resp.text instead of json().</p> <pre><code>@bot.command() async def insult(ctx): resp = requests.get(&quot;https://insult.mattbas.org/api/insult&quot;) if 300 &gt; resp.status_code &gt;= 200: content = resp.content #We have a dict now. else: content = f&quot;Reciev...
python|discord.py
2
5,501
49,990,453
How to create a dictionary through looping a 2D list?
<p>just wondering if there is a way to convert a 2D list into a dictionary.</p> <p>In my results list I have something like</p> <pre><code>[(15000001, datetime.datetime(2018, 2, 26, 12, 58, 10)), (15000002, datetime.datetime(2018, 2, 26, 12, 58, 11))] </code></pre> <p>And I am try to find a way to loop it to get </p...
<p>Sure, use <code>dict</code>, <code>zip</code>, and a list comprehension.</p> <pre><code>result = [ dict(zip(["StudentID", "ClassAttended"], row)) for row in inputlist] </code></pre> <p>or more directly:</p> <pre><code>result = [ {"StudentID": student, "ClassAttended": class} for (student, class) in input...
python|list
2
5,502
66,703,787
How to fix KeyError: '33'
<p>I am new to Python. A table (pressure_2) was imported into jupyter notebook, and for this table (shown below), the name of each column is a number.</p> <pre><code>Timestamp 1 2 3 4 .... 33 0.000 28.92 33.87 37.13 37.13 .... 48.50 0.083...
<p>The problem is that your column name type is not string. Convert headers' type to string by</p> <pre class="lang-py prettyprint-override"><code>df.columns = df.columns.map(str) </code></pre> <p>Then access the column with</p> <pre class="lang-py prettyprint-override"><code>pressure_2['33'] # or pressure_2.iloc[:, '3...
python|dataframe
0
5,503
64,765,206
How to save json in django database?
<p>I need to save json file from API in database (postgresql) using django. I have classic model which extends the AbstractUser with the default fields for first name, last name and etc. I made a research but can't find how to achieve saved json from API in database while using django. I will appreciate any help or gui...
<p>It's preferable to use the Jsonb field option. While JSON is a good option, JSONb is better, due to speed, and flexibility when it comes to writing and running queries as it supports jsonpath. Check out this thread</p> <p><a href="https://stackoverflow.com/questions/22654170/explanation-of-jsonb-introduced-by-postgr...
json|django|api|python-3.8|django-2.2
1
5,504
64,850,175
How to switch between difference "frames"
<p>I have been recently learning how to use <code>tkinter</code> and I wanted to switch between 2 different <code>canvas</code> (whatever term is more appropriate) using buttons. However, whenever I click between the buttons to switch frames the screen doesn't seem to clear. Any way to fix this?</p> <pre><code>#Imports...
<p>You can switch between widgets (here <code>canvas</code>, but it could be <code>frames</code>, or <code>buttons</code>, or <code>labels</code>, etc.) using the geometry manager <code>pack</code>-<code>pack_forget</code> (or <code>grid</code>-<code>grid_forget</code>)</p> <p>Maybe like this:</p> <pre><code>import tki...
python|tkinter|tkinter-canvas
0
5,505
53,262,552
Can't integrate with dblquad
<p>So I want to integrate a double integral with constants in it, like a, b, etc where the user can asign the value of this constants:</p> <p>The limits of the integral are x[0,1] and y[-1,2]</p> <pre><code>import numpy as np import scipy.integrate as integrate def g(y,x,a): return a*x*y a = int(input('Insert a...
<p>The problem here is that the value you provide in the optional argument args is a tuple. In the case of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow noreferrer">quad</a>, it is what the function expects, but for <a href="https://docs.scipy.org/doc/scipy/refer...
python|scipy|python-3.6|quad
3
5,506
53,078,499
How to do K-means clustering for multiple images in certain directory and save it to another directory? (on local)
<pre><code>import numpy as np import cv2 img = cv2.imread('home.jpg') Z = img.reshape((-1,3)) # convert to np.float32 Z = np.float32(Z) # define criteria, number of clusters(K) and apply kmeans() criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 8 ret,label,center=cv2.kmeans(Z,K,None,crite...
<p>I believe it is because you are trying to reshape a <code>PIL</code> image object instead of a <code>numpy</code> array. </p> <p>Try changing <code>img = Image.open(fullpath)</code> to <code>img = np.array(Image.open(fullpath))</code> and it should work.</p>
python|image|k-means
1
5,507
68,747,908
Automate the Script whenever a new folder/file is added in directory in Python
<p>I have multiple folders in a directory and each folder has multiple files. I have a code which checks for a specific file in each folder and does some data preprocessing and analysis if the specific file is present. A snippet of it is given below.</p> <pre><code>import pandas as pd import json import os rootdir = o...
<p>I've wrote a script which you should only run once and it will work. Please note:</p> <p>1.) This solution does not take into account which folder was created. If this information is required I can rewrite the answer.</p> <p>2.) This solution assumes folders won't be deleted from the main folder. If this isn't the c...
python-3.x|windows|automation|jupyter-notebook
1
5,508
71,490,421
How to calculate cumulative sum (reversed) of a Python DataFrame within given groups?
<p>I have a data frame (df_f) with many (n=19) columns that, if conceptually simplified looks something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Basin</th> <th>(n=17 columns)</th> <th>Chi</th> </tr> </thead> <tbody> <tr> <td>13.0</td> <td>...</td> <td>4</td> </tr> <tr> <td...
<p>Apparently you can't actually add <code>ascending=True</code> or <code>reverse=True</code> to <code>cumsum</code> (!?!?), so just reverse before and after cumsum for each group:</p> <pre><code>df['Chi'] = df.groupby('Basin')['Chi'].apply(lambda x: x[::-1].cumsum()[::-1]) </code></pre> <p>Output:</p> <pre><code>&gt;&...
python|pandas|dataframe|pandas-groupby|cumsum
1
5,509
61,726,439
Using a weekly aggregate filter in pandas
<p>So I have the following table in the pandas tracking dollar sales for vegetables per week </p> <pre><code>datetime | vegetable | sales (amount sold) 2020-01-06. carrot. 100 2020-01-13. carrot. 200 2020-01-20. carrot. 450 . . . 2020-03-23. carrot. 250 2020-01-06. onion. 40 2020-01-...
<p>try this:</p> <pre><code>import pandas as pd df = pd.DataFrame( data=[ ['2020-01-06', 'carrot', 100], ['2020-01-13', 'carrot', 200], ['2020-01-20', 'carrot', 450], ['2020-03-23', 'carrot', 250], ['2020-01-06', 'onion', 40], ['2020-01-13', 'onion', 80], ['...
python|pandas
0
5,510
61,655,419
using Selenium in Python to click on the right checkbox
<p>I am very new to using selenium but I cannot find way around a very simple task. I need to be able to click on the element that specifies bedrooms: 2. I have used I don't know how many references by xpath, by id, by name, by class but selenium just won't find the element. I also have tried to browse the internet but...
<p>Thanks a lot, after multiple and multiple trials I could get around that way:</p> <pre><code>elemt = driver.find_element_by_xpath("//*@name='bedrooms']").find_element_by_xpath("//[@value='2']") idvar = elemt.get_attribute("id") elemt2 = driver.find_element_by_xpath("//label[@for='" + idvar + "']") elemt2.click()...
python|selenium|web-scraping
0
5,511
60,450,394
Understanding target data for softmax output layer
<p>I found some example code for a MNIST hand written character classification problem. The start of the code is as follows:</p> <pre><code>import tensorflow as tf # Load in the data mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 2...
<p>I think you were searching in the wrong direction. It's not because of the softmax. Softmax function (not layer) receives n values and produces n values. It's because of the <code>sparse_categorical_crossentropy</code> loss. </p> <p>In the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/SparseC...
python|tensorflow|softmax
2
5,512
11,164,847
curl large file as POST request
<p>I have a number of ~10MB xml files on a local computer. For each file, I need to send it to a remote server for processing. The way I attempted to do this was by using <code>curl</code> to POST to a function:</p> <pre><code>curl MyIP -d @my_file.xml </code></pre> <p>Where <code>MyIP</code> is the url of the funct...
<p>Use POST</p> <pre><code>curl -X POST -d @my_file.xml http://user:pass@myhost/ </code></pre> <p>By default curl uses "GET" verb. You have to specify the HTTP verb using option <code>-X</code></p>
python|unix|curl
1
5,513
11,041,193
Unique SHA-1 digest generation
<p>In Python I'm creating 3 objects each of whom has a unique identifier.</p> <p>The way I generate this unique identifier in all these objects is the following:</p> <pre><code>class Foo(object): def __init__(self): unique_id = hashlib.sha1(str(time.time())).hexdigest() </code></pre> <p>I create these ob...
<p>Python objects already have a unique identifier, which is their <code>id</code>. This is only unique as long as the objects stay in existence, though; the <code>id</code> may be reused after an object is deleted.</p> <p>You can also use the <a href="http://docs.python.org/library/uuid.html" rel="nofollow"><code>uui...
python|sha
5
5,514
63,727,868
Zero Margin Layout with PySimpleGUI
<p>I am trying to make a layout with zero top, left and right margin in Python with PySimpleGui.</p> <p><strong>Example code</strong></p> <pre><code>import PySimpleGUI as sg layout = [[sg.Text('Text with background color', background_color='#FF0000')]] window = sg.Window('Title', layout, size=(200, 200)) </code></pre>...
<ul> <li>Text → no padding: <code>pad=(0,0)</code></li> <li>Window → no margin: <code>margins=(0,0)</code></li> </ul> <pre class="lang-py prettyprint-override"><code>layout = [[sg.Text('Text with background color', background_color='#FF0000', pad=(0,0))]] window = sg.Window('Title', layout, size=(200, 200), margins=(0,...
python|layout|margin|pysimplegui
1
5,515
55,737,348
Python code to delete headers from txt files
<p>I have one folder with thousands of .txt files. I am using a windows batch code to delete headers (line 1 to 82) from all .txt files inside that folder. The thing is this code works well for relatively small files, but now I need to use it on big files, and the code simply does not respond.</p> <p>Can someone help ...
<p>Probably overkill, but this might work:</p> <pre><code>import tempfile from io import StringIO data = StringIO() file_path = r'C:\Users\...\...' # Set the numder of lines you'd like to exclude header_end = 82 ### Read your data into a StringIO container (untested for directory read!) for i in os.listdir(file_pa...
python|batch-file
0
5,516
56,804,708
Plotting bargraph with x axis categories in ascending order
<p>How is it possible to plot the x axis categories in ascending order in Python. </p> <p>I'm plotting the Total Sales grouping by the region. The regions are Philadelphia, Los Angeles and Chicago. I want the graph plotted with the bar pertaining to Chicago coming first and followed by other regions in ascending order...
<p>The constructor for the <a href="https://seaborn.pydata.org/generated/seaborn.countplot.html" rel="nofollow noreferrer">sns.countplot</a> object has a parameter for the order of the the x axis,<br> you can enter whatever order you want in the form of an array of strings. <a href="https://i.stack.imgur.com/FJF95.png"...
python|python-3.x|matplotlib
0
5,517
66,161,546
Trying to scrape apply now and learn more urls but not able to get it using beautiful soup and python
<p>I am scraping this link : <a href="https://www.americanexpress.com/in/credit-cards/all-cards/?sourcecode=A0000FCRAA&amp;cpid=100370494&amp;dsparms=dc_pcrid_408453063287_kword_american%20express%20credit%20card_match_e&amp;gclid=Cj0KCQiApY6BBhCsARIsAOI_GjaRsrXTdkvQeJWvKzFy_9BhDeBe2L2N668733FSHTHm96wrPGxkv7YaAl6qEALw_...
<p>You can modify this to use your lists and syntax, but this gets you the links I believe you want. Note that using <code>find</code> doesn't get what is needed, but using <code>find_all</code> with <code>href=True</code> and taking the first link does.</p> <pre><code>nurl = 'https://www.americanexpress.com/in/credit...
python|web-scraping|beautifulsoup|python-requests|scrapinghub
2
5,518
66,174,862
Import Error: can't import name gcd from fractions
<p>I'm trying to import a function called gcd from a module called fractions with <code>from fractions import gcd</code>. For some reason, PyCharm throws an ImportError:</p> <pre><code> from fractions import gcd ImportError: cannot import name 'gcd' from 'fractions' </code></pre> <p>I had this working before, what ...
<p><code>fractions.gcd(a, b)</code> has been <strong>moved to <code>math.gcd(a, b)</code> in Python 3.9</strong>.</p> <p>In fact it has been deprecated in Python 3.5 already (in brackets):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">Python Version</th> <th sty...
python|python-3.x|importerror
14
5,519
72,736,760
Making abstract property in Python 3 results in AttributeError
<p>How do you make an abstract property in python?</p> <pre><code>import abc class MyClass(abc.ABC): @abc.abstractmethod @property def foo(self): pass </code></pre> <p>results in the error <code>AttributeError: attribute '__isabstractmethod__' of 'property' objects is not writable</code></p>
<p>It turns out that order matters when it comes to python decorators.</p> <pre><code>@abc.abstractmethod @property </code></pre> <p>is not the same as</p> <pre><code>@property @abc.abstractmethod </code></pre> <p>The correct way to create an abstract property is:</p> <pre><code>import abc class MyClass(abc.ABC): @...
python|python-3.x|abstract|python-decorators
0
5,520
72,567,312
modify all rows of a group except the last row in a Dataframe
<p>I have the following dataframe</p> <pre><code>data = [['object 1', 'property 1'], ['object 1','property 11'],['object 1','property 111'], ['object 2', 'property 2'], ['object 3', 'property 3'],['object 3','property 33']] df = pd.DataFrame(data, columns=['label', 'attribuutLabel']) </code></pre> <p>I want for eac...
<p>Well, that was harder than I though!</p> <p>But thank you for the exercice ;)</p> <p>Let's do this:</p> <pre><code>#check labels which are present more than one time lab_count = df.groupby('label')['attribuutLabel'].count().loc[lambda x: x&gt;1] #considering the result above, select only the labels &gt;1 and add a ...
python|dataframe|group-by
0
5,521
68,214,891
Adjust barplot x-axis to match metric instead of categorical scale
<p><strong>Context</strong></p> <p>I have a <code>pandas-DataFrame</code> containing aggregated data I want to plot as barchart:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ &quot;x_axis&quot;: np.arange(0., 1., .01) , &quot;counts&quot;: some_aggregation }) # df looks like this x_ax...
<p>You can use a <code>sns.histplot()</code>, with <code>weights</code> and explicitly setting bin boundaries nicely between the x-values:</p> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt import seaborn as sns import pandas as pd import numpy as np xs = np.arange(0., 1., .01) df...
python|matplotlib|seaborn
2
5,522
59,201,809
output from the lightgbm.cv method
<p>I am trying to use the lightbgm CV method from lightbgm for a multi classification problem</p> <pre><code>import lightgbm as lgb dftrainLGB = lgb.Dataset(data = X_train, label = y_train) params = {'objective': 'multiclass', 'num_class' : 3, 'random_state': 42} cv_results = lgb.cv( params, dftrain...
<p>cv_results will give you the best number of iteration. In R, this is cv_results$$best_iter. In the lgb.train function, you must specify this, nrounds = cv_results$best_iter. Check the names for python, hope this helps.</p>
python-3.x|lightgbm
-1
5,523
59,451,616
get_as_dataframe convert N/A as NaN want to prevent it
<p>I am using <strong>gspread_dataframe</strong> for reading google spreadsheet data. The problem that faced it converts N/A as NaN but I want to keep it as N/A</p> <pre><code> wks = self.google_spreadsheet_connection.open("test") worksheet = wks.worksheet("data") df = get_as_dataframe(worksheet, index='fal...
<p>You can use <code>df.fillna('N/A')</code>. It will change NaN values with the 'N/A'</p> <p>Another solution:</p> <p><code>na_filter=False</code></p> <pre><code>df = pd.read_excel('test.xlsx', na_filter=False) A B C 0 foo bar N/A 1 N/A bar foo 2 foo N/A bar </code></pre>
pandas|dataframe|google-sheets-api
0
5,524
72,880,226
Facing this issue: pygame.error: video system not initialized
<p>I have written this code but I am facing issues:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((800,600)) running = True while running: for event in pygame.event.get(): if event.type == pygame.quit(): running = False </code></pre>
<p>change <code>if event.type == pygame.quit():</code> to <code>if event.type == pygame.QUIT:</code></p>
python|compiler-errors|pygame|compilation|pycharm
0
5,525
72,940,259
How to join rows in pandas dataframe based on column value?
<p>I have a dataframe which looks like this:</p> <pre><code>time text 01.01.1970 abc 01.01.1970 cde 01.01.1970 fgh 01.01.1980 abc 01.01.1980 xyz </code></pre> <p>I would like to join the content in <code>text</code> based on column <code>time</code>. I want to join them separated by <code>\n</code>. How can I do this i...
<pre><code>df.groupby('time')['text'].apply(lambda x: x.str.cat(sep='\n')) </code></pre> <p>output:</p> <pre><code>time text 01.01.1970 &quot;abc\ndef&quot; 01.01.1980 &quot;ghi\njkl&quot; </code></pre>
python|pandas
2
5,526
35,512,966
Python issue outputting multiline string into single csv.writer row
<p>The below code works, but assigns each newline of a multiline string to a new row vs. the desired state of one cell. </p> <p>While researching a possible solutions I read:</p> <ul> <li>That I should try enclose the string in double quotes </li> <li>That replacing <code>newline</code> with <code>carriage return</co...
<p>Not an answer... but I want code formatting.</p> <pre><code>import csv x = ("1", "2\n3", "4") f = csv.writer(open('foo', 'w'), dialect=csv.excel, delimiter='\t') f.writerow(x) </code></pre> <p>Produces this:</p> <pre><code>$ less foo 1 "2 3" 4 </code></pre> <p>And...
python-2.7|csv
2
5,527
58,953,209
Django "before dispatch" mixin
<p>I am trying to define a mixin to set up a member and check for permissions before the view's dispatch is called but class hierarchy is "getting in the way". The behavior for a specific view would be:</p> <pre><code>class Page1View(TemplateView): # ... def dispatch(self, request, *args, **kwargs): s...
<p>You can use this, but keep in mind that the <code>TemplateView</code> or other generic views is in the right most.</p> <pre><code>class Page1View(BeforeDispatchMixin, TemplateView): # ... class BeforeDispatchMixin(object): def get_object(self): # ... return object def dispatch(self, re...
python|django|inheritance|architecture
0
5,528
58,823,728
Plot sine wave (degrees)
<p>We're supposed to plot the sine wave with the help of Matplotlib but in degrees.</p> <p>First we're supposed to get every sin(x) from 0-360 degrees, every ten degrees.</p> <p>I'm a beginner, would really appreciate the help.</p> <pre><code>def getsin(): for i in range(0,361,10): y=math.sin(math.radia...
<p>Your code is almost OK (you missed a closing parenthesis on line <code>sinvalue.append(round(y,3)</code>), but it can be perfected. </p> <p>E.g., it's usually considered bad practice updating a global variable (I mean <code>sinvalue</code>) from inside a function... I don't say that it should never be done, I say ...
python|trigonometry|degrees
2
5,529
15,691,555
gevent.Timeout not raised
<p>I have a server that does "some stuff" in a section and I have a "with gevent.Timeout(5)" around that. I have some checks going on in another greenlet and through that I noticed that one of the greenlets which did that "some stuff" was running for 45mins. I had to eventually restart the program to kill it (I know of...
<p>Whenever I've used <code>gevent.Timeout</code>, I've also used it as a context manager but with the second argument <code>False</code>. This way the context manager suppresses any exception and just leaves the chunk of code. You can follow up by checking if, say, the block set a value successfully:</p> <pre><code>r...
python|network-programming|timeout|gevent|monkeypatching
0
5,530
49,213,374
How to make this specific sql query using Flask MySQLAlchemy?
<p>I am trying to query and fetch the last row of my database using the following code:</p> <pre><code>from flask import Flask, render_template, redirect, url_for from flask_bootstrap import Bootstrap from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators i...
<p>In <code>getTemperatureData()</code> you use the <code>data</code> variable to store the query result set first:</p> <pre><code>data = temperaturelog.query.order_by(temperaturelog.TemperatureID.desc()).first() </code></pre> <p>In the next line you overwrite <code>data</code> with the temperature (which is probably...
python|sqlalchemy
3
5,531
48,969,754
Comparing dataframes in pandas
<p>I have two separate pandas dataframes (<code>df1</code> and <code>df2</code>) which have multiple columns with some common columns.</p> <p>I would like to find every row in <code>df2</code> that does not have a match in <code>df1</code>. Match between <code>df1</code> and <code>df2</code> is defined as having the s...
<p>This works:</p> <pre><code># set index (as selecting columns) df1 = df1.set_index(['A','B']) df2 = df2.set_index(['A','B']) # now .isin will work df2[~df2.index.isin(df1.index)].reset_index() A B D text 0 45 3 1 shot 1 10 2 3 miss </code></pre>
python|python-2.7|pandas|dataframe|pattern-matching
1
5,532
49,197,131
Select Range of DatetimeIndex Rows Using .loc (Pandas Python 3)
<p>Working with a pandas series with DatetimeIndex. Desired outcome is a dataframe containing all rows within the range specified within the .loc[] function. </p> <p>When I try the following code:</p> <pre><code>aapl.index = pd.to_datetime(aapl.index) print(aapl.loc[pd.Timestamp('2010-11-01'):pd.Timestamp('2010-12-3...
<p>IIUC:</p> <pre><code>import pandas_datareader as web aapl = web.get_data_yahoo('aapl') aapl.loc['2010-11-01':'2010-12-30'] </code></pre> <p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#partial-string-indexing" rel="nofollow noreferrer">partial string indexing</a> and slic...
python|python-3.x|pandas|time-series|datetimeindex
3
5,533
49,015,994
Django model outside of django
<p>I have a non django project for which i would like to use the django models for data access layer.</p> <p>Added the models lib in <code>requirements.txt</code><br> <code>django-model-utils==3.1.1</code></p> <p>And code set it up like below:</p> <pre class="lang-python prettyprint-override"><code>from django.conf ...
<p>(It's an old question, but i answer it, maybe help others.)</p> <p><strong>option 1 (recommended)</strong></p> <p>seeing comments, you mentions:</p> <blockquote> <p>In my particular case, wherein its simply a set of scripts downloading data from apis and saving in database, sqlalchemy is suiting well.</p> </blo...
python|django|django-models
1
5,534
70,978,658
Image not loading from file within same directory, Pygame, python
<p>I'm currently trying to show an image onto my pygame screen but it I keep on being told that my image is not in the directory. Maybe I can be proven wrong but I'm quite confident that the image location is in the same directory, and that something must be wrong with my code and so it's not able to fetch it. The trac...
<p>It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python script.<br /> Put t...
python|pygame
0
5,535
3,198,874
malformed start tag error - Python, BeautifulSoup, and Sipie - Ubuntu 10.04
<p>I just installed python, mplayer, beautifulsoup and sipie to run Sirius on my Ubuntu 10.04 machine. I followed some docs that seem straightforward, but am encountering some issues. I'm not that familiar with Python, so this may be out of my league.</p> <p>I was able to get everything installed, but then running s...
<p>Suppose you are using BeautifulSoup4, I found out something in the official document about this: <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="noreferrer">http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser</a></p> <blockquote> <p>If you’re using a ...
python|beautifulsoup
15
5,536
6,170,548
Using Python to measure audio "loudness"
<p>I'm looking to calculate the loudness of a piece of audio using Python — probably by extracting the peak volume of a piece of audio, or possibly using a more accurate measure (RMS?).</p> <p>What's the best way to do this? I've had a look at <a href="http://people.csail.mit.edu/hubert/pyaudio/" rel="nofollow">pyaudi...
<p>I think that the RMS would be the the most accurate measure. One thing to note is that we percieve loudness differently at different frequencies, so convert the audio to frequency space with an fft (numpy.fft should work great on only 30s of audio). Now compute a power spectral density from this. Weight the PSD by f...
python|audio|audio-analysis
4
5,537
5,894,219
Sorting a multiple river stream branch structure
<p>I have a list of numbered Stream segments. And each one lists the next down stream stream segment. The last stream segment of course has no down stream segment referenced.</p> <p>I need to order the entire river, starting from the topmost stream and progressing down stream. At junctions I need to jump to the top of ...
<p>You need to represent your segments as a graph data structure. Then, familiar graph algorithms like DFS, BFS and topological sort should do the work for you, depending on what you need exactly.</p> <p>If you could clarify your question with a simple example or a picture so it's clearly understood which sorting orde...
python|sorting|tree|stream|branch
1
5,538
66,874,904
`exec -a` does not work for scripts: is there a ways to easily change $0 in scripts?
<p>If I want to automatically &quot;wrap&quot; a program (in order to add some environment variables to it), one solution is to rename the program in something like <code>myscript-wrapped</code>, and create a new file <code>myscript</code> with the following content:</p> <pre class="lang-sh prettyprint-override"><code>...
<p>I can't answer why that's not working as expected. However, you can provide a $0 to a bash script if you use the -c option, so <code>myscript</code> can be:</p> <pre class="lang-sh prettyprint-override"><code>#/usr/bin/env bash PATH=$(dirname &quot;$0&quot;):$PATH exec bash -c &quot;. myscript-wrapped&quot; &quot;$0...
python|bash|arguments|command-line-arguments
2
5,539
63,781,556
ModuleNotFoundError: No module named 'code.victim'; 'code' is not a package
<p>I am trying to import a Python class from another file but it is not working. I've tried everything posted on relative imports but it is still not working.</p> <p>My folder hierarchy is as follows:</p> <p><a href="https://i.stack.imgur.com/k22KA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k22K...
<p>I think it's about naming conflict.</p> <p>Try to rename &quot;code&quot; to something else.</p> <p>Check: <a href="https://stackoverflow.com/a/36066463/479933">https://stackoverflow.com/a/36066463/479933</a></p>
python
1
5,540
72,337,121
My jupyter notebook doesn't warn to use the latest numpy version
<p>I am using a conda virtual env and i already upgraded numpy to 1.22. In my notebook it still uses 1.19.</p> <p><a href="https://i.stack.imgur.com/tl3FJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tl3FJ.png" alt="enter image description here" /></a></p> <p>why isn't it using 1.22?</p> <p>Also w...
<p>Are you running Jupyter from a base environment or from the new environment? If you are launching Jupyter from a different environment, you need to switch kernels to the new environment.</p> <p>There are several ways to check which kernel you are using, typically:</p> <pre><code>import sys sys.executable </code></p...
python|pip|jupyter|conda
0
5,541
65,596,336
having some trouble and confusion in setter & @property decorator, not all attributes defined in `__init__` are updated
<pre><code>class Employee: def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.annual_pay = 12*pay self.email = self.first + '.' + self.last + '@email.com' @property def fullname(self): return ('{} {}'...
<p>That is because the value of email was computed <em>and saved</em> when you ran <code>__init__()</code>. Just because you change <code>self.first</code> and <code>self.last</code> doesn't mean <code>self.email</code> will be affected, because it is not saved in terms of its relationship to those variables. It is sav...
python|decorator|setter
3
5,542
3,797,957
Python: Easily access deeply nested dict (get and set)
<p>I'm building some Python code to read and manipulate deeply nested dicts (ultimately for interacting with JSON services, however it would be great to have for other purposes) I'm looking for a way to easily read/set/update values deep within the dict, without needing a lot of code. </p> <p>@see also <a href="http...
<h1>Attribute Tree</h1> <p>The problem with your first specification is that Python can't tell in <code>__getitem__</code> if, at <code>my_obj.a.b.c.d</code>, you will next proceed farther down a nonexistent tree, in which case it needs to return an object with a <code>__getitem__</code> method so you won't get an <co...
python
34
5,543
35,067,829
how to remove header from xsl file without blowing up on pdf download
<p>I want to remove this Estimated header and the black line underneath. I've tried removing</p> <pre><code> &lt;fo:block text-align="center" padding-left="4pt" margin-left="4pt" margin-bottom="4pt" padding-bottom="4pt"&gt; &lt;xsl:attribute name="border-bottom-color"&gt;black&lt;/xsl:at...
<p>If you're showing what you removed each time, removing the entire <code>fo:block</code> has left you with an <code>fo:table-cell</code> with no content. The "marker* (%block;)+" is telling you that <code>fo:table-cell</code> is expected to have one-or-more block-level FOs (following zero-or-more <code>fo:marker</co...
python|xml|pdf|xslt|xsl-fo
2
5,544
45,252,612
How do you validate application logic using Pyramid's Colander?
<p>So far I am using colander to validate the data in my aiohttp application.</p> <p>The problem I face is that I don't know how to do "deep" validation.</p> <p>Given the following schema:</p> <pre><code>import colander class User(colander.MappingSchema): username = colander.SchemaNode(colander.String()) pa...
<p>Obviously it's a matter of taste but IMHO it's better to keep data validation separate from application logic.</p> <p>You'll also run into a few problems trying to confirm that the username is unique:</p> <ol> <li>Colander would need to have knowledge about your application eg. get access to the database connectio...
python|validation|aiohttp|colander
1
5,545
64,640,579
How can python read "percentage" from excel file?
<p>I have an excel file where some of the columns have percent value. I use pd.read_excel to read my file, but it gives me 1 instead of 100%. Is there any way python can read all percent value?</p> <p>I have referred to <a href="https://stackoverflow.com/questions/63810700/python-read-a-percentage-value-from-excel-usin...
<p>A percentage is expressed by any value over 1. So a percentage of 50 <code>(50/100) is 0.5</code>. A percentage value of 100% <code>(100/100) is 1</code>.</p> <p>To get the percentage, just take the value and multiply it by 100. Example: <code>.5 * 100 = 50</code> and <code>1.0 * 100 = 100</code>.</p>
python|pandas
0
5,546
61,529,720
How to shuffle a pandas GroupBy object?
<p>I have a pandas DataFrame that contains image names and several columns containing features, the image can contain several rows with the same image name but with different column values.</p> <p>Here's how the DataFrame might look like:</p> <pre><code> image val1 val2 val3 0 image1.png 12 14 15 ...
<p>I think you can do this without grouping, instead getting the unique group names (images) as a list, randomly selecting the train images from that list, and then indexing the dataframe.</p> <pre><code>df = pd.DataFrame.from_records( [ {"image": "image1.png", "val1": 12, "val2": 14, "val3": 15}, ...
python-3.x|pandas
1
5,547
61,200,410
replace outliers in a dataframe with the theoretical min/max
<p>I have a dataframe, and have been asked to replace the outliers in the dataframe with the theoretical min/max. However, I'm not exactly sure what that means.</p> <p>I think I have calculated the theoretical min/max--</p> <pre><code>outliers = pd.DataFrame(columns=['min', 'count below', 'max', 'count above']) for ...
<p>You're going to have to figure out what constitutes an outlier for your purposes. I'm a programmer not a statistician, but I suspect anything that falls outside the theoretical min/max fits the bill. </p> <p>As for actually replacing the outlier... you may want to check out the answer to this post. <a href="https:/...
python|pandas|dataframe|statsmodels|outliers
0
5,548
60,524,219
Failed to convert the ipynb to PDF
<p>Today when I tried to convert my ipynb file to PDF, an error occured as follows:</p> <pre><code>nbconvert failed: PDF creating failed, captured latex output: Failed to run "xelatex .\notebook.tex -quiet" command: This is XeTeX, Version 3.14159265-2.6-0.999991 (TeX Live 2019/W32TeX) (preloaded format=xelatex) restr...
<p>Export the ipynb file to HTML file. Then export HTML (on your server) to PDF. This way retains all the numerical and image outputs in your ipynb file</p>
python-3.x|jupyter-lab
3
5,549
57,974,278
Adding new row to a table copy only dropdown lists
<p>I want to add new row with 2 select dropdown columns to my existing table using jquery but I have a problem. </p> <p>When I try my code either I get empty new row or everything is copied.</p> <p>I created an example in JSfiddle. When I add a new row it copies everything from the last row. I just want it to copy th...
<pre><code> $("#addRow").click(function(){ $("#my_id").each(function(){ var tds='&lt;tr&gt;'; jQuery.each($('tr:last th', this), function(){ tds += '&lt;th&gt;' +'&lt;input type="checkbox" name="record" tittle="Delete this row"&gt;&lt;/input&gt;' + '&lt;/th&gt;'; ...
jquery|html|pandas|drop-down-menu
3
5,550
57,814,166
How to plot the correlation coefficient for every last 30 days of two dataframe columns over the past year and plot it? (pandas)
<p><a href="https://i.stack.imgur.com/hmC80.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hmC80.png" alt="enter image description here"></a>Through the following code, i get the 1 year history data for both eth and btc price, i know how to get the correlation of the two columns for the 12 months. B...
<p>You can groupby month, deriving month from your index. You can then subset your groupby to the two variables you want to correlate.</p> <pre><code>btc.groupby(btc.index.month)[['Val1','Val2']].corr() </code></pre>
python|pandas|correlation|data-analysis
0
5,551
58,102,864
How to apply a natural logarithm to a matrix and obtain zero for when the matrix entry is zero
<p>In Python I have a Matrix with some zero values, how can I apply a natural logarithm and obtain zero for when the matrix entry is zero? I am using numpy.log(matrix) to apply the natural logarithm function, but I am getting nan when the matrix entry is equal to zero, and I would like it to be zero instead</p>
<p>You can do something like this:</p> <pre class="lang-py prettyprint-override"><code>arr = numpy.nan_to_num(numpy.log(matrix)) </code></pre> <p>The behavior of nan_to_num replaces all the NaNs by zeroes.</p> <p>You can find more information here:</p> <ul> <li><a href="https://docs.scipy.org/doc/numpy-1.13.0/refer...
python|numpy|natural-logarithm
1
5,552
71,495,954
Applying the counter from collection to a column in a dataframe
<p>I have a column of strings, where each row is a list of strings. I want to count the elements of the column in its entirety and not just the rows which one gets with the value.counts() in pandas. I want to apply the Counter() from the Collections module, but that runs only on a list. My column in the DataFrame looks...
<p>IIUC, your comparison to pandas was only to explain your goal and you want to work with lists?</p> <p>You can use:</p> <pre><code>l = [['FollowFriday', 'Awesome'], ['Covid_19', 'corona', 'Notagain'], ['Awesome'], ['FollowFriday', 'Awesome'], [], ['corona', 'Notagain'], ] from collection...
python|pandas|collections|counter
0
5,553
69,366,074
celery first in first out not working using python
<p>celery task</p> <pre><code>@app.task() def single_task(delay): &quot;&quot;&quot;Run task.&quot;&quot;&quot; if delay: sleep(10) print(&quot;ran ...&quot;) return True </code></pre> <p>terminal 1</p> <pre><code>&gt;&gt;&gt; from settings.celery import single_task &gt;&gt;&gt; single_task(Tru...
<p>I am not really sure if fifo is what you are after. You can specify a fifo queue in your broker and having only one worker, which implicitly guarantees that the first task is finished before the second starts. However, first in first out is not the same as having the first task guaranteed to be finished before the s...
python|celery
0
5,554
57,717,303
Unable to find the class for price - web scraping
<p>I want to extract the price off the <a href="https://www.learningconnection.philips.com/en/catalog/product-group/clinical-informatics/cardiology-informatics" rel="nofollow noreferrer">website</a></p> <p>However, I'm having trouble locating the class type.</p> <p>on this <a href="https://www.learningconnection.phil...
<p>With bs4 4.7.1 + you can use :contains to isolate the appropriate preceeding tag then use adjacent sibling and descendant combinators to get to the target</p> <pre><code>import requests from bs4 import BeautifulSoup as bs r = requests.get('https://www.learningconnection.philips.com/en/course/pinnacle%C2%B3-advance...
python|web-scraping|beautifulsoup
3
5,555
57,520,642
Building a docker image for a flask app fails in pip
<pre><code>from alpine:latest RUN apk add --no-cache python3-dev \ &amp;&amp; pip3 install --upgrade pip WORKDIR /backend COPY . /backend RUN pip --no-cache-dir install -r requirements.txt EXPOSE 5000 ENTRYPOINT ['python3'] CMD ['app.py'] </code></pre> <p>I have a simple Dockerfile that looks like above.</p> <p...
<p>I struggled with that for a moment as well. I ended up creating my container with</p> <pre><code>FROM python:3.7-alpine RUN apk update &amp;&amp; apk add gcc libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev </code></pre> <p>Anyway, if you want to use <code>alpine:latest</code> you pro...
python|docker|pip
19
5,556
54,193,072
How to interpolate semilogx plot with cubic spline or pchip
<p>So I have been stuck on this for a while. I am wondering how to interpolate on a semilogx plot using different methods like pchip or cubic spline. So far this is the code that I have.</p> <pre><code>from scipy.interpolate import PchipInterpolator import numpy as np import matplotlib.pyplot as plt data = [[0.425, 1...
<blockquote> <p>Should I be transforming the data before interpolation?</p> </blockquote> <p>Yes, certainly! You have to make sure the samples are logarithmically spaced. Linearly spaced samples on a logarithmic axis squeeze together on the right side of the plot together and pull apart on the left side. </p> <p>Fu...
python|numpy|scipy|interpolation
1
5,557
58,304,054
How to resolve an invalid syntax error in Flask when trying to name?
<p>So I am designing an API in flask and get invalid syntax when I try this:</p> <pre><code> @summy.route('/api/summarize', methods=['POST', 'GET']) # Get Data articleUrl = request.json['articleUrl'] if not request.json or 'articleUrl' not in request.json: abort(400) html = urllib.urlopen(url).read() soup = Be...
<p>Write #Get Data part in function. Also there is a space before @summy. The code will be :</p> <pre><code>@summy.route('/api/summarize', methods=['POST', 'GET']) def api(): # Get Data articleUrl = request.json['articleUrl'] if not request.json or 'articleUrl' not in request.json: abort(400) ...
json|flask|python-requests|api-design
0
5,558
22,464,173
Maximum sum of sublist with a specific length
<p>I'm supposed to write a function which takes two numbers, the first is a given number, and the second is the length for the maximum sublist that I'm supposed to find: for example input (1234,2) the output would be 7</p> <p>this is my code so far, it just computes the sum of the entire digits:</p> <pre><code>def al...
<p>By what i get from question, this should do what you want:</p> <pre><code>def do(n, d): print sum(sorted([int(x) for x in str(n)])[-d:]) </code></pre>
python|list|max|sublist
1
5,559
14,699,762
Creating first Django project: admin webpage will not open
<p>NOTE: THE SPECIFIC QUESTION IS AT THE END BELOW. FIRST I DESCRIBE ALL THE STEPS I WENT THROUGH :-) )</p> <p>Im using Python 2.7 and Django 4.2.1 on Windows.</p> <p>I am creating a project called "mysite" which is the project used at docs.djangoproject.com.</p> <p>So far, I have done the following just like in ...
<p>Usually when the admin in Django isn't working the two main culprits are forgetting to add the following two lines to the urls.py file.</p> <pre><code>admin.autodiscover() </code></pre> <p>and</p> <pre><code>url(r'^admin/', include(admin.site.urls)) </code></pre> <p>Now you can go ahead with the tutorial and whe...
python|django
5
5,560
14,812,029
Designing URLs in URLconf
<p>while developing web app using Django, why is URLconf required? I'm trying to create one for a web app, and I can't understand how is it written. :(</p> <p>I got this URLconf example from djangoproject.com. Would anyone help me interpret how the patterns are written here? What are (\d{4}), (\d{2}) and (\d+)/ ?</p> ...
<p>Django URL patterns are actually python regular expressions. <code>\d{4}</code> means 4 digits. <code>\d+</code> means at least one (or more) digits. <a href="http://www.regular-expressions.info/quickstart.html" rel="nofollow">Here's a quick intro</a> to the subject.</p>
python|django
1
5,561
6,960,470
SWIG: 'module' object has no attribute 'Decklist'
<p>I'm having one hell of a time with SWIG, due in part to the lack of good C++ examples to learn from. I finally got my first program to compile with SWIG, but am having troubles running it. Let me just get right to the code...</p> <p>setup.py:</p> <pre><code>#!/usr/bin/env python """ setup.py file for SWIG examp...
<p>change decklist.i as following:</p> <pre><code>//decklist.i %module decklist %{ #include "decklist.hpp" %} %include "decklist.hpp" // &lt;-- *** use % in *.i *** </code></pre> <p>or you can declare your classes &amp; functions here that you want to export.</p>
c++|python|gcc|swig|python-idle
2
5,562
57,068,383
How to perform offline image augmentation using Keras?
<p>I want to perform <strong>offline image augmentation</strong> for different image classes in my dataset and save the images to one of the folders before I start creating the model.</p> <p>Using Keras <code>ImageDataGenerator - flow_from_directory()</code> which has <code>save_to_dir</code> and setting its value to ...
<p>If you want to save augmented images you needed define a model and use <code>fit/fit_generator</code>. Note that <code>datagen_set</code> is an iterator so you can use the <code>next</code> method to get values from the iterator.</p> <pre><code>for i in range(no_iter): image, label = next(datagen_set) </code></...
python|image-processing|keras|deep-learning|data-processing
0
5,563
25,518,662
Convert unicode characters to utf-8 in python
<p>Can someone tell me how to convert unicode characters to utf-8 in python ?</p> <p>For example :</p> <p><strong>Input</strong> - अ अ घ ꗄ </p> <p><strong>Output</strong> - E0A485 E0A485 E0A498 EA9784</p> <p>I tried the following method in python console :</p> <blockquote> <blockquote> <p><em>python-prompt</...
<p>Just call <code>encode()</code> on your unicode string, then <a href="https://docs.python.org/2/library/binascii.html#binascii.hexlify" rel="nofollow"><code>hexlify()</code></a> it.</p> <pre><code>s = u'\u0905 \u0905 \u0918 \ua5c4' print s अ अ घ ꗄ s_utf8 = s.encode('utf8') print s_utf8 अ अ घ ꗄ &gt;&gt;&gt; s_utf8 '...
python|unicode|utf-8
1
5,564
25,843,698
ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?
<p>I use pickle to dump a file on python 3, and I use pickle to load the file on python 2, the ValueError appears. </p> <p>So, python 2 pickle can not load the file dumped by python 3 pickle?</p> <p>If I want it? How to do?</p>
<p>You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number <code>3</code> (and uses it as default), so switch back to a value of <code>2</code> which can be read by Python 2.</p> <p>Check the <code>protocol</code>parameter in <a href="https://docs....
python|python-3.x|python-2.7|pickle|valueerror
166
5,565
25,921,287
Numpy nanmean and dataframe (possible bug?)
<p>I'm wondering if this is a bug, or possibly I don't understand how nanmean should work with a dataframe. Seems to work if I convert the dataframe to an array, but not directly on the dataframe, nor is any exception raised. Originally noticed here: <a href="https://stackoverflow.com/questions/25909115/fill-data-ga...
<p>It's definitely strange behavior. I don't have the answers, but it mostly seems that entire pandas <code>DataFrames</code> can be elements of numpy arrays, which results in strange behavior. I'm guessing this should be avoided as much as possible, and I'm not sure why <code>DataFrames</code> are valid numpy elements...
python|numpy|pandas
1
5,566
23,495,208
Selenium webdriver click through pages of a pagination and check if an element is present
<p>I am trying to click through paginated pages on a website and on each page that loads I need to check if an element that was created in a previous step is present, as the assignment of pages is dynamic I don't know before its created which page the newly created element will be displayed on, so need to check all unt...
<p>Use <a href="http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_xpath" rel="nofollow"><code>find_elements_by_xpath()</code></a>:</p> <pre><code>for page_link in driver.find_elements_by_xpath('//div[@class="pagination"]/ol/li/a'): print "page ...
python-2.7|selenium|webdriver
1
5,567
23,704,521
Python Random Playing Card Generator Game
<p><br> I'm currently attempting to create a program in Python that will allow a random card to be created using the random function, with a suit and the card number. <br> The code so far is shown below... <br></p> <p><br></p> <pre><code>import random num1 = random.randint(1,13) num2 = random.randint(1,4) cardnum1 = ...
<pre><code>import random cards = [&quot;Ace&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;, &quot;Jack&quot;, &quot;Queen&quot;, &quot;King&quot;] suits = [&quot;Diamonds&quot;, &quot;Hearts&quot;, &quot;Spades&quot;, &quo...
python
3
5,568
24,329,712
before event shutil copy2
<p>I want to use my own copy2 function when calling <code>shutil.copytree</code>. I will be using a regex on the dst to create a new dst(copy and rename). I see the function header for copy2 as <code>shutil.copy2(src, dst, *, follow_symlinks=True)</code>. If I were to create the following:</p> <pre><code>def my_copy2(...
<p>You can import the module inside the function or you can do it on the script. The <a href="https://docs.python.org/3.4/library/shutil.html#shutil.copy" rel="nofollow">documentation</a> doesn't explain what is <code>*</code>. I would omit it.</p> <pre><code>from shutil import copy2 def my_copy2(src, newdst, ...) ...
regex|python-3.x|directory
0
5,569
20,815,135
Distinguishing the return values from threads when a queue is used
<p>This is my code :</p> <pre><code> queue=Queue.Queue() isbn=str(9789382711056) thread1= Thread(target = amazon, args=[isbn,queue]) thread2= Thread(target = bookadda, args=[isbn,queue]) thread3= Thread(target = infibeam, args=[isbn,queue]) def jo(): thread1.join() thread2.join() ...
<p>If you use a <a href="https://stackoverflow.com/q/3033952/190597">multiprocessing.ThreadPool</a>, then you could use <code>pool.map</code>:</p> <pre><code>import multiprocessing.pool as mpool def worker(target, isbn): return target(isbn) def amazon(isbn): ... def bookadda(isbn): ... def infibeam(isb...
python|multithreading|queue
3
5,570
20,598,229
Insert blank line in doxygen code fragment
<p>In the fragment @code some code @endcode</p> <p>How do I get a closing blank line in the output?</p>
<p>Found a simple fix:</p> <h2>\htmlonly <br/></h2> <h2>\endhtmlonly</h2> <p>Seem to to the job of inserting a single blank line in doxygen generated page.</p>
python|doxygen
1
5,571
71,948,602
How to correctly import python modules when the program runs in visual studio code?
<p>I have a <code>my_program.py</code> python script.</p> <p>Inside this script, I can import the class in <code>utils/my_util.py</code> by starting the script with <code>python -m foo.my_program</code>.</p> <p>Here's the content of <code>my_program.py</code></p> <pre><code>from utils.my_util import Util u = Util() </...
<p>Except in the launch.json file, you can also:</p> <p>Add this in the settings.json file, it will affects the action which run within the terminal, such as <code>Run Python File in Terminal</code>:</p> <pre><code> &quot;terminal.integrated.env.windows&quot;: { &quot;PYTHONPATH&quot;: &quot;${workspaceFolder}&q...
python|python-3.x|visual-studio-code
0
5,572
71,804,238
Download File or Video from URL (Python 3)
<p>ı tried diffrent libs to download video from url. But even one of them didnt worked. Here is the link, that ı trying: <code>https://td-cdn.pw/api.php?download=tikdown.org-42500282235.mp4</code></p> <p>If it opened once, it directly asking to download, not like a html video. And ı want to save this video to local fol...
<p>There are two steps to getting file downloaded in Python so the process is os independant. I would recommend using inbuilt <code>requests</code> library. We use it to make requests to server and fetch content. Then we write the data into a file in next step.</p> <pre><code>import requests URL = &quot;https://td-cdn...
python|python-3.x|urllib|wget
3
5,573
15,303,639
Tkinter Image viewer
<p>I'm trying to create a program using Tkinter that displays a thumbnail from several different directories in on window. So far I have this:</p> <pre><code>import Tkinter as tk from PIL import Image, ImageTk import Image, os root = tk.Tk() root.title('Shot Viewer') w, h, x, y = 1000, 1000, 0, 0 root.geometry("%dx%d...
<p>Use the glob module to help find the relevant files.</p> <p>As for images failing to appear:</p> <pre><code>import Tkinter as tk from PIL import Image, ImageTk import glob root = tk.Tk() labels = [] for jpeg in glob.glob("C:/Users/Public/Pictures/Sample Pictures/*.jpg")[:5]: im = Image.open(jpeg) im.thu...
python|image|tkinter|viewer
1
5,574
15,264,367
what's the 'index' term on inspect.getouterframes() function?
<p>I did a "help(inspect.getouterframes)" on python, and here's what it gave me:</p> <pre><code>getouterframes(frame, **context**=1) Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and **index wit...
<p>It's to add some context from the surrounding code for the current line. Simple example:</p> <pre><code>import sys import inspect def f(): # prev return sys._getframe() # next # prev framelist = inspect.getouterframes(f(), 3) # next for frame in framelist: print frame[3], "context:\n" for i, ...
python
0
5,575
15,028,782
Generate functions without closures in python
<p>right now I'm using closures to generate functions like in this simplified example:</p> <pre><code>def constant_function(constant): def dummyfunction(t): return constant return dummyfunction </code></pre> <p>These generated functions are then passed to the init-method of a custom class which stores...
<p>You could use a callable class:</p> <pre><code>class ConstantFunction(object): def __init__(self, constant): self.constant = constant def __call__(self, t): return self.constant def constant_function(constant): return ConstantFunction(constant) </code></pre> <p>The closure state of you...
python|function|closures|pickle
7
5,576
49,545,144
How can I tell ChromeDriver to wait longer for Chrome to launch before giving up?
<h3>Background</h3> <p>I'm using Selenium and Python to automate display and navigation of a website in Chromium on Ubuntu MATE 16.04 on a Raspberry Pi 3. (Think unattended digital signage.) This combination was working great until today when the newest version of Chromium (with matching ChromeDriver) installed via ...
<h2>The bad news</h2> <p>It turns out that not only is there no <code>timeout</code> option for Selenium to pass to ChromeDriver, but short of recompiling your own custom ChromeDriver, there is currently no way to change this value programmatically whatsoever. Sadly, <a href="https://cs.chromium.org/chromium/src/chro...
python|selenium|raspberry-pi|selenium-chromedriver
0
5,577
62,625,377
Discord Bot not coming online
<p>I'm using Visual Studio Code for my bot. I just started and I can't get my bot to come online. This is my code</p> <pre><code>from discord.ext import commands client = commands.Bot(command_prefix = '-') @client.event async def on_ready(): print('YEEEEEEEEET') client.run('BOT_TOKEN') </code></pre> <p>I'm ...
<p>It was a certificate problem, and not problem with the code.</p>
python|discord|discord.py
0
5,578
53,384,231
How to apply SMOTE technique (oversampling) before word embedding layer
<p>How to apply SMOTE algorithm before word embedding layer in LSTM.</p> <p>I have a problem of text binary classification (Good(9500) or Bad(500) review with total of 10000 training sample and it's unbalanced training sample), mean while i am using LSTM with pre-trained word-embeddings (100 dimension space for each w...
<p>I faced the same issue. Found this post on stackexchange which proposes to adjust the weights of the class distribution instead of oversampling. Apparently it is the standard way in LSTM / RNN to deal with class imbalance.</p> <p><a href="https://stats.stackexchange.com/questions/342170/how-to-train-an-lstm-when-the...
python-3.x|tensorflow|deep-learning|oversampling
1
5,579
45,987,966
Django Union of ManyToMany Model Querysets
<p>Here's a basic many to many relationship model:</p> <pre><code>from django.db import models class ManyToManyModel(models.Model): name = models.CharField(max_length=50) ...
<p>You can't filter after doing the <code>union</code>. As stated <a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.union" rel="nofollow noreferrer">in the documentation</a>:</p> <blockquote> <p>... only LIMIT, OFFSET, COUNT(*), and ORDER BY (i.e. slicing, count(),...
python|django|django-models
1
5,580
46,025,163
Writing values to datetime field in odoo
<p>I have to create a calendar event through button function.</p> <pre><code>meeting_start_val = datetime.strptime(str_start_time, '%Y-%m-%d %H:%M:%S') meeting_start = meeting_start_val.strftime("%Y-%m-%d %H:%M:%S") meeting_end_val = meeting_start_val + timedelta(minutes=60) meeting_end = meeting_end_val.strftime("%Y-...
<pre><code> ist_timedelta = timedelta(seconds=((self.planned_hours*3600)-10800)) str_start_time = '%s %s' % (start_time,'00:00:00') meeting_start_val = datetime.strptime(str_start_time, '%Y-%m-%d %H:%M:%S') + ist_timedelta meeting_start = meeting_start_val.strftime("%Y-%m-%d %H:%M:%S") meeting_end_v...
python-2.7|datetime|odoo-8|openerp-8
0
5,581
45,817,153
Py.test fixture: Use function fixture in scope fixture
<p>I am facing a small issue with pytest fixtures, would appreciate your help. </p> <p>I have a few function fixtures as mentioned below. for simplicity I have not show the implementation.</p> <pre><code>@pytest.fixture() def get_driver(): pass @pytest.fixture() def login(get_driver): pass @pytest.fixture()...
<p>You will need to use a workaround. The action needs to be done in a <code>function</code> scoped fixture with <code>autouse</code> set to <code>True</code>. </p> <p>You need to initialize a variable in <code>session</code> based fixture, which will check if the <code>settings</code> have been done or not. If not do...
python|python-2.7|selenium|pytest|fixtures
2
5,582
46,162,182
Python mathmetical operation using a "for" loop not working
<p>I am trying to make a very basic account money reduction system The code I am using asks the user if he would like to buy the object which costs 200 bucks. The idea is that the $200 will be deducted from the variable named <code>total</code> but, for some reason, this is not working.</p> <p>I do not know if it is ...
<p>I don't think you need the for loop at all...</p> <pre><code>total = 1500 print('Would you like to buy this item?') print('It costs 200 bucks') purchaseConfirm = input() cost = 200 if purchaseConfirm == 'yes': total = total - cost print(total) </code></pre>
python|for-loop|if-statement
5
5,583
45,792,825
Python - Write file in intervals
<p>I want to run a command using Python script, which writes a file in 10 seconds interval, then read it and analyze the content.</p> <p>When I execute the script, the file is created but the content is not written.</p> <pre><code>cmd0 = 'airodump-ng -c '+ channel + ' --bssid ' + bssid + ' --write interval 10 -w psk ...
<p>I found the solution. I put next code:</p> <pre><code>p = subprocess.Popen(cmd0) t =threading.Thread(target=myfunction,args=(values,)) t.start() t.join() p.terminate() </code></pre> <p>Instead of the next:</p> <pre><code>p = Popen(cmd0,stdin=PIPE, stdout=PIPE, stderr=PIPE) time.sleep(10)#wait 10 seconds for num...
python|file
0
5,584
33,294,213
How to decode unicode in a Chinese text
<pre><code>with open('result.txt', 'r') as f: data = f.read() print 'What type is my data:' print type(data) for i in data: print "what is i:" print i print "what type is i" print type(i) print i.encode('utf-8') </code></pre> <p>I have file with string and I am trying to read the file and split...
<p>Let me give you some hints:</p> <ul> <li>You'll need to decode the bytes you read from UTF-8 into Unicode <em>before</em> you try to iterate over the words.</li> <li>When you read a file, you won't get Unicode back. You'll just get plain bytes. (I think you knew that, since you're already using <code>decode()</code...
python|unicode
7
5,585
73,833,796
Python BeautifulSoup find_all returns empty list
<pre class="lang-py prettyprint-override"><code>from urllib import request from bs4 import BeautifulSoup import requests url = &quot;https://recreation.northeastern.edu/&quot; result = requests.get(url) doc = BeautifulSoup(result.text, &quot;html.parser&quot;) marino = doc.find_all(text=&quot;Marino&quot;) print(m...
<p>It works for me, if you use <code>find_all(text=...)</code> in combination with <code>re.compile()</code></p> <p>Perhaps you want to try this:</p> <pre><code>import re import requests from bs4 import BeautifulSoup url = &quot;https://recreation.northeastern.edu/&quot; result = requests.get(url) doc = BeautifulSoup(...
python|beautifulsoup
0
5,586
21,916,566
Linear regression with Lasso penalty needs to increase iterations, Scikit-learn
<p>I am using Linear regression with Lasso implemented in Scikit-learn package. </p> <pre><code>linear_regress = linear_model.Lasso(alpha = 2) linear_regress.fit(X, Y) </code></pre> <p>For X, there is 7827 examples and 758 features. However I got a warning: </p> <pre><code>Objective did not converge for target 0, yo...
<p>I guess the warning on <code>'not converge'</code> may be due to underfitting, yet you need to verify (probably don't need to set the <code>tol</code> value too small). I would suggest you iterate <code>alpha</code> through <code>2^(-5)</code> to <code>2^3</code> in the fitting, and draw a learning curve to observe ...
python|machine-learning|scikit-learn|linear-regression
4
5,587
21,737,958
Virtualenv installing to local instead of virtual
<p>I am trying to install OpenERP server into a virtual enviroment that I created for that. I created the virtual using </p> <pre><code>mkvirtualenv openerp_rev5054 </code></pre> <p>On said virtual enviroment I use</p> <pre><code>&gt; (openerp_rev5054)user@machine:python setup.py install --record files.txt </code></...
<p>Try installing with pip rather than setup.py. I hear that pip plays nicer with virtual environments.</p>
python|openerp|virtualenv
1
5,588
38,149,631
How to resize the scrollbar from a QTextEdit in PyQt?
<p>I'm using a QTextEdit widget in my python GUI - designed with PyQt4. The vertical scrollbar appears as soon as the text doesn't fit anymore in the QTextEdit widget. But the scrollbar itself is so small (high dpi screen). How can I enlarge the scrollbar, such that clicking and dragging it gets more user friendly?</p>...
<p>I was able to get this to work using:</p> <pre class="lang-py prettyprint-override"><code>QScrollBar::handle:vertical { min-height : 16px; } </code></pre> <p>I was trying to display over 40000 lines in a <code>QTextEdit</code> and the scroll bar kept getting too small to even see. I struggled to get this working for...
python|pyqt|pyqt4
1
5,589
40,289,280
Call multiple functions inside list comprehension
<p>I'm trying to import a text file and return the text into a list of strings for each word while also returning lower case and no punctuation. </p> <p>I've created the following code but this doesn't split each word into a string. Also is it possible to add <code>.lower()</code> into the comprehension?</p> <pre><co...
<p>Yes, you can add <code>.lower</code> to the comprehension. It should probably happen in <code>word</code>. Also the following code probably does not split each word because of <code>string.punctuation</code>. If you are just trying to split on whitespace calling <code>.split()</code> without arguments will suffice.<...
python|list|list-comprehension
0
5,590
29,097,678
python tornado linkedin auth
<p>I would like to authenticate to <code>linkedin.com</code> and get some content</p> <p>I use <code>requests</code> python module and do something like this:</p> <pre><code>import requests from BeautifulSoup import BeautifulSoup client = requests.Session() HOMEPAGE_URL = 'https://www.linkedin.com' LOGIN_URL = HOME...
<p>Tornado's AsyncHTTPClient doesn't have any concept of a session; each request is independent. It looks like requests.Session is transferring something from the login request to the vsearch request, probably cookies. You'll need to handle the Set-Cookie header from the login request and transfer the cookies to any fo...
python|tornado
0
5,591
8,463,209
How to make a field conditionally optional in WTForms?
<p>My form validation is working nearly complete, I just have 2 cases I don't know exactly how to solve: 1) The password field should be required of course but I also provide the possibility to log in with google or facebook account via OAuth and then name gets prefilled but I remove the password field completely from ...
<p>I'm not sure this quite fits your needs, but I've used a <code>RequiredIf</code> custom validator on fields before, which makes a field required if another field has a value in the form... for instance, in a datetime-and-timezone scenario, I can make the timezone field required to have a value if the user has entere...
python|google-app-engine|validation|wtforms
72
5,592
18,765,904
numpy get mask from the array
<p>Suppose I have a numpy array</p> <pre><code>a = np.array([0, 8, 25, 78, 68, 98, 1]) </code></pre> <p>and a mask array <code>b = [0, 1, 1, 0, 1]</code></p> <p>Is there an easy way to get the following array:</p> <p><code>[8, 25, 68]</code> - which is first, second and forth element from the original array. Which ...
<p>If <code>a</code> and <code>b</code> are both numpy arrays and <code>b</code> is strictly 1's and 0's:</p> <pre><code>&gt;&gt;&gt; a[b.astype(np.bool)] array([ 8, 25, 68]) </code></pre> <p>It should be noted that this is only noticeably faster for extremely small cases, and is much more limited in scope then @fals...
python|numpy
3
5,593
18,879,667
Converting Unicode Values as String from a Python Dictionary
<p>I've built a python dictionary as follows:</p> <pre><code>result = {} for fc in arcpy.ListFeatureClasses(): for field in arcpy.ListFields(fc): result.setdefault(field.name, []).append(fc) </code></pre> <p>which takes the name of the fields in each table (feature class) and sets tyhem as the key value i...
<p>The issue in your code is that you are calling str(value), where value is an array. So what happens is that the array object's <a href="http://docs.python.org/2/reference/datamodel.html#object.__str__" rel="nofollow"><code>__str__</code></a> function is getting invoked and it has its own way of making a string repr...
python|dictionary|python-unicode
2
5,594
18,955,554
Get random key:value pairs from dictionary in python
<p>I'm trying to pull out a random set of key-value pairs from a dictionary I made from a csv file. The dictionary contains information for genes, with the gene name being the dictionary key, and a list of numbers (related to gene expression etc.) being the value.</p> <pre><code># python 2.7.5 import csv import random...
<p>If you want to get random <code>K</code> elements from dictionary <code>D</code> you simply use</p> <pre><code>import random random.sample( D.items(), K ) </code></pre> <p>and that's all you need. </p> <p>From the Python's documentation:</p> <blockquote> <p>random.<strong>sample</strong>(<em>population</em>, <...
python|csv|random|dictionary
17
5,595
18,822,164
pass data from a python application to a running c++ application
<p>I coded to applications one in python the other one in c++. In the middle of the python app I need to run the c++ app pass some input to it and receive the output. I already know that I can call the c++ app from python using subprocess but since that c++ app has to do some initial calculations each time it is called...
<p>Using subprocess.Popen you can open a process and keep it open, use the stdin and stdout to communicate with it. When you open the process use: stdout=subprocess.PIPE, stdin=subprocess.PIPE .<br> You can then write to process.stdin and read from process.stdout the output of the c++ program.</p>
c++|python
3
5,596
13,271,894
Interfacing with Sqlalchemy query object to extend, custom query types
<p>I'm working on adding pagination functionality to my models. I could do this with a method in a mixin, I think I understand what pagination is in this context, but I'm looking to add queries so I can pass in pagination wherever I want without hard coding a model method and without a mixin e.g.:</p> <pre><code>Mymod...
<p>Have you read this yet ?</p> <p><a href="http://packages.python.org/Flask-SQLAlchemy/api.html?highlight=pagination#flask.ext.sqlalchemy.Pagination" rel="nofollow">http://packages.python.org/Flask-SQLAlchemy/api.html?highlight=pagination#flask.ext.sqlalchemy.Pagination</a></p> <p>It clearly explains that to use pag...
python|sql|sqlalchemy
-2
5,597
57,747,841
Extracting the suffix of a filename in Python
<p>I'm using Python to create HTML links from a listing of filenames. The file names are formatted like: song1_lead.pdf, song1_lyrics.pdf. They could also have names like song2_with_extra_underscores_vocals.pdf. But the common thing is they will all end with _someText.pdf</p> <p>My goal is to extract just the someText...
<p>As @wwii said in its comment, you should use <a href="https://docs.python.org/3.6/library/os.path.html?highlight=splitext#os.path.splitext" rel="nofollow noreferrer"><code>os.path.splitext</code></a> which is especially designed to separate filenames from their extension and <a href="https://docs.python.org/3.6/libr...
python|python-3.x
1
5,598
57,995,334
Selenium - Cannot locate elements in page source
<p>I am trying to crawl a web page using Selenium, but for some reason the elements I need are not showing up in the page source</p> <p>I've tried using a WebDriverWait until the page loads. I've also tried to see if the data is in a different frame that I need to switch to.</p> <pre><code>driver.get('https://foreclo...
<p>Try the below code.It would return all the elements.Use <code>visibility_of_all_elements_located</code>()</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver...
python|selenium|selenium-webdriver|xpath|webdriverwait
1
5,599
58,115,013
How to pad multiple images to the minimum shape containing them all?
<p>I'm trying to write a function to load and process data for NN. As input I have a set of pictures of different sizes. The pictures should be represented as 3D numpy array with RGB channels. I need them to be of the same size (the size of the biggest of the pictures).</p> <p>I've tried <code>np.pad</code> but it se...
<p>The use of <code>np.pad()</code> is actually quite well <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow noreferrer">documented</a>.</p> <p>An example that would work for 3D data with the numbers you provided is:</p> <pre><code>import numpy as np arr = np.random.randint...
python|numpy|multidimensional-array
1