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 |
|---|---|---|---|---|---|---|
6,100 | 71,338,184 | Conflict between how PEP8 E127 is supposed to work and warnings I get | <p>Here below is a screenshot of my code saying it doesn't respect E127 from the PEP 8 rules:
<a href="https://i.stack.imgur.com/CgmtI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CgmtI.png" alt="enter image description here" /></a>
However, in this <a href="https://www.flake8rules.com/rules/E127.... | <p>Idk about your specific question, but personally, the way I indent is as follows</p>
<pre><code>def foo(
x: int,
y: int = 1
) -> int:
res = bar(
x=x,
y=y,
some_very_long_arg="some_very_long_arg"
)
return res
</code></pre>
<p>PyCharm never complained about that... | python|pycharm|pep8 | 2 |
6,101 | 9,495,925 | Continous integration, easy_install and download problems | <p>Some of my python projects are tested under continuous integration with a setup like the one described here : <a href="https://stackoverflow.com/questions/225598/pretty-continuous-integration-for-python">"Pretty" Continuous Integration for Python</a>.</p>
<p>I currently use <code>easy_install</code> to in... | <p>Have you considered using <code>pip</code> instead? If so, you could take advantage of its support for alternate package repositories:</p>
<p><a href="http://www.pip-installer.org/en/latest/usage.html#alternate-package-repositories" rel="nofollow">http://www.pip-installer.org/en/latest/usage.html#alternate-package-... | python|continuous-integration|easy-install | 1 |
6,102 | 39,181,884 | Spark job aborted | <p>I would like to add a prediction column to my dataframe given the logistic regression model. The function is below:</p>
<pre><code>def add_probability(df, model):
coefficients_broadcast = sc.broadcast(model.coefficients)
intercept = model.intercept
def get_p(features):
# Compute the raw value
raw... | <p>You will absolutely love the reason why it fails:</p>
<pre><code>return (1+exp(-raw_prediction))^(-1)
</code></pre>
<p>should be</p>
<pre><code>return (1+exp(-raw_prediction))**(-1)
</code></pre>
<p>Glad I could help</p> | python|apache-spark | 1 |
6,103 | 37,591,879 | Scapy with Python to save packets in a log file with time stamp | <p>I am using the Scapy library with Pyhton to collect data such as mac address. I am creating a log file that saves the data collected and timestamps it. I would like to save the packet as well, just in case I will need any of the data at a later case. </p>
<p>I've been using some of their methods that displays the p... | <p>I solved it:</p>
<pre><code>pac=p.show
</code></pre>
<p>And then in logger:</p>
<pre><code>logger.log(
mac=mac,
signal=signal,
channel = channel,
pi=pi_id,
ap=ap,
s_id=s_id,
packet=packet,
)
</code></pre>
<p>Thanks</p> | python|logging|scapy | 3 |
6,104 | 37,440,324 | How to override 'lambda' in Python? | <p>How can I redefine the syntax level <code>lambda</code> operator in python?</p>
<p>For example, I want to be able to do this:</p>
<pre><code>λ = lambda
squared = λ x: x*x
</code></pre> | <p>As some other users have noted, <code>lambda</code> is a reserved keyword in Python, and so cannot be aliased or overridden in the same way that you would a function or variable without changing the grammar of the Python language. However, you can define a function which itself defines and returns a new lambda funct... | python | 2 |
6,105 | 34,222,449 | Python: Memory Error while using MatplotLib | <p>I am facing the below error while plotting graph in matplotlibFile "</p>
<pre><code><stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2515, in bar
ret = ax.bar(left, height, width=width, bottom=bottom, **kwargs)
File "/usr/lib/pymodules/python2.7/matplo... | <p>I'm not convinced that you are passing the arguments you want to <code>bar</code>. The arguments are <code>left</code> and <code>height</code> and they are supposed to be sequences of the same length giving the position and height of the bars.</p>
<p>You are passing in 56 million positions to generate 56 million b... | python|matplotlib|matplotlib-widget | 3 |
6,106 | 7,676,947 | What is the advantage in using `exec` over `type()` when creating classes at runtime? | <p>I want to dynamically create classes at runtime in python.</p>
<p>For example, I want to replicate the code below:</p>
<pre><code>>>> class RefObj(object):
... def __init__(self, ParentClassName):
... print "Created RefObj with ties to %s" % ParentClassName
... class Foo1(object):
... ref_... | <p>I would recommend <code>type</code> over <code>exec</code> here.</p>
<p>In fact, the <code>class</code> statement is just syntactic sugar for a call to <code>type</code>: The class body is executed within its own namespace, which is then passed on to the metaclass, which defaults to <code>type</code> if no custom ... | python|namedtuple|dynamic-class-creation | 7 |
6,107 | 72,748,967 | Failed to Fetch error when trying to build docker image (while RUN apt-get update) | <p>I'm trying to create a flask-docker project, but i also need some tools from linux.
So i have a debian:latest base image for my dockerfile, in which i want to install
python3 and dieharder(the package i need for my project).
But every time i try to build the image with following command:
<code>docker build --no-cac... | <p>Update:
It seems like i solved this problem, although I'm not really sure why it works now.<br>
I had to change my run command and install gcc and g++ independently from
apt-get update. I don't know if this is an elegant solution, but it works for now.<br>
If anyone has a smoother solution pls let me know :) <br>
An... | python|linux|docker|ubuntu|debian | 1 |
6,108 | 72,538,362 | Tkinter - How to increase label value by clicking button? | <p>By clicking the <kbd>Start</kbd> button, the value on label must be increased by 3 every 500 milliseconds until I destroy the window,
but the value is stuck on 0.</p>
<pre><code>from tkinter import *
def start(value):
value+=3
label['text']=str(value)
if True:
root.after(500, start, value)
def s... | <p>As it turns out <code>tkinter.Label</code> can support <code>int</code>eger values too, so the way you can do incrementing is by simply using <code>label["text"] += 3</code> if the starting <code>text</code> of the label is an <code>int</code>eger (or <code>float</code> probably works too).</p>
<p>You also... | python|user-interface|tkinter|tkinter-button|tkinter-label | 0 |
6,109 | 72,728,902 | How can Ghostscript enable Unicode in Outline / Bookmarks? | <p>I am post processing a pdf file in order to add an index. For that I use</p>
<pre><code>gs -sDEVICE=pdfwrite -q -dBATCH -dNOPAUSE \
-sOutputFile=newfile_indexed.pdf index.info \
-f original_unindexed_file.pdf
</code></pre>
<p>The input file <code>index.info</code> is encoded in utf-8. Entries that include umlauts (... | <p>The supplementary file may be UTF-8 but the Data must be in 16BE format
so within < <code>FEFF</code> is the ByteOrderMark and <code>0028</code> = <code>(</code> in UTF-16BigEndian thus <code>0029</code> is <code>)</code> before the <code>></code> closing bracket</p>
<pre><code>[/Title <FEFF0028004C00FC0067... | python|encoding|ghostscript | 2 |
6,110 | 16,541,328 | Sqlite3 List index out of range when trying to get LIKE Query | <p>I'm trying to execute the following code:</p>
<pre><code>conn = sqlite3.connect("./Databases/Functions/He.db")
cursor = conn.cursor()
sql = "SELECT * FROM Requests WHERE Request like ?"
cursor.execute(sql, [(msg)])
results = cursor.fetchall()[0]
print results
if((results)[1] == "True"):
GPIO = (results)[2]
... | <p>Your query returned 0 results, so there is no first row to fetch. <code>.fetchall()</code> returns an empty list in that case, and there is no item at index <code>0</code>.</p>
<p>If you are only interested in the first result of a query, you should really use <a href="http://docs.python.org/2/library/sqlite3.html#... | python|database|sqlite|raspberry-pi | 1 |
6,111 | 16,492,621 | Python logging not working | <p>I'm loading my logging configuration from a file. The log file is given below:</p>
<pre><code>[loggers]
keys=root
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler
[handler_consoleHandler]
class=StreamHandler
level=INFO
for... | <p>By creating the log file like so:</p>
<pre><code>_logger = logging.getLogger(__name__)
</code></pre>
<p>It will look for a file with the name with the value of <code>__main__</code>, which your <strong>main</strong> module will have equal to <code>"__main__"</code>. However the other modules you import will have <... | python|logging | 1 |
6,112 | 16,064,409 | How to create a code object in python? | <p>I'd like to create a new code object with the function types.CodeType() .<br>
There is almost no documentation about this and the existing one says "not for faint of heart"<br>
Tell me what i need and give me some information about each argument passed to types.CodeType ,<br>
possibly posting an example.</p>
<p><st... | <p>–––––––––––<br>
<strong><em>Disclaimer</em></strong> :<br>
Documentation in this answer is not official and may be incorrect.</p>
<p>This answer is valid only for python version 3.x</p>
<p>–––––––––––</p>
<p>In order to create a code object you have to pass to the function CodeType() the following arguments: </p... | python|python-3.x|bytecode | 46 |
6,113 | 32,011,264 | Scrapy Item pipeline for multi spiders | <p>I have 2 spiders and run it here:</p>
<pre><code>from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
process1 = CrawlerProcess(settings)
process1.crawl('spider1')
process1.crawl('spider2')
process1.start()
</code></pre>
<p>and I want ... | <p>I agree with A. Abramov's answer. </p>
<p>Here is just an idea I had. You could create two tables in a DB of your choice and then merge them after both spiders are done crawling. You would have to keep track of the time the logs came in so you can order your logs based on time received. You could then dump the db i... | python|scrapy|scrapy-pipeline | 2 |
6,114 | 40,607,454 | Docker image with R (rocker/r.base) and python does not work when running on EC2, but local is fine | <p>I have started using docker recently. Seems pretty exciting, the fact that you can build apps once and run them in any machine, sounds amazing!</p>
<p>The truth is that I have experienced something else. I have an R image as a base (rocker/r.base) and I want to install python to it, so I can run a flask app on the ... | <p>Reason was that r.base had conflicts with some python packages, and could not use python with this R image.</p>
<p>I ended up with a solution of a docker-inside-docker image, that had ubuntu as base. I installed the required python libraries in the ubuntu image, installed docker on it and inside this image I used d... | python|r|docker|docker-compose | 2 |
6,115 | 68,330,151 | dataframes don't merge but concat using pandas python | <p>The thing is when get data from the query and use like</p>
<pre><code>df1 = pd.DataFrame(test_data)
df2 = pd.DataFrame(original_data)
df = df1.merge(df2, how = 'outer', indicator=False,
left_on = query_uniq_col.replace(' ','').split(','),
right_on = query_uniq_col.repl... | <p>I found the issue, although changing the format and style, it didn't work. So i did try to convert the date field in to String, problem got solved. Thank you so much for taking time for me!</p> | python|pandas|dataframe|data-science|data-processing | 0 |
6,116 | 26,166,352 | Python: Split string at the start of delimiter rather than the end | <p>I'm trying to split a string using a multiple character delimiter, I can keep the delimiter in the result, but it is in the first part rather than the second part where I need it. This is what I have.</p>
<pre><code>test = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
d = 'DEF'
for line in test:
s = [e+d for e in test.split(d) ... | <p>Using <a href="https://docs.python.org/2/library/stdtypes.html#str.partition" rel="nofollow"><code>str.partition</code></a>:</p>
<pre><code>>>> test = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> d = 'DEF'
>>> head, sep, tail = test.partition(d)
>>> [head, sep+tail]
['ABC', 'DEFGHIJKLMNOPQRS... | python|string|list|python-2.7|split | 1 |
6,117 | 60,243,118 | Time Series Data: Fill gaps in timeseries data and aggregate values | <p>I am novice using VBA to organize some data in an Excel sheet. I also have some experience in Python if that is easier. </p>
<p>I have a .csv file from a model that outputs a discontinuous time series (whenever there is inflow but not every 1-min time step): </p>
<blockquote>
<p>Date/Time Drainage cm/BRA <br/>5/... | <p>Give this solution a try. It employs <code>pandas</code> and the following techniques:</p>
<ul>
<li>Reading a CSV file into a DataFrame</li>
<li>Combining column data</li>
<li>Converting a date/time string to a <code>datetime</code> datatype</li>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/... | python|python-3.x|vba|time-series|aggregate | 1 |
6,118 | 1,749,769 | Python - Create html page with hyperlinks from os.listdir | <p>I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyper... | <pre><code>import cgi
def is_video_file(filename):
return filename.endswith(".wmv") # customize however you like
def createHTML():
videoDirectory = os.listdir("videos")
with open("videos.html", "w") as f:
f.write("<html><body><ul>\n")
for filename in videoDirectory:
if is_video_f... | python | 9 |
6,119 | 62,906,045 | Is there a SQLite function similar to Pandas tail() | <p>I am struggling to solve a problem in SQLite that was easy in Pandas. I have a large amount of data that is growing and has reached the point where the below call to a pandas dataframe results in a memory error (insufficient memory).</p>
<pre class="lang-py prettyprint-override"><code> df_tail = df.groupby(['Phas... | <p>If you want just the last "group"'s data, then you don't want <code>GROUP BY</code> - I think this would work instead:</p>
<h3>Step 1: Find the latest <code>Phase+Cycle</code> tuple:</h3>
<pre><code>SELECT
Phase,
Cycle
FROM
table
ORDER BY
Phase,
Cycle
LIMIT
1
</code></pre>
<h3>Step ... | sql|pandas|sqlite|group-by|tail | 1 |
6,120 | 32,423,554 | What am I doing wrong? (Convertion) | <p>I'm trying to convert this meters to kilometers but I don't how to let the input to realize it's an integer</p>
<pre><code>m = input("Enter the distance (meters) you want to convert to kilometers ")
km = 1000
print (m/km,"km")
</code></pre> | <p>If you use Python 3 you can do this:</p>
<p>For taking <code>int</code>, you do this by <code>m = int(input("Enter int"))</code> </p>
<p>So, in your code just change <code>input()</code> to <code>int(input())</code>:</p>
<pre><code>m = int(input("Enter the distance (meters) you want to convert to kilometers "))
... | python | 2 |
6,121 | 28,133,141 | wordend doesn't consider an apostrophe | <p>If we want to analyze the word under our mouse cursor we can use:</p>
<pre><code>text.get('current wordstart', 'current wordend')
</code></pre>
<p>However, this does not consider a word with an apostrophe.<br>
Is there another method that will?</p> | <p>Christian Gollwitzer over at <a href="https://groups.google.com/forum/#!topic/comp.lang.tcl/6iqwChYethQ" rel="nofollow">comp.lang.tcl</a> provided me with a workaround.<br>
Here's my test code for Python 3.4:</p>
<pre><code>import tkinter
import tkinter.messagebox as messagebox
class Creator(object):
def __in... | python|tkinter | 2 |
6,122 | 28,329,139 | Kivy class factory error | <p>I tried to make a program with a screen manager an images you can click on.
I first I tried to store the kivy file within a string variable and return the string variable, but I got this error message:</p>
<pre><code> kivy.factory.FactoryException: Unknown class <BILD1>
</code></pre>
<p>So I tried to return ... | <p>Move your Builder.load_file('turf.kv') like so:</p>
<pre><code>class Auswahl(Screen):
pass
class Frage(Screen):
farbe = ListProperty([1, 1, 1, 1])
def druck(self):
self.farbe = ([1, 0, 0, 1])
self.ids.box1.clear_widgets()
wimg = Image(source='Bild1.png')
self.ids.box1.add... | python|python-2.7|kivy | 2 |
6,123 | 44,323,998 | Need to parse the output of linux command | <p>I have the output of the linux command as below:</p>
<pre><code>/auto/qalogs/branch_team_5.7/drt/hash_list/bk20170401/audit-gc.rb:11:{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>10800, ... | <p>This should be a simple <code>re</code> problem.</p>
<pre><code>import re
command = 'grep -rwn /auto/qalogs/branch_team_5.7/ert/hash_list/ -e ' + alist[0] + ''
filter = '/auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb'
log = subprocess.subprocess.getoutput(command)
with open('output.txt', 'w+'... | python|regex | 0 |
6,124 | 34,838,211 | Selenium unable to find element SOMETIMES | <p>I'm trying to scrape a list of URLs:</p>
<blockquote>
<p><a href="https://www.jobsbank.gov.sg/ICMSPortal/portlets/JobBankHandler/SearchDetail.do?id=JOB-2016-0010810" rel="nofollow">https://www.jobsbank.gov.sg/ICMSPortal/portlets/JobBankHandler/SearchDetail.do?id=JOB-2016-0010810</a>
<a href="https://www.jobsban... | <p>The first problem is that you should give it some time for the page to load by adding a <a href="https://selenium-python.readthedocs.org/waits.html#explicit-waits" rel="nofollow">wait</a>. You should also simplify your locators and make them less dependent on the HTML structure:</p>
<pre><code>from selenium import ... | python|selenium|find|element | 2 |
6,125 | 12,409,994 | How to do tag searches on Djapian composite indexes | <p>I have a Djapian Indexer something like this..</p>
<pre><code>class SomeModelIndexer(Indexer):
fields = ["body"]
tags = [('title', 'title', 2),
('tag', 'strtags')]
space.add_index(SomeModel, SomeModelIndexer, attach_as="indexer")
</code></pre>
<p>This allows me to search SomeModels by tag with a ... | <p>I think that you should file a bug.</p>
<p>If you search for <code>sausages</code> only it should return some results. </p>
<p>Doing some tests, following the <a href="http://code.google.com/p/djapian/wiki/Tutorial" rel="nofollow">tutorial</a> i made some queries:</p>
<pre><code>Person.indexer.search("name:alex")... | python|django|xapian | 2 |
6,126 | 12,321,357 | Python install issue on Mac OS X | <p>I have been using the standard python that comes with OS X Lion (2.7.2) but I wanted to build a UCS-4 version to handle 4-byte unicode characters better.</p>
<p>I had already installed pip and packages like pytz, virtualenv and virtualenvwrapper, etc., and these are installed in <code>/Library/Python/2.7/site-packa... | <p>Since you will be using the custom python installation as your main one, I suggest you uninstall all non-standard packages from the system python and make sure that the existing easy_install.py is gone (possibly by manually removing it). Then download distribute's distribute_setup.py and run it with the new interpre... | python|macos|pip | 1 |
6,127 | 7,935,975 | Asynchronously redirect stdout/stdin from embedded python to c++? | <p>I am essentially trying to write a console interface with input and output for an embedded python script. Following the instructions <a href="http://docs.python.org/faq/extending.html#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" rel="noreferrer">here</a>, I was able to capture... | <p>Easiest way I found so far to do this is as follows:</p>
<pre class="lang-py prettyprint-override"><code>PyObject *sys = PyImport_ImportModule("sys");
PyObject* io_stdout = PyFile_FromFile(stdout, "stdout", "a", nullptr);
PyObject_SetAttrString(sys, "stdout", io_stdout);
PyObject* io_stderr = PyFile_FromFile(stderr... | c++|python|console|stdout|stdin | 1 |
6,128 | 47,267,698 | looping through a textfile and adding certain strings to a dictionary | <p>So I have a file morsecode.txt that contains </p>
<pre><code>A2.-B4-...C4-.-.D3-..E1.F4..-.G3--.H4....I2..J4.---K3-.-L4.-..M2--N2-.O3---P4.--.Q4--.-R3.-.S3...T1- all the way to Z.
</code></pre>
<p>what it does is state the letter "A" has 2 symbols ".-" as its morse equivalent,
the rest of the textfile follows the ... | <p>The error messages generally tell you what the problem is, once you get used to them, and it will make debugging much easier. </p>
<p>When it reads the code_length from the file, it expects to find a string that it can convert to an integer. That was not the case. Therefore something is wrong with code_length, beca... | python|file|loops|dictionary|morse-code | 0 |
6,129 | 47,343,252 | How to find where a specific sequence of numbers in a list starts? | <p>I couldn't find an answer for this, I'm a novice programmer so sorry about this dumb question!</p>
<p>Say in python I want to find <strong>where</strong> the first time the sequence [69, 69] appears in the list <code>[34,34,34,50,39,69,69,54]</code>. Is there a list notation for this? I feel like there is, but I ha... | <pre><code>[x for x in enumerate(a) if x[1] == 69]
</code></pre> | python|algorithm|python-3.x|list|sequences | -1 |
6,130 | 70,985,490 | How to make camera movement in a pygame 3d engine from scratch? | <p>I am new to matrices and matrix transformations and other things. I am making a 3d engine of my own in pygame using 2d, but I ran into a problem. I can't get my engine to implement camera movement and it only does camera rotation. Here is my code:</p>
<p>window.py: The custom window class</p>
<pre><code>from .genera... | <p>As you pointed out, in the <code>translate_matrix</code> function, your <code>rotation_y</code> variable is declared incorrectly:</p>
<pre><code>rotation_y = np.matrix([
[int(np.cos(angle_y)), 0, int(np.sin(angle_y))], # <--- missing an item
[0, 1, 0, 0],
[-int(np.sin(angle_y)), 0, int(np.cos(angle_y)... | python|numpy|matrix|pygame|3d | 1 |
6,131 | 11,990,350 | pip error while installing package in Cygwin/Python2.7 | <p>I installed Python2.7.3 in Cygwin using <a href="https://superuser.com/a/443094/372910">this guide</a>, I then installed pip from source.</p>
<p>When I try to use pip:</p>
<pre><code>$ pip install sqlalchemy
Downloading/unpacking sqlalchemy
Downloading SQLAlchemy-0.7.8.tar.gz (2.6Mb): 2.6Mb downloaded
Running setu... | <p>You can't just "run <code>rebaseall</code>" the way the site you link to implies. You need to do the following:</p>
<ol>
<li>Exit all running Cygwin programs. Yes, all of them, even your shell, even MinTTY, even X11.</li>
<li>Start > Run > <code>C:\cygwin\bin\ash.exe</code> > OK.</li>
<li><code>cd /bin</code></li>
... | python|cygwin | 15 |
6,132 | 33,664,190 | replace all characters in a string with asterisks | <p>I have a string</p>
<pre><code>name = "Ben"
</code></pre>
<p>that I turn into a list</p>
<pre><code>word = list(name)
</code></pre>
<p>I want to replace the characters of the list with asterisks. How can I do this?</p>
<p>I tried using the <code>.replace</code> function, but that was too specific and didn't cha... | <blockquote>
<p>I want to replace the characters of the list w/ asterisks</p>
</blockquote>
<p>Instead, create a new string object with only asterisks, like this</p>
<pre><code>word = '*' * len(name)
</code></pre>
<p>In Python, you can multiply a string with a number to get the same string concatenated. For exampl... | python|string | 16 |
6,133 | 33,564,395 | Draw, then re-draw lines in python code | <p>I'm a python beginner trying to draw a bunch of points and a line on a plot using the matplotlib.pyplot library. Below is some sample code</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x1,x2,n,m,b = -50.,150.,11,0.,0.
x = np.r_[x1:x2:n*1j]
for list in points:
plt.plot(list[0], list[1], '... | <p>One way is to enter interactive mode with <code>plt.ion()</code>, plot your line and store it and then change its ydata</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from time import sleep
x1,x2,n,m,b = -50.,150.,11,0.,0.
x = np.r_[x1:x2:n*1j]
plt.ion()
plt.axis([ -50, 150, -50, 150])
line, = pl... | python|matplotlib | 0 |
6,134 | 46,837,449 | Custom object with __iter__() not returning what is defined in __tuple__()? | <p><strong>In a custom object with <code>__iter__()</code> defined, when calling <code>tuple(obj)</code>, it returns the data of <code>__iter__()</code> in tuple form, but I want it to return from <code>__tuple__()</code>.</strong></p>
<p>This is a really big class, and I don't want to paste it here. I instead wrote a... | <p><code>__tuple__</code> isn't a thing. <code>tuple</code> doesn't look for a <code>__tuple__</code> method to perform conversion-to-tuple. I don't know where you got that idea.</p> | python|python-3.x|object|methods | 4 |
6,135 | 37,870,808 | Should I commit /bin directory when working with virtualenv? | <p>I am starting my first actual python project. I follow "Learn Python the Hard Way" to make an initial <a href="http://learnpythonthehardway.org/book/ex46.html" rel="nofollow">Python skeleton</a> and I am using virtualenv too.</p>
<p>Now I want to use git to do the version control. According to some previous questio... | <p><code>yourproject/bin</code> is distinct from <code>yourproject/env/bin</code>, where <code>yourproject/env</code> is the virtual environment's directory (and neither of them is <code>/bin</code> in the root directory). You should ignore everything in <code>env</code>, and indeed, your project should work for someon... | python|git|project|virtualenv|setuptools | 3 |
6,136 | 67,897,259 | Add filter based on condition in MongDB | <p>I am new to MongoDB and I have a collection <strong>student</strong>. I need to add the <strong>student.name</strong> filter in the query only when <strong>is_rep=true</strong>.</p>
<p>My document structure.</p>
<pre><code>{
{
"student": {
"name": "arun",
"dept&qu... | <p>You can use aggregations like</p>
<pre><code>db.collection.aggregate([
{
$match: {
is_rep: true,
"student.name": "arun"
}
}
])
</code></pre>
<p><strong>Working <a href="https://mongoplayground.net/p/aw7u5pAHDKz" rel="nofollow noreferrer">Mongo playground</a></strong></p>
<... | python-3.x|mongodb|pymongo | 0 |
6,137 | 30,279,498 | How to send multiple files using rest_framework.test.APITestCase | <p>I'm trying to send a couple of files to my backend:</p>
<pre><code>class AccountsImporterTestCase(APITestCase):
def test(self):
data = [open('accounts/importer/accounts.csv'), open('accounts/importer/apartments.csv')]
response = self.client.post('/api/v1/accounts/import/', data, format='multipa... | <p>You are sending a list of files to the view, but you aren't sending them correctly. When you send data to a view, whether it is a Django view or DRF view, you are supposed to send it as a list of key-value pairs.</p>
<pre><code>{
"key": "value",
"file": open("/path/to/file", "rb"),
}
</code></pre>
<p>To answer... | python|testing|django-rest-framework | 2 |
6,138 | 56,880,938 | How to identify root nodes in a python dictionary? | <p>I have a python dictionary that is representing a graph. I wish to identify the root/independent nodes so that I can process them simultaneously and then the next nodes will become root/independent nodes.
I am confused about how to implement this technique in python.</p>
<p>Below is a sample dictionary:</p>
<pre>... | <p>This is called "topological sort". A simple algorithm is</p>
<ol>
<li>build a mapping between nodes and number of "incoming" arcs</li>
<li>process nodes with 0 (those are "roots") and update the counters as you proceed (when you process a node decrement counter for all neighbors).</li>
</ol>
<p>You may get to a st... | python|data-structures|graph | 2 |
6,139 | 56,899,639 | How to force pythons format method to place values as they are evaluated | <p>I need to figure out the accounting year based on a date, while I am using the format method with datetime.datetime object it is generating the unexpected results for the same type objects with different values</p>
<p>Below is my code.</p>
<pre class="lang-py prettyprint-override"><code>from datetime import dateti... | <pre><code>## Below line is killing my mind as it is resulting 2019-2018
print('{}-{}'.format(dt.year, (dt.year+1)%100 if dt.month > 3 else dt.year-1,(dt.year)%100))
</code></pre>
<p>Okay, so let's break down your code:</p>
<p><code>'{}-{}'.format(dt.year, (dt.year+1)%100 if dt.month > 3 else dt.year-1,(dt.year... | python|datetime|string-formatting | 1 |
6,140 | 27,663,205 | Passing a Python Object to C module | <p>Say I have this simple class and instance:</p>
<pre><code>class MyClass:
def __init__(self, value):
self.value = value
def my_method(self):
return self.value * 2
my_object = MyClass(1)
</code></pre>
<p>Is it possible to pass <code>my_object</code> directly to C using <code>ctypes</code> o... | <p>No, you can't pass pure Python objects to C that way. However, you can declare a ctypes.Structure or ctypes.Union type and pass that to a c function as if it were a C struct or union, usually with a POINTER.</p>
<p>Example from the docs:</p>
<pre><code>from ctypes import *
class POINT(Structure):
_fields_ = [... | python|ctypes | 1 |
6,141 | 27,650,947 | Sprites not aligning to boundaries correctly | <p>I am creating a basic Pong-style game using Pygame, and I have gotten as far as moving the paddles. I have code that should prevent the paddles from moving beyond the edges of the screen, but if a player holds down a movement key, the paddle moves just slightly past the edge of the screen. Once the player releases t... | <p>The problem is that you're correcting each <code>paddle</code>'s <code>posy</code> <em>without</em> adjusting its <code>rect</code> at the same time. <code>posx</code> and <code>posy</code> store the location of your sprite-- in this case, it's center-- but the position of what you see on-screen is determined by the... | python-2.7|pygame|collision-detection|sprite|rect | 0 |
6,142 | 65,511,627 | How can I scale (x-axes) and shift data within array in Python? | <p>I have an array of data that represents some signal <strong>f(x)</strong>. If there is a way to perform operations which gives me in result an array of <strong>f(ax + b)</strong> by using only first array?</p>
<p>For "+ b" shifting part I use numpy.insert to insert array of zeros to shift signal left or ri... | <p>Depending on the size of the array there are several solutions, the simplest is to access the array <code>f as f[a*x+b]</code> and checking if that is a valid index. Here is a code that creates the shifted array:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def scale_shift(f, a , b):
i ... | python|arrays|numpy | 0 |
6,143 | 43,245,924 | How to open and catch all the links inside an accordion? | <p>I have a website with some accordion elements like this:</p>
<p><a href="https://i.stack.imgur.com/KPsmv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KPsmv.png" alt="enter image description here"></a></p>
<pre><code> <div class="col-md-12">
<a data-toggle="collapse" data-... | <p>following is the java code not sure about python but you can try the same logic </p>
<pre><code>List<WebElement> accordions = driver.findElements(By.xpath("\\a[@data-parent='#accordion1']");
</code></pre>
<p>This will get all the accordion in list. Now iterate through list and click on each accordion. </p>
... | python|python-3.x|selenium-webdriver|beautifulsoup|web-crawler | 0 |
6,144 | 66,803,535 | Is there a way to use order_by in Django to specify the order in which the results are returned? | <p>So far I have seen only ascending and descending uses for order_by. I want to order_by(Risk) but have the results returned in High, Med, Low order (These are my options in the field), not based on alphabet sorting, the way order_by is done by default.</p>
<p>To explain it a different way...I have a Field in my mode... | <p>One solution is to annotate your query with some conditional statement that will output a number depending on the field value:</p>
<pre><code>items = ScanData.objects.filter(
Q(Owner__icontains="HooliCorp")
).annotate(
risk_order=models.Case(
models.When(Risk='Low', then=1),
models.... | python|django|django-views | 2 |
6,145 | 69,381,708 | Element changes class selenium | <p>I try to access two dropdowns using selenium and python. The first problem is that, the class for second button is not too stable meaning, after selecting an option, the class name is changing.
__________ SECOND BUTTON _____________</p>
<pre><code>awsui-select-trigger-placeholder
</code></pre>
<p>Before:
<a href="ht... | <p>Try like this once:</p>
<p>Collect both the dropdowns and use indexing to click on them.</p>
<pre><code>The xpaths should highlight only those two dropdowns. As per the information you have shared, xpath might be like this.
options = driver.find_elements_by_xpath("//div[@class='awsui-select-trigger-wrapper']/sp... | python|selenium | 0 |
6,146 | 70,507,056 | One liner for matrix and vector square sum | <p>Given a matrix an a vector, with the same number of columns</p>
<pre><code>matrix = [[1, 1, 0, 0],
[1, 0, 1, 0],
[0, 0, 1, 1]]
vector = [1, 2, 3, 2]
</code></pre>
<p>Step 1: sum</p>
<pre><code>matrix_b = [[2, 3, 3, 2],
[2, 2, 4, 2],
[1, 2, 4, 3]]
</code></pre>
<p>Step 2: s... | <p>You can write <code>matrix_b</code> using a nested comprehension:</p>
<pre><code>matrix_b = [[r + v for r, v in zip(row, vector)] for row in matrix]
</code></pre>
<p>Adding <code>matrix_c</code> is trivial:</p>
<pre><code>matrix_c = [[(r + v)**2 for r, v in zip(row, vector)] for row in matrix]
</code></pre>
<p>Summi... | python|list|sum | 0 |
6,147 | 70,665,575 | How to move a robot in the API Python with the Pilz_Industrial_Motion ? Every Move Fail: RobotMoveFailed | <p>I want to use the Pilz Industrial Motion in my robot for construct the trajectories, but in the redme file on pilz_robot_programming, it tell's me that i need a service named /get_speed_override, so how to create it?
I do all the tutorials in the website of ROS: ( <a href="http://wiki.ros.org/pilz_robots/Tutorials" ... | <p>To create the service /get_speed_override you can add this line in your launch file:</p>
<pre><code><node name="fake_speed_override_node" pkg="prbt_hardware_support" type="fake_speed_override_node"/>
</code></pre>
<p>or:</p>
<pre><code>rosrun prbt_hardware_support fake_speed_overr... | python|ros|moveit | 0 |
6,148 | 72,954,689 | Groupby two columns and create a new column based on a conditional subtraction in python | <p>I'm trying to create a new column based on a conditional subtraction in python. I want to first group the dataframe by column A and D, then take the row value of C where B equals 2, and subtract that value from all values in column C.</p>
<pre><code>import pandas as pd
data = [
["R", 1, 2, "p"],... | <p>IIUC, you can use a mask before using <code>groupby.transform('first')</code>:</p>
<pre><code>df['e'] = df['c'] - (df['c'].where(df['b'].eq(2))
.groupby([df['a'], df['d']])
.transform('first')
.convert_dtypes()
)
... | python|pandas|lambda|apply|subtraction | 2 |
6,149 | 55,968,575 | I tried downloading nltk 'stopwords' using nltk.download("stopwords"), for NLP model. Which shows an error | <p>I am learning Machine Learning, NLP- Natural Language Processing, where, i tried downloading nltk stopwords. I got an error as below and the code & error is like... sklearn is not defined... i have not used it in code too..</p>
<p>I tried installing using pip & conda using commands,
pip install --upgrade nl... | <p>I could not reproduce the error but if you have already installed scikit-learn, please uninstall or update it and try again. You can try upgrading numpy too.
Please refer to this question, <a href="https://stackoverflow.com/questions/37224419/import-nltk-does-not-work">import nltk does not work</a></p> | python|jupyter-notebook|nltk | 0 |
6,150 | 64,743,120 | Running Python via batch, different Python.exe lovations? | <p>I have a working Python script in daily use, created and used at the begining im Spyder.
Now I have created a bat file to run the tool.
Problem:
The tool should be used by 4 different user in daily work. Every user has done Python installation on their own. That means the locations of python.exe are different.
How t... | <p>As long as all system users have the path to their python binary on the <strong>PATH</strong> environment variable, you can use the <code>where</code> command to locate the path. (for linux/mac users there is the <code>which</code> command that works simmilar)</p>
<p>when I enter <code>where python.exe</code> into m... | python|batch-file|installation|location | 0 |
6,151 | 64,641,029 | Trying to mute the system using pyautogui.press('volumemute') but it's not doing anything | <p>Simple code, does not work, is there anything else I need to do?
This is just a test, I just want to know if 'volumemute' works or not, other special keys like 'capslock', and 'volumeup' do not work as well. What is 'volumemute' doing? is it muting the system? was hoping to see mac's little volume window, but it als... | <p>Ah well, that took a bit to figure out. :-)</p>
<h3>Finding the bug:</h3>
<p>Turns out that one of the many issues with pyautogui is this one from 2015 complaining that <a href="https://github.com/asweigart/pyautogui/issues/37" rel="nofollow noreferrer">press is not working for all keys in macOS</a>, which already h... | python|pyautogui|macos-high-sierra | 1 |
6,152 | 63,937,766 | why im getting OSError: [Errno 5] Input/output error error while running streamlit in live server ? the code is running ok in my localhost | <p>Why I'm getting <code>OSError: [Errno 5] Input/output error</code> while running streamlit in live server ? the code is running ok in my localhost but getting</p>
<blockquote>
<p>OSError: [Errno 5] Input/output error</p>
</blockquote>
<p>while running on server</p> | <p>thanks for everyone i traced the error and corrected by changing control flow of the streamlit program</p> | python|nginx|server|streamlit | 0 |
6,153 | 52,940,184 | Tensorflow Hub : Stuck while importing a model | <p>Trying to import some models with Tensorflow Hub with this code :</p>
<pre><code>import tensorflow as tf
import tensorflow_hub as hub
elmo_model = hub.Module('https://tfhub.dev/google/elmo/2', trainable=True)
</code></pre>
<p>Makes my notebook stuck. The only log line appearing before getting stuck is :</p>
<blo... | <p>It was simply about privileges : I couldn't access the default directory where Tensorflow Hub store the models (<code>/tmp/tfhub_modules</code>).</p>
<p>To solve it, I just choose a directory to store the models which I can access :</p>
<pre><code>import os
import tensorflow as tf
import tensorflow_hub as hub
os.... | python|tensorflow|jupyter-notebook|tensorflow-hub | 8 |
6,154 | 65,201,813 | forming dictionary with two dictionaries with a specific logic | <p>I have two dicts:</p>
<pre><code>dict1={"test":345,"testing":123,"reality":2,"factor":5,"user":1}
dict2={"newone":123,"test":4,"reality":"4","edu":2}
</code></pre>
<p>Now,I want to form a new dictionary as follows:</p... | <p>use <a href="https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey">dict.get()</a> to return a default value if the key is not in the dictionary:</p>
<pre><code>{x:[dict1.get(x,0),dict2.get(x,0)] for x in list(dict1.keys()) + list(dict2.keys())}
</code></pre>
<p>gives</p>
<pre><code>{'test... | python|python-3.x|dictionary | 2 |
6,155 | 61,937,699 | How to access elements in a popup modal iframe using selenium and python | <p>I am trying to click on an input that dynamically appears when clicking another button on the page. I can see that the input is contained in an iframe tag and have tried to use selenium with <code>browser.switch_to.frame()</code> (where browser is my webdriver object) Whether I use the frame's id or the frame's obje... | <p>Try <code>driver.switch_to.frame</code> instead of <code>frame_to_be_available_and_switch_to_it</code>.</p>
<pre><code>time.sleep(5)
frames = wait(self.browser, 10).until(EC.presence_of_all_elements_located((By.XPATH,"//iframe")))
if frames[4].is_displayed():
print("frame is displayed")
#wait(self.browser,... | python|selenium|selenium-webdriver|iframe | 0 |
6,156 | 71,126,312 | Return dataframe to original state from pivot state | <p>I am currently trying to return a dataframe to its' original state after performing some operations on the pivoted dataframe.</p>
<p>I basically have a dataframe which looks like: <a href="https://i.stack.imgur.com/KMiPQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KMiPQ.png" alt="enter image d... | <p>Add <code>total</code> to index for <code>MultiIndex</code>, then split columns and reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a>:</p>
<pre><code>df1 = df.set_index('total', append=True)
df1.column... | python|pandas|pivot-table | 1 |
6,157 | 61,154,930 | problem with callback in python ( ctypes) | <p>Hi I have problem with CTYPES in python. I have ready dll library with some callback. On swift everything works, but I have some problem in python.</p>
<p>Python:</p>
<pre><code>def set_up_callback(self):
self.lib.set_callback(self.callback1)
@CFUNCTYPE(None, c_float, c_float, c_float, c_uint64)
def callback1... | <p>In <code>set_up_callback</code>, <code>callback</code> is a local variable that goes out-of-scope after calling <code>self.lib.set_callback(callback)</code>. You must keep a reference to <code>callback</code> for the lifetime that it could be called, so store it as a member variable of the class instance.</p>
<p>W... | python|c++|ctypes | 2 |
6,158 | 68,982,655 | Adding unique identifier column with prefix in pandas | <p>I am trying to add a unique column in pandas DataFrame with prefix "ACC". How do I do that?</p>
<p>i.e</p>
<pre><code>City New column,
Atlanta ACC-1,
Newyork ACC-2,
</code></pre> | <p>If there is unique index values use:</p>
<pre><code>df['New column'] = 'ACC-' + (df.index + 1).astype(str)
</code></pre>
<p>Another idea for any index:</p>
<pre><code>df['New column'] = np.arange(1, len(df) + 1)
df['New column'] = 'ACC-' + df['New column'].astype(str)
</code></pre>
<hr />
<pre><code> df['New column'... | pandas|uniqueidentifier|prefix | 2 |
6,159 | 63,188,937 | Function creation with pandas dataframe? | <p>I have the following pandas DataFrame named table</p>
<pre><code> grh pm_0 age_0
0 1 39054414 74
1 2 34054409 37
2 3 3715955000 65
3 4 19373605 53
4 5 99411 64
5 6 25664143 37
6 7 5161112 77
7 8 41517547 80
8 9 9517054000 ... | <p>You need to send the df to the function and return it at the end:</p>
<pre><code>def sto(scn, df)
.....
.....
return df
</code></pre> | pandas|function|dataframe | 0 |
6,160 | 49,141,359 | Implementing median cut using numpy | <p>So I'm trying to implement a basic median cut algorithm in python using python and numpy so far i got some simple code to calculate which medians i need to calculate </p>
<pre><code>img = ...
per = [100.0/(cuts+2)*i for i in range(1,cuts+1)]
med = np.percentile(img,per)
</code></pre>
<p>however I now want to conve... | <p>at the risk of sounding like a smartass ... you have looked at?:
<a href="https://docs.python.org/3/library/statistics.html" rel="nofollow noreferrer">https://docs.python.org/3/library/statistics.html</a></p>
<p>I would assume you can load the image as a data-grid (pandas) or an array with numpy. And then pass the... | python|numpy|compression | 0 |
6,161 | 67,023,152 | How to g_spawn (GLib) a Python script from a C program | <p>I am trying to use GLib to spawn a python script process from within a C program. I can easily do this when the Python script has been compiled into an executable via PyInstaller by using:</p>
<pre><code>// Set the python executable string based on the OS
gchar* python_executable;
#ifdef __MSYS__
python_executable ... | <p>The solution is using:</p>
<pre><code>gchar* argv[] = {"python3", "../gtk_simple_plot/plot.py", NULL};
</code></pre>
<p>with the addition of <code>G_SPAWN_SEARCH_PATH</code> in the default spawn settings, such that the g_spawn call now looks like this:</p>
<pre><code>// Spawn the python program t... | python|c|glib|spawn | 0 |
6,162 | 42,891,126 | set_xticklabels in an animated bar chart | <p>I have an animated bar chart in python where I would like to display the height of each bar on the x-axis at each frame. For that purpose, I use set_xticklabels to reset the xticks. It actually works nice, with one exception: if I run the animation and the number of bars is >8, then only half of the xtickslabels are... | <p>Mind that there is a difference between ticks and ticklabels. When setting a known number of ticklabels to an unknown number of ticks, the result can be anything. </p>
<p>In order to make sure each bar has its own ticklabel we can set the ticks to the positions of the bars. </p>
<pre><code>ax.set_xticks(range(l))
... | python|matplotlib | 1 |
6,163 | 72,191,071 | How to create a new column with the percentage of the occurance of a particular value in another column in a DataFrame | <p>I have a column, it has A value either 'Y' or 'N' for yes or no. i want to be able to calculate the percentage of the occurance of Yes. and then include this as the value of a new column called "Percentage"</p>
<p>I have come up with this so far, Although this is what i need i dont know how to get the info... | <p>You should use a lambda.</p>
<p>Something like that:</p>
<pre><code>res = port_merge_lic_df.groupby(['Port']).size().groupby('Shellfish Licence licence (Y/N)').apply(lambda x: x / x.sum())
</code></pre>
<p>And the last step:</p>
<pre><code>res.reset_index(name='Percentage')
</code></pre>
<p>It should work.</p>
<p>Sa... | python|pandas|dataframe | 0 |
6,164 | 35,238,705 | Column operation on Spark RDDs in Python | <p>I have a RDD with MANY columns (e.g. hundreds), and most of my operation is on columns, e.g. I need to create many intermediate variables from different columns.</p>
<p>What is the most efficient way to do this?</p>
<p>I create a RDD from a CSV file:</p>
<pre><code>dataRDD = sc.textFile("/...path/*.csv").map(lamb... | <p>With just a map it would be enough:</p>
<pre><code>rdd = sc.parallelize([(1,2,3,4), (4,5,6,7)])
# just replace my index with yours
newrdd = rdd.map(lambda x: x + (x[1] + x[2],))
newrdd.collect() # [(1,2,3,4,6), (4,5,6,7,12)]
</code></pre> | python|apache-spark|pyspark|rdd | 1 |
6,165 | 26,461,800 | Celery & RabbitMQ configuration | <p>I use Celery and RabbintMQ for my project. </p>
<p>I have 3 servers (Main, A, B). A and B are calculating the tasks from Main server, then they post response to him.</p>
<p>This is an organizational question: where I need to install Celery and RabbitMQ?</p>
<p>As I think, RabbitMQ must be install on Main server (... | <p>There is no need to install RabbitMQ on all servers. Installing it in one server is sufficient. You just need to route tasks to A & B servers.</p>
<p>Also, remember AMQP is network protocol, the producers, consumers and the broker can all reside on same or different machines. Following are the possible arrangem... | python|rabbitmq|celery | 1 |
6,166 | 26,540,885 | lambda is slower than function call in python, why | <p>I think lambda is faster than function call, but after testing, I find out that I am wrong. Function call is definitely faster than lambda call. </p>
<p>Can anybody tell me why? </p>
<p>And how to speed up function call in Python?</p>
<p>I'm using Ubuntu 14.04 and Python 2.7.6</p>
<pre><code>>>> timeit(... | <p><code>timeit('def a(): return [].extend(range(10)) ;a()')</code> is not calling <code>a()</code>; The call to <code>a()</code> is part of the definition of <code>a</code>:</p>
<pre><code>In [34]: def a(): return [].extend(range(10)) ;a()
In [35]: import dis
In [36]: dis.dis(a)
1 0 BUILD_LIST ... | python|function|lambda | 17 |
6,167 | 57,761,457 | Getting a best fit put onto the plot along with its equation | <p>So I have a data file that I have extracted the data from and made a graph, but I can't seem to figure out how to add a best fit to it along with a best fit equation. I always get an error message back saying "can't multiple a sequence to a non-int of type numpy.float64"</p>
<p>I have tried changing the b, m variab... | <p>There are a few areas that might be causing some issues you might want to check.</p>
<ol>
<li><code>polyfit</code> will return the slope then intercept--so you have <code>b</code> and <code>m</code> reversed.</li>
<li><code>abscissa</code> is a list so you won't be able to perform arithmetic operations as you would... | python|linux|ubuntu|plot | 0 |
6,168 | 42,164,910 | Pyinstaller: Images fail to extract | <p>I run the build command and everything appears to build correctly until I try to launch the exe and this message pops up:</p>
<p><img src="https://i.stack.imgur.com/S8NTQ.png" alt="Image"></p>
<p>Here is my spec file, I am not sure why it appears to be combing the file path with both images.</p>
<pre><code>block_... | <p>From the (<a href="http://pythonhosted.org/PyInstaller/spec-files.html#adding-data-files" rel="nofollow noreferrer">DOCS</a>):</p>
<blockquote>
<p><strong>Adding Data Files:</strong></p>
<p>To have data files included in the bundle, provide a list that describes the files as the value of the <code>datas=</co... | python|pyinstaller | 4 |
6,169 | 57,138,478 | Why does `scrapy` stop working after parsing the first URL? | <p>Below is my code in <code>python</code> to crawl a website with multiple pages. It starts to crawl the website <code>https://www.reddit.com/r/movies/top.json?sort=top&limit=25/</code> then if there is a <code>after</code> field in the response, it will <code>yield</code> another request. But what is happening is... | <p>After some debugging and I found this is caused by a wrong value in <code>allowed_domains</code> field. It can be fixed by changing:</p>
<pre><code>allowed_domains = ['www.reddit.com/r/movies/']
</code></pre>
<p>to </p>
<pre><code>allowed_domains = ['www.reddit.com']
</code></pre> | python|scrapy | 0 |
6,170 | 25,799,943 | My classes think that "self" is an argument that needs a value assigned | <p>I'm not sure why this is happening. It seems to think that "self" requires an argument, which doesn't make any sense.</p>
<p>Here's my code:</p>
<pre><code>class Animal:
def __init__(self):
self.quality = 1
class Bear(Animal):
def __init__(self):
Animal.__init__(self)
def getImage(... | <p>You have to instantiate <code>Bear</code> before you call <code>getImage()</code>:</p>
<pre><code>b = Bear()
b.getImage()
</code></pre>
<p><code>getImage</code> is an instance method, so it is only designed to be called on a specific <em>instance</em> of the <code>Bear</code> class. The state of that instance is w... | python|inheritance | 8 |
6,171 | 41,192,354 | Doctest fails when normal output and exception mixed together? | <p>Does <code>doctest</code> support that both output and exception mixed together?</p>
<p>One example is:</p>
<pre class="lang-py prettyprint-override"><code>>>> def foo():
... print 'hello world!'
>>> foo()
hello world!
>>> def bar():
... raise Exception()
>>> bar()
Traceb... | <p>Regular output and tracebacks cannot be mixed since they are just indistinguishable text. However you can wrap the block, catching the exception you expect:</p>
<pre class="lang-py prettyprint-override"><code>>>> try:
... foo_bar()
... except TheSpecificExceptionYouWant:
... pass
... else:
... ... | python|testing|doctest | 2 |
6,172 | 52,337,838 | Proper virtualenv setup for a project with multiple packages | <p>I'm relatively new to the world of python, so I apologize if this is a stupid question.</p>
<p>I'm having some trouble discerning at what level I should be creating my virtual environment. Using a trivial example:</p>
<pre><code>project
│ README.txt
│ setup.py
| venv ** should this go here *... | <p>Think about it like this - Your whole project is a single environment, well because you would want it to be separated from other things in your system. Now within your environment, things(modules) must be interacting with each other and therefore each of the modules can't really be in different environments.</p>
<p... | python|virtualenv | 2 |
6,173 | 43,816,275 | Access list at the end of Numpy matrix Python | <p>I am converting networkx graph to Numpy matrix in python using following code:</p>
<pre><code>a = networkx.attr_matrix(G, edge_attr='length')
</code></pre>
<p>which produces following output:</p>
<pre><code>(matrix([[ 0. , 0. , 1.2, ..., 0. , 0. , 0. ],
[ 0. , 0. , 0. , ..., 0. , 0. , 0. ],
[ 1.... | <p>Is the output actually a Numpy matrix? Or is it a 2-tuple (it looks like a tuple). If so, the matrix is in a[0] and the "rc_order" is in a[1].</p> | python|numpy|networkx | 1 |
6,174 | 43,484,550 | making user post show on profile page | <p>Hey guys I am looking to do something like what this question is but I dont see whats wrong with my code. <a href="https://stackoverflow.com/questions/34731589/how-can-i-get-all-post-of-users-in-django">Something like this question</a>. I'm just trying to make a profile page for my site and I wanted to add all the u... | <p>You want to filter based on <code>author</code> since that's what is defined in your <code>Post</code> model, and you want to check against the currently logged in user.</p>
<p>Try making the following change</p>
<pre><code>logged_in_user_posts = Post.objects.filter(author=logged_in_user)
</code></pre> | python|django | 1 |
6,175 | 34,400,757 | Linear programming, unexpected solution with equality constraint | <p>I'm trying to figure out what is wrong with my implementation, I expect the result to be <code>[5, 10]</code>, I don't understand how it gets <code>[7.5, 7.5]</code>, <code>x1</code> should be half of <code>x2</code>.</p>
<pre><code>from scipy.optimize import linprog
import numpy as np
c = [-1, -1]
A_eq = np.arra... | <p>Your problem is:</p>
<pre><code>x1 + x2 == 15
0.5 * x1 - 0.5 * x2 == 0
minimize -x1 -x2
</code></pre>
<p>So obviously you have <code>x1 == x2</code> (second constraint), and thus <code>x1 = x2 = 7.5</code> (first constraint).</p>
<p>Looking at your question, you probably don't want to transpose <code>A</code>:</... | python|scipy|linear-programming | 2 |
6,176 | 32,222,387 | How to make urlpatterns in case of "http//domain/include/Tom+Sam/exclude/Bob+Jane" | <p>I have tried below:</p>
<pre><code>url(r'^include/(?P<in>\w+([+]w+)*)/exclude/(?P<ex>\w+([+]w+)*)/$', views.MW_Tag_Search.as_view(), name='tagSearch')
</code></pre>
<p>I got Page Not Found.</p>
<p>what's wrong?</p> | <p>The first problem is that you have missed out the backslash before the w both times you use <code>([+]w+)</code>.</p>
<p>The second problem is that <code>in</code> is a keyword in Python, so it's best to avoid using it as a kwarg. I would use <code>include</code> and <code>exclude</code> instead. Remember to update... | python|django | 2 |
6,177 | 32,400,893 | Pandas: compare two columns and return matched rows | <p>I have two dataframes with multiple columns. </p>
<p>I would like to compare df1['postcode'] and df2['pcd'] and build a new df based on the matched values of these two columns. </p>
<p>Note- the length of the two columns I want to match is not the same. </p>
<pre><code>df1
postcode brand
1 znuee soony
2 eus... | <p>You can perform an inner <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="noreferrer"><code>merge</code></a>:</p>
<pre><code>In [134]:
df1.merge(df2, left_on=['postcode', 'brand'], right_on=['pcd', 'brand'])
Out[134]:
postcode brand pcd
0 e... | pandas|match|dataframe|vlookup | 8 |
6,178 | 23,232,775 | Iterating through a dictionary with a 'for' loop breaks prematurely | <pre><code>import itertools
print "Hello and welcome to the questionnaire software"
def list_to_dict(l):
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))
return d
activities = ["Go Shopping","Sleep","Read a Book"]
def choosing():
print "This questionnaire is intended to help two people choose ... | <p>When you <em>modify</em> the dict (or list, or etc.) <em>while iterating over it</em>, you confuse the interpreter. You should only iterate over a copy.</p>
<p>In this case, since you already have a list of the keys, which you don't modify, I'd just ditch <code>list_to_dict()</code>, and change these two lines:</p>... | python|python-2.7|for-loop|dictionary | 2 |
6,179 | 33,868,323 | How to use lxml in Python to get the following elements? | <p>I have the next XML file:</p>
<pre><code><separator colspan="4" string="Application"/>
<field name="sel_groups_9_28_10" modifiers="{}"/>
<newline/>
<field name="sel_groups_49_50" modifiers="{}"/>
<newline/>
<field name="sel_groups_68" modifiers="{}"/>
<newline/>
<field n... | <p>You can use simple XPath to get the nearest preceding sibling <code>separator</code> element from current <code>element</code> :</p>
<pre><code>element.xpath('preceding-sibling::separator[1]')
</code></pre> | python|xml|python-2.7|lxml|xml.etree | 0 |
6,180 | 70,560,193 | sqlalchemy filter() Table instance | <p>this feels basic but for the life of me I can't figure it out</p>
<p>I got the following table:</p>
<pre><code>class Node(BaseModel):
__tablename__ = "node"
id = sqla.Column(sqla.Integer, primary_key=True)
name = sqla.Column(sqla.String)
ntype = sqla.Column(sqla.String)
....
many m... | <p>i ended up with:</p>
<pre><code>@classmethod
def object_select(cls,node:Node)->List[Node]:
if not node:
return []
qu = Node.query.filter()
for vk, v in vars(node).items():
if hasattr(Node,vk):
if v:
attr = getattr(Node,vk)
qu = qu.filter(attr... | python|sqlalchemy | 0 |
6,181 | 55,648,630 | How to decode the time variable while using xarray to load a NETCDF file | <p>I have a netcdf file giving monthly precipitation values from 1948 to 2008. The time variable has a format as below:</p>
<pre><code>float time(time) ;
time:units = "months since 1948-01-01 00:00:00" ;
time:time_origin = "01-JAN-1948:00:00:00" ;
</code></pre>
<p>When i try to use Xarray to open the ... | <p>Thanks for the update in your comment. In your case, since your data has a regular frequency, I recommend working around this by creating your own time coordinate with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="noreferrer"><code>pandas.date_range</code></a>:</p>... | datetime|netcdf|python-xarray | 9 |
6,182 | 73,327,092 | Python, format() function | <pre><code>Months={"01":"January","02":"February","03":"March","04":"April","05":"May","06":"June","07":"July","08":"August","09":"September"... | <p>If you must do it yourself, try f-strings?</p>
<pre><code>MONTHS={1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"November", 12:&quo... | python|dictionary|lambda|format | 2 |
6,183 | 66,451,981 | how to create wheel package in python from the private git repo | <p>I've cloned the private repo to my local machine and added setup.py and have added README file and my directory structure looks something similar to this.</p>
<pre><code> abc/
abc(cloned private repo)/
__init__.py
requirements.txt
other Related Modules/
setup.py
READ... | <p>I'm not sure if this solves your problem exactly but I had a similar issue trying to install a private package from S3 via a requirements file. I ended up switching to using CodeArtifacts instead of S3 and it worked well. You just install everything through CodeArtifacts. You just need to point pip at the CodeArtif... | python-3.x|python-packaging|python-wheel | 0 |
6,184 | 66,340,925 | Text to csv converter | <p>I have a use case to convert text file or command output to csv file.</p>
<p>My output of current text file is as below:</p>
<p>File 1.test</p>
<pre><code>Use Yes
Mode Enabled
</code></pre>
<p>File 2.test</p>
<pre><code>Use No
Mode Disabled
</code></pre>
<p>File 3.test</p>
<pre><code>Use Partial
Mode enabled
</co... | <p>We can do this using csv module:</p>
<pre><code>import csv
data = []
files = ['File 1.test', 'File 2.test', 'File 3.test']
csv_columns = ["file_name", "Use", "Mode"]
with open('output.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writehe... | python | 0 |
6,185 | 72,033,850 | Multi-Level decorator in Flask | <p>I'm developing <strong>Flask</strong> application and I have a decorator called <code>login_required</code> which checks if the user is logged in, and sends the current user to the next function.</p>
<pre><code>def login_required(function):
@wraps(function)
def decorator(*args, **kwargs):
token = Non... | <p>So you can create your functionality like this</p>
<pre><code>def decorator1(function):
def fun(*args, **kwargs):
user = function(*args, **kwargs)
print("here")
return user
return fun
def decorator2(function):
def fun(*args, **kwargs):
# firslty i will decorate function with decora... | python|python-3.x|flask | 1 |
6,186 | 72,087,441 | append python list with only the integer | <p>I have the code below, which works, but I want a list of integers only. How do I get python to only append the integer, and not the (array) portion?</p>
<pre><code>import numpy as np
import matplotlib.pyplot as p
icp4 = np.loadtxt(icp4_img)
ptm = np.loadtxt(ptm_img)
inside, outside = [], []
with np.nditer(icp4, o... | <p>It appears that each <code>ptm</code> is a scalar array.</p>
<p>To obtain the scalar equivalent of a scalar array <code>ptm</code>, use <code>ptm.item()</code> (<a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html" rel="nofollow noreferrer">documentation</a>).</p>
<p>So instead of append... | python|append | 1 |
6,187 | 68,852,427 | Difference in magnitude between sound file read and wave file read in Python | <p>I am seeing an issue in the magnitude response between reading a wav file with <code>soundfile</code> and <code>wavefile</code>. Here are the different plots:</p>
<p><a href="https://i.stack.imgur.com/aKdKI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aKdKI.png" alt="enter image description he... | <p>By the two values you reported, it really does seem like <code>soundfile.read</code> gave you a <code>float64</code> array between -1 and 1 while <code>wavfile.io.read</code> gave you a <code>int32</code> array between -2147483648 and 2147483647 (-4850432/2147483648 = -0.00225866). You can make a normalized <code>fl... | python|wav|soundfile | 1 |
6,188 | 10,592,674 | Updating a list of python dictionaries with a key, value pair from another list | <p>Let's say I have the following list of python dictionary:</p>
<pre><code>dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
</code></pre>
<p>and a list like:</p>
<pre><code>list1 = [3, 6]
</code></pre>
<p>I'd like to update <code>dict1</code> or create another list as follows:</p>
<pre><code>dict1 = [{'domain'... | <pre><code>>>> l1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
>>> l2 = [3, 6]
>>> for d,num in zip(l1,l2):
d['count'] = num
>>> l1
[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]
</code></pre>
<p>Another way of doing it, this time with a list compr... | python|list|dictionary | 23 |
6,189 | 10,340,444 | How to find the location of msbuild without hardcoding it in my script? | <p>I'm writing a script in python to build a solution file and report the number of errors and warnings automatically, for all configuration and platforms. Currently, I rely on the fact that the user provide the location of the msbuild which I can use to build the project. Is there an automated way of finding the locat... | <p>Have you considered something like...</p>
<pre><code>%FrameworkDir%%FrameworkVersion%\MSBuild.exe
</code></pre> | python|msbuild | -2 |
6,190 | 62,801,715 | Why does this while loop using a data frame attribute not work? | <p>While I'm still learning Python, I'm just baffled by this one. This while loop gets the error:
"AttributeError: 'list' object has no attribute 'empty'" and I cannot figure out why. Your help is appreciated.</p>
<pre><code>import pandas as pd
import numpy as np
tickData = pd.DataFrame([])
print (tickDat... | <p>Initially you had given <code>tickData</code> as a Dataframe and later on, you are changing that to a list datatype which is not having any attribute <code>empty</code>. The while loop is based upon the condition <code>tickData.empty</code> and hence it throws the attribute error.</p>
<p>Hope this helps.</p> | python|while-loop | 1 |
6,191 | 62,497,452 | List comprehension from two sources | <p>Having this input:</p>
<pre><code>a = (1,2,3)
b = 'something'
</code></pre>
<p>I want to create a list which will look like that:</p>
<pre><code>['something', 1, 2, 3]
</code></pre>
<p>I tried to do:</p>
<pre><code>[b, i for i in a]
</code></pre>
<p>But got a syntax error.</p>
<p>Note that, I'm looking for a <strong... | <p>If your variable 'a' will always be a tuple and 'b' will always be a string then you can try one thing...</p>
<pre><code>a = (1,2,3)
b = 'something'
c = [b] + [i for i in a]
</code></pre> | python|list-comprehension | 0 |
6,192 | 67,238,203 | How can I get input from the user and check if part of it is a key in my dictionary? | <p>I need to get input from the user and check if the word following 'city' is inside of my dictionary (the key).</p>
<p>This is my dic:</p>
<pre><code>mydic = {'Paris':132, 'Rome':42, 'San Remo':23}
</code></pre>
<p>I need the user to write 'city' (they will do so, given instructions that I gave them) but after it the... | <p>Your code is very close to working</p>
<pre><code>user_input = input().lower() # Assume user input is "city Rome"
tag, city = user_input.split(" ", 1) # This will set tag = 'city' and city = 'rome'
if tag == 'city':
if city.capitalize() in mydic: # You could also do mydic.keys() it doesn't m... | python|dictionary|input | 2 |
6,193 | 71,129,315 | Retrieve data if a choice in Django models.TextChoices is met | <p>Program versions:<br />
<em>Django 3.1.13</em><br />
<em>Python 3.8.10</em></p>
<p>My <em><strong>models.py</strong></em>:</p>
<pre><code># Create your models here.
class Odorant(models.Model):
Pubchem_ID = models.IntegerField(primary_key = True)
Name = models.CharField(max_length =50)
Ruletype = models... | <p>This is something that's answered in Django's <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#exclude" rel="nofollow noreferrer">queryset documentation</a>. One way to accomplish this is by chaining exclude functions.</p>
<p>It doesn't make sense to <em>also</em> save conditions that satisfy all... | python|html|mysql|django | 1 |
6,194 | 71,288,432 | Drop only specific consequtive duplicates in a pandas dataframe | <p>I have the following dataframe, from which I need to drop consecutive duplicate values only if they equal 0.3 or 0.4.</p>
<pre><code>In [2]: df = pd.DataFrame(index=pd.date_range('20020101', periods=7, freq='D'),
data={'poll_support': [0.3, 0.4, 0.4, 0.4, 0.3 0.5 0.5]})
In [3]: df
... | <p>Boolean indexing will help. Try:</p>
<pre><code>df[~((df['poll_support']==df['poll_support'].shift())&(df['poll_support'].isin([0.3,0.4])))]
poll_support
2002-01-01 0.3
2002-01-02 0.4
2002-01-05 0.3
2002-01-06 0.5
2002-01-07 0.5
</code></pre> | python|python-3.x|pandas | 1 |
6,195 | 64,403,499 | why python gives None in the last line of output of this program? | <p>I created a simple 'stone paper scissors game' in python with oops. why python gives None in the last line of output?</p>
<pre><code>class Game:
def gameWin(self,comp,user):
if comp== user:
print('Match is Tie!')
elif comp=='s':
if user=='p':
print('You won... | <p>It's because you're printing <code>object.gameWin(comp,user)</code>. Since <code>object.gameWin(comp,user)</code> doesn't return a value, it prints <code>None</code>. Just remove the print around that last line. If you want to learn more about returning values, you can look at this question: <a href="https://stackov... | python | 0 |
6,196 | 70,361,947 | How to install Python package from GitHub that doesn't have setup.py in it | <p>I would like to use the following sdk in my python project -> <a href="https://github.com/LBank-exchange/lbank-api-sdk-v2" rel="nofollow noreferrer">https://github.com/LBank-exchange/lbank-api-sdk-v2</a>. It has sdk's for 3 languages (I just want the python one). I tried to install it using the command:</p>
<p><c... | <p>Looks like the developer didn't bother to package it properly. It it was me using it, I would fork it on GH, add the setup.py and use the fork. Maybe a good exercise for you?</p>
<p>Meanwhile, to just get it to work, in your project "root":</p>
<pre><code>git clone https://github.com/LBank-exchange/lbank-a... | python | 2 |
6,197 | 11,106,483 | Custom HTML5 NumberField always fails validation | <p>I have a simple custom NumberField:</p>
<pre><code>class NumberInput(forms.widgets.Input):
input_type = 'number'
class NumberField(forms.DecimalField):
def __init__(self, *args, **kwargs):
self.widget = kwargs.get('widget', NumberInput)
self.min_value = kwargs.get('min', 0)
self.max... | <p>You're initializing it with strings for min and max value, instead of integers.</p> | python|django|forms|html|widget | 1 |
6,198 | 11,057,199 | Can't execute a bash script with python 2.2 | <p>SO I've been stuck on this problem for a while now. I have a cgi python script that needs to execute a bash script. I have the following line in my code:</p>
<pre><code>os.system("/complete/path/to/executable/run_summary_page.sh " + labelName)
</code></pre>
<p>I've been trying to debug this for hours now and I can... | <p>I don't remember all of what is and isn't there back in python 2.2, but you can try a simple alternative for calling that command and seeing what is happening:</p>
<pre><code>import commands
stat, output = commands.getstatusoutput("command")
</code></pre>
<p>That isn't the most robust way to run commands, but its ... | python|bash|cgi | 1 |
6,199 | 55,664,168 | Pandas time series resampling with month and with group by column | <p>How to resample a dateindex with month and group by one column and aggregate mean of another column.</p>
<p>Example of dataframe:</p>
<pre><code> bts_name duration
cleareddate
2019-01-19 1002_NUc_Marathalli 95
2019-01-21 1002_NUc_Marathalli 188
2019-02-11 1002_NUc_Marathalli 1332
2019-04-... | <p>You can <code>reset_index</code> to set the <code>cleareddate</code> field as a column in your dataframe. I'd create a new column with month and then you can perform a straightforward <code>groupby</code> on that. </p>
<pre><code>df.reset_index(inplace=True)
df['month'] = df.cleareddate.dt.month
df.groupby(['month... | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.