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 |
|---|---|---|---|---|---|---|
3,000 | 47,484,883 | Tensorflow object detection training makes python crash | <p>I am training ssd_mobilenet_v1_coco_2017_11_17 model from Tensorflow object detection model zoo.
My dataset is satellite imagery and my aim is to detect vehicles in the images.
But training fails with python memory issues. I am training on CPU and my windows 10 machine has 32 gb RAM. TF record file for training is a... | <p>try to adjust batch size, queue capacity, reader threads. </p> | python-3.x|tensorflow|object-detection | 0 |
3,001 | 47,400,055 | Python3 - Adding User Response to a List Instead of Over-writing Existing Data | <p>I am trying to write a basic store-front script that loops until the customer says no to the question. Each time there's input of an Item Number, I'm trying to store it and then eventually be able to match those numbers up with the Item Name and the Price (not quite yet, though)...</p>
<p>I am just, now, trying to g... | <p>I'm not sure why you're appending to <code>SKU</code>, you need a new list to track order numbers. </p>
<pre><code>orders = []
while str(input("Order products [Y / N]?: ")) != 'N':
item_nums = input("Enter an item number: ")
orders.append(item_nums)
print("Here is the list of items you ordered: ", orders)
... | python|if-statement|while-loop|tuples|user-input | 1 |
3,002 | 11,562,590 | Postgresql failed to start | <p>I am trying to use PostgreSQL on Ubuntu. I installed it and everything was working fine. However, I needed to change the location of my database due to space constraints so I tried an online guide to do it.</p>
<p>I proceeded to stop postgresql, create a new empty directory and give it permissions by using</p>
<p... | <p>First: You may find it easier to manage your Pg installs on Ubuntu using the custom tools Ubuntu provides as part of <a href="http://manpages.ubuntu.com/manpages/precise/man1/pg_wrapper.1.html" rel="nofollow"><code>pg_wrapper</code></a>: <a href="http://manpages.ubuntu.com/manpages/precise/man8/pg_createcluster.8.ht... | python|sql|postgresql|ubuntu | 4 |
3,003 | 58,590,083 | the same audio have different length using different tools (librosa,ffprobe) | <p>I want to measure an audio file's duration.<br>
I'm using two different tools and got different values.</p>
<ol>
<li>ffprobe:<br>
I'm using this line to get duration using ffprobe </li>
</ol>
<pre><code> ffprobe -i audio.m4a -show_entries format=duration -v quiet -of csv="p=0"
</code></pre>
<p>result :<code>780.... | <p>This is likely just normal floating point error. The two libraries probably make mathematically similar computations, but use different internal representation of the values which produce small rounding errors. This is normal and expected in floating point numbers. </p> | python|audio|ffmpeg|ffprobe|librosa | 2 |
3,004 | 46,749,095 | python gspread updating multiple cells from reponse body | <p>I am using this python script to take a response from Progresso API:
<a href="http://docs.progresso.apiary.io/#reference/behaviour/behaviour-events-collection/get-behaviour-events" rel="nofollow noreferrer">http://docs.progresso.apiary.io/#reference/behaviour/behaviour-events-collection/get-behaviour-events</a></p>
... | <p>If you mean something like two columns with one row being "BehaviourEntryId" and the other row being 13798177, you can try something like this:</p>
<pre><code>import json
response = json.loads(response_body) #decode the json response string, returns a dict
response_pairs = list(response.items)
for i in range(1, le... | python|api|gspread | 0 |
3,005 | 46,788,577 | How to use multiple "or" in python code | <p>My code below only prints "Remove Special Character". but if i leave only ("#"), it runs very well. </p>
<pre><code>def name_character(word=input("Username: ")):
if ("#") or ("$") or ("&") in word:
return print ("Remove Special Character")
if word == "":
return print ("Enter Username")
... | <p>Try this: </p>
<pre><code>>>> username = "foo#"
>>> any(x in username for x in "#&$")
True
>>> username = "bar"
>>> any(x in username for x in "#&$")
False
</code></pre> | python|python-3.x | 0 |
3,006 | 46,861,242 | How to find position of character in a list with respect to other characters in a list in o(n) time? | <p>Suppose I have a string <code>PRIME</code> on a list <code>['P','R','I','M','E']</code>. If we iterate through the list, the first element <code>'P'</code> has 3 elements less than it which is <code>['I','M','E']</code> and the second element <code>'R'</code> has only three elements less than it (note that we are lo... | <p>Here is mine (not O(n), but not O(n^2) either I guess):</p>
<pre><code>>>> def find_dict_position(s):
from collections import defaultdict
counter = defaultdict(int)
result = []
less_count = 0
for e in s[::-1]:
less_count = sum(counter[c] for c in counter ... | python|python-3.x | 3 |
3,007 | 47,061,129 | Class hierarchy in Python | <p>I have a relaisboard connected to an arduino via firmata protocol using Python bindings. The communication works without problems using pyfirmata (<a href="https://github.com/tino/pyFirmata" rel="nofollow noreferrer">https://github.com/tino/pyFirmata</a>).</p>
<p>The relaisboard has 16 relais. Every group of 3 rela... | <p>On the one hand, your actual question is pretty general, and you should try to be more specific in the future. On the other hand, it is often difficult for a beginner to know where to start, so I will provide you with some design tips that should help you get through this challenge.</p>
<p><strong>No nested classes... | python|class-hierarchy | 1 |
3,008 | 37,782,094 | how to split findall result which contain "," in data | <pre><code>x = re.findall(r'FROM\s(.*?\s)(WHERE|INNER|OUTER|JOIN|GROUP,data,re.DOTALL)
</code></pre>
<p>I am using above expression to parse oracle sql query and get the result.
I get multiple matches and want to print them each line by line.
How can i do that.
Some result even have "," in between them.</p> | <p>You can try this :</p>
<pre><code>for elt in x:
print('\n'.join(elt.split(',')))
</code></pre>
<p><code>join</code> returns a list of the comma-separated elements, which are then joined again with <code>\n</code> (new line). Therefore, you get one result per line.</p> | python | 1 |
3,009 | 37,865,608 | running bash command from python3 | <p>I am trying to remove some file (from my linux machine), except few:</p>
<pre><code>touch INCAR KPOINTS foo bar
$ls
bar foo INCAR KPOINTS
$python3 mini.py
Job Done
$ls
bar foo INCAR KPOINTS
</code></pre>
<p>The <code>mini.py</code> is:</p>
<pre><code>#!/usr/bin/python3
import subprocess
subprocess.run(['r... | <p>It doesn't work because <a href="http://wiki.bash-hackers.org/syntax/pattern#extended_pattern_language" rel="noreferrer"><code>!()</code></a> is an extended matching pattern, and needs to be enabled explicitly:</p>
<pre><code>subprocess.run(['/bin/bash', '-O', 'extglob', '-c', 'rm -f !(INCAR|KPOINTS|PO*|*.sh)'])
</... | python|bash | 5 |
3,010 | 67,999,140 | Odoo Python : How to copy/forward a phone number into user's device ( like <href="tel:"> behaviour) using Odoo python backend? | <p>Suppose in Odoo Form, i have a button. This button will trigger a python method in odoo backend to search the PIC and then forward/copy the PIC's <code>phone_number</code> to user's device, so that user can make a phonecall to the <code>PIC</code> using their device.</p>
<blockquote>
<p>The concern is, PIC is changi... | <p>Let's say you have the <code>pic_phone_number</code> field on <code>res.users</code> model. And you want to show a <code>tel:</code> URI on model <code>crm.lead</code>.</p>
<p>First you have to create a new computed field on model <code>crm.lead</code>:</p>
<pre class="lang-py prettyprint-override"><code>
pic_phone_... | python|html|odoo|tel | 0 |
3,011 | 30,176,488 | Error printing a string: %d format: a number is required, not str | <p>I am planning on taking a trip to Disney World late this summer and I have been trying to make a program to calculate an approximate cost of the trip for fun and to try and keep myself from getting too rusty. My problem is that when I try to display all of my calculated values, I keep receiving the error that is in ... | <p>Likely the error is caused by one of the <code>%i</code> formattings. For example, the following code:</p>
<pre><code>'this is %i' % '5'
</code></pre>
<p>This will return the same error: <code>TypeError: %d format: a number is required, not str</code>.</p> | python|python-2.7|format|typeerror | 1 |
3,012 | 61,512,284 | Python conditional boolean | <p>Im trying to understand the possibilities with Booleans in Python.</p>
<p>I don't want to use an If statement.</p>
<pre><code>its_valid = True
</code></pre>
<p>but I want something like this</p>
<pre><code>its_valid = True if taking_stones == 2 or taking_stones == 1
</code></pre>
<p>Is it possible in python an... | <p>Equality comparisons return booleans, so there's no need to explicitly write <code>True if {something true}</code>. You can simply write:</p>
<pre><code>its_valid = (taking_stones == 2 or taking_stones == 1)
</code></pre>
<p>Or, if you want to check multiple values more succinctly:</p>
<pre><code>its_valid = (tak... | python|python-3.x|boolean|conditional-statements | 2 |
3,013 | 56,928,447 | XKCD Web Scraper - Automate the Boring Stuff | <p>I'm currently on Chapter 11 of ATBS and working through the Web Scraper project. I can get it to run fine however the web comics are never actually downloaded on my Mac.</p>
<pre><code>#! /usr/bin/env python3
#downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
url = 'http://xkcd.com' ... | <p>You seemed to have left out the html.parser as follows:</p>
<pre><code>soup = bs4.BeautifulSoup(res.text, 'html.parser')
</code></pre> | python|python-3.x|web-scraping|beautifulsoup | 0 |
3,014 | 27,802,755 | Cumulative custom function over grouped data in Python | <p>I am looking to create a retention function over a pandas DataFrame which runs the cumulative function over grouped portions of the data. </p>
<p>I want to do something similar to what the R <i> plyr</i> package does</p>
<p>Say I have some dummy data as of so:</p>
<pre><code>df = pd.DataFrame({'x' : np.repeat(np.... | <p>Interesting question.
It appears that your decay factor, if call it so, is 0.25, the following two steps do what is intended (first 10 observations printed, the resultant is called <code>z</code>):</p>
<pre><code>In [67]:
z = df.groupby('x').y.apply(lambda x: np.convolve(x, np.power(0.25, range(len(x)))[:len(x)],... | python|r|function|pandas|plyr | 1 |
3,015 | 36,757,606 | How do I code a data encryption program using Python? | <p>Once I choose the appropriate encryption algorithm, what function would I use, in Python, to implement it into my security software that I am working on? I can't figure the logic. </p> | <p>You can use <strong>PyCrypto</strong>: <a href="https://pypi.python.org/pypi/pycrypto" rel="nofollow">https://pypi.python.org/pypi/pycrypto.</a>
It's simple to use:</p>
<pre><code>>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>>... | python|function|encryption|logic | -1 |
3,016 | 19,874,789 | Cut peaks and troughs | <p>Here is an algorithm I would like to implement using numpy:</p>
<p>For a given 1D array, calculate the maximum and the minimum over a sliding window.
Create a new array, with the first value equals to the first value in the given array.
For each subsequent values, clip the previous value inserted in the new array b... | <p>I don't think you can. You can sometime do this kind of iterative computation with unbuffered ufuncs, but this isn't the case. But let me ellaborate...</p>
<p>OK, first the windowing an min/max calculations can be done much faster:</p>
<pre><code>>>> a = np.array([3, 4, 5, 4, 3, 2, 3, 3])
>>> len... | python|algorithm|python-2.7|numpy | 2 |
3,017 | 48,425,276 | scrape an api result page with scrapy | <p>I have this url that the content of its response, contains some JSON data. </p>
<pre><code>https://www.tripadvisor.com/TypeAheadJson?action=API&types=geo%2Cnbrhd%2Chotel%2Ctheme_park&legacy_format=true&urlList=true&strictParent=true&query=sadaf%20dubai%20hotel&max=6&name_depth=3&inte... | <p>Try removing the sessionID from the URL and maybe check how "unfriendly" your <a href="https://doc.scrapy.org/en/latest/topics/settings.html" rel="nofollow noreferrer">settings.py</a> is. (Also see <a href="https://blog.scrapinghub.com/2016/08/25/how-to-crawl-the-web-politely-with-scrapy/" rel="nofollow noreferrer">... | python|json|scrapy | 1 |
3,018 | 51,165,264 | How to change Alexa talking speed? | <p>How to change Alexa talking/playback speed to super fast or super slow? Is there a way to manipulate the sampling rate of Alexa audio output?</p> | <p>Use <strong>prosody</strong> tag of SSML to modify the speed, pitch and volume of response speech.</p>
<p>Ex: </p>
<pre><code><speak>
<prosody rate="medium">I speak in medium pace</prosody>.
<prosody rate="slow">I speak in slow pace</prosody>.
<prosody rate="fast">I spe... | python|alexa|ssml | 1 |
3,019 | 51,124,618 | Regular expression with different number of characters | <p>I need to create a regular expression to validate strings. The strings can have only few characters and each character can be repeated only a few number of times.</p>
<p>The regular expression should check below conditions.</p>
<ol>
<li>The string can have only <strong>a, b, c, d, e</strong> as characters.</li>
<l... | <p>Likely, performance wise, the best way to do this is with Python native string operations.</p>
<p>I would write like so:</p>
<pre><code>lim=(('a',2),('b',3),('c',3),('d',1),('e',1))
results={}
for s in [list_of_many_strings]:
results[s]=bool(not(set(s)-set('abcde'))) and (not any(s.count(c)>x for c,x in lim... | python|regex | 4 |
3,020 | 64,464,196 | Pandas: How to (cleanly) unpivot two columns with same category? | <p>I'm trying to unpivot two columns inside a pandas dataframe. The transformation I seek would be the inverse of <a href="https://stackoverflow.com/questions/44167418/expand-category-in-a-column-to-column-name-in-pandas">this question</a>.</p>
<p>We start with a dataset that looks like this:</p>
<pre class="lang-py pr... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>wide_to_long</code></a>:</p>
<pre><code>np.random.seed(123)
df_orig = pd.DataFrame(data=np.random.randint(255, size=(4,5)),
columns=['accuracy','time_a','time_b','me... | python|pandas|dataframe|melt | 3 |
3,021 | 70,468,738 | Content API for Shopping - No module named google_auth_httplib2 | <p>I'm following the link below with the aim of implementing a Google API for shopping:</p>
<p><a href="https://developers.google.com/shopping-content/guides/quickstart/making-an-api-call" rel="nofollow noreferrer">https://developers.google.com/shopping-content/guides/quickstart/making-an-api-call</a></p>
<p>but when I... | <p>You should install <code>google-auth-httplib2</code> and not <code>google-auth-oauthlib</code></p>
<pre><code>pip install google-auth-httplib2
</code></pre> | python|python-3.x|terminal|google-auth-library | 0 |
3,022 | 73,287,019 | BeforeClass and AfterClass methods in Selenium Python | <p>I am new to test automation in Selenium Python. I was trying to automate a simple login test and I want to do some things in AfterClass method like in Selenium Java.</p>
<p>I have attached my code here.</p>
<p>test_login.py</p>
<pre><code>import unittest
from helper_actions import load_page, type_username, type_pass... | <p>@Anupama Balasooriya you can use setUpClass() and tearDownClass() for your purpose. You can refer this link for details. <a href="https://docs.python.org/3/library/unittest.html" rel="nofollow noreferrer">https://docs.python.org/3/library/unittest.html</a></p> | python|selenium | 0 |
3,023 | 49,969,788 | Confusion matrix get value error | <p>I am trying to create a confusion matrix with sci-kit learn for epileptic data set from
<a href="https://archive.ics.uci.edu/ml/datasets/Epileptic+Seizure+Recognition" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/datasets/Epileptic+Seizure+Recognition</a></p>
<p>after preparation, doing cross validation... | <p>You can convert both predicted and true label to <code>str</code>:</p>
<pre><code>conf = confusion_matrix(pred["y"].astype(str), pred["PredictedLabel"].astype(str))
</code></pre>
<p>Trying to recreate the similar issue, consider following case where predicted and true are different types:</p>
<pre><code>import pa... | python|scikit-learn|confusion-matrix|valueerror | 3 |
3,024 | 64,749,432 | Pandas - resample rows based on another df index | <p>I have a datframe looks like this:</p>
<pre><code>zone Datetime Demand
48 2020-08-02 00:00:00 14292.550740
48 2020-08-02 01:00:00 14243.490740
48 2020-08-02 02:00:00 9130.840744
48 2020-08-02 03:00:00 10483.510740
48 2020-08-02 04:00:00 10014.970740
</code></pre>
<p>I want to resamp... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>merge_asof</code></a>:</p>
<pre><code>print (df2)
a
2020-08-02 03:00:00 1
2020-08-02 06:00:00 2
2020-08-02 07:00:00 3
2020-08-02 10:00:00 4
df1['Date... | python|pandas|timestamp|pandas-resample | 1 |
3,025 | 61,810,843 | Null or None function in Python | <p>I am using the CreateTrackBar function in OpenCV to create a trackbar. But I don't want any callback to happen on change. I will be doing that in a separate loop where I get the trackbar value using cv2.getTrackbarPos(). But Python returns an error if I don't give a callable function as an argument to CreateTrackBar... | <p>I think you might just need to define a quick function. You can use an anonymous lambda and avoid explicitly defining a function to return <code>None</code>:</p>
<pre><code>cv2.createTrackbar("Value", "Window", 100, 255, lambda x:x)
</code></pre> | python|opencv|null-pointer|callable-object | 1 |
3,026 | 61,809,563 | Using If Statements To Check If Something Raises An Error | <p>I'm trying to write a program that will solve questions about parametric equations for me. I'm trying to do the following:</p>
<p>I'm trying to find 2 answers to a parametric equation. The first answer will be the positive square root. The second answer will be the negative square root. If the first square root rai... | <p>You cannot test for a run-time exception with <code>if</code>; that's exactly what <code>try-except</code> does. However, when the illegal operation is so directly defined, you can test for <em>that</em> condition before you try the <code>sqrt</code> opertaion:</p>
<pre><code>if (time - k)/-16 < 0:
# no roo... | python|math|parametric-equations | 0 |
3,027 | 60,443,930 | Issue while extracting data using Beautifulsoup | <p>My objective is to convert an xls file to xlsx file. The xls file which I am trying to convert is actually an html file containing tables (This xls file is obtained as a result of a query from jira). To facilitate the conversion I have created a file handler and then given that file handler to a beautiful soup and ... | <p>There is no good way for large files, but you can try different ways.</p>
<pre><code>from simplified_scrapy import SimplifiedDoc
print('Begin')
fileName = 'TestSample.xls'
html=open(fileName, encoding='utf-8').read()
doc = SimplifiedDoc(html)
start = 0 # If a string can uniquely mark the starting position of data, ... | python|python-3.x|parsing|beautifulsoup | 0 |
3,028 | 60,860,271 | Is it possible to $.post inside a $.get in jquery (Flask + Python) | <p>I'm relatively new to Flask in Python. So please bear with me if my question sounds stupid.</p>
<p>I've a <code>GET</code> function like this below:</p>
<pre><code>@app.route('/transactions', methods=['GET','POST'])
def get_transactions():
...
</code></pre>
<p>I've a text box (#transaction_year) on html and ... | <p>I've managed to get a workaround for this. I created a separate function to store the $.post value in a global variable input_year.</p>
<pre><code>input_year = 1
@app.route('/transactions_input', methods=['POST'])
def get_transactions_input():
global input_year
transaction_year = float(request.form['transac... | python|jquery|flask | 0 |
3,029 | 68,063,856 | populate combobox editable human_name and line edit phone and email from mariadb | <p>I have table hr and 1 combobox with a list of hr, I want to show email and phone to <code>hremail_lineEdit</code> and <code>hrphone_lineEdit</code>, but I can only show phone to <code>hrphone_lineEdit</code>.</p>
<pre><code>def hr_name(self):
self._conn = pymysql.connect(host=127.0.0.1, port=3306, user='root', p... | <p>There are several options:</p>
<ul>
<li><p>Pass email and phone as a tuple (or list) to the userData:</p>
<pre class="lang-py prettyprint-override"><code>self.hr_name_comboBox.clear()
for row in res_coop4hr:
un, email, phone = row
self.hr_name_comboBox.addItem(un, (email, phone))
</code></pre>
<pre class="la... | python|python-3.x|pyqt5|mariadb|qcombobox | 0 |
3,030 | 58,989,485 | How to implement DBMS_METADATA.GET_DDL in cx_Oracle and python3 and get the ddl of the table? | <p>this is the oracle command i am using :-</p>
<pre><code>query = '''SELECT DBMS_METADATA.GET_DDL('TABLE', 'MY_TABLE', 'MY_SCHEMA') FROM DUAL;'''
cur.execute(query)
</code></pre>
<p>now how to get the ddl of the table using <code>cx_Oracle</code> and <code>python3</code> .</p>
<p>please help . i am unable to extrac... | <p>The following code can be used to fetch the contents of the DDL from dbms_metadata:</p>
<pre><code>import cx_Oracle
conn = cx_Oracle.connect("username/password@hostname/myservice")
cursor = conn.cursor()
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
if defaultType == cx_Oracle.CLOB... | python|python-3.x|oracle|oracle11g|cx-oracle | 2 |
3,031 | 51,003,411 | Slicing a multiindexed column dataframe to obtain a new data frame | <pre><code>import pandas as pd
import string
from random import randint
months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
monthyAmounts = [ "actual", "budgeted", "difference" ]
summary = []
summary.append( [ randint( -1000, 15000 ) for x in ra... | <p>You need to align indices for the series which constitute your dataframe:</p>
<pre><code>res = pd.DataFrame({'difference': budgetDifference,
'months': budgetMonths,
'actual': pd.Series(budgetActual.values, index=budgetDifference.index)})
print(res)
differenc... | python|pandas|dataframe|slice|multi-index | 1 |
3,032 | 57,941,970 | Reducing overfitting in CNN by increasing training data size versus augmenting images (preprocessing data) using DataImageGenerator | <p>Does increasing the size of the training data helps in reducing overfitting ? Or is it suggested to go for image augmentation (data preprocessing) using the ImageDataGenerator in Tensorflow to skew or rotate the image to decrease overfitting ?
Which method is better to reduce overfitting ??</p> | <p>By means of image augmentation, basically you are increasing the size of your training data. If you have data which is different from your existing training data, then adding that data into your training data is good.</p>
<p>So in short, both the methods are good to overcome over-fitting.</p> | tensorflow|computer-vision|conv-neural-network | 0 |
3,033 | 56,156,329 | SQLalchemy not committing changes when setting role | <p>I'm creating tables using a sqlalchemy engine, but even though my create statements execute without error, the tables don't show up in the database when I try to set the role beforehand. </p>
<pre><code>url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, password, host, port, db)
engine = sqlalchemy.create_... | <p>The issue here how sqlalchemy decides to issue a commit after each statement. </p>
<p>if a text is passed to <code>engine.execute</code>, sqlalchemy will attempt to determine if the text is a DML or DDL using the following regex. <a href="https://github.com/sqlalchemy/sqlalchemy/blob/f601791a914d3181252493800871c45... | python|sql|postgresql|sqlalchemy|roles | 1 |
3,034 | 46,375,967 | How to efficiently serialize python dict with known schema to binary? | <p>I have a lot of python dicts with known schema. For example, the schema is defined as Pyspark StructType like this:</p>
<pre><code>from pyspark.sql.types import *
dict_schema = StructType([
StructField("upload_time", TimestampType(), True),
StructField("name", StringType()... | <p>You can use the built-in <code>struct</code> module. Simply "pack" the values:</p>
<pre><code>import struct
struct.pack('Q10s5s`, time, name, value)
</code></pre>
<p>That's assuming time is a 64-bit int, name is at most 10 characters and value is at most 20 characters. You'll need to tune that. You might also c... | python|dictionary|serialization | 1 |
3,035 | 49,568,578 | Why it says ValueError for the below program with python3 but not python2 | <pre><code>k=['d','e','f']
v=[4,5,6]
h=zip(k,v) #zipping
for i,j in h:
print(i ,':',j)
(k,v)=zip(*h) #unzipping
print(k)
print(v)
output:
Traceback (most recent call last):
File "hasht.py", line 6, in <module>
(k,v)=zip(*h)
ValueError: not enough values to unpack (expected 2, got 0)
</code></pre> | <p>zip creates a list in Python 2, so your <code>h</code> is a value that you can inspect at any time. zip creates an iterator in Python 3, so your loop with the <code>print</code> statement exhausts <code>h</code>.</p>
<p>Use <code>h = list(zip(k, v))</code> to get the same behavior in both Python 2 and 3.</p> | python-3.x|python-2.7|dictionary|hashtable | 0 |
3,036 | 51,470,200 | Cannot insert row using Flask and SQLAlchemy | <p>I am doing CS50 project and the current task is to create a register page. User fills in the form and presses button. So it has to be insert into my PostgreSQL database. But when I fill the form and press 'Register' I got this error:</p>
<pre><code>StatementError: (sqlalchemy.exc.InvalidRequestError) A value is req... | <p>you are almost there.</p>
<pre><code>db.execute("INSERT INTO users (name, surrname, nickname, password) VALUES (:name, :surname, :nickname, :password", {":name": name, ":surname": surname, ":nickname": nickname, ":password": password})
</code></pre>
<p>Firstly, this doesn't execute as you are missing the closing p... | python|postgresql|flask|sqlalchemy | 2 |
3,037 | 64,288,116 | ModelMultipleChoiceField django and debug mode | <p>i'm trying to implement a ModelMultipleChoiceField in my application, like that: <a href="https://stackoverflow.com/questions/41809057/django-form-select-multipe-allow-to-add-the-objects">Link</a></p>
<p>model.py</p>
<pre><code>class Services(models.Model):
id = models.AutoField(primary_key=True)
type = mod... | <p>Your <code>service</code> is a <code>ForeignKey</code>:</p>
<pre><code> service = models.<s>ForeignKey(Services, on_delete=models.CASCADE)</s></code></pre>
<p>A <code>ForeignKey</code> means that you select a <em>single</em> element, not multiple ones. You use a <a href="https://docs.djangoproject.com/en/dev/ref/... | python|django|django-forms | 1 |
3,038 | 64,342,685 | Keeping variable names when exporting Pyomo into a .mps file | <p>So, i'm currently working with a pyomo model with multiple instances that are being solved in parallel. Issue is, solving them takes pyomo quite a long time (like 2 to 3 secs, even though the <em>solving part</em> by gurobi takes about 0.08s). I've found out that, by exporting a pyomo instance into an .mps file and ... | <p>Managed to solve it!
To anyone who might find this useful, i passed a dictionary with "symbolic_solver_labels" as an io_options argument for the method, like this:</p>
<pre><code>instance.write(filename = str(es_) + ".mps", io_options = {"symbolic_solver_labels":True})
</code></pre>
<p>... | python|pyomo|gurobi | 3 |
3,039 | 64,205,663 | How to specify the `--formats` sdist option inside setup.py? | <p>I try to create a zipped source python package on a linux distribution without specifying the <code>--formats</code> option to sdist on the command line (using an existing Jenkins pipeline which do not support this option).
In the documentation <a href="https://docs.python.org/2/distutils/sourcedist.html" rel="nofol... | <p>From the linked documentation <a href="https://docs.python.org/2/distutils/configfile.html" rel="nofollow noreferrer">previous topic</a>:</p>
<blockquote>
<p>The basic syntax of the configuration file is simple:</p>
<pre><code>[command]
option=value
...
</code></pre>
<p>where command is one of the Distutils commands... | python|python-2.7|setup.py|sdist | 2 |
3,040 | 70,695,543 | A question about the use of parenthesis with arguments | <pre><code>def calculate_pythagoras():
pythagoras_list = list()
for i in range(1, 101):
for j in range(1, 101):
c = (i ** 2 + j ** 2) ** 0.5
if (c == int(c)):
pythagoras_list.append((i, j, int(c)))
return pythagoras_list
for i in calculate_pythagoras():
... | <pre><code>def calculate_pythagoras():
pythagoras_list=list()
for i in range(1,101):
for j in range(1,101):
c=(i**2 + j**2)**0.5
if(c==int(c)):
pythagoras_list.append((i,j,int(c))) # You're calling the append method with those extra parentheses.
return pythago... | python|parentheses|brackets | -1 |
3,041 | 70,712,543 | How to parse a dataframe efficiently, while storing data (specific row, or multiple rows) in others dataframe using a specific pattern? | <p>How to parse data on all rows, and use this row to populate other dataframes with data from multiple rows ?</p>
<p>I am trying to parse a csv file containing several data entry for training purpose as I am quite new to this technology.</p>
<p>My data consist in 10 columns, and hunderds of rows.
The first column is f... | <p>For df2, it's pretty simple:</p>
<pre><code>df2 = df.rename(columns={'Power/Character': 'Power'}) \
.loc[df['Code'] == 10, :]
</code></pre>
<p>For df3, it's a bit more complex:</p>
<pre><code># Extract power and fill forward values
power = df.loc[df['Code'] == 10, 'Power/Character'].reindex(df.index).ffill()... | python|pandas|dataframe|vectorization | 2 |
3,042 | 55,598,651 | Creating a 'normal distribution' like range in numpy | <p>I am trying to 'bin' an array into bins (similar to histogram). I have an input array <code>input_array</code> and a range <code>bins = np.linspace(-200, 200, 200)</code>. The overall function looks something like this:</p>
<pre><code>def bin(arr):
bins = np.linspace(-100, 100, 200)
return np.histogram(arr,... | <p>Use the inverse error function to generate the bins. You'll need to scale the bins to get the exact range you want</p>
<p>This transform works because the inverse error function is flatter around zero than +/- one. </p>
<p><a href="https://i.stack.imgur.com/mhtCg.png" rel="nofollow noreferrer"><img src="https://i.... | python|numpy|normal-distribution | 1 |
3,043 | 66,646,384 | TypeError: object of type 'ID3TimeStamp' has no len() | <p>I have made this code, to get the year from an mp3, and if i print it, it works, but when i write to text box in my webpage, it gives an error(traceback below), but not always, sometimes the error not show, so i suspect it is from the way the mp3 is tagged:</p>
<pre><code>nfo_year = ''
audio_filename = 'myfile.mp3'
... | <p><code>nfo_year</code> is a timestamp object, of type ID3TimeStamp. You have to pass strings to <code>AB_author.send_keys</code>. Since <code>print</code> worked, you can try <code>str(nfo_year)</code>.</p> | python|selenium|mutagen | 0 |
3,044 | 66,750,082 | Cant delete/drop columns from multiple files through looping in python | <p>I am facing some issue while trying to drop columns from multiple excel files in Python. I get the below error, when I am trying the same code on single file it works, but it doesn't work on multiple files while looping and I don't undersand why the error is <code>[columns ] not found in axis</code> . I am not sure ... | <p>It is very likely the case that an <code>xlsx</code> file in the <code>extracted</code> folder does not have the columns that you are wishing to drop. Try adding a filter condition to process the rest of the files and also print the name of the file(s) without the columns.</p>
<pre><code>import os
import glob
import... | python|pandas | 0 |
3,045 | 64,133,838 | Pygame - Sprite Group movement doesnt work | <p>I'm currently trying to program an space invaders clone. I created an "Invaders"-Class with several attributes and I created an sprite group for all my enemy invaders.</p>
<pre class="lang-py prettyprint-override"><code>class Invader(pygame.sprite.Sprite):
def __init__(self, settings, picture, x, y):
... | <p>The moving direction has to be an attribute of the class <code>Invader</code>. Change the direction if the <em>Sprite</em> is at the left or the right of the window:</p>
<pre class="lang-py prettyprint-override"><code>class Invader(pygame.sprite.Sprite):
def __init__(self, settings, picture, x, y):
super... | python|pygame | 0 |
3,046 | 53,234,848 | Getting points in convex hull | <p>I have two overlapping sets of points T and B.</p>
<p>I want to return all points from T that are within the convex hull of B
I compute the convex hulls as follows</p>
<pre><code>from scipy.spatial import Convexhull
import numpy as np
T=np.asarray(T)
B=np.asarray(B)
Thull = ConvexHull(T)
Bhull = ConvexHull(B)
</c... | <p>Here is an example of what you want using the function defined in the <a href="https://stackoverflow.com/questions/16750618/whats-an-efficient-way-to-find-if-a-point-lies-in-the-convex-hull-of-a-point-cl">other question</a> I posted in the comments:</p>
<pre><code>from scipy.spatial import Delaunay
import numpy as ... | python|python-3.x|scipy | 0 |
3,047 | 53,025,031 | How can I read a message (in HTML format) from gmail gmail-api using python (v3.7)? | <p>I tried to follow the orientation followed in the link below but I did not succeed.
<a href="https://developers.google.com/gmail/api/v1/reference/users/messages/get" rel="nofollow noreferrer">https://developers.google.com/gmail/api/v1/reference/users/messages/get</a></p>
<p>Can someone help me by "being very specif... | <p>I ended up answering my question... Look below what I did to read a message using gmail's api.</p>
<p>In some situations the best response is in a good night's rest, a bit of insistence and the letitura of documentations.</p>
<p><a href="https://i.stack.imgur.com/ywVLQ.png" rel="nofollow noreferrer">Image with the... | python|python-3.x|base64|html-email|gmail-api | 0 |
3,048 | 65,471,101 | Streamlit crashes when it runs a turtle drawing more than once | <h1>Intro</h1>
<p>I'm building a drawing app using the <em>Streamlit</em> library as a frontend and the <em>Turtle</em> library as the drawing engine.</p>
<h1>Issue</h1>
<p>Streamlit crashes and throw the following message when the drawing is invoked more than once:</p>
<pre><code>Exception ignored in: <function Ima... | <p>I solved the problem by running turtle in a child process. New <strong>frontend.py</strong> code:</p>
<pre><code>import multiprocessing
import streamlit as st
from backend import *
st.title("Turtle App")
title = st.text_input("Canvas Title", value="My Canvas")
width = st.number_input(&... | turtle-graphics|python-turtle|streamlit | 1 |
3,049 | 65,339,099 | Remove font's shadow in Sankey | <p>Is it possible to remove the white shadow of the font in the following sankey diagram?</p>
<p><a href="https://i.stack.imgur.com/wyI11.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wyI11.png" alt="enter image description here" /></a></p>
<pre><code> import plotly.graph_objects as go
... | <p>It certainly seems to <em><strong>not</strong></em> be possible. You can edit <em>some</em> text attributes through <code>f['data'][0]['textfont']</code> like:</p>
<pre><code>sankey.Textfont({
'color': '#2a3f5f', 'family': '"Open Sans", verdana, arial, sans-serif', 'size': 10
})
</code></pre>
<p>And as you... | python|plotly|plotly-python|sankey-diagram | 1 |
3,050 | 65,139,045 | python regular expression to get a token from the page | <p>I am trying to automate a few things in Python instead of manually doing the same thing again and again. Currently, I am stuck find the 'csrfmiddlewaretoken' from a site called dnsdumpster.com. I have written a regular expression for it, but it returns the whole tag that contains the 'csrfmiddlewaretoken'. I am only... | <p>You could use a capture group in the regex by adding parentheses</p>
<pre><code>match = re.search('name="csrfmiddlewaretoken" value="([0-9a-zA-z]+)', body)
if match:
csrfmiddlewaretoken = match.group(1)
else:
# deal with it
</code></pre>
<p>The risk is that minor changes in the returned page c... | python|python-re | 0 |
3,051 | 68,862,401 | Get missing rows in dataframe | <p>I have a dataframe like this:</p>
<pre><code>Object Period
A 202101
A 202102
A 202103
A 202105
A 202107
B 202102
B 202103
B 202104
B 202106
</code></pre>
<p>Now I would like for each object to iterate and get the missing period between the min and the max of the object, and get something like:</p>
<pre><code>Object ... | <p>You can convert the <code>Period</code> strings to Pandas period by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.to_period.html" rel="nofollow noreferrer"><code>dt.to_period()</code></a>. Then group by <code>Object</code> and aggregate to get the missing periods for each grou... | python|pandas|function|aggregation | 1 |
3,052 | 68,608,259 | How to update certain dictionary key value in python | <p>I have a below dictionary and want to update certain value of that dictionary</p>
<p><strong>for example :</strong></p>
<pre><code>my_dict = {'name':'Raju','surname':'XYZ','age':13,'dateofjoin':'12-Jul-2017'}
</code></pre>
<p>The value for <code>dateofjoin : 12-Jul-2017</code> need to update to <code>15-Aug-2017</c... | <pre><code>my_dict['dateofjoin'] = '15-Aug-2017'
my_dict['age']=18
</code></pre>
<p>This will directly update your existing dictionary. Once you run this, your output for my_dict will be</p>
<pre><code>{'name': 'Raju', 'surname': 'XYZ', 'age': 18, 'dateofjoin': '15-Aug-2017'}
</code></pre> | python | 2 |
3,053 | 71,714,917 | Getting most common element from list in Python | <p>I was able to use this piece of code to find the most common value if there was only one, however, it wouldn't work if there were multiple. I want it so that if there are multiple, it would just return None.</p>
<pre><code>numbers = [5, 3, 5, 3, 2, 6, 7]
my_dict = {}
for i in numbers:
if i in my_dict:
my... | <p>Use a library function to sort the numbers:</p>
<pre><code>s = sorted(numbers)
</code></pre>
<p>Check if the last two numbers are the same (then you have more than one max):</p>
<pre><code>one_max = s[-1] if (len(s)==1 or s[-1]!=s[-2]) else None
</code></pre> | python | 0 |
3,054 | 71,580,682 | Why can't I print a random number from 1 to a variable? | <p>I was making a python program where you type in an input, and it finds a random number from 1 to that input. It won't work for me for whatever reason.</p>
<p>I tried using something like this</p>
<pre><code>import random
a = input('pick a number: ')
print(random.randint(1, a))
input("Press enter to exit")
... | <p><code>randInt()</code> takes in two <code>int</code> data types, <code>input()</code> returns a <code>String</code>. So all you need to do is convert <code>a</code> into an <code>int</code>.</p>
<p>So do this</p>
<pre class="lang-py prettyprint-override"><code>import random
a = input('pick a number: ')
print(random.... | python|random|input | 2 |
3,055 | 5,533,996 | Numpy.putmask with images | <p>I have an image converted to a ndarray with RGBA values. Suppose it's 50 x 50 x 4.</p>
<p>I want to replace all the pixels with values <code>array([255, 255, 255, 255])</code> for <code>array([0, 0, 0, 0])</code>. So:</p>
<pre><code>from numpy import *
from PIL import Image
def test(mask):
mask = array(mas... | <p>A more concise way to do this is</p>
<pre><code>img = Image.open('test.png')
a = numpy.array(img)
a[(a == 255).all(axis=-1)] = 0
img2 = Image.fromarray(a, mode='RGBA')
</code></pre>
<p>More generally, if the items of <code>find</code> and <code>repl</code> are not all the same, you can also do</p>
<pre><code>find... | python|arrays|image|image-processing|numpy | 4 |
3,056 | 62,553,200 | Find out which features are in my components after PCA | <p>I performed a PCA of my data. The data looks like the following:</p>
<pre><code>df
Out[60]:
Drd1_exp1 Drd1_exp2 Drd1_exp3 ... M7_pppp M7_puuu Brain_Region
0 -1.0 -1.0 -1.0 ... 0.0 0.0 BaGr
3 -1.0 -1.0 -1.0 ... 0.0 0.0 ... | <p>You can use <code>pca.components_</code> (or <code>pca.components</code> depending on the sklearn version).
It has shape <code>(n_components, n_features)</code>, in your case <code>(2, n_features)</code> and represents the directions of maximum variance in the data, which reflects the magnitude of the corresponding ... | python|pandas|scikit-learn|statistics|pca | 1 |
3,057 | 67,278,730 | Limit the number of threads numpy 1.19.2 uses | <h1>Context</h1>
<p>My computer mysteriously shutsdown when all my cores go to 100% in <code>htop</code>.</p>
<p>I am running a simple program using <code>sklearn.impute.KNNImputer</code> from <code>scikit-learn</code></p>
<p>I have read that I need to limit the number of threads that <code>numpy</code> uses because <c... | <pre><code>import mkl
mkl.set_num_threads(1)
</code></pre>
<p>successfully restricts <code>numpy</code> 1.19.2 on <code>Ubuntu 18.04</code> to one cpu</p> | python|numpy|pthreads | 0 |
3,058 | 60,474,137 | bot.get_me() doesn't work and raises an error | <p>I can manually interact with the bot through url. For example when I send a request to api.telegram.com/bot-token/getMe
the bot's basic info is returned I even get correct results using requests library in python shell but when I try bot.get_me() in the python shell it doesn't work and says this</p>
<pre><code>Trac... | <p>Looks like you're having problems with your internet connection, i.e. the request could not be finished within the timeout of 5 seconds. Keep in mind that a lot of problems can happen unexpectedly in networking. In fact python-telegram-bot has a <a href="https://github.com/python-telegram-bot/python-telegram-bot/wik... | python-telegram-bot | 0 |
3,059 | 60,726,162 | How to add separate id to class and subclass in python | <p>I have two classes : Child class which inherits Ancestor class.
My goal is to add id attribute for each instance without override </p>
<p>Code example:</p>
<pre><code>class Ancestor(tensorflow.Module):
_id = 0
def __init__(self, some_list=):
super(Ancestor, self).__init__()
self.id = Ances... | <p>Python 3 users: see the bottom for a better solution using <code>__init_subclass__</code>.</p>
<hr>
<p>Don't hard-code the class name. Use <code>type(self)</code> to get access to the appropriate class for each instance.</p>
<pre><code>class Ancestor(object):
_id = 0
def __init__(self):
type(self... | python | 4 |
3,060 | 64,179,115 | How do I print a variable which is multiline string in the body of email in python | <p>I have this piece of code:</p>
<pre><code>l = ["Jargon", "Hello", "This", "Is", "Great"]
result = "\n".join(l[1:])
print result
</code></pre>
<p>output:</p>
<pre><code>Hello
This
Is
Great
</code></pre>
<p>And I am trying to print this to a body of an email ... | <p>When using <code>yagmail</code>, it works as intended.</p>
<pre class="lang-py prettyprint-override"><code>import yagmail
yag = yagmail.SMTP(
user=conf_yag['user'],
password=conf_yag['password'])
l = ["Jargon", "Hello", "This", "Is", "Great"]
result = "\n... | python|email-attachments|mime-message | 0 |
3,061 | 70,090,254 | Installing python package - error: Microsoft Visual C++ 14.0 or greater is required | <p>I am trying to install one package - cvxpy for python in Windows 10 and keep on getting errors related to C++ 14.0. I have followed similar questions and the answers posted:</p>
<ol>
<li><p>I have updated to VS 2022 and the corresponding build tools.</p>
</li>
<li><p>I have installed MSVCv143 and Windows 10 SDK 10.0... | <p>I was recently struggling with this issue myself, where I had MSVC installed but I could not get python to detect it. This is what solved it for me:</p>
<p>Clear the registry key that is mentioned in this SO thread:
<a href="https://stackoverflow.com/a/64389979/15379178">https://stackoverflow.com/a/64389979/15379178... | python-3.x|visual-studio|visual-c++|windows-10 | 1 |
3,062 | 70,038,604 | Deploy pytorch .pth model in a python script | <p>After successfully training my yolact model using a custom dataset I'm happy with the inference results outputted by eval.py using this command from anaconda terminal:</p>
<pre><code>python eval.py --trained_model=./weights/yolact_plus_resnet50_abrasion_39_10000.pth --config=yolact_resnet_abrasion_config --score_thr... | <p>I will just write the pseudocode here for you.</p>
<p>Step 1: Try loading the model using the lines starting from <a href="https://github.com/dbolya/yolact/blob/57b8f2d95e62e2e649b382f516ab41f949b57239/eval.py#L1097" rel="nofollow noreferrer">here</a> and ending <a href="https://github.com/dbolya/yolact/blob/57b8f2d... | python|opencv|pytorch|computer-vision | 0 |
3,063 | 70,062,968 | Beautification of the print output of the console | <p>I have an output in the Console. Unfortunately the texts are of different length and therefore looks very shifted. Is there an option that writes the texts below each other, no matter how many characters are in front of them, so that the output looks the way I want it to look?</p>
<p>I would not like to use another ... | <p>hi so you have to remove some \t cause they create tabs and you can remove them one by one to find one that you prefer</p>
<p>print('for example, this is a tab \t\t\t there is going to be space between them')</p>
<p>print('for example, there is no tab here and it is going to be next to each other')</p> | python|printing|console | 1 |
3,064 | 56,844,115 | How to attach file buffer to Django Mail Queue | <p>I have been trying to attach an xls buffer or a pdf buffer to a Django mail queue, but I couldn't. </p>
<p>I've tried using FileResponse or HttpResponse and converting to a Django file object but that fails, too.</p>
<p>This is what I tried:</p>
<pre><code>new_message = MailerMessage()
new_message.subject = "Test... | <p>You don't need to use FileResponse to attach a buffer. Suppose you have a BytesIO object buffer, you just need to convert it to a bytes-like object:</p>
<pre><code>content = buffer.read()
EmailMessage.attach('File Name.xls', content)
EmailMessage.send()
</code></pre> | python|django|attachment | 0 |
3,065 | 56,467,895 | How can I check for a digit or character in an SQL table column? | <p>I feel like this question has to have been answered somewhere, but I read through tons of posts and tried many variations of solutions and I can't get this to work. </p>
<p>I have a database table called <code>schedule</code> and I simply want to select the rows that contain a specific digit from the <code>days</c... | <p>Do you use MySQL?</p>
<p>MySQL doesn't have 'CONTAINS' operator, use 'LIKE' operator.</p>
<pre><code>"SELECT * FROM schedule WHERE days LIKE '%{}%'".format(day)
</code></pre>
<p><code>%</code> is the wildcard character that can be any characters.</p> | python|mysql|mysql-workbench | 0 |
3,066 | 66,054,280 | Python Pandas Dataframe Datetime Range | <p>Here is my code block:</p>
<pre><code>import pandas as pd
import datetime as dt
first_day = dt.date(todays_year, todays_month, 1)
print(first_day)
>2021-02-01
print(type(first_day))
>class 'datetime.date'>
</code></pre>
<p>My code runs successfully as below:</p>
<pre><code>df = pd.read_excel('AllServiceAc... | <p>Without a <a href="https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples">reproducible example</a> it's hard to know for sure. But try this. It uses the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer"><cod... | python|pandas|dataframe|date|datetime | 1 |
3,067 | 65,969,851 | Anyone knows how to code this polynomial into python:? | <p>Are there anyone help me how to write this polynomial into python language please, I’ve tried my best, but it’s too hard
P/s sorry for my bad grammar, i’m from vietnam
<a href="https://i.stack.imgur.com/lzF6D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lzF6D.png" alt="" /></a></p> | <p>Assuming you simply want to be able to get y result for either one of those equations, you can just do the following:</p>
<pre><code>import math
def y1(x):
return 4*(x*x + 10*x*math.sqrt(x)+3*x+1)
def y2(x):
return (math.sin(math.pi*x*x)+math.sqrt(x*x+1))/(exp(2*x)+math.cos(math.pi/4*x))
</code></pre>
<p>I... | python-3.x|polynomial-math | 0 |
3,068 | 66,111,665 | Numpy element-wise addition with multiple arrays | <p>I'd like to know if there is a more efficient/pythonic way to add multiple numpy arrays (2D) rather than:</p>
<pre class="lang-py prettyprint-override"><code>def sum_multiple_arrays(list_of_arrays):
a = np.zeros(shape=list_of_arrays[0].shape) #initialize array of 0s
for array in list_of_arrays:
a += arra... | <pre><code>np.sum(list_of_arrays, axis=0)
</code></pre>
<p>should work. Or</p>
<pre><code>np.add.reduce(list_of_arrays).
</code></pre> | numpy|matrix|numpy-ndarray|numpy-ufunc | 6 |
3,069 | 68,125,593 | pyspark: count number of rows written | <p>When I do</p>
<pre><code>df: DataFrame = ...
df.write.parquet('some://location/')
</code></pre>
<p>Can I track and report (for monitoring) the number of rows that was just written to <code>some://location</code>?</p>
<pre><code>df.write.parquet('some://location/')
# I imagine something like:
spark_session.someWeirdA... | <p>After doing some digging I found a way to do it:</p>
<ul>
<li>You can register a QueryExecutionListener (beware, this is annotated <code>@DeveloperApi</code> in the <a href="https://github.com/apache/spark/blob/0494dc90af48ce7da0625485a4dc6917a244d580/sql/core/src/main/scala/org/apache/spark/sql/util/QueryExecutionL... | python|apache-spark|pyspark|monitoring|metrics | 2 |
3,070 | 59,326,491 | Python AES encryption program is returning Memory Error | <p>So i am following a tutorial on AES implementation with python. It is an project which demanded to implement aes. Following is the code in Python which works fine on small files , but it i tried it ona 1 gb file and then the following error occured </p>
<p><strong>File "Desktop\AES\encrypting.py", line 73, in
... | <p>Fernet buffers all output before returning to prevent misuse before the data is verified. However, this approach is not suitable for encryption of large files without additional framing.</p>
<p>If you want to encrypt large files <code>cryptography</code> currently has no high level API for that, but you can use the... | python|encryption|aes|pycrypto|encryption-asymmetric | 0 |
3,071 | 72,839,382 | How to set the date format on wx.adv.DatePickerCtrl | <p>I am using the wxPython wx.adv.DatePickerCtrl and it presents the dates as "mm dd yyyy". I want "dd mm yyyy". How can I do this? I can see nothing in the <a href="https://docs.wxpython.org/wx.adv.DatePickerCtrl.html?highlight=datepicker#wx.adv.DatePickerCtrl" rel="nofollow noreferrer">docs</a></p... | <p>since wxPython aims at a <strong>truly native user interface</strong> the control uses the users system format (on Windows f.i. <em>Time & Language, Regional format data</em>)</p> | wxpython | 0 |
3,072 | 63,011,123 | Create table error in MYSQL database using Python | <p>I wanted to create a database of my data which have been stored in files .For this I used file handling to read data from the stored files and input into the table of my database. But it shows error given below.</p>
<p>Is it the correct way to switch data storage option from files to database.</p>
<p>The error occur... | <p>on this line</p>
<pre><code>CREATE TABLE PETROL...
</code></pre>
<p>you are missing the closing parenthesis after <code>Date DATE</code></p> | python|mysql|database|file|exception | 0 |
3,073 | 62,999,521 | Scraping data from the <script> tag using python | <p>I am looking for a way to scrape data from <a href="https://stonks.gg/products/search?input=Superior%20Fragment" rel="nofollow noreferrer">here</a> to a list. The data I want to extract is in</p>
<p>rangeSelector -> series -> data</p>
<p>It is a collection of the price of a specific item at a certain time. I n... | <p>You can parse the data with <code>re</code>/<code>json</code> modules.</p>
<p>For example:</p>
<pre><code>import re
import json
import requests
url = 'https://stonks.gg/products/search?input=Superior%20Fragment'
html_data = requests.get(url).text
d1 = json.loads(re.search(r'Unit Price \(Buy\).*?(\[\[.*?\]\])', ht... | python|html|web|web-scraping | 0 |
3,074 | 62,413,589 | How to swap items in the list at any point? | <pre><code>l = [ 1 ,2 ,3, 4,
5 ,6 , 7,8,
9,10,11,12,
13,14,15,16,
17,18,19,20,
21,22,23,24
]
</code></pre>
<p>When swapping with next line is done at the middle.
Intended Output: </p>
<pre><code>l = [ 1 ,2 ,7,8,
5 ,6 ,3,4,
9,10,15,16,
13,14,11,12... | <p>Here is one way to do that: </p>
<pre><code>a = int(input()) # Swap index
cl = 4 # Amount of columns
l = [1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16,
17, 18, 19, 20,
21, 22, 23, 24]
l2 = l.copy()
for i,v in enumerate(l):
if i in range(a,len(l),cl*2):
l2[i] = l[i+cl... | python|list|algorithm|dictionary|data-structures | 0 |
3,075 | 62,091,006 | Guess Counting Control | <p>I'm starting my studies in Python and I was assigned the Task to write code for a guessing game in which I have to control the total tries the player will have. I've described the functions, they're working (I believe...haha) but I can't make to "reset" the game when a wrong guess is input...
I wrote this:... | <p>The rub is in that you have a state of a game that you are tracking as global variables <code>guess_count</code> and <code>count_control</code></p>
<p>This is an example of why python and other languages provide classes and objects:</p>
<pre><code>class Game:
def __init__(self):
self.guess_count = []
... | python|python-3.x|function | 0 |
3,076 | 62,406,227 | How does Python compare two lists of unequal length? | <p>I am aware of the following:</p>
<ul>
<li><code>[1,2,3]<[1,2,4]</code> is <code>True</code> because Python does an element-wise comparison from left to right and <code>3 < 4</code></li>
<li><code>[1,2,3]<[1,3,4]</code> is <code>True</code> because <code>2 < 3</code> so Python never even bothers to compa... | <p>The standard comparisons (<, <=, >, >=, ==, !=, in , not in ) work exactly the same among lists, tuples and strings. </p>
<p>The lists are compared element by element.</p>
<p>If they are of variable length, it happens till the last element of the shorter list</p>
<p>If they are same from start to the length... | python|python-3.x|list | 1 |
3,077 | 35,516,412 | Python: How to get all of the local variables defined in another module | <p>Is there a way to get a reference to the local variables defined in a different module?</p>
<p>for example, I have two files: framework.py and user_code.py:</p>
<p><strong>framework.py:</strong></p>
<pre><code>from kivy.app import App
class BASE_A:
pass
class MyApp(App):
def on_start(self):
'''H... | <p>New-style classes in Python have a method named <code>__subclasses__</code> which returns a list of all direct subclasses that have been defined so far. You can use that to get a hold of the <code>A</code> class in your example, just call <code>BASE_A.__subclasses__()</code> (if you're using Python 2, you'll also ne... | python | 1 |
3,078 | 58,793,612 | Why can't my two docker containers communicate? | <p>I have two docker containers running Flask, just a simple backend/frontend example bit I was running through to learn docker and flask.</p>
<p>My frontend is:</p>
<pre><code>from flask import Flask, jsonify
import requests
import simplejson
import json
app = Flask(__name__)
@app.route('/')
def hello():
uri =... | <p>Can you share the <code>docker run</code> command you're using?</p>
<p>Are you exposing the ports with the <code>-p</code> flag?</p>
<pre><code>docker run -p 5000:5000 ...
</code></pre>
<p><strong>[Update]</strong>: Depending on your docker install and config, you may not be able to use that IP. Docker considers ... | python|python-3.x|api|docker|flask | 2 |
3,079 | 58,620,480 | cx_oracle insert with select query not working | <p>I am trying to insert in database(Oracle) in python with cx_oracle. I need to select from table and insert into another table.</p>
<pre><code> insert_select_string = "INSERT INTO wf_measure_details(PARENT_JOB_ID, STAGE_JOB_ID, MEASURE_VALS, STEP_LEVEL, OOZIE_JOB_ID, CREATE_TIME_TS) \
... | <p>As mentioned by Chris in the comments to your question, you want to use cursor.execute() instead of cursor.executemany(). You also want to use bind variables instead of interpolated parameters in order to improve performance and reduce security risks. Take a look at the <a href="https://cx-oracle.readthedocs.io/en/l... | python-2.7|insert|cx-oracle | 0 |
3,080 | 73,354,433 | Python, Tkinter, Can not insert text in textbox | <p>Everything works except for the insertion of the text.</p>
<p>Does anyone have an idea what the reason can be?</p>
<pre class="lang-py prettyprint-override"><code>def appendLog(txt):
logOutput.insert("end", txt)
root = tk.Tk()
root.title("Blablabla")
root.minsize(width=850, height=400)
root... | <p>I think <code>logOutput = tk.Text(root)</code> should change to <code>logOutput = tk.Entry(root) </code>
and you should add <code>root.mianloop()</code> at the end of the code.
You aslo should delete <code>state='disable'</code> in the end of <code>logOutput.configure(fg="#aaaaaa",bg="#181818",fo... | python|tkinter | 0 |
3,081 | 73,237,539 | Can I know the actual exception caught by the method? | <p>I have a scenario where I call a library method that catches any exception that occurs and re-throws another exception. Is there a way I can get the original exception? Please find a minimal reproducible code below:</p>
<pre><code>def f():
raise KeyError("key not found")
def g():
try:
f()
... | <p>When you raise an exception in an <code>except</code> clause, the new exception's <a href="https://docs.python.org/3/library/exceptions.html#exception-context" rel="nofollow noreferrer"><code>__context__</code> attribute</a> is set to the original exception.</p>
<pre><code>try:
g()
except Exception as e:
pri... | python|python-3.x|exception | 2 |
3,082 | 31,468,188 | How to combine np string array with float array python | <p>I would like to combine an array full of floats with an array full of strings. Is there a way to do this?</p>
<p>(I am also having trouble rounding my floats, insert is changing them to scientific notation; I am unable to reproduce this with a small example)</p>
<pre><code>A=np.array([[1/3,257/35],[3,4],[5,6]],dty... | <p>Use <code>dtype=object</code> in your numpy array; like bellow:</p>
<pre><code>np.array([1, 'a'], dtype=object)
</code></pre> | python|arrays|string|floating-point|scientific-notation | 1 |
3,083 | 49,164,985 | How to load module into python with argv | <p>I want to load oneRunParams.py into my current program but won't know where it is till I run it. I want to have it as an input argument, accessed through argv. I was using:</p>
<p>from oneRunParams import *</p>
<p>I now want to replace this with something that will do the same only with the path to oneRunParams sp... | <p>You can use <a href="https://docs.python.org/2/library/functions.html#__import__" rel="nofollow noreferrer"><code>__import__</code></a>:</p>
<p>Here is <code>test.py</code>:</p>
<pre><code># test.py
import sys
filename = sys.argv[1]
f = __import__(filename[:-3]) # This removes the `.py` extension
f.test()
</code>... | python|python-3.x|python-import | 2 |
3,084 | 49,029,020 | Python Error - TypeError: bad operand type for unary -: 'NoneType' | <p>I have the next for loop inside a function</p>
<pre><code>def Cost_F(Y, Ypred, m):
for i in range(0,m):
# Y and Ypred
X = np.matmul(-Y, np.log10(Ypred))
</code></pre>
<p>Dimensions for Y and Ypred are both <strong>(10,1)</strong>.</p>
<p>Type of Y and Ypred => <strong>class 'numpy.matrixlib.d... | <pre><code>-Y
</code></pre>
<p>does not work as you are trying to use it. What you mean is:</p>
<pre><code>-1*Y
</code></pre>
<p>What python is trying to do in your case is:</p>
<pre><code>None - Y
</code></pre>
<p>which will obviously not work. That is, beacuse it interprets <code>-</code> to be an operand with a... | python|numpy|typeerror | 8 |
3,085 | 25,299,681 | Google App Engine 413 error (Request Entity Too Large) | <p>I've implemented an app engine server in Python for processing html documents sent to it. It's all well and good when I run it locally, but when running off the App engine, I get the following error:</p>
<p>"413. That’s an error. Your client issued a request that was too large. That’s all we know."</p>
<p>The requ... | <p>Looks like it was because I was making a GET request. Changing it to POST fixed it.</p> | python|google-app-engine|http-status-code-413 | 4 |
3,086 | 60,319,340 | Regular expression to extract all sentences that start and end with the same word | <p>Given a string of sentences, I need to extract a list of all of the sentences which start and end with the same word.</p>
<p>e.g.</p>
<pre class="lang-py prettyprint-override"><code># sample text
text = "This is a sample sentence. well, I'll check that things are going well. another sentence starting with anoth... | <pre><code>text = "This is a sample sentence. going to checking whether it is well going. another
sentence starting with another."
sentences = re.split('[.!?]+', text)
result = []
for s in sentences:
words = s.split()
if len(words) > 0 and words[0] == words[-1]:
result.append(s.strip())
print(res... | python|regex | 0 |
3,087 | 3,094,576 | Debugging python using Textmate? | <p>I'd like to use TextMate for debugging python scripts. I'm looking for suggestions on the best way to accomplish this. I found these "solutions" -- is there a better approach?</p>
<p><a href="http://www.libertypages.com/clarktech/?p=192" rel="nofollow noreferrer">http://www.libertypages.com/clarktech/?p=192</a> <... | <p>TextMate is not an IDE, it's just an awsome editor.</p>
<p>Therefore you'll find that these features might not be available, and that you should just debug from the provided command line.</p> | python|debugging|textmate|textmatebundles | 0 |
3,088 | 30,284,967 | Pyspark - reducer task iterates over values | <p>I am working with pyspark for the first time.</p>
<p>I want my reducer task to iterates over the values that return with the key from the mapper just like in java.</p>
<p>I saw there is only option of accumulator and not iteration - like in add function add(data1,data2) => data1 is the accumulator.</p>
<p>I want ... | <p>Please use reduceByKey function. In python, it should look like</p>
<pre><code>from operator import add
rdd = sc.textFile(....)
res = rdd.map(...).reduceByKey(add)
</code></pre>
<p>Note: Spark and MR has fundamental diffrences, so it is suggested not to force-fit one to another. Spark also supports pair functions ... | python|mapreduce|apache-spark|pyspark|reducers | 0 |
3,089 | 67,104,569 | Templates while exporting Jupyter notebook to PDF with nbconvert | <p>Someone knows how to use templates while exporting Jupyter notebook to PDF with nbconvert? Where did I get templates?</p>
<p>Thanks</p> | <p>A few built-in <a href="https://nbconvert.readthedocs.io/en/latest/external_exporters.html" rel="nofollow noreferrer">formats</a> are available by default: html, pdf, webpdf, script, latex</p>
<p>You can use the below code to export your code to a pdf:</p>
<pre class="lang-py prettyprint-override"><code>$ jupyter nb... | python|templates|jupyter-notebook | 1 |
3,090 | 64,110,189 | Convert 2020-09-01T00:00:00-05:00 timestamp to dd-mm-yyyy | <p>Hi I am trying to convert the following time format</p>
<pre><code>2020-08-28T13:42:00.298363-05:00
</code></pre>
<p>to</p>
<pre><code>28-Sept-2020
</code></pre>
<p>I am using the following code but it does not work.</p>
<pre><code>from datetime import datetime
start_time = "2020-08-28T13:42:00.298363-05:00&q... | <p>Your code is missing the closing quote at the end of the datetime format string, which is causing the error message you see. You also have an issue with the actual format string as well, as pointed out by @ChrisCharley</p>
<p>This <code>start_period_obj = datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%f.%-s-%z)... | python|datetime | 0 |
3,091 | 72,456,554 | Is there a faster way I can count the number of occurrences of a number in a list? | <p>I am trying to write a function to count the occurrences of a number in a list, and the order is ascending according to the number (from 0 to the maximum value in the list), not the occurrences. Here's the function I wrote:</p>
<pre><code>def sort_counts(sample):
result = []
for i in range(max(sample)+1):
... | <p>Counter from collections module is a nice way to count the number of occurrences of items in a list</p>
<pre class="lang-py prettyprint-override"><code>from collections import Counter
lst = [1,2,2,3,3,4,1,1,1,1,2,5]
# create a counter object
c = Counter(lst)
# get the counts
[c[i] for i in range(max(c)+1)]
# [0, 5, ... | python|list|count | 2 |
3,092 | 72,359,399 | Calculate average of extreme values in Netcdf - Python | <p>I have started working with large datasets from Copernicus Marine Service.
I am downloading the netcdf files through motuclient and then i can process (using xarray) the data to calculate the mean value for each position of the grid. I would like to calculate the average of the 20 highest values (extremes). How can ... | <p><code>dask.array</code> has <a href="https://docs.dask.org/en/latest/generated/dask.array.topk.html#dask.array.topk" rel="nofollow noreferrer"><code>topk</code></a> and <a href="https://docs.dask.org/en/latest/generated/dask.array.argtopk.html#dask.array.argtopk" rel="nofollow noreferrer"><code>argtopk</code></a> me... | python|dask|netcdf|python-xarray|netcdf4 | 0 |
3,093 | 51,053,709 | Trying to use NER (Named Entity Recognition), but I can't get the server running | <p>I've been following the instructions from this github repo: <a href="https://github.com/caihaoyu/sner" rel="nofollow noreferrer">https://github.com/caihaoyu/sner</a>. I installed NER from the official website: <a href="https://nlp.stanford.edu/software/CRF-NER.html" rel="nofollow noreferrer">https://nlp.stanford.edu... | <p>Please see this documentation for using the Stanford CoreNLP server:</p>
<p>Overall info: <a href="https://stanfordnlp.github.io/CoreNLP/index.html" rel="nofollow noreferrer">https://stanfordnlp.github.io/CoreNLP/index.html</a></p>
<p>Server info: <a href="https://stanfordnlp.github.io/CoreNLP/corenlp-server.html"... | java|python-3.x|github|stanford-nlp|named-entity-recognition | 0 |
3,094 | 50,902,696 | Web development with just Python Flask | <p>Is it just fine to build a website with a python backend that interacts with the database and use flask to display it on html? flask can also get inputs from the html form and from there python can manipulate it. Is there any security concern with it?</p> | <p>Yes it is perfectly safe, provided you take safeguards and use best practices. Flask is my favorite Python web server framework - extremely lightweight and flexible, makes the fewest assumptions about your application.</p> | python|ajax|flask | 1 |
3,095 | 50,813,307 | What's the proper way to use the Python module scholar.py? | <p>I'm kind of new to both Python and the command line, but I'm trying to use the Python module <a href="https://github.com/ckreibich/scholar.py/blob/master/README.md" rel="nofollow noreferrer">https://github.com/ckreibich/scholar.py/blob/master/README.md</a> in order to fetch certain results from Google Scholar. After... | <p>The problem here is that you're trying to write a command intended for the command line inside of python, you can't do that, and that's why you're setting `SyntaxError'</p>
<p>The problem you are having at the command line as specified in your comment:</p>
<blockquote>
<p>"-bash: scholar.py: command not found" <... | python|python-module|google-scholar | 1 |
3,096 | 50,657,326 | matplotlib + locale de_DE + LaTeX = space btw. decimal separator and number | <p>if I run the following code with enabled LaTeX (<code>usetex=True</code>), then I get a strange spacing between the decimal comma and the first following number. Has anyone an idea how to fix this?</p>
<pre><code>import matplotlib.pyplot as plt
import locale
plt.style.use('classic')
locale.setlocale(locale.LC_NUME... | <p>Using the LaTeX-Package <code>icomma</code> solves the problem!</p>
<pre><code>import matplotlib.pyplot as plt
import locale
plt.style.use('classic')
locale.setlocale(locale.LC_NUMERIC, 'de_DE')
plt.rc('text', usetex=True)
font = {'family':'serif','size':14}
plt.rc('font',**font)
# Add the following two lines to ... | python-3.x|matplotlib|latex | 2 |
3,097 | 61,384,887 | export dataframe excel directly to sharepoint (or a web page) | <p>I created a dataframe to jupyter notebook and I would like to export this dataframe directly to sharepoint as an excel file. Is there a way to do that?</p> | <p>You can add the SharePoint site as a network drive on your local computer and then use a file path that way. Here's <a href="https://collab365.community/map-a-sharepoint-document-library-as-a-network-drive/" rel="nofollow noreferrer">a link</a> to show you how to map the SharePoint to a network drive. From there, ju... | python|pandas|dataframe|jupyter-notebook | 0 |
3,098 | 61,334,751 | Improve speed parsing XML with elements and namespace, into Pandas | <p>So I have a <code>52M</code> xml file, which consists of <code>115139</code> elements.</p>
<pre><code>from lxml import etree
tree = etree.parse(file)
root = tree.getroot()
In [76]: len(root)
Out[76]: 115139
</code></pre>
<p>I have this function that iterates over the elements within <code>root</code> and inserts... | <p>You declare an empty dataframe, so you might get a speedup if you specify the index ahead of time. Otherwise, there is constant expansion of the dataframe. </p>
<pre><code>df = pd.DataFrame(index=range(0, len(root)))
</code></pre>
<p>You could also create the dataframe at the end of the loop.</p>
<pre><code>vals ... | python-3.x|xml|pandas|parsing|lxml | 1 |
3,099 | 56,134,697 | How to replace/overwrite default header of EmailMultiAlternatives | <p>Environment: Ubuntu 18.10, Python 2.7.15, Django 1.11.16</p>
<p>I'm trying to send an email containing an inline image. I have the following code:</p>
<pre><code>msg = EmailMultiAlternatives(some_subject, some_body, 'from@some-domain.com', ['to@some@domain'])
img_data = open('path/to/image.png', 'rb').read()
img ... | <p>If you look at the source code, you'll see that <code>EmailMultiAlternatives</code> is a subclass of <code>EmailMessage</code>, which itself has a class attribute: </p>
<pre><code>mixed_subtype = 'mixed'
</code></pre>
<p>So if you create your own subclass to override this, you should get what you need:</p>
<pre><... | python|django|email-attachments|amazon-ses|email-headers | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.