Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
5,700 | 66,507,034 | Jupyter ipython kernel dies on large file loading | <p>I have a huge binary file of size ~10gbs which I want to load into a pandas dataframe on my Jupyter notebook. I am using the following code for creating the dataframe:</p>
<pre><code>df = pd.DataFrame(np.fromfile('binary_file.dat', dtype = mydtype)) #the file has over 20 columns of dtype '<f8'
</code></pre>
<p>Ev... | <p>Try</p>
<pre><code>df = pd.read_csv('.....\binary_file.dat' , sep="however you dat-file is separated",engine ='python')
</code></pre> | python|python-3.x|pandas|jupyter-notebook|ipython | 0 |
5,701 | 66,410,803 | Understanding of fig, ax, and plt when combining Matplotlib and Pandas | <p>I'm trying to get a better understanding of how figure, axes, and plt all fit together when combining Matplotlib and Pandas for plotting. The accepted <a href="https://stackoverflow.com/questions/29568110/how-to-use-ax-with-pandas-and-matplotlib/29568196#29568196">answer here</a> helped me connect Matplotlib and Pan... | <p><code>plt.xticks()</code> only works on the "current" ax. You should use <code>ax.set_xticks()</code>, <code>ax.set_xticklabels()</code> and <code>ax.tick_params()</code> instead.</p>
<p><code>plt.xticks()</code> is a rather old function that is still supported, mimicking similar matlab code, born in a tim... | python|pandas|matplotlib | 1 |
5,702 | 66,753,634 | Add column of WordNet synonyms to DataFrame | <p>I have the below example DataFrame in the var output_table:</p>
<pre><code>Job Title ReqID Word TFAbs
Agree to Agree Manager R4 Trust 2
Agree to Agree Manager R4 agree 2
Agreement Manager R2 Trust 5
</code></pre>
<p>I want to check synonyms of each word in column "Word" using WordNet. For t... | <p>You could use .assign() to add the new values as a column. In order to do so, I first created a new column.</p>
<pre><code>column = []
for ind in output_table.index:
word = output_table['Word'][ind]
syn = list()
for synset in wn.synsets(word):
for lemma in synset.lemmas():
syn.ap... | pandas|dataframe|loops|nltk|wordnet | 0 |
5,703 | 64,665,578 | matplotlib bar chart - only size-1 arrays can be converted to Python scalars | <p>I want to matplotlib bar chart but I am giving below errors for one variable(g) (no-problem with the second variable) I have fetched these values from sqlite queries in python and its shape is like:</p>
<pre><code>g= [(11,), (7,), (6,), (3,), (1,), (4,), (7,), (0,), (0,), (0,), (172,)]
error
TypeError: only size-1 a... | <p>Use:</p>
<pre><code>g1 = np.array(g).flatten()
</code></pre>
<p>Output:</p>
<pre><code>array([ 11, 7, 6, 3, 1, 4, 7, 0, 0, 0, 172])
</code></pre> | python|matplotlib | 0 |
5,704 | 64,852,610 | does setMouseCallback method not work with tkinter? | <p>I am working on Slideshow application.
Basically this shows all the pictures in a certain directory in every 5 seconds, and if you click the picture changes.
It had worked so well until I mixed it with <code>tkinter</code>.
It seems like my <code>setMouseCallback</code> method doesn't work anymore...
Any helps?</p>
... | <p>Tkinter has it's own method of capturing button presses and it is probably blocking the cv2 callback.</p>
<p>You can register a call back for a button press in tkinter using</p>
<pre><code>root.bind("<Button-1>", nameOfCallbackFunction)
</code></pre>
<p>Worth noting that tkinter does not work with in... | python|opencv|tkinter | 0 |
5,705 | 65,046,403 | Name not defined, even with global variable? | <p>So I'm trying to write a function to calculate an estimated value of pi, which is then subtracted from the actual value of pi. However, when I run it, I get an error saying that name 'piCalc' is not defined. Any ideas as to what I did wrong?</p>
<pre><code>import math
import random
def computePI (numThrows):
circl... | <p>You have not declared global in your function</p>
<pre><code>import math
import random
def computePI (numThrows):
global piCalc
circleCount = 0
for i in range(numThrows):
xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)
distance = math.hypot(xPos, yPos)
if distance &l... | python|python-3.x|nameerror | 0 |
5,706 | 65,257,711 | Jupyter keeps producing a 500 error no matter what (new and existing notebooks) | <p>I am running into a 500: Internal Server Error when launching Jupyter, and trying to open or create a notebook. I checked multiple threads here, but nothing worked. I also tried installing, reinstalling, installing from within PyCharm, and from the commandline. I used the steps on Juypter official website as well. I... | <p>I recommend that you update your python version. Make sure that your jupyter installation is running with the new version and not 3.6.0.</p> | python|jupyter-notebook|jupyter|jupyter-lab|jupyter-console | 0 |
5,707 | 65,406,991 | How to fetch the resource ID of an virtual machine in azure using python | <p>how to get the resource ID of an VM in azure with using subscriptionID, vm name and resource group</p> | <h1>We can use rest api to get resource id.</h1>
<p><a href="https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/get#code-try-0" rel="nofollow noreferrer">Offical Doc: Virtual Machines - Get</a></p>
<p><a href="https://i.stack.imgur.com/rta9w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.... | python|python-3.x|azure | 0 |
5,708 | 71,888,174 | Predicting future data using a single column as input data | <p>I am having trouble with predicting future values with my input set. I am fairly new with statsmodels so I am not sure if it is even possible to do with this much input data.</p>
<p>This is the DataFrame that I am using. (Note: Starts at index 5 since I had to filter some data)</p>
<pre><code> year suicides_no
5... | <p>This is a rather open-ended problem. I can certainly show you how you might write some code to make <strong>a</strong> prediction, but I think discussing how to make a <strong>good</strong> prediction is beyond the scope of StackOverflow. It will be very dependent on a good understanding of the problem domain.</p>
<... | python|pandas|dataframe|matplotlib|statsmodels | 0 |
5,709 | 72,076,771 | Class Input Question for user not showing up on console when taking user input for OOP in Python | <p>I am making a bank simulator that needs input from the user regarding the name of their "bank account".</p>
<p>Here is my code:</p>
<pre><code>class Account():
def __init__(self,balance=0):
self.owner = input("What is your full name, again?: ")
self.balance = balance
</code></pre>
<p>However,... | <p>You need to create an instance of <code>Account</code>, so that <code>__init__</code> gets called.</p>
<pre><code>class Account():
def __init__(self,balance=0):
self.owner = input("What is your full name, again?: ")
self.balance = balance
a = Account()
</code></pre>
<p>However, you should ... | python|python-3.x | 1 |
5,710 | 10,275,971 | How to tell if there is a missing item in request.REQUEST in Django | <p>I have five keys that I want to check are in request.REQUEST. So I want to make sure first_name, last_name, age, gender, and location are all in request.REQUEST. Then if one or more are not there, I want to tell the which attributes are missing.</p>
<p>Is there a way to do this without using a bunch of if stateme... | <p>Create a set of the keys that you expect, and a set of the keys that were returned, and intersect them:</p>
<pre><code>expected = set(['first_name', 'last_name', 'age'])
got = set(request.REQUEST.keys())
if expected.issubset(got):
# Request contained everything you expected
# Bonus points: check if field w... | python|django | 1 |
5,711 | 10,745,595 | What causes a method wrapped via a metaclass to forget self when called? | <p>The following code allows me to follow the operation of how metaclasses work. However, when
lines 21 and 22 are uncommented, <code>Metaclass.__init__</code> will fail because the <code>self</code> argument is not passed to the wrapped method. What is causing <code>VerboseFunction.__call__</code> to not pass the nee... | <p>The <code>VerboseMetaclass</code> class can be modified, and the <code>VerboseFunction</code> class can be removed. <code>VerboseMetaclass.wrap</code> should be altered as follows, and <code>wrap_function</code> should be added.</p>
<pre><code>@classmethod
def wrap(cls, key, value):
sign('VerboseMetaclass')
... | python|metaclass | 2 |
5,712 | 5,393,557 | adding nodes to xml file with same node name but different attributes with Python Dom | <p><br>
is it possible to add two nodes with the same name to a xml document ?<br>
That is something like that :<br>
<strong>Initial file :</strong></p>
<pre><code><Files>
<Filter>
</Filter>
</Files>
</code></pre>
<p><strong>Wanted file :</strong></p>
<pre><code><Files>
<Filter... | <p>Not sure where your code is going wrong, as you've not provided a testable example. I'm not particularly familiar with minidom, I prefer lxml.</p>
<p>I suspect you need to instantiate each new child node separately.</p>
<p>This works for me:</p>
<pre><code>>>> import xml.dom.minidom
>>>
>>... | python|xml|dom|minidom | 3 |
5,713 | 5,429,577 | showing progress while spawning and running subprocess | <p>I need to show some progress bar or something while spawning and running subprocess.
How can I do that with python? </p>
<pre><code>import subprocess
cmd = ['python','wait.py']
p = subprocess.Popen(cmd, bufsize=1024,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.close()
outputmessag... | <p>Since the subprocess call is blocking, one way to print something out while waiting would be to use multithreading. Here's an example using threading._Timer:</p>
<pre><code>import threading
import subprocess
class RepeatingTimer(threading._Timer):
def run(self):
while True:
self.finished.w... | python|subprocess|progressdialog | 6 |
5,714 | 64,226,516 | How to set mocked exception behavior on Python? | <p>I am using an external library (github3.py) that defines an internal exception (github3.exceptions.UnprocessableEntity). It doesn't matter how this exception is defined, so I want to create a side effect and set the attributes I use from this exception.</p>
<p>Tested code not-so-minimal example:</p>
<pre><code>impor... | <p>So based on your example, you don't really need to mock <a href="https://github.com/sigmavirus24/github3.py/blob/master/src/github3/exceptions.py#L287" rel="nofollow noreferrer">github3.exceptions.UnprocessableEntity</a> but only the incoming <a href="https://github.com/sigmavirus24/github3.py/blob/master/src/github... | python-3.x|unit-testing|exception|pytest|pytest-mock | 1 |
5,715 | 64,607,822 | copy dataframe lines and replace on the same dataframe | <p>I have a dataframe in which I have 2 records that are with few values, I wanted to replace those records with others with more values, make a copy.
Does anyone know how to do this on pandas or vaex?</p>
<p><a href="https://i.stack.imgur.com/9cgiM.png" rel="nofollow noreferrer">image</a></p>
<p>wanted to replace the ... | <p>If I understand you correctly, this should be straightforward in vaex:</p>
<pre><code>df['new_col'] = df.func.where(df.day_of_week==148, 140, df.day_of_week)
</code></pre>
<p>In vaex the new column will be virtual, i.e. not take any memory. So it does not matter if you overwrite your existing one, or keep a separate... | python|pandas|vaex | 0 |
5,716 | 70,058,771 | Finding continued fractions of pi with Stern-Brocot tree | <p>Im trying to use python to determine the continued fractions of pi by following the stern brocot tree. Its simple, if my estimation of pi is too high, take a left, if my estimation of pi is too low, take a right.</p>
<p>Im using <code>mpmath</code> to get arbitrary precision floating numbers, as python doesn't suppo... | <p>You need to include the term prec=xxxxx in each fdiv operation, eg:<code>mp.fdiv(stern_frac[0],stern_frac[1])</code> becomes <code>mp.fdiv(stern_frac[0],stern_frac[1], prec=200)</code></p> | python|math|mpmath | 0 |
5,717 | 10,953,548 | Correct way to save nested formsets in Django | <p>I have a 3-level Test model I want to present as nested formsets. Each Test has multiple Results, and each Result can have multiple Lines. I am following <a href="http://yergler.net/blog/2009/09/27/nested-formsets-with-django/" rel="nofollow noreferrer">Yergler's method</a> for creating nested formsets, along with... | <p>When I used <code>extra</code> on formsets in similar situation I ended up having to include all the required fields from the model in the form, as HiddenInputs. A bit ugly but it worked, curious if anyone has a hack-around.</p>
<p><strong>edit</strong><br>
I was confused when I wrote above, I'd just been working o... | python|django|django-forms | 1 |
5,718 | 11,058,199 | Why does SciPy's loadmat throw a MemoryError when reading a 200 MB Matlab struct | <p>I'm using the following code to try to load a MAT file in Python. I can load it without issue in MATLAB. </p>
<pre><code>from scipy.io import loadmat
test_filename = 'test_data.mat' #This is a struct
data =loadmat(test_filename, struct_as_record=True)
</code></pre>
<p>Running that code produces this error:</p>
<p... | <p>I found the answer.</p>
<p>Loadmat can't deal with heavily nested structures. In the data set I was given, three of the struct fields, 'waves, neurons, contvars' were cell arrays. Each member of that cell array was a struct. Some of the fields of those structs were themselves cell arrays. Those cell arrays had one ... | python|matlab|file-io|scipy|mat-file | 3 |
5,719 | 11,307,538 | Is there an equivalent Matlab dot function in numpy? | <p>Is there an equivalent Matlab <code>dot</code> function in numpy? </p>
<p>The <code>dot</code> function in Matlab:
For multidimensional arrays A and B, dot returns the scalar product along the first non-singleton dimension of A and B. A and B must have the same size.</p>
<p>In numpy the following is similar but no... | <p>In MATLAB, <code>dot(A,B)</code> of two matrices <code>A</code> and <code>B</code> of same size is simply:</p>
<pre><code>sum(conj(A).*B)
</code></pre>
<p>Equivalent Python/Numpy:</p>
<pre><code>np.sum(A.conj()*B, axis=0)
</code></pre> | python|matlab|numpy | 10 |
5,720 | 63,492,418 | Plotting a graph with neworkx using a csv file as co-occurence matrix | <p>I made a co-occurrence matrix using sklearn CountVectorizer and saved it as a csv file. Let's say it looks something like that :</p>
<pre><code> Unnamed: 0 a b c d
0 a 0 1 0 0
1 b 2 0 1 0
2 c 0 1 0 3
3 d 0 0 1 0
</code></pre>
<p>What would be the easiest way t... | <p>As @ALollz has mentioned in the comments, you can use <code>G=nx.from_pandas_adjacency(df)</code> to create a graph from your pandas dataframe and then visualize it with <code>pyvis.network</code> as follows:</p>
<pre><code>import pandas as pd
import numpy as np
import networkx as nx
from pyvis.network import Networ... | python|pandas|networkx | 1 |
5,721 | 56,544,310 | Two player Tic-tac toe Python program not running completely | <p>I am trying to write a simple two player tic-tac toe game but whenever I run it always says its a tie. I can't seem to find the problem with it so I was wondering if someone would assist me in figuring out why it always does that. I've attached the sample code below.</p>
<pre><code>import random
import os
def dis... | <p>The error may be in the function <code>position_check</code>, where you check if the board position is equal to <code>""</code>, while you may want to check if it is still a space <code>" "</code>:</p>
<pre><code>def position_check(board,position):
if board[position] == "":
return True
else:
... | python | 0 |
5,722 | 69,741,459 | How to assign new column to existing DataFrame in pandas | <p>I'm new to pandas. I'm trying to add new columns to my existing DataFrame but It's not getting assigned don't know why can anyone explain me what I'm missing this is what i tried</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data = {"test":["mkt1","mkt2","mkt3"],
... | <p>Pandas <code>assign</code> method returns a new modified dataframe with a new column, it does not modify it in place.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame(data = {"test":["mkt1","mkt2","mkt3"],
"... | python|pandas | 1 |
5,723 | 60,869,676 | Appending to a new row when converting from xml to csv in python | <p>Im having trouble writing each <code>control_code</code> along with its <code>description</code> on a new row rather than having it in the same row but different column (see image). Any ideas would be appreciated!</p>
<p>This is the <a href="https://nvd.nist.gov/static/feeds/xml/sp80053/rev4/800-53-controls.xml" re... | <p>Reset <code>list_nodes=[]</code> when you want a new row. Right now you have:</p>
<pre><code>for element in root.findall('control'):
list_nodes=[]
...
for controlStmt in element.findall('statement'):
...
csvwriter.writerow(list_nodes)
</code></pre>
<p>And it should be:</p>
<pr... | python|xml|csv|elementtree | 0 |
5,724 | 66,000,324 | Python Scrapy: How do you run your spider from a seperate file? | <p>So I've created a spider in scrapy that now successfully targets all the text I want.</p>
<p>How exactly do you execute this spider in another python file? Cause I want to be able to pass it new URLs/store the data it finds within a dictionary and then a dataframe.</p>
<p>Cause at the moment I can only get it to run... | <p>In Scrapy doc <a href="https://docs.scrapy.org/en/latest/topics/practices.html" rel="nofollow noreferrer">Common Practices</a> you can see <a href="https://docs.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script" rel="nofollow noreferrer">Run Scrapy from a script</a></p>
<pre><code>import scrapy
fro... | python|scrapy|screen-scraping | 1 |
5,725 | 69,106,967 | Jupyter matplotlib widget: place toolbar horizontally over plot? | <p>Consider the following Jupyter notebook Python code:</p>
<pre class="lang-py prettyprint-override"><code>%matplotlib widget
import matplotlib.pyplot as plt
from ipywidgets import widgets, Layout
from IPython.display import display
out_widget_plot = widgets.Output()
with out_widget_plot:
with plt.style.context(&... | <p>Well, this was a short joy; as of ipympl 0.8.4, the below hack does not work anymore: <a href="https://github.com/matplotlib/ipympl/issues/411" rel="nofollow noreferrer">Getting back toolbar on left (if set to top position) in 0.8.4? · Issue #411 · matplotlib/ipympl</a> - so the work I put in to get the hack working... | python|matplotlib|jupyter-notebook|ipywidgets | 1 |
5,726 | 69,141,545 | create a multidimensional array field in Django model | <p>I get multidimensional arrays must-have array expressions with matching dimensions error from Django when I try to insert data into my model, below is my model and the data format i have</p>
<pre><code>effect = ArrayField(
ArrayField(
models.IntegerField(
blank=True,
... | <p>This is not an issue with the ArrayField, but with the Django Admin. The default admin widget expects the Array to be 1-dimensional (both when displaying as when updating).</p>
<p>If you want to use the django-admin you can use something like <a href="https://django-jsonform.readthedocs.io/en/stable/guide/arrayfield... | python|arrays|django|django-models | 0 |
5,727 | 72,498,432 | Python: Naming of columns and merging two data frames into one | <p>I would like to give my sample data column names. I'd like the columns be named after objective functions and their decision variables like this: f_1, f_2, h, b, l, t</p>
<p>Sample data:</p>
<pre><code>sampler = qmc.LatinHypercube(d=4)
u_bounds = np.array([5.0, 5.0, 10.0, 10.0])
l_bounds = np.array([0.125, 0.125, 0... | <p>Like the error says, you can't <code>concat</code> a dataframe with a numpy array.</p>
<p>So you should transform y, the numpy array, into a df to concat with another df:</p>
<pre><code>y = np.zeros((2,2))
y = pd.DataFrame(y) #this
pd.concat([df, y])
</code></pre>
<p><strong>Reproducing error:</strong></p>
<p><a h... | python|pandas|dataframe|optimization | 1 |
5,728 | 72,569,074 | How do I test start_server_http is working for Prometheus | <p>I have created this monitoring class that updates some Counter Metrics according to some logic. I have attached the code. Please can someone explain to me why would my registry be empty even after I add the test metric.</p>
<pre><code>import logging
from prometheus_client import (
CollectorRegistry,
Counter,... | <p>before = reporter.registry.get_sample_value('bycounter', ['level1', 'WSJ2'])</p>
<p>The counter is being renamed as <code>bycounter_total</code></p> | python|testing|prometheus|prometheus-alertmanager | 0 |
5,729 | 72,782,449 | nltk stopwords - AttributeError: 'function' object has no attribute 'words' | <p>This is my import:</p>
<pre><code>from nltk.corpus import stopwords
</code></pre>
<p>And this is my code:</p>
<pre><code>def stopwords(text):
"""a function for removing the stopword"""
sw = stopwords.words('english')
# removing the stop words and lowercasing the selected words
text = [w... | <p>Hello the problem is that you've named your function like the nltk.corpus module. You should find an other name for your function and it'll work I think.</p> | python|error-handling|nlp|nltk|stop-words | 1 |
5,730 | 68,384,466 | CustomMaskWarning when using Keras OxfordPets code | <p>I'm on a project that is taking the Oxford Pets code <a href="https://keras.io/examples/vision/oxford_pets_image_segmentation/" rel="nofollow noreferrer">https://keras.io/examples/vision/oxford_pets_image_segmentation/</a> and modifying it various ways. We're getting the following warning (when running on Google Col... | <p>As mentioned by @Henrique Mendonça, This warning appears when we use Resnet model on Tfv2.5.</p>
<p>These warnings will not hamper your code execution, still you can suppress these warnings using following code</p>
<pre><code>import logging, os
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL&q... | python|keras|tf.keras | 5 |
5,731 | 59,337,219 | How can I change my x-axis ticks to show every date on my x-axis in my chart? | <p>I downloaded Bitcoin price data and I want to plot the results. This is my code to retrieve price data:</p>
<pre><code>import requests
periods = '86400'
resp = requests.get('https://api.cryptowat.ch/markets/bitfinex/btcusd/ohlc', params={'periods': periods})
data = resp.json()
df = pd.DataFrame(data['result'][per... | <p>Try this:</p>
<pre><code>plt.xticks(price.index, price.index, rotation=45)
</code></pre>
<p>As per the <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xticks.html" rel="nofollow noreferrer">documentation</a> you can provide the index <strong>and</strong> the labels.</p>
<p><a href="https://i.s... | python|matplotlib|charts|axis|bitcoin | 0 |
5,732 | 63,254,419 | pandas: groupby apply using numba | <p>Using pandas v1.1.0.</p>
<p>In the pandas docs there is a nice example on how to use numba to speed up a <code>rolling.apply()</code> operation <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html#rolling-apply" rel="nofollow noreferrer">here</a></p>
<pre><code>import pandas as pd
import... | <p>Have you tried Bodo for this? It's built on top of Numba and supports Pandas directly. For example:</p>
<pre><code>pip install bodo
</code></pre>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
import bodo
def mad(x):
return np.fabs(x - x.mean()).mean()
np.random.seed(0)
... | python|pandas|pandas-groupby|numba|bodo | 4 |
5,733 | 63,219,811 | Algorithm to print all valid combinations of n pairs of parentheses | <p>This is a very popular interview question and there are tons of pages on the internet about the solution to this problem.
eg. <a href="https://stackoverflow.com/questions/31479647/calculating-the-complexity-of-algorithm-to-print-all-valid-i-e-properly-opene">Calculating the complexity of algorithm to print all valid... | <p>It looks like a wrong approach.</p>
<p>As you can see in your failure case <code>(())(())</code> your algorithm may only obtain such string by placing parenthesis around <code>())(()</code>. Unfortunately the latter is not a valid combination, and cannot be generated: the prior recursive call only builds valid ones.... | python|algorithm|combinations | 0 |
5,734 | 62,898,228 | Scrapy spider is repeating scraped data | <p>from scrapy.spiders import Spider
from ..items import QtItem</p>
<pre><code>class QuoteSpider(Spider):
name = 'acres'
start_urls = ['any_url']
def parse(self, response):
items = QtItem()
all_div_names = response.xpath('//article')
for bks in all_div_names:
name = all_div_names.xpath('/... | <p>You use a for loop but not use for loop variable 'bks'.</p>
<pre><code> for bks in all_div_names:
name = bks.xpath('//span[@class="css-fwbz9r"]/text()').extract()
price = bks.xpath('//h2[@class="css-yr18fa"]/text()').extract()
sqft = bks.xpath('//div[@class="css-1t... | python-3.x|scrapy|data-science | 1 |
5,735 | 58,701,646 | Getting mouse relative motion even at the border of screen | <p><strong>Purpose:</strong>
I want to have the relative movement of my mouse even when she is on the border of my screen (so I can't compute the vector between 2 moment).</p>
<p><strong>Application:</strong>
I want to make a helper for mortar shooting in a game called 'squad', you control the mortar with your mouse. ... | <p>Rather than warping the cursor to the center of the screen, could you just warp it back a little from the edge? It seems like anti-cheat software would have a harder time detecting that.</p> | python|mouse|motion | 0 |
5,736 | 59,021,295 | How to convert dictionaries to nested dictionary? | <p>I have the dictionary as shown below:</p>
<pre><code>dict1 = {'K7': ['k07 = v07', ''], 'K2': ['k02 = v02', ''], 'K01': ['k2 = v2', 'k02 = v2', ''], 'K3': ['k1 = v1', ''], 'K02': ['k2 = v2', '']}
</code></pre>
<p>I am trying to make a nested dictionary as follows:</p>
<pre><code>dict1 = [{'K7': {'k07' : 'v07'}}, {... | <p>You can use <code>dict</code> with a list comprehension:</p>
<pre><code>dict1 = {'K7': ['k07 = v07', ''], 'K2': ['k02 = v02', ''], 'K01': ['k2 = v2', 'k02 = v2', ''], 'K3': ['k1 = v1', ''], 'K02': ['k2 = v2', '']}
new_d = [{a:dict(i.split(' = ') for i in b if i)} for a, b in dict1.items()]
</code></pre>
<p>Output:... | python|python-2.7|dictionary | 2 |
5,737 | 59,570,611 | PySide2/QT for Python : Widget not updating / GUI Freezing | <p>I'm using pyside2 with python. On a Qmainwindow, I've created a QpushButton and a Qlabel. The label is hidden at the init of the mainWindow, and the pushButton is connected to the following function, defined in mainWindow : </p>
<pre><code>def buttonPushed(self):
self.label.show()
self.doStuff()
... | <p>If a task is executed for a long time, it will block the Qt event loop causing certain ones to not work properly since the events cannot be transmitted causing the window to freeze, generating as an effect what you indicate.</p>
<p>So in those cases you must execute that task in another thread (assuming that task d... | python|pyside2 | 4 |
5,738 | 25,127,134 | Intelligently Execute Python Functions in Order | <p>I'm curious what the relative merits are of calling functions in a program using a decorator to create an ordered map of the functions, and iterating through that map, versus directly calling the functions in the order I want. Below are two examples that yield the same result:</p>
<pre><code>PROCESS_MAP = {}
def... | <p>I would prefer the second (non-decorated) approach in all situations I can think of. Explicitly naming the functions is direct, obvious, and clear. Consider asking the question "where is this function called from?" and how you might answer that in each case.</p>
<p>There is a possible bug in your decorator where it... | python|decorator | 4 |
5,739 | 70,922,483 | QGraphicsView scale scene gives weird results | <p>Inside the <code>QGraphView</code>'s <code>mouseMoveEvent</code> I'm calculating the difference of the mouse position to scale the view's scene by scaling a transform. This seems to work well, but it scales in a weird way. Like it almost feels like it makes the items slide as the anchor to which it scales from doesn... | <p>The scale transformation is always applied on the origin point of the matrix (the top left corner). This causes the scene rect to adapt inside the view.</p>
<p>To scale around a specific point, you need to first translate the matrix, then apply the scale, and finally restore the translation back:</p>
<pre><code> ... | python|qt5|pyside2|qgraphicsview | 2 |
5,740 | 60,220,406 | remove new line spaces from json file and reading it in pandas dataframe | <pre><code>{"country":"India","city":"Chennai","lat":13.0827,"lon":80.2707,"isp":"Facebook, Inc.","query":"157.240.23.19"}
{"country":"India","city":"Mumbai","lat":19.076,"lon":72.8777,"isp":"Facebook, Inc.","query":"31.13.79.18"}
{"country":"India","city":"Bhadohi","lat":25.3953,"lon":82.5703,"isp":"Railtel Enterprise... | <p>Your sample json file is incorrect, If you are using lines=True, each object should be in new line, and not in single line.</p>
<pre><code>{"country":"India","city":"Chennai","lat":13.0827,"lon":80.2707,"isp":"Facebook, Inc.","query":"157.240.23.19"}
{"country":"India","city":"Mumbai","lat":19.076,"lon":72.8777,"is... | python|json|pandas|newline|spaces | 0 |
5,741 | 60,280,364 | Kivy - Saving object's values changed in Popup, so that after closing it, when I open the popup again it opens with new values | <p>I want to change some button labels of a class in a popup and retain the new label after reopening the popup. If you run my app, you can see that after pressing "Press me" button, a popup appears with a button with a label "Default", after pressing on it, it changes the label to "New". I want to be able to close the... | <p>One way that you can do it, is by keeping a reference to the popup.<br>
The <code>py</code> side:</p>
<pre class="lang-py prettyprint-override"><code>Window.clearcolor = (1, 1, 1, 1)
Window.size = (800, 480)
class MyGrid(Widget):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
... | python|python-3.x|kivy|kivy-language | 0 |
5,742 | 60,119,971 | Seaborn/Matplotlib categorical plot markers size by count of observations | <p>I want to scale markers on a plot of 2 categorical variables by count of observations.</p>
<p>I am using <code>seaborn.pairplot</code> for easiness, because I have quite a lot of variables (features). But I don't think there is an argument for a case like this.</p> | <p>I am guessing that what you are looking for is a <a href="https://rpkgs.datanovia.com/ggpubr/reference/ggballoonplot.html" rel="nofollow noreferrer">balloon plot</a>, also known as a matrix bubble chart or a <a href="https://stackoverflow.com/questions/50399802/python-categorical-bubble-plot">categorical bubble plot... | python|matplotlib|seaborn | 1 |
5,743 | 5,630,186 | Python: Find item in multidimensional list | <p>I have a list of lists, a snippet of which is below:</p>
<p><code>x_attrib = []</code></p>
<pre><code>self.x_attrib.append(["Is_virtual", False, 'virtual', 'flag'])
self.x_attrib.append(["X_pos", None, 'pos/x', 'attrib'])
self.x_attrib.append(["Y_pos", None, 'pos/y', 'attrib'])
</code></pre>
<p>I want make a func... | <p>If I understand correctly, you need to something like this:</p>
<pre><code>def find_it(key):
for index, sublist in enumerate(lists):
if sublist[0] == key:
return index
</code></pre>
<p>Having said that your code looks like you are solving the more general problem incorrectly. i.e. that list l... | python|list|find|multidimensional-array | 4 |
5,744 | 67,757,732 | Pygame not exiting even after receiving keypress | <p>So I'm trying to exit the pygame using a function but its not working. It's definitely entering the function block but for some reason is not quitting after the keypress.</p>
<pre class="lang-py prettyprint-override"><code>import pygame
from pygame import mixer
from random import *
from math import *
pygame.init()
... | <p>"running" is not associated with anything. You need a while running loop.</p>
<pre><code>running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((120,120,120))
pygame.display.update()
</c... | python|pygame|game-loop | 0 |
5,745 | 66,868,387 | Generating a numpy array of ones and zeros with weighted chance for ones equal 0.11 | <p>How can I generate a size 10000 Numpy array of 1's and 0's where getting 1's is weighted by a chance of 0.11?</p> | <p>Use numpy's <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html" rel="nofollow noreferrer">random choice</a>.</p>
<pre><code>from numpy.random import choice
ratio = 0.11
draw = choice([0,1], 10000, p=[1-ratio, ratio])
# Evaluate
sum(draw)
# 1119
</code></pre> | python|numpy|probability | 0 |
5,746 | 66,833,120 | How can I annotate text/mark in matplotlib based on an if condition? | <p>I have 3 pandas series plotted where the values are:</p>
<pre><code>date_series = date1,date2...
price_series = price1,price2...
factor_series = factor1,factor2...
</code></pre>
<p>and so i wish to annotate/highlight it on a matplotlib figure automatically based on an if condition which is when factor_series > ... | <p>If possible, I would recommend putting your series together in a DataFrame indexed by date for easier access. Then you can add a scatterplot of the subset DataFrame: <code>df[df['factor'] > 4]</code> to your secondary y-axis object with corresponding text and markers.</p>
<pre><code>import pandas as pd
import num... | python|pandas|matplotlib|data-visualization | 3 |
5,747 | 66,931,837 | Pandas copy previous day's data based on key and date range | <p>I have below dataframe in Pandas. I want to roll/copy the data for the missing dates withing the start/end dates.</p>
<p>I want to create rows for 3-MAR-21 and 4-MAR-21 as per below ---</p>
<p>For 3-MAR-21, all the three loans L1, L2 and L3 rows should be copied from 2-MAR-21</p>
<p>For 4-MAR-21, only L1 and L3 shou... | <p>You could try:</p>
<pre class="lang-py prettyprint-override"><code># 4-MAR-21
rows = df.loc[df['DATE'] == '2-MAR-21, :]
rows['DATE] = '3-MAR-21'
df = df.append(rows, ignore_index=True)
# 5-MAR-21
rows = df.loc[
(df["DATE"] == "2-MAR-21") & ((df["Loan ID"] == "L1") | (... | python|pandas | 0 |
5,748 | 42,652,111 | How to delete queried results from Splunk database? | <p>Query is on Splunk DB data delete: </p>
<p>My requirement:</p>
<p>I do a query to splunk, based on time stamp, "from date" & "to date".</p>
<p>After I got the list of all events results between the timestamp, I want to delete these list of events from the Splunk database.</p>
<p>Each queried results data wil... | <p>I'm not sure you can actually delete them to free up storage space.
As written <a href="https://answers.splunk.com/answers/1484/how-do-i-delete-events.html" rel="nofollow noreferrer">here</a>, what you can do is simply mask the results from ever showing up again in the next searches.</p>
<p>To do this, simply pipe ... | python|splunk-query | 0 |
5,749 | 42,979,837 | python not defined error function/argument | <p>I am having a problem with an error message about tk not being defined? </p>
<p>How can I get around this, I thought I defined it. I was wondering if it was a problem with the <code>window = tk</code> but when I remove one and vice versa the define problem still occurs.</p>
<pre><code>import tkinter
import os
win... | <p>Your code is a bit namespace messed up. Some parts of your code follows the format <code>from tkinter import *</code> provides. While some parts followed the format <code>import tkinter</code>. You <em>can</em> do both, but it's not preferred.
Many people like to use import <code>tkinter as tk</code> since it's eas... | python|python-2.7|authentication|tkinter|interface | 0 |
5,750 | 72,149,677 | Two 2D array's of coordinates, finding if any of the coordinates from the different arrays are within a set distance of one another (python) | <p>I have been trying to figure out how to make it so there is two 2D arrays, each containing a number of arrays that have x and y coordinates for set objects of the same class. The two arrays contain coordinates of objects of two different classes. I've been trying to essentially do a scan of each points surroundings,... | <p>Split into two lists:</p>
<pre><code>apples = [x for x in objects if isinstance(x, Apple)]
oranges = [x for x in objects if isinstance(x, Orange)]
</code></pre>
<p>Then compare all of them against each other, brute-force, i.e. O(n^2):</p>
<pre><code>colliding_pairs = [
(a, o)
for a in apples
for o in ora... | python|arrays|multidimensional-array | 0 |
5,751 | 72,371,137 | Python GUI Tutorials | <p>I'm looking for good longform tutorials on creating GUIs with Python. I've found one previous answers, but it's quite old (10 years) and closed. What would you recommend? Any good example repos?</p>
<p>I want to have a dynamic user interface that allows the user to tab between different screens, enter data, and se... | <p>you have this tuturial in first link in English with PYQT and guizero in the second link(in portuguese)</p>
<p><a href="https://www.youtube.com/watch?v=MOItX2aKTGc" rel="nofollow noreferrer">https://www.youtube.com/watch?v=MOItX2aKTGc</a></p>
<p><a href="https://www.youtube.com/channel/UCiTnSna5qYf9tC0mBScw2Rg" rel=... | python|python-3.x|user-interface|dynamic|graphics | 0 |
5,752 | 65,807,468 | module "android" has no attibute "Android()" | <p>My python interpreter on my phone says there is no <em>"attribute"</em> Android in the android module, which i am able import:</p>
<blockquote>
<p>module 'android' has no attribute 'Android()'</p>
</blockquote>
<p>I am pretty sure it's supposed to be a class. I am using android 10 and I have an a71 samsung... | <p>Try</p>
<pre><code>import androidhelper
droid = androidhelper.Android()
</code></pre>
<p>or</p>
<pre><code>import androidhelper as android
droid=android.Android()
</code></pre> | python-3.x | 0 |
5,753 | 65,720,929 | PyGame only shows black screen | <pre><code>import pygame, sys
#from pygame.locals import *
def load_map(path):
f = open(path + ".txt","r")
data = f.read()
f.close()
data = data.split("\n")
game_map = []
for row in data:
game_map.append(list(row))
return(game_map)
#main
pygame.init()
... | <p>You have to target surfaces, <code>screen</code> and <code>display</code>. However, just 1 of this surfaces can be associated to the window.</p>
<blockquote>
<pre class="lang-py prettyprint-override"><code>screen = pygame.display.set_mode(window_size, 0, 32)
</code></pre>
</blockquote>
<p>Therefore you will only see... | python|pygame|pygame-surface | 0 |
5,754 | 65,623,799 | StaleElementReferenceException even after adding the wait while collecting the data from the wikipedia using web-scraping | <p>I am a newbie to the web-scraping. Pardon my silly mistakes if there are any.</p>
<p>I have been working on a project in which I need a list of movies as my data. I am trying to collect the data from the <a href="https://en.wikipedia.org/wiki/Lists_of_Bollywood_films" rel="nofollow noreferrer">wikipedia</a> using we... | <p>To collect the data from the wikipedia <a href="https://en.wikipedia.org/wiki/Lists_of_Bollywood_films" rel="nofollow noreferrer">Lists of Bollywood films</a> using <a href="https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491">Selenium</a> and <a href="/questions/tag... | python-3.x|selenium|selenium-webdriver|web-scraping|webdriverwait | 1 |
5,755 | 50,701,591 | when i take input from user and wanna convert that input,the system errors | <p>[enter image description here][1]</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>from word2number import w2n
w2n.word_to_num('one')
1
q = input('write your number le... | <p>Please post the full code as text that you are trying that is giving you errors. </p>
<p>But the code from the Word2number documentation is working fine for me. </p>
<p><a href="https://pypi.org/project/word2number/" rel="nofollow noreferrer">https://pypi.org/project/word2number/</a></p>
<p><strong>Python 3</stro... | python-2.x | 0 |
5,756 | 51,001,489 | Download text data from HTML link in Python | <p>Hi I want to download delimited text which is hosted on a HTML Link. (The link is accessible on a Private network only, so can't share here). </p>
<p>In R, following function solves the purpose (all other functions gave "Unauthorized access" or "401" error)</p>
<pre><code>url = 'https://dw-results.ansms.com/dw-pla... | <p></p>
<pre><code>def geturls(path):
yy=open(path,'rb').read()
yy="".join(str(yy))
yy=yy.split('<a')
out=[]
for d in yy:
z=d.find('href="')
if z>-1:
x=d[z+6:len(d)]
r=x.find('"')
x=x[:r]
x=x.strip(' ./')
#
... | python|pandas|url|https | 0 |
5,757 | 3,973,325 | Remove all html in python? | <p>Is there a way to remove/escape html tags using lxml.html and not beautifulsoup which has some xss issues? I tried using cleaner, but i want to remove all html.</p> | <p>I believe that, this code can help you:</p>
<pre><code>from lxml.html.clean import Cleaner
html_text = "<html><head><title>Hello</title><body>Text</body></html>"
cleaner = Cleaner(allow_tags=[''], remove_unknown_tags=False)
cleaned_text = cleaner.clean_html(html_text)
</co... | python|tags|xss|lxml | 12 |
5,758 | 35,224,186 | Conda create environment fails with Error: No packages found | <p>This is on Windows (32bit) and the full error message is: <code>Error: No packages found in current win-32 channels matching: package_name</code> I have been unable to get the conda package management to work.<br>
Reinstalling Anaconda didn't solve the problem.</p> | <p>The problem is that I had created a file in my home directory .condarc which had the following contents:</p>
<pre><code>create_default_packages:
- PACKAGE_NAME
</code></pre>
<p>I don't know how I did it. I think I had followed half asleep an instruction to create the non existent package <code>package_name</cod... | python|conda | 0 |
5,759 | 35,116,689 | TensorFlow exited abnormally with code 137 | <p>I'm trying convolutional neural net using TensorFlow.</p>
<p>Though I could success some training, the script failed with</p>
<pre><code>Process Python exited abnormally with code 137
</code></pre>
<p>when I just changed the training data.
The data sizes of the first and second data are the same, and
I could tr... | <p>Exit code 137 means that your Python process was killed by the SIGKILL signal. It's hard to say for certain, but one possibility is that your process was killed by the OOM (out-of-memory) killer. Check <code>/var/log/messages</code> to see if there is any information about why your process was killed.</p>
<p><a hre... | python|tensorflow | 8 |
5,760 | 34,998,939 | return all columns when filtering matrix with Numpy pythonically | <p>I have tried several methods and cannot get both columns back. The filtering works, but only returns one column.</p>
<pre><code>import numpy as np
<<<<read in some data, now get counts>>>>
unique, counts = np.unique(data[0::,2], return_counts=True)
x = np.asmatrix((unique, counts))
x = x.ast... | <p>You may consider using <code>asarray</code> instead of <code>asmatrix</code> :</p>
<pre><code>x = np.asarray((unique, counts))
</code></pre>
<p>Then it should work as you except.</p>
<p>When I run your code on python 3.4 / numpy 1.10.1, if i use <code>asmatrix</code> I get:</p>
<pre><code>>>> x = np.asm... | python|numpy | 2 |
5,761 | 35,215,937 | python maze using recursion | <p>I want to solve a maze using recursion. The program opens a text file like this one:</p>
<pre><code>10 20
1 1
10 20
-----------------------------------------
| | | | | | | | | |
|-+ +-+-+ +-+ + +-+ + + +-+-+ +-+-+ + + |
| | | | | | | | | |
| + +-+ + + +-+-+-+ + + + + + +... | <p>Looking at your code I see several errors. You do not handle the entry and exit row/column pairs correctly. (10,20) is correct for this maze, if you assume that every other row, and every other column, is a grid line. That is, if the <code>|</code> and <code>-</code> characters represent infinitely thin lines that h... | python|recursion|backtracking|maze | 2 |
5,762 | 26,830,707 | pass python argument to awk script | <p>I am using a python script which takes in few arguments:</p>
<pre><code> pipeline.py -t reg.bed -n WT -s run -ID 567
</code></pre>
<p>Inside the python script, i am using awk script which should take in the arguments passed above:</p>
<p>For instance, it should take the argument by name, ID = 567 and print it in ... | <p>use awk's <code>-v</code> option</p>
<pre><code>awk -v id=567 '{print id, $0}' input.txt > output.txt
</code></pre>
<p>Although this awk script is so simple, surely you should implement it in python.</p> | python|awk|arguments | 1 |
5,763 | 56,781,521 | How to glue (stitch) two python code together? | <p>I am wondering what is the best way to put together codes from different python files into a new python file.
Lets say the first file <code>1.py</code>would consist of:</p>
<pre class="lang-py prettyprint-override"><code>def(...):
a=1
b=2
return c=a+b
</code></pre>
<p>And another file <code>2.py</code>... | <p>If you're on a unix shell:</p>
<p><code>cat 1.py 2.py > 3.py</code></p> | python|python-3.x | 6 |
5,764 | 44,934,026 | Mock functions in a function dict in python | <p>Let's say I have a class declared like below:</p>
<pre><code>class SampleClass(object):
def __init__(self):
self.ops = {
'key 1': self.function_a,
'key 2': self.function_b
}
def function_a(self):
print('Inside a')
def function_b(self):
print('Inside b')
... | <p>It's possible to patch dictionary entries, here's an example that's very similar to what you posted:</p>
<pre><code>from mock import patch, Mock
class SampleClass():
def __init__(self):
self.ops = {
'key 1': self.function_a,
'key 2': self.function_b
}
def function_a... | python|python-2.7|unit-testing|mocking | 2 |
5,765 | 61,523,952 | Pygame, if key pressed and then released action | <p>I am experimenting with physics for a game and wanted to try how you can speed up.</p>
<p>My current code is this</p>
<pre><code> def left(self):
self.x -= 1 * self.xvelocity
if not self.xvelocity == 10:
self.xvelocity += 1
def right(self):
self.x += 1 * self.xvelocity
... | <p>You can try breaking down your left/right inputs as follows:</p>
<pre><code>1) left. Increase velocity to left till max
2) right. increase velocity to right till max
3) L+R. Invalid
4) No input. Velocity resets to zero
5) L->R/R->L. left velocity resets to zero and now increases in right direction. vice-v... | python|pygame | 1 |
5,766 | 57,906,930 | Why is Python subprocess not working as expected with named_pipe? | <p>I am using python subprocess to run a mysqlimport command. For tracking the uploading progress, I am using a named pipe and pipe_viewer.
Here is another similar <a href="https://stackoverflow.com/questions/53981907/getting-pv-output-with-subprocess">problem</a>. </p>
<p>The subprocess Pipes are running without any ... | <p>To get the ">" redirection to work correctly, you most likely need to set "shell=True" to the Popen function.</p> | mysql|python-3.x|subprocess|pipe|pv | 1 |
5,767 | 56,208,340 | Verify which numbers are prime in the list | <p>I am trying to verify which numbers in the list are primes.</p>
<pre><code>vetor = [2,3,4,5,11,15,20]
divisions_list = []
def isprime():
divisions = 0
i = 0
for i in range(1, vetor[i+1]):
if i % i == 0:
divisions = divisions + 1
divisions_list.append... | <p>You already had a piece of code that takes a number and checks if it is a prime or not, then instead of using it you reinvented the wheel and broke it in the process (for example, you re-used <code>i</code> which caused a division by zero and tried to check if a list is equal to 2 instead of checking if its length i... | python|loops|iteration|primes | 2 |
5,768 | 56,123,769 | How to check the feature names for the one hot label using keras.utils.to_categorical? | <p>I would like to check the vocabulary after applying keras.util.to_categorical.</p>
<p>Eg. </p>
<pre><code>from keras.utils import to_categorical
l = to_categorical(np.asarray([1,2,3,4,5,6]))
</code></pre>
<p>when I print l[0]</p>
<p>My result:</p>
<pre><code>array([0., 1., 0., 0., 0., 0., 0.], dtype=float32)
</... | <p>The coding is fixed, positional one-hot encoding. <code>0</code> will always have a 1 in the first column, <code>1</code> will always have a 1 in the 2nd column and so on. Better understood using examples - </p>
<pre><code>from keras.utils import to_categorical
import numpy as np
arr1 = np.asarray([0,1,2])
arr2 = ... | python|keras | 1 |
5,769 | 18,683,909 | Sqlalchemy query returns incorrect and outdated results (for sqlite engine) | <p>I'm using sqlalchemy with sqlite engine (development server) and just discovered that after update query, queries in next web-requests return outdated data set (that depends on fact which thread is used for the request, as I understand there is a pool of threads). </p>
<p>I'm using <code>scoped_session</code> and t... | <p>You could issue a <a href="http://docs.sqlalchemy.org/en/rel_0_8/orm/session.html#sqlalchemy.orm.session.Session.refresh" rel="nofollow"><code>Session.refresh</code></a> with the database object you want to get the value of.</p> | python|sqlite|sqlalchemy|pyramid | 1 |
5,770 | 55,184,318 | keyboard shortcut for sublime text new version | <p>I have this code to create a shortcut to run current file in <code>sublimeREPL</code>:</p>
<pre><code>{
"keys": ["ctrl+alt+b"],
"command": "run_existing_window_command",
"args": {
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
}
</code></pre>
<p>But with the su... | <p>This is the code:</p>
<pre><code>{
"keys": ["ctrl+alt+b"],
"command": "repl_open",
"args": {
"cmd": ["python", "-u", "-i", "$file_basename"],
"cwd": "$file_path",
"encoding": "utf8",
"extend_env": {"PYTHONIOENCODING": "utf-8"},
"external_id": "python",
"syntax": "Packages/Python/Python... | python|python-3.x|sublimetext3|sublimerepl | 0 |
5,771 | 55,544,952 | Order of Operation for python | <p>My question is to solve </p>
<p><code>result = 8 - 4 ** 3 / 5 // 2 % 15 * 2</code></p>
<p>This is what I did</p>
<p>First: 4^3=64</p>
<p>second: 5//2=2</p>
<p>third: 64/2=32</p>
<p>4th: 32%15=2</p>
<p>5th: 2*2=4</p>
<p>final: 8-4=4</p>
<p>I expected the output of 8-4=4 but the actual output was -4.0.</p> | <p><code>result = 8 - 4 ** 3 / 5 // 2 % 15 * 2</code></p>
<p>In your particular case, the <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow noreferrer">operator precedence</a> is as follows:</p>
<p>First, <code>**</code></p>
<p>Second, <code>*</code>, <code>/</code>, <c... | python | 1 |
5,772 | 57,639,529 | Make the same cooldown for multiple discord.py bot commands? | <p>This is written in <code>discord.py</code>.</p>
<p>I have multiple commands similar to the following:</p>
<pre><code>@bot.command(name ="hi")
async def hi(ctx):
link = ["https://google.com", "https://youtube.com"]
chosen = random.choice(link)
url = chosen
embed = discord.Embed(title="Your Link", de... | <p>This is how the <code>cooldowns</code> decorator is defined in the code:</p>
<pre><code>def cooldown(rate, per, type=BucketType.default):
def decorator(func):
if isinstance(func, Command):
func._buckets = CooldownMapping(Cooldown(rate, per, type))
else:
func.__commands_co... | python|discord|discord.py | 3 |
5,773 | 57,413,721 | How can i generate random variables using np.random.zipf for a given range of values? | <p>I have a given price range and i had used random uniform to get random generated random results from it. How can i introduce <code>np.random.zipf</code> to do the same ?</p>
<p>i have tried the following : </p>
<pre><code>a = np.random.zipf((randint(1, 6000000)), size=None)
print(a)
</code></pre>
<p>But it seems ... | <p>While @RobinNicole is right wrt Zipf distribution, you could simulate truncated Zipf using discrete sampling. Along the lines</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
def Zipf(a: np.float64, min: np.uint64, max: np.uint64, size=None):
"""
Generate Zipf-like random variables,
... | python|random | 2 |
5,774 | 57,560,093 | Can't create a python virtual environment on Ubuntu 18.04 | <p>I'm a complete beginner to Ubuntu and I'm trying to create a virtual environment on Ubuntu 18.04. I had one running and it was working just fine, but I don't know what I did and know I cant get it to run.</p>
<p>I deleted my old <code>env/</code> file and now I'm trying to create a new one using</p>
<pre><code>pyt... | <blockquote>
<p>just reinstall your python3-venv</p>
</blockquote>
<pre><code>apt-get purge python3-venv
apt-get install python3-venv
</code></pre>
<blockquote>
<p>and then create the virtualenv</p>
</blockquote>
<pre><code> python3.7 -m venv venvTest
</code></pre>
<blockquote>
<p>if you have different versi... | python|ubuntu|pip|python-venv | 1 |
5,775 | 42,502,100 | Python Flask retrieve POST data from AngularJS AJAX | <p>I am using Angular AJAX call to send data to my Flask backend for natural language processing.</p>
<p>AJAX code:</p>
<pre><code>$scope.processText = function(){
$http({
method: "POST",
url: "http://127.0.0.1:5000/processText",
headers: {
'Access-Control-Allow-Origin': '*',
... | <p>You need to use jsonify to return the object since jsonify creates a flask.Response() object that automatically has the Content-Type header.</p>
<p>Try using this: <code>return jsonify(data)</code></p>
<p>Alternatively, if you want to return the string (value of message), you can just go ahead and return the value... | python|angularjs|json|ajax|flask | 1 |
5,776 | 42,260,031 | Python string with currency formatted | <p>I am attempting to retrieve a dollar amount from my database, concatenate it with other information and have it print with 2 decimal points. I have tried so many different configurations I have lost tract but continue to get only one decimal point (or an error). Can someone please show me where I am losing it.</p>
... | <p>As an alternative to Haifeng's answer, you could do the following</p>
<pre><code>from decimal import Decimal
str(round(Decimal(row[0]), 2))
</code></pre>
<p>Edit: I would also like to add that there is a <code>locale</code> module and that it is probably a better solution, even if it is a little bit more work. Yo... | python-3.x | 2 |
5,777 | 42,352,483 | IF statement doesnt compare values recieved from file | <p>I just started programming a few days ago. I made this program where the user can create a quiz ( all the Q's and A's are written to a file ) When i come to read the answers file, i make a with statement to extract every line independently, then compare it with every independent line of the Qs file. This works just... | <p>The problem is that when you write the answers to your file, you also write the newline character <code>"\n"</code>. Now, when you compare your strings, you are actually comparing <code>abdo1</code> to <code>abdo1\n</code>, which is false. Use the <code>.rstrip()</code> method on your <code>line2</code> string befor... | python|file | 2 |
5,778 | 54,236,600 | Special characters are printed only as a part of string, but not independently (python3) | <p>I work with strings containing diacritics. When I print the string, it is printed correctly:</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = "ˈtau̯rum"
print(s)
> ˈtau̯rum
</code></pre>
<p>However, When I iterate over the string and print each character independently, some of the characters ar... | <p>As the comment suggested, the printing issue is most likely due to how your terminal handles displaying the unicode characters. You can check that the character is what you expect by encoding it to <code>utf-8</code> bytes, or by using the <a href="https://docs.python.org/3/library/functions.html#ord" rel="nofollow ... | python-3.x|utf-8|utf | 0 |
5,779 | 65,474,351 | error in python: name not defined (variable in if statement) | <p>May I know why there is an error that 'the name 'output' is not defined'? Thank you</p>
<pre><code>weight = input('> ')
converter = input('lbs or kg: ').lower()
if converter == 'l':
output = weight * 2.205 + 'lbs'
elif converter == 'k':
output = weight / 2.205 + 'kg'
print(f'converted weight = {str(... | <p>If <code>converter</code> is not <code>'l'</code> or <code>'k'</code>, then no <code>output = ...</code> is never executed.</p>
<p>You can precede the conditionals by</p>
<p><code>output = <some default value></code></p>
<p>or raise an exception if no condition was met.</p> | python | 3 |
5,780 | 28,514,938 | Overwrite printed line in python 3.x on mac | <p>I'm attempting to write a program that involves the use of a coin flip, heads or tails, but so that it will print 'heads' then be replaced by 'tails' and continue doing this until it decides on an answer.</p>
<p>At the moment, when I run the program, it prints the 'heads' or 'tails' on the next line every time. Thi... | <p><code>print</code> writes a <code>\n</code> character to the end, therefore you need to modify that if you want to keep on the same line.</p>
<pre><code>import time
import random
offset = random.randint(0,1)
for i in range (0, 20+offset):
if i % 2 == 0:
print("Heads", end='')
else:
print("... | python|macos|carriage-return|sys | 5 |
5,781 | 28,738,025 | What is a good way to get a function to use its default value for an argument when the argument is specified as None in Python? | <p>Let's say I have a function (called <code>function</code>) that takes a boolean argument with default value of <code>True</code> like <code>def function(argument1 = True)</code>.</p>
<p>Now let's say I want to use this function, specifying its argument using the output of another function (<code>resolveArg</code>) ... | <p>I have not seen this kind of problem before, so may be there is a way to improve your logic and omit this functionality.</p>
<p>However there is a way to do introspection of code in Python by using the module <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">"inspect"</a>. </p>
<p>An example ... | python|function|default-arguments | 1 |
5,782 | 28,422,915 | Print dict on KeyError | <p>I'm working with several enormous lists of dicts, some of which might be missing items. I'm getting a lot of KeyErrors. They tell me what the bad key is, but they don't tell me what the dict in question is. I'd like something that does the equivalent of</p>
<pre><code>foos = [{'abc': 0, 'bcd': 1}, {'abc': 2}, {'abc... | <p>If you are looking for the index of the dictionary within the list you can use enumerate: </p>
<pre><code>foos = [{'abc': 0, 'bcd': 1}, {'abc': 2}, {'abc': 4, 'bcd': 0}]
for idx, foo in enumerate(foos):
try:
print foo['bcd']
except KeyError as err:
print 'bcd not found in dictionary #' + idx... | python|python-2.7|error-handling | 2 |
5,783 | 14,491,938 | Python GDal installation | <p>Having some problems with Gdal installation with python 2.7 on Windows 7 32bit. I am running MSVC 2010. I have followed the instruction from the blog website</p>
<p><a href="http://cartometric.com/blog/2011/10/17/install-gdal-on-windows/" rel="nofollow">http://cartometric.com/blog/2011/10/17/install-gdal-on-windows... | <p>Get the precompiled gdal from here:</p>
<p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal</a></p>
<p>I have some other notes on setting up postgres and postgis 2.0 here if you need it:</p>
<p><a href="http://monkut.webfactional.com/blog/arc... | python|gis|gdal | 1 |
5,784 | 14,823,373 | Python: Identify the generator function that created a generator | <p>Given a generator object, is it possible to identify the function used to create it?</p>
<pre><code>def gen_func():
yield
gen = gen_func()
// From `gen`, how do I get a reference to `gen_func` ?
</code></pre>
<p>I am implementing a decorator used to decorate a generator function with an additional attribute.... | <p>What you're literally asking for isn't possible in a clean way, both because generator objects don't have access to their generator function, and because new attributes can't be created on a generator.</p>
<p>But what you're trying to achieve probably <em>is</em> possible. Here's an example decorator that wraps the... | python|generator|yield|python-3.3 | 1 |
5,785 | 41,547,592 | sort dataframe by position in group then by that group | <p>consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(dict(
A=list('aaaaabbbbccc'),
B=range(12)
))
print(df)
A B
0 a 0
1 a 1
2 a 2
3 a 3
4 a 4
5 b 5
6 b 6
7 b 7
8 b 8
9 c 9
10 c 10
11 c 11
</code></pre>
<p>I want to sort the ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> for count values in <code>groups</code> first, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html" ... | python|pandas|numpy | 4 |
5,786 | 41,236,661 | Failed to get broadcast_1_piece0 of broadcast_1 in pyspark application | <p>I was building an application on Apache Spark 2.00 with Python 3.4 and trying to load some CSV files from HDFS (Hadoop 2.7) and process some KPI out of those CSV data.</p>
<p>I use to face "Failed to get broadcast_1_piece0 of broadcast_1" error randomly in my application and it stopped. </p>
<p>After searching a l... | <ol>
<li><p>You should to extends Serializable for your class</p></li>
<li><p>Your code Framework error, you can test it </p>
<pre><code>$SPARK_HOME/examples/src/main/scala/org/apache/spark/examples/
</code></pre></li>
</ol>
<p>If it's ok, you should check your code.</p> | python-3.x|apache-spark|pyspark|hadoop2|spark-csv | 0 |
5,787 | 6,333,367 | Django on Apache web server 'dict' object has no attribute 'render_context' | <p>I'm having a bit of a problem, I uploaded my Django project to a webserver running apache, mod_python, and django. On the computer I developed on the following works fine</p>
<pre><code>nameBox = getNamesBox().render(locals())
</code></pre>
<p>-</p>
<pre><code>def getNamesBox():
users = User.objects.filter()
... | <p>The <code>render()</code> method on a <code>Template</code> takes a <code>Context</code> object as its argument, not a dict. You'll have to construct a <code>Context</code> object from the dict, e.g.</p>
<pre><code>namedbox = getNamesBox().render(Context(locals()))
</code></pre> | python|html|django|apache|mod-python | 16 |
5,788 | 6,901,783 | simplejson decoder for a python script | <p>I am trying to parse the code with simplejson using a python script.</p>
<pre><code>{ "name":"some",
"products_valid_time_from":2011-08-01T14:45:00,
"products_valid_time_to":2011-08-01T21:00:00,
}
</code></pre>
<p>Ia m getting an error </p>
<pre><code>simplejson.decoder.JSONDecodeError: Expecting , delimite... | <p>Dates are not part of JSON. See for example <a href="http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx" rel="nofollow">this blog entry</a>.</p> | python | 0 |
5,789 | 6,701,449 | Python and no obvious way to get a specific element from a dictionary | <p>How come that I can easily do a for-loop in Python to loop through all the elements of a dictionary in the order I appended the elements but there's no obvious way to access a specific element? When I say element I'm talking about a key+value pair.</p>
<p>I've looked through what some basic tutorials on Python says... | <p>You access a specific element in a dictionary <em>by key.</em> That's what a dictionary <em>is.</em> If that behavior isn't what you want, use something other than a dictionary.</p>
<blockquote>
<p>a dict is supposed to be unordered but then why does the for-loop print them in the order I put them in?</p>
</block... | python|dictionary | 7 |
5,790 | 57,085,245 | How do you import a .txt (or other file type) into a Google Colab notebook directly from your own Drive? | <p>I'm trying to import a couple .txt files into Colab from my own Google Drive. The colab notebook I'm using is in the same folder as the files I want to upload within that notebook. While there is documentation on file I/O on <a href="https://colab.research.google.com/notebooks/io.ipynb" rel="nofollow noreferrer">Ext... | <p>If you have a file that you want to write in the root of your Google Drive called <code>foo.txt</code> then the following code should read the file into Colab: </p>
<pre><code>from google.colab import drive
drive.mount('/content/drive')
</code></pre>
<p>The above will ask you to provide your credentials via a link... | python|file-upload|google-drive-api|jupyter-notebook|google-colaboratory | 4 |
5,791 | 56,873,621 | How to display image icons on nodes in NetworkX | <p>I am using NetworkX module to present the network of an infrastructure systems. In this systems, nodes and edges consist of different types of entities and I would like to use some icons representing their types instead of circle, star or square. </p>
<pre><code>G = nx.Graph()
G.add_edge('a', 'b')
nx.draw(G, labels... | <p>You can create a plot using networkx and get the handle to the figure. Then use matplotlib to plot ontop of it.</p>
<pre><code>import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
from numpy import sqrt
import glob
path = 'some/folder/with/png/files'
files = [f for f i... | python|python-3.x|networkx | 0 |
5,792 | 44,538,400 | How do i import files that mutually import each other? | <p>how do i import a function and a dictionary that mutually imports each other. These two files are already in the same directory thus, there is no nid to import sys. Also, i this it is recursive that is why it is unable to import. How do i import a dictionary from each other's file without making it recursive and cau... | <p>This is a circular dependency. I am not sure how you can solve it without changing the basic structure of the modules and therefore the dependency graph. Why don't you try to define both the dicts in a separate file and import them. As it looks like form your code they are empty dicts anyway.</p>
<p>You may find <a... | python|python-3.x|dictionary|recursion|tinydb | 1 |
5,793 | 61,935,417 | What is the fastest way to manipulate large csv files in Python? | <p>I have been working on a python code, which reads a csv file with 800 odd rows and around 17000 columns.
I would like to check each entry in the csv file and see if this number is bigger than or smaller than a value, if it is, I assign a default value. I used pandas and worked with dataframes, apply and lambda funct... | <p>using pandas,for cvs data, makes it efficient. but your code is not efficient.it will be faster if you try code given blow.</p>
<pre><code>def do_something(some_dataframe):
col = get_req_colm(some_dataframe)
col = col.to_numpy()
np_array = np.zeros_like(col)
for i in range(len(col)):
k = np_... | python|csv|large-files | 0 |
5,794 | 24,273,338 | why updating sys.path is not effecting the list of directories python will search | <p>I am trying to import serial module. But it was throwing error</p>
<pre><code>AttributeError: 'module' object has no attribute 'RawIOBase'
</code></pre>
<p>Later I found that there is one more directory with name 'io' and 'init.py' file exists in the directory. so when I print using print(io), it is displaying </p... | <p>FYI, you can join your system path together using</p>
<pre><code>>>> ':'.join(sys.path)
'/usr/lib/python2.7:/usr/lib/python2.7/plat-x86_64-linux-gnu:/usr/lib/python2.7/lib-tk:/usr/lib/python2.7/lib-old:/usr/lib/python2.7/lib-dynload:/usr/local/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages:/u... | python | 1 |
5,795 | 72,044,493 | User object has no attribute | <p>I am creating an app in which it manages ranking and ELO functions for a local hobby game store. I am using django to write the application. I am having troubles trying to figure out how to access a user's model from their name.</p>
<p>models.py</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneF... | <p>You should assign a related name to OneToOneField like this:</p>
<pre class="lang-py prettyprint-override"><code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="assigned_profile")
...
</code></pre>
<p>then you will be able to access it like <co... | python|django | 1 |
5,796 | 35,976,802 | How do I print out everytime the state of the list every time you make a pass in bubble sort? | <p>I have a question on how to get the following output in python 2.7.</p>
<pre><code>>> bubble(['abe','Ada','bak','bAr'], False)
['Ada', 'bak', 'bAr', 'abe']
['bak', 'bAr', 'Ada', 'abe']
['bAr', 'bak', 'Ada', 'abe']
>> bubble(['Adm','abe','bAr','bak'], False)
['Ada','bAr','bak','abe']
['bArt','bak','Ada',... | <p>Use feature of range method which allow you to iterate in reverse order</p>
<pre><code>print range(1,3) # [1,2]
print range(3-1, 0, -1) # [1,2]
</code></pre>
<p>By the way you can avoid code duplication of loops ( <code>if asc == False</code> and <code>if asc == True</code> remove conditions).</p>
<p>To do it use... | list|python-2.7|sorting|for-loop|bubble-sort | 1 |
5,797 | 35,950,050 | How to import python file located in same subdirectory in a pycharm project | <p>I have an input error in pycharm when debugging and running.</p>
<p>My project structure is rooted properly, <code>etc./HW3/.</code> so that <code>HW3</code> is the root directory. </p>
<p>I have a subfolder in HW3, <code>util</code>, and a file, <code>util/util.py</code>. I have another file in <code>util</code>... | <p><strong>Recommended Way:</strong></p>
<p>Make sure to set the working folder as <code>Sources</code>.</p>
<p>You can do it in <code>Pycharm</code> <code>-></code> <code>Preferences</code> <code>-></code> <code>Project: XYZ</code> <code>-></code> <code>Project Structure</code></p>
<p>Select your working fold... | python|pycharm|importerror | 109 |
5,798 | 15,097,907 | How to execute many functions one after the other | <p>I'd like to execute many function after the other. Each function returns True or False. So if one function returns True, I'd like to execute the next one. etc...</p>
<p>All the functions don't have necessary the same arguments.</p>
<p>Now i have something like :</p>
<pre><code>res=function1()
if res:
res=funct... | <p>Well, you can define your own way to do this, but I would do that like that:</p>
<pre><code>my_functions = (
(my_func1, [2, 5], {'kwarg1': 'val1'}),
# ...
)
for function, args, kwargs in my_functions:
if not function(*args, **kwargs):
break
</code></pre>
<p>Edited according to the comment. Gre... | python | 8 |
5,799 | 46,201,887 | Dynamically defining methods with names derived from a class attribute? | <p>The title might not be the best description of what I'm trying to do but I'm not sure what to call this. I came across various seemingly related concepts with names like "decorators", "descriptors", and "metaclasses" but I don't know which of those approaches (if any) I should investigate further!</p>
<p>Given the ... | <p>An easy way to do this would just be to implement <code>__getattr__()</code>, e.g.:</p>
<pre><code>class MyGreeter(AnimalGreeter):
animals = {'dog', 'parrot'}
def __getattr__(self, animal):
if animal in self.animals:
return self.greet(animal)
raise AttributeError("'{}' object un... | python|metaprogramming | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.