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 |
|---|---|---|---|---|---|---|
4,500 | 70,781,171 | Spyder: Is there any way to leave the "view background colour" in the variable explorer unchecked by default? | <p>For personal preference, I prefer viewing my dataframes without the colouring scheme:</p>
<p><a href="https://i.stack.imgur.com/9Nk6o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Nk6o.png" alt="variable explorer" /></a></p>
<p>There is an option to untick the 'background colour' option, but ev... | <p>(<em>Spyder maintainer here</em>) No, there isn't, sorry.</p> | python|arrays|dataframe|spyder | 1 |
4,501 | 2,906,790 | way to fix number of concurrent sessions allowed at app level. django | <p>How can I fix number of concurrent sessions allowed at app level?
Basically I want a limit to how many concurrent requests to this url to keep the server from getting congested.
I guess some middleware hack?</p>
<p>Thanks.</p> | <p>Don't do this in django, but in Apache / nginx / whatever webserver you have in front of Django. They have specific modules exactly for such tasks.</p>
<p>A possible solution for Apache would be: mod_limitipconn2 - <a href="http://dominia.org/djao/limitipconn2.html" rel="nofollow noreferrer">http://dominia.org/djao... | python|django|session | 1 |
4,502 | 5,804,969 | Displaying an inverted vertical date axis | <p>The chart I'm trying to make is a 2D-array with date as its vertical dimension. By convention, the dates should increase from the top down. Displaying the date the other way around works fine with this code:</p>
<pre><code>import numpy as np
import matplotlib as mpl
import matplotlib.colorbar as cb
import matplotli... | <p>It's too bad that inverting a datetime axis obliterates the ticklocator and formatting settings. The easiest thing I can figure is to manually re-set them. Here's a link to the <a href="http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">format table</a>. Here's ... | python|matplotlib|axis | 1 |
4,503 | 6,032,720 | How can I name my objects in Python? | <p>I know this is a very simple question, but unfortunately I don't know enough to search effectively for an answer. Any answers or links to things I should already know would be greatly appreciated.</p>
<p>What I am trying to do is make an environment in Python where I have a bunch of turtles running around doing var... | <p>You should add the turtles to the list directly while executing the loop, for example</p>
<pre><code>my_turtles = []
for i in range(num_turtles):
x = ...
y = ...
h = ...
my_turtles.append(Turtle(x, y, h))
</code></pre>
<p>It's often also possible to write this as a "list comprehension":</p>
<pre><... | python | 6 |
4,504 | 67,996,895 | Can't install Pyaudio on Command promt | <pre><code>Collecting pyaudio
Using cached PyAudio-0.2.11.tar.gz (37 kB)
Using legacy 'setup.py install' for pyaudio, since package 'wheel' is not installed.
Installing collected packages: pyaudio
Running setup.py install for pyaudio ... error
ERROR: Command errored out with exit status 1:
command: 'c:\p... | <p>write :</p>
<pre><code>pip install pipwin
</code></pre>
<p>then :</p>
<pre><code>pipwin install pyaudio
</code></pre> | python|visual-c++|module|pyaudio | 0 |
4,505 | 30,642,950 | Script doesn't autorizate in strava.com | <p>I want to login in strava.com with python. I try do it (using <a href="http://www.youtube.com/watch?v=eRSJSKG4mDA" rel="nofollow">http://www.youtube.com/watch?v=eRSJSKG4mDA</a>), but i can't... </p>
<pre><code>import requests
import bs4
with requests.Session() as c:
url='https://strava.com/login'
url_p='https:/... | <p>It is much easier if, instead of using requests, you use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow"><code>mechanize</code></a>.</p>
<pre><code>>>> import mechanize
>>> br = mechanize.Browser()
>>> response = br.open('https://strava.com/login')
>>> br.sel... | python|python-requests | 1 |
4,506 | 64,104,119 | Custom JSON Encoder raises "Object not JSON serializable" error | <p>I am trying to create a custom JSON Encoder for one of my classes.
I have created a <a href="https://paste.pythondiscord.com/olajolebob.rb" rel="nofollow noreferrer">simplified version</a> to try the method and it works, but when I apply the method in my project it keeps throwing the error:</p>
<pre><code> json.d... | <p>It looks like you have a typo: <code>def defaut(self, o):</code> should be <code>def default(self, o):</code></p> | python|json|python-3.x|encoding | 1 |
4,507 | 42,777,957 | web Crawling and Extracting data using scrapy | <p>I am new to python as well as scrapy.
I am trying to crawl a seed url <a href="https://www.health.com/patients/status/.This" rel="nofollow noreferrer">https://www.health.com/patients/status/.This</a> seed url contains many urls. But I want to fetch only urls that contain Faci/Details/#somenumber from the seed url .... | <p>To be honest, the regex-based and mighty <code>Rule/LinkExtractor</code> gave me often a hard time. For simple project it is maybe an approach to extract all links on page and then look on the <code>href</code> attribute. If the href matches your needs, <code>yield</code> a new <a href="https://doc.scrapy.org/en/lat... | python-2.7|web-scraping|scrapy|web-crawler|scrapy-spider | 1 |
4,508 | 42,657,294 | Python 2.7.11 getopt doesn't read the argument | <p>In Python 2.7.13</p>
<p>We have the following python code to take the command line argument:</p>
<pre><code>import sys
import csv
import os
import sys, getopt
import pandas as pd
print('Python version ' + sys.version)
print('Pandas version ' + pd.__version__)
def main():
SERVER_NAME=''
PORT_NAME=''
... | <p><code>SERVER_NAME</code> is defined as a variable local to the <code>main()</code> function, si it is not visible in the global scope (the lines at the bottom of your code.<br>
You could either make <code>SERVER_NAME</code> a global variable or move the code after the call to <code>main()</code> into <code>main()</c... | python-2.7|getopts | 1 |
4,509 | 42,612,264 | pyYAML, expected NodeEvent, but got DocumentEndEvent | <p>I'm trying to dump a custom object, that is a kind of a list of objects. So I overrode the <code>to_yaml</code> method of the <code>YAMLOBject</code> class from which I set my class to inherit from:</p>
<pre><code>@classmethod
def to_yaml(cls, dumper, data):
""" This methods defines how to save this class to a ... | <p>Your code does not work because <code>dumper.represent</code> doesn't return anything. You want to use <code>dumper.represent_data</code> instead.</p> | python|yaml|pyyaml | 1 |
4,510 | 65,604,912 | Vaex unable to open hdf5 created by pandas | <p>I am getting this error:</p>
<pre><code>OSError: Could not open file: test/pd.hdf5, did you install vaex-hdf5? Is the format supported?
</code></pre>
<p>Yes I have installed vaex-hdf5</p>
<p>Here is a screenshot of the hdf5 I am attempting to open in vaex, opened in pandas:<br />
<a href="https://i.stack.imgur.com/s... | <p>This one is actually explained in the <a href="https://vaex.io/docs/faq.html#Why-can%27t-I-add-a-new-column-after-filtering-a-vaex-DataFrame?" rel="nofollow noreferrer">vaex documentation</a>: basically, pandas exports the data into row based format and vaex expects a column based format.</p> | python|hdf5|vaex | 1 |
4,511 | 65,634,318 | Why does this code not output anything after getting user input? | <pre><code>num_1 = int(input("Enter the first number >>>>"))
num_2 = int(input("Enter the second number >>>>"))
if num_1 > num_2:
for i in range(num_1,num_2+1):
print(i)
else:
for i in range(num_1,num_2,-1):
print(i)
</code></pre>
<p>What is the is... | <p>You've got the logic the wrong way around. You need to check is num_1 is less than num_2 when counting up.</p>
<pre><code>num_1 = int(input("Enter the first number >>>>"))
num_2 = int(input("Enter the second number >>>>"))
if num_1 < num_2:
for i in range(num_1,num... | python | 1 |
4,512 | 65,795,917 | In this python pygame code, am I updating atrribute for the rectangle object .midbottom? | <p>So I am working through No Starch Presses' Python Crash Course 2e. I have finally made it to the part where you create the Alien Invasion game. I am understanding everything up until these specific two lines of code.</p>
<p>There is a class called alien Invasion that holds a screen rect that will be passed to this c... | <p>A <em>Rect</em> object has exactly 4 attributes <code>x</code>, <code>y</code>, <code>width</code>, <code>height</code>. However there are many virtual attributes. If you set a virtual attribute under the hood, the attributes <code>x</code>, <code>y</code>, <code>width</code>, <code>height</code> are changed.
See <a... | python|pygame | 2 |
4,513 | 50,852,610 | Issues with building tensorflow unit tests | <p>I need to run tests on some XLA passes and used <code>bazel test
--config=opt --config=cuda //tensorflow/compiler/xla/service</code> to do the same (from <a href="https://stackoverflow.com/questions/34204551/run-tensorflow-unit-tests">here</a>). The build failed with the following message, hinting at the missing g... | <p>Linking to the shared libraries instead of the object file archive solved this problem, i.e.,</p>
<pre><code>bazel test --linkopt="$GTEST_DIR/libgtest.so" --linkopt="GTEST_DIR/libgtest_main.so"
</code></pre>
<p>instead of,</p>
<pre><code>bazel test --linkopt="$GTEST_DIR/libgtest.a" --linkopt="GTEST_DIR/libgtest_m... | tensorflow|build|googletest|position-independent-code | 0 |
4,514 | 50,937,824 | Click on link using selenium webdriver | <p>I am trying to click on a link and can't seem to get it to work. I click all the way up to the page I need, but then it won't click the last link. The code is as follows:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
im... | <p>There can be multiple reasons for that. </p>
<p><strong>1.</strong> You might have to scroll down or might have to perform some action so that it'll be visible to script. </p>
<p>for scroll down you can use this code : </p>
<pre><code>browser.execute_script("window.scrollTo(0, Y)")
</code></pre>
<p>where <str... | python|selenium|webdriver | 2 |
4,515 | 3,725,071 | oocalc plugin - development step by step guide available? | <p>I want to develop plugin for OoCalc Open Office,
is there any good resource or link will help to start working on it.</p>
<p>any existing article like step by step guide for developer would be great !!</p>
<p>I want to develop the plugin based on Python Programming Language.</p> | <p>You can refer to the <a href="http://wiki.openoffice.org/wiki/Extensions_development" rel="nofollow">OpenOffice.org's extension development</a> site. This has all the information regarding the development of extensions for openoffice. For how to develop plugin in Python, you can refer to <a href="http://wiki.openoff... | python|plugins|openoffice.org|openoffice-calc | 1 |
4,516 | 3,546,952 | Open a new window in Vim-embedded python script | <p>I've just started wrapping my head around vim+python scripts (having no experience with native vim scripts).</p>
<p>How can I open a new window to contain the stdout from a background process?</p>
<p>Currently, after reading some :help python, the only option I see is something like:</p>
<pre><code>cmd = ":bel ne... | <p>Since <code>vim.command</code> can execute most (if not all?) ex commands, you can simply call <code>:new +read!ls</code> from within it.</p>
<p><code>:new</code> splits the current window and puts a new (empty, no name) buffer into the upper window. It takes an argument <code>+[cmd]</code> which we use to execute ... | python|scripting|vim | 3 |
4,517 | 34,968,430 | Replacing csv data based on conditions (python) | <p>I have a csv file which contains data I need to delete based on certain conditions (using python). My conditions for when data needs to be deleted are: </p>
<ul>
<li>x < -10 </li>
<li>x > 10 </li>
<li>-1.0e-300 < x < 1.0e-300</li>
</ul>
<p>So far I have only got as far as:</p>
<pre><code> with open... | <p>You have to convert text to <code>int()</code> or <code>float()</code> before compare.</p>
<p>To delete elements when <code>x < -10</code> or <code>x > 10</code> you need:</p>
<pre><code>[ x if -10 <= float(x) <= 10 else 'NaN' for x in row]
</code></pre>
<hr>
<p>btw: maybe you should use module <code... | python|csv | 0 |
4,518 | 44,970,835 | Changing the name of the file to folder name | <p>I have some files and I want to change names to their folder names. However, the problem is that sometimes they are located in main folder and sometimes in subfolders.
For instance lets assume that "Es" is the main directory
Then I have three options: </p>
<pre><code>Es--> France---_-2011 --> import.csv
Es--&... | <h3>Join path (<a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="nofollow noreferrer">ref</a>)</h3>
<pre><code>full_path = os.path.join(root, file)
# C:\\Users\\Es\\France-----2011\\import.csv
</code></pre>
<h3>Get relative path (<a href="https://docs.python.org/3/library/os.path.html#os.path... | python|os.walk | 1 |
4,519 | 45,242,194 | Is datetime.replace fundamentally broken? | <p>Converting a timezone naive date time to a specific timezone gives a completely incorrect result.</p>
<pre><code>import dateutil as du
import pytz
du.parser.parse('2017-05-31T15:00:00').replace(tzinfo=pytz.timezone('Europe/London')).isoformat()
</code></pre>
<p>returns a one minute not one hour offset vs UTC</... | <p>The main problem here is that you are using a <code>pytz</code> time zone. <code>pytz</code> zones do not follow the <code>tzinfo</code> interface and cannot be simply attached to <code>datetime</code> objects (either through the constructor or through <code>replace</code>). If you would like to use <code>pytz</code... | python|datetime|timezone|pytz|python-dateutil | 2 |
4,520 | 64,948,722 | error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 2: invalid start byte | <p>I have a piece of code that does this:</p>
<pre><code>def command(self, s, level=1):
sub=subprocess.Popen(s, bufsize=0, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True);
(out, err) = sub.communicate()
</code></pre>
<p>I see this error:
UnicodeDecodeError: 'utf-8' c... | <p>With the <code>universal_newlines=True</code> parameter (which has a more readable alias <code>text=True</code> since Python 3.7), input and output are en-/decoded implicitly by Python.
You can tell Python which codec to use through the <code>encoding=</code> parameter.
If you don't specify a codec, the same default... | python|python-3.x|utf-8 | 3 |
4,521 | 64,829,392 | Updating Python3 and Pip3 on Mac | <p>I have two versions of python3 installed on my computer. They are located here:</p>
<pre><code>/usr/local/bin/python3
/usr/bin/python3
</code></pre>
<p>I have set my PATH variable to use the first version. Running "which python3" routes to this version: /usr/local/bin/python3 -- this is what I want.</p>
<p... | <p>There are a few things that I have found increase the chances of success here:</p>
<ul>
<li>don't mess with the Mac-installed default Python</li>
<li>don't use homebrew to install Python</li>
<li>use <a href="https://github.com/pyenv/pyenv" rel="nofollow noreferrer">pyenv</a> to install and manage Python versions</l... | python|macos|pip | 1 |
4,522 | 64,713,964 | Converting repeating rows to columns in pandas dataframe | <p>I am trying to convert a dataframe with repeating rows into columns as follows</p>
<pre><code>INPUT
Key | Value
A | 1
B | 2
C | 3
A | 4
B | 5
C | 6
EXPECTED OUTPUT
A | B | C
1 | 2 | 3
4 | 5 | 6
</code></pre>
<p>There are a lot of options like pivot(), unstack(), groupby(), etc.... | <p>Its not a straight-forward <code>pivot</code>. Do this using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>df.pivot</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="... | python|pandas|dataframe | 2 |
4,523 | 61,231,332 | how to check for an exact string match in parameters that being passed for API call Python | <p>I am passing the parameters with a Soap Call to AdPoint platform. My parameters look like this:</p>
<pre><code>[{'nUID': '39', 'Query': [{'MaxRecords': '40', 'OrderName': 'Forecast Placeholder - 100', 'CustomerID': '15283'}]}]
</code></pre>
<p>Passing the parameters below:</p>
<pre><code>response = client.service... | <p>If someone could make this a comment, that would be very helpful. I don't have enough reputation to do so.</p>
<p>@Chique_Code, when you say:</p>
<blockquote>
<p>The response I get back might be Forecast Placeholder - 1005 or 1007 etc. I wonder if there is a way in Python to tell the code to only return the exac... | python|string|api|soap|match | 0 |
4,524 | 61,506,156 | Bulk edit date format in exported chats (.txt file) | <p><a href="https://i.stack.imgur.com/yhJ6y.png" rel="nofollow noreferrer">This is the chat file exported from an instgram .json file</a></p>
<p><a href="https://i.stack.imgur.com/48021.png" rel="nofollow noreferrer">This is how I want to alter the date format to look like</a></p>
<p>I am trying to edit the exported ... | <p>This will do what you want in Ruby:</p>
<pre><code>require 'date'
class DateFormatter
def format(dates)
formatted = []
dates.each do |date|
formatted << DateTime.parse(date).strftime('%-m/%d/%y,%l:%M %p')
end
formatted
end
end
</code></pre>
<p>This is the ... | python|ruby|timestamp|chat | 0 |
4,525 | 57,762,385 | How to append multiple columns values into a single column without append function? | <p>I have a data which consist of 16310 columns x 6000 rows. I wanted to append all columns value into one columns. Let say </p>
<pre><code>c1 c2
2 3
5 4
1 2
</code></pre>
<p>I wanted output like this</p>
<pre><code>c1
2
5
1
3
4
2
</code></pre>
<p>I have done this using append function and it's working fine. </... | <p>Do you want <code>.melt()</code>?</p>
<pre><code>df = pd.DataFrame({'c1': [2, 5, 1], 'c2': [3, 4, 2]})
df.melt(value_name='c1')
# returns:
variable c1
0 c1 2
1 c1 5
2 c1 1
3 c2 3
4 c2 4
5 c2 2
</code></pre>
<h2>Timed Example:</h2>
<pre><code... | python|pandas | 1 |
4,526 | 56,209,596 | JINJA creating xml files | <p>I am having issues creating xml files using JINJA. I am not using flask. this is just for creating the xml files.</p>
<pre><code>env = Environment(FileSystemLoader(r'C:\Users\template\templates'))
template = env.get_template('template_fie.xml')
keeping my logic here and writing the values to a dictionary.
tempxml... | <p>jinja2.Environment has multiple options in <strong>init</strong>, and loader isn't first position one</p>
<p>In order to make your code work you need only to set loader as keyword argument of Environment like this:</p>
<pre><code>env = Environment(loader=FileSystemLoader(r'C:\Users\template\templates'))
</code></p... | python|jinja2 | 0 |
4,527 | 56,103,828 | Keep negative value of 3d distance | <p>I'm trying to calculate deviations of coordinates. The deviations I have can be both positive and negative.</p>
<p>I have nominal x,y,z coordinates, and actual x,y,z coordinates. But no matter the method I'm trying, the distance always comes out positive. And that makes sence. But I need to keep the negative devia... | <p>I figured it out. I also need the vector of the point. I'm going to use the vector of the nominal point. Then I set the nominal point (XYZ) as a origin, and the vector as direction (IJK) as positive. Once I have a direction I can see if the actual point (IJK) is located "plus" or "minus" relative to the nominal poin... | python-3.x|math|sqrt | 0 |
4,528 | 18,444,840 | How to disable a pep8 error in a specific file? | <p>I tried with</p>
<pre><code>#:PEP8 -E223
</code></pre>
<p>or</p>
<pre><code># pep8: disable=E223
</code></pre>
<p>I thought the second would work but doesn't seems to work.</p>
<p>Do you have an idea how I can handle this ?</p> | <p>As far as I know, you can't.
You can disable errors or warnings user wide, or per project. See <a href="http://pep8.readthedocs.org/en/latest/intro.html#configuration">the documentation</a>.</p>
<p>Instead, you can use the <code># noqa</code> comment at the end of a line, to skip that particular line (see <a href="... | python|pep8 | 122 |
4,529 | 69,593,904 | Validate user's input from dictionary | <p>I am trying to validate the user's input for 2 options (one is an int and one is a word). I have attempted to use the try and except values however, they appear to just break the program. Basically I just need the user to only be able to enter in S,D or Q for the human's turn and 1,2 or 3 for the comp strategy.</p>
... | <p>Well, you could do simply check if the user's input is a key from your pre-defined dictionary!</p>
<pre class="lang-py prettyprint-override"><code>human_input_map = {
's': 'Steal',
'd': 'Deal',
'q': 'Quit'
}
#Human's turn
human = input('Steal, Deal or Quit [s|d|q]?: ').lower()
if human not in human_inpu... | python|validation|input | 0 |
4,530 | 69,574,748 | How to assign multiple variables to a dictionary | <p>Part of the goal of my program is to show all the books in the dictionary and for the user to have the ability to search for a title of a book.</p>
<p>I created a function called retrieve_books where I declared a list called list_of_books. Then I opened the file called "books.csv" to read form the list_of_... | <p>You have quite a lot of namespace collisions:</p>
<pre class="lang-py prettyprint-override"><code>def retrieve_books():
list_of_books = {}
</code></pre>
<p>At this point <code>list_of_books</code> is an empty dictionary.</p>
<pre><code>with open("books.csv", "r") as list_of_books:
for boo... | python | 0 |
4,531 | 55,261,314 | django url_for equivalent | <p>I'm trying to find a django method that is equivalent to Flask's url_for.</p>
<p>I'm not looking for the jinja equivalent (as shown <a href="http://%20https://stackoverflow.com/questions/40313374/how-to-change-a-html-page-from-flask-to-django" rel="nofollow noreferrer">here</a>) -- I'm talking about on the python s... | <p>It depends what you're looking for. </p>
<h1>Static Files</h1>
<p>If you want to get the URL for a <a href="https://docs.djangoproject.com/en/2.1/ref/contrib/staticfiles/" rel="noreferrer">static file</a>, you can use the following bit:</p>
<pre><code>from django.templatetags.static import static
url = static('i... | python|django | 5 |
4,532 | 57,561,113 | How to remove small contours attached to another big one | <p>I'm doing cell segmentation, so I'm trying to code a function that removes all minor contours around the main one in order to do a mask.
That happens because I load an image with some color markers:
<a href="https://i.stack.imgur.com/PjMQR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PjMQR.png"... | <p>So another approach, without color ranges.</p>
<p>A couple of things are not going right in your code I think. First, you are drawing the contours on <code>thresh_binary</code>, but that already has the outer lines of the other cells as well - the lines you are trying to get rid off. I think that is why you use <co... | python|image|opencv|computer-vision|scikit-image | 4 |
4,533 | 42,368,713 | Performance of data streaming from file vs directory of files | <p>I am using word2vec from Gensim and I am feeding sentences to the model with the following iterator:</p>
<pre><code>class SentencesIterator(object):
def __init__(self, source):
self.source = source
if os.path.isdir(self.source):
self.type_source = 'dir'
else:
sel... | <p>The <strong>decrease in the speed</strong> you are seeing, is the effect of caching files in the OS. </p>
<p>Successive reading the same file or files are results in reading form the OS cache instead of reading from HDD.</p> | python|python-3.x|io|gensim | 0 |
4,534 | 53,967,109 | How to use MergeError in try-except statement? | <p>I was making a program for merging tables 1-1, and wanted to use concat by try-except statement if validate='one-to-one' doesn't work. </p>
<p>However, I failed to use MergeError in "except MergeError as e:" code.</p>
<p>Since the actual code I am writing is too long, I made a simple example of my problem. In the ... | <p>Use this:</p>
<pre><code>except pd.errors.MergeError as e:
</code></pre>
<p>Or alternatively, import the name at top:</p>
<pre><code>from pd.errors import MergeError
</code></pre> | python|pandas|merge | 4 |
4,535 | 58,237,211 | skimage.io.imread behaving differently when giving a string or Path | <p>I just stumbled upon a weird situation with <code>skimage.io.imread</code>.</p>
<p>I was trying to open a MultiPage TIFF (dimensions: 96x512x512) like this:</p>
<pre><code>import argparse
from pathlib import Path
import numpy as np
from skimage import io
def numpy_array_from_file(path):
""" method to load num... | <p>Indeed, <code>pathlib.Path</code> is relatively new, so support in scikit-image is generally patchy. What's happening is that, because the <code>Path</code> is not a string, the extension isn't checked, and <code>imageio</code> is used instead of <code>tifffile</code>. The behavior of <code>imread</code> is differen... | python|scikit-image|imread|pathlib | 1 |
4,536 | 22,736,701 | Listbox filtering using a combo box | <p>I'm trying to filter the content that is displayed in my listbox depending on the currently selected item of a combo box. I'm not sure how I can accomplish this and I have not found even a simple, plain example online. Any ideas? I'd really appreciate some help.</p>
<p>Here are code excerpts. </p>
<p>Listbox:</p>
... | <p>From what I understand, what you are trying to do is clear and repopulate the listbox every time the combobox changes. Surprisingly, it's not too difficult.</p>
<p>Here is my example app. It utilizes root.after to recursively check to see if the combo box has changed. Note that there is probably a way to bind the u... | python|python-2.7|combobox|listbox|tkinter | 1 |
4,537 | 45,643,497 | Why does computational time decrease when removing unnecessary items from a list in Python | <p>The past days I've been trying get a better understanding of computational complexity and how to improve Python code. For this I have tried out different functions for calculating Fibonacci numbers, comparing how long the script runs if I make small changes. </p>
<p>I'm calculating Fibonacci numbers using a list, a... | <p>A <code>list</code> stores its elements in memory in a <em>contiguous</em> way.</p>
<p>So the <code>append</code> method of the <code>list</code> object needs to resize the allocated memory block from time to time (not every time <code>append</code> is called, fortunately)</p>
<p>Sometimes, the system is able to r... | python|time-complexity|fibonacci | 6 |
4,538 | 28,727,928 | how to make submit button to point to view | <p>I want my submit button in the template that uses a django form to take to another view or to just show the message that i returned in httpresponse. here is my code :</p>
<h1>views.py</h1>
<pre><code>def customer_form(request):
form = customerForm(request.POST)
if form.is_valid():
try:
cu... | <p>I don't understand the way you have written views.py but <a href="https://docs.djangoproject.com/en/1.7/topics/forms/#the-view" rel="nofollow">here</a> is the way I would have written.</p>
<p>Copying here for convenience:</p>
<pre><code>from django.shortcuts import render
from django.http import HttpResponseRedire... | python|django | 0 |
4,539 | 28,486,088 | How can I return line by line like iteraction for a variable and takes values starting line1, and stops when the length of my file ends? | <p>I have this file (pruebe.txt), and has this information: </p>
<pre><code>(1, 1)
(15, 20)
(13, 21)
(4, 3)
(2, 26)
</code></pre>
<p>I need to do this:</p>
<p>1.- Read line by line the elements (a, b) like a string in the function and then, return other line, and so that, stop when the length of my file ends. </p>
... | <p>Here's a high-level sketch of a typical line-by-line process in Python:</p>
<pre><code>with open('file_path', 'r') as f, open('logfile.txt', 'w') as logfile:
for line in f:
# process each line here
</code></pre>
<p>Under this approach, you'll process each line in order and processing will stop (and the... | python | 0 |
4,540 | 68,687,698 | Python - Regularize a multidimensional jagged list | <p>Say I have a 3D list in Python, but it's severely jagged:</p>
<pre class="lang-py prettyprint-override"><code>old_list = [[[0, 1, 2],
[3, 4, 5, 6],
[7, 8]],
[[9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18],
[19, 20, 21, 22]],
... | <p>This function should do the trick:</p>
<pre><code>def regularize3D(list3d, padding=0):
# figure out how long each 1d list needs to be
target_length = max(max(len(list1d) for list1d in list2d) for list2d in list3d)
# now remake each sublist with the right length
return [[list1d + [padding] * (target_l... | python|list|multidimensional-array | 2 |
4,541 | 41,261,230 | Python regular expression newline escape character | <p>I'm a bit confused about Python's regular expression. Specifically, why doesn't the following line return <code>True</code>? </p>
<p>Code:<code>bool(re.search(r'ab\n^c$', 'ab\nc'))</code></p> | <p><code>$</code> matches the end of the string, so <code>c</code> must be at the end. Your matched string ends in <code>c$</code> however. Next, you also included <code>^</code>, which matches the <em>start</em> of a string, but you put it in the middle of the expression.</p>
<p>Either escape <code>^</code> and <code... | python|regex | 2 |
4,542 | 6,883,319 | Python: Use an import done inside of a class in a function | <p>Can anyone explain how to make the following example work? Since several functions inside of the class will use the same function from platform I thought it would be better to import it right inside of the class, but I don't see how I can use it inside of the function (since I constantly get errors about it).</p>
... | <p>Well, it is not that simple.
Actually, import statement in many aspects looks like direct definition of something in place of it. If you write</p>
<pre><code>class test:
from platform import system
</code></pre>
<p>it looks exactly like</p>
<pre><code>class test:
def system():
# ....
</code></pre>... | python|python-import | 13 |
4,543 | 25,455,648 | Defining a range of symbols whose bounds are OTHER symbols | <p>I'm trying to express a summation over an arbitrary (but finite) number of symbols, which I wish to be given by another symbol. For instance, is it possible to say:</p>
<pre><code>N,ci,cj = symbols('N,c_i,c_j')
# pseudocode
k = sum(ci+cj,(ci,0,N),(cj,0,N))
</code></pre>
<p>or, more literally,</p>
<pre><code>k = s... | <p>You can use a Function, like <code>x = symbols('x', cls=Function)</code> and <code>x(i)</code>. Indexed should also work, but it looks like Sum has a bug that disallows <code>Idx</code>. It works if you just use <code>i = symbols('i')</code>, though. </p> | python|math|sympy | 1 |
4,544 | 44,405,989 | Tkinter Label image setting won´t work | <p>I've been learning how to use Tkinter from scratch and while I try to set a simple Label widget in a frame:</p>
<pre><code>from Tkinter import *
from ttk import *
root = Tk()
root.title("Practice")
mainW = LabelFrame(root, text = "Main info")
mainW.grid()
image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pict... | <blockquote>
<p><em>image</em><br>
The image to display in the widget. <strong><em>The value should be a
PhotoImage, BitmapImage, or a compatible object.</em></strong> If specified, this
takes precedence over the text and bitmap options. (image/Image)</p>
</blockquote>
<p>Right now you are just passing a strin... | python|python-2.7|tkinter|label | 4 |
4,545 | 44,659,986 | PyCharm: “Simplify Chained Comparison” | <p>I have two integer value <code>cnt_1</code> and <code>cnt_2</code>, and I write the following statements:</p>
<pre><code>if cnt_1 < 0 and cnt_2 >= 0:
# some code
</code></pre>
<p>This statement gets underlined, and the tooltip tells me that I must:</p>
<blockquote>
<p>simplify chained comparison</p>
<... | <p>Your expression can be rewritten as:</p>
<pre><code>if cnt_1 < 0 <= cnt_2:
</code></pre>
<p>This is called comparison chaining.</p> | python|pycharm | 12 |
4,546 | 20,687,403 | running the simplest Google Appengine code but the log said python25.dll conflicts with this version of Python | <p>I tried the simplest hello world app in Google AppEngine
I already download and setup
1) Python 2.7
2) Google Appengine launcher
create an app </p>
<p>app.yaml </p>
<pre><code>application: first
version: 1
runtime: php
api_version: 1
threadsafe: yes
handlers:
- url: /favicon\.ico
static_files: favicon.ico
u... | <p>Google app engine launcher didn't work for me.
To deploy i used following command in command prompt</p>
<pre><code>python appcfg.py -A YOUR_PROJECT_ID update <path to your project>/app.yaml
</code></pre> | php|python|google-app-engine | 0 |
4,547 | 36,164,828 | Randomly Select Sentences from Text File, Find Coresponding ID Number | <p>I am helping a professor of mine with a research project that involves pulling one thousand sentences randomly from a set of 20 text files. This is all data from the Corpus of Contemporary American English, if anyone is familiar with working with that. In these text files, the data is arranged like so: </p>
<blockq... | <p>Perhaps you could use regex to extract each paragraph along with it's source id, and then extract sentences from the paragraph, similarly to how you're doing it at the moment. This should help you catch the paragraph: </p>
<pre><code># with open... etc.
for source_id, paragraph in re.findall(r"(##\d+)([^#]+)", f.re... | python|regex|random|linguistics | 4 |
4,548 | 15,052,536 | A python class constructor error | <p>i have this line in my main.py:</p>
<pre><code>import classes
info = classes.information(a, b, c)
</code></pre>
<p>and this class and constructor in classes.py</p>
<pre><code>class information:
#constructor:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
</code></pre... | <p><code>classes.information(a, b, c)</code> <strong>isn't</strong> calling the <code>classes</code> constructor <code>classes.__init__()</code>. Rather it's calling what looks like something called a classmethod of the <code>classes</code> class itself. </p>
<p>This <em>might</em> be what you want (can't say for sure... | python|oop|class|constructor | 0 |
4,549 | 29,481,069 | Dictionary Python3. Updating value of dict | <p>Need you help to get an idea how to update dictionary value that represented as dictinary.</p>
<p>Here are two dictionaries:
d1 = {'x': {'y': 5}}
d2 = {'x': {'z': 6}}</p>
<p>Assume d1 + d2, then dictionary = {'x': {'y': 5, 'z': 6}}</p>
<p>Thank you.</p> | <p>It's rather simple...</p>
<pre><code>d1['x'].update(d2['x'])
</code></pre>
<p>or for all keys:</p>
<pre><code>[d1[k].update(d2[k]) for k in d1]
</code></pre> | python|dictionary | 0 |
4,550 | 46,382,525 | Python - Mean of each value across keys in dict | <p>I am having trouble iterating across an entire dictionary to do simple summary statistics (an average) for each element of a value across keys. </p>
<p>My dictionary consists of keys and values that are lists of numbers:</p>
<pre><code>test_dict={'NJ':[20,50,70,90,100],'NY':[10,3,0,99,57],'CT':[90,1000,2,3.4,5]}
<... | <p>Not sure where your error lies but the <code>i</code> is a dead giveaway for "using indices where it's not useful / harmful".</p>
<p>Your problem has a straight input/output data stream, and is a perfect match for using dictionary comprehension, iterating on the key, values and rebuilding the dict with the mean as ... | python|loops|dictionary | 1 |
4,551 | 60,832,299 | Alternative to: Sorting List by two arguments with 'Key-Function' | <p>Goal:</p>
<ul>
<li>Sorting List by 'Key-Function' with two Functions A, B</li>
<li>Start sorting with Function A</li>
<li>For each element, with the same A(element) value, sort those elements by B(element)</li>
</ul>
<p>Problem:</p>
<ul>
<li>Function A is fast and efficient (duplicates can happen!)</li>
<li>Funct... | <p>Here is a possible solution:</p>
<pre><code>from collections import Counter
A_values = [A(e) for e in elements]
c = Counter(A_values)
B_values = [B(e) if c[a] > 1 else None
for e, a in zip(elements, A_values)]
sorted_elements = [e for a, b, e in sorted(zip(A_values, B_values, elements))]
</code></pr... | python-3.x | 1 |
4,552 | 49,714,510 | find a cube root with Newton's method | <p>Newton's method is to find successively better approximations to the roots of polynominal.<br>
I have learned to find square root like:</p>
<pre><code> from sys import argv
script, k,epsilon = argv
def find_square_root(k, epsilon):
guess = k/2
while abs(guess**2 -k) >= epsilon:
... | <p>Following <a href="http://www.mathpath.org/Algor/cuberoot/cube.root.newton.htm" rel="nofollow noreferrer">this link</a>:</p>
<pre><code>def find_cube_root(k, epsilon):
guess = k
while(((1/3)*(2*guess + k/guess**2))**3 - k >= epsilon):
guess = (1/3)*(2*guess + k/guess**2)
print(f"Cube root of {k} is a... | python|python-3.x|algorithm | 1 |
4,553 | 49,539,353 | create addition program like package | <p>like this following example how can I do addition program.</p>
<h1>mammal.py</h1>
<pre><code>class Mammals:
def __init__(self):
''' Constructor for this class. '''
# Create some member animals
self.members = ['Tiger', 'Elephant', 'Wild Cat']
def printMembers(self):
print... | <p>I'm uncertain of exactly what you want, but I'm guessing that you want a program that uses your addition class, right?</p>
<p>It should look something like this:</p>
<p><strong>addition.py</strong></p>
<pre><code>class Addition:
def add():
a=int(input("Enter the number : "))
b=int(input("Enter the number... | python|math|package | 0 |
4,554 | 49,441,984 | Convert string representation of a list in sqlite3 database while making SELECT command | <p>I have an sqlite3 database, where one of the columns contains a string representation of a list (ex: "['hello', 'there', 'example']"). I need to use a SELECT command and the LIKE clause to extract rows where an element of such a 'list' contains a certain substring. I know how to build a command that extracts rows th... | <p>You almost certainly don't want to do this. This will become less and less performant as your database increases in size. This is because when this query is performed, your DB engine has to scan linearly through every single row to perform some expensive string operations on that column.</p>
<p>What you want instea... | python|sqlite | 0 |
4,555 | 49,581,213 | Is there a better way to assign a new value to a numpy array scalar? | <p>I am doing some quick calculations on a scalar value from a numpy array. As it says in the <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html#array-scalars" rel="nofollow noreferrer">documentation</a>, </p>
<blockquote>
<p>The primary advantage of using array scalars is that they preserve th... | <p>A 0d array can be modified, but an <code>array scalar</code> cannot:</p>
<pre><code>In [199]: x = np.array(1.0, 'float32')
In [200]: x
Out[200]: array(1., dtype=float32)
In [201]: x.shape
Out[201]: ()
In [202]: x[...] = 2
In [203]: x
Out[203]: array(2., dtype=float32)
In [204]: x[()] =3
In [205]: x
Out[205]: array(3... | python|arrays|numpy|scalar|copy-assignment | 7 |
4,556 | 21,353,977 | Why do pyplot methods apply instantly and subplot axes methods do not? | <p>I'm editing my graphs step by step. Doing so, <code>plt</code> functions from <code>matplotlib.pyplot</code> apply instantly to my graphical output of pylab. That's great.</p>
<p>If I address axes of a subplot, it does not happen anymore.
Please find both alternatives in my minimal working example.</p>
<pre><code>... | <p>The <code>plt.xticks()</code> method calls a function <code>draw_if_interactive()</code> that comes from <code>pylab_setup()</code>, who is updating the graph. In order to do it using <code>sp1.set_xticks()</code>, just call the corresponding <code>show()</code> method:</p>
<pre><code>sp1.figure.show()
</code></pre... | python|matplotlib|plot|pandas | 1 |
4,557 | 21,097,266 | How can I use a regex subpattern with a named group in Python? | <p>I am translating a regex-heavy script from Perl to Python and I have a problem with regex subpatterns.</p>
<p>In Perl, if I write the following works as expected, i.e. the string "OK" is written. I have never given it much thought, but it just looks like Perl knows that those are different groups although they have... | <p>This can be done using true regular expressions.</p>
<pre><code>ident0 = r"[a-zA-Z_] \w*"
ident1 = r"' [a-zA-Z_] \w* '"
ident2 = r"\" [a-zA-Z_] \w* \""
ident3 = r"` [a-zA-Z_] \w* `"
ident = "(?:" + ident0 + "|" + ident1 + "|" + ident2 + "|" + ident3 + ")"
</code></pre> | python|regex|perl | 2 |
4,558 | 62,674,205 | I would like to pass raw HTML to QWebEngineView but getting errors | <pre><code>app = QApplication(sys.argv)
abc = pd.read_csv("filepath")
web = QWebEngineView()
web.load(QUrl.fromLocalFile(abc.to_html())
web.show()
sys.exit(app.exec_())
</code></pre> | <p>If you are going to load html then you must use the <a href="https://doc.qt.io/qt-5/qwebengineview.html#setHtml" rel="nofollow noreferrer"><code>setHtml()</code></a> method:</p>
<pre><code>web.setHtml(abc.to_html())
</code></pre> | python|pyqt|pyqt5|qtwebengine|qwebengineview | 0 |
4,559 | 53,361,062 | What can cause a dask distributed future to have the state 'lost'? | <p>Using a dask distributed cluster, I've noticed, that several of the futures of long running tasks switch from <code>pending</code> to <code>finished</code>, others switch from <code>pending</code> to <code>lost</code>. </p>
<p>I have the suspicion, that some of the <code>lost</code> tasks are still running, as I se... | <p>This means that for some reason the scheduler no longer has the information necessary to execute this task. Commonly this is due to non-resilient data being lost by a worker going down, such as if you explicitly scatter a piece of data to a single worker and then that worker fails.</p>
<pre><code>>>> futu... | python-2.7|distributed|dask | 2 |
4,560 | 53,635,457 | Python3: convert big int to float - wrong result - how do it right? | <p>I need to do some division on a very big int in python3 <em>(Version 3.6.7)</em>. Since I always got wrong results after the division (checked with small numbers), I figured out that it is the conversion between int and float.</p>
<p>Why does <code>int(float(number))</code> give back another number than given in th... | <p>This is tipical of binary floating-point arithmetic. <a href="https://docs.python.org/3/tutorial/floatingpoint.html" rel="nofollow noreferrer">Python doc just here.</a> </p>
<p>You should take a look about <strong>Decimal</strong> module in your case.</p>
<pre><code>from decimal import *
int(Decimal('1111215645465... | python-3.x|type-conversion|int | 0 |
4,561 | 33,142,651 | Use unicode as predicate in xpath with lxml and python 2.7 | <p>I've been facing the problem where I have an XML file with Unicode strings and need to evaluate an Xpath on it, through lxml in Python-2.7.</p>
<pre><code># -*- coding: utf-8 -*-
from lxml import etree
...
class Language:
description = None
def __init__(self, description):
xpath = "//language[./description = '... | <p>Stop mixing them.</p>
<pre><code>xpath = u"//language[./description = '{}']//description/text()".format(description)
</code></pre> | python-2.7|xpath|unicode|lxml | 1 |
4,562 | 24,531,336 | Pandas: apply tupleize_cols to dataframe without to_csv()? | <p>I like the tupleize_cols option in the to_csv() function. Is this function available on a in-memory dataframe? I would like to clean up the tuples of the multi-indexed columns to 'reportable' column names automatically.</p>
<p>Thanks,</p>
<p>Luc</p> | <p>Just use <code>.values</code> on the index</p>
<pre><code>In [1]: i = pd.MultiIndex.from_product([[1,2,3],['a','b','c']])
In [2]: i
Out[2]:
MultiIndex(levels=[[1, 2, 3], [u'a', u'b', u'c']],
labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]])
In [3]: i.values
Out[3]:
array([(1, 'a'), (... | pandas|dataframe | 1 |
4,563 | 41,191,288 | Python: Dictionary changing | <p>For some reason when I modify mydict2 it changes the contents of mydict</p>
<p>Here is my code:</p>
<pre><code>mydict = {1:'a', 2:'b'}
mydict2 = mydict
mydict2[1] = 'c'
print(mydict2)
</code></pre>
<p>If you try this, it outputs <code>{1: 'c', 2: 'b'}</code></p>
<p>It should output <code>{1: 'a', 2: 'b'}</code> ... | <p><code>mydict</code> and <code>mydict2</code> are both references to the same object.</p>
<p>So changes to <code>mydict</code> or <code>mydict2</code> will change the same object, and therefore it looks like changing one of them is changing the other.</p> | python|python-3.x|dictionary | 1 |
4,564 | 30,900,037 | Reading from linux command line with Python | <p>Is there a way to read data that is coming into the command-line, straight into another Python script for execution?</p> | <p>You need to read <code>stdin</code> from the python script.</p>
<pre><code>import sys
data = sys.stdin.read()
print 'Data from stdin -', data
</code></pre>
<p>Sample run -</p>
<pre><code>$ date | python test.py
Data from stdin - Wed Jun 17 11:59:43 PDT 2015
</code></pre> | python|linux|shell|command-line | 4 |
4,565 | 58,921,536 | Stale Element in for loop even though I am searching for element at the beginning of each loop | <p>I am writing a for loop to go through a table of rows and perform an action for each row, then save. After saving, the webpage is reloaded automatically. In order to avoid a stale element exception, I call on the web element at the beginning of the loop after the webpage has refreshed. It works fine for the first lo... | <p>I would try refactoring the following lines:</p>
<pre><code>yp = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.XPATH, "//table/tbody/tr/td[6]")))[counter]
actionChains.double_click(yp).perform()
</code></pre>
<p>into something a little different:</p>
<pre><code>yp = WebDriverWait(drive... | python-3.x|selenium|selenium-chromedriver | 0 |
4,566 | 52,289,366 | Store a base64 image in python memory, then retrieve for use in wxpython/PIL | <p>1) I have an image that I converted to a string. It looks like this: </p>
<pre><code>bytesimage = b'iVBORw0KGgoAAAANSUhEUgA.... etc etc
</code></pre>
<p>2) I can convert it to an 'bytesimage.png' using:</p>
<pre><code>def StringToImage(self, stringname, imageoutput):
imgdata = base64.b64decode(stringname)
... | <p>StringIO seems to be the way to go. It allows you to pass the decoded string directly to PIL.</p>
<pre class="lang-python prettyprint-override"><code>import base64
from PIL import Image
import StringIO
# Banana emoji (JPG) as a b64 string.
b64_img_str = '/9j/4AAQSkZJRgABAQEAYABgAAD/4QCKRXhpZgAATU0AKgAAAAgABVEAAAQA... | python|image|memory|wxpython|python-imaging-library | 0 |
4,567 | 51,703,577 | Can we pass html log path in pytest from a variable in script | <p>I am new to <code>pytest</code>. I am looking for a way to generate html logging in pytest. I got one way which is generating html logs too like</p>
<pre><code>pytest script.py--html=report.html
</code></pre>
<p>It is working. But the problem is the html report path. Can I provide html path in a var that is presen... | <p>If you just want to generate the HTML report without entering the <code>--html</code> argument every time, you can persist it in the config file. Create a file named <code>pytest.ini</code> with the content:</p>
<pre><code>[pytest]
addopts=--html my_report.html
</code></pre>
<p>Now running <code>pytest</code> will... | python|pytest | 3 |
4,568 | 51,957,757 | python - can't get audio player working | <p>everything works except the next song doesn't play after the first is finished.</p>
<pre><code>import os, random
from pygame import mixer
from pynput import keyboard
startup = 0
pause = 0
volume = 0.5
def Picker():
global startup
global volume
startup += 1
if startup > 1:
ThisSong = rando... | <p>Working solution, incase anyone else has the same problem as me in the future :)</p>
<pre><code>from pygame import mixer
from pynput import keyboard
import threading
import random
import os
paused = 0
def player():
song = random.choice(os.listdir("C:\\users\\...\\desktop\\music"))
mixer.init()
mixer.m... | python|python-3.x | 0 |
4,569 | 56,168,364 | Beautiful Soup is giving none, though value is present | <p>Why my following code is giving an output <code>NONE</code></p>
<pre><code>from bs4 import BeautifulSoup
import urllib3
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
urllib3.disable_warnings()
url = "https://www.amazon.ae/dp/B07N62ZGWQ/ref=br_msw_pdt-5?_encoding=UTF8&smid=ABO0A2K2SKD... | <p>First, I altered <code>urllib3</code> to <code>requests</code> because <code>urllib3</code> was giving an exception</p>
<p>See the code below:</p>
<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup
url = "https://www.amazon.ae/dp/B07N62ZGWQ/ref=br_msw_pdt-5?_encoding=UTF... | python|beautifulsoup | 2 |
4,570 | 67,482,108 | discord.py - Guessing game no response | <p>The following code is supposed to be executed when <code>$play</code> is typed into a channel on my Discord Server but the bot doesn't respond or react in any way.</p>
<pre><code>bot = commands.Bot(command_prefix='$')
@bot.command(name="play")
async def play(ctx):
def check(m):
return m.author == ct... | <p>Because there’s a logic error in your code, in all the if/elif statements you’re checking if <code>guess.content</code> (a string) is less/higher/equal than an integer, that’s never true, then in your else statement you’re not sending anything at all (you’re returning, exiting out of the function instead of sending ... | python|discord|discord.py | 3 |
4,571 | 63,546,116 | Im trying to read a log file which is written in text in my Python program but its returning an "No such file or directory" | <p>Even though it in the same directory as the Python file it cannot be red</p>
<pre><code>from datetime import datetime
infile = r"./system.log.txt"
logFile = []
def readLog():
with open(infile) as f:
f = f.readlines()
for line in f:
temp= line.split('\n')
logFile.a... | <p>I am assuming you have this sructure<br />
folder<br />
|--sys.log.txt<br />
|--main.py</p>
<p><code>cd folder</code> then <code>python main.py</code></p>
<pre class="lang-py prettyprint-override"><code>file='system.log.txt'
with open(file,'r') as f:
print(f.read())
</code></pre> | python | 1 |
4,572 | 36,506,622 | Creating similar multiple sub-folders in multiple different folders using python | <p>How do I create a multiple different folders that also contain multiple different folders using python?<br>
My path is: './work/animals/'. The 'animals' directory contains the folders 'cat', 'dog', 'horse', 'mouse', 'lion', 'cheetah', 'rat', 'baboon', 'donkey', 'snake' and 'giraffe'.
I have managed to write the part... | <p>You can use <code>itertools.product</code> to get the combinations of animals plus gender that you want and then use <code>os.makedirs</code> which will create intermediate directories for you.</p>
<pre><code>import os
import itertools
root_path = './work/animals/'
folders = ['cat','dog','horse','mouse','lion','c... | python|directory | 1 |
4,573 | 36,267,794 | Meaning of a function "-> str" | <pre><code>def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs
</code></pre>
<p>In the above block of code which got from <b><a href="https://docs.python.org/3.5/tutorial/controlflow.html#documentation-strings" r... | <p>Those are type hints. Various type checkers can use them to determine if you're using the correct types. In your example, you function is expecting <code>ham</code> of type <code>str</code>, and <code>eggs</code> of type <code>str</code> (defaulting to <code>eggs</code>). The final <code>-> str</code> implies tha... | python | 3 |
4,574 | 13,555,712 | Numpy sum over planes of 3d array, return a scalar | <p>I'm making the transition from MATLAB to Numpy and feeling some growing pains.</p>
<p>I have a 3D array, lets say it's 3x3x3 and I want the scalar sum of each plane.
In matlab, I would use:</p>
<pre><code>sum_vec = sum(3dArray,3);
</code></pre>
<p>TIA
wbg</p>
<p>EDIT: I was wrong about my matlab code. Matlab onl... | <p>You can do</p>
<pre><code>sum_vec = np.array([plane.sum() for plane in cube])
</code></pre>
<p>or simply</p>
<pre><code>sum_vec = cube.sum(-1).sum(-1)
</code></pre>
<p>where <code>cube</code> is your 3d array. You can specify <code>0</code> or <code>1</code> instead of <code>-1</code> (or <code>2</code>) dependi... | numpy | 7 |
4,575 | 22,143,352 | How to slice and extend a 2D numpy array? | <p>I have a numpy array of size <code>nxm</code>. I want the number of columns to be limited to <code>k</code> and rest of the columns to be extended in new rows. Following is the scenario -</p>
<p>Initial array: <code>nxm</code></p>
<p>Final array: <code>pxk</code></p>
<p>where <code>p = (m/k)*n</code></p>
<p>Eg. ... | <p>Here's one way to do it</p>
<pre><code>q=array([[1, 2, 3, 4, 5, 6,],
[7, 8, 9, 10, 11, 12]])
r=q.T.reshape(-1,2,2)
s=r.swapaxes(1,2)
t=s.reshape(-1,2)
</code></pre>
<p>as a one liner, </p>
<pre><code>q.T.reshape(-1,2,2).swapaxes(1,2).reshape(-1,2)
array([[ 1, 2],
[ 7, 8],
[ 3, 4],
... | python|numpy | 4 |
4,576 | 16,630,295 | How to use only a part a tuple from return | <p>This question maybe is a little awkward but i don't wanna unused variables. for example:</p>
<pre><code>height, width = my_function()
</code></pre>
<p>i wanna use only the width value, there is a way to assign only the <code>width</code> value, example:</p>
<pre><code>, width = my_function()
</code></pre> | <p>If you only want to assign <code>width</code>, you can simply do <code>width = my_function()[1]</code></p> | python | 3 |
4,577 | 16,732,813 | HTTP Response problems with Django form | <p><br>
at the moment, I try to make a search form for a small database.</p>
<p>This is a part of my models.py file:</p>
<pre><code>from django.db import models
from django import forms
#...
class searchForm(forms.Form):
searchField = forms.CharField(max_length = 100)
#...
</code></pre>
<p>This is a part of my vi... | <p>First: The form isn't showing up because as you say, you want it to appear in <code>index.html</code> but the <code>index</code> view isn't passing any form to the template. Is in <code>search</code> view where you pass the form the template.</p>
<p>If you want the behavior described you should reorganize the code ... | python|django|forms | 3 |
4,578 | 43,530,200 | create permutations of one column grouping by another column pandas | <p>I have a dataframe like this: </p>
<pre><code>In [1]: df = pd.DataFrame([['jon snow', 'jon-snow'], ['jon snow', 'jon+snow'], [jon snow, 'jonsnow']], columns=['name', 'name_variation'])
</code></pre>
<p>What I want is : </p>
<pre><code>df_want = pd.DataFrame([['jon snow', 'jon-snow', 'jon-snow'],
['... | <h1><code>numpy</code></h1>
<pre><code>u = pd.unique(df.values.ravel())
r = np.arange(u.size)
i, j = r.repeat(u.size), np.tile(r, u.size)
pd.DataFrame(dict(
name=['jon snow' for _ in range(i.size)],
name_variation=u[i],
name_variation2=u[j]
))
name name_variation name_variation2
0... | python|pandas|group-by|cartesian-product | 2 |
4,579 | 43,562,952 | How to tell RandomizedSearchCV to choose from distribution or None value? | <p>Let's say we are trying to find best <code>max_depth</code> parameter of <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier" rel="nofollow noreferrer"><code>RandomForestClassifier</code></a>. We are using <a href="http://scik... | <p>Also from the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html#sklearn.model_selection.RandomizedSearchCV" rel="nofollow noreferrer">docs</a>: "If a list is given, it is sampled uniformly." Use this:</p>
<pre><code>'max_depth': list(range(1, 100)) + [None]
</... | python|scipy|scikit-learn|random-forest|hyperparameters | 3 |
4,580 | 71,279,263 | How to Iterate over two lists and position the elements of the output list differently in python pandas? | <p>How to iterate over two lists such that the output list should have the first value of the first list as the first element, the first value of the second list as the last element, the second value of the first list as the second element, the second value of the second list as the second last element and so on and th... | <p>This is a possible solution:</p>
<pre><code>from itertools import zip_longest
lst = [[], []]
s = set()
for t in zip_longest(a, b):
for i, x in enumerate(t):
if x is not None and x not in s:
lst[i].append(x)
s.add(x)
c = lst[0] + lst[1][::-1]
</code></pre> | python|pandas|list | 0 |
4,581 | 9,264,299 | How does one unit test handling of the error conditions for Python/C APIs like PyType_Ready and PyObject_New? | <p>It's fairly straightforward (if tedious) to unit test Python extension modules written in C, including the error cases for many of the Python/C APIs such as PyArg_ParseTuple. For example, the idiomatic way to start a C function which implements a Python function or method looks like:</p>
<pre><code> if (!PyArg_... | <p>This is a clear case for test doubles (for example, mocking). Since the Python C API doesn't offer any facilities for faking an out of memory condition, you'd have to do it yourself.</p>
<p>Create your own layer that provides <code>PyType_Ready</code> and <code>PyObject_New</code>. Have them pass through to the C... | python|c|unit-testing | 2 |
4,582 | 9,607,573 | Passing variable inside of function to a variable outside of function | <p>I am trying to set a new variable to reference a variable inside a function. My pseudo code goes like this:</p>
<pre><code>def myfunction():
a bunch of stuff that results in
myvariable = "Some Text"
</code></pre>
<p>Further down the code I have this:</p>
<pre><code>for something in somethinglist:
if some... | <p>As written, <code>myvariable</code> is only defined within the scope of <code>myfunction</code>.<br>
To make the value in that variable available outside of the function you can return it from the function:</p>
<pre><code>def myfunction():
myvariable = "Some Text"
return myvariable
</code></pre>
<p>And the... | python|function|variables | 4 |
4,583 | 39,206,298 | How to query a one to many/many to many relationship in Flask SQL Alchemy? | <p>These are two database models that are important in my problem. </p>
<p><b>I have established a one to many relationship (a Conversation can have multiple Messages) </b>
There is also a many to many relationship established between User and Conversation. </p>
<p><b>After obtaining two User objects, say <i>user1... | <p>The best way I know to do this is to use SQLAlchemy's <a href="http://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.properties.RelationshipProperty.Comparator.contains" rel="nofollow">contains</a>. </p>
<pre><code>Conversation.query.filter(
Conversation.users.contains(user1),
Conversation.... | python|flask|sqlalchemy | 3 |
4,584 | 52,765,384 | Why isn't np.nan_to_num() converting this (n x m) array? | <p>I would like to set all <code>nan</code> entries in my numpy array <code>a</code> to zero.</p>
<p>Regardless how I use <code>np.nan_to_num()</code>, the array is not processed at all (it still leaves <code>np.nan</code> in the array)</p>
<pre><code>import numpy as np
a = np.empty((0, 3), dtype='object')
for runne... | <p>As the <code>nan_to_num</code> docstring states:</p>
<blockquote>
<p>If <code>x</code> is not inexact, then no replacements are made.</p>
</blockquote>
<p>And dtype object does not count as inexact.</p>
<p>If for some reason one needs to use dtype object (perhaps one wants to have <code>nan</code>s and exact <c... | python|arrays|numpy|type-conversion|nan | 2 |
4,585 | 47,985,433 | sort by a value in Pandas column | <p>I groupby my data as follows in Pandas:</p>
<p>df.groupby(by=['industry', 'country', 'category'])['category'].count()</p>
<p>The DataFrame looks something like this after the groupby:</p>
<pre><code>---------------------------------------
Industry | Country | category |
------------------... | <p>The following should work for what you need:</p>
<pre><code>df = df.groupby(by=['industry', 'country', 'category'])['category'].count().reset_index()
df.sort_values(by='category', ascending=True, na_position='Last',inplace=True)
</code></pre> | python|django|pandas|sorting | 0 |
4,586 | 47,978,137 | Reading image data using a .txt file containing file names | <p>I am using Tensorflow to make a CNN that can classify images. I have a <code>images.txt</code> file that contains a list of the <code>.jpg</code> files along with their corresponding labels, with the following format:</p>
<pre><code>image1.jpg,4
image2.jpg,3
image3.jpg,2
</code></pre>
<p>I have written a function ... | <p>The optimized way of doing this is to use Tensorflow for doing everything.</p>
<p>There's a straightforward way to do this:</p>
<pre><code># load csv content
csv_path = tf.train.string_input_producer(['images.txt'])
textReader = tf.TextLineReader()
_, csv_content = textReader.read(csv_path)
im_name, label = tf.dec... | python|tensorflow|conv-neural-network|pillow | 2 |
4,587 | 47,710,894 | Index find position for matching string | <p>Consider following example</p>
<pre><code>index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index
</code></pre>
<p>I want to find the position of 'a' in the index "index_id". How do I do that. Tryin... | <p>Try this:</p>
<pre><code>index = pd.Index(list(df))
print index.get_loc('a')
</code></pre> | python|pandas|dataframe|indexing | 1 |
4,588 | 47,946,875 | get the Alarm object of CloudWatch using boto 2 | <p>I created an alarm and want to delete it afterward...
The <a href="http://boto.cloudhackers.com/en/latest/ref/cloudwatch.html" rel="nofollow noreferrer">documentation</a> for boto 2 doesn't show how to do that.</p>
<p>Any help ?
Thanks</p> | <p>If you want to delete alarms, the API you need is <code>DeleteAlarms</code>. The link you have in your question is mentioning it (search for <code>delete_alarms</code>).</p>
<p>Also, boto 3 is the recommended version to use and here is the API you need: <a href="https://boto3.readthedocs.io/en/latest/reference/serv... | python|amazon-web-services|amazon-ec2|boto3|amazon-cloudwatch | 2 |
4,589 | 47,551,406 | extract the skills from one file after matching with datasets using python | <pre><code>inputfile=open('inputfile.txt', 'r')
cleaned_resume= inputfile.read()
def fetch_skills(cleaned_resume):
with open('skillsdata.csv', 'r') as skills:
skill_set=[]
for skill in skills:
if skill in cleaned_resume:
print(skill)
skill_set.append(ski... | <p>Try running this:</p>
<pre><code>def fetch_skills(cleaned_resume=None):
with open('skillsdata.csv', 'r') as skills:
skill_set=[]
for skill in skills:
if skill in cleaned_resume:
skill_set.append(skill)
# Stripping newlines and tabs
skill_set = [s.rstrip() fo... | python|python-3.x | 0 |
4,590 | 47,760,063 | How to find the index of a sorted series? | <p>I suspect I am misunderstanding something. </p>
<blockquote>
<p><strong>Problem</strong>: Given a series, I want to return a new series where the value
at each row would be the index if that series was sorted.</p>
</blockquote>
<p>I posted a different question and seemed like <code>argsort</code> was the right... | <p>We can using <code>rank</code> </p>
<pre><code>test.rank(method ='first')-1
Out[917]:
red 1.0
green 8.0
yellow 3.0
purple 9.0
orange 4.0
white 0.0
black 7.0
pink 2.0
brown 5.0
gray 6.0
Name: tt, dtype: float64
</code></pre> | python|pandas|numpy | 1 |
4,591 | 37,594,908 | Pass all data from 2 column MySQL table into Python variable | <p>I'm trying to pass all data from 2 column (label, tweets) from my table in MySQL into Python variable and use it as training data for my classifier. what I want is for example if I print(data[0]), then I can get ([('tweet'), 'label'] using the code below</p>
<p><div class="snippet" data-lang="js" data-hide="false" ... | <p>I'm not sure about the structure of your tables, and I don't really understand what you are trying to calculate in your <code>review</code>. Anyway, I hope this might help: the result of <code>read_sql_query</code> is a dataframe, thus you have to treat it as such.</p>
<p>In the example below the table "tweet" cont... | python|mysql|twitter|machine-learning|text-classification | 1 |
4,592 | 34,319,121 | ElementTree text mixed with tags | <p>imagine the following text:</p>
<pre><code><description>
the thing <b>stuff</b> is very important for various reasons, notably <b>other things</b>.
</description>
</code></pre>
<p>How would I manage to parse this with the <code>etree</code> interface? Having the <code>descriptio... | <p>Get the <code>.text_content()</code>. Working sample using <a href="http://lxml.de/lxmlhtml.html" rel="nofollow"><code>lxml.html</code></a>:</p>
<pre><code>from lxml.html import fromstring
data = """
<description>
the thing <b>stuff</b> is very important for various reasons, notably <b>o... | python|html|elementtree | 1 |
4,593 | 7,669,462 | Get a whole unicode sentence | <p>I'm trying to parse a sentence like <code>Base: Lote Numero 1, Marcelo T de Alvear 500. Demanda: otras palabras.</code> I want to: first, split the text by periods, then, use whatever is before the colon as a <code>label</code> for the sentence after the colon.
Right now I have the following definition:</p>
<pre><c... | <p>To directly answer your question, wrap your value definition with <code>originalTextFor</code>, and this will give you back the string slice that the matching tokens came from, as a single string. You could also add a parse action, like:</p>
<pre><code>value.setParseAction(lambda t : ' '.join(t))
</code></pre>
<p... | python|nlp|pyparsing|text-segmentation | 2 |
4,594 | 31,801,633 | Python Program to generate the Private IP Addresses | <p>Below given program is to generate N number of private IP addresses randomly.</p>
<p>If x1 = 172,x2 value should be from 16 to 31...But it generate the value from 0 to 255... Can someone please have a look and let me know what could be the error? </p>
<p><strong>Code:</strong></p>
<pre><code>import random
n = in... | <p>That is because you are checking <code>int with string</code></p>
<p><strong>i.e)</strong></p>
<pre><code>1=="1"
Out[10]: False
</code></pre>
<p><strong>Modification:</strong></p>
<pre><code>import random
n = int(raw_input("How many IP addresses need to be generated \n"))
x1 = random.choice(["172","192","10"]) ... | python | 2 |
4,595 | 38,947,278 | df.mean is not the real mean of the Series? | <p>I'm debugging and run into the following strange behavior.
I'm calculating the mean of a pandas series which contains all exactly the same numbers. However, the <code>pd.mean()</code> gives a different number.</p>
<p>question1: why mean of this Series is a different number?</p>
<p>question2: <code>tmm[-1]== tmm.me... | <p>Try using <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html" rel="nofollow">np.isclose()</a></p>
<pre><code>tmm[20]== tmm.mean()
False
np.isclose(tmm[20], tmm.mean())
True
</code></pre> | python|pandas | 2 |
4,596 | 38,804,986 | Replacing pairs of variables in a file | <p>I working on a problem and my goal is to replace variables in the file and the name of the files.
The issue is that I have to change a couple of variables at the same time for all combinations (Generally 24 combinations).</p>
<p>I know how to create of all combinations of strings, but I want to put lists inside a... | <p>I think I almost tackled the above problem:</p>
<pre><code>#!/usr/bin/env python
import itertools
import copy
def replace_variables(i, distance ='0', T1 ='0', T2 = '0', gamma = '0' ):
k_ = copy.deepcopy(i)
k_[0][0] = '-2'
k_[1][0] = '2'
template_new = template.replace('*distance*',... | python | 0 |
4,597 | 40,506,559 | how to resize cifar10 image from 32x32 to 227x227? | <p>I have read the image from cifar-10-batches-python</p>
<pre><code>import os
import numpy as np
from PIL import Image
from pylab import *
import matplotlib.pyplot as plt
from scipy.misc import imresize
# read data
data_dir = "F:\\dataSet\\cifar-10-batches-py"
testdata_dir="F:\\dataSet\\cifar-10-batches-py\\test_batc... | <p>You can use opencv to pre-process the images-</p>
<pre><code>import cv2
img = cv2.imread('IMAGE_LOCATION')
img_fin = cv2.resize(img, (227, 227))
</code></pre> | python|deep-learning|image-resizing|keras | 1 |
4,598 | 51,637,718 | python: how to get up until the last error made by my code | <p>So when I run this... the error is on this line <code>bomb=pd.DataFrame(here,0)</code> but the trace shows me a bunch of code from the <code>pandas</code> library to get to the error. </p>
<pre><code>import traceback,sys
import pandas as pd
def error_handle(err_var,instance_name=None): #err_var list of var... | <p>You can define how far back a traceback goes using the <a href="https://docs.python.org/3/library/sys.html#sys.tracebacklimit" rel="nofollow noreferrer"><code>sys.traceback</code></a> variable. If your code is only 3 levels deep, (a function in a class in a file), then you can define this appropriately with the code... | python|error-handling | 4 |
4,599 | 68,099,745 | How to get (fast) first non-Nan daily value of a DataFrame while keeping the shape and index? | <p>I have the following <code>pd.DataFrame</code></p>
<pre><code>from datetime import datetime
df1 = pd.DataFrame(
data=[[0, 0, 1], [0, 1, 1], [1, 1, 0], [1, 1, 0], [0, 0, 1], [0, 1, 1], [1, 1, 0], [1, 1, 0]],
index=[
datetime(2020, 1, 1, 1, 10), datetime(2020, 1, 1, 1, 15), datetime(2020, 1, 1, 1, 20),... | <p>One solution:</p>
<p>just get the first 1 value in each row:</p>
<pre><code>df1[df1.cumsum(axis=1)!=1] = 0
</code></pre>
<p>set a temporary date col</p>
<pre><code>df1["date"] = df1.index.date
</code></pre>
<p>set any duplicated rows to 0</p>
<pre><code>df1[df1.duplicated()] = 0
</code></pre>
<p>get rid of... | python|pandas|dataframe | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.