Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
8,800
1,242,541
What's the point of alloc_color() in gtk?
<p>Various examples always use alloc_color() and stuff like gtk.color.parse('red'), etc. I just do gtk.gdk.Color(65535,0,0), and that seems to work. What's the need for <code>alloc_color</code>?</p>
<p>If you're running on a system that uses a palette display (as opposed to a true-colour display), then you must allocate new colours in the palette before you can use them. This is because palette-based displays can only display a limited number of colours at once (usually 256 or sometimes 65536).</p> <p>Most displa...
python|gtk|colors|pygtk
2
8,801
41,761,293
Unable to access jira worklogs via python-jira
<p>I am trying to access the worklogs in python by using the <a href="http://jira.readthedocs.io/en/latest/examples.html" rel="noreferrer">jira python library</a>. I am doing the following:</p> <pre><code>issues = jira.search_issues("key=MYTICKET-1") print(issues[0].fields.worklogs) issue = jira.search_issues("MYTICK...
<p>This is because <strong>it seems</strong> <code>jira.JIRA.search_issues</code> doesn't fetch all "builtin" fields, like <code>worklog</code>, by default (although documentation only uses vague term <a href="https://jira.readthedocs.io/en/master/api.html?highlight=worklogs#jira.JIRA.search_issues" rel="noreferrer">"f...
python|jira
7
8,802
41,919,544
How to get equally spaced audio chunks from .wav file using ffmpeg?
<p>I have a .wav file which I am trying to slice into chunks of .wav files that are each 5 seconds long. I am calling ffmpeg as a sub process from within my Python script.</p> <p>So far, I tried using this:</p> <pre><code>"/user/local/bin/ffmpeg -i dirconf.UPLOAD/movie.wav -ss " + str(start) + " " + str(end) + " -asy...
<p>Use the segment muxer.</p> <pre><code>ffmpeg -i in.wav -f segment -segment_time 5 -c copy frame-%d.wav </code></pre>
python|audio|ffmpeg
2
8,803
47,216,684
How to retrieve the original string from UTF-8 file?
<p>I am doing some web scraping with python and BeautifulSoup.</p> <pre><code>body = soup.find("article") tempvar = body.find() fuu = open('tempfile', 'w') tempvar = tempvar.encode('utf-8') fuu.write(str(tempvar)) fuu.close() fupa = open('tempfile') joji = BeautifulSoup(fupa,'html.parser') fupa.close() print(joji) ...
<p><code>tempvar</code> is a Unicode string. To write it correctly to a file:</p> <pre><code>with open('tempfile', 'w', encoding='utf8') as fuu: fuu.write(tempvar) </code></pre> <p>Read it back in with:</p> <pre><code>with open('tempfile', encoding='utf8') as fupa: ... </code></pre>
python|utf-8|beautifulsoup|emoji
1
8,804
57,549,675
A non-recursive function follow_me(d, s) where d is a dictionary and s is a string
<p>I'm currently studying for an exam and have struggled to solve this question, my biggest problem seems to be iterating through the dictionary properly. The question itself is a non-recursive function follow_me(d, s) where d is a dictionary and s is a string. The string may be a key to the dictionary. The value assoc...
<p>You're close, but you don't need to loop over the keys; a simple <code>while</code> loop will do. </p> <pre><code>def follow_me(d, s): while s in d: s = d[s] return s </code></pre> <p>That said, you should check for cycles by adding the checked values to a <code>set</code>:</p> <pre><code>def foll...
python|python-3.x|function|dictionary
2
8,805
11,661,461
PIL saved jpeg string cannot be read in java
<p>I create a PIL image string on a python server:</p> <pre><code>frame = cv.CaptureFromCAM(0) image = Image.fromstring('RGB', cv.GetSize(frame), frame.tostring(), 'raw', 'BGR') buffer = cStringIO.stringIO() image.save(buffer,'JPEG') udptransmit(buffer.getvalue()) </code></pre> <p>I have a java client trying to read ...
<p>Just found a solution to the problem The problem was with the charset used in java while converting the string sent from my python server into bytes in java. Here's the simple modification that was required in my java client code:</p> <pre><code>Charset charset = Charset.forName("ISO-8859-1"); Byte[] bytes: Array[...
java|python|image|jpeg|python-imaging-library
0
8,806
11,528,682
In python, how can I count the times a condition is met within a function?
<p>I am very new to programming in general, and while I'm sure this looks like homework, it likely is for somebody, but I'm teaching myself, so it's "self-homework"?</p> <p>Anyway, I want to count the number of times a turtle leaves the window as it randomly makes squares. I also wanted to put a dot down at every poin...
<p>The easiest way to do this would be to keep track of how many times your turtle has gone off screen outside of your function, but inside of your <code>while</code> loop. </p> <p>Instead of having your function return whether the turtle has gone out four times, just have it return if it went out in that step. You'd ...
python
3
8,807
11,925,827
pandas: Writing to an existing excel file (xlsx) using to_excel
<p>I have a simple use case for <code>df.to_excel()</code> that I'm struggling with. I want to write to a specific worksheet tab (let's call it "Data") of an existing XLSX workbook, which could be referenced by formulas and pivots on other tabs. </p> <p>I've tried to modify ExcelWriter in two ways but both produce err...
<p>When you load your workbook with <code>use_iterators=True</code>, it then <code>_set_optimized_read()</code> on the <code>Workbook</code> object, which cause it to be loaded read-only.</p> <p>Thus, with the following code :</p> <pre><code>from openpyxl.reader.excel import load_workbook book = load_workbook('t.xls...
python|pandas|openpyxl
3
8,808
47,084,024
django/db/backends/mysql/operations.py full path please for ubuntu
<p>Need full path for django.db.backends folder.</p> <p>I already searched for django folder in usr/lib, usr/local/lib/python2.7/dist-packages but unable to find it.</p>
<p>Run this command:<br> <code>$ locate django/db/backends</code>.<br> This will give you all the possible paths where <strong>django/db/backends</strong> exists.</p>
django|python-2.7|ubuntu
0
8,809
46,792,631
Why i can't call container.findAll("h3", {"class":"name"})?
<p>What I want is just scrape all the products. Why I also can't use containers.div ? I really confused when there is <code>&lt;div&gt;&lt;\div&gt;&lt;div&gt;</code> while at my tutorial is just <code>&lt;div&gt;&lt;/div&gt;</code>.</p> <pre><code>from urllib.request import urlopen as uReq from bs4 import BeautifulSou...
<p>Try the below script and tell me it didn't fix the issue. I used conditional statement to avoid any error supposed to happen if any item is none, as in the second result where price is none. Now it works great.</p> <pre><code>import requests ; from bs4 import BeautifulSoup url = "https://hbx.com/categories/sneaker...
python|html|python-3.x|web-scraping|beautifulsoup
1
8,810
46,772,462
Print numbers on same line (Python)
<p>I have a variable which give as output numbers taken from a list every loop.</p> <pre><code>idx = 0 for i in y: listbyte = subprocess.check_output('python foo.py ' + path + str(y[idx]), shell=True).rstrip() idx += 1 listnum = listbyte.decode() number = (listnum[0]) print(numb...
<p>You can either store the numbers in a <code>string</code> and convert that to <code>int</code> or append to a <code>list</code> and <code>join</code> them later on.</p> <p><strong>Example</strong> for a list of numbers from <code>[1,5]</code> :</p> <p>Using a <code>list</code>,</p> <pre><code>&gt;&gt;&gt; nums = ...
python
1
8,811
47,023,516
Call a function in another one
<p>I have coded a quite simple program but I'll post a script short enough to reach the main point of the question:</p> <pre><code>def hello(): print("hello") good_morning() def good_morning(): print("good morning") hello() </code></pre> <p>I've a question about functions. According to a Python guide (wr...
<p>Statements are executed in order. By the time you execute <code>hello()</code> you have executed the statement that defines <code>good_morning</code>. There, when <code>hello()</code> tries to call <code>good_morning()</code>, it succeeds because the function is defined.</p> <p>In other words, the function has to b...
python|function|python-3.5
1
8,812
30,018,148
Python Tkinter Scrollable Frame Class?
<p>I would like to make a <code>Tkinter</code> <code>class</code>, based on <a href="https://stackoverflow.com/a/1884142/901641">the answer here</a>, which is a <code>Frame</code> that automatically shows/hides <code>Scrollbar</code>s around the content as necessary.</p> <p>The answer that I linked to above works perf...
<p>You're calling <code>canvas.config(scrollregion = canvas.bbox('all'))</code> when the canvas is still empty, effectively making the scrollregion <code>(0, 0, 1, 1)</code>.</p> <p>You should wait with defining the scrollregion until you have the widgets in your Frame. To do that you should rename <code>canvas</code>...
python|tkinter|scrollbar|tkinter-canvas
2
8,813
61,387,626
generate a random number between 2 and 40 with mean 20 as a column in pandas
<p>I have a data frame as shown below </p> <pre><code>session slot_num appt_time s1 1 2020-01-06 09:00:00 s1 2 2020-01-06 09:20:00 s1 3 2020-01-06 09:40:00 s1 3 2020-01-06 09:40:00 s1 4 2020-01-06 10:00:00...
<p>One possible solution with cutom function:</p> <pre><code>#https://stackoverflow.com/a/39435600/2901002 def gen_avg(n, expected_avg=20, a=2, b=40): while True: l = np.random.randint(a, b, size=n) avg = np.mean(l) if avg == expected_avg: return l df['service_time'] = df.grou...
pandas|numpy|random|pandas-groupby
1
8,814
27,879,294
In Python 3, best way to open an image stored in a list as a file object?
<p>Using python 3.4 in linux and windows, I'm trying to create qr code images from a list of string objects. I don't want to just store the image as a file because the list of strings may change frequently. I want to then tile all the objects and display the resulting image on screen for the user to scan with a barcode...
<p>You <em>already</em> have <code>PIL</code> image objects; <code>qr.make_image()</code> returns the (a wrapper around) the right type of object and you do not need to open them again.</p> <p>As such, all you need to do is:</p> <pre><code>base = img_list[0] </code></pre> <p>and go from there.</p> <p>You do need to...
image|python-3.x|qr-code|pillow
1
8,815
43,444,134
How do you implement custom response?
<p>I found that the DRF's return value could be various upon different occasions. So I want to make sure all my JSON return have "code" "message" or other values nested inside in order to keep consistency of my APIs.</p> <p>For example:</p> <p>Success</p> <pre><code>{"code": 1, "status": "success", "message": "", "d...
<p>You can use the status code of the HTTP to indicate the errors and success and you dont have to explicitly specify the error codes and response codes. In DRF status codes are defined in the module <a href="http://www.django-rest-framework.org/api-guide/status-codes/" rel="nofollow noreferrer">rest_framework.status<...
python|django|rest|django-rest-framework
0
8,816
36,963,160
Install/import sklearn module on Spyder 2.1? (Ubuntu)
<p>I am trying to import the sklearn module into <code>Spyder 2.1 (for Python 2.7)</code>. I have installed it on <code>Anaconda</code> through the terminal, but when I try to import it from the console in <code>Spyder</code> I get this error:</p> <blockquote> <p>ImportError: No module named sklearn.linear_model</p>...
<p>I think this may help. [link]<a href="https://stackoverflow.com/questions/10729116/adding-a-module-specifically-pymorph-to-spyder-python-ide">Adding a module (Specifically pymorph) to Spyder (Python IDE)</a> If you can locate, it's just a matter of changing the file paths.</p>
python|ubuntu|scikit-learn|crouton-os
0
8,817
48,795,945
Parsing MS specific html tags in BeautifulSoup
<p>When trying to parse an email sent using MS Outlook, I want to be able to strip the annoying Microsoft XML tags that it has added. One such example is the <code>o:p</code> tag. When trying to use Python's BeautifulSoup to parse an email as HTML, it can't seem to find these specialty tags. </p> <p>For example:</p> ...
<p>It's a namespace issue. Apparently, BeautifulSoup does not consider custom namespaces valid when parsed with <code>"html5lib"</code>.</p> <p>You can work around this with a regular expression, which – strangely – <em>does</em> work correctly!</p> <pre><code>print (soup.find_all(re.compile('o:p'))) &gt;&gt;&gt; [&l...
python|python-3.x|beautifulsoup
3
8,818
69,608,470
How to create this plot in python matplot
<p>I have these data from csv file, How can I plot this figure, I don't know the plot name to search, I took a look at <a href="https://matplotlib.org/stable/gallery/lines_bars_and_markers/csd_demo.html#sphx-glr-gallery-lines-bars-and-markers-csd-demo-py" rel="nofollow noreferrer">CSD demo on matplotlib page</a>, but I...
<p>plot by using plt.plot:</p> <pre><code>import matplotlib.pyplot as plt plt.plot(date, users, label=data_account_created) plt.legend() plt.show() </code></pre>
python|matplotlib|data-visualization
0
8,819
48,178,493
Decreasing distance between text and edge for QPushButton?
<p>How can we decrease the distance between the text strings inside of a <code>QPushButton</code> and the edge?</p> <p>For me (on LXDE) it now looks like this:</p> <p><a href="https://i.stack.imgur.com/fBSQU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fBSQU.png" alt="buttons-actual"></a></p> <...
<p>A possible solution is to set the width of the text according to the text with the help of <code>QFontMetrics</code>, or you can create a class that implements the logic with size policies and return an appropriate <code>sizeHint()</code> as shown in the following example:</p> <pre><code>from PyQt5.QtCore import * ...
python|pyqt|pyqt5|qpushbutton
1
8,820
48,223,587
How to create a dictionary of dictionaries using dict comprehension?
<p>I am trying to create a dictionary of dictionaries using a dict comprehension over a list of lists.</p> <p>The list of lists contains student names, assignment names and grades. For example, the data could look like this:</p> <pre><code>grades_lists = [ ['Student', 'Test', 'Assignment', 'Exam'], ['Bella', ...
<p>You got your nesting mixed up. The following works:</p> <pre><code>{name: {col: int(value) for col, value in zip(grades_list[0][1:], row)} for name, *row in grades_list[1:]} </code></pre> <p>The <code>for name, *row in ...</code> loop takes each row, and extracts just the first value into <code>name</code>, the r...
python|list|dictionary|list-comprehension
5
8,821
64,548,131
Column name mapping with data is being observed different when creating a pandas dataframe with column names given as a dictionary instead of list
<p>I'm observing random results in the column name mapping to the data when the column names are specified in a dictionary instead of a list.</p> <p>In the first case below, the ordering is as expected, but in the latter case the column names get incorrectly mapped to the data.</p> <p><a href="https://i.stack.imgur.com...
<p>That's because your column values are neither a <code>dictionary</code> nor a <code>list</code>. You have a <code>set</code> there, which are inherently unordered which is why you're seeing this result. Use square brackets to denote a <code>list</code> (which is ordered; e.g. <code>[&quot;col1&quot;, &quot;col2&quot...
python|pandas|dataframe
1
8,822
64,506,283
Create a pandas table
<p><a href="https://i.stack.imgur.com/xuvUc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xuvUc.png" alt="enter image description here" /></a></p> <p>In using pandas, how can I display a table similar to this one.</p> <p>I think I have to use a dataframe similar to <code>df = pandas.DataFrame(resul...
<p>You can pass in a dictionary for the data when you create the DataFrame:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; d = { ... 'Algothime': ['KNN', 'SVM', 'MLP'], ... 'Param. 1': ['-', '-', '-'], ... 'Param. 2': ['-', '-', '-'], ... 'Plage param. 1': ['-', '-', '-'], ... 'Plage p...
python|pandas
4
8,823
73,291,357
pytesseract does not extract numbers from image
<p>I am trying to extract numbers from an image using pytesseract but it does not return any text. Here is my code.</p> <pre><code>from PIL import Image import pytesseract im = Image.open('time.png') custom_oem_psm_config = r'--oem 3 --psm 11 -c tessedit_char_whitelist=&quot;0123456789&quot;'# -c preserve_interword_sp...
<p>Pyteserract is not able to extract from all images.</p> <p>It is mostly able to extract text which is similar to normal fonts we use on Microsoft word, notepad, etc.</p>
python|python-tesseract
0
8,824
50,041,734
pandas sum of group of elements with certain relative difference
<pre><code>time | value 1 4 2 5 20 7 ------------ 50 8 55 10 74 12 ------------ 100 1 105 21 120 0 </code></pre> <p>How to get the sum of values for each group of elements: such that the group has relative difference between each element and the next that ...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ge.html" rel="nofollow noreferrer"><code>ge</code></a> for <code>&gt;=20</code> and ...
python|pandas
0
8,825
53,216,877
Can't perform a backup or restore operation within a transaction
<p>I am trying to restore a transaction log to the database with a Python script. But I get an error message </p> <blockquote> <p>cannot perform a backup or restore operation within a transaction</p> </blockquote> <p>How can I solve this problem?</p> <pre><code>query_ms=r""" RESTORE LOG [miadmfggp_live] FROM DISK ...
<p>cursor_ms.autocommit='true' could solve the problem</p>
python|sql|sql-server
0
8,826
72,067,697
Keras - Dense and Conv2D values
<p>Images that I would like to use to train the network are about the size of <code>4000px*3000px</code> and about <code>40k</code> of them, sorted in <code>250</code> classes. I have made a CNN shown below:</p> <pre><code>model = keras.Sequential([ layers.Input((imgHeight, imgWidth, 1)), layers.Conv2D(16, 3, p...
<p>The output shape of the <code>Flatten()</code> layer is 96 Million, and so the final dense layer of your model has 24 Billion parameters, this is why you are running out of memory. There are some steps you can take to fix this issue:<br /> Try resizing your images to a smaller shape, if <code>4000x3000x1</code> isn'...
python|machine-learning|keras|conv-neural-network
2
8,827
68,823,878
Python type hinting: class of given type
<p>Sharing something I found in case it might be helpful to someone.</p> <p>What I wanted to do is to create a generic method that receives a <em>class (type)</em> and returns an instance of that type. Since I'm <em>strongly</em> in favor of static-typing (pun intended), I wanted to have it statically typed. This is so...
<pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Type T = TypeVar('T') def instantiate(self, t_type: Type[T]) -&gt; T: return T() # or whatever your code does # example class Foo: def some_method(self): pass f = instantiate(Foo) # IDE recognizes f is Foo (even without yo...
python-3.x|generics|type-hinting
0
8,828
68,823,485
Edit dataframe values in a group
<p>I need the values in group C to be in 200 intervals instead of 100 in Col3. I have a lot of columns in my actual dataframe but see below for simple example</p> <p>Original DF:</p> <pre><code>Group Col2 Col3 A 50 44 A 3 144 B 200 500 B 4.5 600 B...
<p>You can use boolean-indexing + <code>range()</code>:</p> <pre class="lang-py prettyprint-override"><code>mask = df[&quot;Group&quot;].eq(&quot;C&quot;) df.loc[mask, &quot;Col3&quot;] = df.loc[mask, &quot;Col3&quot;] + range(0, mask.sum() * 100, 100) print(df) </code></pre> <p>Prints:</p> <pre class="lang-none pretty...
python|pandas|dataframe
1
8,829
60,493,594
Gantt Chart - Printing all the Mondays in a year
<p>Given a dataset like this:</p> <pre><code>Task,Start,End a,2020-03-01,2020-03-16 a,2020-04-01,2020-04-16 b,2020-03-05,2020-06-22 c,2020-06-10,2020-11-28 </code></pre> <p>and this Gantt chart</p> <pre><code>import pandas as pd import altair as alt df = pd.read_csv("/Gantt.csv") df["Start"] = pd.to_datetime(df["St...
<p>You can customize tick values using <a href="https://altair-viz.github.io/user_guide/generated/core/altair.Axis.html" rel="noreferrer"><code>alt.Axis</code></a></p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import altair as alt df = pd.read_csv("Gantt.csv", parse_date...
python|altair
5
8,830
71,158,327
Applying wrapper to a function brakes it
<p>I'm trying to create wrapper. My code works with simple example function, but when I apply it to example function, it stops working.</p> <p>Code of my wrapper:</p> <pre><code>import functools import time from functools import wraps def profiler(func): @wraps(func) def wrapper(*args, **kwds): ...
<p>Your wrapper doesn't return, which is the same as returning <code>None</code>. When you call the decorated function, you will in practice just run the wrapper.</p> <p>Make sure the wrapper returns the result of your function and it will work just fine.</p> <pre><code>import functools import time from functools impor...
python|decorator|wrapper|python-decorators
1
8,831
56,863,556
How to represent Binary tree into an array using python?
<p>I want to convert Binary Tree into Array using Python and i don't know how to give index to tree-node?</p> <p>I have done this using the formula left_son=(2*p)+1; and right_son=(2*p)+2; in java But i'm stuck in python. Is there any Function to give index to tree-node in python ?</p>
<p>You can represent a binary tree in python as a one-dimensional list the exact same way.</p> <p>For example if you have at tree represented as:</p> <pre><code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15] </code></pre> <p><code>0</code> is the root<br> <code>1</code> &amp; <code>2</code> are the next level<br...
python-3.x|binary-tree
8
8,832
69,193,523
How to scrape text from a hidden element?
<p>I am trying to scrape the text of the Swiss constitution from <a href="https://www.fedlex.admin.ch/eli/cc/1999/404/en" rel="nofollow noreferrer">Link</a> and convert it to markdown. However, the page source is different from what I see in the inspector: The source only contains no script warnings in various language...
<p>In your code, you're not giving any time for the driver to render the contents, resulting in incomplete source code.</p> <p><a href="https://selenium-python.readthedocs.io/waits.html" rel="nofollow noreferrer">Waits</a> can be used to wait for required elements to be visible/present etc. The given code below waits f...
python|selenium|web-scraping
1
8,833
68,220,661
How to authenticate an end user with OAuth 2.0 for BigQuery API with python as a backend code in cloud function
<p>We have created a Flutter Web app that fetches bigquery data through bigquery API from Cloud Function. We were using a service account for authentication but as we want to make our application public, we need to use <code>OAuth</code> for end-user and use <code>OAuth</code> credentials.</p> <p>I have tried to deploy...
<p>I think you are missing the point of the use of Cloud Functions. The documentation you shared clearly states:</p> <blockquote> <p>This guide explains how to authenticate by using user accounts for access to the BigQuery API when your app is installed onto users' machines.</p> </blockquote> <p>This is never the case ...
python|authentication|google-bigquery|google-cloud-functions|authorization
0
8,834
63,278,659
My Network is rather predicts the mean output instead of individual predictions
<p>I am currently working on my Bachelor Thesis. I want to predict the heartrate of people with video data. I build my network similar to the paper &quot;RhythmNet: End-to-End Heart Rate Estimation From Face via Spatial-Temporal Representation&quot;.</p> <p>My problem: My network does not learn to predict the HR proper...
<p>According to Page 8 of the Paper, the output of the network is the mean Heart Rate. The output is computed with a mean pooling layer. Maybe you can get the single values from the single heart rates before the mean pooling layer?</p>
python|tensorflow|regression
0
8,835
62,377,335
VSCode change default python version
<p>When I code on VSCode and don't specify a python version it is set to python2.7.17</p> <p>I would like to set it by default to python3.6</p> <p>I tried doing so by adding this at the top of my script : <code>#!/usr/bin/python3.6</code> But it is not working</p> <pre><code>#!/usr/bin/python3.6 from flask import F...
<p>Open settings and search for <code>Python Default Interpreter Path</code>.</p> <p><a href="https://i.stack.imgur.com/hQJOR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hQJOR.png" alt="VS code settings for default python interpreter" /></a></p> <p>In your case, you wish to set it to <code>/usr/b...
python|visual-studio-code
4
8,836
59,904,826
Anaconda client CLI installed, but anaconda command not found
<p>I would like to use the <a href="https://github.com/Anaconda-Platform/anaconda-client" rel="nofollow noreferrer">anaconda-client CLI</a> to access the Anaconda Cloud (specifically, to upload a local package to an Anaconda Organization), but the command is not found:</p> <pre><code>$ which anaconda #empty $ anacond...
<p>I resolved this by realizing that I had disabled the <code>base</code> environment from activating by default, to avoid having <code>(base)</code> display on every new terminal (see <a href="https://stackoverflow.com/a/57587606/9161344">this answer</a>).</p> <p>By manually activating the <code>base</code> environme...
python|ubuntu|pip|anaconda
2
8,837
25,252,218
How to hide/disable close button or at least catch/override built-in quit() function? (Kivy)
<p>I need to do some actions before quit (save settings, etc.), I do it with Button widgets, but if I press on close button of the window, it just closes. Maybe I should handle App's <code>on_close()</code> event somehow? Then I don't know how to send data from Layout to App. For now I have smth like:</p> <pre><code>d...
<p>Yes, you should <a href="http://kivy.org/docs/api-kivy.app.html#profiling-with-on-start-and-on-stop" rel="nofollow">handle the <code>on_stop</code> method on your <code>App</code> class</a> by implementing the appropriate method.</p> <p>Example:</p> <pre><code>class MyApp(App): ... def on_stop(self): ...
python|kivy|python-3.4|quit
3
8,838
60,191,302
How to join two different dataframe whit different index
<p>Good morning, I want to join two different DataFrame, but they have different index (As you can see in the picture below). Infact, the first is the result of a train_test_split and the second is an array converted into a DataFrame. The first (<code>new_features</code>) is a DataFrame 1700x21 and the second (<code>y_...
<p>You can use append instead of concat, but you have to rest the index of the big dataframe</p>
python|machine-learning|neural-network|spyder
0
8,839
50,387,902
List all users in a project in Google Cloud using Python API
<p>I am trying to list all users with their access levels, in a project in Google Cloud.</p> <p>I am able to do so using Command Prompt command, <code>gcloud projects get-iam-policy MY_PROJECT</code></p> <p>However, while I try doing it using <a href="https://cloud.google.com/iam/reference/rest/v1/projects.roles/lis...
<p>The API call you are doing (which is <a href="https://cloud.google.com/iam/reference/rest/v1/projects.roles/list" rel="nofollow noreferrer"><code>projects.roles.list</code></a>) lists all custom roles defined in an organization or project, so it does not do the same as <a href="https://cloud.google.com/sdk/gcloud/re...
google-cloud-platform|google-python-api|google-cloud-iam
2
8,840
35,115,130
Oauth2 lib cannot import name 'run'
<p>I am coding to connect to the Youtube API, and the examples I've seen use "run" from the Oauthlib2 tools to run auth flows. It seems that something is wrong on my venv install ( I have reinstalled it like 4 times already ) but it can't find run ... may it be a version issue ? I can import other parts of the library ...
<p>I'm strongly suggesting looking for a more recent example of the current oauth2client implementation. The old <code>run</code> method has been removed from the library in august, 2015 and was replaced by <code>run_flow()</code> in the tools module. Import it like this:</p> <pre><code>from oauth2client import tools ...
python|oauth-2.0
23
8,841
45,135,071
drop columns below a certain value count of a specific character
<p>Some columns of dataframe, df, have elements equal to "?" character. The df has 2000 rows. I want to drop the columns where more than 1800 elements are equal to "?".</p> <p>I think I need to use the apply method to figure out which columns need to be dropped and then use drop method to drop them but I can't figure ...
<p>You do not necessarily have to use <code>apply</code> method and <code>value_counts</code>; Checking equality and sum can do the same thing here and would potentially be more efficient:</p> <pre><code>df.eq("?").sum() </code></pre> <p>gives the amount of <code>?</code> in each column:</p> <pre><code>df.eq("?").su...
python|pandas|apply
6
8,842
44,952,750
Oauth authentication in Apache SuperSet
<p>I'm trying to enable authentication in <a href="https://github.com/apache/incubator-superset" rel="nofollow noreferrer">Apache SuperSet</a> through Oauth2.</p> <p>It shoud be straightforward due to the fact that it's built upon <a href="https://github.com/dpgaspar/flask-appbuilder/" rel="nofollow noreferrer">Flask ...
<p>You have to change the superset_config.py. Look at this example config, it works for me.</p> <pre><code>import os from flask_appbuilder.security.manager import AUTH_OID, AUTH_REMOTE_USER, AUTH_DB, AUTH_LDAP, AUTH_OAUTH basedir = os.path.abspath(os.path.dirname(__file__)) ROW_LIMIT = 5000 SUPERSET_WORKERS = 4 SECR...
python|docker|flask|flask-appbuilder|apache-superset
5
8,843
61,230,022
How to apply different styles with a condition using pandas
<p>I want to apply different background colours to a column on a DataFrame according to the value found on another, equal length list. My data (this is a toy example) has the following structure:</p> <pre><code>Username Password Indications New_name Mr/Mrs Balance Carlos xxx LoreIpsum Corona ...
<p>You can create <code>DataFrame</code> filled by <code>background-color</code>s by conditions, e.g. from your list in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html" rel="nofollow noreferrer"><code>Styler.apply</code></a>:</p> <pre><code>checkList = [Tru...
python|pandas|dataframe|pandas-styles
2
8,844
58,144,363
Only the first word of a string replaced in Python
<p>I try to translate dates with Python. If "January" is in the string, I replace it with "janvier" etc.</p> <p>I loop trough the json database. But when there is two months in the same string ("september" and "october"), only the first is translated. Why ?</p> <pre><code>datestring = datestring.replace(" - ", "-") ...
<p>You need to assign the replacement back to the date string, as strings are immutable in Python:</p> <pre><code>datestring = datestring.replace(" - ", "-") # Trad french/english if "January" or "january" in datestring: datestring = datestring.replace("January", "janvier") if "February" in datestring: dates...
python
2
8,845
56,098,494
I'm trying to create a program that will convert 2 (user) inputs to lists and then print the duplicates in a list
<p>For some reason the program prints the duplicates but not all of them. For example if <code>list1 = 'test'</code> and <code>list2 = 'test'</code> it prints <code>['t','e','s']</code></p> <pre><code>dublicates = [] x = input('type something : ') y = input('type something again : ') list1 = list(x) list2 = list(y) fo...
<p>Your initial logic doesn't work since when it gets to the last character <code>t</code>, it is already present in <code>duplicates</code> list, so <code>if i not in duplicates:</code> is evaluated to <code>False</code> and the last <code>t</code> is not added to the <code>duplicates</code> list</p> <p>Instead for y...
python|python-3.x
2
8,846
41,607,078
HOW DO I PARSE THE DATA IN THESE HTML TAGS?
<p>I am a python newbie.I was trying to get some data from my school site. Below is the code I wrote to scrap only the news items. It works but I want the title, date and paragraph to be in new lines. I feel there is something missing in my code but I don't have a hang on it. Need your help guys.</p> <pre><code>from b...
<pre><code>for i in soup.findAll("div", {"class": "blog-thumbnail-inside"}): print (i.get_text('\n')) #You can specify a string to be used to join the bits of text together print ("----------" *20) </code></pre> <p>out:</p> <pre><code>Final Undergraduate Examination Timetable for Semester 1 2016/2017 Posted ...
beautifulsoup|python-3.5
0
8,847
51,943,574
pygame: position not updated with keyboard input
<p>I have been working on a Pong game using pygame. I am trying to get the paddle to move up by pressing 'w' key, but the position for the paddle <code>LeftPaddle().pos</code> seems to not be updated when pressing the key. I suspect <code>LeftPaddle().pos</code> being defined under <code>__init__(self)</code> make it c...
<p>Everytime you call <code>LeftPaddle()</code>, you create a new instance of <code>LeftPaddle</code>.</p> <p>You want to create an instance <em>once</em> and then call methods on that very instance, like:</p> <pre><code>... self.boundaries() leftpaddle = LeftPaddle() leftpaddle.blit(self.background) ...
python|pygame
1
8,848
44,097,518
Why doesn't class B print every 1 second
<p>Given the code below</p> <pre><code>from threading import Thread import Queue from time import sleep class myClassA(Thread): def __init__(self,num,q): Thread.__init__(self) self.daemon = True self.num = num self.start() def run(self): while True: self.num...
<p>Yes, <code>Queue.get()</code> is blocking by default. From the <a href="https://docs.python.org/2/library/queue.html#Queue.Queue.get" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>If optional args <em>block</em> is true and <em>timeout</em> is <code>None</code> (<strong>the default</strong>), b...
python|multithreading|queue
1
8,849
44,032,876
Pandas to_csv multiple pages
<p>So as of right now I have FINALLY figured out how to get things into a dataframe but am totally new to programming and think something shouldnt be in this loop hence the problem..</p> <p>So what I am trying to do is pull baseball data from <a href="http://rotoguru1.com/cgi-bin/byday.pl?game=dk" rel="nofollow norefe...
<p>Is this what you want?</p> <pre><code>import os path = 'testingbaseball.csv' if not os.path.exists(path): df.to_csv('testingbaseball.csv') else: df.to_csv('testingbaseball.csv', mode='a', header=False) </code></pre> <p>This way you'll just keep adding the new data to your csv data file. </p>
python|csv|pandas|beautifulsoup
0
8,850
48,352,221
How does python web developers in general include the required python modules?
<p>I am writing a code in python that uses numpy, matplotlib etc.</p> <p>How to make sure that even a remote web server with python installed but no extra modules, can run the code without errors?</p> <p>I usually work on linux environment. Hence from source code, I can install the libraries in a prefix directory and...
<p>A popular convention is to list requirements in a text file (<code>requirements.txt</code>) and install them when deploying the project. Depending on your deployment configuration, libraries can be installed in a virtual environment (google keyword: virtualenv), or in a local user folder (<code>pip install --user -r...
python|numpy|matplotlib|cross-platform
2
8,851
51,330,473
Gevent/Gevent-websocket not being used by Flask-SocketIO
<p>I am building a web interface/data API using Flask and Flask-SocketIO for websocket communication. I would like to start shifting to a more development-ready setup using Gevent/Gevent-websocket, Gunicorn, and eventually Nginx for load balancing. However, after installing Gevent and Gevent-websocket, I am still get...
<p>The portion of the docs that you quoted refers to the <code>async_mode</code> argument, and how it is set by default. You are setting <code>async_mode='threading'</code>, so that disables the automatic selection of an async mode. Remove the argument, and then you'll get eventlet or gevent, depending on what you have...
python|flask|websocket|gevent|flask-socketio
3
8,852
70,583,652
grabbing video title from yt-dlp command line output
<pre><code>from yt_dlp import YoutubeDL with YoutubeDL() as ydl: ydl.download('https://youtu.be/0KFSuoHEYm0') </code></pre> <p>this is the relevant bit of code producing the output.</p> <p>what I would like to do is grab the 2nd last line from the output below, specifying the video title.</p> <p>I have tried a few...
<p>Credits: <a href="https://stackoverflow.com/a/31184514/12511801">answer</a> to question: <a href="https://stackoverflow.com/q/23727943/12511801">How to get information from youtube-dl in python ??</a></p> <hr /> <p>Modify your code as follows:</p> <pre><code>from yt_dlp import YoutubeDL with YoutubeDL() as ydl: ...
python|python-3.x|youtube
4
8,853
55,762,514
Best practices for unknown max_length in Django?
<p>After having to increase max_length of another field in a model, I've started to wonder: maybe this is not the way?</p> <p>I'm getting data from an external API, so I can't check what's the maximum length. Let's say that I'm guessing the field can have 100 chars - because it makes sense, but I have no idea if this ...
<p>The point of <code>max_length</code> is that <em>you decide</em> it. If you really want variable/unlimited length text, use <code>TextField</code> instead.</p> <p>The <code>max_length</code> is enforced on database level, If it's longer, it will just fail. If you want to truncate it from code side, you have to do i...
python|django|django-models
9
8,854
73,243,723
yuv420p pixel format in GStreamer?
<p>I am trying to stream a video from opencv/python to rtsp-simple-server via GStreamer. I am able to view the video fine in vlc, but the online streaming application I am using is very picky. I need the stream to have a pixel format of <strong><code>yuv420p</code></strong>. How do I convert a stream to this format wit...
<pre><code>.. videoconvert ! video/x-raw, format=I420 ! x264enc .. </code></pre> <p>You could also tell <code>x264</code> to use a specific profile that does 420 instead:</p> <pre><code>.. x264enc ! video/x-h264, profile=main ! .. </code></pre> <p>Both methods should work.</p>
python|opencv|ffmpeg|gstreamer|rtsp
1
8,855
50,165,978
Pandas: Concat DataFrames with Unexpected Behavior
<p>I'm doing some work in Pandas and getting strange behavior when using <code>pd.concat</code>. Specifically, I have a DataFrame, <code>df</code>, and I'm one-hot encoding the <code>zipcode</code> column. Here's what I'm doing:</p> <pre><code>zip_encoded = label_binarizer.transform(df["zipcode"]) zip_encode...
<p>You may need add <code>index</code> from df when you create <code>zip_encoded</code> </p> <pre><code>zip_encoded = label_binarizer.transform(df["zipcode"]) zip_encoded = pd.DataFrame(zip_encoded, columns=label_binarizer.classes_,index=df.index) </code></pre> <p>Then doing the concat </p> <pre><code>df = d...
python|pandas
1
8,856
63,971,308
While creating telegram bot, terminal was arguing for the 'text' in 8th line
<pre><code>import telebot import config from telebot import types bot = telebot.TeleBot(config.TOKEN) language = &quot;kazakh&quot; keyboard1 = types.ReplyKeyboardMarkup() item_kaz = types.ReplyKeyboardMarkup(text = &quot;Қазақ тілі&quot;, callback_data = &quot;kazakh&quot;) item_rus = types.ReplyKeyboardMarkup(text ...
<p>There are few concepts in <code>python-telegram-bot</code>:</p> <ul> <li><p><code>KeyboardButton</code> - <strong>button</strong> class for description of simple reply button, can be used just string instead. Example:</p> <pre class="lang-py prettyprint-override"><code>KeyboardButton(text='ABC') </code></pre> </li> ...
python|telegram|telegram-bot|py-telegram-bot-api
1
8,857
64,175,567
scipy.io : element.item(0) vs element[0]
<p>I would like to know the difference between:</p> <pre><code>element.item(0) </code></pre> <p>and</p> <pre><code>element[0] </code></pre> <p>after converting a matlab file to a &quot;dictionary-like&quot; structure using scipy.io</p> <p>Thank you.</p>
<p>Looks like your <code>element</code> is a <code>numpy</code> array.</p> <p>Then <code>element.item(k)</code> according to <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html" rel="nofollow noreferrer">this documentation</a> is <code>k-th</code> element in flattened version of <code>elem...
python|matlab|scipy
1
8,858
53,291,250
Python 3.6 DateTime Strptime Returns error while Python 3.7 works well
<p>I just created a data type for my date data, which returns a <code>datetime.datetime</code> object</p> <p>Here is the code:</p> <pre><code>import datetime class Date: def __new__(cls, dateTime, *args, **kwargs): return datetime.datetime.strptime(dateTime, "%Y-%m-%dT%H:%M:%S.%f%z") </code></pre> <p>S...
<p>Ok, after 2 days, I checked the <a href="https://docs.python.org/3/whatsnew/changelog.html" rel="noreferrer">Python 3.7 changelog</a>, and I found out support for <code>Z</code> as a UTC offset was added in Python 3.7. See this <a href="https://bugs.python.org/issue31800" rel="noreferrer">issue</a> on the Python iss...
python|datetime|python-3.6|python-3.7
21
8,859
53,289,844
check the arguments only if the letters in that list are formed
<p>I have three arguments and all arguments must be consist of letters like john, car, yoga. If arguments contain any numbers or signs I need to print error you need to use only letters. I think I need to create a list and check the arguments only if the letters in that list are formed. Can someone help me to do that ...
<p>Usually if you just want to know if a given string contains only alphabet letters (no spaces, punctuation marks, numerals, etc.), you can simply use Python's <code>.isalpha()</code> function on the string. For example, <code>'john'.isalpha()</code> returns <code>True</code>, but <code>'johnny5'.isalpha()</code> ret...
python|string
0
8,860
68,779,350
Pylance (ReportMissingModuleSource) with Docker
<p>I'm getting the error of missing import when doing import in my Django project, I think it's because it's installed in a Docker Container.</p> <p>But how can I make it so VSCode somehow knows that the packages are installed? If I select an interpreter of a venv in which I have installed django or other packages it d...
<p>It's recommended to install the packages individually, but if you want to reuse them, you can add the paths of them into the <code>PYTHONPATH</code>.</p> <p>You can do this to modify the <code>PYTHONPATH</code>:</p> <ol> <li><p>Add these in the settings.json file to Modify the <code>PYTHONPATH</code> in the terminal...
python|docker|visual-studio-code
2
8,861
68,586,561
sklearn: multi-class problem and reporting sensitivity and specificity
<p>I have a three-class problem and I'm able to report precision and recall for each class with the below code:</p> <pre><code>from sklearn.metrics import classification_report print(classification_report(y_test, y_pred)) </code></pre> <p>which gives me the precision and recall nicely for each of the 3 classes in a tab...
<p>If we check the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html" rel="nofollow noreferrer">help page for classification report</a>:</p> <blockquote> <p>Note that in binary classification, recall of the positive class is also known as “sensitivity”; recall of the ...
python|scikit-learn|classification|supervised-learning
4
8,862
71,444,261
Getting 'confidence' value for OCR text - Python/Azure
<p>I've managed to put together enough Python code to capture an image, store it locally, treat it to remove noise etc and then run Azure OCR API (in PyCharm, using Python 3.9) to get back the text it contains.</p> <p>Here is an approximate example of the images I have to work with. The only information I want to extra...
<p>There's no built in function to extract a specific portion of an image using Pytesseract but we can use OpenCV to extract the ROI bounding box then throw this ROI into Pytesseract.</p> <p>We convert the image to grayscale then threshold to obtain a binary image. Assuming you have the desired ROI coordinates, we use ...
python-3.x|azure|pycharm|computer-vision|ocr
0
8,863
71,704,307
how to create a dataframe class in pandas/python
<p>i want to create a class, which will create a dataframe object.</p> <p>but the below code doesn't work properly:</p> <pre><code>class Df: def __init__(self,df): self = df my_df = Df(df) print(my_df.columns) AttributeError: 'Df' object has no attribute 'columns' </code></pre> <p>what should I do? I wan...
<p>You could directly inherit from Dataframe and add methods to this class:</p> <pre><code>import pandas as pd class Df(pd.DataFrame): def say_hello(self): print('hello world') df = Df({'data': [1,2,3]}) print(df.columns) df.say_hello() </code></pre>
python|pandas|dataframe
2
8,864
71,536,052
Debugging the solution to a possible Bipartition
<p>I came across this problem</p> <pre><code>We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the perso...
<p>Consider a scenario:</p> <ol> <li>Let's assume that in the dislikes array, we have <code>[1,6],[2,6]</code> among other elements (so <code>6</code> hates <code>1</code> and <code>2</code>).</li> <li>Person <code>1</code> doesn't hate anybody else</li> <li>After placing everybody into groups, let's say <code>2</code>...
python|algorithm|graph
0
8,865
5,287,050
Specifying installed native library paths during pypy translate
<p>I am trying to build the latest pypy repo on a Mac machine. One of the needed libraries, libintl, is installed in <code>$HOME/opt/local/lib</code>. I run (using a previously built <code>pypy-c</code>),</p> <pre><code>pypy-c translate.py -Ojit --ldflags=-L~/opt/local/lib --cflags=-L~/opt/local/lib </code></pre> <p>...
<h3>New Environment Variable</h3> <p>Talk about timing — I just added support for this! You can now set a <code>PYPY_LOCALBASE</code> environment variable when you translate, e.g.</p> <pre><code>PYPY_LOCALBASE=/Users/tav/local pypy-c translate.py -Ojit </code></pre> <p>It will then add the <code>lib</code> and <code...
python|dynamic-linking|static-linking|pypy|rpython
3
8,866
62,639,017
Keyerror in Python.I am a beginner and tried to make this login system to take the user inputs and write it into a text file in the form of dictionary
<p>import pprint</p> <p>users_entry = {}</p> <p>account = input(&quot;Do you already have an account? (Y/N): &quot;) account = account.lower()</p> <p>if account == 'y': print(&quot;Happy logging in!&quot;) else: acc_creation = input(&quot;Would you want to create an account? (Y/N): &quot;) acc_creation = acc_creation.l...
<p>The reason you are getting a KeyError is because you are adding key/values to the dictionary incorrectly. Key value pairs are added to a dictionary in python like so:</p> <pre><code>users_entry['name'] = name users_entry['email'] = email users_entry['password'] = password </code></pre> <p>Those changes to your code ...
python-3.x|dictionary
0
8,867
61,798,461
Django's displayed datetime doesn't change based on the user's local timezone
<p>models.py</p> <pre class="lang-py prettyprint-override"><code>from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self)...
<p>In you settings.py file your default time zone is set to </p> <pre><code>TIME_ZONE = 'UTC' </code></pre> <p>You're going to want to leave this as-is so you don't encounter issues with DST. Once you obtain your object from the database, it will be up to you to convert to the local timezone. In order to get the loca...
python|django|django-models
1
8,868
60,511,674
Statement seems to have no effect hex to dec converter
<p>When trying to use my hex to decimal converter I get an error for this line where I assign 'E' to 14, it says the statement has no effect</p> <pre><code>def hex2dec(n): res = [x for x in n] for i in range (len(res)): if res[i] == 'A' or res[i] == 'a': res[i] = 10 if res[i] == 'B' or res[i] == 'b': ...
<p>This is because you used double equal signs <code>==</code> instead of the single one <code>=</code>. <code>==</code> is used for logical evaluations, while <code>=</code> is used for assigning values to variables. Secondly, you have a typo in the "E" conditional statement. The second condition should be smaller-cas...
python|hex|effect
1
8,869
71,351,379
filter dataframe checking if values in a column are certain object
<p>I have a question. I have a GeoDataFrame object from geopandas with a column named &quot;geometry&quot; and polygons and multipolygons from shapely.geometry. I want to filter the dataframe and only leaving out the multipolygons (knowing that multipolygons are object).</p> <p>I tried:</p> <p>gdf = gdf[gdf[&quot;geome...
<p>a combination of <code>loc[]</code> and <code>isinstance()</code> will filter to just polygons. Full working example below.</p> <pre><code>import geopandas as gpd import shapely world = gpd.read_file(gpd.datasets.get_path(&quot;naturalearth_lowres&quot;)) world.loc[world[&quot;geometry&quot;].apply(lambda g: isin...
pandas|numpy|geopandas
1
8,870
64,348,283
How to remove unwanted characters in python
<p>I am trying to call an API from the output of a query , the output of the query is int , but when I call the query it returns something like <code>[(12345,)],</code> but I want only <code>12345</code> how to reconstruct the output</p> <p>i am using import re regular expression to remove the unwanted characters but i...
<p>[(12345,)] it is just a tuple inside a list</p> <p>you can take the element out by using</p> <pre><code>data = contact[0][0] print(data) </code></pre> <p>will give you the required results</p>
python
1
8,871
64,195,020
My Python code is not printing the result after completion in my def statement. What is the issue?
<p>I want to have my code print a certain string, showing the cost of the user's liability insurance depending on what they choose. Here is the code:</p> <pre><code>print(&quot;Use this program to estimate your liability.&quot;) def main(): user_name = get_user_name() user_age = get_age() violation = get_...
<p>There's no unconditional print in your code so if no condition is met, nothing will show up. You need to better debug your code or at least introduce <code>else</code> to catch such case.</p>
python
1
8,872
70,344,156
SQL-Alchemy: having problems creating relationships without ForeignKeys
<p>Im trying to create relations but without foreign key constraints in db</p> <p>quite similar to this post: <a href="https://stackoverflow.com/questions/37806625/sqlalchemy-create-relations-but-without-foreign-key-constraint-in-db">sqlalchemy: create relations but without foreign key constraint in db?</a></p> <p>Howe...
<p>got this working:</p> <p>change to mapper to mapper_registry.map_imperatively</p> <pre><code>def start_mappers(): inspected_items_mapper = mapper_registry.map_imperatively(InspectedItem, inspected_items) inspection_records_mapper = mapper_registry.map_imperatively(InspectionRecord, inspection_records, proper...
python|sqlalchemy
0
8,873
70,121,833
PYTHON: Open Chrome on Bookmarks
<p>So every time I open my chrome browser, it loads the company website, and of course I don't have adm permissions to modify the settings on chrome.</p> <p>It is possible using Python webbrowser or another library to open directly my chrome bookmarks?</p> <p>I have something like this, but didn't work:</p> <pre><code>...
<p>Maybe try something like that:</p> <pre><code>import webbrowser webbrowser.open(&quot;chrome://bookmarks/&quot;) </code></pre> <p>I try this on my PC and that works.</p>
python|web|browser
0
8,874
70,127,908
VSCODE how to debug python in conda environment in docker container in remote server
<p>I start by enabling the docker container in the remote server, then I connect VSCODE to that server via SSH, and finally I attach VSCODE to the docker (docker extension installed). I have selected the interpreter in the conda environment by editing a ./.vscode/launch.json file When I start the python program debug t...
<p>You most likely need to select the Interpreter inside VSCode. First open up the Command Palette <code>Ctrl+Shift+P</code>, then type <code>Python: Select Interpreter</code> then select the environment you want to use.</p>
python|docker|visual-studio-code|conda|remote-server
0
8,875
63,452,725
Incorrect change point detection by FB Prophet
<p>I have a time series data as follows:</p> <pre><code> ds y 0 2016-10-31 2000 1 2016-11-30 3000 2 2016-12-31 5000 3 2017-01-31 5000 4 2017-02-28 4000 5 2017-03-31 4500 6 2017-04-30 10000 7 2017-05-31 6500 8 2017-06-30 3500 9 2017-07-31 5500 10 2017-08-31 2000 11 2017-09-...
<p>Changepoints are a measure to calculate where the <strong>trend</strong> of the data changes. Your points 6, 12, and 22 are outliers, or perhaps holiday effects. Changepoints do nothing to account for this in a reliable way. Taken your 7 changepoints example prophet analyzed the following trendlines:</p> <pre><code>...
python-3.x|forecasting|trend|facebook-prophet
0
8,876
63,375,292
How to compress a file-like object with password and then upload it to s3 in Python?
<p>I want to export a dataframe to a .csv file, zip it, set a password to it, and then upload it to a public s3 bucket.</p> <p>Since I am writing a serverless script, the I/O is a bit tricky, but I was able to write this code:</p> <pre><code>import gzip import io import boto3 gz_buffer = io.BytesIO() report_bucket_pub...
<p>I accomplished this by using <code>tempfile.TemporaryDirectory()</code> and writing both the uncompressed and compressed data to files within the temporary directory. See <a href="https://stackoverflow.com/a/59452759/9465722">this answer</a> to a related question.</p>
python|python-3.x|amazon-s3|file-io|zip
0
8,877
69,668,907
Determining Overall Time Series Model Percent Improvement
<p>I have the true values as well as the predictions for both an older and a newer model ran on thousands of time series. My goal is to calculate the overall improvement of the new model over the old model. Below is an example of what my data looks like:</p> <pre><code> DATE TRUE OLD_PRED NEW_PRED TI...
<p>When calculating MAPE, you say:</p> <blockquote> <p>Then to get the percentage improvement for each time series, I would take the difference between the 2 values (old - new)</p> </blockquote> <p>But you are actually describing how to calculate the difference in percentage points, not how to calculate the percent dif...
python|time-series|loss-function
1
8,878
61,130,995
Python using child class's class attribute as default parameter without overriding method
<p>While initializing a class, the default arg for a parameter is a constant class attribute.</p> <pre class="lang-py prettyprint-override"><code>class SomeClass: """Some class.""" DEFAULT_VAL = 0 def __init__(self, some_param: int = DEFAULT_VAL): print(f"default = {self.DEFAULT_VAL} and some_par...
<p>The problem here is that <em>default values</em> take <em>objects, not variables/attributes</em>. The object is evaluated <em>once</em> when the function is defined. The generic way to solve this <em>in any function</em> is to do something like:</p> <pre><code>class SomeClass: """Some class.""" DEFAULT_VAL...
python|oop|overriding|class-attributes
2
8,879
60,888,483
Python - Append list to list
<p>I am trying to solve a problem about lists. For output I want to add all the lists to one final list (<code>ans</code>).</p> <p>But when I append the second list, the first list becomes equal to the second one. I can't understand why this happens.</p> <pre><code>ls = list() ans = [] n = int(input()) for _ in...
<p>When you append a list into a list, i.e. <code>ans.append(ls)</code> you actually pass it by reference. So when you append <code>ls</code> 3 times into <code>ans</code> it will append the same reference of <code>ls</code>.</p> <p>If you don't want to append by reference, you should give a copy of the list. And in a...
python|list|append
1
8,880
69,261,202
How to determine if a Glyph can be displayed?
<p>I have a large list of Unicode icons that I want to display. However, I would like to hide/skip any icon that I cannot display (because I don't have the correct font installed). Is there a programmatic way to determine this?</p>
<p>There's nothing built into Python for this. However, you can apply the <code>fonttools</code> module e.g. as follows (used in Windows 10):</p> <pre><code># ToDo: find fallback font # ToDo: reverse algorithm (font =&gt; characters) instead of (character =&gt; fonts) # ToDo: check/print merely basic font (omit variant...
python|unicode|glyphicons
2
8,881
68,998,947
subprocess Popen - decode
<p>In my script I was using this with decoding to utf-8:</p> <pre><code>result = subprocess.run(['command'], stdout=subprocess.PIPE).stdout.decode('utf-8') </code></pre> <p>Now I need to change command, where I need to use pipelines, so according to few examples which I have found, I need to use subprocess.Popen instea...
<p>When you run <code>Popen</code>, you have to do the plumbing yourself.</p> <p>In very brief, you want to add</p> <pre class="lang-py prettyprint-override"><code>stdout, stderr = r3.communicate() </code></pre> <p>to allow <code>r3</code> (and by extension, the other two processes) to finish.</p> <p>You should still a...
python|subprocess|decode
0
8,882
72,585,750
Django Subquery Sum with no results returns None instead of 0
<p>I have a Django Subquery which returns a Sum. If the subquery finds at least one result, it works fine. But, if the subquery finds no records, it returns None which then causes any other calculations using this result (I use it later in my query in an F expression) to also result in None.</p> <p>I am trying to Sum...
<p>You should <em>not</em> <code>Coalesce</code> the <code>.annotate(…)</code> <em>in</em> the <code>Subquery</code>, but the <em>result</em> of the <code>Subquery</code>, so:</p> <pre><code>.annotate(tapx=<strong>Coalesce(</strong> Subquery(InvTrx.objects.filter( job=OuterRef('job'), consumed__isnull=False...
python|django|postgresql|django-queryset|django-orm
3
8,883
68,200,890
appending a parameter to sql script in python
<p>Suppose a simple query in python as follows. The python code reads a &quot;new city&quot; from a user. The question is how to update the query by appending a list of cities (e.g., 'city1', 'city2', 'city3') to the where clause in the query.</p> <pre><code>mycursor = mydb.cursor() sql = &quot;select * FROM my_table ...
<p>Use <code>city IN (...)</code> rather than multiple <code>city =</code> operations. Then you can build the list of placeholders dynamically and replace them using parameters.</p> <pre><code>cities = ['Seattle', 'Portland', 'city1', 'city2', 'city3'] placeholders = ','.join(['%s']*len(cities)) sql = f'SELECT * FROM ...
python|mysql
2
8,884
59,410,182
How to send multipart/form file from base64 Python
<p>How to send base64 image using multipart form data in Python?</p> <p>I use a requests module, and read base64 string from file</p> <p>I need to send image by multipart form, but this file is base64 decoded. How to solve it?</p> <p>This code does not send file... :(</p> <pre class="lang-py prettyprint-override"><...
<p>Working example for a test file &amp; test url which just dumps passed data.</p> <pre><code>import base64 from io import BytesIO from pprint import pprint import requests iamge = open("template.txt", "r").read() decoded_image = base64.b64decode(iamge) files = { 'file1': ('test file.csv', BytesIO(decoded_imag...
python|python-requests|base64|multipartform-data
1
8,885
72,933,237
issue with my attempt at diffie-hellman key exchange
<p>I've been trying to write some code in python to create a diffie-hellman key exchange, but I found that any value for &quot;n&quot; that is large enough to be secure seems to cause the code to freeze up when calculating the partial key. From what I understand a 2k bit value for n is commonplace. It seems that any nu...
<p>There are two things that are important to get right:</p> <ol> <li>Use predefined domain parameters such as the ones defined in <a href="https://www.rfc-editor.org/rfc/rfc3526.html#section-3" rel="nofollow noreferrer">RFC 3526</a>. You cannot just use any value.</li> <li>If you perform a modulus exponentiation then ...
python|cryptography|python-cryptography
0
8,886
63,182,683
Search for multiple files in folder with particular file name, and select the most recent file, or filename with the largest numeric value
<p>Total beginner here, I'm writing a program that searches for a particular string as file names in a folder, the folder has only PDFs.</p> <p>For each file name I search for, typically it returns multiple files, like below:</p> <pre><code>200031-2018-252-20190828102708.pdf 200031-2018-252-20190828102735.pdf </code></...
<p>You can use use the <code>max</code> function and pass to the <code>key</code> argument a slice of the filename containing only the timestamp. To achieve this you can use the <a href="https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem" rel="nofollow noreferrer">.stem</a> function, which uses the pa...
python|excel
0
8,887
63,107,145
Writing to a tsv file from multiple list in Python
<p>I have two lists</p> <pre><code>ids = [1,2,3] values = [10,20,30] </code></pre> <p>I need to create a tsv file with two columns - <code>id</code> and <code>result</code> and put the <code>ids</code> and <code>values</code> in there. The output should look like this</p> <pre><code>id result 1 10 2 20 3 30 </code><...
<p>It's easier using pandas</p> <pre><code>In [8]: df = pd.DataFrame({&quot;ids&quot;:[1,2,3], &quot;values&quot;:[10,20,30]}) In [9]: df Out[9]: ids values 0 1 10 1 2 20 2 3 30 In [10]: df.to_csv(&quot;data.tsv&quot;, sep=&quot;\t&quot;, index=False) </code></pre>
python-3.x|csv
2
8,888
62,467,108
Checking the contents of python dataloader
<p>This is probably a simple question, but how see how the contents of this standard data loader looks like: </p> <pre><code>from torchtext import datasets import random train_data, test_data = datasets.IMDB.splits(TEXT, LABEL) train_data, valid_data = train_data.split(random_state = random.seed(SEED)) </code></pre> ...
<p>Datasets are iterables, you can get the first element with <code>next(iter(test_data))</code>.</p>
python|pytorch|dataloader
3
8,889
35,394,803
Python Matplotlib - Multiple series in same data file
<p>I'm a 'newbie' in python (started learning 2 weeks ago) and I'm trying to plot a file that looks like this:</p> <pre><code>"1stSerie" 2 23 4 12 6 12 "2ndSerie" 2 51 4 90 6 112 </code></pre> <p>Using any of the following: pandas, matplotlib and numpy. But I am not having much of a success. I tried searching fo...
<p>AFAIK there's no builtin features in pandas, matplotlib or numpy to read files like that one. If you have some control on the data format I encourage you to change it.</p> <p>If you have no options but using that format, you can parse the data yourself using just the python I/O and string manipulation features (I d...
python|python-3.x|numpy|pandas|matplotlib
2
8,890
58,789,596
The syntax the my python programming has some syntax errors
<p>This is how the exercise wants the output to be:</p> <pre><code>Give name: Peter The given name is wrong. Give name: John Give password: Monkeys? The password is incorrect. Give name: John Give password: ABC123 Both inputs are correct! </code></pre> <p>This is the code that I've written:</p> <pre><code>print("G...
<p>It's because your program will proceed regardless of whether your first <code>if</code> statement. You could flip your first <code>if</code> condition and then nest your password validation within the 2nd one:</p> <pre><code>print("Give name:") name = input() if name != "John": # This prevents your program from pro...
python|if-statement
0
8,891
58,935,622
Problem with implementation with the 100 doors Problem
<p>So far I got this code and its working perfectly, but my prof wants me to add something more.</p> <pre class="lang-py prettyprint-override"><code>doors = [False] * 100 for i in range(100): for j in range(i, 100, i+1): doors[j] = not doors[j] print("Door %d:" % (i+1), 'open' if doors[i] else 'close')` <...
<p>I guess this should be something like you want:</p> <pre><code>def create(num): doors = [False] * num return doors def switch(doors, nths): for n in nths: if not doors[n-1]: doors[n-1] = True else: doors[n-1] = False return doors def results(doors, val): ...
python|dictionary|data-structures
1
8,892
58,966,025
Unable to access Flask app hosted on EC2 after adding https support
<p>I have a Flask application currently using http being hosted on an ec2 instance. I want to host my application using https. Currently with http, I am able to access my application (running on 0.0.0.0 port 80) by just accessing the ec2 public IP address (displays <code>Running on http://0.0.0.0:80/</code>, and I am a...
<p>Simple way is put your instance behind ALB. ALB is not only load balancer, but also integrate ACM for free.</p>
python|amazon-web-services|flask|amazon-ec2
1
8,893
31,584,283
Shutdown a TThreadPoolServer in python
<p>I want to know how to shutdown a <code>TThreadPoolServer</code> properly. Right now I use the following python code:</p> <pre><code>try: # Other settings transport = TSocket.TServerSocket(port=server_port) server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) print("Starting s...
<p>Don't you need to <a href="http://people.apache.org/~thejas/thrift-0.9/javadoc/org/apache/thrift/server/TThreadPoolServer.html#stop%28%29" rel="nofollow"><code>.stop()</code></a> the <code>server</code>?</p>
python|thrift
0
8,894
48,909,850
How can I disable SSL verification in a third party python library?
<p>I am using the python library OSMnx, and it sends out a request to nomatim.openstreetmap.org in order to generate and load a map that is then used to create a network. However, when I try and run this over a VPN or at the office, I get this:</p> <pre><code>File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app....
<p>OSMnx can <a href="https://github.com/gboeing/osmnx/pull/745" rel="nofollow noreferrer">now</a> point to a local certificate file or override requests' parameters like auth, cert, verify, and proxies via the <code>ox.config()</code> function.</p>
python|ssl|ssl-certificate|verify
0
8,895
25,379,294
python2.7 using debug behave different then without debug
<p>I have a bug in my program and want to check it out using debug. In my IDE (WingIDE) I have a debug functionality. But I can not use that call the program from shell. So I use the Python module pdb. My application is single threaded.</p> <p>I have looked into <a href="https://stackoverflow.com/questions/4787082/cod...
<p>You introduced a delay between opening the subprocess and writing to it.</p> <p>When you create the <code>Popen()</code> object, the child process is started immediately. When you then call <code>p.communicate()</code> and try to write to it, the process is not quite ready yet to receive input, and that delay toget...
python|shell|debugging|subprocess
1
8,896
2,439,618
Parsing/Tokenizing a String Containing a SQL Command
<p>Are there any open source libraries (any language, python/PHP preferred) that will tokenize/parse an ANSI SQL string into its various components? </p> <p>That is, if I had the following string</p> <pre><code> SELECT a.foo, b.baz, a.bar FROM TABLE_A a LEFT JOIN TABLE_B b ON a.id = b.id WHERE baz = 'snafu'; </c...
<p>SQLite source has a file named <code>parse.y</code> that contains grammar for SQL. You can pass that file to <a href="http://www.hwaci.com/sw/lemon/" rel="nofollow noreferrer">lemon parser generator</a> to generate C code that executes the grammar. </p>
php|python|sql|parsing|tokenize
2
8,897
5,756,205
Foreign key in tastypie
<p>So, I started using the <a href="https://github.com/toastdriven/django-tastypie" rel="nofollow">TastyPie</a> plugin for Django to make a REST api for my project. I was following the getting started guide with my project, but when I got in <a href="http://toastdriven.github.com/django-tastypie/tutorial.html#creating-...
<p>The final answer for my problem is the answer from @manji and @dlrust combined:</p> <p>"change <code>urlpatterns</code> value to <code>urlpatterns = patterns('', (r'^api/', include(api.urls)),)</code>"</p> <p>and, after that, "define an authorization in your Meta for the resource".</p> <p>Hope it's useful for som...
python|django|rest|tastypie
3
8,898
30,294,146
Fastest way to process a large file?
<p>I have multiple 3 GB tab delimited files. There are 20 million rows in each file. All the rows have to be independently processed, no relation between any two rows. My question is, what will be faster?</p> <ol> <li><p>Reading line-by-line?</p> <pre><code>with open() as infile: for line in infile: </code></pre> <...
<p>It sounds like your code is I/O bound. This means that multiprocessing isn't going to help—if you spend 90% of your time reading from disk, having an extra 7 processes waiting on the next read isn't going to help anything.</p> <p>And, while using a CSV reading module (whether the stdlib's <code>csv</code> or someth...
python|file|python-2.7|filereader
40
8,899
67,136,637
Python run one function multiple times at the same time
<p>I am writing one bot and it needs to run multiple instances: first you input how many you want:</p> <pre><code>instances = int(input('How many instances?: ')) </code></pre> <p>Then the code will run one function (the main and only thing it does) and thats it. The bot is just Selenium, if that is relevant in any way<...
<p>Pythons multiprocessing module should do what you want. From the <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer">docs</a>:</p> <pre><code>from multiprocessing import Process def f(name): print('hello', name) if __name__ == '__main__': p = Process(target=f, args=('...
python|selenium|asynchronous
2