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 |
|---|---|---|---|---|---|---|
1,300 | 71,124,205 | Show usages of module in Pycharm | <p>I have a module and am trying to find all the places any method defined in that module is used anywhere outside of it. Is there a function to do this? I'm aware of the call hierarchy tool window, but haven't managed to accomplish this exact use case.</p> | <p>In project view (where you see the file and directory structure), right click on the module you want to check, and click the <em>Find usages</em> on context menu.</p>
<p>Because you are using Python, you find where such module is imported (so not really where you use the functions), and from there you can find if th... | python|pycharm | 1 |
1,301 | 9,551,365 | swapping between menus in python | <p>How should I write this so I could constantly move between "menus".</p>
<pre><code> #!/bin/env python
import os
class Menu:
def __init__(self):
self.menu = '1'
def Main(self):
os.system('clear')
print "main menu"
test = raw_input()
if test == '2':
... | <p>The first while loop runs, and when you enter '2', finishes. Therefore, the second while loop will begin to loop.</p>
<p>In the second while loop, you enter '1', which causes the second while loop to finish (because menu.menu is now == '1'). Thus, the program finishes.</p>
<p>Instead, you'll probably want one valu... | python | 0 |
1,302 | 39,143,204 | Getting specific indexed distinct values in nested lists | <p>I have a nested list of around 1 million records like:</p>
<pre><code>l = [['a', 'b', 'c', ...], ['d', 'b', 'e', ...], ['f', 'z', 'g', ...],...]
</code></pre>
<p>I want to get the distinct values of inner lists on second index, so that my resultant list be like:</p>
<pre><code>resultant = ['b', 'z', ...]
</code><... | <p>Since you want the unique items you can use <code>collections.OrderedDict.fromkeys()</code> in order to keep the order and unique items (because of using hashtable fro keys) and use <code>zip()</code> to get the second items.</p>
<pre><code>from collections import OrderedDict
list(OrderedDict.fromkeys(zip(my_lists... | python|nested-lists | 1 |
1,303 | 52,791,415 | In Tensorflow How can I add a Tensor to another Tensor with different shape? | <p>I use Tensorflow.
I want to add a tensor A whose shape is [64,64] (=[Batch size,values])
to another tensor B whose shape is [64,7,7,64].
I reshaped the tensor A, but it should have same number of elements as tensor B.
So, how can I reshape or expand tensor A. Or is there any other way to add A to B?
Specifically, I... | <p>Use <a href="https://www.tensorflow.org/performance/xla/broadcasting" rel="nofollow noreferrer">broadcasting</a>. Here you have an example:</p>
<pre><code>import tensorflow as tf
import numpy as np
A = tf.constant(np.arange(64*64), shape=(64, 64), dtype=tf.int32)
B = tf.ones(shape=(64, 7, 7, 64), dtype=tf.int32)
A... | python|tensorflow | 3 |
1,304 | 52,651,905 | In Python, is it a bad practice to "reset" an iterator when __iter__ is called? | <p>For example, let's say I have a class for iterating the records inside a file:</p>
<pre><code>class MySpecialFile:
...
def reset(self):
self._handle.seek(0)
def __iter__(self):
self.reset()
return self
</code></pre>
<p><strong>EDIT:</strong> </p>
<p>I just read this question m... | <p><code>iter</code> is expected to have no side effects. By violating this assumption, your code breaks all sorts of things. For example, the standard test for whether a thing is iterable:</p>
<pre><code>try:
iter(thing)
except TypeError:
do_whatever()
</code></pre>
<p>will reset your file. Similarly, the <a... | python|iterator|iterable | 2 |
1,305 | 47,759,007 | Pythonic way to handle function overloading | <p>I'm trying to write a function to invert a dictionary but I'm having troubles finding the proper way to do it without rewriting code, using different methods and avoiding if/else at each iteration. What's the most pythonic way to do it?</p>
<pre><code>def invert_dict(dic, type=None):
if type == 'list':
... | <p>I won't comment on the actual impementation, but for the type based branching there is <code>functools.singledispatch</code>:</p>
<pre><code>import functools
@functools.singledispatch
def inv_item(value, key, dest):
< fallback implementation >
# special case based on type
@inv_item.register(list)
@inv_i... | python|overloading | 1 |
1,306 | 34,113,441 | Python Tkinter Clear frame and associate user's answer to a value | <p>I am trying to clear the frame between each question that is asked in the multiple choice survey but I would like the frame itself to stay. I tried to created a next button that will allow the user to skip to the next question but the frame doesn't appear when I run my code (No error message is appering either). </p... | <p>One solution is to use an inner frame to hold your radiobuttons. Then, you can delete the frame which will delete all of the radiobuttons. Finally, you can recreate the frame with new radiobuttons.</p>
<p>Another solution is to simply iterate over the radiobuttons, reconfiguring them for the current question (assum... | python|tkinter|radio-button | 0 |
1,307 | 7,472,181 | c++ loop through registry recursively is slow | <p>Have an annoying problem with my code, probably I am doing something wrong because my Python
implementation is much faster!</p>
<p>C++ implementation problems:</p>
<ol>
<li>Iterating over "HKEY_CLASSES_ROOT" takes a lot of ram, I assume it's because c++ implementation uses lots of variables. <strong><em>Fixed</em>... | <p>There is leak of resource in your code. You open <code>hkey</code> but you close <code>hKey</code> (note the difference in case of <code>k</code> and <code>K</code>).</p>
<p>On a side note, you store the opened registry key into <code>hkey</code> itself. And it happens that <code>hkey</code> is the passed in parame... | c++|python|registry | 4 |
1,308 | 72,721,693 | cant automate calendar in selenium python | <p>I 'm trying to automate a calendar with selenium, but cant find a way through, structure of the calendar html is like this:</p>
<p><a href="https://i.stack.imgur.com/6o5Hv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6o5Hv.png" alt="img" /></a></p>
<p>6 divs containing a tags of each day, some ... | <p>Get all active elements:</p>
<pre><code>all_active_dates = self.driver.find_elements(By.XPATH, f'//*[@id="calweeks"]//a[not(contains(@class,'caldisabled')) and not(contains(@class,'caloff'))]')
</code></pre>
<p>and then just enumerate through <code>all_active_dates</code> and simply <code>print(active_dat... | python|selenium|xpath|calendar | 2 |
1,309 | 39,477,897 | MySQL On Update not triggering for Django/TastyPie REST API | <p>We have a resource table which has a field <code>last_updated</code> which we setup with mysql-workbench to have the following properties:</p>
<p>Datatype: <code>TIMESTAMP</code></p>
<p>NN (NotNull) is <code>checked</code></p>
<p>Default: <code>CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP</code></p>
<p>When I m... | <p>I suspect that the UPDATE statement issued by Django may be including an assignment to the <code>last_updated</code> column. This is just a guess, there's not enough information provided.</p>
<p>But if the Django model contains the <code>last_updated</code> column, and that column is fetched from the database into ... | python|mysql|django|mysql-workbench|tastypie | 1 |
1,310 | 38,736,722 | How to check input against a huge list? | <p>This is my code:</p>
<pre><code>while True:
print(vehiclelist)
reg = input('Enter registration number of vehicle: ')
if reg in vehiclelist:
break
else:
print("Invalid")
</code></pre>
<p>But it keeps showing its invalid, this is the output:</p>
<blockquote>
<p>[Ca... | <p>Here the problem is <code>vehicle_list</code> is a list of Vehicle objects and you can not directly search for a registration number inside a list of vehicle object.</p>
<p>A better design pattern is to use a dictionary in which <code>regNo</code> will appear as key and vehicle object will appear as value.</p>
<p>... | python | 1 |
1,311 | 40,744,501 | Centroid of a set of positions on a toroidally wrapped (x- and y- wrapping) 2D array? | <p>I have a flat Euclidean rectangular surface but when a point moves to the right boundary, it will appear at the left boundary (at the same y value). And visa versa for moving across the top and bottom boundaries. I'd like to be able to calculate the centroid of a set of points. The set of points in question are most... | <p>If cluster size is relatively small (smaller than half of grid), you can use simple approach:</p>
<p>Let's surface width and height are W and H. Imagine that the surface dimensions are tripled, so you have -W..2*W and -H..2*H axis ranges. Unroll wrapped values.</p>
<pre><code> XMin = X[0]; XMax = X[0]
the same f... | python|algorithm|math | 1 |
1,312 | 68,272,597 | Test method with a mock response, without create data | <p>I'm testing with unittest a method, createData, which create something in my database.</p>
<pre><code>def createData(self, content):
logging.info("Creating data...")
request = requests.post(self.url, data=content)
if request.status_code == 201:
logging.info("Data created")
... | <p>Well, I found how to resolve this problem : using patch decorator.
I guess it "defuses" requests post in data, substituting response with the configured mock</p>
<pre><code>import unittest, logging
from data import Data as data
from unittest.mock import patch
class TestData(unittest.TestCase):
@... | python|python-3.x|unit-testing|mocking|python-unittest | 1 |
1,313 | 63,059,111 | Error while trying to compile Python script to exe | <p>I'm trying to compile python script to exe.
My script - <code>hello.py</code>:</p>
<pre><code>print("hello")
</code></pre>
<p>My <code>setup.py</code>:</p>
<pre><code>from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
name = 'hello',
description = 'hello scr... | <p>py2exe seems to support up to Python 3.4 (thanks Michael Butscher)</p>
<p>However, there are other libraries such as Pyinstaller which work just fine, and are compatible with a variety of Python versions (from Python 2.7 to 3.5+)</p>
<p>Check it out, it's actually really easy :)</p>
<p><a href="https://pyinstaller.r... | python|python-3.x|py2exe|distutils | 0 |
1,314 | 63,034,394 | How to call functions from a python module in a different folder? | <p>My project structure is something like this:</p>
<pre><code>/project-name
app.py
/python-modules
login.py
home.py
</code></pre>
<p>I want to import some functions present in login.py and home.py into app.py.</p>
<p>I tried to run <code>from python-modules.login import *</code>, but no luck.</... | <p>Simple solution Just create blank (empty) <code>__init__.py</code> file in both folders i.e. project-name and python modules.</p> | python | 2 |
1,315 | 32,609,005 | using numpy repeat simultaneously on arrays with distinct multiplicities but same dimension | <p>I have two trival arrays of the same length, <em>tmp_reds</em> and <em>tmp_blues</em>: </p>
<pre><code>npts = 4
tmp_reds = np.array(['red', 'red', 'red', 'red'])
tmp_blues = np.array(['blue', 'blue', 'blue', 'blue'])
</code></pre>
<p>I am using <em>np.repeat</em> to create multiplicity: </p>
<pre><code>red_occupa... | <p>For a generic case -</p>
<pre><code># Two 1D color arrays
tmp1 = np.array(['red', 'red', 'red', 'green'])
tmp2 = np.array(['white', 'black', 'blue', 'blue'])
# Multiplicity arrays
color1_occupations = [1, 0, 1, 2]
color2_occupations = [0, 2, 0, 1]
# Stack those two color arrays and two multiplicity arrays separat... | python|arrays|performance|numpy|vectorization | 1 |
1,316 | 54,346,748 | Iterate excel files and output in one folder in Python | <p>I have a folder and subfolders structure as follows:</p>
<pre><code>D:/src
├─ xyz.xlsx
├─ dist
│ ├─ xyz.xlsx
│ ├─ xxx.zip
│ └─ xxy.xlsx
├─ lib
│ ├─ xy.rar
│ └─ xyx.xlsx
├─ test
│ ├─ xyy.xlsx
│ ├─ x.xls
│ └─ xyz.xlsx
</code></pre>
<p>I want to extract all excel files (xls or xlsx) from source directory and ... | <p>I think this will do what you want:</p>
<pre><code>import os
import shutil
src = os.path.abspath(r'.\_src')
dst = os.path.abspath(r'.\_dst')
wanted = {'.xls', '.xlsx'}
copied = set()
for root, dirs, filenames in os.walk(src, topdown=False):
for filename in filenames:
ext = os.path.splitext(filename)... | python|operating-system | 2 |
1,317 | 27,318,384 | Implementing ping using Python | <p>I'm trying to ping a range of servers and I want to store the output of the ping. This is as far as I have got. </p>
<pre><code>import subprocess
string_part = 'ping -W 2 -c 2 64.233.'
for i in range(160,165):
for j in range(0,5):
prompt = string_part + str(i) + '.' + str(j)
... | <p><code>subprocess.call()</code> returns the <em>exit code</em> of the process. To get the stdout output of the <code>ping</code> command, use a <a href="https://docs.python.org/2/library/subprocess.html#subprocess.PIPE" rel="nofollow">pipe</a> and <a href="https://docs.python.org/2/library/subprocess.html#subprocess.... | python|networking|subprocess|ping | 1 |
1,318 | 27,005,561 | How can I execute Python scripts using Anaconda's version of Python? | <p>I recently downloaded the Anaconda distribution for Python. I noticed that if I write and execute a Python script (by double-clicking on its icon), my computer (running on Windows 8) will execute it using my old version of Python rather than Anaconda's version. So for example, if my script contains <code>import matp... | <p>I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your <code>PYTHONPATH</code> or <code>PATH</code> every time you want to use a different interpreter. Sure, from the command line, <code>acti... | python|python-3.x|anaconda | 13 |
1,319 | 23,072,236 | how to implement CURL cli using python to consume REST services | <p>There are lot of questions posted how to consume the REST services with python, but none of them worked for me,
currently with the below curl cli i can get the authentication token.</p>
<p>curl cli</p>
<pre><code>curl -v --user username:pass1234 -H "content-type: application/json" -X POST -d "" https://mywebsite/... | <p>Have a look at the following HOWTO of the python documentation: <a href="https://docs.python.org/2/howto/urllib2.html" rel="nofollow">HOWTO Fetch Internet Resources Using urllib2</a>. There you also find a section with an code example for <a href="https://docs.python.org/2/howto/urllib2.html#id6" rel="nofollow">Basi... | python|json|rest|curl | 0 |
1,320 | 8,107,261 | ipython: %paste over ssh connection | <p>In ipython >=0.11, the %paste command is required to paste indented commands. However, if I run an ipython shell in a remote terminal, the buffer %paste refers to is on the remote machine rather than the local machine. Is there any way around this?</p> | <p>I think this is exactly what <code>%cpaste</code> is for (I am always forgetting about all the things IPython does). <code>%cpaste</code> enters a state allowing you to paste already formatted or indented code, and it will strip leading indentation and prompts, so you can copy/paste indented code from files, or eve... | ipython | 54 |
1,321 | 1,169,000 | Smart date interpretation | <p>I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation.</p>
<p>For example, you could type in 'two days ago' or 'tomorrow' and it would understand.</p>
<p>Any libraries to suggest? Bonus points if usable from Python.</p> | <p>Perhaps you are thinking of PHP's <code>strtotime()</code> function, the <a href="http://brian.moonspot.net/2008/09/20/strtotime-the-php-date-swiss-army-knife/" rel="noreferrer">Swiss Army Knife of date parsing</a>:</p>
<blockquote>
<p>Man, what did I do before <code>strtotime()</code>. Oh, I know, I had a 482 line... | python|date-parsing | 8 |
1,322 | 42,093,004 | TypeError: grid_configure() missing 1 required positional argument: 'self' | <pre><code>prompt = ">>"
from tkinter import *
root = Tk()
userName = Entry()
myLabel = Label(root, text="UserName")
userName.grid(row=0)
myLabel = Label.grid(row=0, column=1)
root.mainloop()
</code></pre>
<p>TypeError:
grid_configure() missing 1 required positional argument: 'self'</p> | <p>This statement is incorrect:</p>
<pre><code>myLabel = Label.grid(row=0, column=1)
</code></pre>
<p>At the very least it needs to be this:</p>
<pre><code>myLabel = Label().grid(row=0, column=1)
</code></pre>
<p>Though, if you want <code>mayLabel</code> to be anything other than <code>None</code> you need to use t... | user-interface|tkinter|python-3.5 | 1 |
1,323 | 47,382,463 | Looping through Where statement until a result is found (SQL) | <h2>Problem Summary:</h2>
<p>I'm using Python to send a series of queries to a database (one by one) from a loop until a non-empty result set is found. The query has three conditions that must be met and they're placed in a where statement. Every iteration of the loop changes and manipulates the conditions from a spec... | <p>Here is an idea</p>
<pre><code>select top 1
*
from
(
select
MyTable.*,
accuracy = case when description like keyword1 + '%'
and description like keyword2 + '%'
and description like keyword3 + '%'
then accuracy
end
-- an example of data from MyTabl... | python|sql|sql-server|sql-like | 1 |
1,324 | 38,017,401 | Patch all functions in module with decorator | <p>I have a python module with lots of functions and I want to apply a decorator for all of them.
Is there a way to patch all of them via monkey-patching to apply this decorator for every function without copy-pasting on line of applying decorator?</p>
<p>In other words, I want to replace this:</p>
<pre><code>@loggi... | <p>I'm really not certain that this is a good idea. <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Explicit is better than implicit</a>, after all.</p>
<p>With that said, something like this should work, using <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a> to fi... | python | 4 |
1,325 | 27,885,692 | Access to a dict's values | <p>I'm currently building small manager (learning python) using Pythons Flask, which uses the Jinja2 template engine. I'm using Peewee to talk to my database.</p>
<p>I have a dictionary of pins, which all contains info on the given pin. The info on the pins comes directly from Peewee, like so:</p>
<pre><code>pins = {... | <p>The issue is that you have made a dictionary, not a list. When you iterate through a dictionary via <code>for pin in pins</code>, you are iterating through the <em>keys</em>, not the values - so in each iteration you get one of 3, 5, 7 etc. Those values obviously don't have properties like <code>description</code>.<... | python|dictionary|flask|jinja2 | 1 |
1,326 | 27,508,266 | save a html string to PDF in python | <p>I have a html string which I want to store as a PDF file in python. I am using <a href="https://pypi.python.org/pypi/pdfkit" rel="nofollow">PDFkit</a> for that purpose. Below is the code which I tried for the purpose. In the below code I am also trying to serve the image via tornado server.</p>
<pre><code>class Mai... | <p><a href="https://pypi.python.org/pypi/pdfkit/0.4.1" rel="nofollow">This</a> link says that given the above error the path should be set to location of wkhtmltopdf binary. Which I thought I did. But it worked for me when the changed the config to</p>
<pre><code>config = pdfkit.configuration(wkhtmltopdf='E:\\wkhtmlto... | python|wkhtmltopdf|node-pdfkit | 0 |
1,327 | 27,469,477 | Reading Regular Expressions from a text file | <p>I'm currently trying to write a function that takes two inputs:</p>
<p><strong>1 - The URL for a web page
2 - The name of a text file containing some regular expressions</strong></p>
<p>My function should read the text file line by line (each line being a different regex) and then it should execute the given regex... | <p>Your string has some backlashes and other things escaped to avoid special meaning in Python string, not only the regex itself.</p>
<p>You can easily verify what happens when you print the string you load from the file. If your backslashes doubled, you did it wrong.</p>
<p>The text you want in the file is:</p>
<p>... | python|regex | 1 |
1,328 | 72,217,615 | N by N spiral matrix (1 to square(N)) - Unexpected Output | <p>While trying to create a N by N spiral matrix for number 1 to square(N) , using the usual algorithm for spiral matrix , there is an unexpected output in one of the rows which cannot be found even on rechecking.</p>
<pre><code>def getSpiralOrder(N):
matrix = [ [ 0 for i in range(N) ] for j in range(N) ]
c = 1
r... | <p>Your last two for loops are wrong:</p>
<pre><code>def getSpiralOrder(N):
matrix = [ [ 0 for i in range(N) ] for j in range(N) ]
c = 1
rS = 0
rE = len(matrix)
cS = 0
cE = len(matrix[0])
while(rS < rE and cS < cE):
for i in range(cS , cE ):
matrix[rS][i]=c
... | python | 1 |
1,329 | 43,343,973 | Stack dimensions of numpy array | <p>I have a numpy array of shape (2500, 16, 32, 24), and I want to make it into a ( something, 24) array, but I don't want numpy to shuffle my values. The 32 x 24 dimension at the end represent images and I want the corresponding elements to be consistent. Any ideas?</p>
<p>EDIT: Ok , I wasn't clear enough. (something... | <p>Use <code>arr.reshape(-1,arr.shape[-1])</code> or if you know it will be 24 <code>arr.reshape(-1,24)</code></p> | python|numpy|reshape | 0 |
1,330 | 43,424,960 | How to get basic interactive pyqtgraph plot to work in IPython REPL or Jupyter console? | <p>Typing</p>
<pre><code>import pyqtgraph as pg
pg.plot([1,2,3,2,3])
</code></pre>
<p>into the standard Python REPL opens a window containing a plot of the data. Typing exactly the same code into the IPython REPL or the Jupyter console, opens no such window.</p>
<p>[The window can be made to appear by typing <code>p... | <p>As sugested by @titusjan, the solution is to type</p>
<pre><code>%gui qt
</code></pre>
<p>(or some variation on that theme: see what other options are available with <code>%gui?</code>) in IPython <em>before</em> issuing any pyqtgraph (or PyQt in general) commands.</p> | ipython|pyqtgraph | 5 |
1,331 | 36,952,565 | Swap indexes using slices? | <p>I know that you can swap 2 single indexes in Python</p>
<pre><code>r = ['1', '2', '3', '4', '5', '6', '7', '8']
r[2], r[4] = r[4], r[2]
</code></pre>
<p>output:</p>
<pre><code>['1', '2', '5', '4', '3', '6', '7', '8']
</code></pre>
<p>But why can't you swap 2 slices of indexes in python?</p>
<pre><code>r = ['1'... | <p>The slicing is working as it should. You are replacing slices of different lengths. <code>r[2:4]</code> is two items, and <code>r[4:7]</code> is three items.</p>
<pre><code>>>> r = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> r[2:4]
['3', '4']
>>> r[4:7]
['5', '6', '7']
</code></pre>
<p>... | python|python-3.x|indexing|slice|swap | 1 |
1,332 | 48,874,767 | win32 ExportAsFixedFormat | <p>I was trying to change the footers of my excel file then convert it to pdf with win32 package in Python3.6.
It actually work with my home pc and at work pc only the pdf exporting part is giving me error. I am wondering if the MS Office version matters, since I have the newest at home and Excel 2007 at work.
Here is ... | <p>I just find out the answer. For the Excel 2007 on my work desktop, I need to download the add-in for ExportAsFixedFormat(). Here is the link:
<a href="https://www.microsoft.com/en-us/download/confirmation.aspx?id=7" rel="nofollow noreferrer">https://www.microsoft.com/en-us/download/confirmation.aspx?id=7</a></p>
<p... | python|excel | 0 |
1,333 | 48,480,390 | How to bundle Python for AWS Lambda | <p>I have a project I'd like to run on AWS Lambda but it is exceeding the 50MB zipped limit. Right now it is at 128MB zipped and the project folder with the virtual environment sits at 623MB and includes (top users of space):</p>
<ul>
<li>scipy (~187MB)</li>
<li>pandas (~108MB)</li>
<li>numpy (~74.4MB)</li>
<li>lambda... | <ol>
<li>The limit in AWS is for unpacked 250MB of code (as seen here <a href="https://hackernoon.com/exploring-the-aws-lambda-deployment-limits-9a8384b0bec3" rel="nofollow noreferrer">https://hackernoon.com/exploring-the-aws-lambda-deployment-limits-9a8384b0bec3</a>)</li>
<li>I would suggest going for second method an... | python|python-3.x|amazon-web-services|aws-lambda | 3 |
1,334 | 48,807,726 | Is there a way to continue my script after running an if statement to catch anomaly in Python? | <p>I have tried searching online but I can't seem to find anything that would answer this question.</p>
<p>I current have a script that is running, and I am using an if statement to catch anomaly. </p>
<pre><code>if test <= limit:
return True
</code></pre>
<p>This works as intended, but I am looking to reduce... | <p>Sure, you can do that, at least in principle, although it's not really a single line of code. At all. And it's almost certainly not what you want:</p>
<pre><code>class LimitException(Exception):
pass
def LimitExceptionRaiser(msg):
raise LimitException(msg)
def f(test, limit):
try:
return True ... | python|python-3.x|if-statement | 0 |
1,335 | 19,895,495 | File Counter in python or last 5 files | <p>I am trying to get a list of the 5 most recently imported pictures into a folder to feed into a function loading them into a contact sheet.</p>
<p>I have a program bringing in files and it uses a counter to name them 00001, 00002 etc... I was thinking something like </p>
<pre><code>while blah:
N = '0000'x
x = x+1... | <pre><code>>>> '{:05}'.format(10)
00010
</code></pre>
<p>As for sorting files based on this numbering:</p>
<pre><code>import os
# List all files in current directory
files = os.listdir('.')
recent_images = sorted(files)[-5:]
</code></pre> | python|counter | 2 |
1,336 | 20,017,708 | Modifying number of ticks on Pandas hourly time axis | <p>If I have the following example Python code using a Pandas dataframe:</p>
<pre><code>import pandas as pd
from datetime import datetime
ts = pd.DataFrame(randn(1000), index=pd.date_range('1/1/2000 00:00:00', freq='H', periods=1000), columns=['Data'])
ts['Time'] = ts.index.map(lambda t: t.time())
ts = ts.groupby('Ti... | <p>You can pass to <code>ts.plot()</code> the argument <code>xticks</code>. Giving the right interval you can plot hourly our bi-hourly like:</p>
<pre><code>max_sec = 90000
ts.plot(x_compat=True, figsize=(20,10), xticks=arange(0, max_sec, 3600))
ts.plot(x_compat=True, figsize=(20,10), xticks=arange(0, max_sec, 7200)... | python|matplotlib|plot|pandas|time-series | 3 |
1,337 | 20,156,243 | Binary Search Tree Python, Implementing Delete | <p>I am trying to implement a binary search tree in python, but I can't find a solution for delete. If the item is in a leaf, that is simple, but what if the item I want to delete has 2 children which also have other children and so on ? How can in find its successor, so that I can replace it ? Are there any simple rec... | <p>If this isn't homework, you might use one of these:</p>
<ol>
<li><a href="https://pypi.python.org/pypi/treap/" rel="nofollow">https://pypi.python.org/pypi/treap/</a></li>
<li><a href="https://pypi.python.org/pypi/red-black-tree-mod" rel="nofollow">https://pypi.python.org/pypi/red-black-tree-mod</a></li>
</ol>
<p>B... | python|recursion|tree|implementation|binary-search-tree | 3 |
1,338 | 20,202,922 | finding cosine using python | <p>I must write a function that computes and returns the cosine of an angle using the first 10 terms of the following series: <code>cosx = 1 - (x**2)/2! + (x**4)/4! - (x**6)/6!....</code></p>
<p>I can't use the factorial function, but i can use the fact that if the previous denominator was <code>n!</code>, the curren... | <p>Maybe something like this:</p>
<pre><code>#! /usr/bin/python3.2
def cos (a):
d = 1
c = 1
for i in range (2, 20, 2):
d *= i * (i - 1)
sign = -1 if i % 4 else 1
print ('adding {} * a ** {} / {}'.format (sign, i, d) )
c += sign * a ** i / d
print ('cosine is now {}'... | python|factorial|accumulator | 2 |
1,339 | 67,128,631 | ndarray.view() doesn't work if entries are multidimensional? | <p>I have a multidimensional NumPy array of shape <code>(n, i, j, k, ...)</code> and I'd like to view it as a list of length <code>n</code> with entries of shape <code>(i, j, k, ...)</code>. (Makes subsequent computations easier.) Now, <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.view.html" r... | <p>What you are doing with view as type np.void? Are you trying to manipulate the bytes?</p>
<p>If you just want to convert a shape <code>(n, i, j, k, ...)</code> array into a python list of n elements of shape <code>(i, j, k, ...)</code> why not just use <a href="https://numpy.org/doc/stable/reference/generated/numpy.... | python|arrays|numpy | 0 |
1,340 | 4,297,949 | Image on a button | <p>I expect the same output for both of the scripts below. </p>
<p>But I don't get the image on the button when I execute <strong>Script 1</strong>. However, <strong>Script 2</strong> works well.</p>
<p><strong>Script 1</strong></p>
<pre><code>from Tkinter import *
class fe:
def __init__(self,master):
se... | <p>The only reference to the image object is a local variable. When <code>__init__</code> exits, the local variable is garbage collected so the image is destroyed. In the second example, because the image is created at the global level it never goes out of scope and is therefore never garbage collected.</p>
<p>To work ... | python|image|button|tkinter | 35 |
1,341 | 69,551,144 | Python Git and Git-Lab create project and push code/commit | <p>We are building an automation process using python in which we clone a base source code repository and add necessary changes to it and add the new code to a new git repository and push it to our private gitlab server.</p>
<p>So far I'm using git library to clone, and initial a new repository and make an initial comm... | <p>This is how I created a new project in gitlab in python using python-gitlab libary.</p>
<pre><code>gl = gitlab.Gitlab('gitlab website url', private_token='token', api_version=4)
gl.auth()
gl.projects.list()
"""Create Project of the new Repository"""
response = gl.projects.create({"... | python-3.x|python-gitlab | 0 |
1,342 | 48,140,520 | Why is Image not shown properly as a Button background in Kivy? | <p>I'm trying to convert this kv code into my own class</p>
<pre><code><BaseScreen>: # This is GridLayout
cols: 4
rows: 4
padding: 25
Button:
size_hint_x: None
size_hint_y: None
Image:
source: "business_bookcover.png"
x: self.parent.x
... | <p>In kv languaje properties used in the expression (<code>x:</code>, <code>y:</code>, <code>width:</code>) will be observed. When the parent's <code>size</code>/<code>pos</code> change, child widget change accordingly. You must suply this event bindings in the Python class:</p>
<pre><code>class Book(Button):
def... | python|python-3.x|kivy|kivy-language | 1 |
1,343 | 64,374,269 | How to receive a message from a certain user in discord, then wait for another certain user's reply, then send a custom message in python | <p>I'm new to python and discord bots. I created a bot for my friend's server and I'm stuck on a certain event.
I want to be able to:</p>
<ol>
<li>Wait for a certain user to send a random message</li>
<li>Wait for a certain user to respond to that message (if the someone else replies before the user I want, I want the ... | <p>there is an inbuilt function for that</p>
<pre><code>def check(user):
return user.channel.id == message.channel.id and user.author == message.author
reply = await bot.wait_for('message', check=check())
</code></pre> | python|discord.py | 0 |
1,344 | 55,894,260 | How to fix Index value 1 is out of range. Can't get variable to pass properly through twitter get status function | <p>Appended variable not working with get status to retrieve tweet texts</p>
<hr>
<p>I have a list of tweets id's, probably around 50,000 in an excel file on my computer. I want to create a piece of code that will allow me to extract the text from the tweets so I can then analyse...</p>
<p>I have created a variable ... | <p>The first time through this <code>for</code> loop:</p>
<pre><code>tweetref = []
for t in range (0,20):
tweetref.append(datalist[30:50])
print(tweetref[1])
</code></pre>
<p>your code appends a list to <code>tweetref</code> that was previously empty. So that list of (maybe) 20 items becomes element 0 of <cod... | python|excel|indexing|twitter|tweepy | 0 |
1,345 | 71,662,077 | Odoo 10 - Cannot unblock a work center in dashboard, neither on individual work orders | <p>my work center is blocked :
<img src="https://i.stack.imgur.com/qgtZZ.png" alt="enter image description here" /></p>
<p>But when I try to unblock, I always get this error : (the same error happens if I try to unblock the work order).
Please let me know if more details needed, I am new in stack overflow.
Thanks in ad... | <p>When unblocking a workcenter Odoo will set "now" as <code>date_end</code> to every productivity record (model <code>mrp.workcenter.productivity</code>) without an end date belonging to the workcenter. That's the part in your traceback with "unblock" at the end.</p>
<p>That itself triggers a recom... | python-2.7|odoo|odoo-10 | 0 |
1,346 | 61,750,334 | Populate data from another panda df conditionally? | <p>So I have a df1 with string objects in its 'Name' column.</p>
<p>Then there is a df2 with 'Categories' and 'Regex'.
df2.Regex holds regular expressions.</p>
<p>What I need to do is to:</p>
<ul>
<li>add a 'Category' column to df1;</li>
<li>populate it with df2.Categories strings when their regex returns a match.</... | <p>In your solution is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> for set values only for matched rows by condition:</p>
<pre><code>for cat, reg in df2.values:
mask = df1['Name'].str.contains(re... | python-3.x|pandas | 1 |
1,347 | 61,942,915 | How to plot two different graphs on a single figure in pandas? | <p>I am trying to get two different plots as one plot. I will not write down my entire code (is so long), but based on the two small codes below, i get two different time series and I want to put these together in one figure. </p>
<p>My code for the first plot:</p>
<pre class="lang-py prettyprint-override"><code>plt.... | <p>Quick dirty fix would be to plot dictionaries at first, only then plot with <code>plt.plot</code>. Also, if you want to plot in the same figure, define <code>figsize</code> only in the first figure you are plotting. (Therefore <code>plt.figure</code> is ommitted completely.)</p>
<pre class="lang-py prettyprint-over... | python|pandas | 0 |
1,348 | 63,411,145 | Grade not displayed successfully using python | <p>I am a beginner in python programming. I scripted a system to compute student marks.</p>
<p>Everything works as intended, but I get <code>fail</code> displayed once. Also, if average is more than 50 I also get a <code>fail</code> message. I can't understand why. Here is my code</p>
<pre><code> from tkinter import *
... | <p>Format your code so:</p>
<pre><code> if (average > 50):
grade = "pass"
else:
grade = "fail"
gradeText.set(grade)
</code></pre>
<p>Instead of:</p>
<pre><code> if (average > 50):
grade = "pass"
else:
grade = "fail"
... | python | 1 |
1,349 | 61,145,352 | How to define custom function to generate summary stats in pydatatable? | <p>I'm trying to build a custom function to generate a summary stats for a given field as showed in the code snippet.</p>
<pre><code>def estadistica_dt_summario(dt,col,por):
dt_summary= dt[{'mean_of_specific_col':mean(col),'median_of_specific_col':median(col)},by(por)]
return dt_summary
</code></pre>
<p>Where... | <p>you can try this out:</p>
<pre><code>def estadistica_dt_summario(DT, col, por):
dt_summary = DT[{'mean_of_specific_col': mean(f[col]),
'median_of_specific_col': median(f[col])},
by(f[por])]
return dt_summary
</code></pre>
<p>Remember to make use of <code>f</code> ex... | python|py-datatable | 1 |
1,350 | 66,167,506 | In pandas dataframe keep repeated values that are only in a group, if value is repeated after other value then print some message | <p>Example Dataframe:</p>
<pre><code>A1
A1
A1 #these values are ok because these are repeated continuously
A2
A3
A4
A1 #this is duplicate value as this is not in continuation
A5
</code></pre> | <p>Use:</p>
<pre><code>#test if duplciated, first dupe is False
df['dup'] = df['col'].duplicated()
#consecutive groups
df['g'] = df['col'].ne(df['col'].shift()).cumsum()
#test if not all Trues per groups
df['new'] = ~df.groupby('g')['dup'].transform('all')
print (df)
col dup g new
0 A1 False 1 True
1 A1 ... | python|pandas|dataframe|series | 0 |
1,351 | 59,422,725 | Query function not working with spaces and parenthesis in column names | <p>I have a dataframe with spaces and parenthesis in column names.I am trying to use <code>query</code> method to get the results. It is working fine with <code>target_names</code> column but getting error for <code>sepal length (cm)</code>.</p>
<pre><code>import pandas as pd
from sklearn import datasets
iris = datase... | <p>It is a known issue in the <code>pandas</code> library. It accepts spaces but not special characters like <code>$</code>, <code>(</code> etc. </p>
<p>One possible solution is to rename the columns and then use the query function call.</p> | python-3.x|pandas|dataframe | 0 |
1,352 | 63,141,619 | How to make a discord bot find, and move to the current voice channel of a specific user | <p>I've been playing around with making fun discord bots for my friends, and we had the idea to create a bot that every 10 seconds checks the location of one of our friends and follows him to whatever voice chat he joins.</p>
<p>I've been unable to sort through the <a href="https://discordpy.readthedocs.io/en/latest/in... | <p>To join a <a href="https://discordpy.readthedocs.io/en/latest/api.html#voicechannel" rel="nofollow noreferrer"><code>VoiceChannel</code></a>, you can just use the <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect" rel="nofollow noreferrer"><code>VoiceChannel.connect</code></a>... | python|python-3.x|discord.py | 1 |
1,353 | 70,939,382 | How to extract specific attributes value from multiple tags in xml using python | <p>xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Page xmlns="http://gigabyte.com/documoto/Statuslist/1.6" xmlns:xs="http://www.w3.org/2001/XMLSchema" hashKey="MDAwNTgxMzQtQS0xLjEuc3Zn" pageFile="status-1.1.svg" tenantKey="Staus"... | <pre><code>from bs4 import BeautifulSoup as Soup
import pandas as pd
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Page xmlns="http://gigabyte.com/documoto/Statuslist/1.6" xmlns:xs="http://www.w3.org/2001/XMLSchema" hashKey="MDAwNTgxMzQtQS0xLjEuc3Zn" pageFi... | python|python-3.x|python-2.7 | 0 |
1,354 | 71,009,013 | Applying a function to each couple of elements of a column in a pandas data frame | <p>I have the need to create a new column of a pandas data frame applying a function to each couple of consecutive elements.The first element if the new column has to be a nan.
Let's assume that the function is the sum of the elements divided by 3.
Here's an example to clarify what I need:</p>
<pre><code>a b new_column... | <p>I believe this solution should now give you the desired result:</p>
<pre><code># We are going to assign a new column
df = df.assign(
# based on a function that we will apply
new_column=df.apply(
# If our row index is not 0: --> if row.name !=0
# we take the value of column["b"] -... | python|pandas | 1 |
1,355 | 67,747,810 | How to add 2dp to Plotly Go Sunburst | <p>Objective of this Task: <br>
1)Plotting a hierarhical sunburst (year -> product category -> product subcategory) <br>
2)Label showing percentage with 1/2 d.p. <br>
3)Continous colour scale based on total amount of sales</p>
<p>I was using Plotly Express to create a sunburst initially but I realised that the pe... | <p>To achieve 2dp percentages it's a simple case of updating the trace. You can use plotly express or graph objects. If using graph objects, using plotly express to structure inputs to <strong>go</strong> makes coding far simpler
<strong>plotly express</strong> does structuring</p>
<pre><code>pxfig = px.sunburst(val... | python|pandas|plot|plotly|sunburst-diagram | 1 |
1,356 | 65,652,634 | How could I create many radio inputs with for loop? | <p>Here's my code:</p>
<pre><code>{% for answer in value %}
<div class="answer">
<input type="radio" name="answer-checkbox" value="{{ answer.id }}">
{{ answer }}
</div>
{%... | <p>I assume that <code>value</code> is an object list, and for each object <code>answer</code> there is <code>answer.id</code> representing the answer you use, and <code>answer.label</code> you use for display.</p>
<p>try the following:</p>
<pre><code><div class="answer">
{% for answer in value %}
<... | python|html|django | 0 |
1,357 | 65,676,915 | Distinguish Person's names from Organization names in structured table column | <p>Are there any solutions to distinguish person names from organization names?</p>
<p>I was thinking NER, however the data are stored in a structured table (and are not unstructured sentences). Specifically, the <code>NAME</code> column lists person and organization names (which I'm trying to distinguish). In the belo... | <p>If you have reason to believe that all entries are sufficiently known (i.e., common brands and celebrities), you could utilize distant learning approaches with Wikipedia as a source.<br />
Essentially, you search for each entry on Wikipedia, and utilize results from unique search results (i.e., searching for "T... | python|text|nlp | 0 |
1,358 | 69,609,235 | How to calculate the correlation between two cols of dataframe in pandas | <p>I am working on a method for calculating the correlation between to columns of data from a dataset. The dataset is constructed of 4 columns A1, A2, A3, and Class. My goal is remove A3 if the correlation between A1 & A3 greater than 0.6 or if the correlation between A1 & A3 is less than 0.6.</p>
<p>A sample o... | <p>It was pretty straight forward after I gave I found <a href="https://pandas.pydata.org/docs/getting_started/intro_tutorials/03_subset_data.html" rel="nofollow noreferrer">this</a>.</p>
<pre><code>def calculate_correlation(s):
# if correlation > 0.6 or correlation < 0.6 remove A3
s = s[['A1','A3']]
... | python|pandas | 0 |
1,359 | 55,380,264 | Find if the docker daemon is running | <p>I need execute from the Python code to see if the docker` daemon is running OS independently. </p>
<p>Is it possible to achieve? Otherwise, it will be also okay to read the OS and execute for each platform individually. </p> | <p>If it was some linux system i would try to launch <code>systemctl status docker</code> to check of if service is running.</p>
<p>To make this platform independent you can make call to some docker function which needs docker daemon running like <code>docker ps</code>. It should return table of running processes when... | python | 1 |
1,360 | 57,578,178 | Replace end string text with new string text | <p>How to replace just end of text with new text?</p>
<p>From:</p>
<pre><code>/var/www/html/file.php
/home/www/html/data.php
</code></pre>
<p>To:</p>
<pre><code>/var/www/html/module.php
/home/www/html/module.php
</code></pre> | <p>Another possibility with <code>str.rsplit()</code>:</p>
<pre><code>l = ['/var/www/html/file.php',
'/home/www/html/data.php']
for item in l:
print( item.rsplit('/', 1)[0] + '/module.php' )
</code></pre>
<p>Prints:</p>
<pre><code>/var/www/html/module.php
/home/www/html/module.php
</code></pre>
<hr>
<p>Or usi... | python-2.7 | 0 |
1,361 | 20,796,815 | Modularizing python code | <p>I have around 2000 lines of code in a python script. I decided to cleanup the code and moved all the helpers in a helpers.py file and all the configs and imports in a config.py file
Here my main file: </p>
<pre><code>from config import *
from helpers import *
from modules import *
</code></pre>
<p>And in my conf... | <p>Read <code>import threading as th</code> as <code>th = __import__("threading")</code>: it's an assignment first and foremost. Thus, you have to do the import in <em>every</em> file where you're using the variable.</p>
<p>PS: <code>import *</code> is best avoided.</p> | python | 4 |
1,362 | 39,126,411 | How can I check a file has been copied fully to a folder before moving it using python | <p>I'm currently working on a project that adds images to a folder. As they're added they also need to be moved (in groups of four) to a secondary folder overwriting the images that are already in there (if any). I have it sort of working using watchdog.py to monitor the first folder. When the 'on_created' event fires ... | <p>I see multiple solutions :</p>
<ol>
<li>When you first create your images in the first folder, add a suffix to their name, for instance, <code>filexxx.jpg.part</code> and when they are fully written just rename them, removing the <code>.part</code>.
Then in your watchdog, be sure not to work on files ending with <c... | python|image|filesystems | 1 |
1,363 | 41,771,969 | Analytics: split-summarize records | <p>Consider the following hypothetical accounting records for staff activities in a publishing company:</p>
<pre><code>Name Activity Begin-date End-date
---------------------------------------------------------
Hasan Proofreading 2015-01-27 2015-02-09
Susan Writing ... | <p>First, create a dense long dataframe with each day between each begin date and end date. To do so, Pandas has <code>pd.date_range</code> that generate a <code>DatetimeIndex</code> from two dates. Assuming people dans work on weekends, let's use a business day frequency, but you can use any useful frequency for your ... | python|pandas|analytics | 0 |
1,364 | 20,629,195 | Django internal API Client/Server Authentication or not? | <p>I have a django project, in which i expose a few api endpoints (api endpoint = answers to get/post, returns json response, correct me if im wrong in my definition). Those endpoints are used by me on front end, like update counts or get updated content, or a myriad other things. I handle the representation logic on s... | <p>I would strongly recommend using <a href="https://github.com/toastdriven/django-tastypie" rel="nofollow">django-tastypie</a> for server to client communication.
I have used it in numerous applications both server to server or server to client.
This allows you to apply the django security as well as some more logic r... | python|django|api|rest|oauth | 0 |
1,365 | 71,849,611 | TypeError: unhashable type: 'list' when creating a new column | <pre><code>import pandas as pd
data = {'A': [1,2],
'B':[[1,1,1,2,2,4,4,4,4],[5, 4, 8, 1, 1, 1, 3, 2, 4, 2, 2, 2, 1, 1, 1]]}
df = pd.DataFrame(data)
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>[1, 1, 1, 2, 2, 4, 4,... | <p>The problem is that when you pass <code>df['B']</code> into <code>top_frequent()</code>, <code>df['B']</code> is a column of list, you can view is as a list of list.</p>
<p>So in your <code>for j in a:</code>, you are getting item from outer list. For list of list, what you get is a list.</p>
<p>Then in <code>k[j]</... | python|pandas|list|dataframe|function | 1 |
1,366 | 71,986,668 | "AttributeError: partially initialized module 'pytube' has no attribute 'YouTube' (most likely due to a circular import)" | <p>Here is the code:</p>
<pre><code>import pytube as p
video_url = input("Enter the link: ")
youtube = p.YouTube(video_url)
filters = youtube.streams.filter(progressive=True, file_extension="mp4")
filters.get_highest_resolution().download("MyPath")
</code></pre>
<p>I tried to write a code ... | <blockquote>
<p><em>AttributeError: partially initialized module 'pytube' has no attribute 'YouTube' (most likely due to a circular import)</em></p>
</blockquote>
<p>Did you notice how is your file named? <code>pytube.py</code>. This may have caused the <a href="https://stackoverflow.com/questions/22187279/python-circu... | python|importerror|pytube | 2 |
1,367 | 35,952,962 | Python-2.x: list directory without os.listdir() | <p>With <code>os.listdir(some_dir)</code>, we can get all the files from <code>some_dir</code>, but sometimes, there would be 20M files(no sub-dirs) under <code>some_dir</code>, these would be a long time to return 20M strings from <code>os.listdir()</code>.</p>
<p>(We don't think it's a wise option to put 20M files u... | <p>If you have python 3.5+ you can use os.scandir() see documentation for <a href="https://docs.python.org/3/library/os.html#os.scandir" rel="nofollow">scandir</a></p> | python|listdir | 3 |
1,368 | 35,819,419 | error with python thread | <p>I try to use <code>thread</code> in my script but i get this error:</p>
<blockquote>
<p>Unhandled exception in thread started by sys.excepthook is missing
lost sys.stderr</p>
</blockquote>
<p>My script:</p>
<pre><code># -*- coding: utf-8 -*-
import tweepy
import thread
consumer_key = ""
consumer_secret = ""... | <p><strong>Update</strong></p>
<blockquote>
<p>I just solve my problem by adding <code>time.sleep(1)</code> before</p>
<p><code>thread.start_new_thread( deleteThread, (api, status.id, ) )</code></p>
</blockquote> | python|python-2.7|tweepy | 0 |
1,369 | 15,432,499 | python: how to get the source from a code object? | <p>let's suppose we have a python string(not a file,a string,no files)</p>
<pre><code>TheString = "k=abs(x)+y"
</code></pre>
<p>ok? Now we compile the string into a piece of python bytecode</p>
<pre><code>Binary = compile( TheString , "<string>" , "exec" )
</code></pre>
<p>now the problem: how can i get from ... | <p>Without the source code, you can only approximate the code. You can <em>disassemble</em> the compiled bytecode with the <a href="http://docs.python.org/2/library/dis.html" rel="noreferrer"><code>dis</code> module</a>, then reconstruct the source code as an approximation:</p>
<pre><code>>>> import dis
>&... | python|decompiling | 16 |
1,370 | 49,481,611 | Successive matrix multiplication in R using TensorFlow | <p>A simple question.</p>
<p>Suppose I have an <code>m x m</code> <code>matrix</code> (<code>mat</code>) which I'd like to raise to the power of <code>n</code>, meaning <code>mat %*% mat %*% mat %*%</code> ... (and suppose I'd like to keep all the intermediate products)</p>
<p>To to this using <code>tensorflow</code... | <p>Have you tried the <code>expm</code> library?</p>
<pre><code>> library(expm)
> mat %^% 2 # raise to power of 2
</code></pre> | r|matrix|tensorflow | 1 |
1,371 | 21,200,640 | parsing JSON which contains "objects" | <p>I'm getting data from an application that returns what seems to be an JSON, but with some "objects". For instance:</p>
<pre><code>{"rgEvtData":[new VisData(0,0,1,0,1,0,0,0,0,-1),new VisData(0,1,1,1,1,0,0,0,0,-1),new VisData(0,2,1,2,1,0,0,0,0,-1),new VisData(0,3,2,0,1,0,0,0,0,-1),new VisData(0,4,2,1,1,0,0,0,0,-1),ne... | <p>No, you can't.<br>
Even if python could parse it, what would it do with the <code>VisData</code>s? </p>
<p>I think your only option (except the stick approach mentioned), to translate this string into valid JSON somehow. For example, replacing <code>new VisData(...)</code> with <code>[...]</code>, or <code>{"class... | python|json | 1 |
1,372 | 62,659,358 | How to get arguments string in a function? | <p>In Python, is it possible to define a function <code>get_arg_str</code> that implements this:</p>
<pre><code>def get_arg_str(arg):
# do something here
mydict = {'key': 3}
str_arg = get_arg_str(mydict['key'])
# then str_arg should be string "mydict['key']"
</code></pre> | <p>Yes it's possible using introspection.</p>
<p>Something alone the lines of:</p>
<pre><code>def get_arg_str(object, namespace):
return [name for name in namespace if namespace[name] is object]
mydict = 'foo'
print(get_arg_str(mydict, globals()))
</code></pre>
<blockquote>
<p><code>['mydict']</code></p>
</blockq... | python | 0 |
1,373 | 45,981,388 | Python blocked thread termination method? | <p>I have a question in Python programming. I am writing a code that has a thread. This thread is a blocked thread. Blocked thread means: a thread is waiting for an event. If the event is not set, this thread must wait until the event is set. My expectation that block thread must wait the event without any timeout for ... | <p><strong>Ctrl+C</strong> stops only the main thread, Your threads aren't in <code>daemon</code> mode, that's why they keep running, and that's what keeps the process alive. First make your threads to daemon.</p>
<pre><code>t1 = threading.Thread(name='block',
target=wait_for_event,
... | python|multithreading|pthreads|signals|python-multithreading | 2 |
1,374 | 55,127,218 | Constrain logic in Linear programming | <p>I'm trying to build a linear optimization model for a production unit. I have Decision variable (binary variable) X(i)(j) where I is hour of J day. The constrain I need to introduce is a limitation on downtime (minimum time period the production unit needs to be turned off between two starts).</p>
<p>For example:</... | <p>I think you are asking for a way to model: "<em>at least two consecutive periods of <strong>down time</em></strong>". A simple formulation is to <strong>forbid</strong> the pattern:</p>
<pre><code>t t+1 t+2
1 0 1
</code></pre>
<p>This can be written as a linear inequality:</p>
<pre><code>x(t) - x(t+1) + x(t... | python|optimization|linear-programming|pulp|stochastic | 1 |
1,375 | 54,797,826 | Setting Jupyter Notebook Server Using Mac | <p>I have a mac and want to set it as a Jupyter Notebook server so that I could connect it using browser through the internet when I'm not at home. But I cannot find instruction online. Is my idea feasible and easy to realize? Thanks!</p> | <p>Set host to 0.0.0.0 to expose the server to your internal network. Then follow these instructions to open it up externally.</p>
<p><a href="https://medium.com/botfuel/how-to-expose-a-local-development-server-to-the-internet-c31532d741cc" rel="nofollow noreferrer">https://medium.com/botfuel/how-to-expose-a-local-dev... | python-3.x|jupyter-notebook | 0 |
1,376 | 73,745,176 | Vectorized-oriented definition of functions (Python) | <p>I want to integrate a function using <a href="https://pypi.org/project/quadpy/" rel="nofollow noreferrer">quadpy</a>. I noticed that quadpy passes numpy arrays as arguments to the function. For example, if I define <code>f = lambda x: x**2</code>, then quadpy will integrate passing a vector like <code>x = [0, 0.3, 0... | <p>Check <a href="https://github.com/sigma-py/quadpy/wiki/Dimensionality-of-input-and-output-arrays" rel="nofollow noreferrer">https://github.com/sigma-py/quadpy/wiki/Dimensionality-of-input-and-output-arrays</a> on what the dimensions of the input array mean, and how to construct an output array.</p> | python|vectorization|numerical-integration | 1 |
1,377 | 73,692,812 | Color code a column based on values in another column in Excel using pandas | <p>I have a pandas data frame that I am then writing into an Excel sheet:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Measure</th>
<th>value</th>
<th>lower limit</th>
<th>upper limit</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
<td>0.1</td>
<td>1.2</td>
</tr>
<tr>
<td>B</td>
<... | <p>You can use a custom function:</p>
<pre><code>def color(df):
out = pd.DataFrame(None, index=df.index, columns=df.columns)
out['value'] = (df['value']
.between(df['lower limit'], df['upper limit'])
.map({True: 'background-color: yellow'})
)
retu... | python|excel|pandas | 1 |
1,378 | 12,815,887 | iterate over dictionaries in module | <p>I import a module that only contains several dictionaries. How can I iterate over those?
Something along the lines of</p>
<pre><code>import moduleX as data
for d in data:
do stuff with d
</code></pre>
<p>this obviously does not work as the module is not iterable. is there a way to extract all dicts from module... | <p>My answer:</p>
<pre><code>import moduleX as data
for k, v in data.__dict__.iteritems():
if isinstance(v, dict) and not k.startswith('_'):
# do something
pass
</code></pre> | python|iteration | 3 |
1,379 | 21,897,133 | django two foreign keys unique record | <p>I have three django models:</p>
<pre><code>class Item(models.Model):
itemid = models.IntegerField(default=0, unique=True)
class Region(models.Model):
regionid = models.IntegerField(default=0, unique=True)
class Price(models.Model):
regionid = models.ForeignKey(Region)
itemid = models.ForeignKey(It... | <p>You should take a look at <a href="https://docs.djangoproject.com/en/dev/ref/models/options/#django.db.models.Options.unique_together" rel="nofollow noreferrer">unique together</a>! It may solve your issue.</p> | python|django|django-models|foreign-keys|foreign-key-relationship | 2 |
1,380 | 21,627,457 | looping through nodes and extract attributes in Networkx | <p>I defined in python some shapes with corresponding corner points, like this:</p>
<pre><code>square = [[251, 184],
[22, 192],
[41, 350],
[244, 346]]
triangle = [[250, 181],
[133, 43],
[21, 188]]
pentagon = [[131, 37],
[11, 192],
[37, 35... | <p>Here is an image of your polygons
<img src="https://github.com/yardsale8/cs106/raw/master/images/poly.png" alt="Polygon image"></p>
<p>First, there is no need to cast the nodes as dictionaries, we can iterate on them directly. This code is based off of <a href="https://github.com/abidrahmank/OpenCV2-Python/blob/ma... | python|attributes|iteration|nodes|networkx | 7 |
1,381 | 40,856,119 | Python SSL: CERTIFICATE_VERIFY_FAILED | <p>I'm getting an error when connecting to <code>www.mydomain.com</code> using Python 2.7.12, on a fairly new machine that uses Windows 8.1. The error is <em><code>SSL: CERTIFICATE_VERIFY_FAILED</code></em> on the <code>ssl_sock.connect</code> line of the code below. The code wraps an SSL connection in an context, and ... | <p>I resolved this issue, which seems to be related to a post Aug 29th 2016 security update for Windows that causes issues with certificate verification when using the TLS 1.0 protocol. Re-installing Windows without the security update at least allows things to work for now. Also I didn't get this issue when running un... | python|windows|ssl|ssl-certificate|pyopenssl | 0 |
1,382 | 30,949,618 | How do I pull out the first 3 lines of each ppm file? | <p>All I have done is opened up the small file and appended the contents to a list called <code>files</code>. Files contains a list of the tiny ppm lines. </p>
<p>How do I remove the first three lines of this file from existence? </p>
<p>Here's an example of what a <code>.ppm</code> file looks like, it's called, tiny... | <p>If you want something more robust for reading images and performing various operations on them, I recommend the Pillow package in Python.</p>
<pre><code>from PIL import Image
from glob import glob
def readFiles():
images = []
for f in glob("*.ppm"):
image = Image.open(f)
image_pix = list(im... | python | 1 |
1,383 | 30,967,923 | How to get the name of parent directory in Python? | <p>I have a program in python that prints out information about the file system... I need to know to save the name of the parent directory to a variable...</p>
<p>For example, if a tiny bit of the file system looked like this: <br />
<strong>ParentDirectory</strong><br />
<strong>ChildDirectory</strong><br />
<strong>... | <p>You can get the complete file path for the script resides using <code>__file__</code> variable , then you can use <code>os.path.abspath()</code> to get the absolute path of your file , and then use <code>os.path.join()</code> along with your current path , and the parent directory descriptor - <code>..</code> in mos... | python|variables|directory | 7 |
1,384 | 40,302,006 | No such file or directory: 'geckodriver' for a simple Selenium application in Python | <p>I'm running a simple example of selenium on Linux:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("something")
</code></pre>
<p>and get an error:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'geckodri... | <p><strong>Downloading geckodriver</strong></p>
<p>The geckodriver executable can be downloaded <a href="https://github.com/SeleniumHQ/selenium/blob/master/py/docs/source/index.rst" rel="noreferrer">here</a>. </p>
<p><strong>Python3 venv</strong></p>
<p>Download the geckodriver executable from the above link and ex... | python|selenium | 51 |
1,385 | 28,999,267 | Open audio with callback using ALSA | <p>Is it possible in Python, using ALSA, to access the audio hardware for playback, with a callback function:</p>
<pre><code>def audiocallback():
# create some audio and return a buffer of 1024 samples (~23 ms @ 44.1khz)
# that is going to be played on the device
return buffer
openaudio(deviceid=1, type=O... | <p>I've succeeded in getting it to work with python-alsaaudio. There is no from-the-box method for this purpose, but it's relatively easy to implement.</p>
<pre><code>import alsaaudio
import random
import struct
BUFFER_SIZE = 1024
def noise_callback():
return [random.randint(-20000, 20000) for i in range(BUFFER_... | python|linux|audio|python-multithreading|alsa | 2 |
1,386 | 8,808,890 | Uploading an image to the datastore in GAE | <p>I have this little set of Python code on the GAE, trying to upload an image to the datastore:</p>
<pre><code>class UploadPage(webapp.RequestHandler):
def get(self):
self.response.out.write("""<html><body>
<form action="/addimg" enctype="multipart/form-data" method="post">
... | <p>I switched the addimg to a POST under the UploadPage, and it worked, not sure why it didnt work when coming frmo a class though</p> | python|google-app-engine | 0 |
1,387 | 52,434,568 | How to pickle a sklearn pipeline for multi label classifier/one vs rest classifier? | <p>I am trying to create a multi-label classifier using the one vs rest classifier wrapper. </p>
<p>I used a pipeline for TFIDF and the classifier. </p>
<p>When fitting the pipeline, I have to loop through my data by category and then fit the pipeline each time to make predictions for each category. </p>
<p>Now, I w... | <p>OneVsRestClassifier internally fits one classifier per class. So you should not be fitting the pipeline for each class like you are doing in </p>
<pre><code>for category in categories:
pipeline.fit(X_train, y_train[category])
pipeline.predict(['kiwi'])
print (predict)
</code></pre>
<p>You should be doi... | python|scikit-learn|pickle|pipeline|multilabel-classification | 2 |
1,388 | 51,693,993 | PyQt5 error "PyCapsule_GetPointer called with incorrect name" | <p>I've just built PyQt5 in a pyenv virtualenv with python 3.6.3 on OpenSUSE leap, the build went fine, but when I import</p>
<pre><code>>>> from PyQt5 import QtCore
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: PyCapsule_GetPointer called with incorrect name... | <p>OK so this was pretty easy actually, as stated in the doc (<a href="http://pyqt.sourceforge.net/Docs/PyQt4/installation.html#downloading-sip" rel="nofollow noreferrer">PyQt4</a>, <a href="https://pyqt.readthedocs.io/en/latest/installation.html#downloading-sip" rel="nofollow noreferrer">PyQt5</a>), SIP must be config... | linux|python-3.x|pyqt5|python-sip | 3 |
1,389 | 51,850,773 | Converting Histogram Values to Int Array in Python | <p>everyone. I created an histogram with by using an array with a size of 1x1000 and its values range from 0 to 99. I want to store histograms values as an int array. However, when I run the program I got the following results for the program(the numeric values are different for everyone since its random): </p>
<block... | <p>When dealing with random numbers you can use <code>np.random.seed(n)</code> to ensure that others who run your code have the same numbers.</p>
<p>According to the docs you get both the bin values and the bin edges back from <code>plt.hist()</code>.</p>
<p>Take a look at the following:</p>
<pre><code>print(y[0])
... | python|arrays|histogram | 2 |
1,390 | 51,578,739 | Django 404 Page Not Found blog.views.post_detail | <p>I'm new with django and I use mysql. I followed the tutorial to make blog with django. I made list and detail blog, but when I clicked the detail post of blog, the error comes Page Not Found (404) Raised by: blog.views.post_detail. These are my site urls.py, blog urls.py, models.py and views.py.</p>
<p>Site urls.py... | <p>I think maybe you should use "pk" as an argument instead of complicated urls that you have got</p>
<pre><code>def post_detail(request, pk):
post = get_object_or_404(Post,pk=pk)
return render (request,
'blog/post/detail.html',
{'post':post})
urlpatterns = [
url(r'^$', vie... | python|django|python-3.x|web | 1 |
1,391 | 51,655,172 | Why does my loop stop after one iteration? | <p>I'm struggling to see why my loop stops after one iteration.</p>
<p>My code: </p>
<pre><code>import os
def open_data(fpath):
counter=0
for i in os.listdir(fpath):
if os.path.isfile(os.path.join(fpath,i)):
#print counter
f=open(os.path.join(fpath,i),"r")
#counter... | <p>You are not reading all the files you are only opening all the files, in the same variable and in the end when you are doing <code>f.readlines()</code> <code>f</code> it's only whatever was your last file, you should read all in a "buffer" and in the end return it</p>
<p>It should be something like this</p>
<pre><... | python|python-2.7|file|loops|directory | 0 |
1,392 | 19,122,408 | Python: Can't add string at the end of the list | <p>I'm trying to make a text based RPG and when I'm trying to shorten every possible input into one variable I can't end a list with string:</p>
<pre><code>input_use = ["use ", "use the "]
...
input_press = ["press ", "press the ", input_use]
...
input_interact_button = input_press + "button"
</code></pre> | <p>If you want to build lists, then concatenate the lists onto existing values:</p>
<pre><code>input_press = ["press ", "press the "] + input_use
input_interact_button = input_press + ["button"]
</code></pre>
<p>Demo:</p>
<pre><code>>>> input_use = ["use ", "use the "]
>>> input_press = ["press ",... | python|string|list | 6 |
1,393 | 19,195,077 | The len() of this list is not coming out right: Python | <p>I'm trying to count the number of times the word "fizz" appears in my list. This is the code:</p>
<pre><code>def fizz_count(key):
for x in key:
if x != 'fizz':
key.remove(x)
return len(key)
print fizz_count(["fizz",0,0,0,10])
</code></pre>
<p>However, this returns 4 instead of... | <p>As soon as a function returns something, it breaks. Hence, when you do <code>return len(key)</code>, you return the length of the list after removing the first <code>0</code>.</p>
<p>If you want to count how many times something appears in a list, just do <code>key.count('fizz')</code></p>
<hr>
<p>You should neve... | python|list | 6 |
1,394 | 62,373,578 | Removing zero values from a numpy array of arrays | <p>Original datas</p>
<pre><code> [[ 0.00000000e+00 1.00000000e+00 -6.76207728e+00 -1.63236398e+01]
[ 0.00000000e+00 1.00000000e+00 2.51283367e+01 1.13952157e+02]
[ 0.00000000e+00 1.00000000e+00 3.11402956e+00 -5.16009612e+02]
[ 0.00000000e+00 1.00000000e+00 3.10969787e+01 1.82175649e+02]
[ 1.00000000e+00... | <p>It seems like you do not want a list of arrays as the output but instead want a 2-dimensional array (i.e. <code>[[...]]</code> instead of <code>[array([...]), array([...])]</code>).</p>
<p>However, this is not possible as the rows of your array end up with different sizes after you trim them by removing the zeros (... | python|numpy | 1 |
1,395 | 43,527,859 | Python subprocess call throws error when writing file | <p>I'd like to use SVOX/pico2wave to write a wav-file from Python code. When I execute this line from a terminal the file is written just fine:</p>
<pre><code>/usr/bin/pico2wave -w=/tmp/tmp_say.wav "Hello world."
</code></pre>
<p>I've verified that pico2wave is located in <code>/usr/bin</code>.</p>
<p>This is my Pyt... | <p>From the <a href="https://docs.python.org/2/library/subprocess.html#popen-constructor" rel="nofollow noreferrer">documentation</a></p>
<blockquote>
<p>Providing a sequence of arguments is generally preferred, as it allows
the module to take care of any required escaping and quoting of
arguments (e.g. to permi... | python|linux|python-2.7|ubuntu|text-to-speech | 2 |
1,396 | 43,856,866 | Button matrix/multiple button + function for each one | <pre><code>def create_widget(self):
for x in range(11):
for y in range(11):
self.bttn = Button(self)
self.bttn.grid(row=x, column=y)
for c in range(len(path)):
if [x,y] == path[c]:
self.bttn["text"] = numbers[c]
brea... | <p>Each new button you declare overwrite the same instance of <code>self.bttn</code> which leads to you in the end only having access to the lastly defined button. Thus, the buttons get created alright, but then you have access only to the last one. Thus, its name will be the one you access through <code>self.bttn</cod... | python|python-3.x | 0 |
1,397 | 43,589,755 | Python: list indices must be integers or slices, not str | <p>Hi am trying to print a list of string in python but still its showing me this error.
"list indices must be integers or slices, not str"</p>
<p>code:</p>
<pre><code>Features ['entity_number',
'type',
'programs',
'name',
'title',
'addresses']
</code></pre>
<p>So in here i just want to display the data under '... | <p>it looks like you are looking for a dictionary<code>{}</code> and not a list<code>[]</code>. A dictionary has the added benefit of allowing for what is known as a 'key: value' pairs. If you know your key, you can get your value! </p>
<pre><code>Features = {
'entity_number': 'some number',
'type': 'som... | python|string|list | 7 |
1,398 | 71,152,479 | how to display entry widget on new window in tkinter? | <pre><code>from tkinter import *
from tkinter import messagebox
w = Tk()
w.geometry('200x250')
def buttons():
r1 = Tk()
r1.geometry('200x250')
r1.mainloop()
t= Label(text = "MIB",font =("Arial", 49))
t.pack(side = TOP)
e = Label(text = "Email")
e1 =Entry()
e.pack()
e1... | <p>TK() is the root window, so it needs to be called only once. After that, to open another window, you need to use tkinter.Toplevel(). Below is the code I put labelexample in a new window.</p>
<pre><code>from tkinter import *
from tkinter import messagebox
w = Tk()
w.geometry('200x250')
def buttons():
r1 = Topl... | python|tkinter | 1 |
1,399 | 71,408,697 | Changing name of the file to parent folder name | <p>I have a bunch of folders in my directory. In each of them there is a file, which you can see below:</p>
<p><a href="https://i.stack.imgur.com/eo1N6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eo1N6.png" alt="enter image description here" /></a></p>
<p>Regardless the file extension I would lik... | <p>Reasoning for each line of code are commented! Every answer should use <code>iglob</code>, please read more about it <a href="https://docs.python.org/3/library/glob.html#glob.iglob" rel="nofollow noreferrer">here</a>! The code is also suffix agnostic (<code>.klm</code> as the suffix is not hardcoded), and works in a... | python|python-3.x|file|directory | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.