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,907,900
34,871,212
How to interpret decision trees' graph results and find most informative features?
<p>I am using sk-learn python 27 and have output some decision tree feature results. Though I am not sure how to interpret the results. At first, I thought the features are listed from the most informative to least informative (from top to bottom), but examining the \nvalue it suggests otherwise. How do I identify the top 5 most informative features from the outputs or using python lines?</p> <pre><code>from sklearn import tree tree.export_graphviz(classifierUsed2, feature_names=dv.get_feature_names(), out_file=treeFileName) # Output below digraph Tree { node [shape=box] ; 0 [label="avg-length &lt;= 3.5\ngini = 0.0063\nsamples = 250000\nvalue = [249210, 790]"] ; 1 [label="name-entity &lt;= 2.5\ngini = 0.5\nsamples = 678\nvalue = [338, 340]"] ; 0 -&gt; 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ; 2 [label="first-name=wm &lt;= 0.5\ngini = 0.4537\nsamples = 483\nvalue = [168, 315]"] ; 1 -&gt; 2 ; 3 [label="name-entity &lt;= 1.5\ngini = 0.4016\nsamples = 435\nvalue = [121, 314]"] ; 2 -&gt; 3 ; 4 [label="substring=ee &lt;= 0.5\ngini = 0.4414\nsamples = 73\nvalue = [49, 24]"] ; 3 -&gt; 4 ; 5 [label="substring=oy &lt;= 0.5\ngini = 0.4027\nsamples = 68\nvalue = [49, 19]"] ; 4 -&gt; 5 ; 6 [label="substring=im &lt;= 0.5\ngini = 0.3589\nsamples = 64\nvalue = [49, 15]"] ; 5 -&gt; 6 ; 7 [label="lastLetter-firstName=w &lt;= 0.5\ngini = 0.316\nsamples = 61\nvalue = [49, 12]"] ; 6 -&gt; 7 ; 8 [label="firstLetter-firstName=w &lt;= 0.5\ngini = 0.2815\nsamples = 59\nvalue = [49, 10]"] ; 7 -&gt; 8 ; 9 [label="substring=sa &lt;= 0.5\ngini = 0.2221\nsamples = 55\nvalue = [48, 7]"] ; ... many many more lines below </code></pre>
<ol> <li><p>In Python you can use <code>DecisionTreeClassifier.feature_importances_</code>, which according to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier" rel="nofollow">documentation</a> contains</p> <blockquote> <p>The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance [R66].</p> </blockquote> <p>Simply do a <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.argsort.html" rel="nofollow"><code>np.argsort</code></a> on the feature importances and you get a feature ranking (ties are not accounted for).</p></li> <li><p>You can look at the <a href="https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity" rel="nofollow">Gini impurity</a> (<code>\ngini</code> in the graphviz output) to get a first idea. Lower is better. However, be aware that you will need a way to combine impurity values if a feature is used in more than one split. Typically, this is done by taking the average information gain (or 'purity gain') over all splits on a given feature. This is done for you if you use <code>feature_importances_</code>.</p></li> </ol> <p><strong>Edit</strong>: I see the problem goes deeper than I thought. The graphviz thing is merely a graphical representation of the tree. It shows the tree and every split of the tree in detail. This is a representation of the tree, not of the features. Informativeness (or importance) of the features does not really fit into this representation because it accumulates information over multiple nodes of the tree.</p> <p>The variable <code>classifierUsed2.feature_importances_</code> contains importance information for every feature. If you get for example [0, 0.2, 0, 0.1, ...] the first feature has an importance of 0, the second feature has an importance of 0.2, the third feature has an importance of 0, the fourth feature an importance of 0.1, and so on.</p> <p>Let's sort features by their importance (most important first): </p> <pre><code>rank = np.argsort(classifierUsed2.feature_importances_)[::-1] </code></pre> <p>Now rank contains the indices of the features, starting with the most important one: [1, 3, 0, 1, ...]</p> <p>Want to see the five most important features?</p> <pre><code>print(rank[:5]) </code></pre> <p>This prints the indices. What index corresponds to what feature? That's something you should know yourself because you supposedly constructed the feature matrix. Chances are, that this works:</p> <pre><code>print(dv.get_feature_names()[rank[:5]]) </code></pre> <p>Or maybe this:</p> <pre><code>print('\n'.join(dv.get_feature_names()[i] for i in rank[:5])) </code></pre>
python-2.7|machine-learning|scikit-learn|decision-tree
5
1,907,901
27,042,244
Stop a while loop from running a certain amount of times
<p>I've been searching around nearly all morning looking for a piece of code that can help me here but its hard to find one that is similar! I have to create a bank system that asks the user to input a username and password. If these are entered 3 times the system shuts down. So far, i have got my program to know if the password/username is correct or not. Now i just need to figure out how to make it run and stop after 3 incorrect attempts. Really appreciate any help given on this one! Thanks</p> <p>Code:</p> <pre><code>username = "bank_admin" password = "Hytu76E" usernameGuess = raw_input("Please enter your username: ") passwordGuess = raw_input("Please enter the password: ") while (username != usernameGuess or password != passwordGuess): print ("Please try again.") usernameGuess = raw_input("Please enter your username: ") passwordGuess = raw_input("Please enter your password: ") print ("Password accepted. Access Authorized.") </code></pre>
<p>You can add a counter to see how many times they guessed the wrong password. Then use that as another condition in your <code>while</code> loop.</p> <pre><code>incorrectGuesses = 0 correct = False while (not correct and incorrectGuesses &lt; 4): usernameGuess = raw_input("Please enter your username: ") passwordGuess = raw_input("Please enter your password: ") correct = ((username == usernameGuess) and (password == passwordGuess)) if not correct: print ("Please try again.") incorrectGuesses += 1 </code></pre>
python|loops
1
1,907,902
12,614,677
python functional testing
<p>I am currently writing a Java Decompiler in Python and would like to add some automated functional testing. I have a bunch of short pieces of Java code and need to ensure that they decompile without error, the output code compiles, and the resulting program gives the expected output. </p> <p>I plan to write some scripts using <code>subprocess</code> to do this all automatically, but I'm having trouble deciding how to create and store the tests. I figured that before I go out and create my own format and test runner, I should try to see if there's any feasible way to use an existing framework. What should I do? I've read a lot on the internet about unit testing, integration testing, etc. but I am not sure how to apply it to my situation.</p>
<p>Have you check <a href="http://docs.python.org/library/unittest.html" rel="nofollow">http://docs.python.org/library/unittest.html</a> that is included in standard python API. I think this should be enough what you are trying to achive. You can run those tests through command line too. So they can be automated with any tool you want outside of python.</p> <p>Also check doctests They are really great for testing single functions.</p>
python|functional-testing|regression-testing
3
1,907,903
12,231,929
Pyglet handlers and deleted objects
<p>In my game with Python and pyglet, I have groups which propagate events downward to its members:</p> <pre><code>class Group(EventDispatcher): def __init__(self): self.members = [] def add(self, member): self.members.append(member) self.push_handlers(member) def remove(self, member): self.members.remove(member) # and then what??? Group.register_event('on_event') </code></pre> <p>If I <code>del</code> all my references to a member and remove() it, will the handlers in Group prevent the object from being garbage collected? Will the handlers just disappear (weakref)? If not, how can I clean up the handlers?</p> <p>EDIT: I ran I test session to see what happens:</p> <pre><code>&gt;&gt;&gt; from pyglet.event import EventDispatcher &gt;&gt;&gt; class Group(EventDispatcher): ... pass ... &gt;&gt;&gt; Group.register_event_type('on_tick') 'on_tick' &gt;&gt;&gt; g = Group() &gt;&gt;&gt; class Members: ... def on_tick(self): ... print('tick') ... &gt;&gt;&gt; m = Members() &gt;&gt;&gt; g.push_handlers(m) &gt;&gt;&gt; g.dispatch_event('on_tick') tick &gt;&gt;&gt; del m &gt;&gt;&gt; g.dispatch_event('on_tick') tick &gt;&gt;&gt; class B: ... def on_tick(self): ... print(self.x) ... &gt;&gt;&gt; m = B() &gt;&gt;&gt; g.push_handlers(m) &gt;&gt;&gt; g.dispatch_event('on_tick') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.2/site-packages/pyglet/event.py", line 355, in dispatch_event if handler(*args): File "&lt;stdin&gt;", line 3, in on_tick AttributeError: 'B' object has no attribute 'x' &gt;&gt;&gt; m.x = 3 &gt;&gt;&gt; g.dispatch_event('on_tick') 3 tick &gt;&gt;&gt; del m &gt;&gt;&gt; g.dispatch_event('on_tick') 3 tick </code></pre> <p>So I guess EventDispatcher still keeps a reference to the handler. Thus, the question becomes how do I clean up the handlers.</p>
<p>EventDispatcher.remove_handlers is the opposite of push_handlers. So calling remove_handlers(m) then del m will allow m to be garbage collected.</p>
python|pyglet
1
1,907,904
23,373,395
Django South Schema migration with fixture pre-loading
<p>So the issue is that I have a Django project running fine now. </p> <p>I need to make two schema changes, A and B.</p> <p>For some reason, I need to load some fixture to database after I apply migration A and then apply migration B.</p> <p>I can do it manually, of course. Like:</p> <pre><code>./manage.py migrate my_app 0001 ./manage.py loaddata my_fixture.json ./manage.py migrate my_app 0002 </code></pre> <p>and that works fine.</p> <p>However, in production, I want to deploy my project with script automatically. I don't want to add too many manual step in it.</p> <p>My ideal solution is that I can automatically populate my fixture after my schema change (maybe with some special option parameters). </p> <p>Does anyone have an idea how to do it?</p> <p>PS: I may not giving enough info of my problem. So if you think problem itself is too vague, leave the comment, and let me see what I can do to make it more clear.</p> <p>UPDATE: I have marked Serafeim as correct answer. Robert Jørgensgaard Engdahl points out a good point, which can be explained detailed in following post <a href="https://stackoverflow.com/questions/5472925/django-loading-data-from-fixture-after-backward-migration-loaddata-is-using-mo?rq=1">django loading data from fixture after backward migration / loaddata is using model schema not database schema</a></p> <p>However, the problem we have is not exactly same. My schema A is to create a new table and won't change it in foreseeable future. migration B is to add a new column to another table which point to the table created by A. And that is why I need to pre-populate some data in new table (for some other complicate reason, I don't want to explain this too much). And I have tested the solution from Serafeim, it works. </p> <p>HOWEVER, if anyone encounter a similar situation, look at the post shared by Robert Jørgensgaard Engdahl to understand the downside of this solution before you take it. Thanks again for both of answer providers!</p>
<p>Introducing new rows in any migration should be considered harmful: It becomes impossible to "reset" the migrations; i.e. make a release with no ORM changes, but all migrations replaced with 0001_initial migrations. In long lived projects you want to keep this option open.</p>
python|django|django-south
0
1,907,905
670,084
Partial Upload With storbinary in python
<p>I've written some python code to download an image using </p> <pre><code>urllib.urlopen().read() </code></pre> <p>and then upload it to an FTP site using </p> <pre><code>ftplib.FTP().storbinary() </code></pre> <p>but I'm having a problem. Sometimes the image file is only partially uploaded, so I get images with the bottom 20% or so cut off. I've checked the locally downloaded version and I have successfully downloaded the entire image, which leads me to believe that it is a problem with storbinary. I believe I am opening and closing all of the files correctly. Does anyone have any clues as to why I'm getting a partial upload with storbinary?</p> <p><strong>Update:</strong> When I run through the commands in the Python shell, the upload completes successfully, I don't know why it would be different from when run as a script...</p>
<p>It turns out I was not closing the downloaded file correctly. Let's all pretend this never happened.</p>
python|ftp|ftplib
0
1,907,906
700,480
Control access to WebDav/Apache using Python
<p>I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user and provide them with a dedicated webdav user-specific area.</p> <p>Any hints?</p>
<p>First, for you other readers, my authentication was done against Django using a <a href="http://www.davidfischer.name/2009/10/django-authentication-and-mod_wsgi/" rel="nofollow">WSGI authentication script</a>.</p> <p>Then, there's the meat of the question, giving each Django user, in this case, their own WebDav dir separated from other users. Assuming the following WebDAV setup in the Apache virtual sites configuration (customarily in <em>/etc/apache2/sites-enabled/</em>)</p> <pre><code>&lt;Directory /webdav/root/on/server&gt; DAV On # No .htaccess allowed AllowOverride None Options Indexes AuthType Basic AuthName "Login to your webdav area" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /where/is/the/authentication-script.wsgi &lt;/Directory&gt; </code></pre> <p>Note how there's no public address for WebDav set up yet. This, and the user area thing, is fixed in two lines in the same config file (put these after the ending clause):</p> <pre><code>RewriteEngine On RewriteRule ^/webdav-url/(.*?)$ /webdav/root/on/server/%{LA-U:REMOTE_USER}/$1 </code></pre> <p>Now, webdav is accessed on <a href="http://my-server.com/webdav-url/" rel="nofollow">http://my-server.com/webdav-url/</a> The user gets a login prompt and will then land in a subdirectory to the webdav root, having the same name as their username. <em>LA-U:</em> makes Apache "look ahead" and let the user sign in <em>before</em> determining the mounting path, which is crucial since that path depends on the user name. Without some rewrite-rule there will be no URL, and the user won't get a login prompt. In other words, LA-U avoids a catch-22 for this type of login handling.</p> <p><strong>Precautions</strong>: requires mod_rewrite to be enabled, and user names must be valid as dir names without any modification. Also, the user dirs won't be created automatically by these commands, so their existence must be assured in some other way.</p>
python|django|apache|webdav
1
1,907,907
42,022,018
Trying to export the data from the crawl to a csv file
<p>I found this code online, and I want to use it, but I can't find a way to export the data collected to a csv file.</p> <pre><code>import urllib import scrapy import json import csv from bs4 import BeautifulSoup url = "http://www.straitstimes.com/tags/malaysia-crimes" html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # get text text = soup.body.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) print(text) </code></pre>
<p>The below appears to work for what i believe you want:</p> <p>I used the xlwt package to create, write to and save the workbook and then a loop to go through each line of text and write it to the workbook. I saved it as testing.csv</p> <pre><code>import urllib import scrapy import json import csv from bs4 import BeautifulSoup from xlwt import Workbook url = "http://www.straitstimes.com/tags/malaysia-crimes" html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # create excel workbook wb = Workbook() sheet1 = wb.add_sheet('Sheet 1') # kill all script and style elements for script in soup(["script", "style"]): script.extract() # rip it out # get text text = soup.body.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) print(text) # go through each line and print to a new row in excel counter = 1 for text_to_write in text.splitlines(): sheet1.write(counter,1,text_to_write) counter = counter + 1 wb.save('testing.csv') </code></pre>
python|python-2.7|beautifulsoup
0
1,907,908
57,345,647
Python - How can I send a rsa.key.PublicKey object through socket?
<p>I'm using the python rsa module to generate a public/private key pair. I want to send the public key to the other computer through a socket connection.</p> <p>When I try to encode the public key to send it, I get this error:</p> <pre><code> File "chatclient.py", line 128, in &lt;module&gt; s.sendall(pubkey.encode('utf-8')) AttributeError: 'PublicKey' object has no attribute 'encode' </code></pre> <p>I cannot figure out a way to encode the key other than the method that causes the error. If I try to convert it to a string, encode it and send it through, I cannot use the key to encrypt any messages, nor are there any documented ways to turn it back into a PublicKey object.</p> <p>This is what causes the error:</p> <pre><code>s.sendall(pubkey.encode('utf-8')) </code></pre> <p>Here's the package on pypi and the documentation:</p> <p><a href="https://pypi.org/project/rsa/" rel="nofollow noreferrer">https://pypi.org/project/rsa/</a></p> <p><a href="https://stuvel.eu/python-rsa-doc/usage.html" rel="nofollow noreferrer">https://stuvel.eu/python-rsa-doc/usage.html</a></p>
<p>Use save_pkcs1 and load_pkcs1:</p> <pre><code>a = pubkey.save_pkcs1(format='DER') b = rsa.key.PublicKey.load_pkcs1(a, format='DER') </code></pre>
python|sockets|rsa
4
1,907,909
70,867,391
ModuleNotFoundError: No module named 'SpeechRecognition' despite module being successfully installed
<p>Forgive me if this is a redundant question. I viewed a couple of similar posts and I do believe my issue is unique. I am making a simple AI Assistant using a tutorial on geeksforgeeks. Link below:</p> <p><a href="https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/</a></p> <p>I wanted to tweak this to be more specific to my needs, and I think I have it all figured out, including replacing <code>import speech_recognition as sr</code> with it's python3 counterpart, <code>import SpeechRecognition as sr</code>. I am using PyCharm Community as my IDE, and for those that know it, it allows you to install missing modules used by <code>import</code> by mousing over them and clicking the prompt to install the module. Long story short, this doesn't work for SpeechRecognition. It's showing <code>No module named 'SpeechRecognition'</code> despite clicking the prompt several times and seeing that it successfully installed.</p> <p>I went to the Python Terminal and tried to do this manually with the following:</p> <pre><code> &gt;&gt; pip3 install SpeechRecognition WARNING: You are using pip version 21.1.2; however, version 21.3.1 is available. You should consider upgrading via the 'C:\Users\[user]\PycharmProjects\[my project]\venv\Scripts\python.exe -m pip install --upgrade pip' command. &gt;&gt; C:\Users\[user]\PycharmProjects\[my project]\venv\Scripts\python.exe -m pip install --upgrade pip Requirement already satisfied: pip in C:\Users\[user]\PycharmProjects\[my project]\venv\lib\site-packages (21.1.2) Collecting pip` Using cached pip-21.3.1-py3-none-any.whl (1.7 MB) Installing collected packages: pip Attempting uninstall: pip` Found existing installation: pip 21.1.2 Uninstalling pip-21.1.2: Successfully uninstalled pip-21.1.2 Successfully installed pip-21.3. &gt;&gt; pip3 install SpeechRecognition Requirement already satisfied: pip in C:\Users\[user]\PycharmProjects\[my project]\venv\lib\site-packages (3.8.1) </code></pre> <p>I'm fairly new to Python and coding in general, but from I can tell it <em>is</em> installed. However, when I run the program, it returns the following error:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\[user]\PycharmProjects\[my project]\main.py&quot;, line 2, in &lt;module&gt; import SpeechRecognition as sr ModuleNotFoundError: No module named 'SpeechRecognition' </code></pre> <p>Not sure what I'm doing wrong here, but any help would be appreciated.</p> <p>Thanks, and cheers.</p>
<blockquote> <p>I think I have it all figured out, including replacing <code>import speech_recognition as sr</code> with it's python3 counterpart, <code>import SpeechRecognition as sr</code></p> </blockquote> <p>This is your issue. I can't find anywhere that says you should import the library that way. All the <a href="https://github.com/Uberi/speech_recognition/tree/master/examples" rel="nofollow noreferrer">official examples</a>, and the <a href="https://github.com/Uberi/speech_recognition#readme" rel="nofollow noreferrer">official readme</a>, state that it should be imported via:</p> <pre><code>import speech_recognition as sr </code></pre> <p>Again I'm not sure why you thought it should be imported differently just because you're using Python 3. I will say that GeeksForGeeks is generally <em>not</em> recognized as a good source of information by this site's community. I highly recommend using other sites, and also always starting from official sources.</p>
python|python-3.x|pip|speech-recognition
2
1,907,910
71,065,266
Is there a way to get all combinations of overlap between values in dictionary, or from within a list
<p>I have a few lists</p> <pre><code>A =['D','KIT','SAP'], B= ['F','G','LUFT','SAP'], C= ['I','SAP'], D= ['SAP','LUF','KIT'], F= ['SAP','LUF','KIT','HASS'] </code></pre> <p>I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.</p> <pre><code>my_dict={&quot;AB&quot;:[['D','KIT','SAP'],['F','G','LUFT','SAP']]} </code></pre> <p>My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.</p> <pre><code> for k,v in my_dict.items(): print(k,list(set.intersection(*[set(x) for x in v]))) </code></pre> <p>AB ['SAP']</p> <p>However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.</p> <p>The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. <strong>And in the end, I would like to get the overlap for each of the following combinations.</strong></p> <pre><code> AB, AC, AD, AF ABC, ABD, ABF ABCD, ABCDF ABCDF BC, BD, BF DF, DC FC </code></pre> <p>The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.</p> <p>As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.</p> <p>Thanks</p>
<p>Have a look at <code>itertools.combinations</code>. It returns all possible combinations of a given length for a given iterable. You'll have to loop over all possible lengths.</p> <pre><code>import itertools lists = [A, B, C, D, E, F] combinations = [] for l in range(2, len(lists) + 1): combinations += itertools.combinations(lists, l) </code></pre> <p><code>combinations</code> will be a list of tuples with all possible combinations of at least two lists.</p>
python|list|dictionary|overlap|venn
3
1,907,911
11,845,727
Possible to write i-phone app in python
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/43315/can-i-write-native-iphone-apps-using-python">Can I write native iPhone apps using Python</a> </p> </blockquote> <p>I just googled whether it is possible to write an i-phone app in Python and got very confusing, and not super good results.</p> <p>Is it possible? And if so, what module(s) do I need to install?</p>
<p>You can use PyObjC on the iPhone.</p> <p><a href="http://pyobjc.sourceforge.net/" rel="nofollow">http://pyobjc.sourceforge.net/</a></p> <p>You need to jail break your iphone for this to run.</p> <p>They have a tutorial too which of course comes top of google search.</p> <p><a href="http://www.saurik.com/id/5/" rel="nofollow">http://www.saurik.com/id/5/</a></p>
iphone|python
2
1,907,912
11,618,687
Why can't you re-import in Python?
<p>There are plenty of questions and answers regarding re-imports on SO, but it all seems very counter-intuitive without knowing the mechanisms behind it.</p> <p>If you import a module, change the contents, then try to import it again, you'll find that the second import has no effect:</p> <pre><code>&gt;&gt;&gt; import foo # foo.py contains: bar = 'original' &gt;&gt;&gt; print foo.bar original &gt;&gt;&gt; # edit foo.py and change to: bar = 'changed' &gt;&gt;&gt; import foo &gt;&gt;&gt; print foo.bar original </code></pre> <p>I was a very happy camper when I discovered <code>reload</code>:</p> <pre><code>&gt;&gt;&gt; reload(foo) &gt;&gt;&gt; print foo.bar changed </code></pre> <p>However there's no easy solution when you're importing items from a module without importing the module itself:</p> <pre><code>&gt;&gt;&gt; from foo import baz &gt;&gt;&gt; print baz original &gt;&gt;&gt; # change foo.py from baz = 'original' to baz = 'changed' &gt;&gt;&gt; from foo import baz &gt;&gt;&gt; print baz original &gt;&gt;&gt; reload(foo) Traceback (most recent call last): File "&lt;pyshell#10&gt;", line 1, in &lt;module&gt; reload(foo) NameError: name 'foo' is not defined </code></pre> <p>Why won't Python update imported items when you give it a new <code>import</code> statement?</p>
<p>When you import a module, it is cached in <a href="http://docs.python.org/library/sys.html?highlight=sys.modules#sys.modules"><code>sys.modules</code></a>. Any attempt to import the same module again within the same session simply returns the already existing module contained there. This speeds up the overall experience when a module is imported from multiple places. It also allows a module to have its own objects shared between all of the imports, since the same module is returned each time.</p> <p>As mentioned you can use <a href="http://docs.python.org/library/functions.html?highlight=reload#reload"><code>reload</code></a> to re-import a whole module. Check the documentation for the caveats, because even this is not fool-proof.</p> <p>When you import specific items from a module, the whole module is imported as above and then the objects you requested are placed in your namespace. <code>reload</code> doesn't work because these objects aren't modules, and you never received a reference to the module itself. The work-around is to get a reference to the module, reload it, then re-import:</p> <pre><code>&gt;&gt;&gt; from foo import baz &gt;&gt;&gt; print baz original &gt;&gt;&gt; # change foo.py from baz = 'original' to baz = 'changed' &gt;&gt;&gt; import foo &gt;&gt;&gt; reload(foo) &gt;&gt;&gt; from foo import baz &gt;&gt;&gt; print baz changed </code></pre>
python|import
11
1,907,913
11,991,199
Multithreading Boost Python C++ Code in PySide
<p>I have c++ code that I am wrapping with Boost Python. The idea is, I create a shared object that my python GUI can use to instantiate variables that wrap the c++ functionality</p> <p>The c++ code does some heaving lifting, and I want to be able to make the wrapped object run concurrently so that the GUI doesn't block.</p> <p>I compiled a Boost Python shared object wrapped with CMake like so:</p> <pre><code>find_package(Boost COMPONENTS system thread python REQUIRED) find_package(PythonLibs REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) include_directories(${PYTHON_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) link_directories(${PYTHON_LIBRARIES}) set(Boost_USE_MULTITHREADED ON) add_library(mynewlibinpython SHARED src/boost_python_wrapper_code.cpp) target_link_libraries(mynewlibinpython ${Boost_LIBRARIES} ${PYTHON_LIBRARIES} mylibincpp) </code></pre> <p>I can instantiate the object in python fine, but it causes the GUI to block. Here is a generalized snippet of my python code:</p> <pre><code>from mynewlibinpython import * class CppWrapper(QtCore.QObject): def __init__(self): super(CppWrapper,self).__init__() #some more initialization... @QtCore.Slot() def heavy_lifting_cpp_invocation(): #constructor that takes a long time to complete self.cpp_object = CppObject() </code></pre> <p>and in an object that has a member function that is triggered when I press a button in the GUI:</p> <pre><code>class GuiObjectWithUnimportantName: def __init__(self): #inititalization self.cpp_thread = QThread() self.cpp_wrapper = CppWrapper() def function_triggered_by_button_press(self): self.cpp_wrapper.moveToThread(self.cpp_thread) self.cpp_thread.started.connect(self.cpp_wrapper.heavy_lifting_cpp_invocation) print "starting thread" self.cpp_thread.start() print "Thread started" </code></pre> <p>So the cpp code will start doing its thing, and I'll also get the output basically immediately from both of the <code>print</code> statements ("starting thread" and "Thread started").</p> <p>But the GUI is frozen. Does this have anything to do with the python GIL? I tried adding those macros into the <code>boost_python_wrapper_code.cpp</code> and recompiled, but it causes the python GUI to segfault immediately upon startup.</p>
<p>Yes, I believe your problem is GIL related. Here is a simple example of what might be happening:</p> <pre><code>from PyQt4 import QtCore, QtGui import time class Window(QtGui.QDialog): def __init__(self): super(Window, self).__init__() self.resize(200,100) layout = QtGui.QVBoxLayout(self) layout.addWidget(QtGui.QLineEdit()) self.button1 = QtGui.QPushButton("Sleep") self.button1.clicked.connect(self.go_safe) layout.addWidget(self.button1) self.button2 = QtGui.QPushButton("Crunch") self.button2.clicked.connect(self.go_GIL_buster) layout.addWidget(self.button2) def go_safe(self): t = QtCore.QThread(self) heavy = Heavy() heavy.moveToThread(t) t.started.connect(heavy.safe) print "starting thread" t.start() print "thread started" self.t1 = t self.heavy1 = heavy def go_GIL_buster(self): t = QtCore.QThread(self) heavy = Heavy() heavy.moveToThread(t) t.started.connect(heavy.GIL_buster) print "starting thread" t.start() print "thread started" self.t2 = t self.heavy2 = heavy class Heavy(QtCore.QObject): def safe(self): print "Sleeping" time.sleep(10) print "Done" def GIL_buster(self): print "Crunching numbers" x = 2 y = 500000000 foo = x**y print "Done" if __name__ == "__main__": app = QtGui.QApplication([]) win = Window() win.show() win.raise_() app.exec_() </code></pre> <p>When you click the first button, the thread will do a sleep for 10 seconds, and you will notice that you can still type into the text field. A sleep releases the GIL so the main thread can continue to work.</p> <p>When you click the second button, the thread does a heavy number operation. This acquires the GIL the entire time, and the GUI will lock until it is done.</p> <p>If your boost extension isn't doing anything with python objects in any way, I think you can release the GIL for its operations. Then it won't block the GUI. If you are doing heavy operations on python objects, then you might have a problem here.</p> <p>There is a <a href="http://wiki.python.org/moin/boost.python/HowTo" rel="nofollow">tip on creating a scope-based GIL releasing class</a> that you can use in any function to release the GIL for the duration of that function (when the helper instance gets destroyed)</p> <pre><code>class ScopedGILRelease { // C &amp; D ---------------------------- public: inline ScopedGILRelease() { m_thread_state = PyEval_SaveThread(); } inline ~ScopedGILRelease() { PyEval_RestoreThread(m_thread_state); m_thread_state = NULL; } private: PyThreadState * m_thread_state; }; </code></pre> <p>And using it...</p> <pre><code>int foo_wrapper(int x) { ScopedGILRelease scoped; return foo(x); } </code></pre> <p>Someone else has some more examples of using this tip in this repo: <a href="https://bitbucket.org/wwitzel3/code/src/tip/nogil/nogil.cpp" rel="nofollow">https://bitbucket.org/wwitzel3/code/src/tip/nogil/nogil.cpp</a></p>
c++|python|multithreading|user-interface|boost-python
3
1,907,914
37,966,998
pandas pivot_table: values per column instead of columns per value
<p>I have the following rows:</p> <pre><code>ID date value1 value2 1 16-01 1 2 1 16-02 3 4 2 16-01 5 6 2 16-02 7 8 </code></pre> <p>pivot table:</p> <pre><code>pd.pivot_table(rows,index = ["ID"],values = ["value1","value2"],columns = ["date"] </code></pre> <p>prints:</p> <pre><code> value1 value2 16-01 16-02 16-01 16-02 ID 1 1 3 2 4 2 5 7 6 8 </code></pre> <p>But I want:</p> <pre><code> 16-01 16-02 value1 value2 value1 value2 ID 1 1 2 3 4 2 5 6 7 8 </code></pre> <p>So how can I create all values per column instead of all columns per values?</p>
<p>Try using <code>.swaplevel</code> and <code>.sortlevel</code> methods </p> <pre><code>In [15]: pd.pivot_table(rows,index=["ID"],values=["value1","value2"],columns=["d ate"]).swaplevel(0,1, axis=1).sortlevel(0, axis=1) Out[15]: date 16-01 16-02 value1 value2 value1 value2 ID 1 1 2 3 4 2 5 6 7 8 </code></pre>
python|pandas|pivot-table
3
1,907,915
65,683,397
Is there a fast way to compare every two rows in a 2-dimensional array?
<p>So I've got a 2-dimensional array, say <code>list</code>:</p> <pre><code>list = [[x11, x12, x13, x14], [x21, x22, x23, x24], ...] </code></pre> <p>Some samples of <code>list</code> are:</p> <pre><code># numbers in list are all integers list = [[0, 17, 6, 10], [0, 7, 6, 10], ] list = [[6, 50, 6, 10], [0, 50, 6, 10], ] list = [[6, 16, 6, 10], [6, 6, 6, 10], ] list = [[0, 50, 6, 10], [6, 50, 6, 10], [6, 40, 6, 10] ] list = [[0, 27, 6, 10], [0, 37, 6, 10], ] </code></pre> <p>I need to iterate every two rows, for example [x11, x12, x13, x14] and [x21, x22, x23, x24], and do some complex comparisons:</p> <pre><code>cnt1 = cnt2 = cnt3 = cnt4 = cnt5 = 0 for i in range(0, length): for j in range(i + 1, length): if (list[i][0] + list[i][2] == list[j][0] or list[j][0] + list[j][2] == list[i][0]) and \ list[i][1] == list[j][1]: cnt1 += 1 if list[i][3] == list[j][3]: cnt2 += 1 else cnt3 += 1 elif (list[i][1] + list[i][3] == list[j][1] or list[j][1] + list[j][3] == list[i][1]) and \ list[i][0] == list[j][0]: cnt4 += 1 if list[i][2] == list[j][2]: cnt2 += 1 else cnt3 += 1 else cnt5 += 1 # do something with the counts </code></pre> <p><code>length</code> here is usually small, but this nested loop runs thousands of times, so it takes very long to finish the program. I've read some tutorials of vectorizing in Numpy, but cannot figure out how to edit the code since the logic is kind of complex. Is there a way to optimize my code, even for a little bit? Any help would be highly appreciated. Thanks in advance!</p>
<p>I am posting a solution for how to do this for the first <code>if</code> and the subsequent <code>if</code> and <code>else</code> conditions.</p> <p>You can follow similar logic to do the same for the rest as well.</p> <pre><code>import numpy as np arr = np.array([[0, 17, 6, 10], [0, 7, 6, 10], [6, 50, 6, 10], [0, 50, 6, 10], [6, 16, 6, 10], [6, 6, 6, 10], [0, 50, 6, 10], [6, 50, 6, 10], [6, 40, 6, 10], [0, 27, 6, 10], [0, 37, 6, 10]]) N = len(arr) cnt1 = cnt2 = cnt3 = cnt4 = cnt5 = 0 for i in range(0, N): for j in range(i + 1, N): if (arr[i][0] + arr[i][2] == arr[j][0] or arr[j][0] + arr[j][2] == arr[i][0]) and \ arr[i][1] == arr[j][1]: cnt1 += 1 if arr[i][3] == arr[j][3]: cnt2 += 1 else: cnt3 += 1 elif (arr[i][1] + arr[i][3] == arr[j][1] or arr[j][1] + arr[j][3] == arr[i][1]) and \ arr[i][0] == arr[j][0]: cnt4 += 1 if arr[i][2] == arr[j][2]: cnt2 += 1 else: cnt3 += 1 else: cnt5 += 1 # this corresponds to (arr[i][0] + arr[i][2] == arr[j][0] or arr[j][0] + arr[j][2] == arr[i][0]) cnt1_bool_c1 = ((arr[:, 0] + arr[:, 2])[:, None] == arr[:, 0][None, :]) # arr[i][1] == arr[j][1]: cnt1_bool_c2 = arr[:, 1][:, None] == arr[:, 1][None, :] # So that i and j are compared only if i != j cnt1_bool_c2[np.arange(N), np.arange(N)] = False # doing and of the two previous conditions finishing the very first if condition cnt1_bool = np.bitwise_and(cnt1_bool_c1, cnt1_bool_c2) # corresponds to cnt1 cnt1_n = cnt1_bool.sum() # verified print(cnt1 == cnt1_n) # corresponds to arr[i][3] == arr[j][3] cnt2_bool_c = arr[:, 3][:, None] == arr[:, 3][None, :] # So that i and j are compared only if i != j cnt2_bool_c[np.arange(N), np.arange(N)] = False # correspond to the inner if, count only if these elemets share the same position as the previous elements cnt2_n1 = np.bitwise_and(cnt1_bool, cnt2_bool_c).sum() # corresponds to the cnt2 += 1 in the first inner condition # correspond to the inner else, count only if these elemets do not share the same position as the previous elements cnt3_n1 = np.bitwise_and(cnt1_bool, ~cnt2_bool_c).sum() # corresponds to the cnt3 += 1 in the first inner else condition </code></pre>
python|arrays|numpy|optimization|vectorization
0
1,907,916
72,278,908
Return of None not expected
<p>I have a small function as follows:</p> <pre><code># Given the numerical value of a minute hand of a clock, return the number of degrees assuming a circular clock. # Raise a ValueError for values less than zero or greater than 59. def exercise_20(n): try: if n &lt; 0 or n &gt; 59: raise ValueError(&quot;Number supplied is less than 0 or greater than 59&quot;) except ValueError as ex: print(ex) else: return n * 6 print(exercise_20(-15)) print(exercise_20(30)) print(exercise_20(75)) </code></pre> <p>Here is the output:</p> <pre><code>Number supplied is less than 0 or greater than 59 None 180 Number supplied is less than 0 or greater than 59 None </code></pre> <p>Why am I returning 'None' when I strike an exception?</p> <p>The function correctly prints the exception for the appropriate values and it prints the correct answer for a value within the correct range.</p> <p>I don't understand why it also printing 'None' when it strikes an exception.</p>
<p>You try a block, if it fails your condition <code>if n &lt; 0 or n &gt; 59</code>, you raise. You then catch your raise and just log it. Then you return nothing. Catch and release is for fishing :).</p> <pre><code>def exercise_20(n): if n &lt; 0 or n &gt; 59: raise ValueError(&quot;Number supplied is less than 0 or greater than 59&quot;) return n * 6 print(exercise_20(-15)) print(exercise_20(30)) print(exercise_20(75)) </code></pre> <p>You might be interested on this too: <a href="https://softwareengineering.stackexchange.com/questions/187715/validation-of-the-input-parameter-in-caller-code-duplication#">https://softwareengineering.stackexchange.com/questions/187715/validation-of-the-input-parameter-in-caller-code-duplication#</a>. When should you check for input conditions? Caller or callee?</p>
python|python-3.x
1
1,907,917
43,453,844
Python QWebEngineView redirects to wrong language page
<p>When I browse to a page using the following code, the result is in another language (Russian I think). When I browse to the same url in other browsers I get the English 404 page as expected. I tried setting the accept language, but that didn't help. What am I missing?</p> <pre><code>import sys from PyQt5 import QtWidgets, QtCore from PyQt5.QtWebEngineWidgets import QWebEngineView app = QtWidgets.QApplication(sys.argv) w = QWebEngineView() w.page().profile().setHttpAcceptLanguage('en') # This doesn't help w.load(QtCore.QUrl('http://turbobit.net/download')) # Goes to russian? 404 page w.show() app.exec_() </code></pre> <p>The following webkit version works as expected</p> <pre><code>import sys from PyQt5 import QtWidgets, QtCore from PyQt5.QtWebKitWidgets import QWebView app = QtWidgets.QApplication(sys.argv) w = QWebView() w.setUrl(QtCore.QUrl('http://turbobit.net/download')) # Loads correct English 404 page w.show() app.exec_() </code></pre>
<p>You need to set the language before creating the view:</p> <pre><code>import sys from PyQt5 import QtWidgets, QtCore from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile app = QtWidgets.QApplication(sys.argv) QWebEngineProfile.defaultProfile().setHttpAcceptLanguage('en') w = QWebEngineView() w.load(QtCore.QUrl('http://turbobit.net/download')) w.show() app.exec_() </code></pre>
python|pyqt|pyqt5|qtwebengine
3
1,907,918
43,469,260
Use in operator in set of tuples python
<p>I have a problem trying to check if an element is part of a set in Python. (My set contains about 600K tuples of string.)</p> <p>I'm searching for a solution that use the benefit of <code>in</code> operator to check if a value is element of a tuple of the set.</p> <p>I've found solution like:</p> <pre><code># S set of tuples, I'm checking if v is the second element of a tuple any( y == v for (_, y) in S ) </code></pre> <p>but this has a O(n) complexity.</p> <p>The Python documentation says that the average complexity of the IN operator is O(1).</p> <p><strong>EDIT</strong></p> <p><strong>My problem is:</strong> How to check if an element is the first/second/... element of at least one tuple of the set using the speed of <code>in</code> operator.</p>
<p>The complexity of a containment test depends on the <em>object type</em>, not the operator, because the operation is delegated to the container. Testing containment in a list is O(n), containment in a set is O(1).</p> <p>However, you are not testing containment in a set, you are testing containment in a pile of tuples (where the container for the tuples <em>can't help</em>). Without further processing, you can't do better than O(n) here.</p> <p>You could create and maintain separate datastructures, for example, where you track the separate values contained in your tuples as well as the tuples themselves, then test against those separate datastructures. That'd increase the memory requirements, but lower the computational cost. </p> <p>You'd amortise the cost of keeping that structure up-to-date over the lifetime of your program (only increasing the constant cost of building the data structure slightly), and in return you get O(1) operations on your containment test. Only do this if you need to do this test multiple times, for different values.</p>
python|performance|set|tuples|any
4
1,907,919
48,779,945
Python directory copy using shutil
<p>I have below code:</p> <pre><code>import shutil import os def copy_files(file_path, symlinks=False, ignore=None): try: if os.path.isdir(src): shutil.copytree(src, dest, symlinks, ignore) else: shutil.copy2(src, dest) except IOError: pass </code></pre> <p>Receiving below error when executing code:</p> <pre><code> shutil.copytree(src, dest, symlinks, ignore) File "/usr/lib64/python2.7/shutil.py", line 177, in copytree os.makedirs(dst) File "/usr/lib64/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 17] File exists: ' File path: /etc/ /var/tmp/ it works cp -r /etc/ /var/tmp/ </code></pre> <p>Python2.7 I am using </p>
<p>Probably you get this error because the destination directory already exists. From the documentation of <code>copytree()</code>:</p> <blockquote> <p>The destination directory, named by dst, must not already exist;...</p> </blockquote> <p>Try calling <code>shutil.rmtree(dest, True)</code> before <code>shutil.copytree()</code>.</p> <p><code>cp</code> does not fail if destination exists: it just overwrites it.</p>
python|python-2.7
2
1,907,920
66,922,669
Plotting a 2D line over a figure 2D line in matplotlib
<p>I'm trying to plot a line over a figure line but couldn't plot it exactly on the axes. You can find the code here:</p> <p><a href="https://colab.research.google.com/drive/1J12vWUIUr0dDIesMHBU9vYUkjnNKXOqT?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1J12vWUIUr0dDIesMHBU9vYUkjnNKXOqT?usp=sharing</a></p> <p>Here is the code for the 2D line which is then saved.</p> <pre><code>ax = plt.subplot() ax.plot([10,45], [20,100], color=&quot;g&quot;) plt.xticks([]) plt.yticks([]) ax.set_axis_off() plt.axis([0, 144, 0, 144]) plt.figure(figsize = (2,2)) plt.tight_layout() plt.show() fig.savefig('testfig.png') </code></pre> <p><a href="https://i.stack.imgur.com/mqVu6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mqVu6.png" alt="ground truth" /></a></p> <p>Here is the code where I import the figure line and create a similar line with exact same coordinates and axes but couldn't figure it out. Green line is the imported one and the red one is the line to draw exactly over the imported one.</p> <pre><code>image = plt.imread('testfig.png') #fig2 = plt.figure() #fig2.set_size_inches(1,1) ax2 = plt.subplot() ax2.imshow(image, extent=[0, 144, 0, 144]) ax2.plot([10,45], [20,100], color=&quot;r&quot;) plt.xticks([]) plt.yticks([]) ax2.set_axis_off() plt.tight_layout() plt.axis([0, 144, 0, 144]) plt.figure(figsize = (2,2)) print(image.shape) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/xALpn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xALpn.png" alt="2 lines" /></a></p> <p>Maybe it's because the exported line's shape comes out different from what I intended i.e 144x144. Is there a way to export exactly 144x144 without reshaping?</p>
<p>I figured this out. Upon digging, I found that <code>plt.tight_layout()</code> has a default 1.08 padding: <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html" rel="nofollow noreferrer">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html</a></p> <p>The only thing I wanted was to pass <code>pad=0</code> as a parameter to <code>plt.tight_layout(pad=0)</code>. That's it.</p>
python|matplotlib|plot|line
2
1,907,921
48,032,876
Get RGB image pixel values as 16bit and fill lists
<p>With ImageMagick I can convert any image into a textfile with pixel/value representation of every single (RGB) pixel. This is a sample output of an 16bit integer png file obtained via "convert spektrum.png spektrum.txt"</p> <pre><code># ImageMagick pixel enumeration: 1553,24,65535,srgba 0,0: (16192,7721,24114,65535) #3F401E295E32FFFF srgba(25%,12%,37%,1) </code></pre> <p>this represents the the first upper left pixel (0,0) in the image with its rgb(a) values.</p> <p><strong>Question:</strong> How can I read the same image with Python(3) into a list/array with its 16bit values? If I use pillow to read this PNG file</p> <pre><code>from PIL import Image im = Image.open("spektrum.png") pix = im.load() print(pix[2,5]) (67, 35, 99, 255) </code></pre> <p>I only get 0-255 RGBA-values from it.</p>
<p>I can read now 16 bit values with opencv:</p> <pre><code>&gt;&gt;&gt; import cv2 &gt;&gt;&gt; img = cv2.imread('spektrum.png',-1) # -1 read format as is &gt;&gt;&gt; print(img.dtype) uint16 &gt;&gt;&gt; px = img[0,0] &gt;&gt;&gt; print(px) [24114 7721 16192 65535] </code></pre>
python|image|pixel|16-bit
1
1,907,922
51,128,072
use xlwings to run python code in excel
<p>I have a problem running python code by xlwings in excel. My vba code is:</p> <pre><code>Sub Practice() RunPython ("import practice; practice.getdata()") End Sub </code></pre> <p>My python code is practice.py in pycharm. I use the python code to connect to the deribit api and then use excel to run the python code to download data from deribit api to excel. My python code is the following:</p> <pre><code>import pprint import xlwings as xw import pandas as pd import numpy as np from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl import Workbook from deribit_api import RestClient def getdata(): access_key = "6wvUvxmVSoJq" access_secret = "HQQ7ZTU2ZESOR2UELLVSHCRWSHPP2VYE" url = "https://test.deribit.com" client = RestClient(access_key, access_secret, url) client.index() positions = client.positions() account = client.account() dfp = pd.DataFrame(columns=['Kind', 'Expiry Date', 'Direction', 'Underlying', 'Delta', 'Size', 'P&amp;L'], index=range(len(positions))) for i in range(len(positions)): dfp.loc[i]['Kind'] = positions[i]['kind'] dfp.loc[i]['Expiry Date'] = positions[i]['instrument'] dfp.loc[i]['Direction'] = positions[i]['direction'] dfp.loc[i]['Underlying'] = positions[i]['indexPrice'] dfp.loc[i]['Delta'] = positions[i]['delta'] dfp.loc[i]['Size'] = positions[i]['size'] dfp.loc[i]['P&amp;L'] = positions[i]['profitLoss'] wb = xw.Book.caller() ws = wb.active for r in dataframe_to_rows(dfp, index=False, header=True): ws.append(r) ws.cell(row=15, column=1).value = 'Total Delta' ws.cell(row=15, column=2).value = 'Options Delta' ws.cell(row=15, column=3).value = 'Options Gamma' ws.cell(row=15, column=4).value = 'Options Theta' ws.cell(row=15, column=5).value = 'Options Vega' ws.cell(row=16, column=1).value = account['deltaTotal'] ws.cell(row=16, column=2).value = account['optionsD'] ws.cell(row=16, column=3).value = account['optionsG'] ws.cell(row=16, column=4).value = account['optionsTh'] ws.cell(row=16, column=5).value = account['optionsV'] </code></pre> <p>After running excel, I get an error message like the following:</p> <blockquote> <p>File "/Users/wenchengwang/PycharmProjects/practice/practice.py", line 7, in </p> <p>from deribit_api import RestClient</p> <p>ModuleNotFoundError: No module named 'deribit_api'</p> </blockquote> <p>I am confused the error message, does it mean I have to install deribit api into excel?</p>
<p>You seem to be invoking a Python environment from Excel that does not have the derebit package installed. You have to either point your Excel add-in to the interpreter that has the package installed or add the path of the package to your PYTHONPATH, see: </p> <p><a href="http://docs.xlwings.org/en/stable/addin.html#global-settings" rel="nofollow noreferrer">http://docs.xlwings.org/en/stable/addin.html#global-settings</a></p>
python|api|xlwings
0
1,907,923
51,484,491
Get output of subprocess after Keyboard Interrupt
<p>I want to store into a variable the last output of a subprocess after the user performs a Keyboard Interrupt. My problem is mainly with a subprocess without end, i.e. tail in my exemple below. Here is my code:</p> <pre><code>class Testclass: def Testdef(self): try: global out print "Tail running" tail_cmd='tail -f log.Reconnaissance' proc = subprocess.Popen([tail_cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() except KeyboardInterrupt: print("KeyboardInterrupt received, stopping…") finally: print "program output:", out if __name__ == "__main__": app = Testclass() app.Testdef() </code></pre> <p>Below is its output, which I don't understand at this moment.</p> <pre><code>Tail running program output: Traceback (most recent call last): File "./2Test.py", line 19, in &lt;module&gt; app.Testdef() File "./2Test.py", line 15, in Testdef print "program output:", out NameError: global name 'out' is not defined </code></pre>
<p><code>out</code> not being defined indicates that the process <code>proc.communicate()</code> did not return any values, otherwise it would have populated your tuple <code>(out, err)</code>. Now to find out whether the <code>communicate()</code> method was supposed to return or whether, more likely, your keyboard interrupt simply killed it, thus preventing <code>out</code> from being defined.</p> <hr> <p>I assume you imported the <code>subprocess</code> module, but make sure you do that first. I rewrote your program without using <code>global out</code> or the <code>try</code> statements.</p> <pre><code>import subprocess class Testclass: def __init__(self,out): # allows you to pass in the value of out self.out = out # makes out a member of this class def Testdef(self): print("Tail running") tail_cmd='tail -f log.Reconnaissance' proc = subprocess.Popen([tail_cmd], stdout=subprocess.PIPE, shell=True) # Perhaps this is where you want to implement the try: (self.out, err) = proc.communicate() # and here the except: # and here the finally: if __name__ == "__main__": app = Testclass(1) # pass 1 (or anything for testing) to the out variable app.Testdef() print('%r' % app.out) # print the contents of the out variable # i get an empty string, '' </code></pre> <hr> <p>So as-is this program runs once. There is nothing in <code>out</code>. I believe to create a meaningful example of the user doing a keyboard interrupt, we need the program to be doing something that can be interrupted. Maybe I can provide an example in the future...</p>
python|subprocess
0
1,907,924
51,257,233
Python: "ImportError: DLL load failed: The specified module could not be found." Problems when importing ffn (finance library for python)
<p>Apologies if there does in fact exist a thread that has already figured this out (I've spent a few hours attentively searching multiple sites and the GitHubs for the dependencies that seem to cause the problems), however each solution seemed fairly specific to the particular library that so and so was attempting to use.</p> <p>I've been messing around with quantitative finance/ algorithmic trading and have been trying to import a particular library <code>ffn</code>, however, per the question title, I've been receiving a somewhat lengthy error message detailing an <code>ImportError</code>, and how I'm supposedly missing certain, very specific dependencies that seem to be there. Honestly this may just be a dependency-ception (I'm missing dependencies of dependencies of <code>ffn</code>), but I've done my best to rule out this possibility.</p> <p>Here's the full error:</p> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-2-01bc82d8cf41&gt; in &lt;module&gt;() 2 import numpy as np 3 import pandas as pd ----&gt; 4 import ffn 5 import math ~\PycharmProjects\buff\venv\lib\site-packages\ffn\__init__.py in &lt;module&gt;() ----&gt; 1 from . import core 2 from . import data 3 4 from .data import get 5 #from .core import year_frac, PerformanceStats, GroupStats, merge ~\PycharmProjects\buff\venv\lib\site-packages\ffn\core.py in &lt;module&gt;() 8 from pandas.core.base import PandasObject 9 from tabulate import tabulate ---&gt; 10 import sklearn.manifold 11 import sklearn.cluster 12 import sklearn.covariance ~\PycharmProjects\buff\venv\lib\site-packages\sklearn\__init__.py in &lt;module&gt;() 132 else: 133 from . import __check_build --&gt; 134 from .base import clone 135 __check_build # avoid flakes unused variable error 136 ~\PycharmProjects\buff\venv\lib\site-packages\sklearn\base.py in &lt;module&gt;() 11 from scipy import sparse 12 from .externals import six ---&gt; 13 from .utils.fixes import signature 14 from . import __version__ 15 ~\PycharmProjects\buff\venv\lib\site-packages\sklearn\utils\__init__.py in &lt;module&gt;() 9 10 from .murmurhash import murmurhash3_32 ---&gt; 11 from .validation import (as_float_array, 12 assert_all_finite, 13 check_random_state, column_or_1d, check_array, ~\PycharmProjects\buff\venv\lib\site-packages\sklearn\utils\validation.py in &lt;module&gt;() 16 17 from ..externals import six ---&gt; 18 from ..utils.fixes import signature 19 from .. import get_config as _get_config 20 from ..exceptions import NonBLASDotWarning ~\PycharmProjects\buff\venv\lib\site-packages\sklearn\utils\fixes.py in &lt;module&gt;() 142 from ._scipy_sparse_lsqr_backport import lsqr as sparse_lsqr 143 else: --&gt; 144 from scipy.sparse.linalg import lsqr as sparse_lsqr # noqa 145 146 ~\PycharmProjects\buff\venv\lib\site-packages\scipy\sparse\linalg\__init__.py in &lt;module&gt;() 112 from __future__ import division, print_function, absolute_import 113 --&gt; 114 from .isolve import * 115 from .dsolve import * 116 from .interface import * ~\PycharmProjects\buff\venv\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py in &lt;module&gt;() 4 5 #from info import __doc__ ----&gt; 6 from .iterative import * 7 from .minres import minres 8 from .lgmres import lgmres ~\PycharmProjects\buff\venv\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py in &lt;module&gt;() 8 import numpy as np 9 ---&gt; 10 from . import _iterative 11 12 from scipy.sparse.linalg.interface import LinearOperator ImportError: DLL load failed: The specified module could not be found. </code></pre> <p>This particular message was from a failed Jupyter notebook trial (IPython console), though I've tried running the same code through a "normal" Python 3 file, only to get the same message. As I inferred earlier, I already have downloaded/ properly installed all the dependencies mentioned in the message (<code>sklearn</code> and <code>scipy</code> are the only problem children outside of <code>ffn</code> itself that the error mentions). The thing confusing me the most is that all of the things that these import statements within the dependencies/ within <code>ffn</code> reference are where they should and (to my knowledge) are accessible.</p> <p>Perhaps I should've researched this more thoroughly, but the only thing that really made sense to me was that I had the wrong version of these libraries (which are, for the most part, well maintained and somewhat frequently updated) and that certain features that <code>ffn</code> and its dependencies need were deprecated and no longer exist. However, this theory was disproven (at least in part) when I took 30 seconds to figure out if <code>sklearn.manifold</code> existed, and to my apparent surprise, it does. I also checked my IDE's library manager/ interpreter settings menu and everything is up to date (I'm using PyCharm CE). </p> <p>In short: why I am receiving this message when I seem to have everything it's searching for/ what exactly does it mean, and how do I fix this so that I can use the libraries I wanted to use?</p> <p>If this helps at all, here's a summary:</p> <p>All libraries/ dependencies are up to date (PyCharm maintains what versions each one is currently on, although I have to go in manually to tell it to execute the update).</p> <p>Again, I'm on PyCharm CE 2018 (most recent version).</p> <p>Here's the entire cell from the Jupyter notebook which yields the error (which also happens to be everything that's in the notebook): </p> <p><code>from pylab import * import numpy as np import pandas as pd import ffn import math</code></p> <p>Here's all of the contents of the Python document that yields the same error (virtually the same code):</p> <p><code>import ffn import math import pandas as pd, numpy as np import datetime data1 = ffn.get('agg, hyg, spy, eem, efa', start='2018-01-01', end='2018-02-02') print(data1.head())</code></p> <p>I'm running Windows 10 64 bit</p>
<p>Your code is not able to locate your modules. In a Jupyter Notebook, you can make it so that it can. <code>'PYTHONPATH'</code> is the environment variable which locates the custom modules in python. Now your modules are in your project directory, so you need to make sure your interpreter can locate your files.</p> <p>Basically, you need to set the path in your Jupyter Notebook to locate imported user define modules.</p> <p>"To set an <code>env</code> variable in a jupyter notebook, just use a "%" magic commands, either <code>%env</code> or <code>%set_env</code>, e.g., <code>%env MY_VAR=MY_VALUE</code> or <code>%env MY_VAR MY_VALUE</code>. (Use <code>%env</code> by itself to print out current environmental variables.)"</p> <p>See: <a href="https://stackoverflow.com/questions/37890898/how-to-set-env-variable-in-jupyter-notebook">How to set env variable in Jupyter notebook</a></p>
python|python-3.x|python-import|importerror|finance
1
1,907,925
51,177,099
How to read RTSP Video from OpenCV with Low CPU Usage?
<pre><code>import numpy as np import cv2 cap = cv2.VideoCapture("rtsp://admin:admin123@10.0.51.110/h264/ch3/main/av_stream") while(True): # Capture frame-by-frame ret, frame = cap.read() # Processing Frame - # Running Computer Vision Algorithm # Display the resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() </code></pre> <p></p> <p> This code is using nearby 50% of CPU Usage. How can we reduce this CPU Usage ? <br> I have used time.sleep(0.05) but its delaying video feed processing, so won't work like realtime for me. </p>
<p>Use Mjpeg as the codec and lower the fps ( frames per second) for video streaming source.</p> <p>As mjpeg is less compressed as compared to H.264 , so bandwidth usage will be higher but your cpu usage will be less. </p>
python|opencv|cython
0
1,907,926
70,640,656
I have a file with n URLS, I what to download these to certain location and also have same dimensions to all images using python
<p>I have a .txt file with n urls like below:</p> <pre><code>url1 url2 url3 url4 url5 </code></pre> <ol> <li>I want to download these images to C:\Users\username\Pictures location</li> <li>Each image must be downscaled or upscaled to 256x256 dimension.</li> </ol>
<p>Here is a rough code with the things needed to achieve your goal:</p> <pre><code>import requests from PIL import Image with open('D:/urls.txt') as f: urls = f.read().split('\n') for url in urls: content = requests.get(url).content with open('D:/image_big_' + f'{urls.index(url)}' + '.jpg', 'wb') as f: f.write(content) with Image.open('D:/image_big_' + f'{urls.index(url)}' + '.jpg') as img: img.thumbnail(size=(256, 256)) img.save('D:/image_small_' + f'{urls.index(url)}' + '.jpg', bitmap_format=&quot;png&quot;) </code></pre>
python-3.x|python-requests
1
1,907,927
64,562,347
How to get the longest user name? (discord.py)
<p>I have a list of users ID, and I want to find the user with the longest name. But when I use <code>bot.get_user(id)</code> it returns None. I checked the ID, it is valid and does correspond to a user on the server. Code:</p> <pre><code> for score in scores: bad_chars = &quot;&lt;@!&gt;&quot; for letter in score: if letter in bad_letters: score = score.replace(letter, &quot;&quot;) print(score) print(bot.get_user(int(score.strip(&quot;&lt;@! &gt;&quot;)))) member_len = bot.get_user(int(score.strip(&quot;&lt;@ &gt;&quot;))) if member_len: print(len(member_len.name)) if len(member_len.name) &gt; score_len: score_len = len(member_len.name) print(score_len) </code></pre>
<p>In the new version of discord.py(1.5.x), there're some updates about <code>Intents</code>. Intents are similar to permissions, you have to define Intents to get channels, members and some events etc. You have to define it before defining the <code>client = discord.Bot(prefix='')</code>.</p> <pre class="lang-py prettyprint-override"><code>import discord intents = discord.Intents().all() client = discord.Bot(prefix='', intents=intents) </code></pre> <p>If you want to get more information about Intents, you can look at the <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents" rel="nofollow noreferrer">API References</a>.</p>
python|python-3.x|discord.py
3
1,907,928
70,707,697
How to use integrate.quad with an array
<p>I would like to use integrate.quad with an array but it returns me : <em>&quot;TypeError: only size-1 arrays can be converted to Python scalars&quot;</em></p> <p>I understand that the first argument which is required must be a scalar. But the argument I want to use comes from a function that depends on one parameter and that return an array and I can't get the problem fixed:</p> <p>Here is my script in Python:</p> <pre><code>from scipy import integrate as intg DfH_ref_jp = np.array([0,-393.52,-110.53,-74.87,-241.83,0]) *1000 n_jp = np.array([1.2,0.2,0.15,0.001,0.49,0.30]) Tref = 1298 Ta = 1310 def c_jp(T): t = T/1000 XC = np.array([1,t,t**2,t**3,t**(-2)]) Mah = M_ah(T) # a matrix defined before c = np.dot(Mah[:,:5],XC) return c H1_jp = n_jp * (DfH_ref_jp + intg.quad(c_jp,Tref,Ta)[0]) # this where it doesn't work / [0] because intg.quad returns an array and I want the first value </code></pre> <p>So I have tried with a function which returns a scalar:</p> <pre><code>def c_jp0(T): t = T/1000 XC = np.array([1,t,t**2,t**3,t**(-2)]) Mah = M_ah(T) c = np.dot(Mah[0,:5],XC) return c H1_jp = np.zeros(6, dtype=float) H1_jp[0] = n_jp[0] * (DfH_ref_jp[0] + intg.quad(c_jp0,Tref,Ta)[0]) </code></pre> <p>It works but I don't want to specify 6 functions : c_jp0 ... c_jp6. Does anyone has an idea how to do it ? Thanks</p>
<p>The <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow noreferrer">quad</a> method, is designed to integrate a scalar function only over one scalar variable.</p> <p>If your integral has only one integration variable, but depends on other parameters you can pass them via params in <code>quad(func, a, b, params)</code>.</p> <p>If you want to integrate over multiple variables you can use <a href="https://docs.scipy.org/doc/scipy/reference/reference/generated/scipy.integrate.nquad.html#scipy.integrate.nquad" rel="nofollow noreferrer">nquad</a>, in that case you have to give a limit for each of your variables.</p> <p>If the limits are constant you can pass them directly, if the limits depend on other integration variable you must pass the limits as a function of variables that are not integrated yet.</p> <p>e.g. For instance, to calculate the volume of a cube having one corner at the origin and other corner at the point (1,1,1).</p> <pre><code>from scipy import integrate as intg nquad(lambda x,y,z: 1.0, [(0,1), (0,1), (0,1)]) </code></pre> <p>Or the volume of square base pyramid with vertices at (0,0,1), (-1,-1,0) and (1,1,0). Where the limits of <code>x</code> and <code>y</code> depends on <code>z</code></p> <pre><code>from scipy import integrate as intg intg.nquad(lambda x,y,z: 1.0, [lambda y,z: (z-1,1-z), lambda z: (z-1,1-z), (0,1)]) </code></pre>
python|arrays|function|scipy|integrate
0
1,907,929
72,905,444
Calculate time difference between two dates in the same column in Pandas
<p>I have a column (DATE) with multiple data times and I want to find the difference in minutes from date to date and store it into a new column (time_interval).</p> <p>This is what I have tried:</p> <p>df['time_interval'] = (df['DATE'],axis=0 - df['DATE'],axis=1) * 24 * 60</p> <p><a href="https://i.stack.imgur.com/68hpM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/68hpM.png" alt="These are the data times I am working on" /></a></p> <p><a href="https://i.stack.imgur.com/qJDcQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qJDcQ.png" alt="That is the output I am looking for: " /></a></p>
<p>Depending on how you'd care to store the differences, either</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(data=['01-01-2006 00:53:00', '01-01-2006 01:53:00', '01-01-2006 02:53:00', '01-01-2006 03:53:00', '01-01-2006 04:53:00'], columns=['DATE']) df['DATE'] = pd.to_datetime(df['DATE']) df['time_interval'] = df['DATE'].diff().fillna(timedelta(0)).apply(lambda x: x.total_seconds() / 60) </code></pre> <p>to get</p> <pre><code> DATE time_interval 0 2006-01-01 00:53:00 0.0 1 2006-01-01 01:53:00 60.0 2 2006-01-01 02:53:00 60.0 3 2006-01-01 03:53:00 60.0 4 2006-01-01 04:53:00 60.0 </code></pre> <p>or alternatively</p> <pre class="lang-py prettyprint-override"><code>df['time_interval'] = df['DATE'].diff().shift(-1).fillna(timedelta(0)).apply(lambda x: x.total_seconds() / 60) </code></pre> <p>to get</p> <pre><code> DATE time_interval 0 2006-01-01 00:53:00 60.0 1 2006-01-01 01:53:00 60.0 2 2006-01-01 02:53:00 60.0 3 2006-01-01 03:53:00 60.0 4 2006-01-01 04:53:00 0.0 </code></pre>
python|pandas
1
1,907,930
73,221,295
Regex search to return a whole word if subword matches
<p>I have a string of words and I would like to return a word if a part of it matches. For e.g.</p> <pre><code>str = &quot;welcome to the sunshine hotel&quot; j= re.search(r'sun',str).group(0) print(j) </code></pre> <p>the output is : sun</p> <p>what changes do I make to get the output as 'sunshine' ? Thank you</p>
<p>This approach does not use regexes:</p> <pre><code>s = &quot;welcome to the sunshine hotel&quot; j = next((w for w in s.split() if &quot;sun&quot; in w), None) </code></pre>
python|regex|string
1
1,907,931
66,732,553
Meeting a pip requirement using an alternative module
<p>I'm trying to install a python module, 'pyAudioProcessing' (<a href="https://github.com/jsingh811/pyAudioProcessing" rel="nofollow noreferrer">https://github.com/jsingh811/pyAudioProcessing</a>) on my Linux Mint distribution, and one of the items in requirements.txt is causing issues: <code>python-magic-bin==0.4.14</code>. When I run <code>pip3 install -e pyAudioInstaller</code>, I get an error:</p> <pre><code>ERROR: Could not find a version that satisfies the requirement python-magic-bin==0.4.14 (from pyAudioProcessing==1.1.5) (from versions: none) ERROR: No matching distribution found for python-magic-bin==0.4.14 (from pyAudioProcessing==1.1.5) </code></pre> <p>The same error appears if I try to manually install the module using <code>pip3 install python-magic-bin</code>. The module installs without issues on my windows machine.</p> <p>pypi.org lets me download files for it manually, however only Windows and MacOS .whl files are available. I tried simply removing the requirement from the list, but that resulted in a large number of other errors to appear, so I assume the module is legitimately required.</p> <p>Thee is another module called <code>python-magic-debian-bin</code> that I can download. Is there a simple way to convince pyAudioInstaller to use this other module instead of the original? Like can I somehow rename <code>python-magic-debian-bin</code> to <code>python-magic-bin</code> and hope it works out?</p>
<p><a href="https://pypi.org/project/python-magic-bin/0.4.14/#files" rel="nofollow noreferrer"><code>python-magic-bin</code> 0.4.14</a> provides wheels for OSX, w32 and w64, but not for Linux. And there is no source code at PyPI.</p> <p>You need to install it from <a href="https://github.com/julian-r/python-magic" rel="nofollow noreferrer">github</a>:</p> <pre><code>pip install git+https://github.com/julian-r/python-magic.git </code></pre> <p>As for <code>pyAudioProcessing</code> I can see 2 ways to install it:</p> <ol> <li><p>Clone <a href="https://github.com/jsingh811/pyAudioProcessing" rel="nofollow noreferrer">the repository</a> and edit <code>requirements/requirements.txt</code>, replace <code>python-magic-bin==0.4.14</code> with <code>pip install git+https://github.com/julian-r/python-magic.git#egg=python-magic</code>;</p> </li> <li><p>Install <a href="https://github.com/jsingh811/pyAudioProcessing/blob/master/requirements/requirements.txt" rel="nofollow noreferrer">requirements</a> manually and then install <code>pyAudioProcessing</code> <a href="https://pip.pypa.io/en/stable/reference/pip_install/#cmdoption-no-deps" rel="nofollow noreferrer">without dependencies</a>:</p> <p><code>pip install --no-deps pyAudioProcessing</code></p> </li> </ol> <p>or</p> <pre><code>pip install --no-deps git+https://github.com/jsingh811/pyAudioProcessing.git </code></pre>
python|module|pip|python-3.7|requirements.txt
3
1,907,932
66,454,523
Solving linear equation system with sympy takes forever
<p>I have a linear equation system consisting of 3 equations as a result of a matrix multiplication. The equation system has 3 unknowns and 24 input variables. In theory, it should be solvable, however, <code>linsolve</code> takes forever (roughly a day so far) to calculate a solution.</p> <p>Here is my sympy input:</p> <pre class="lang-py prettyprint-override"><code>from sympy import Matrix, symbols, pprint, Eq, linsolve from sympy.utilities.lambdify import lambdastr n2_x, n2_y, n2_z, o2_x, o2_y, o2_z, a2_x, a2_y, a2_z, p2_x, p2_y, p2_z = symbols('n2_x n2_y n2_z o2_x o2_y o2_z a2_x a2_y a2_z p2_x p2_y p2_z', real=True) T_2 = Matrix([[n2_x, o2_x, a2_x, p2_x], [n2_y, o2_y, a2_y, p2_y], [n2_z, o2_z, a2_z, p2_z], [0,0,0,1]]) n3_x, n3_y, n3_z, o3_x, o3_y, o3_z, a3_x, a3_y, a3_z, p3_x, p3_y, p3_z = symbols('n3_x n3_y n3_z o3_x o3_y o3_z a3_x a3_y a3_z p3_x p3_y p3_z', real=True) T_3 = Matrix([[n3_x, o3_x, a3_x, p3_x], [n3_y, o3_y, a3_y, p3_y], [n3_z, o3_z, a3_z, p3_z], [0,0,0,1]]) p_x, p_y, p_z = symbols('p_x p_y p_z', real=True) R_p = Matrix([[0, 0, 0, p_x], [0, 0, 0, p_y], [0, 0, 0, p_z], [0,0,0,1]]) eq1 = (Matrix.eye(4)-T_2*T_3**-1)*R_p eq2 = Eq(eq1[0, 3], 0) eq3 = Eq(eq1[1, 3], 0) eq4 = Eq(eq1[2, 3], 0) res = linsolve([eq1[0, 3], eq1[1, 3], eq1[2, 3]], (p_x, p_y, p_z)) pprint(res) print(res) </code></pre> <p>How can I speed up solving the problem, or what am I doing wrong?</p> <p>Thanks in advance.</p> <p>EDIT: As background information: <code>T_2</code> and <code>T_3</code> are transformation matrices, <code>R_p</code> is also a transformation matrix, but with (known) zero rotation. We are looking for the translation only.</p>
<p>I do concur with JohanC that it might be worth considering a different way of approaching this since the expressions you are asking for are enormous. If you know anything more specific about any relationship between the symbols then it can be better to use that information up front.</p> <p>Looking at the answer (below) there seems to be a clear repetitive structure to it that would suggest that there could be a more intelligent way of computing that result rather than just slinging the whole system of arbitrary symbols into sympy. I expect that finding an expression for the <code>i,j</code> element of your matrix would lead to a shorter result involving indices and summations.</p> <p>That being said there have been a lot of improvements in the performance of <code>linsolve</code> in sympy 1.7 and since (i.e. the current master branch that will at some point become 1.8). I expect further improvements after 1.8 as well.</p> <p>With the (almost-)current sympy master branch I tried this and got a solution in around 1 minute:</p> <pre><code>In [33]: %time res = linsolve([eq1[0, 3], eq1[1, 3], eq1[2, 3]], (p_x, p_y, p_z)) CPU times: user 42.7 s, sys: 1.23 s, total: 43.9 s Wall time: 51.2 s </code></pre> <p>Note that the first time I tried it took 1 minute. When I tried again after quitting Python and updating to the absolute latest sympy master it took a lot longer (not sure how long). I don't think anything should have changed but it's possible that the time taken is non-deterministic somehow.</p> <p>The answer I found is:</p> <pre><code>In [41]: str(res) Out[41]: 'FiniteSet(((a2_x*n2_y*o2_z*p3_x - a2_x*n2_y*o3_x*p2_z + a2_x*n2_y*o3_x*p3_z - a2_x*n2_y*o3_z*p3_x - a2_x*n2_z*o2_y*p3_x + a2_x*n2_z*o3_x*p2_y - a2_x*n2_z*o3_x*p3_y + a2_x*n2_z*o3_y*p3_x + a2_x*n3_x*o2_y*p2_z - a2_x*n3_x*o2_y*p3_z - a2_x*n3_x*o2_z*p2_y + a2_x*n3_x*o2_z*p3_y - a2_x*n3_x*o3_y*p2_z + a2_x*n3_x*o3_y*p3_z + a2_x*n3_x*o3_z*p2_y - a2_x*n3_x*o3_z*p3_y - a2_x*n3_y*o2_z*p3_x + a2_x*n3_y*o3_x*p2_z - a2_x*n3_y*o3_x*p3_z + a2_x*n3_y*o3_z*p3_x + a2_x*n3_z*o2_y*p3_x - a2_x*n3_z*o3_x*p2_y + a2_x*n3_z*o3_x*p3_y - a2_x*n3_z*o3_y*p3_x - a2_y*n2_x*o2_z*p3_x + a2_y*n2_x*o3_x*p2_z - a2_y*n2_x*o3_x*p3_z + a2_y*n2_x*o3_z*p3_x + a2_y*n2_z*o2_x*p3_x - a2_y*n2_z*o3_x*p2_x - a2_y*n3_x*o2_x*p2_z + a2_y*n3_x*o2_x*p3_z + a2_y*n3_x*o2_z*p2_x - a2_y*n3_x*o3_z*p2_x - a2_y*n3_z*o2_x*p3_x + a2_y*n3_z*o3_x*p2_x + a2_z*n2_x*o2_y*p3_x - a2_z*n2_x*o3_x*p2_y + a2_z*n2_x*o3_x*p3_y - a2_z*n2_x*o3_y*p3_x - a2_z*n2_y*o2_x*p3_x + a2_z*n2_y*o3_x*p2_x + a2_z*n3_x*o2_x*p2_y - a2_z*n3_x*o2_x*p3_y - a2_z*n3_x*o2_y*p2_x + a2_z*n3_x*o3_y*p2_x + a2_z*n3_y*o2_x*p3_x - a2_z*n3_y*o3_x*p2_x - a3_x*n2_x*o2_y*p2_z + a3_x*n2_x*o2_y*p3_z + a3_x*n2_x*o2_z*p2_y - a3_x*n2_x*o2_z*p3_y + a3_x*n2_x*o3_y*p2_z - a3_x*n2_x*o3_y*p3_z - a3_x*n2_x*o3_z*p2_y + a3_x*n2_x*o3_z*p3_y + a3_x*n2_y*o2_x*p2_z - a3_x*n2_y*o2_x*p3_z - a3_x*n2_y*o2_z*p2_x + a3_x*n2_y*o3_z*p2_x - a3_x*n2_z*o2_x*p2_y + a3_x*n2_z*o2_x*p3_y + a3_x*n2_z*o2_y*p2_x - a3_x*n2_z*o3_y*p2_x - a3_x*n3_y*o2_x*p2_z + a3_x*n3_y*o2_x*p3_z + a3_x*n3_y*o2_z*p2_x - a3_x*n3_y*o3_z*p2_x + a3_x*n3_z*o2_x*p2_y - a3_x*n3_z*o2_x*p3_y - a3_x*n3_z*o2_y*p2_x + a3_x*n3_z*o3_y*p2_x + a3_y*n2_x*o2_z*p3_x - a3_y*n2_x*o3_x*p2_z + a3_y*n2_x*o3_x*p3_z - a3_y*n2_x*o3_z*p3_x - a3_y*n2_z*o2_x*p3_x + a3_y*n2_z*o3_x*p2_x + a3_y*n3_x*o2_x*p2_z - a3_y*n3_x*o2_x*p3_z - a3_y*n3_x*o2_z*p2_x + a3_y*n3_x*o3_z*p2_x + a3_y*n3_z*o2_x*p3_x - a3_y*n3_z*o3_x*p2_x - a3_z*n2_x*o2_y*p3_x + a3_z*n2_x*o3_x*p2_y - a3_z*n2_x*o3_x*p3_y + a3_z*n2_x*o3_y*p3_x + a3_z*n2_y*o2_x*p3_x - a3_z*n2_y*o3_x*p2_x - a3_z*n3_x*o2_x*p2_y + a3_z*n3_x*o2_x*p3_y + a3_z*n3_x*o2_y*p2_x - a3_z*n3_x*o3_y*p2_x - a3_z*n3_y*o2_x*p3_x + a3_z*n3_y*o3_x*p2_x)/(a2_x*n2_y*o2_z - a2_x*n2_y*o3_z - a2_x*n2_z*o2_y + a2_x*n2_z*o3_y - a2_x*n3_y*o2_z + a2_x*n3_y*o3_z + a2_x*n3_z*o2_y - a2_x*n3_z*o3_y - a2_y*n2_x*o2_z + a2_y*n2_x*o3_z + a2_y*n2_z*o2_x - a2_y*n2_z*o3_x + a2_y*n3_x*o2_z - a2_y*n3_x*o3_z - a2_y*n3_z*o2_x + a2_y*n3_z*o3_x + a2_z*n2_x*o2_y - a2_z*n2_x*o3_y - a2_z*n2_y*o2_x + a2_z*n2_y*o3_x - a2_z*n3_x*o2_y + a2_z*n3_x*o3_y + a2_z*n3_y*o2_x - a2_z*n3_y*o3_x - a3_x*n2_y*o2_z + a3_x*n2_y*o3_z + a3_x*n2_z*o2_y - a3_x*n2_z*o3_y + a3_x*n3_y*o2_z - a3_x*n3_y*o3_z - a3_x*n3_z*o2_y + a3_x*n3_z*o3_y + a3_y*n2_x*o2_z - a3_y*n2_x*o3_z - a3_y*n2_z*o2_x + a3_y*n2_z*o3_x - a3_y*n3_x*o2_z + a3_y*n3_x*o3_z + a3_y*n3_z*o2_x - a3_y*n3_z*o3_x - a3_z*n2_x*o2_y + a3_z*n2_x*o3_y + a3_z*n2_y*o2_x - a3_z*n2_y*o3_x + a3_z*n3_x*o2_y - a3_z*n3_x*o3_y - a3_z*n3_y*o2_x + a3_z*n3_y*o3_x), (a2_x*n2_y*o2_z*p3_y - a2_x*n2_y*o3_y*p2_z + a2_x*n2_y*o3_y*p3_z - a2_x*n2_y*o3_z*p3_y - a2_x*n2_z*o2_y*p3_y + a2_x*n2_z*o3_y*p2_y + a2_x*n3_y*o2_y*p2_z - a2_x*n3_y*o2_y*p3_z - a2_x*n3_y*o2_z*p2_y + a2_x*n3_y*o3_z*p2_y + a2_x*n3_z*o2_y*p3_y - a2_x*n3_z*o3_y*p2_y - a2_y*n2_x*o2_z*p3_y + a2_y*n2_x*o3_y*p2_z - a2_y*n2_x*o3_y*p3_z + a2_y*n2_x*o3_z*p3_y + a2_y*n2_z*o2_x*p3_y - a2_y*n2_z*o3_x*p3_y - a2_y*n2_z*o3_y*p2_x + a2_y*n2_z*o3_y*p3_x + a2_y*n3_x*o2_z*p3_y - a2_y*n3_x*o3_y*p2_z + a2_y*n3_x*o3_y*p3_z - a2_y*n3_x*o3_z*p3_y - a2_y*n3_y*o2_x*p2_z + a2_y*n3_y*o2_x*p3_z + a2_y*n3_y*o2_z*p2_x - a2_y*n3_y*o2_z*p3_x + a2_y*n3_y*o3_x*p2_z - a2_y*n3_y*o3_x*p3_z - a2_y*n3_y*o3_z*p2_x + a2_y*n3_y*o3_z*p3_x - a2_y*n3_z*o2_x*p3_y + a2_y*n3_z*o3_x*p3_y + a2_y*n3_z*o3_y*p2_x - a2_y*n3_z*o3_y*p3_x + a2_z*n2_x*o2_y*p3_y - a2_z*n2_x*o3_y*p2_y - a2_z*n2_y*o2_x*p3_y + a2_z*n2_y*o3_x*p3_y + a2_z*n2_y*o3_y*p2_x - a2_z*n2_y*o3_y*p3_x - a2_z*n3_x*o2_y*p3_y + a2_z*n3_x*o3_y*p2_y + a2_z*n3_y*o2_x*p2_y - a2_z*n3_y*o2_y*p2_x + a2_z*n3_y*o2_y*p3_x - a2_z*n3_y*o3_x*p2_y - a3_x*n2_y*o2_z*p3_y + a3_x*n2_y*o3_y*p2_z - a3_x*n2_y*o3_y*p3_z + a3_x*n2_y*o3_z*p3_y + a3_x*n2_z*o2_y*p3_y - a3_x*n2_z*o3_y*p2_y - a3_x*n3_y*o2_y*p2_z + a3_x*n3_y*o2_y*p3_z + a3_x*n3_y*o2_z*p2_y - a3_x*n3_y*o3_z*p2_y - a3_x*n3_z*o2_y*p3_y + a3_x*n3_z*o3_y*p2_y - a3_y*n2_x*o2_y*p2_z + a3_y*n2_x*o2_y*p3_z + a3_y*n2_x*o2_z*p2_y - a3_y*n2_x*o3_z*p2_y + a3_y*n2_y*o2_x*p2_z - a3_y*n2_y*o2_x*p3_z - a3_y*n2_y*o2_z*p2_x + a3_y*n2_y*o2_z*p3_x - a3_y*n2_y*o3_x*p2_z + a3_y*n2_y*o3_x*p3_z + a3_y*n2_y*o3_z*p2_x - a3_y*n2_y*o3_z*p3_x - a3_y*n2_z*o2_x*p2_y + a3_y*n2_z*o2_y*p2_x - a3_y*n2_z*o2_y*p3_x + a3_y*n2_z*o3_x*p2_y + a3_y*n3_x*o2_y*p2_z - a3_y*n3_x*o2_y*p3_z - a3_y*n3_x*o2_z*p2_y + a3_y*n3_x*o3_z*p2_y + a3_y*n3_z*o2_x*p2_y - a3_y*n3_z*o2_y*p2_x + a3_y*n3_z*o2_y*p3_x - a3_y*n3_z*o3_x*p2_y - a3_z*n2_x*o2_y*p3_y + a3_z*n2_x*o3_y*p2_y + a3_z*n2_y*o2_x*p3_y - a3_z*n2_y*o3_x*p3_y - a3_z*n2_y*o3_y*p2_x + a3_z*n2_y*o3_y*p3_x + a3_z*n3_x*o2_y*p3_y - a3_z*n3_x*o3_y*p2_y - a3_z*n3_y*o2_x*p2_y + a3_z*n3_y*o2_y*p2_x - a3_z*n3_y*o2_y*p3_x + a3_z*n3_y*o3_x*p2_y)/(a2_x*n2_y*o2_z - a2_x*n2_y*o3_z - a2_x*n2_z*o2_y + a2_x*n2_z*o3_y - a2_x*n3_y*o2_z + a2_x*n3_y*o3_z + a2_x*n3_z*o2_y - a2_x*n3_z*o3_y - a2_y*n2_x*o2_z + a2_y*n2_x*o3_z + a2_y*n2_z*o2_x - a2_y*n2_z*o3_x + a2_y*n3_x*o2_z - a2_y*n3_x*o3_z - a2_y*n3_z*o2_x + a2_y*n3_z*o3_x + a2_z*n2_x*o2_y - a2_z*n2_x*o3_y - a2_z*n2_y*o2_x + a2_z*n2_y*o3_x - a2_z*n3_x*o2_y + a2_z*n3_x*o3_y + a2_z*n3_y*o2_x - a2_z*n3_y*o3_x - a3_x*n2_y*o2_z + a3_x*n2_y*o3_z + a3_x*n2_z*o2_y - a3_x*n2_z*o3_y + a3_x*n3_y*o2_z - a3_x*n3_y*o3_z - a3_x*n3_z*o2_y + a3_x*n3_z*o3_y + a3_y*n2_x*o2_z - a3_y*n2_x*o3_z - a3_y*n2_z*o2_x + a3_y*n2_z*o3_x - a3_y*n3_x*o2_z + a3_y*n3_x*o3_z + a3_y*n3_z*o2_x - a3_y*n3_z*o3_x - a3_z*n2_x*o2_y + a3_z*n2_x*o3_y + a3_z*n2_y*o2_x - a3_z*n2_y*o3_x + a3_z*n3_x*o2_y - a3_z*n3_x*o3_y - a3_z*n3_y*o2_x + a3_z*n3_y*o3_x), (a2_x*n2_y*o2_z*p3_z - a2_x*n2_y*o3_z*p2_z - a2_x*n2_z*o2_y*p3_z + a2_x*n2_z*o3_y*p3_z + a2_x*n2_z*o3_z*p2_y - a2_x*n2_z*o3_z*p3_y - a2_x*n3_y*o2_z*p3_z + a2_x*n3_y*o3_z*p2_z + a2_x*n3_z*o2_y*p2_z - a2_x*n3_z*o2_z*p2_y + a2_x*n3_z*o2_z*p3_y - a2_x*n3_z*o3_y*p2_z - a2_y*n2_x*o2_z*p3_z + a2_y*n2_x*o3_z*p2_z + a2_y*n2_z*o2_x*p3_z - a2_y*n2_z*o3_x*p3_z - a2_y*n2_z*o3_z*p2_x + a2_y*n2_z*o3_z*p3_x + a2_y*n3_x*o2_z*p3_z - a2_y*n3_x*o3_z*p2_z - a2_y*n3_z*o2_x*p2_z + a2_y*n3_z*o2_z*p2_x - a2_y*n3_z*o2_z*p3_x + a2_y*n3_z*o3_x*p2_z + a2_z*n2_x*o2_y*p3_z - a2_z*n2_x*o3_y*p3_z - a2_z*n2_x*o3_z*p2_y + a2_z*n2_x*o3_z*p3_y - a2_z*n2_y*o2_x*p3_z + a2_z*n2_y*o3_x*p3_z + a2_z*n2_y*o3_z*p2_x - a2_z*n2_y*o3_z*p3_x - a2_z*n3_x*o2_y*p3_z + a2_z*n3_x*o3_y*p3_z + a2_z*n3_x*o3_z*p2_y - a2_z*n3_x*o3_z*p3_y + a2_z*n3_y*o2_x*p3_z - a2_z*n3_y*o3_x*p3_z - a2_z*n3_y*o3_z*p2_x + a2_z*n3_y*o3_z*p3_x + a2_z*n3_z*o2_x*p2_y - a2_z*n3_z*o2_x*p3_y - a2_z*n3_z*o2_y*p2_x + a2_z*n3_z*o2_y*p3_x - a2_z*n3_z*o3_x*p2_y + a2_z*n3_z*o3_x*p3_y + a2_z*n3_z*o3_y*p2_x - a2_z*n3_z*o3_y*p3_x - a3_x*n2_y*o2_z*p3_z + a3_x*n2_y*o3_z*p2_z + a3_x*n2_z*o2_y*p3_z - a3_x*n2_z*o3_y*p3_z - a3_x*n2_z*o3_z*p2_y + a3_x*n2_z*o3_z*p3_y + a3_x*n3_y*o2_z*p3_z - a3_x*n3_y*o3_z*p2_z - a3_x*n3_z*o2_y*p2_z + a3_x*n3_z*o2_z*p2_y - a3_x*n3_z*o2_z*p3_y + a3_x*n3_z*o3_y*p2_z + a3_y*n2_x*o2_z*p3_z - a3_y*n2_x*o3_z*p2_z - a3_y*n2_z*o2_x*p3_z + a3_y*n2_z*o3_x*p3_z + a3_y*n2_z*o3_z*p2_x - a3_y*n2_z*o3_z*p3_x - a3_y*n3_x*o2_z*p3_z + a3_y*n3_x*o3_z*p2_z + a3_y*n3_z*o2_x*p2_z - a3_y*n3_z*o2_z*p2_x + a3_y*n3_z*o2_z*p3_x - a3_y*n3_z*o3_x*p2_z - a3_z*n2_x*o2_y*p2_z + a3_z*n2_x*o2_z*p2_y - a3_z*n2_x*o2_z*p3_y + a3_z*n2_x*o3_y*p2_z + a3_z*n2_y*o2_x*p2_z - a3_z*n2_y*o2_z*p2_x + a3_z*n2_y*o2_z*p3_x - a3_z*n2_y*o3_x*p2_z - a3_z*n2_z*o2_x*p2_y + a3_z*n2_z*o2_x*p3_y + a3_z*n2_z*o2_y*p2_x - a3_z*n2_z*o2_y*p3_x + a3_z*n2_z*o3_x*p2_y - a3_z*n2_z*o3_x*p3_y - a3_z*n2_z*o3_y*p2_x + a3_z*n2_z*o3_y*p3_x + a3_z*n3_x*o2_y*p2_z - a3_z*n3_x*o2_z*p2_y + a3_z*n3_x*o2_z*p3_y - a3_z*n3_x*o3_y*p2_z - a3_z*n3_y*o2_x*p2_z + a3_z*n3_y*o2_z*p2_x - a3_z*n3_y*o2_z*p3_x + a3_z*n3_y*o3_x*p2_z)/(a2_x*n2_y*o2_z - a2_x*n2_y*o3_z - a2_x*n2_z*o2_y + a2_x*n2_z*o3_y - a2_x*n3_y*o2_z + a2_x*n3_y*o3_z + a2_x*n3_z*o2_y - a2_x*n3_z*o3_y - a2_y*n2_x*o2_z + a2_y*n2_x*o3_z + a2_y*n2_z*o2_x - a2_y*n2_z*o3_x + a2_y*n3_x*o2_z - a2_y*n3_x*o3_z - a2_y*n3_z*o2_x + a2_y*n3_z*o3_x + a2_z*n2_x*o2_y - a2_z*n2_x*o3_y - a2_z*n2_y*o2_x + a2_z*n2_y*o3_x - a2_z*n3_x*o2_y + a2_z*n3_x*o3_y + a2_z*n3_y*o2_x - a2_z*n3_y*o3_x - a3_x*n2_y*o2_z + a3_x*n2_y*o3_z + a3_x*n2_z*o2_y - a3_x*n2_z*o3_y + a3_x*n3_y*o2_z - a3_x*n3_y*o3_z - a3_x*n3_z*o2_y + a3_x*n3_z*o3_y + a3_y*n2_x*o2_z - a3_y*n2_x*o3_z - a3_y*n2_z*o2_x + a3_y*n2_z*o3_x - a3_y*n3_x*o2_z + a3_y*n3_x*o3_z + a3_y*n3_z*o2_x - a3_y*n3_z*o3_x - a3_z*n2_x*o2_y + a3_z*n2_x*o3_y + a3_z*n2_y*o2_x - a3_z*n2_y*o3_x + a3_z*n3_x*o2_y - a3_z*n3_x*o3_y - a3_z*n3_y*o2_x + a3_z*n3_y*o3_x)))' </code></pre> <p>Expanded that looks like:</p> <pre><code>FiniteSet(((a2_x*n2_y*o2_z*p3_x - a2_x*n2_y*o3_x*p2_z + a2_x*n2_y*o3_x*p3_z - a2_x*n2_y*o3_z*p3_x - a2_x*n2_z*o2_y*p3_x + a2_x*n2_z*o3_x*p2_y - a2_x*n2_z*o3_x*p3_y + a2_x*n2_z*o3_y*p3_x + a2_x*n3_x*o2_y*p2_z - a2_x*n3_x*o2_y*p3_z - a2_x*n3_x*o2_z*p2_y + a2_x*n3_x*o2_z*p3_y - a2_x*n3_x*o3_y*p2_z + a2_x*n3_x*o3_y*p3_z + a2_x*n3_x*o3_z*p2_y - a2_x*n3_x*o3_z*p3_y - a2_x*n3_y*o2_z*p3_x + a2_x*n3_y*o3_x*p2_z - a2_x*n3_y*o3_x*p3_z + a2_x*n3_y*o3_z*p3_x + a2_x*n3_z*o2_y*p3_x - a2_x*n3_z*o3_x*p2_y + a2_x*n3_z*o3_x*p3_y - a2_x*n3_z*o3_y*p3_x - a2_y*n2_x*o2_z*p3_x + a2_y*n2_x*o3_x*p2_z - a2_y*n2_x*o3_x*p3_z + a2_y*n2_x*o3_z*p3_x + a2_y*n2_z*o2_x*p3_x - a2_y*n2_z*o3_x*p2_x - a2_y*n3_x*o2_x*p2_z + a2_y*n3_x*o2_x*p3_z + a2_y*n3_x*o2_z*p2_x - a2_y*n3_x*o3_z*p2_x - a2_y*n3_z*o2_x*p3_x + a2_y*n3_z*o3_x*p2_x + a2_z*n2_x*o2_y*p3_x - a2_z*n2_x*o3_x*p2_y + a2_z*n2_x*o3_x*p3_y - a2_z*n2_x*o3_y*p3_x - a2_z*n2_y*o2_x*p3_x + a2_z*n2_y*o3_x*p2_x + a2_z*n3_x*o2_x*p2_y - a2_z*n3_x*o2_x*p3_y - a2_z*n3_x*o2_y*p2_x + a2_z*n3_x*o3_y*p2_x + a2_z*n3_y*o2_x*p3_x - a2_z*n3_y*o3_x*p2_x - a3_x*n2_x*o2_y*p2_z + a3_x*n2_x*o2_y*p3_z + a3_x*n2_x*o2_z*p2_y - a3_x*n2_x*o2_z*p3_y + a3_x*n2_x*o3_y*p2_z - a3_x*n2_x*o3_y*p3_z - a3_x*n2_x*o3_z*p2_y + a3_x*n2_x*o3_z*p3_y + a3_x*n2_y*o2_x*p2_z - a3_x*n2_y*o2_x*p3_z - a3_x*n2_y*o2_z*p2_x + a3_x*n2_y*o3_z*p2_x - a3_x*n2_z*o2_x*p2_y + a3_x*n2_z*o2_x*p3_y + a3_x*n2_z*o2_y*p2_x - a3_x*n2_z*o3_y*p2_x - a3_x*n3_y*o2_x*p2_z + a3_x*n3_y*o2_x*p3_z + a3_x*n3_y*o2_z*p2_x - a3_x*n3_y*o3_z*p2_x + a3_x*n3_z*o2_x*p2_y - a3_x*n3_z*o2_x*p3_y - a3_x*n3_z*o2_y*p2_x + a3_x*n3_z*o3_y*p2_x + a3_y*n2_x*o2_z*p3_x - a3_y*n2_x*o3_x*p2_z + a3_y*n2_x*o3_x*p3_z - a3_y*n2_x*o3_z*p3_x - a3_y*n2_z*o2_x*p3_x + a3_y*n2_z*o3_x*p2_x + a3_y*n3_x*o2_x*p2_z - a3_y*n3_x*o2_x*p3_z - a3_y*n3_x*o2_z*p2_x + a3_y*n3_x*o3_z*p2_x + a3_y*n3_z*o2_x*p3_x - a3_y*n3_z*o3_x*p2_x - a3_z*n2_x*o2_y*p3_x + a3_z*n2_x*o3_x*p2_y - a3_z*n2_x*o3_x*p3_y + a3_z*n2_x*o3_y*p3_x + a3_z*n2_y*o2_x*p3_x - a3_z*n2_y*o3_x*p2_x - a3_z*n3_x*o2_x*p2_y + a3_z*n3_x*o2_x*p3_y + a3_z*n3_x*o2_y*p2_x - a3_z*n3_x*o3_y*p2_x - a3_z*n3_y*o2_x*p3_x + a3_z*n3_y*o3_x*p2_x)/(a2_x*n2_y*o2_z - a2_x*n2_y*o3_z - a2_x*n2_z*o2_y + a2_x*n2_z*o3_y - a2_x*n3_y*o2_z + a2_x*n3_y*o3_z + a2_x*n3_z*o2_y - a2_x*n3_z*o3_y - a2_y*n2_x*o2_z + a2_y*n2_x*o3_z + a2_y*n2_z*o2_x - a2_y*n2_z*o3_x + a2_y*n3_x*o2_z - a2_y*n3_x*o3_z - a2_y*n3_z*o2_x + a2_y*n3_z*o3_x + a2_z*n2_x*o2_y - a2_z*n2_x*o3_y - a2_z*n2_y*o2_x + a2_z*n2_y*o3_x - a2_z*n3_x*o2_y + a2_z*n3_x*o3_y + a2_z*n3_y*o2_x - a2_z*n3_y*o3_x - a3_x*n2_y*o2_z + a3_x*n2_y*o3_z + a3_x*n2_z*o2_y - a3_x*n2_z*o3_y + a3_x*n3_y*o2_z - a3_x*n3_y*o3_z - a3_x*n3_z*o2_y + a3_x*n3_z*o3_y + a3_y*n2_x*o2_z - a3_y*n2_x*o3_z - a3_y*n2_z*o2_x + a3_y*n2_z*o3_x - a3_y*n3_x*o2_z + a3_y*n3_x*o3_z + a3_y*n3_z*o2_x - a3_y*n3_z*o3_x - a3_z*n2_x*o2_y + a3_z*n2_x*o3_y + a3_z*n2_y*o2_x - a3_z*n2_y*o3_x + a3_z*n3_x*o2_y - a3_z*n3_x*o3_y - a3_z*n3_y*o2_x + a3_z*n3_y*o3_x), (a2_x*n2_y*o2_z*p3_y - a2_x*n2_y*o3_y*p2_z + a2_x*n2_y*o3_y*p3_z - a2_x*n2_y*o3_z*p3_y - a2_x*n2_z*o2_y*p3_y + a2_x*n2_z*o3_y*p2_y + a2_x*n3_y*o2_y*p2_z - a2_x*n3_y*o2_y*p3_z - a2_x*n3_y*o2_z*p2_y + a2_x*n3_y*o3_z*p2_y + a2_x*n3_z*o2_y*p3_y - a2_x*n3_z*o3_y*p2_y - a2_y*n2_x*o2_z*p3_y + a2_y*n2_x*o3_y*p2_z - a2_y*n2_x*o3_y*p3_z + a2_y*n2_x*o3_z*p3_y + a2_y*n2_z*o2_x*p3_y - a2_y*n2_z*o3_x*p3_y - a2_y*n2_z*o3_y*p2_x + a2_y*n2_z*o3_y*p3_x + a2_y*n3_x*o2_z*p3_y - a2_y*n3_x*o3_y*p2_z + a2_y*n3_x*o3_y*p3_z - a2_y*n3_x*o3_z*p3_y - a2_y*n3_y*o2_x*p2_z + a2_y*n3_y*o2_x*p3_z + a2_y*n3_y*o2_z*p2_x - a2_y*n3_y*o2_z*p3_x + a2_y*n3_y*o3_x*p2_z - a2_y*n3_y*o3_x*p3_z - a2_y*n3_y*o3_z*p2_x + a2_y*n3_y*o3_z*p3_x - a2_y*n3_z*o2_x*p3_y + a2_y*n3_z*o3_x*p3_y + a2_y*n3_z*o3_y*p2_x - a2_y*n3_z*o3_y*p3_x + a2_z*n2_x*o2_y*p3_y - a2_z*n2_x*o3_y*p2_y - a2_z*n2_y*o2_x*p3_y + a2_z*n2_y*o3_x*p3_y + a2_z*n2_y*o3_y*p2_x - a2_z*n2_y*o3_y*p3_x - a2_z*n3_x*o2_y*p3_y + a2_z*n3_x*o3_y*p2_y + a2_z*n3_y*o2_x*p2_y - a2_z*n3_y*o2_y*p2_x + a2_z*n3_y*o2_y*p3_x - a2_z*n3_y*o3_x*p2_y - a3_x*n2_y*o2_z*p3_y + a3_x*n2_y*o3_y*p2_z - a3_x*n2_y*o3_y*p3_z + a3_x*n2_y*o3_z*p3_y + a3_x*n2_z*o2_y*p3_y - a3_x*n2_z*o3_y*p2_y - a3_x*n3_y*o2_y*p2_z + a3_x*n3_y*o2_y*p3_z + a3_x*n3_y*o2_z*p2_y - a3_x*n3_y*o3_z*p2_y - a3_x*n3_z*o2_y*p3_y + a3_x*n3_z*o3_y*p2_y - a3_y*n2_x*o2_y*p2_z + a3_y*n2_x*o2_y*p3_z + a3_y*n2_x*o2_z*p2_y - a3_y*n2_x*o3_z*p2_y + a3_y*n2_y*o2_x*p2_z - a3_y*n2_y*o2_x*p3_z - a3_y*n2_y*o2_z*p2_x + a3_y*n2_y*o2_z*p3_x - a3_y*n2_y*o3_x*p2_z + a3_y*n2_y*o3_x*p3_z + a3_y*n2_y*o3_z*p2_x - a3_y*n2_y*o3_z*p3_x - a3_y*n2_z*o2_x*p2_y + a3_y*n2_z*o2_y*p2_x - a3_y*n2_z*o2_y*p3_x + a3_y*n2_z*o3_x*p2_y + a3_y*n3_x*o2_y*p2_z - a3_y*n3_x*o2_y*p3_z - a3_y*n3_x*o2_z*p2_y + a3_y*n3_x*o3_z*p2_y + a3_y*n3_z*o2_x*p2_y - a3_y*n3_z*o2_y*p2_x + a3_y*n3_z*o2_y*p3_x - a3_y*n3_z*o3_x*p2_y - a3_z*n2_x*o2_y*p3_y + a3_z*n2_x*o3_y*p2_y + a3_z*n2_y*o2_x*p3_y - a3_z*n2_y*o3_x*p3_y - a3_z*n2_y*o3_y*p2_x + a3_z*n2_y*o3_y*p3_x + a3_z*n3_x*o2_y*p3_y - a3_z*n3_x*o3_y*p2_y - a3_z*n3_y*o2_x*p2_y + a3_z*n3_y*o2_y*p2_x - a3_z*n3_y*o2_y*p3_x + a3_z*n3_y*o3_x*p2_y)/(a2_x*n2_y*o2_z - a2_x*n2_y*o3_z - a2_x*n2_z*o2_y + a2_x*n2_z*o3_y - a2_x*n3_y*o2_z + a2_x*n3_y*o3_z + a2_x*n3_z*o2_y - a2_x*n3_z*o3_y - a2_y*n2_x*o2_z + a2_y*n2_x*o3_z + a2_y*n2_z*o2_x - a2_y*n2_z*o3_x + a2_y*n3_x*o2_z - a2_y*n3_x*o3_z - a2_y*n3_z*o2_x + a2_y*n3_z*o3_x + a2_z*n2_x*o2_y - a2_z*n2_x*o3_y - a2_z*n2_y*o2_x + a2_z*n2_y*o3_x - a2_z*n3_x*o2_y + a2_z*n3_x*o3_y + a2_z*n3_y*o2_x - a2_z*n3_y*o3_x - a3_x*n2_y*o2_z + a3_x*n2_y*o3_z + a3_x*n2_z*o2_y - a3_x*n2_z*o3_y + a3_x*n3_y*o2_z - a3_x*n3_y*o3_z - a3_x*n3_z*o2_y + a3_x*n3_z*o3_y + a3_y*n2_x*o2_z - a3_y*n2_x*o3_z - a3_y*n2_z*o2_x + a3_y*n2_z*o3_x - a3_y*n3_x*o2_z + a3_y*n3_x*o3_z + a3_y*n3_z*o2_x - a3_y*n3_z*o3_x - a3_z*n2_x*o2_y + a3_z*n2_x*o3_y + a3_z*n2_y*o2_x - a3_z*n2_y*o3_x + a3_z*n3_x*o2_y - a3_z*n3_x*o3_y - a3_z*n3_y*o2_x + a3_z*n3_y*o3_x), (a2_x*n2_y*o2_z*p3_z - a2_x*n2_y*o3_z*p2_z - a2_x*n2_z*o2_y*p3_z + a2_x*n2_z*o3_y*p3_z + a2_x*n2_z*o3_z*p2_y - a2_x*n2_z*o3_z*p3_y - a2_x*n3_y*o2_z*p3_z + a2_x*n3_y*o3_z*p2_z + a2_x*n3_z*o2_y*p2_z - a2_x*n3_z*o2_z*p2_y + a2_x*n3_z*o2_z*p3_y - a2_x*n3_z*o3_y*p2_z - a2_y*n2_x*o2_z*p3_z + a2_y*n2_x*o3_z*p2_z + a2_y*n2_z*o2_x*p3_z - a2_y*n2_z*o3_x*p3_z - a2_y*n2_z*o3_z*p2_x + a2_y*n2_z*o3_z*p3_x + a2_y*n3_x*o2_z*p3_z - a2_y*n3_x*o3_z*p2_z - a2_y*n3_z*o2_x*p2_z + a2_y*n3_z*o2_z*p2_x - a2_y*n3_z*o2_z*p3_x + a2_y*n3_z*o3_x*p2_z + a2_z*n2_x*o2_y*p3_z - a2_z*n2_x*o3_y*p3_z - a2_z*n2_x*o3_z*p2_y + a2_z*n2_x*o3_z*p3_y - a2_z*n2_y*o2_x*p3_z + a2_z*n2_y*o3_x*p3_z + a2_z*n2_y*o3_z*p2_x - a2_z*n2_y*o3_z*p3_x - a2_z*n3_x*o2_y*p3_z + a2_z*n3_x*o3_y*p3_z + a2_z*n3_x*o3_z*p2_y - a2_z*n3_x*o3_z*p3_y + a2_z*n3_y*o2_x*p3_z - a2_z*n3_y*o3_x*p3_z - a2_z*n3_y*o3_z*p2_x + a2_z*n3_y*o3_z*p3_x + a2_z*n3_z*o2_x*p2_y - a2_z*n3_z*o2_x*p3_y - a2_z*n3_z*o2_y*p2_x + a2_z*n3_z*o2_y*p3_x - a2_z*n3_z*o3_x*p2_y + a2_z*n3_z*o3_x*p3_y + a2_z*n3_z*o3_y*p2_x - a2_z*n3_z*o3_y*p3_x - a3_x*n2_y*o2_z*p3_z + a3_x*n2_y*o3_z*p2_z + a3_x*n2_z*o2_y*p3_z - a3_x*n2_z*o3_y*p3_z - a3_x*n2_z*o3_z*p2_y + a3_x*n2_z*o3_z*p3_y + a3_x*n3_y*o2_z*p3_z - a3_x*n3_y*o3_z*p2_z - a3_x*n3_z*o2_y*p2_z + a3_x*n3_z*o2_z*p2_y - a3_x*n3_z*o2_z*p3_y + a3_x*n3_z*o3_y*p2_z + a3_y*n2_x*o2_z*p3_z - a3_y*n2_x*o3_z*p2_z - a3_y*n2_z*o2_x*p3_z + a3_y*n2_z*o3_x*p3_z + a3_y*n2_z*o3_z*p2_x - a3_y*n2_z*o3_z*p3_x - a3_y*n3_x*o2_z*p3_z + a3_y*n3_x*o3_z*p2_z + a3_y*n3_z*o2_x*p2_z - a3_y*n3_z*o2_z*p2_x + a3_y*n3_z*o2_z*p3_x - a3_y*n3_z*o3_x*p2_z - a3_z*n2_x*o2_y*p2_z + a3_z*n2_x*o2_z*p2_y - a3_z*n2_x*o2_z*p3_y + a3_z*n2_x*o3_y*p2_z + a3_z*n2_y*o2_x*p2_z - a3_z*n2_y*o2_z*p2_x + a3_z*n2_y*o2_z*p3_x - a3_z*n2_y*o3_x*p2_z - a3_z*n2_z*o2_x*p2_y + a3_z*n2_z*o2_x*p3_y + a3_z*n2_z*o2_y*p2_x - a3_z*n2_z*o2_y*p3_x + a3_z*n2_z*o3_x*p2_y - a3_z*n2_z*o3_x*p3_y - a3_z*n2_z*o3_y*p2_x + a3_z*n2_z*o3_y*p3_x + a3_z*n3_x*o2_y*p2_z - a3_z*n3_x*o2_z*p2_y + a3_z*n3_x*o2_z*p3_y - a3_z*n3_x*o3_y*p2_z - a3_z*n3_y*o2_x*p2_z + a3_z*n3_y*o2_z*p2_x - a3_z*n3_y*o2_z*p3_x + a3_z*n3_y*o3_x*p2_z)/(a2_x*n2_y*o2_z - a2_x*n2_y*o3_z - a2_x*n2_z*o2_y + a2_x*n2_z*o3_y - a2_x*n3_y*o2_z + a2_x*n3_y*o3_z + a2_x*n3_z*o2_y - a2_x*n3_z*o3_y - a2_y*n2_x*o2_z + a2_y*n2_x*o3_z + a2_y*n2_z*o2_x - a2_y*n2_z*o3_x + a2_y*n3_x*o2_z - a2_y*n3_x*o3_z - a2_y*n3_z*o2_x + a2_y*n3_z*o3_x + a2_z*n2_x*o2_y - a2_z*n2_x*o3_y - a2_z*n2_y*o2_x + a2_z*n2_y*o3_x - a2_z*n3_x*o2_y + a2_z*n3_x*o3_y + a2_z*n3_y*o2_x - a2_z*n3_y*o3_x - a3_x*n2_y*o2_z + a3_x*n2_y*o3_z + a3_x*n2_z*o2_y - a3_x*n2_z*o3_y + a3_x*n3_y*o2_z - a3_x*n3_y*o3_z - a3_x*n3_z*o2_y + a3_x*n3_z*o3_y + a3_y*n2_x*o2_z - a3_y*n2_x*o3_z - a3_y*n2_z*o2_x + a3_y*n2_z*o3_x - a3_y*n3_x*o2_z + a3_y*n3_x*o3_z + a3_y*n3_z*o2_x - a3_y*n3_z*o3_x - a3_z*n2_x*o2_y + a3_z*n2_x*o3_y + a3_z*n2_y*o2_x - a3_z*n2_y*o3_x + a3_z*n3_x*o2_y - a3_z*n3_x*o3_y - a3_z*n3_y*o2_x + a3_z*n3_y*o3_x))) </code></pre>
python|python-3.x|matrix|sympy|symbolic-math
2
1,907,933
64,967,308
How to return a column by checking multiple column with True and False without if statements
<p>How to get this desired output without using if statements ? and checking row by row</p> <pre><code>import pandas as pd test = pd.DataFrame() test['column1'] = [True, True, False] test['column2']= [False,True,False] index column1 column2 0 True False 1 True True 2 False False desired output: index column1 column2 column3 0 True False False 1 True True True 2 False False False </code></pre> <p>Your help is much appriciated.</p> <p>Thank you in advance.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>DataFrame.all</code></a> for test if all values are <code>True</code>s:</p> <pre><code>test['column3'] = test.all(axis=1) </code></pre> <p>If need filter columns add subset <code>['column1','column1']</code>:</p> <pre><code>test['column3'] = test[['column1','column1']].all(axis=1) </code></pre> <p>If want test only 2 columns here is possible use <code>&amp;</code> for bitwise <code>AND</code>:</p> <pre><code>test['column3'] = test['column1'] &amp; test['column1'] </code></pre>
pandas|list|dataframe|if-statement|list-comprehension
0
1,907,934
63,757,209
Python: inconsistent handling of IF statement in loop
<p>I have a dataframe <code>df</code> containing conditions and values.</p> <pre><code>import pandas as pd df=pd.DataFrame({'COND':['X','X','X','Y','Y','Y'], 'VALUE':[1,2,3,1,2,3]}) </code></pre> <p>Therefore <code>df</code> looks like:</p> <pre><code> COND VALUE X 1 X 2 X 3 Y 1 Y 2 Y 3 </code></pre> <p>I'm using a loop to subset <code>df</code> according to <code>COND</code>, and write separate text files containing values for each condition</p> <pre><code>conditions = {'X','Y'} for condition in conditions: df2 = df[df['COND'].isin([condition])][['VALUE']] df2.to_csv(condition + '_values.txt', header=False, index=False) </code></pre> <p>The end results is two text files: X_vals.txt and Y_vals.txt, both of which contain <code>1 2 3</code>. Up until this point everything is working as expected.</p> <p>I would like to further subset <code>df</code> for one condition only. For example, perhaps I want all values from condition Y, but ONLY values &lt; 3 from condition X. In this scenario, X_vals.txt should contain <code>1 2</code> and Y_vals.txt should contain <code>1 2 3</code>. I tried implementing this with an IF statement:</p> <pre><code>conditions = {'X','Y'} for condition in conditions: if condition == 'X': df = df[df['VALUE'] &lt; 3] df2 = df[df['COND'].isin([condition])][['VALUE']] df2.to_csv(condition + '_values.txt', header=False, index=False) </code></pre> <p>Here is where the inconsistency occurs. The above code works fine (i.e. X_vals.txt contains <code>1 2</code>, and Y_vals.txt <code>1 2 3</code>, as intended), but when I use <code>if condition=='Y'</code> instead of <code>if condition=='X'</code>, it breaks, and both text files only contain <code>1 2</code>.</p> <p>In other words, if I specify the first element of <code>conditions</code> in the IF statement then it works as intended, however if I specify the second element then it breaks and applies the &lt; 3 subset to values from both conditions.</p> <p>What is going on here and how can I resolve it?</p> <p>Thanks!</p>
<p>The problem you are encountering arises because you are overwriting <code>df</code> inside the loop.</p> <pre class="lang-py prettyprint-override"><code>conditions = {'X','Y'} for condition in conditions: if condition == 'X': df = df[df['VALUE'] &lt; 3] # &lt;-- HERE'S YOUR ISSUE df2 = df[df['COND'].isin([condition])][['VALUE']] df2.to_csv(condition + '_values.txt', header=False, index=False) </code></pre> <p>What slightly surprised me is that when you are looping over the set <code>conditions</code> you get <code>condition = 'Y'</code> first, <em>then</em> <code>condition = 'X'</code>. But as a set is an <em>unordered collection</em> (i.e. it doesn't claim to have an inherent order of its elements), this ought not to be too disturbing: python is just reading out the elements in the most internally convenient way.</p> <p>You could use <code>conditions = ['X', 'Y']</code> to loop over a list (an ordered collection) instead. Then it will do X first, then Y. However, if you do that you will get the same bug but in reverse (i.e. it works for <code>if condition == 'Y'</code> but not <code>if condition == 'X'</code>).</p> <p>This is because after the loop runs once, <code>df</code> has been reassigned to the subset of the original <code>df</code> that only contains values less than three. That's why you get only the values 1 and 2 in both files if the <code>if condition</code> statement triggers on the <strong>first pass through the loop</strong>.</p> <p>Now for the fix:</p> <pre class="lang-py prettyprint-override"><code> conditions = ['X', 'Y'] for condition in conditions: csv_name = f&quot;{condition}_values.txt&quot; if condition == 'X': df_filter = f&quot;VALUE &lt; 3 &amp; COND == '{condition}'&quot; else: df_filter = f&quot;COND == '{condition}'&quot; df.query(df_filter).VALUE.to_csv(csv_name, header=False, index=False) </code></pre> <p>Here I've introduced the <code>DataFrame.query</code> method, which is typically more concise than trying to create a Boolean series to use as a mask as you were doing.</p> <p>The f-string syntax only works on python 3.6+, if you're on a lower version then modify as appropriate (e.g. <code>df_filter = &quot;COND == '{}'&quot;.format(condition)</code>)</p>
python|pandas|loops|if-statement
7
1,907,935
65,443,949
flask mysql SUM() Decimal in Dictionary from cursor.fetchone()
<p>I'am connecting my flask-app to a MySQL-Database like this:</p> <pre><code> from flask_mysql_connector import MySQL from flask_mysqldb import MySQL # MySQL Connection app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'Prices' app.config['MYSQL_PORT'] = 3306 app.config['MYSQL_DATABASE_SOCKET'] = '' app.config['MYSQL_UNIX_SOCKET'] = '' app.config['MYSQL_CONNECT_TIMEOUT'] = '' app.config['MYSQL_READ_DEFAULT_FILE'] = '' app.config['MYSQL_USE_UNICODE'] = '' app.config['MYSQL_CHARSET'] = '' app.config['MYSQL_SQL_MODE'] = '' app.config['MYSQL_CURSORCLASS'] = 'DictCursor' mysql = MySQL() mysql.init_app(app) </code></pre> <p>Performing a query like this:</p> <pre><code>cursor.execute(&quot;SELECT SUM(total) AS sumy FROM tbl&quot;) total = cursor.fetchone() total = total[&quot;sumy&quot;] </code></pre> <p>returns this:</p> <pre><code>({'sumy': Decimal('123.4')}) </code></pre> <p>My Questions now are:</p> <p>Does every connector, the</p> <pre><code>MySQL Connector/Python PyMySQL MySQLDB mysqlclient and the OurSQL </code></pre> <p>return a Decimal('123.4') Value from a SUM(column) query? How would I get rid of this Decimal-feature the easy way? I know there are CAST() and float() suggestions out there. I like to keep it simple so is there maybe a fetchone() parameter I am missing? Or a connection parameter like ['raw'] as the MySQL Connector/Python has(I'd have to rewrite my code, if I had to change to that...)</p> <p>thank you.</p>
<p>Decimal is the python way of representing fixed decimal values. The SQL is returning a decimal probably because the <code>sumy</code> is decimal. Its likely all implementation will handle this the same way.</p> <p>Leaving the python application to handle it as a <code>Decimal</code> is probably the best way to maintain the database being responsible for retrieval and the application for presentation.</p>
python|mysql|flask|sum|decimal
0
1,907,936
65,124,975
Page not found at /polls
<p>I am a total beginner in &quot;django&quot; so I'm following some tutorials currently I' am watching <a href="https://youtu.be/JT80XhYJdBw" rel="nofollow noreferrer">https://youtu.be/JT80XhYJdBw</a> Clever Programmer's tutorial which he follows django tutorial</p> <p>Everything was cool until making a polls url</p> <p>Code of views.py:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse def index(request): HttpResponse(&quot;Hello World.You're at the polls index&quot;) </code></pre> <p>Code of polls\urls.py:</p> <pre><code>from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] </code></pre> <p>Code of Mypr\urls.py:</p> <pre><code>from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/',admin.site.urls), path('polls/',include('polls.urls')), ] </code></pre> <p>I don't get it I did the same thing but I'm getting error not only polls.In one turtorial he decided to make blog,and again the same error:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. </code></pre> <p>Please my seniors help me.</p> <p>Note:I'm using the latest versions of django,windows and as editor I'm using Pycharm.</p> <p>Already tried(and did not work):</p> <pre><code>from django.urls import path from polls.views import index urlpatterns = [ path('', index, name='index'), ] </code></pre>
<pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. </code></pre> <p>You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page.</p>
python|django|error-handling|pycharm
0
1,907,937
72,132,930
Async Multiprocessing
<p>Hi I am trying to send this processing to different cores as they are all independent of one another, however none of them are awaiting so the tasks never run. I thought that was what futures were for?</p> <pre class="lang-py prettyprint-override"><code> async def process_object(filename): # await 1 - download file from S3 # await 2 - parse XML file if &quot;__main__&quot; == __name__: objects = get_objects( bucket_name=bucket_name, prefix=prefix, file_extension=&quot;.xml&quot;, top_n=top_n ) futures = [] with concurrent.futures.ProcessPoolExecutor( multiprocessing.cpu_count() ) as executor: futures = [executor.submit(process_object, filename) for filename in objects] concurrent.futures.wait(futures) </code></pre>
<p>You don't need to use <code>asyncio</code> if you're submitting a task to <code>ProcessPoolExecutor</code>. Those tasks will be executed in another process so they are already running concurrently without the use of asyncio. Your <code>process_object</code> function never runs with your current code because a coroutine must be <code>awaited</code> before it will execute.</p> <p>That is, you want something like:</p> <pre><code>def process_object(filename): # download file # parse file ... if &quot;__main__&quot; == __name__: objects = get_objects( bucket_name=bucket_name, prefix=prefix, file_extension=&quot;.xml&quot;, top_n=top_n ) futures = [] with concurrent.futures.ProcessPoolExecutor( multiprocessing.cpu_count() ) as executor: futures = [executor.submit(process_object, filename) for filename in objects] concurrent.futures.wait(futures) </code></pre>
python|multiprocessing|concurrent.futures
0
1,907,938
10,583,362
Bluetooth lib for python 3
<p>I searched for lib for bluetooth programming in python and I found <code>PyBluez</code> but it is not compatible with Python 3. So is there any other free library for bluetooth programming compatible with Python 3?</p>
<p><a href="http://code.google.com/p/pybluez/downloads/list">PyBluez</a> now supports Python 3. </p> <p>Like the other answers state, there is inbuilt support for Bluetooth in <a href="http://docs.python.org/3.3/library/socket.html">Python sockets</a> (Python 3.3 and above). However, there is little to no documentation on how to actually use the sockets with Bluetooth. I wrote a <a href="http://blog.kevindoran.co/bluetooth-programming-with-python-3/">brief tutorial</a> so that I could refer back to it once I forget. You might find it useful. </p>
bluetooth|python-3.x
37
1,907,939
4,876,399
How to test whether x is a member of a universal set?
<p>I have a list L, and <code>x in L</code> evaluates to True if x is a member of L. What can I use instead of L in order <code>x in smth</code> will evaluate to True independently on the value of x? </p> <p>So, I need something, what contains all objects, including itself, because x can also be this "smth".</p>
<pre><code>class Universe: def __contains__(_,x): return True </code></pre>
python|math
8
1,907,940
62,808,801
How to check if method is called with the expected objects
<p>How can I test in pytest-mock whether a method has been called with a corresponding object or not?</p> <p>My object is the following:</p> <pre class="lang-py prettyprint-override"><code>class Obj: def __init__(self): self.__param = [] self.__test = [] @property def param(self): return self.__param @param.setter def param(self, value): self.__param = value # both methods: getter and setter are also available for the self.__test # This is just a dummy test object class Test: def call_method(self, text:str): obj = Obj() obj.param = [(&quot;test&quot;, &quot;1&quot;), (&quot;test2&quot;, &quot;2&quot;)] self.test_call(text, obj) def test_call(self, text:str, object: Obj): pass </code></pre> <p>My test is the following:</p> <pre class="lang-py prettyprint-override"><code>def test_method(mocker): mock_call = mocker.patch.object(Test, &quot;test_call&quot;) test = Test() test.call_method(&quot;text&quot;) expected_obj = Obj() expected_obj.param = [(&quot;test&quot;, &quot;1&quot;), (&quot;test2&quot;, &quot;2&quot;)] mock_call.assert_called_once_with(&quot;text&quot;, expected_obj) </code></pre> <p>At the moment I get the error message:</p> <pre><code>assert ('text...7fbe9b2ae4e0&gt;) == ('text...7fbe9b2b5470&gt;) </code></pre> <p>It seems that pytest checks if both objects have identical adresses. I just want to check if both objects have the same parameters. How can I check this?</p>
<p>You cannot use <code>assert_called_with</code> if you don't want to check object identitiy - instead you have to check the arguments directly:</p> <pre class="lang-py prettyprint-override"><code>def test_method(mocker): mock_call = mocker.patch.object(Test, &quot;test_call&quot;) test = Test() test.call_method(&quot;text&quot;) mock_call.assert_called_once() assert len(mock_call.call_args[0]) == 2 assert mock_call.call_args[0][0] == &quot;text&quot; assert mock_call.call_args[0][1].param == [(&quot;test&quot;, &quot;1&quot;), (&quot;test2&quot;, &quot;2&quot;)] </code></pre> <p>E.g. you have to check separately that it was called once, and that the arguments have the correct properties.</p> <p>Note that <code>call_args</code> is a <a href="https://docs.python.org/3/library/unittest.mock.html?highlight=mock#calls-as-tuples" rel="nofollow noreferrer">list of tuples</a>, where the first element contains all positional arguments, and the second element all keyword arguments, therefore you have to use <code>[0][0]</code> and <code>[0][1]</code> indexes to address the two positional arguments.</p> <p>From Python 3.8 on, you can also access the positional arguments in <code>call_args</code> via <code>args</code> and the keyword arguments via <code>kwargs</code>.</p>
python|pytest|pytest-mock
1
1,907,941
60,467,878
How to programmatically get schema from confluent schema registry in Python
<p>As of now i am doing something like this reading avsc file to get schema</p> <pre><code>value_schema = avro.load('client.avsc') </code></pre> <p>can i do something to get schema from confluent schema registry using topic-name? </p> <p>i found one way but didn't figure out how to use it.</p> <p><a href="https://github.com/marcosschroh/python-schema-registry-client" rel="nofollow noreferrer">https://github.com/marcosschroh/python-schema-registry-client</a></p>
<p><strong>Using <a href="https://github.com/confluentinc/confluent-kafka-python" rel="noreferrer"><code>confluent-kafka-python</code></a></strong></p> <pre><code>from confluent_kafka.avro.cached_schema_registry_client import CachedSchemaRegistryClient sr = CachedSchemaRegistryClient({ 'url': 'http://localhost:8081', 'ssl.certificate.location': '/path/to/cert', # optional 'ssl.key.location': '/path/to/key' # optional }) value_schema = sr.get_latest_schema("orders-value")[1] key_schema= sr.get_latest_schema("orders-key")[1] </code></pre> <hr> <p><strong>Using <a href="https://marcosschroh.github.io/python-schema-registry-client/client/" rel="noreferrer"><code>SchemaRegistryClient</code></a></strong></p> <p><em>Getting schema by subject name</em></p> <pre><code>from schema_registry.client import SchemaRegistryClient sr = SchemaRegistryClient('localhost:8081') my_schema = sr.get_schema(subject='mySubject', version='latest') </code></pre> <p><em>Getting schema by ID</em></p> <pre><code>from schema_registry.client import SchemaRegistryClient sr = SchemaRegistryClient('localhost:8081') my_schema = sr.get_by_id(schema_id=1) </code></pre>
python|apache-kafka|avro|confluent-schema-registry
16
1,907,942
60,560,408
Easy way to get file owner in Windows 7?
<p>I need to get the file owner but I don't see a simple way to achieve it.</p> <p>I tried <a href="https://stackoverflow.com/questions/41280639/how-to-get-the-owner-of-the-file-in-the-windows-7">this</a> but didn't work. Same with <a href="https://stackoverflow.com/questions/1830618/how-to-find-the-owner-of-a-file-or-directory-in-python">this</a>, not working in Windows.</p> <p>I used os.path for other file info, but doesn's seem to have anythin related to file owners.</p> <p>Any hint?</p>
<p>I found the solution in <a href="https://community.foundry.com/discuss/topic/101091/getting-file-owner-on-windows-x64?mode=Post&amp;postID=886094" rel="nofollow noreferrer">this url</a>.</p> <pre><code>from win32 import win32security OwnrSecInfo = win32security.GetFileSecurity(inFilePath, win32security.OWNER_SECURITY_INFORMATION) SecDscp = OwnrSecInfo.GetSecurityDescriptorOwner() # returns a tuple (u'owner, u'domain) ownr = win32security.LookupAccountSid(None,SecDscp) return str(ownr[0]) </code></pre>
python|file|owner
1
1,907,943
64,311,752
i'm making a count up timer that displays seconds then minute
<p>what i want as an output is</p> <pre><code>1sec 2sec 3sec . . . 1min 0sec 1sec . . . 2min 0sec </code></pre> <p>the code i'm stuck on rn is</p> <pre><code>from time import sleep i = 0 j = 0 def clockpt1 (i): while i &lt; 5: print(i, &quot;sec&quot;) i = i + 1 sleep(1) else: i = 0 clockpt2(j) def clockpt2(j): global j j += 1 print(j,&quot;min&quot;) def clock(): while True: clockpt1(i) clock() </code></pre> <p>i looked around stackoverflow and apparently using the &quot;global&quot; term is best especially if i want to draw from a global variable and update said variable, but i cant seem to get it to work.</p> <p>At the same time can someone explain why does &quot;return&quot; not work in this situation?</p> <p>i get this error</p> <pre><code> File &quot;clocktest&quot;, line 14 global j ^ SyntaxError: name 'j' is parameter and global ``` </code></pre>
<p>Remove j from <code>def clockpt2(j):</code></p> <pre><code>from time import sleep i = 0 j=0 def clockpt1 (i): while i &lt; 5: print(i, &quot;sec&quot;) i = i + 1 sleep(1) else: i = 0 clockpt2() def clockpt2(): global j j += 1 print(j,&quot;min&quot;) def clock(): while True: clockpt1(i) clock() </code></pre>
python|python-3.x
0
1,907,944
53,115,242
Two very similar Regex, other could not find match
<p>I'm trying to match a shortName-field from a JSON'ish string (no longer in correct JSON format, thus regex). Running regex here might not be the most efficient way. I'm open for suggestions, but <strong>I WANT the solution for the original problem as well.</strong></p> <p><strong>I'm using Python 2.7 and Scrapy, running PyCharm 2018.2</strong></p> <p><strong>What I want:</strong> Get matches from the huge JSON'ish file full of restaurants, run every match into list, iterate the list objects and collect different fields data, which I set into variables for future use. We don't go that far here though.</p> <p>I want to match the shortName-field, and pull out the value/data from it.</p> <p>The code samples below start from the point where the huge file is already received (in unicode or string), and we start to match for restaurant specific data fields. In the actual pattern, I tried to escape, and not to escape, the " and : symbols.</p> <p><strong>What I have:</strong> <a href="https://regex101.com/r/6J2Wbt/1" rel="nofollow noreferrer">Regex101</a> (below)</p> <p><strong>I got the actual regex which I'm trying to fix, which ends up in "NoneType has no attribute 'group'".</strong></p> <p><strong>Do note, the first line "pattern" works, and brings me the data which I start to go through in for-loop. I don't believe that the problem lies there.</strong></p> <pre><code>regex = re.compile(pattern, re.MULTILINE) for match in regex.finditer(r.text): restaurant = match.group() restaurant = str(restaurant) print restaurant print type(restaurant) name = re.search(r'(?&lt;=shortName\":\")(.*?)(?=\")',restaurant,re.MULTILINE | re.DOTALL).group() </code></pre> <p>Source sample: </p> <pre><code>156,"mainGroupId":1,"menuTypeId":1,"shopExternalId":"0001","displayName":"Lorem Ipsum","shortName":"I WANT THIS TEXT HERE","streetAddress":"BlankStreet 5","zip":"1211536","city":"Wonderland", </code></pre> <p><strong>Testing regex, which works for a fixed source sample.</strong> NOTE: The source sample for this one was formatted with \ by regex101, as I first had every " and : escaped with . I copied this straight from their code generator, but it does work in code:</p> <pre><code>testregex = r'(?&lt;=shortName\"\:\")(.*?)(?=\")' test_str = ( 156,\"mainGroupId\":1,\"menuTypeId\":1,\"shopExternalId\":\"0001\",\"displayName\":\"Lorem Ipsum\",\"shortName\":\"I CAN GET THIS MATCHED \",\"streetAddress\":\"BlankStreet 6\",\"zip\":\"2136481\",\"city\":\"Wonderland\") matches = re.search(testregex, test_str, re.MULTILINE | re.DOTALL).group() print matches restaurantname = matches </code></pre> <p><strong>What is the problem:</strong> The upper regex prints out the <em>"'nonetype' object has no attribute 'group'"</em>-error. The lower regex gets me the data I want, in this example it prints out "I CAN GET THIS MATCHED" </p> <p>I am well aware that there might be small syntax problems, as I've been trying to fix this for some time.</p> <p>Thank you in advance. The more detailed answer, the better. If you got different approach to the problem, please do give code so I can learn from it.</p>
<p>Your <a href="https://regex101.com/r/hbyXZf/1" rel="nofollow noreferrer">regex</a> does not match your string. There is no <code>shopID</code> in the input. </p> <p>You may get all your restaurant names directly with one <code>re.findall</code> call using the following regex:</p> <pre><code>shortName":"([^"]+) </code></pre> <p>See the <a href="https://regex101.com/r/hbyXZf/3" rel="nofollow noreferrer">regex demo</a>. <strong>Details</strong></p> <ul> <li><code>shortName":"</code> - a literal substring</li> <li><code>([^"]+)</code> - Capturing group 1 (the result of the <code>re.findall</code> call will be the substrings captured into this Group): 1 or more chars other than <code>"</code>.</li> </ul> <p>See <a href="https://ideone.com/VqE5q3" rel="nofollow noreferrer">Python demo</a>:</p> <pre><code>import re regex = re.compile(r'shortName":"([^"]+)') print(regex.findall('156,"mainGroupId":1,"menuTypeId":1,"shopExternalId":"0001","displayName":"Lorem Ipsum","shortName":"I WANT THIS TEXT HERE","streetAddress":"BlankStreet 5","zip":"1211536","city":"Wonderland",')) </code></pre>
python|regex|python-2.7
2
1,907,945
70,348,464
Ray - Tensorflow - parallel processing issue
<p>By following the article <a href="https://towardsdatascience.com/modern-parallel-and-distributed-python-a-quick-tutorial-on-ray-99f8d70369b8" rel="nofollow noreferrer">https://towardsdatascience.com/modern-parallel-and-distributed-python-a-quick-tutorial-on-ray-99f8d70369b8</a> I'm trying to use Ray module for parallel processing of below tensorflow program '''</p> <pre><code>import ray import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ray.init() graph = tf.Graph() with graph.as_default(): variable = tf.Variable(42, name='foo') initialize = tf.global_variables_initializer() assign = variable.assign(13) @ray.remote class Simulator(object): def __init__(self): self.sess = tf.Session(graph=graph) def simulate(self): self.sess = tf.Session(graph=graph) self.sess.run(initialize) self.sess.run(assign) return self.sess.run(variable) # Create two actors. simulators = [Simulator.remote() for _ in range(2)] # Run two simulations in parallel. results = ray.get([s.simulate.remote() for s in simulators]) print(results) </code></pre> <p>'''</p> <p>but ended up with the below issues:</p> <p><strong>TypeError: can't pickle _thread.RLock objects</strong></p> <p><strong>TypeError: Could not serialize the actor class</strong></p> <p>Can anyone please let me know if there is any issue in my approach.</p> <p>I observed the same error (can't pickle _thread.RLock objects)even if I use multiprocessing module</p> <p>Please find the versions I'm using:</p> <p>python - 3.7.4</p> <p>tensorflow - 2.0.0</p> <p>ray - 1.9.0</p>
<p>I believe the issue is that you are creating some TF objects (e.g., <code>variable</code>, <code>initialize</code>, and <code>assign</code>) in your main script and then using them inside of the actor. This causes Ray to try to serialize the TF objects when it serializes the <code>Simulator</code> class definition (because these have to get passed from one process to another). TF objects are often not serializable. Instead, you could create the objects inside of the actor. For example</p> <pre class="lang-py prettyprint-override"><code>import ray import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ray.init() @ray.remote class Simulator(object): def __init__(self): self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) with self.graph.as_default(): self.variable = tf.Variable(42, name='foo') self.initialize = tf.global_variables_initializer() self.assign = self.variable.assign(13) def simulate(self): self.sess = tf.Session(graph=self.graph) self.sess.run(self.initialize) self.sess.run(self.assign) return self.sess.run(self.variable) # Create two actors. simulators = [Simulator.remote() for _ in range(2)] # Run two simulations in parallel. results = ray.get([s.simulate.remote() for s in simulators]) print(results) </code></pre>
python|tensorflow|ray
0
1,907,946
10,882,469
What's the Groovy equivalent to Python's dir()?
<p>In Python I can see what methods and fields an object has with:</p> <pre><code>print dir(my_object) </code></pre> <p>What's the equivalent of that in Groovy (assuming it has one)?</p>
<p>Looks particulary nice in Groovy (untested, <a href="http://noor.ojuba.org/2008/07/groovy-introspection-know-what-you-have/">taken from this link</a> so code credit should go there):</p> <pre><code>// Introspection, know all the details about classes : // List all constructors of a class String.constructors.each{println it} // List all interfaces implemented by a class String.interfaces.each{println it} // List all methods offered by a class String.methods.each{println it} // Just list the methods names String.methods.name // Get the fields of an object (with their values) d = new Date() d.properties.each{println it} </code></pre> <p>The general term you are looking for is <strong>introspection</strong>.</p>
python|groovy
10
1,907,947
63,571,190
Best way to CONVERT python code(with Tensorflow) to Android APK
<p>I'm python user and very weak in Java for android APK coding.</p> <p>Now I want to my python OCR code(Package with so many *.py) to my companies APK.</p> <p>I heard tensorflow maybe converted TF-lite for APK...</p> <p>I searched kivy but it seems just a tools for android new app builder, not converting exist *.py codes.</p> <ol> <li><p>I need to entirely code new android APK for java? (Only some like tf.keras.fit() maybe convertable to java via TF-lite?)</p> </li> <li><p>I just want to OCR when it receive inputs image file and act like just python OCR. what option should I get?? (I really need to study java? it will take some times..)</p> </li> </ol>
<p>If all you need is to create an OCR app and don't have the need to use a custom OCR model built with TensorFlow, I'd suggest you to just use an existing model, as they exist and are super simple to use in Android.</p> <p>I recommend you to use ML Kit's Text Recognition Package and API: <a href="https://developers.google.com/ml-kit/vision/text-recognition/android" rel="nofollow noreferrer">https://developers.google.com/ml-kit/vision/text-recognition/android</a></p> <p>You can find code examples on the page above and a sample app in the link below: <a href="https://github.com/googlesamples/mlkit/tree/master/android/vision-quickstart" rel="nofollow noreferrer">https://github.com/googlesamples/mlkit/tree/master/android/vision-quickstart</a></p> <p>Google also provides a CodeLab to take you through on a gentle journey of how to build a simple app using ML KIT</p> <p><a href="https://codelabs.developers.google.com/codelabs/mlkit-android/#0" rel="nofollow noreferrer">https://codelabs.developers.google.com/codelabs/mlkit-android/#0</a></p>
python|android|tensorflow
2
1,907,948
60,997,312
Blank lines in txt files in Python
<p>I want to write sensor values to a text file with Python. All is working fine but one thing; in the text file, there are blank lines between each value. It's really annoying because I can't put the values in a spreadsheet. It looks like this:</p> <pre><code>Sensor values: 2 4 6.32 1 etc.... </code></pre> <p>When I want it without the line breaks:</p> <pre><code>Sensor values: 1 2 3 5 8 etc... </code></pre> <p>Here's the part of the code which writes the data to file:</p> <pre class="lang-py prettyprint-override"><code>def write_data(): global file_stream now = datetime.now() dt_string = now.strftime(&quot;%d-%m-%Y %H_%M_%S&quot;) file_stream = open(&quot;data &quot; + dt_string+&quot;.txt&quot;, &quot;w&quot;) # mode write ou append ? write_lines() def write_lines(): global after_id data = arduinoData.read() data2 = data.decode(&quot;utf-8&quot;) file_stream.write(data2) print(data2) if data2 == &quot;F&quot;: print(&quot;Ca a marché&quot;) stopacq() return after_id = root.after(10, write_lines) </code></pre>
<p>Add the newline attribute</p> <pre><code>file_stream = open("data " + dt_string+".txt", "w", newline="") </code></pre>
python|file|arduino
1
1,907,949
61,072,688
How to change python script to .exe with user defined input and output paths in python
<p>I have python script , i want to change this simple script to .exe file with user defined input and output path .</p> <p>in below script 'csv' is input folder and contain multiple txt files , </p> <pre><code>import pandas as pd import numpy as np import os for file in os.listdir('csv/'): filename = 'csv/{}'.format(file) print(filename) df=pd.read_csv(filename) df.to_csv(path_out) </code></pre>
<p>A simple way you can do this with cx_freeze is as follows:</p> <ol> <li><p>conda install -c conda-forge cx_freeze, or pip install cx_freeze to your env with numpy and pandas</p></li> <li><p>Make a folder called dist for your new .exe </p></li> <li><p>Save the code below as csv_thing.py, or whatever you want it to be called.</p></li> <li><p>Run the command: cxfreeze csv_thing.py --target-dir C:\somepath\dist</p></li> <li><p>There is a good chance that without using a cx_freeze setup file (spec file in pyinstaller) that not all of the files will get copied over to the dist dir. Numpy and pandas from Anaconda envs are often tricky.</p></li> <li><p>If file failure occurs, you can manually copy the .dll files over into the dist folder; it's easy if you just grab them all. If you're using an Anaconda env, they likely live here: C:\Users\your_user_account\Anaconda3\envs\panel\Library\bin. Otherwise grab all of them from the numpy location: C:\Users\matth\Anaconda3\envs\panel\Lib\site-packages\numpy and copy to the dist dir.</p></li> </ol> <hr> <pre><code>import numpy as np import pandas as pd import os in_dir = input(' enter a folder path where your .csvs are located: ') out_dir = input(' enter a folder path where your .csvs will go: ') csv_list = [os.path.join(in_dir, fn) for fn in next(os.walk(in_dir))[2]if fn.endswith('.csv')] for csv in csv_list: file_name = os.path.basename(csv) print(file_name) df = pd.read_csv(csv) df.to_csv(os.path.join(out_dir, file_name)) </code></pre>
python-3.x|pandas|numpy|exe
0
1,907,950
61,106,572
How to check if list only contains numbers
<p>I am struggling to write a program that will determine if there are only numbers in a list, so floats or integers. Nothing special like "True" is 1 or the ASCII code of "A" or anything like that. I want to check the list to make sure it only has floats or integers. This is my code so far but it doesn't work for all cases.</p> <pre><code>list1 = [-51,True] for i in list1: if (isinstance(i,int))==False and (isinstance(i,float)==False): print("None") </code></pre> <p>In this case it doesn't print "None". When it should for "True". Any ideas?</p>
<p>you can use:</p> <pre><code>all(isinstance(e, (int, float)) for e in list1) </code></pre>
python|list|numbers
6
1,907,951
66,111,428
how do i use string.replace() to replace only when the string is exactly matching
<p>I have a dataframe with a list of poorly spelled clothing types. I want them all in the same format , an example is i have &quot;trous&quot; , &quot;trouse&quot; and &quot;trousers&quot;, i would like to replace the first 2 with &quot;trousers&quot;.</p> <p>I have tried using string.replace but it seems its getting the first &quot;trous&quot; and changing it to &quot;trousers&quot; as it should and when it gets to &quot;trouse&quot;, it works also but when it gets to &quot;trousers&quot; it makes &quot;trousersersers&quot;! i think its taking the strings which contain trous and trouse and trousers and changing them.</p> <p>Is there a way i can limit the string.replace to just look for exactly &quot;trous&quot;.</p> <p>here's what iv troied so far, as you can see i have a good few changes to make, most of them work ok but its the likes of trousers and t-shirts which have a few similar changes to be made thats causing the upset.</p> <pre><code> newTypes=[] for string in types: underwear = string.replace(('UNDERW'), 'UNDERWEAR').replace('HANKY', 'HANKIES').replace('TIECLI', 'TIECLIPS').replace('FRAGRA', 'FRAGRANCES').replace('ROBE', 'ROBES').replace('CUFFLI', 'CUFFLINKS').replace('WALLET', 'WALLETS').replace('GIFTSE', 'GIFTSETS').replace('SUNGLA', 'SUNGLASSES').replace('SCARVE', 'SCARVES').replace('TROUSE ', 'TROUSERS').replace('SHIRT', 'SHIRTS').replace('CHINO', 'CHINOS').replace('JACKET', 'JACKETS').replace('KNIT', 'KNITWEAR').replace('POLO', 'POLOS').replace('SWEAT', 'SWEATERS').replace('TEES', 'T-SHIRTS').replace('TSHIRT', 'T-SHIRTS').replace('SHORT', 'SHORTS').replace('ZIP', 'ZIP-TOPS').replace('GILET ', 'GILETS').replace('HOODIE', 'HOODIES').replace('HOODZIP', 'HOODIES').replace('JOGGER', 'JOGGERS').replace('JUMP', 'SWEATERS').replace('SWESHI', 'SWEATERS').replace('BLAZE ', 'BLAZERS').replace('BLAZER ', 'BLAZERS').replace('WC', 'WAISTCOATS').replace('TTOP', 'T-SHIRTS').replace('TROUS', 'TROUSERS').replace('COAT', 'COATS').replace('SLIPPE', 'SLIPPERS').replace('TRAINE', 'TRAINERS').replace('DECK', 'SHOES').replace('FLIP', 'SLIDERS').replace('SUIT', 'SUITS').replace('GIFTVO', 'GIFTVOUCHERS') newTypes.append(underwear) types = newTypes </code></pre>
<p>Use a dict for string to be replaced:</p> <pre><code> d={ 'trous': 'trouser', 'trouse': 'trouser', # ... } newtypes=[d.get(string,string) for string in types] </code></pre> <p>d.get(string,string) will return string if string is not in d.</p>
python|string|list|dataframe|replace
0
1,907,952
66,056,710
how to get the value of combobox selected item in python
<pre><code>selectedfood = tk.StringVar() foodselectionUI = ttk.Combobox(homeUI, width = 27, textvariable = selectedfood) foodselectionUI['values'] = (&quot;None&quot;, &quot;Nasi Ayam&quot;, &quot;Maggi Mee Goreng&quot;, &quot;Wan Tan Mee&quot;, &quot;Nasi Lemak&quot;,&quot;Nasi Ayam Tiga Rasa&quot;, &quot;Ayam Goreng&quot;, &quot;Sushi&quot;, &quot;Burger Special&quot;,&quot;Vega Bao&quot;, &quot;Kari Ayam Bao&quot;,&quot;select food&quot;) foodselectionUI.place(x = 10, y = 125, width = 150) foodselectionUI.current(11) </code></pre> <p>this is my code and this picture is my tkinter UI</p> <p><a href="https://i.stack.imgur.com/daHZC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/daHZC.jpg" alt="enter image description here" /></a></p> <p>may i know how to get my selection</p> <p>for example if user choose 'sushi' i can get it as my <strong>textvariable</strong></p> <p>i didnt get my output using this way</p> <p>i get this thing <code>PY_VAR1</code></p>
<pre><code>def justamethod (*args): print(&quot;method is called&quot;) print (selectedfood.get()) foodselectionUIbind(&quot;&lt;&lt;ComboboxSelected&gt;&gt;&quot;, justamethod) </code></pre>
python|tkinter|combobox
0
1,907,953
69,225,662
Plot an unknown netcdf file (without ncview)
<p>I am starting with the netcdf in python and I want to know more options to view the netcdf in a friendly way</p> <p>In raster cases (2D or 3D) I can use ncview, but there are cases that only give me longitude, latitude, and others variables (as height for example) or save polygons contours or lines, I would like to visualize this a friendly way (as in QGis format) in order to have a better data overview</p> <pre><code>import netCDF4 src = netCDF4.Dataset(file) var_names = src.variables.keys() float32 nav_lat(y, x) units: degrees_north long_name: Latitude unlimited dimensions: current shape = (10800, 21600) float32 upst(y, x) axis: TYX units: m2 long_name: area associate: nav_lat nav_lon coordinates: nav_lat nav_lon unlimited dimensions: current shape = (10800, 21600) </code></pre>
<p>You could try it with ncplot (<a href="https://pypi.org/project/ncplot/" rel="nofollow noreferrer">https://pypi.org/project/ncplot/</a>) which provides ncview style auto-plotting in Python.:</p> <pre><code>from ncplot import view view(file) </code></pre> <p>Though if ncview cannot automatically plot it, there may be some data issues.ncview should be able to handle almost anything.</p>
python|plot|netcdf
0
1,907,954
72,535,869
How to get text from html attributes
<p>I tried to parse a page to get some element as text, but I cant find how to get text from select</p> <p>For exmaple, html below has data-initial-rating=&quot;4&quot; and title=&quot;Members who rated this thread&quot;&gt;12 Votes&quot;, but I cant get it</p> <pre><code>&lt;select name=&quot;rating&quot; class=&quot;br-select input&quot; data-xf-init=&quot;rating&quot; data-initial-rating=&quot;4&quot; data-rating-href=&quot;/threads/isis-the-fall-v1-02-tjord.117157/br-rate&quot; data-readonly=&quot;false&quot; data-deselectable=&quot;false&quot; data-show-selected=&quot;true&quot; data-widget-class=&quot;bratr-rating&quot; data-vote-content=&quot;&lt;div data-href=&amp;quot;/threads/game-mod-v-1-02/br-user-rated&amp;quot; data-xf-click=&amp;quot;overlay&amp;quot; data-xf-init=&amp;quot;tooltip&amp;quot; title=&amp;quot;Members who rated this thread&amp;quot;&gt;12 Votes&lt;/div&gt;&quot; style=&quot;display: none;&quot;&gt; &lt;option value=&quot;&quot;&gt;&amp;nbsp;&lt;/option&gt; &lt;option value=&quot;1&quot;&gt;Terrible&lt;/option&gt; &lt;option value=&quot;2&quot;&gt;Poor&lt;/option&gt; &lt;option value=&quot;3&quot;&gt;Average&lt;/option&gt; &lt;option value=&quot;4&quot;&gt;Good&lt;/option&gt; &lt;option value=&quot;5&quot;&gt;Excellent&lt;/option&gt; &lt;/select&gt; </code></pre> <p>what i tried</p> <pre><code>import requests import lxml.html response = requests.get('somewebsite.com') tree = lxml.html.fromstring(response.text) # full xptah messy_rating_and_votes = tree.xpath('/html/body/div[2]/div/div[3]/div/div[1]/div/div/div[3]/div/div[2]/div/div/select') print(messy_rating_and_votes) # its just print empty list, so i cant use .text or .text_content() </code></pre> <p>So, i guese thats i select wrong or use wrong method, but almost 2 hours of googling dosent help me</p>
<p>This example uses BeautifulSoup4</p> <pre><code>import requests from bs4 import BeautifulSoup response = requests.get(&quot;somewebsite.com&quot;) soup = BeautifulSoup(response.content, 'html5lib') # requires pip install html5lib for option in soup.find_all('option'): print(f&quot;value: {option['value']} text: {option.text}&quot;) </code></pre>
python|html|python-3.x|xpath|lxml.html
0
1,907,955
72,751,166
How to create tables in a different schema in django?
<p>I'm using postgresql database in my django project.</p> <p>I have multiple apps in my projects.</p> <pre><code>users/ UserProfile model myapp/ CustomModel model </code></pre> <p>Now I need <code>UserProfile</code> table should be created in <code>public</code> schema And <code>CustomModel</code> table needs to be created in a separate schema called <code>myapp</code></p> <p>How to implement this and Do I need to change anything in the queries or migration command in future after implementing this?</p>
<p>Just use a meta information:</p> <pre><code>class User(models.Model) class Meta: db_table = 'schema&quot;.&quot;tablename' </code></pre> <p>I've been using it from some time and found not problem so far.</p> <p>More info: This will replace table name in all your database queries with <code>db_table</code>. So any query will <code>SELECT * FROM &quot;tablename&quot;</code> will be converted to <code>SELECT * FROM &quot;geo&quot;.&quot;tablename&quot;</code>. Its just a neat trick, hopefully Django gives this option natively in future.</p>
python|django|postgresql|django-models|django-orm
1
1,907,956
72,721,768
List of deque() appends item to all deque() in list
<pre><code>import collections from deque test = [deque()] * 3 test[2].append(7) print(test) </code></pre> <p>I am expecting the above to print: [deque([]), deque([]), deque([7])]</p> <p>but instead i get: [deque([7]), deque([7]), deque([7])]</p> <p>What is the reason for this?</p>
<p>Your list contains three times the same deque not three different deques.</p>
python|list|deque
0
1,907,957
72,537,958
How do I create a function that takes a users input as a command for file navigation?
<p>I'm new to Python (programming in general) and am trying to make a very basic file navigation that works like CMD to navigate my 3D files. So far, it works at a very VERY basic level. It prints out the subdirectories in the root folder. From there the user can input the subdirectory to see a list of continued subdirectories. Below is a small example of what I'm trying to do. This prints the folders in the root, and continues to the subdirectories. My 'testFunction' is a place holder. I'm hoping that if the user doesn't see the subdirectory they can type &quot;Back&quot; and go up a level in the folder tree. Right now it seems to be erroring out because &quot;Back&quot; isn't a sub directory. I'm not sure how to get around this. Any suggestions?</p> <pre><code>import os rootDir = &quot;C:\\Users\\xyz\\OneDrive - xyz&quot; def testFunction(): if input(&quot;Back&quot;): print(&quot;Working!&quot;) for file in os.listdir(rootDir): d = os.path.join(rootDir, file) if os.path.isdir(d): subDirTest = d print(d) input_1 = input(&quot;Enter Sub Directory &quot;) userSubDirInput_1 = rootDir + &quot;\\&quot; + input_1 print(rootDir + userSubDirInput_1) subDirectory_1 = userSubDirInput_1 = rootDir + &quot;\\&quot; + input_1 </code></pre> <p>I'm hoping as I keep learning I'll have several input functions that control navigation.</p>
<p>You probably want to have a variable that tracks the current directory, and update it in a loop. If the user enters <code>Back</code>, go back; otherwise go into the directory they entered. Here's a quick example adapted from your current code:</p> <pre><code>import os cwd = os.getcwd() while True: for file in os.listdir(cwd): d = os.path.join(cwd, file) if os.path.isdir(d): print(d) i = input(&quot;Enter Sub Directory &quot;) if i == &quot;Quit&quot;: break elif i == &quot;Back&quot;: cwd = os.path.join(*os.path.split(cwd)[:-1]) else: cwd = os.path.join(cwd, i) </code></pre>
python|function|input|directory|callback
0
1,907,958
68,173,284
Remove suffix of the column names and unpivot
<p>I'd like to unpivot the following table with column names &quot;Year&quot;, &quot;Item&quot;, and &quot;$&quot;. My workaround is to separate the table into two dataframes and remove the suffixes, then concatenate the two columns vertically. Are there any other easier ways to approach this?</p> <p>Example Dataframe:</p> <pre><code>data = {'Year_x': [1993, 1994, 1995, 1996], 'Year_y': [2000, 2001, 2002, 2003], 'Item_x':['A','B','C','D'], 'Item_y':['E','F','G','H'], '$':[3,4,5,6]} pd.DataFrame.from_dict(data) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Year_x</th> <th style="text-align: left;">Year_y</th> <th style="text-align: left;">Item_x</th> <th style="text-align: left;">Item_y</th> <th style="text-align: center;">$</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1993</td> <td style="text-align: left;">2000</td> <td style="text-align: left;">A</td> <td style="text-align: left;">E</td> <td style="text-align: center;">3</td> </tr> <tr> <td style="text-align: left;">1994</td> <td style="text-align: left;">2001</td> <td style="text-align: left;">B</td> <td style="text-align: left;">F</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: left;">1995</td> <td style="text-align: left;">2002</td> <td style="text-align: left;">C</td> <td style="text-align: left;">G</td> <td style="text-align: center;">5</td> </tr> <tr> <td style="text-align: left;">1996</td> <td style="text-align: left;">2003</td> <td style="text-align: left;">D</td> <td style="text-align: left;">H</td> <td style="text-align: center;">6</td> </tr> </tbody> </table> </div> <p>What I want to achieve:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Year</th> <th style="text-align: left;">Item</th> <th style="text-align: center;">$</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1993</td> <td style="text-align: left;">A</td> <td style="text-align: center;">3</td> </tr> <tr> <td style="text-align: left;">1994</td> <td style="text-align: left;">B</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: left;">1995</td> <td style="text-align: left;">C</td> <td style="text-align: center;">5</td> </tr> <tr> <td style="text-align: left;">1995</td> <td style="text-align: left;">D</td> <td style="text-align: center;">6</td> </tr> <tr> <td style="text-align: left;">2000</td> <td style="text-align: left;">E</td> <td style="text-align: center;">3</td> </tr> <tr> <td style="text-align: left;">2001</td> <td style="text-align: left;">F</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: left;">2002</td> <td style="text-align: left;">G</td> <td style="text-align: center;">5</td> </tr> <tr> <td style="text-align: left;">2003</td> <td style="text-align: left;">H</td> <td style="text-align: center;">6</td> </tr> </tbody> </table> </div>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> for convert columns without separator <code>_</code> to index, then split columns names to <code>MultiIndex</code> :</p> <pre><code>cols = ['$'] #if multiple columns cols = ['$', '$Column1', '$Column2'] df1 = df.set_index(cols) df1.columns = df1.columns.str.split('_', expand=True) df1 = (df1.stack() .sort_values(['Item','Year']) .reset_index()[['Year','Item'] + cols]) print (df1) Year Item $ 0 1993 A 3 1 1994 B 4 2 1995 C 5 3 1996 D 6 4 2000 E 3 5 2001 F 4 6 2002 G 5 7 2003 H 6 </code></pre>
python|pandas|dataframe|unpivot|suffix
3
1,907,959
59,067,407
SQLITE3 / Python - Database disk image malformed but integrity_check ok
<p>My actual problem is that <code>python</code> <code>sqlite3</code> module throws <code>database disk image malformed</code>.</p> <p>Now there must be a million possible reasons for that. However, I can provide a number of clues:</p> <ul> <li><p>I am using <code>python</code> <code>multiprocessing</code> to spawn a number of workers that all <strong>read</strong> (not write) from this DB</p></li> <li><p>The problem definitely has to do with multiple processes accessing the DB, which fails on the remote setup but not on the local one. If I use only one worker on the remote setup, it works</p></li> <li><p>The same 6GB database works perfectly well on my local machine. I copied it with <code>git</code> and later again with <code>scp</code> to remote. There the same script with the copy of the original DB gives the error</p></li> <li><p>Now if I do <code>PRAGMA integrity_check</code> on the remote, it returns <code>ok</code> after a while - even after the problem occurred</p></li> <li><p>Here are the versions (OS are both <code>Ubuntu</code>):</p> <ol> <li>local: <code>sqlite3.version &gt;&gt;&gt; 2.6.0</code>, <code>sqlite3.sqlite_version &gt;&gt;&gt; 3.22.0</code></li> <li>remote: <code>sqlite3.version &gt;&gt;&gt; 2.6.0</code>, <code>sqlite3.sqlite_version &gt;&gt;&gt; 3.28.0</code></li> </ol></li> </ul> <p>Do you have some ideas how to allow for save "parallel" <code>SELECT</code>?</p>
<p>The problem was for the following reason (and it had happened to me before):</p> <p>Using <code>multiprocessing</code> with <code>sqlite3</code>, make sure to <strong>create a separate connection for each worker</strong>!</p> <p>Apparently this causes problems with some setups and sometimes doesn't.</p>
python|sqlite|select|multiprocessing|malformed
0
1,907,960
59,396,898
can't do cosine similarity between 2 images, how to make both have the same length
<p>I was doing some face verification stuff(I'm a newbie) first I vectorize the 2 pics I want to compare</p> <pre><code>filename1 = '/1_52381.jpg' filename2 = '/1_443339.jpg' img1 = plt.imread(filename1) rows,cols,colors = img1.shape img1_size = rows*cols*colors img1_1D_vector = img1.reshape(img1_size).reshape(-1, 1) img2 = plt.imread(filename2) rows,cols,colors = img2.shape img2_size = rows*cols*colors img2_1D_vector = img2.reshape(img2_size).reshape(-1, 1) (img2_1D_vector.shape,img1_1D_vector.shape) </code></pre> <p>and here I get the dim of the both vector which is: ((30960, 1), (55932, 1)).</p> <p>My question is how to make them both of the same length do I need to reshape the picture to have the same size first? or I can do it after vectorize it? thanks for reading</p>
<p>Yes, to compute a cosine similarity you need your vectors to have the same dimension, and resizing one of the pictures before reshaping it into a vector is a good solution.</p> <p>To resize, you can use one of image processing framework available in python.</p> <p><em>Note: they are different algorithm/parameters that can be use for resizing.</em></p> <pre><code># with skimage (you can also use PIL or cv2) from skimage.transform import resize shape = img1.shape img2_resized = resize(img1, shape) img1_vector = img1.ravel() img2_vector = img2_resized.ravel() # now you can perform your cosine similarity between img1_vector and img2_vector # which are of the same dimension </code></pre> <p>you may wan't to downscale the bigger picture instead of upscaling the smaller one as upscaling may introduce more artefacts. You may also want to work with a fixed size accross a whole dataset.</p>
python|face-recognition
1
1,907,961
63,034,652
GTTS module error, ImportError: cannot import name gTTS
<p>I am trying to make a Voice assistant in python using this code</p> <pre><code>import os from gtts import gTTs import time import playsound import speech_recognition as sr def speak(text): tts = gTTS(text=text, lang=&quot;en&quot;) filename = &quot;voice.mp3&quot; tts.save(filename) playsound.playsound(filename) def get_audio(): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) said = &quot;&quot; try: said = r.recognize_google(audio) print(said) except Exception as e: print(&quot;Exception: &quot; + str(e)) return said text = get_audio() if &quot;who are you&quot; in text: speak(&quot; I am Friday the virtual assistant&quot;) </code></pre> <p>And when i run it, it shows this error ImportError: cannot import name gTTS</p> <p>Any help would be amazing :)</p> <p>Edit:I have changed it to gTTS and still get ImportError: cannot import name gTTS</p>
<p>Try replacing</p> <pre><code>from gtts import gTTs </code></pre> <p>with</p> <pre><code>from gtts import gTTS </code></pre> <p>(Note the capital <code>S</code>)</p>
python|gtts
3
1,907,962
73,339,978
url returns JSON but with scrapy I got a weird response
<p>I am new to scrapy and I struggle understanding the response I get from a simple address. The address is <a href="https://fr.getaround.com/search.json?address=Gare%20de%20Bordeaux%20Saint-Jean" rel="nofollow noreferrer">https://fr.getaround.com/search.json?address=Gare de Bordeaux Saint-Jean</a> which give a long json response (&gt;130k caracters).</p> <p>The idea with this json is to then scrape the list of cars provided by the response.</p> <p>getaround api is quite standard in its answers so even if there were no cars, I would still receive the global json structure with an empty cars list.</p> <p>When trying with scrapy though I get a very short response : <code>b'{&quot;redirect_to&quot;:&quot;/&quot;}'</code></p> <p>Here under is the code I am using</p> <pre><code>def start_requests(self): addresses= [&quot;Gare de Bordeaux Saint-Jean&quot;] for address in addresses: yield scrapy.Request( f&quot;https://fr.getaround.com/search.json?address={address}&quot; ) def parse(self, response): print(&quot;--------------------------------------------------------\nRESPONSE\n--------------------------------------------------------&quot;) print(response) print(&quot;--------------------------------------------------------\nBODY\n--------------------------------------------------------&quot;) print(response.body) </code></pre> <p>I tried a few things :</p> <ul> <li>Using playwright</li> </ul> <p>It basically wrap the previous response.body between some html tags</p> <ul> <li>Using the shell</li> </ul> <p>Same response. I tried to force the method to GET (<code>request = request.replace(method=&quot;GET&quot;)</code>) or POST (<code>method=&quot;POST&quot;</code>)</p> <ol> <li>GET gives a 200 code with proper response in POSTMAN and 200 status with only a body being <code>b''</code> with scrapy shell</li> <li>POST gives a 404 code in both POSTMAN and scrapy</li> </ol> <ul> <li>I tried enabling or not cookies with settings.py with no luck.</li> <li>I tried to scrape the main page (<code>fr.getaround.com</code>) out of which the response.body seems fine.</li> </ul> <p>Any idea on what I am doing wrong ?</p> <p><strong>EDIT</strong></p> <p><a href="https://www.transfernow.net/dl/20220812xxeDv7vG" rel="nofollow noreferrer">Here</a> the json response I get from POSTMAN / opening the url</p>
<p>So the difference between the request opened in Chrome / Postman and what scrapy was doing is a simple matter of cookie. In my case POSTMAN add some saved cookies (maybe from an initial query) which allowed getaround to still provide an answer to a badly formated url based on the request out of which the cookies were generated</p> <p>So the issue is not from scrapy but from non discarded cookies within Postman (the little &quot;Cookies&quot; link just under the Send button) that made me believe my GET requests were correct.</p>
python|json|scrapy
0
1,907,963
31,251,293
How to download multiple files and images from a website using python
<p>So I am trying to download multiple files from a give a website and saving into a folder. I am trying to get highway data and in their website (<a href="http://www.wsdot.wa.gov/mapsdata/tools/InterchangeViewer/SR5.htm" rel="nofollow">http://www.wsdot.wa.gov/mapsdata/tools/InterchangeViewer/SR5.htm</a>) is a list of pdf links. I want to create a code that will extract the numerous pdfs found on their website. Maybe creating a loop that will go through the website and extract and save each file into a local folder onto my desktop.does anyone know how I can do that?</p>
<p>That's a problem that requires a coding solution. I can point you to some tools to use to accomplish this, but not a full code solution.</p> <p>Request Library: Communicating with HTTP Server (websites)</p> <p><a href="http://docs.python-requests.org/en/latest/" rel="nofollow">http://docs.python-requests.org/en/latest/</a></p> <p>BeautifulSoup: Html Parser (website source code parsing)</p> <p><a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; from bs4 import BeautifulSoup as BS &gt;&gt;&gt; &gt;&gt;&gt; response = requests.get('http://news.ycombinator.com') &gt;&gt;&gt; response.status_code # 200 == OK 200 &gt;&gt;&gt; &gt;&gt;&gt; soup = BS(response.text) # Create a html parsing object &gt;&gt;&gt; &gt;&gt;&gt; soup.title # Heres the browser title tag &lt;title&gt;Hacker News&lt;/title&gt; &gt;&gt;&gt; &gt;&gt;&gt; soup.title.text # The contents of the tag u'Hacker News' &gt;&gt;&gt; &gt;&gt;&gt; # Heres some article posts ... &gt;&gt;&gt; post_containers = soup.find_all('tr', attrs={'class':'athing'}) &gt;&gt;&gt; &gt;&gt;&gt; print 'There are %d article posts.' % len(post_containers) There are 30 article posts. &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; # The article name is the 3rd and last object in a post_container ... &gt;&gt;&gt; for container in post_containers: ... title = container.contents[-1] # The last tag ... title.a.text # Grab the `a` tag inside our titile tag, print the text ... u'Show HN: \u201cWho is hiring?\u201d Map' u'\u2018Flash Boys\u2019 Programmer in Goldman Case Prevails Second Time' u'Forthcoming OpenSSL releases' u'Show HN: YouTube Filesystem \u2013 YTFS' u'Google launches Uber rival RideWith' u'Finish your stuff' u'The Plan to Feed the World by Hacking Photosynthesis' u'New electric engine improves safety of light aircraft' u'Hacking Team hacked, attackers claim 400GB in dumped data' u'Show HN: Proof of concept \u2013 Realtime single page apps' u'Berkeley CS 61AS \u2013 Structure and Interpretation of Computer Programs, Self-Paced' u'An evaluation of Erlang global process registries: meet Syn' u'Show HN: Nearby Buzz \u2013\xa0Take control of your online reviews' u"The Grateful Dead's Wall of Sound" u'The Effects of Intermittent Fasting on Human and Animal Health' u'JsCoq' u'Taking stock of startup innovation in the Netherlands' u'Hangout: Becoming a freelance developer' u'Panning for Pangrams: The Search for the New Quick Brown Fox' u'Show HN: MUI \u2013 Lightweight CSS Framework for Material Design' u"Intel's 10nm 'Cannonlake' delayed, replaced by 14nm 'Kaby Lake'" u'VP of Logistics \u2013 EasyPost (YC S13) Hiring' u'Colorado\u2019s Effort Against Teenage Pregnancies Is a Startling Success' u'Lexical Scanning in Go (2011)' u'Avoiding traps in software development with systems thinking' u"Apache Cordova: after 10 months, I won't using it anymore" u'An exercise in profiling a Go program' u"The Science of Pixar's \u2018Inside Out\u2019" u'Ask HN: What tech blogs, podcasts do you follow outside of HN?' u'NASA\u2019s New Horizons Plans July 7 Return to Normal Science Operations' &gt;&gt;&gt; </code></pre>
python
3
1,907,964
31,329,062
error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool'
<p>I am passing a python module to C as a <code>PyObject</code>. I want to check to see if this value is NONE in my C code, using this form:</p> <pre><code>int func(PyObject tmp) { if(tmp) { // etc </code></pre> <p>I am getting the following error. How can I convert from a PyObject to boolean value, simillar to the way Python's if function behaves. It is worth noting that when <code>tmp</code> is a <code>boost::python::object</code> variable this command works as expected.</p> <pre><code>ex_program.cpp:72:7: error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool' if (tmp) ^~~ </code></pre>
<p><a href="https://docs.python.org/3/c-api/object.html#c.PyObject_IsTrue" rel="nofollow"><code>PyObject_IsTrue</code> seems to do what you want</a>:</p> <pre><code>int PyObject_IsTrue(PyObject *o) Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1. </code></pre>
python|c|python-c-api|pyobject
1
1,907,965
15,619,132
Anaconda Acclerate / NumbaPro CUDA Linking Error OSX
<p>Overall goal is to use <a href="http://docs.continuum.io/numbapro/index.html" rel="nofollow noreferrer">NumbaPro</a> to run some functions on the GPU (on OSX 10.8.3).</p> <p>Before starting, I just wanted to get everything set up. According to <a href="http://docs.continuum.io/numbapro/CUDASupport.html" rel="nofollow noreferrer">this page</a> I installed CUDA, registered as a CUDA developer, downloaded the Compiler SDK and set up the NUMBAPRO_NVVM=/path/to/libnvvm.dylib environment variable.</p> <p>However, running this basic test function:</p> <pre><code>from numbapro import autojit @autojit(target='gpu') def my_function(x): if x == 0.0: return 1.0 else: return x*x*x print my_function(4.4) exit() </code></pre> <p>Brings up this error:</p> <pre><code>File ".../anaconda/lib/python2.7/site-packages/numba/decorators.py", line 207, in compile_function compiled_function = dec(f) File "...lib/python2.7/site-packages/numbapro/cudapipeline/decorators.py", line 35, in _jit_decorator File "...lib/python2.7/site-packages/numbapro/cudapipeline/decorators.py", line 128, in __init__ File "...lib/python2.7/site-packages/numbapro/cudapipeline/environment.py", line 31, in generate_ptx File "...lib/python2.7/site-packages/numbapro/cudapipeline/environment.py", line 186, in _link_llvm_math_intrinsics KeyError: 1 </code></pre> <p>I've tried @vectorize'ing instead of autojit, same error. @autojit by itself with no target works fine.</p> <p>Any ideas?</p>
<p>For posterity's sake, I asked Continuum Support. They responded:</p> <blockquote> <p>It seems that you are running a CUDA GPU with compute capability 1.x. NVVM only supports CC2.0 and above. We definitely should have a better error reporting and make it clear in the NumbaPro documentation for the supported compute capability.</p> </blockquote>
python|gpu|jit|anaconda|numba-pro
5
1,907,966
59,610,716
Is there a way I can simplify this rectangle drawing code?
<p>I was wondering if this part of code can be simplified, it looks a bit repetitive</p> <pre><code>def show(self, W, screen): x = self.i * W y = self.j * W rect = pygame.Rect(x, y, W, W) pygame.draw.rect(screen, BG, rect) # TODO optimize this code if self.new: # TODO better popup animation rect.inflate(-50, -50) pygame.draw.rect(screen,(255, 255, 255), rect) rect.inflate(10, 10) pygame.draw.rect(screen, (255, 255, 255), rect) self.new = False else: if self.value == 2: pygame.draw.rect(screen, Sqr2, rect) elif self.value == 4: pygame.draw.rect(screen, Sqr4, rect) elif self.value == 8: pygame.draw.rect(screen, Sqr8, rect) elif self.value == 16: pygame.draw.rect(screen, Sqr16, rect) elif self.value == 32: pygame.draw.rect(screen, Sqr32, rect) elif self.value == 64: pygame.draw.rect(screen, Sqr64, rect) elif self.value == 128: pygame.draw.rect(screen, Sqr128, rect) elif self.value == 256: pygame.draw.rect(screen, Sqr256, rect) elif self.value == 512: pygame.draw.rect(screen, Sqr512, rect) elif self.value == 1024: pygame.draw.rect(screen, Sqr1024, rect) pygame.draw.rect(screen, BORDER, rect, 10) </code></pre> <p>Sqr2,4,8 ... are color tuples from another file that i've imported</p> <pre><code>Sqr2 = (245, 245, 245) Sqr4 = (245, 245, 220) Sqr8 = (255, 160, 122) Sqr16 = (255, 127, 80) Sqr32 = (255, 99, 71) Sqr64 = (255, 0, 0) Sqr128 = (255, 250, 96) Sqr256 = (240, 224, 80) Sqr512 = (240, 224, 16) Sqr1024 = (250, 208, 0) </code></pre>
<p>I'm not sure how you import the files - if you imported them in a <code>dict</code> it could be cleaner eg:</p> <pre><code>d = {2:(245,245,245),4:(245,245,220),...#etc} else: pygame.draw.rect(screen,d[self.value],rect) pygame.draw.rect(screen,BORDER,rect,10) </code></pre>
python|python-3.x|pygame|drawing|simplify
3
1,907,967
59,859,984
Search SVN for specific files
<p>I am trying to write a Python script to search a (very large) SVN repository for specific files (ending with .mat). Usually I would use os.walk() to walk through a directory and then search for the files with a RegEx. Unfortunately I can't use os.walk() for a repository, since it is not a local directory. </p> <p>Does anyone know how to do that? The repository is too large to download, so I need to search for it "online". </p> <p>Thanks in advance.</p>
<p>Something like</p> <p><code>svn ls -R REPO-ROOT | grep PATTERN</code></p> <p>will help</p>
python|svn
1
1,907,968
59,499,801
Python multipy file content
<p>I'm working on file contains a few lines of numerical sequences. I want to multiply some part of this string. How am I supposed to do it? When I just do 'num[10:](which is for ex 2)*4' (like below) it prints me '2' four times, I want to print 8.</p> <pre><code>import os from datetime import date with open('C:\\Users\\X\\Desktop\\python\\Y\\Z.txt') as file: numbers = file.readlines() def last_number(): for num in numbers: last = num[10:] x = last*4 print(x) last_number() </code></pre>
<p>When reading a file you read it in string format. In order to do math operations with the content you must convert it to an <code>int</code> or a <code>float</code>.</p> <p>Specifically if you know the exact location of the numbers in your code you should try this, notice i also sent <code>numbers</code> as a parameter for the function:</p> <pre><code>import os from datetime import date with open('C:\\Users\\X\\Desktop\\python\\Y\\Z.txt') as file: numbers = file.readlines() def last_number(numbers): # numbers = [int(num) for num in numbers] # prev line will create a list of numbers in integer form for you for num in numbers: last = int(num[10:]) x = last*4 print(x) last_number() </code></pre>
python|file|operating-system|numbers
1
1,907,969
59,528,176
How to run a Python code inside a custom package?
<p>I'm using Visual Studio Code.</p> <p>Suppose my folder looks like:</p> <pre><code>├── main.py └── package ├──__init__.py ├──utils.py └──method.py </code></pre> <p>In my <code>method.py</code>, I import the <code>utils.py</code>, which is in the same directory, so I put the dot before the name:</p> <pre class="lang-py prettyprint-override"><code>from .utils import * </code></pre> <p>then I can run the script in <code>main.py</code> like:</p> <pre class="lang-py prettyprint-override"><code>from package import method </code></pre> <p>This will work. But the question is, how I can run the script in <code>method.py</code> at its directory instead of importing it in <code>main.py</code>? If I run the script <code>method.py</code> directly, an error will occur:</p> <pre><code>ModuleNotFoundError: No module named '__main__.modules'; '__main__' is not a package </code></pre> <p>What can I do to run the script in <code>method.py</code> without removing the dot as <code>from utils import *</code>?</p>
<p>To make your code work, change the <code>import</code> statement in <code>method.py</code> from</p> <pre><code>from .utils import * </code></pre> <p>to</p> <pre><code>import __main__, os if os.path.dirname(__main__.__file__) == os.path.dirname(__file__): # executed script in this folder from utils import * else: # executed script from elsewhere from .utils import * </code></pre> <p>When <code>method.py</code> runs, it checks the folder that the executed python script is in, and if it's the same folder as itself, it will import <code>utils</code>, rather than <code>.utils</code>.</p> <p>You can achieve a similar thing using</p> <pre><code>if __name__=='__main__': </code></pre> <p>as your check. However, if <code>method.py</code> is imported by anther file inside the <code>package</code> folder, then <code>method.py</code> will try to import <code>.utils</code>, and won't be able to find it.</p>
python|python-3.x
2
1,907,970
59,886,279
sum values in dictionary - python 3
<p>Does anyone know why this simple code isn't working ? using IDEone compiler by the way <a href="https://i.stack.imgur.com/M4THj.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Please post your code in your question so it's more accessible for answerers!</p> <p>The problem here is <code>{dict}.values()</code> returns a list of lists which <code>sum()</code> doesn't work on. You can loop over the lists and sum those together. I wrote the following in ipython:</p> <pre><code>In [1]: test = {'A':[1,2,3],'B':[1,2,3],'C':[1,2,3]} In [2]: test.values() Out[2]: dict_values([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) In [3]: total = 0 In [4]: for val in test.values(): ...: total += sum(val) ...: In [5]: total Out[5]: 18 </code></pre>
python|dictionary|sum
0
1,907,971
48,922,447
Using a randomly shuffled batch as input to a CNN from a tensor of image data
<p>I am trying to train a network using STL-10 dataset.</p> <p>I have extracted the data from the STL-10 binary files and converted them into numpy arrays. Then i have converted them to tensors using <code>tf.convert_to_tensor</code> function</p> <p>Now I have a tensor of shape (5000,96,96,3)</p> <p>I want to get a batch of size 32 from this tensor containing data for 5000 images, and the batches will be randomly shuffled in each iteration.</p> <p>using <code>tf.train.batch</code> gives an error </p> <pre><code>`TypeError: `Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn.` </code></pre> <p>How to do i get a batch of image data of size 32, which will be randomly shuffled in each iteration?</p>
<p>From the docs of <code>tf.train.batch</code>:</p> <blockquote> <p>The argument tensors can be a list or a dictionary of tensors. The value returned by the function will be of the same type as tensors.</p> </blockquote> <p>You need to convert your data into a list of 5000 tensors, each of them shaped (96,96,3).</p>
python|tensorflow
1
1,907,972
48,982,185
How to create dataframe from Dict
<pre><code> @app.route('/patient') def patientData(): global patientData patientGuid = request.args.to_dict() df1 = pd.DataFrame([patientGuid]) #df1.to_csv("path.csv") return str(df1) if __name__ == "__main__": app.run() </code></pre> <p>But when save file it gives me output in single row json</p> <pre><code>[ { "PatientGuid": "0", "Gender": 1, "YearOfBirth": 1923 } ] </code></pre> <p>But i want save like this</p> <pre><code>PatientGuid Gender YearOfBirth 0 1 1923 </code></pre> <p>When give columns name</p> <pre><code>df1 = pd.DataFrame([patientGuid],columns=['PatientGuid','Gender','YearOfBirth']) </code></pre> <p>this save csv with only column names.</p>
<p>I think you need,</p> <pre><code> a=[ { "PatientGuid": "0", "Gender": 1, "YearOfBirth": 1923 } ] df=pd.DataFrame(a) print(df) [out]: Gender PatientGuid YearOfBirth 0 1 0 1923 </code></pre> <p>if you want to change the column names,</p> <pre><code> df.columns=["a","b","c"] print(df) a b c 0 1 0 1923 </code></pre>
python|pandas|dictionary|flask|request
1
1,907,973
48,935,422
How to start using Numpy
<p>I am trying to use NumPy. Specifically, to run:</p> <pre><code>import numpy as np lst = [[1, 2, 3], [4, 5, 6]] ary1d = np.array(1st) ary1d array([[1, 2, 3,], [4, 5, 6]]) </code></pre> <p>However, I am not sure whether this is code that is meant to be typed into the command terminal or IDLE. I have Conda and Pip installed. I have consulted multiple online and text references, however they do not provide guidance on where and how to use NumPy. The materials assume that the reader knows these things and skip over it, so I am having trouble solving the problem. My question is how do I use NumPy to effectively run the function above.</p> <p>Thanks in advance for your time and help! It is greatly appreciated.</p>
<p>First off, install NumPy:</p> <p><code>conda install numpy</code> or <code>pip install numpy</code> should work.</p> <p>Afterwards, you can use it either in an interactive session (using the <code>python</code> command, <code>ipython</code>, or an IDE like Spyder) or by putting it in a standard python file and running it. I personally like to use iPython just for playing around with a package like this.</p> <p>In the code snippet you posted in your question it looks like it has been run in an interactive python session, which can make it confusing what the input is and what the output is. Maybe this helps:</p> <pre><code>In [1]: import numpy as np In [2]: lst = [[1, 2, 3], ...: [4, 5, 6]] In [3]: ary1d = np.array(list) In [4]: ary1d Out[4]: array([[1, 2, 3], [4, 5, 6]]) </code></pre> <p>Specifically, that's what it looks like if I run the code in iPython. The last line starting with array() is just the interpreter printing out ary1d (since interactive interpreters print out the variable if you just input the variable itself). In a standard python file, the equivalent equivalent would be:</p> <pre><code>import numpy as np # Import NumPy lst = [[1, 2, 3], # Nested list of values [4, 5, 6]] ary1d = np.array(lst) # This defines a 2D 3x2 array from the values print(ary1d.__repr__()) # Print a string representation of the array. print(ary1d) also # works but prints a slightly different format </code></pre> <p>I hope this makes it a bit clearer.</p>
python|numpy
1
1,907,974
3,108,274
Generate "fuzzy" difference of two files in Python, with approximate comparison of floats
<p>I have an issue for comparing two files. Basically, what I want to do is a UNIX-like diff between two files, for example:</p> <p>$ diff -u left-file right-file</p> <p>However my two files contain floats; and because these files were generated on distinct architectures (but computing the same things), the floating values are not exactly the same (they may differ by, say, 1e-10). But what I seek by 'diffing' the files is to find what I consider to be significant differences (for example difference is more than 1e-4); while using the UNIX command diff, I get almost all my lines containing the floating values being different! That's my problem: how can I get a resulting diff like 'diff -u' provides, but with less restrictions regarding comparison of floats?</p> <p>I thought I would write a Python's script to do that, and found out the module difflib which provides diff-like comparison. But the documentation I found explains how to use it as-is (through a single method), and explains the inner objects, but I cannot find anything regarding how to customize a difflib object to meet my needs (like rewriting only the comparison method or such)... I guess a solution could be to retrieve the unified difference, and parse it 'manually' to remove my 'false' differences, by this is not elegant; I would prefer to use the already existing framework.</p> <p>So, does anybody know how to customize this lib so that I can do what I seek ? Or at least point me in the right direction... If not in Python, maybe a shell script could to the job?</p> <p>Any help would be greatly appreciated! Thanks in advance for your answers!</p>
<p>In your case we specialize the <a href="https://stackoverflow.com/questions/977491/comparing-2-txt-files-using-difflib-in-python">general case</a>: before we pass things into difflib, we need to detect and separately handle lines containing floats. Here is a basic approach, if you want to generate the deltas, lines of context etc you can build on this. Note it is easier to fuzzy-compare floats as actual floats rather than strings (although you could code a column-by-column differ, and ignore characters after 1-e4).</p> <pre><code>import re float_pat = re.compile('([+-]?\d*\.\d*)') def fuzzydiffer(line1,line2): """Perform fuzzy-diff on floats, else normal diff.""" floats1 = float_pat.findall(line1) if not floats1: pass # run your usual diff() else: floats2 = float_pat.findall(line2) for (f1,f2) in zip(floats1,floats2): (col1,col2) = line1.index(f1),line2.index(f2) if not fuzzy_float_cmp(f1,f2): print "Lines mismatch at col %d", col1, line1, line2 continue # or use a list comprehension like all(fuzzy_float_cmp(f1,f2) for f1,f2 in zip(float_pat.findall(line1),float_pat.findall(line2))) #return match def fuzzy_float_cmp(f1,f2,epsilon=1e-4): """Fuzzy-compare two strings representing floats.""" float1,float2 = float(f1),float(f2) return (abs(float1-float2) &lt; epsilon) </code></pre> <p>Some tests:</p> <pre><code>fuzzydiffer('text: 558.113509766 +23477547.6407 -0.867086648057 0.009291785451', 'text: 558.11351 +23477547.6406 -0.86708665 0.009292000001') </code></pre> <p>and as a bonus, here's a version that highlights column-diffs:</p> <pre><code>import re float_pat = re.compile('([+-]?\d*\.\d*)') def fuzzydiffer(line1,line2): """Perform fuzzy-diff on floats, else normal diff.""" floats1 = float_pat.findall(line1) if not floats1: pass # run your usual diff() else: match = True coldiffs1 = ' '*len(line1) coldiffs2 = ' '*len(line2) floats2 = float_pat.findall(line2) for (f1,f2) in zip(floats1,floats2): (col1s,col2s) = line1.index(f1),line2.index(f2) col1e = col1s + len(f1) col2e = col2s + len(f2) if not fuzzy_float_cmp(f1,f2): match = False #print 'Lines mismatch:' coldiffs1 = coldiffs1[:col1s] + ('v'*len(f1)) + coldiffs1[col1e:] coldiffs2 = coldiffs2[:col2s] + ('^'*len(f2)) + coldiffs2[col2e:] #continue # if you only need to highlight first mismatch if not match: print 'Lines mismatch:' print ' ', coldiffs1 print '&lt; ', line1 print '&gt; ', line2 print ' ', coldiffs2 # or use a list comprehension like # all() #return True def fuzzy_float_cmp(f1,f2,epsilon=1e-4): """Fuzzy-compare two strings representing floats.""" print "Comparing:", f1, f2 float1,float2 = float(f1),float(f2) return (abs(float1-float2) &lt; epsilon) </code></pre>
python|floating-point|fuzzy-comparison|inexact-arithmetic
4
1,907,975
2,842,214
RDF/XML format to JSON
<p>I am trying to convert the RDF/XML format to JSON format. Is there any python (library) example that i can look into for this to do ?</p>
<p>You can use <a href="http://www.rdflib.net/" rel="noreferrer">rdflib</a> to parse many RDF variants (including RDF/XML), or maybe the simpler <a href="http://infomesh.net/2003/rdfparser/" rel="noreferrer">rdfparser</a> if it suits your needs. You can then use the standard library Python <code>json</code> module (or equivalently third-party <code>simplejson</code> if you're using some Python version older than 2.6) to serialize the in-memory structure built with the parser into JSON. I'm not familiar with any package embodying both steps, unfortunately.</p> <p>With the example at rdfparser's site, the overall work would be just...:</p> <pre><code>import rdfxml import json class Sink(object): def __init__(self): self.result = [] def triple(self, s, p, o): self.result.append((s, p, o)) def rdfToPython(s, base=None): sink = Sink() return rdfxml.parseRDF(s, base=None, sink=sink).result s_rdf = someRDFstringhere() pyth = rdfToPython(s_rdf) s_jsn = json.dumps(pyth) </code></pre>
python|json|rdf|xml-parsing
9
1,907,976
2,461,853
How to parse the "<media:group>" using feedparser?
<p>The rss file is shown as below, i want to get the content in section <strong>media:group</strong> . I check the document of feedparser, but it seems not mention this. How to do it? Any help is appreciated. </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;rss xmlns:ymusic="http://music.yahoo.com/rss/1.0/ymusic/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"&gt;&lt;channel&gt; &lt;title&gt;XYZ InfoX: Special hello &lt;/title&gt; &lt;link&gt;http://www1.XYZInfoX.com/learninghello/home&lt;/link&gt; &lt;description&gt;hello&lt;/description&gt; &lt;language&gt;en&lt;/language&gt; &lt;copyright /&gt; &lt;pubDate&gt;Wed, 17 Mar 2010 08:50:06 GMT&lt;/pubDate&gt; &lt;dc:creator /&gt; &lt;dc:date&gt;2010-03-17T08:50:06Z&lt;/dc:date&gt; &lt;dc:language&gt;en&lt;/dc:language&gt; &lt;dc:rights /&gt; &lt;image&gt; &lt;title&gt;Voice of America&lt;/title&gt; &lt;link&gt;http://www1.XYZInfoX.com/learninghello&lt;/link&gt; &lt;url&gt;http://media.XYZInfoX.com/designimages/XYZRSSIcon.gif&lt;/url&gt; &lt;/image&gt; &lt;item&gt; &lt;title&gt;Who Were the Deadliest Gunmen of the Wild West?&lt;/title&gt; &lt;link&gt;http://www1.XYZInfoX.com/learninghello/home/Deadliest-Gunmen-of-the-Wild-West-87826807.html&lt;/link&gt; &lt;description&gt; The story of two of them: "Killin'" Jim Miller was an outlaw, "Texas" John Slaughter was a lawman | EXPLORATIONS &lt;/description&gt; &lt;pubDate&gt;Wed, 17 Mar 2010 00:38:48 GMT&lt;/pubDate&gt; &lt;guid isPermaLink="false"&gt;87826807&lt;/guid&gt; &lt;dc:creator&gt;&lt;/dc:creator&gt; &lt;dc:date&gt;2010-03-17T00:38:48Z&lt;/dc:date&gt; &lt;media:group&gt; &lt;media:content url="http://media.XYZInfoX.com/images/archives_peace_comm_480_16mar_se.jpg" medium="image" isDefault="true" height="300" width="480" /&gt; &lt;media:content url="http://media.XYZInfoX.com/images/archives_peace_comm_230_16mar_se_edited-1.jpg" medium="image" isDefault="false" height="230" width="230" /&gt; &lt;media:content url="http://media.XYZInfoX.com/images/tex_trans_lawmans_230_16mar10_se.jpg" medium="image" isDefault="false" height="230" width="230" /&gt; &lt;media:content url="http://www.XYZInfoX.com/MediaAssets2/learninghello/dalet/se-exp-outlaws-part2-17mar2010.Mp3" type="audio/mpeg" medium="audio" isDefault="false" /&gt; &lt;/media:group&gt; &lt;/item&gt; </code></pre>
<p>feedparser 4.1 as available from PyPi has this bug.</p> <p>the solution for me was to get the latest feedparser.py (4.2 pre) from the repository.</p> <pre><code>svn checkout http://feedparser.googlecode.com/svn/trunk/ feedparser-readonly cd feedparser-readonly python setup.py install </code></pre> <p>now you can access all mrss items</p> <pre><code>&gt;&gt;&gt; import feedparser # the new version! &gt;&gt;&gt; d = feedparser.parse(MY_XML_URL) &gt;&gt;&gt; for content in d.entries[0].media_content: print content['url'] </code></pre> <p>should do the job for you</p>
python|rss|feedparser
6
1,907,977
67,977,585
Clearing a Component on Callback in Dash
<p>So I have this dash app where I want to display a png image based on the user's input. It works, but the problem is every time the user makes a selection the image is shown on top of the previous image. I want to somehow clear the previous image so it only shows the most recently selected image.</p> <p>In <code>app.layout</code> I have:</p> <pre><code>app.layout = html.Div(children=[ html.H4(children='Spider Plot'), dcc.Dropdown(id=&quot;select_group&quot;, options=[ {&quot;label&quot;: &quot;Student&quot;, &quot;value&quot;: 'Student'}, {&quot;label&quot;: &quot;Parent&quot;, &quot;value&quot;: 'Parent'}, {&quot;label&quot;: &quot;Both&quot;, &quot;value&quot;: 'Both'}], multi=False, value=&quot;Student&quot;, style={'width': &quot;40%&quot;} ), html.Div(id=&quot;spider_img&quot;, children=[]), ]) </code></pre> <p>And for the callback I have:</p> <pre><code>@app.callback( Output(component_id='spider_img', component_property='children'), Input(component_id='select_group', component_property='value') ) def update_graph(group): key = (2002, group) A = perm_to_series(Ds.loc[key,'D'],Ds.loc[key,'details_fixed_cont_x_minimize']['perm'],'Closest') B = perm_to_series(Ds.loc[key,'D'],Ds.loc[key,'details_fixed_cont_x_maximize']['perm'],'Farthest') pyrankability.plot.spider2(A,B,file='/tmp/spider3.png') return html_image(open('/tmp/spider3.png','rb').read()) </code></pre> <p>I the function <code>html_image</code> is defined by me because apparently this is the way to insert static png images in dash.</p> <pre><code>def html_image(img_bytes): encoding = b64encode(img_bytes).decode() img_b64 = &quot;data:image/png;base64,&quot; + encoding return html.Img(src=img_b64, style={'height': '30%', 'width': '30%'}) </code></pre> <p>This does seem like a kind of hacky way to do things, and if there is a better way let me know, but this is the only thing that worked for me. So when looking for how to clear previous output I thought it would be simple, but I didn't really find much. There are posts that show how to clear a plot by clicking on it such as <a href="https://stackoverflow.com/questions/62954919/how-to-clear-dash-figure-with-callback">here</a> but that's not what I want, I just want the previous image to be cleared so they don't overlap. How can I clear my component so it displays properly?</p> <p>Edit: Here is the updated code using <code>html.Img</code> and <code>component_property='src'</code>:</p> <pre><code>app.layout = html.Div(children=[ html.H4(children='Spider Plot'), dcc.Dropdown(id=&quot;select_group&quot;, options=[ {&quot;label&quot;: &quot;Student&quot;, &quot;value&quot;: 'Student'}, {&quot;label&quot;: &quot;Parent&quot;, &quot;value&quot;: 'Parent'}, {&quot;label&quot;: &quot;Both&quot;, &quot;value&quot;: 'Both'}], multi=False, value=&quot;Student&quot;, style={'width': &quot;40%&quot;} ), html.Img(id=&quot;spider_img&quot;, style={'height': '30%', 'width': '30%'}) ]) @app.callback( Output(component_id='spider_img', component_property='src'), Input(component_id='select_group', component_property='value') ) def update_graph(group): key = (2002, group) A = perm_to_series(Ds.loc[key,'D'],Ds.loc[key,'details_fixed_cont_x_minimize']['perm'],'Closest') B = perm_to_series(Ds.loc[key,'D'],Ds.loc[key,'details_fixed_cont_x_maximize']['perm'],'Farthest') pyrankability.plot.spider2(A,B,file='/tmp/spider3.png') img = open('/tmp/spider3.png','rb').read() return &quot;data:image/png;base64,&quot; + base64.b64encode(img).decode() </code></pre>
<p>To update existing image you should use <code>html.Img(...)</code> instead of <code>html.Div(..., children=[])</code> in <code>app.layout</code>, and update <code>component_property='src'</code> instead of <code>component_property='children'</code></p> <hr /> <p>Many tools can save image/file in <code>file-like</code> object created in memory with <code>io.BytesIO()</code></p> <p>Example for <code>matplotlib</code></p> <pre><code> # plot something plt.plot(...) # create file-like object in memory buffer_img = io.BytesIO() # save in file-like object plt.savefig(buffer_img, format='png') # move to the beginning of buffer before reading (after writing) buffer_img.seek(0) # read from file-like object img_bytes = buffer_img.read() # create base64 img_encoded = &quot;data:image/png;base64,&quot; + base64.b64encode(img_bytes).decode() </code></pre> <hr /> <p>Minimal working code</p> <pre><code>import dash import dash_core_components as dcc import dash_html_components as html import base64 import io import matplotlib.pyplot as plt app = dash.Dash() app.layout = html.Div(children=[ html.H4(children='Spider Plot'), dcc.Dropdown(id=&quot;select_group&quot;, options=[ {&quot;label&quot;: &quot;Student&quot;, &quot;value&quot;: 'Student'}, {&quot;label&quot;: &quot;Parent&quot;, &quot;value&quot;: 'Parent'}, {&quot;label&quot;: &quot;Both&quot;, &quot;value&quot;: 'Both'}], multi=False, value=&quot;Student&quot;, style={'width': &quot;40%&quot;} ), html.Img(id=&quot;spider_img&quot;, style={'height': '30%', 'width': '30%'}), ]) @app.callback( dash.dependencies.Output(component_id='spider_img', component_property='src'), dash.dependencies.Input(component_id='select_group', component_property='value') ) def update_graph(group): # plot plt.clf() plt.text(5, 5, group, size=20) plt.xlim(0, 15) plt.ylim(0, 10) # create file-like object in memory buffer_img = io.BytesIO() # save in file-like object plt.savefig(buffer_img, format='png') # move to the beginning of buffer before reading (after writing) buffer_img.seek(0) # read from file-like object img_bytes = buffer_img.read() # create base64 img_encoded = &quot;data:image/png;base64,&quot; + base64.b64encode(img_bytes).decode() return img_encoded if __name__ == '__main__': app.run_server(debug=False) </code></pre>
python|plotly-dash
1
1,907,978
66,820,470
Is the setting of the vs_code wrong?
<p>I use python in visual studio code and, I wrote the code:</p> <pre><code>list_a = [10, 20, 30] list_a </code></pre> <p>Running, I expected:</p> <pre><code>[10, 20, 30] </code></pre> <p>But, in visual studio code, not working.</p> <p>This code is working:</p> <pre><code>print(list_a) [10, 20, 30] </code></pre> <p>What's the problem??</p>
<p>The first code was probably in a REPL or something like IDLE, where you get instant returning, without having to use print. VSCode is what you call a &quot;text editor&quot;, where it doesn't provide instant feedback without using <code>print</code>. Instead, text editors (and their bigger brothers, IDEs) are much more suited to professional development, where you have a butt-ton of code with a butt-ton of files. And in this context, VSCode blows everyone else out the water.</p> <p>If you still want a REPL, there are quite a few in the Marketplace, which you can get as extensions.</p>
python|visual-studio-code
0
1,907,979
65,534,826
How can I find the average of a value, that is nested within another list when one element is a string, and the other int? - Python
<p>I'm trying to get the average value of the second index in each list in the nested list, but have reached many error attempts so far. The data here is temporary, the user will input the data which makes up the master list. I need to output the average value of the integers here. For example the average would be 5.2 on this occasion. I am trying to get the sole number as output, and not a name associated with it.</p> <pre><code>master_list = [['Kevin', 10], ['Bob', 4], ['Alex', 1], ['Charles', 3], ['Robert', 4], ['David', 2], ['Kris', 5], ['Ben', 8], ['Paul', 6], ['Ben', 9]] </code></pre>
<p>Using a list comprehension and pythons inbuilt <code>sum</code> and <code>len</code> functions:</p> <pre class="lang-py prettyprint-override"><code>sum([a[1] for a in master_list])/len(master_list) </code></pre>
python|python-3.x
1
1,907,980
50,954,589
Pandas rolling corr with no overlap
<p>I have several series of price returns and I would like to calculate the rolling N days correlation in such a way that there is no overlap between dates, i.e, if my first correlation matrix belongs to [2000-04-05 - 2000-06-04], the next correlation matrix should belong to [2000-06-05 - 2000-08-04]. Using the conventional df.rolling(window=window).corr(df, pairwise=True) would return overlapping dates.</p> <p>I'm aware that slicing the result from the rolling approach would give me what I want, but that means we're using time to compute correlations that I won't use, resulting in a waste of resources.</p> <p>Any suggestions?</p> <p>UPDATE:</p> <p>This is a sample of what the input looks like:</p> <p><a href="https://i.stack.imgur.com/9Yp2F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Yp2F.png" alt="enter image description here"></a></p> <p>UPDATE 2:</p> <pre><code>outputs for pd.show_versions() INSTALLED VERSIONS ------------------ commit: None python: 3.6.3.final.0 python-bits: 64 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6 Model 63 Stepping 2, GenuineIntel byteorder: little LC_ALL: None LANG: en LOCALE: None.None pandas: 0.20.3 pytest: 3.2.1 pip: 9.0.1 setuptools: 36.5.0.post20170921 Cython: 0.26.1 numpy: 1.14.5 scipy: 0.19.1 xarray: None IPython: 6.1.0 sphinx: 1.6.3 patsy: 0.4.1 dateutil: 2.6.1 pytz: 2017.2 blosc: None bottleneck: 1.2.1 tables: 3.4.2 numexpr: 2.6.2 feather: None matplotlib: 2.1.0 openpyxl: 2.4.8 xlrd: 1.1.0 xlwt: 1.3.0 xlsxwriter: 1.0.2 lxml: 4.1.0 bs4: 4.6.0 html5lib: 0.999999999 sqlalchemy: 1.1.13 pymysql: None psycopg2: None jinja2: 2.9.6 s3fs: None pandas_gbq: None pandas_datareader: None </code></pre>
<h1><code>resample</code></h1> <p>You can use <code>pd.DataFrame.resample</code> to specify a time rule of 20 days with <code>"20D"</code>. Use the <code>on</code> argument to specify the column that is to be resampled. The resulting <code>resample</code> object is similar to the <code>groupby</code> object and can handle an <code>apply</code> method.</p> <pre><code>def dcorr(df, n): return df.resample(f"{n}D", on='date').apply(lambda d: d.corr()) dcorr(df, 20) A B date 2000-01-01 A 1.000000 0.241121 B 0.241121 1.000000 2000-01-21 A 1.000000 0.083664 B 0.083664 1.000000 2000-02-10 A 1.000000 0.432988 B 0.432988 1.000000 2000-03-01 A 1.000000 -0.269869 B -0.269869 1.000000 2000-03-21 A 1.000000 -0.188370 B -0.188370 1.000000 </code></pre> <hr> <h1><code>groupby</code></h1> <pre><code>df.set_index('date').groupby(pd.Grouper(freq='20D')).corr() A B date 2000-01-01 A 1.000000 0.241121 B 0.241121 1.000000 2000-01-21 A 1.000000 0.083664 B 0.083664 1.000000 2000-02-10 A 1.000000 0.432988 B 0.432988 1.000000 2000-03-01 A 1.000000 -0.269869 B -0.269869 1.000000 2000-03-21 A 1.000000 -0.188370 B -0.188370 1.000000 </code></pre> <p>Or</p> <pre><code>df.set_index('date').groupby(pd.Grouper(freq='20D')).corr().unstack()[('A', 'B')] date 2000-01-01 0.241121 2000-01-21 0.083664 2000-02-10 0.432988 2000-03-01 -0.269869 2000-03-21 -0.188370 Name: (A, B), dtype: float64 </code></pre> <hr> <p>You can also be explicit about the columns you want to correlate:</p> <pre><code>df.resample("20D", on='date').apply(lambda d: d.A.corr(d.B)) </code></pre> <h2>Setup</h2> <pre><code>np.random.seed([3, 1415]) n = 100 df = pd.DataFrame(np.random.rand(n,2), columns=['A','B']) df['date'] = pd.date_range('2000-01-01', periods=n, name='date') </code></pre> <hr> <h2>DEBUGGING</h2> <pre><code>import pandas as pd import numpy as np np.random.seed([3, 1415]) n = 100 df = pd.DataFrame( np.random.rand(n, 4), pd.date_range('2000-01-01', periods=n, name='date'), ['ABC','XYZ __', 'One', 'Two Three'] ) def dcorr(df, n): return df.resample(f"{n}D").apply(lambda d: d.corr()) dcorr(df, 20) </code></pre> <h2>OUTPUT</h2> <pre><code> ABC XYZ __ One Two Three date 2000-01-01 ABC 1.000000 -0.029687 0.403720 0.078800 XYZ __ -0.029687 1.000000 -0.231223 -0.333266 One 0.403720 -0.231223 1.000000 0.330959 Two Three 0.078800 -0.333266 0.330959 1.000000 2000-01-21 ABC 1.000000 -0.024610 0.206002 -0.059523 XYZ __ -0.024610 1.000000 -0.601174 -0.101306 One 0.206002 -0.601174 1.000000 0.149536 Two Three -0.059523 -0.101306 0.149536 1.000000 2000-02-10 ABC 1.000000 -0.361072 0.156693 -0.040827 XYZ __ -0.361072 1.000000 -0.077173 -0.232536 One 0.156693 -0.077173 1.000000 0.343754 Two Three -0.040827 -0.232536 0.343754 1.000000 2000-03-01 ABC 1.000000 0.204763 -0.013132 0.115202 XYZ __ 0.204763 1.000000 -0.339747 -0.206922 One -0.013132 -0.339747 1.000000 0.310002 Two Three 0.115202 -0.206922 0.310002 1.000000 2000-03-21 ABC 1.000000 0.062841 -0.245393 0.233697 XYZ __ 0.062841 1.000000 -0.213742 0.341582 One -0.245393 -0.213742 1.000000 0.251169 Two Three 0.233697 0.341582 0.251169 1.000000 </code></pre>
python|pandas|correlation
7
1,907,981
50,897,022
Trouble finding element
<p>I am very new to coding and I am trying to make a form filler on Nike.com using the Selenium Chrome webdriver. However, a pop-up comes up about cookied and I am finding it hard to remove it so I can fill out the form. <a href="https://i.stack.imgur.com/ZeQ3w.png" rel="nofollow noreferrer">This is what it looks like</a> and my code looks like this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys import time #Initialise a chrome browser and return it def initialisebrowser(): browser=webdriver.Chrome(r'''C:\Users\ben_s\Downloads\chromedriver''') return browser #Pass in the browser and url, and go to the url with the browser def geturl(browser, url): browser.get(url) #Initialise the browser (and store the returned browser) browser = initialisebrowser() #Go to a url(nike.com) with the browser geturl(browser,"https://www.nike.com/gb/en_gb/s/register") button = browser.find_element_by_class_name("nsg-button.nsg-grad--nike-orange.yes-button.cookie-settings-button.js-yes-button") button.click() </code></pre> <p>When I run this code, I get this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\ben_s\Desktop\Nike Account Generator.py", line 19, in &lt;module&gt; button = browser.find_element_by_class_name("nsg-button.nsg-grad--nike-orange.yes-button.cookie-settings-button.js-yes-button") File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 557, in find_element_by_class_name return self.find_element(by=By.CLASS_NAME, value=name) File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 957, in find_element 'value': value})['value'] File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute self.error_handler.check_response(response) File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"nsg-button.nsg-grad--nike-orange.yes-button.cookie-settings-button.js-yes-button"} (Session info: chrome=67.0.3396.87) (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64) </code></pre> <p>Any ideas, pointers or solutions to the problem are much apprieciated</p>
<p>use <code>time.sleep</code> to wait until the popup will load, and after that you can use <code>cookie-settings-button-container</code> class that is parrent of the <code>btn</code> this will work.</p> <pre><code>time.sleep(1) button = browser.find_element_by_class_name("cookie-settings-button-container") button.click() </code></pre>
python|selenium|selenium-webdriver|selenium-chromedriver
0
1,907,982
51,012,221
tkinter freezing with pywinauto import
<p><strong>Issue:</strong><br/> My python gui (tkinter) is freezing when I click a button that runs:<br> <code>filename = filedialog.askdirectory()</code> <br> This <em>only</em> happens when I have <code>from pywinauto import application</code> in another script. If I comment out the pywinauto import, askdirectory works just fine. No freezing, the window pops up as expected. I do not see any errors when this happens.</p> <p>Sorry for the long post btw, I wanted to provide as much detail as possible. Let me know if more is needed and what it is you're looking for. I would ideally like to use askdirectory, but I've thought that I could maybe just use askopenfilename and get the directory off of that.</p> <p><strong>Python version:</strong><br/> Python 3.4.4</p> <p><strong>Windows version:</strong><br /> Windows Server 2012 R2 (Can't change this)</p> <p><strong>Things I've tried:</strong> <br /> 1. Basic Threading via tutorials (still froze every time, code example at bottom) <br /> 2. Commenting out sections of code to narrow problem down. <br/> 3. Tried going through with PyCharms debugger, but if there is an error, I'm not seeing it.<br /> 4. Different IDE. <br /> <li>IDLE = fail</li> <li>Pycharm = fail(same interpreter as idle from what I can tell, so no surprise)</li> <li>Pythonwin = works just fine)</li> <br /></p> <p><strong>Code blocks below:</strong><br /> I have put the code blocks below in order of how they interact if you will. It starts at the first one, then goes to the second(middle) one, which finally goes to the third.</p> <p><strong>Questions:</strong><br /> Is there a way for me to check for an error? Have I done something wrong here that is causing this to happen? Why would askopenfilename work fine but not askdirectory?</p> <p><strong>File containing the window that freezes:</strong></p> <pre><code>from InstallMenu import MainMenu from tkinter import * from tkinter import filedialog """ This is where it freezes. If I change askdirectory to openaskfilename it works without any issues. If I comment out the from pywinauto import application from opusite.py, askdirectory works without issue. """ def chooseInstallFolder(installFolderPath): filename = filedialog.askdirectory() installFolderPath.config(text=filename) def submitFolder(installFolderApp, installFolderPath, setObj): installFolderApp.destroy() MainMenu(installFolderPath, setObj) def chooseInstall(setObj): installFolderApp = Tk() installFolderApp.title("Find Install Folder") installFolderApp.geometry("300x200") #Gui items pickAFolder = Label(installFolderApp, text = "Select your Install Folder") pickInstallerButton = Button(installFolderApp, text="Browse", command = lambda : chooseInstallFolder(installFolderPath)) installFolderPath = Label(installFolderApp, text = " ") submit = Button(installFolderApp, text="Submit", command = lambda : submitFolder(installFolderApp, installFolderPath, setObj)) #Packing pickAFolder.pack() installFolderPath.pack() pickInstallerButton.pack() submit.pack() installFolderApp.mainloop() </code></pre> <p><strong>The menu script the submit button above goes to:</strong><br /> I have iParcPro commented out because it uses the same import causing the freeze.</p> <pre><code>import opusite #from iParcPro import * from Sql import * from tkinter import * def OPUSiteInstall(installFolderPath): opusite.OPUSiteInstall(installFolderPath, setObj) opusite.rs485Install(installFolderPath, setObj) def MainMenu(installFolderPath, setObj): menuWindow = Tk() menuWindow.title("Auto Installer Menu") menuWindow.geometry("325x250") #Create variables ChooseAButton = Label(menuWindow, text = "Choose an option") OPUSiteButton = Button(menuWindow, text="OPUSite Install", height = 1, width = 15, command = lambda : OPUSiteInstall(installFolderPath, setObj)) #Pack ChooseAButton.pack() OPUSiteButton.pack() menuWindow.mainloop() </code></pre> <p><strong>Code containing the import that seems to freeze this:</strong></p> <pre><code>import pyautogui as ag """ This import here freezes it. If I comment out just the import, the askdirectory works fine. """ from pywinauto import application def OPUSiteInstall(installFolderPath, setObj): path = installFolderPath + '\\OPUSite\\AMI.OPUSite.Setup.msi' app = application.Application().Start(r'msiexec.exe /i ' + path) Wizard = app['OPUSite Setup'] Wizard.NextButton.Wait('enabled', 50000) Wizard.NextButton.Click() Wizard['I &amp;accept the terms in the License Agreement'].Wait('enabled').CheckByClick() Wizard.NextButton.Click() Wizard.NextButton.Click() ag.typewrite(setObj.databaseName) ag.press('tab') ag.press('space') ag.press('tab') ag.press('tab') ag.typewrite(setObj.password) ag.press('tab') ag.typewrite(setObj.password) ag.press('tab') ag.typewrite(setObj.password) Wizard.NextButton.Click() Wizard.Install.Click() Wizard.Finish.Wait('visible', 50000) Wizard.Finish.Click() def rs485Install(installFolderPath, setObj): path = installFolderPath + '\\OPUSite\\AMI.RS485AdapterSvc.Setup.msi' app = application.Application().Start(r'msiexec.exe /i ' + path) Wizard = app['RS485Adapter Setup'] Wizard.NextButton.Wait('enabled', 50000) Wizard.NextButton.Click() Wizard['I &amp;accept the terms in the License Agreement'].Wait('enabled').CheckByClick() Wizard.NextButton.Click() Wizard.NextButton.Click() Wizard.Install.Click() Wizard.Finish.Wait('visible', 50000) Wizard.Finish.Click() </code></pre> <p><strong>This is the threading thing I tried. It didn't work:</strong></p> <pre><code>from InstallMenu import MainMenu from tkinter import * from tkinter import filedialog import threading def chooseInstallFolder(installFolderPath): def callback(installFolderPath): filename = filedialog.askdirectory() installFolderPath.config(text=filename) t = threading.Thread(target=callback, args=(installFolderPath,)) t.start() def submitFolder(installFolderApp, installFolderPath, setObj): installFolderApp.destroy() MainMenu(installFolderPath, setObj) def chooseInstall(setObj): installFolderApp = Tk() installFolderApp.title("Find Install Folder") installFolderApp.geometry("300x200") #Gui items pickAFolder = Label(installFolderApp, text = "Select your Install Folder") pickInstallerButton = Button(installFolderApp, text="Browse", command = lambda : chooseInstallFolder(installFolderPath)) installFolderPath = Label(installFolderApp, text = " ") submit = Button(installFolderApp, text="Submit", command = lambda : submitFolder(installFolderApp, installFolderPath, setObj)) #Packing pickAFolder.pack() installFolderPath.pack() pickInstallerButton.pack() submit.pack() installFolderApp.mainloop() </code></pre>
<p>I was able to get past this problem. I want to point out that I'm still not sure why this worked. All I did was move the pywinauto import into my functions and now the askdirectory is working fine.</p> <pre><code>import pyautogui as ag def OPUSiteInstall(installFolderPath, setObj): from pywinauto import application path = installFolderPath + '\\OPUSite\\AMI.OPUSite.Setup.msi' app = application.Application().Start(r'msiexec.exe /i ' + path) Wizard = app['OPUSite Setup'] Wizard.NextButton.Wait('enabled', 50000) Wizard.NextButton.Click() Wizard['I &amp;accept the terms in the License Agreement'].Wait('enabled').CheckByClick() Wizard.NextButton.Click() Wizard.NextButton.Click() ag.typewrite(setObj.databaseName) ag.press('tab') ag.press('space') ag.press('tab') ag.press('tab') ag.typewrite(setObj.password) ag.press('tab') ag.typewrite(setObj.password) ag.press('tab') ag.typewrite(setObj.password) Wizard.NextButton.Click() Wizard.Install.Click() Wizard.Finish.Wait('visible', 50000) Wizard.Finish.Click() def rs485Install(installFolderPath, setObj): from pywinauto import application path = installFolderPath + '\\OPUSite\\AMI.RS485AdapterSvc.Setup.msi' app = application.Application().Start(r'msiexec.exe /i ' + path) Wizard = app['RS485Adapter Setup'] Wizard.NextButton.Wait('enabled', 50000) Wizard.NextButton.Click() Wizard['I &amp;accept the terms in the License Agreement'].Wait('enabled').CheckByClick() Wizard.NextButton.Click() Wizard.NextButton.Click() Wizard.Install.Click() Wizard.Finish.Wait('visible', 50000) Wizard.Finish.Click() ` </code></pre>
python-3.x|tkinter|freeze|pywinauto
3
1,907,983
50,759,770
remove audio from mp4 file ffmpeg
<p>I am on a Mac using Python 3.6. I am trying to remove audio from an mp4 file using ffmpeg but unfortunately it does not give me the "silenced" mp4 file I look for. Code I use is:</p> <pre><code>ffmpeg_extract_audio("input_file.mp4", "output_file.mp4", bitrate=3000, fps=44100) </code></pre> <p>It gives me a new output file with a low-quality video image, but still the audio. Any suggestion?</p>
<p>ok thank you @sascha. I finally put all my mp4 files in the same folder and run the following code: </p> <pre><code>for file in *.mp4; do ffmpeg -i "$file" -c copy -an "noaudio_$file"; done </code></pre> <p>If, like me, one uses Sublime Text or any other text editor (already using Python language), it run with the following:</p> <pre><code>import subprocess command = 'for file in *.mp4; do ffmpeg -i "$file" -c copy -an "noaudio_$file"; done' subprocess.call(command, shell=True) </code></pre>
python-3.x|ffmpeg|moviepy
4
1,907,984
3,295,322
Django, PIP, and Virtualenv
<p>Got this django project that I assume would run on virtualenv. I installed virtualenv through pip install and created the env but when I try to feed the pip requirements file, I got this:</p> <pre><code>Directory 'tagging' is not installable. File 'setup.py' not found. Storing complete log in /Users/XXXX/.pip/pip.log </code></pre> <p>Here's the entry on the log file:</p> <pre><code>------------------------------------------------------------ /Users/XXXX/Sites/SampleProject/bin/pip run on Wed Jul 21 06:35:02 2010 Directory 'tagging' is not installable. File 'setup.py' not found. Exception information: Traceback (most recent call last): File "/Users/XXXX/Sites/SampleProject/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg/pip/basecommand.py", line 120, in main self.run(options, args) File "/Users/XXXX/Sites/SampleProject/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg/pip/commands/install.py", line 158, in run for req in parse_requirements(filename, finder=finder, options=options): File "/Users/XXXX/Sites/SampleProject/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg/pip/req.py", line 1395, in parse_requirements req = InstallRequirement.from_line(line, comes_from) File "/Users/XXXX/Sites/SampleProject/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg/pip/req.py", line 87, in from_line % name) InstallationError: Directory 'tagging' is not installable. File 'setup.py' not found. </code></pre> <p>Also, here's the requirements file I'm trying to feed:</p> <pre><code># to use: # mkvirtualenv %PROJECT% (or workon %PROJECT%) # export PIP_RESPECT_VIRTUALENV=true # pip install -r requirements.txt # you'll also need: # mongodb1.1.4 # imagemagick &gt; 6.3.8 # -e svn+http://code.djangoproject.com/svn/django/trunk#egg=djangoipython ipdb PIL django-extensions django-debug-toolbar pytz tagging </code></pre> <p>Could it be a problem with PIP? I have installed it through easy_install and used it already to install some modules such as fabric and etc. with no problems.</p> <p>Hope someone could lend a hand :) BTW, here's my local setup: OSX 10.6.4, Python 2.6.1, Django 1.3 alpha. Thanks!</p>
<p>Sounds like you have a tagging/ directory in the directory from which you are running pip, and pip thinks this directory (rather than the django-tagging project on PyPI) is what you want it to install. But there's no setup.py in that directory, so pip doesn't know how to install it.</p> <p>If the name of the project you wanted to install from PyPI were actually "tagging", you'd need to move or rename the tagging/ directory, or else run pip from a different directory. But it's not; it's actually django-tagging: <a href="http://pypi.python.org/pypi/django-tagging" rel="nofollow noreferrer">http://pypi.python.org/pypi/django-tagging</a> So if you just change the entry in your requirements file from "tagging" to "django-tagging," it should work.</p> <p>All of this is a bug in pip, really: it should assume something is a PyPI project name rather than a local directory, unless the name you give has an actual slash in it or appended to it.</p>
python|django|setup-project|virtualenv|pip
3
1,907,985
64,648,237
How to convert this numpy one-liner into Tensorflow backend code?
<p>I have multiple depthmaps which show a car from different angles. I need to calculate how well they match together in my loss function, so I have to reproject them into a different view. The depthmaps live in a cube that is relative to the length of the vehicle. The images have the shape (256,256). I already wrote the code to convert them to a pointcloud with backend functions (256*256,3). I can reproject this pointcloud to the side view with numpy like this:</p> <pre><code>reProj = np.zeros((256, 256), np.float32) reProj[pointCloud[:, 1], pointCloud[:, 2]] = pointCloud[:, 0] </code></pre> <p>How can I convert this into keras backend code? I suspect there should be a gather somewhere in there, but I just cannot get it working.</p> <p><strong>Example:</strong></p> <p><strong>Source depth image:</strong></p> <p><a href="https://i.stack.imgur.com/4rAUC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4rAUC.png" alt="enter image description here" /></a></p> <p><strong>Reprojected:</strong></p> <p><a href="https://i.stack.imgur.com/NYRnn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NYRnn.png" alt="enter image description here" /></a></p> <p>Thanks for your help!</p> <p>Edit: Minimal working example with data: <a href="https://easyupload.io/rwutwa" rel="nofollow noreferrer">https://easyupload.io/rwutwa</a></p>
<p>You can do this by using <code>tf.matmul()</code> the first input will be your pointcloud, from the dimensions i am assuming you are storing for every pixel a 3d vector x,y,z. The second input will be the 3d rotation matrix coresponding to the projection you need, keep in mind this works for every angle you want to you just need to define the 3x3 matrix.</p> <p>If i understand correctly your data you need to rotate over x 90 degrees so the matrix would be</p> <pre><code>1 0 0 0 0 -1 0 1 0 </code></pre> <p>read more on rotation matrices here <a href="https://en.wikipedia.org/wiki/Rotation_matrix" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Rotation_matrix</a> just go to the tree dimension and see what you need</p>
numpy|tensorflow|keras|backend|loss
0
1,907,986
61,277,164
Scrape Tables on Multiple Pages with Single URL
<p>I am trying to scrape data from Fangraphs. The tables are split into 21 pages but all of the pages use the same url. I am very new to webscraping (or python in general), but Fangraphs does not have a public API so scraping the page seems to be my only option. I am currently using BeautifulSoup to parse the HTML code and I am able to scrape the initial table, but that only contains the first 30 players, but I want the entire player pool. Two days of web searching and I am stuck. Link and my current code are below. I know they have a link to download the csv file, but that gets tedious through out the season and I would like expedite the data harvesting process. Any direction would be helpful, thank you.</p> <p><a href="https://www.fangraphs.com/projections.aspx?pos=all&amp;stats=bat&amp;type=fangraphsdc" rel="nofollow noreferrer">https://www.fangraphs.com/projections.aspx?pos=all&amp;stats=bat&amp;type=fangraphsdc</a></p> <pre><code>import requests import pandas as pd url = 'https://www.fangraphs.com/projections.aspx?pos=all&amp;stats=bat&amp;type=fangraphsdc&amp;team=0&amp;lg=all&amp;players=0' response = requests.get(url, verify=False) # Use BeautifulSoup to parse the HTML code soup = BeautifulSoup(response.content, 'html.parser') # changes stat_table from ResultSet to a Tag stat_table = stat_table[0] # Convert html table to list rows = [] for tr in stat_table.find_all('tr')[1:]: cells = [] tds = tr.find_all('td') if len(tds) == 0: ths = tr.find_all('th') for th in ths: cells.append(th.text.strip()) else: for td in tds: cells.append(td.text.strip()) rows.append(cells) # convert table to df table = pd.DataFrame(rows) </code></pre>
<pre class="lang-py prettyprint-override"><code>import requests from bs4 import BeautifulSoup import pandas as pd params = { "pos": "all", "stats": "bat", "type": "fangraphsdc" } data = { 'RadScriptManager1_TSM': 'ProjectionBoard1$dg1', "__EVENTTARGET": "ProjectionBoard1$dg1", '__EVENTARGUMENT': 'FireCommand:ProjectionBoard1$dg1$ctl00;PageSize;1000', '__VIEWSTATEGENERATOR': 'C239D6F0', '__SCROLLPOSITIONX': '0', '__SCROLLPOSITIONY': '1366', "ProjectionBoard1_tsStats_ClientState": "{\"selectedIndexes\":[\"0\"],\"logEntries\":[],\"scrollState\":{}}", "ProjectionBoard1_tsPosition_ClientState": "{\"selectedIndexes\":[\"0\"],\"logEntries\":[],\"scrollState\":{}}", "ProjectionBoard1$rcbTeam": "All+Teams", "ProjectionBoard1_rcbTeam_ClientState": "", "ProjectionBoard1$rcbLeague": "All", "ProjectionBoard1_rcbLeague_ClientState": "", "ProjectionBoard1_tsProj_ClientState": "{\"selectedIndexes\":[\"5\"],\"logEntries\":[],\"scrollState\":{}}", "ProjectionBoard1_tsUpdate_ClientState": "{\"selectedIndexes\":[],\"logEntries\":[],\"scrollState\":{}}", "ProjectionBoard1$dg1$ctl00$ctl02$ctl00$PageSizeComboBox": "30", "ProjectionBoard1_dg1_ctl00_ctl02_ctl00_PageSizeComboBox_ClientState": "", "ProjectionBoard1$dg1$ctl00$ctl03$ctl01$PageSizeComboBox": "1000", "ProjectionBoard1_dg1_ctl00_ctl03_ctl01_PageSizeComboBox_ClientState": "{\"logEntries\":[],\"value\":\"1000\",\"text\":\"1000\",\"enabled\":true,\"checkedIndices\":[],\"checkedItemsTextOverflows\":false}", "ProjectionBoard1_dg1_ClientState": "" } def main(url): with requests.Session() as req: r = req.get(url, params=params) soup = BeautifulSoup(r.content, 'html.parser') data['__VIEWSTATE'] = soup.find("input", id="__VIEWSTATE").get("value") data['__EVENTVALIDATION'] = soup.find( "input", id="__EVENTVALIDATION").get("value") r = req.post(url, params=params, data=data) df = pd.read_html(r.content, attrs={ 'id': 'ProjectionBoard1_dg1_ctl00'})[0] df.drop(df.columns[1], axis=1, inplace=True) print(df) df.to_csv("data.csv", index=False) main("https://www.fangraphs.com/projections.aspx") </code></pre> <p>Output: <a href="http://www.sharecsv.com/s/e9e723ec27a035a3bf5e8a3721e598f9/data.csv" rel="nofollow noreferrer">view-online</a></p> <p><a href="https://i.stack.imgur.com/BOYam.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BOYam.png" alt="enter image description here"></a></p>
python|url|web-scraping|beautifulsoup
1
1,907,987
61,577,806
Python 3 tkinter login program
<p>I've recently created a tkinter program to Login to a dice game. The game isn't created yet, as I've had problems logging in. The file made when using register seems to be read differently when logging in? I put the exact same things in, which aren't recognized. Thanks for any help, I'm new to stack-overflow so I don't really know how to use this site.</p> <pre><code>from tkinter import * def register_user(): username_info = username.get() password_info = password.get() file=open(username_info+".txt", "w") file.write(username_info+"\n") file.write(password_info) file.close() username_entry.delete(0, END) password_entry.delete(0, END) Label(screen1, text = "Registration Sucess", fg = "green" ,font = ("Ariel", 11)).pack() screen1.after(1000, lambda: screen1.destroy()) def register(): global screen1 screen1 = Toplevel(screen) screen1.title("Register") screen1.geometry("300x250") global username global password global username_entry global password_entry username = StringVar() password = StringVar() Label(screen1, text = "Please enter details below to register:").pack() Label(screen1, text = "").pack() Label(screen1, text = "Username * ").pack() username_entry = Entry(screen1, textvariable = username) username_entry.pack() Label(screen1, text = "Password * ").pack() password_entry = Entry(screen1, textvariable = password) password_entry.pack() Label(screen1, text = "").pack() Button(screen1, text = "Register", bg = "white", width = 10, height = 1, command = register_user).pack() def login_user(): username_info = username.get() password_info = password.get() file=open(username_info+".txt", "r") #&lt;-------------- This is the part that doesnt work lines = file.readlines() # It should recognise the username and it's corresponding file, and put login success, then close a = lines[0] b = lines[1] if a == username_entry and b == password_entry: Label(screen2, text = "Login Sucess", fg = "green" ,font = ("Ariel", 11)).pack() screen2.after(1000, lambda: screen2.destroy()) else: Label(screen2, text = "Login Failure. Please Try Again.", fg = "red", font = ("Ariel", 11)).pack() def login(): global screen2 screen2 = Toplevel(screen) screen2.title("Login") screen2.geometry("300x250") global username global password global username_entry global password_entry username = StringVar() password = StringVar() Label(screen2, text = "Please enter login details below:").pack() Label(screen2, text = "").pack() Label(screen2, text = "Username * ").pack() username_entry = Entry(screen2, textvariable = username) username_entry.pack() Label(screen2, text = "Password * ").pack() password_entry = Entry(screen2, textvariable = password) password_entry.pack() Label(screen2, text = "").pack() Button(screen2, text = "Login", bg = "white", width = 10, height = 1, command = login_user).pack() def main_screen(): global screen screen = Tk() screen.geometry("300x250") screen.title("Welcome!") Label(text = "Welcome to James' Dice Game!", bg = "lightskyblue", width = "300", height = "2", font = ("Ariel", 12)).pack() Label(text = "").pack() Button(text = "Login", bg = "white", height = "2", width = "30", command = login).pack() Label(text = "").pack() Button(text = "Register", bg = "white", height = "2", width = "30", command = register).pack() screen.mainloop() main_screen() </code></pre>
<p>Your problem is with the <code>a = lines[0]</code> variable. When I tested <code>print(lines)</code> I ended up with <code>['user\n', 'password']</code> instead of the intended <code>['user', 'password']</code>. So far, the easiest solution I've come up with is this:</p> <pre><code> file=open(username_info+".txt", "r") #&lt;-------------- This is the part that doesnt work lines = file.readlines() # It should recognise the username and it's corresponding file, and put login success, then close name = lines[0] &lt;--- # added name variable a = name[:-1] &lt;--- # then just removed the unwanted part of the string being passed to 'a' b = lines[1] if a == username_entry and b == password_entry: Label(screen2, text = "Login Sucess", fg = "green" ,font = ("Ariel", 11)).pack() screen2.after(1000, lambda: screen2.destroy()) else: Label(screen2, text = "Login Failure. Please Try Again.", fg = "red", font = ("Ariel", 11)).pack() print(username_entry, a, password_entry, b) &lt;-- #used to check what you are comparing in your conditional. </code></pre> <p>What I did was put <code>line[0]</code> into a variable, then just remove the last character from the string. I added a <code>print</code> statement after the Failure conditional to see what was being compared. <code>a</code> and <code>b</code> are now presenting the correct strings for comparison.</p>
python-3.x|tkinter
0
1,907,988
61,387,313
Python: Finding time taken for each event in dataframe based on condition
<p>I have a df with two columns, timestamp &amp; eventType.</p> timestamp is ordered in chronological order, and eventType can be either ['start', 'change', 'end', resolve].</p></p> <pre><code>['start', 'change'] denotes the start of an event ['end','resolve'] denotes the end of an event createdTime actionName 2020-03-16 18:28:14 start 2020-03-17 19:12:42 end 2020-03-18 19:56:10 change 2020-03-19 21:29:13 change 2020-03-20 21:42:06 end 2020-03-21 18:28:14 start 2020-03-21 19:12:42 resolve 2020-03-22 19:56:10 change 2020-03-22 21:29:13 change 2020-03-23 21:42:06 end </code></pre> <p></p> <p>I wish to calculate the time delta between the <strong>each</strong> <strong>start/change event</strong> to the <strong>next end/resolve event.</strong> </p> <ul> <li>An event can have several start/change statuses before it is resolved, thus an event would need to take the initial start/change status as the 1st start/change event time.</li> <li>The output would need to be a list of time deltas taken for each event in the df</li> </ul> <p>Thanks in advance :) </p> <hr> <p><strong>Edit</strong> The expected outcome should be a list containing each time taken for each event. </p> <pre><code>event_times = ['24:44:28', '49:45.56', '0:44:28', '25:45:56'] </code></pre>
<p>Better late than never?</p> <pre><code>df['createdTime'] = pd.to_datetime(df.createdTime) starts = ['start', 'change'] ends = ['end','resolve'] prev_status = 'end' spans = [] for i in range(len(df)): curr_status = df.actionName[i] if curr_status in starts and prev_status in starts: pass elif curr_status in starts and prev_status in ends: start_time = df.createdTime[i] elif curr_status in ends and prev_status in starts: t = df.createdTime[i] - start_time hours = t.days * 24 + t.seconds // 3600 minutes = t.seconds % 3600 // 60 seconds = t.seconds % 60 spans.append(f&quot;{hours}:{minutes}:{seconds}&quot;) elif curr_status in ends and prev_status in ends: raise ValueError (f&quot;Two ends in a row at index {i}.&quot;) else: raise ValueError (f&quot;Unrecognized action type at index {i}.&quot;) prev_status = curr_status print(spans) </code></pre> <p>gives</p> <pre><code>['24:44:28', '49:45:56', '0:44:28', '25:45:56'] </code></pre>
python|pandas|dataframe|time-series
0
1,907,989
57,886,528
Unable to patch user DirectoryObjectUnauthorizedAccessException http 500
<p>I am trying to patch users in our Azure active directory to update the hireDate. (Python sample below)</p> <pre><code>message = {'hireDate': hire_date.strftime("%Y-%m-%dT%H:%M:%SZ")} headers = {'Content-type': 'application/json'} response = sess.patch(f'{graph_url}/users/{user_id}', json=message, headers=headers) </code></pre> <p>Where session has the correct token obtained using the adal library.</p> <p>I have tried as both application and delegated permissions (i am a tenant admin as well). With User.ReadWrte.all and Directory.Readwrite.All.</p> <p>I get and HTTP 500 repsonse with error:</p> <pre><code> {'code': '-1, Microsoft.Office.Server.Directory.DirectoryObjectUnauthorizedAccessException', 'message': 'Attempted to perform an unauthorized operation.', 'innerError': {'request-id': 'xxxx', 'date': '2019-09-11T09:47:38'}} </code></pre> <p>I can do the same request for my own userId and it works. I can also read all profiles using the same authentication. Also a similar request using the graph explorer works for any user.</p> <p>Any ideas how i can update all users in my tenant?</p> <p>thanks</p>
<p>Seems like a issue with formatting of the date.</p> <p>As per the documentation</p> <p><strong>"The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'"</strong></p> <p><a href="https://docs.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0&amp;tabs=http#request-body" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0&amp;tabs=http#request-body</a></p> <p>Could you please try updating the date and see if it works.</p> <p>Hope it helps.</p>
python|azure-active-directory|microsoft-graph-api|adal
0
1,907,990
57,850,257
How to get consecutive number of shots played instead of a standard cumulative sum?
<p>I have a <em>dataset</em> with details of shots played by each user in the game. It is a <em>dataset</em> of snooker so one player pots the ball and he carries on until he misses and so on. I need to calculate the highest number of <strong>continuous shots</strong> played by the player in the game. </p> <p>Here's the <em>dataset</em> :</p> <pre><code>Game_id Player ID 5d6576aab80c990500e3ce5a 2ff211 5d6576aab80c990500e3ce5a 2ff250 5d6576aab80c990500e3ce5a 2ff211 5d6576aab80c990500e3ce5a 2ff211 . . . ... </code></pre> <hr> <p>I found out a solution for creating a subgroup using <strong>cumulative summation</strong> and <em>shift methods</em> but what it does is it gives you sum of all the shots played during a match. </p> <pre class="lang-py prettyprint-override"><code># where f is the dataframe. f['subgroup'] = (f['pSId'] != f['pSId'].shift(1)).cumsum() f.groupby('subgroup',as_index=False).apply(lambda x: (x['pSId'].head(1), x.shape[0])) </code></pre> <hr> <p>For each game ID I need to get the maximum number of shots played by a player without giving the chance to next player. <strong>How to get consecutive number of shots played instead of a standard cumulative sum?</strong> </p> <p>The result should be something like this:-</p> <pre><code>Game_id Player ID Maximum Continuous Shots 5d6576aab80c990500e3ce5a 2ff211 5 5d6576aab80c990500e3ce5a 2ff250 2 5d6576aa35c80305060c4a32 2f7a5b 5 5d6576aa35c80305060c4a32 2f0847 6 </code></pre>
<p>You can do this:</p> <pre><code>df['Streak'] =df['Player ID'].groupby((df['Player ID'] != df['Player ID'].shift()).cumsum()).cumcount() + 1 df.head() Game_id Player ID Streak 0 5d6576aab80c990500e3ce5a 2ff211 1 1 5d6576aab80c990500e3ce5a 2ff250 1 2 5d6576aab80c990500e3ce5a 2ff211 1 3 5d6576aab80c990500e3ce5a 2ff211 2 4 5d6576aab80c990500e3ce5a 2ff211 3 </code></pre> <p>and then group it and get the max:</p> <pre><code>df.groupby(['Game_id','Player ID']).max().reset_index() Game_id Player ID Streak 0 5d6576aa35c80305060c4a32 2f0847 6 1 5d6576aa35c80305060c4a32 2f7a5b 5 2 5d6576aab80c990500e3ce5a 2ff211 5 3 5d6576aab80c990500e3ce5a 2ff250 2 </code></pre> <p>you can check this article too: <a href="https://predictivehacks.com/count-the-consecutive-events-in-python/" rel="nofollow noreferrer">https://predictivehacks.com/count-the-consecutive-events-in-python/</a></p>
python|pandas|dataset
1
1,907,991
57,878,537
Cropping live video input from a webcam for facial identification
<p>I am working with OpenCV in Python for facial identification and I want to crop the live video from my webcam to just output the face it recognizes.</p> <p>I have tried using ROI but I do not know how to correctly implement it.</p> <pre><code>import cv2 import sys cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") video_capture = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2) roi = frame[y:y+h, x:x+w] cropped = frame[roi] # Display the resulting frame cv2.imshow('Face', cropped) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break </code></pre> <p>.</p> <pre><code>Traceback (most recent call last): File "C:/Users/Ben/Desktop/facerecog/facerecog2.py", line 31, in &lt;module&gt; cv2.imshow('Face', cropped) cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\array.cpp:2492: error: (-206:Bad flag (parameter or structure field)) Unrecognized or unsupported array type in function 'cvGetMat' </code></pre>
<p>You get cropped image with </p> <pre><code>cropped = frame[y:y+h, x:x+w] </code></pre> <p>and then you can display it.</p> <hr> <p>But sometimes there is no face on frame and it will not create <code>cropped</code> and you can get error. Better create this variabel before <code>for</code> and check it after <code>for</code></p> <pre><code>cropped = None for (x, y, w, h) in faces: cropped = frame[y:y+h, x:x+w] if cropped is not None: cv2.imshow('Face', cropped) #else: # cv2.imshow('Face', frame) </code></pre> <p>or</p> <pre><code>if faces: (x, y, w, h) = faces[0] cropped = frame[y:y+h, x:x+w] cv2.imshow('Face', cropped) </code></pre> <hr> <p>I don't know what you want to do if there will be many faces on frame.</p>
python|opencv|facial-identification
0
1,907,992
56,319,040
My if statement conditions are not triggering properly despite the conditions being met
<p>I'm learning how to program with Python by taking up small projects to get myself familiarized. I'm stuck on a tiny problem in which my if statement is not being triggered properly despite the conditions being met during the programs execution. this is the dice simulation project I made on my own.</p> <p>I could not think of any additional methods at this time since I'm still a novice but learning as i'm going</p> <pre><code>import random import time print("Welcome to the dice simulator, lets find out how lucky you are!") "\n" min = 1 max = 6 roll = input("Do you want to play? ") while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y": print("Now rolling both dice....") time.sleep(1) print("calculating....") time.sleep(3) print(random.randint(min, max)) print(random.randint(min, max)) if min == max: #This if condition does not work even if the dice match. Needs work. print("Amazing! You scored a double!") else: #This else condition works regardless of the outcome. print("Oof! Might wanna keep trying!") roll_again = input("Roll again? y/n: ") if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N": print("Goodbye!") break # else: # print("Invalid answer") # break </code></pre> <p>If the if condition is met, a message will print congratulating the user for scoring a double number such as 1,1 or 6,6 for example. If the dice does not show matching number's, the else condition will print a message telling the user to better luck next time.</p>
<p><strong>TRY:-</strong></p> <pre><code>import os import datetime directory = r'C:\Users\vasudeos\OneDrive\Desktop\Test Folder' extensions = (['.jpg', '.jpeg', '.png']); import random import time print("Welcome to the dice simulator, lets find out how lucky you are!") "\n" min = 1 max = 6 roll = input("Do you want to play? ") while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y": print("Now rolling both dice....") time.sleep(1) print("calculating....") time.sleep(3) min1 = random.randint(min, max) max1 = random.randint(min, max) print("{}\n{}".format(min1, max1)) if min1 == max1: #This if condition does not work even if the dice match. Needs work. print("Amazing! You scored a double!") else: #This else condition works regardless of the outcome. print("Oof! Might wanna keep trying!") roll_again = input("Roll again? y/n: ") if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N": print("Goodbye!") break </code></pre> <p>As others have pointed, variables <code>min</code> and <code>max</code> have constant values (1, 6) throughout the execution of the program, and since their values aren't the same, and don't even change <code>if min == max</code> will always be false.</p>
python
0
1,907,993
18,452,512
how to take data string from variable and write into file
<p>i have program python script like this,</p> <pre><code>import serial import time port = serial.Serial("/dev/ttyAMA0", baudrate=600, timeout= 3.0) while True: rcv = port.read(5) value = (rcv) myString = str(value) b = open("/var/www/lampu1.txt","a") b.write(myString[1]) b.close() </code></pre> <p>that program can receive data from serial and all data will be save into file "lampu1.txt". i just want to take 1 string data from the data are received and write into file. for example: data receive=89435, how i can take the string data, if for example i want to take string data [2]=9 and write into file "lampu1.txt". because when i am execute this program occur error. this the error occur on terminal.</p> <pre><code>Traceback (most recent call last): File "terima.py", line 11, in &lt;module&gt; b.write(myString[1]) IndexError: string index out of range </code></pre> <p>anyone can help me to solved this problem,,, thank you.</p>
<pre><code>import serial import time port = serial.Serial("/dev/ttyAMA0", baudrate=600, timeout= 3.0) while True: rcv = port.read(5) value = (rcv) myString = str(value) b = open("/var/www/lampu1.txt","a") #I want to output first character (0th entry) if (len(b) &gt; 0): b.write(myString[0]) else: b.write("Error condition") b.close() </code></pre>
python
0
1,907,994
71,511,148
python multiprocessing error along using cupy
<p>Consider simplified example using multiprocessing inside a class that use cupy for simulation. this part</p> <pre class="lang-py prettyprint-override"><code>obj = FUNC(par) obj.simulate() </code></pre> <p>done in with <code>cupy</code>, then data copy to <code>CPU</code>. multiprocessing does not touch data on <code>GPU</code> but still, I get the following error:</p> <pre class="lang-py prettyprint-override"><code>import tqdm import cupy as cp import numpy as np from multiprocessing import Pool class FUNC: def __init__(self, par) -&gt; None: self.x = par['x'] def simulate(self): x = self.x xs = [] for t in tqdm.trange(nt): dx = cp.random.rand(nn, ns) * 0.001 x += dx xs.append(x.get()) self.xs = np.asarray(xs) def func(self, i): x = self.xs[:, :, i] return [np.mean(x)] def stats(self): with Pool(processes=2) as pool: data = (pool.map(self.func, range(ns))) return cp.asnumpy(data) if __name__ == &quot;__main__&quot;: nn = 10 ns = 10 nt = 2500 par = { &quot;x&quot;: cp.random.randn(nn, ns).astype('f'), } obj = FUNC(par) obj.simulate() data = obj.stats() print(data.shape) </code></pre> <pre class="lang-sh prettyprint-override"><code>Process ForkPoolWorker-1: Traceback (most recent call last): File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 315, in _bootstrap self.run() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 108, in run self._target(*self._args, **self._kwargs) File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/pool.py&quot;, line 114, in worker task = get() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/queues.py&quot;, line 368, in get return _ForkingPickler.loads(res) File &quot;cupy/_core/core.pyx&quot;, line 2250, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2271, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2403, in cupy._core.core._array_default File &quot;cupy/_core/core.pyx&quot;, line 171, in cupy._core.core.ndarray.__init__ File &quot;cupy/cuda/memory.pyx&quot;, line 698, in cupy.cuda.memory.alloc File &quot;cupy/cuda/memory.pyx&quot;, line 1375, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/memory.pyx&quot;, line 1395, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/device.pyx&quot;, line 48, in cupy.cuda.device.get_device_id File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 159, in cupy_backends.cuda.api.runtime.getDevice File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 132, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInitializationError: initialization error Process ForkPoolWorker-2: Traceback (most recent call last): File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 315, in _bootstrap self.run() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 108, in run self._target(*self._args, **self._kwargs) File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/pool.py&quot;, line 114, in worker task = get() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/queues.py&quot;, line 368, in get return _ForkingPickler.loads(res) File &quot;cupy/_core/core.pyx&quot;, line 2250, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2271, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2403, in cupy._core.core._array_default File &quot;cupy/_core/core.pyx&quot;, line 171, in cupy._core.core.ndarray.__init__ File &quot;cupy/cuda/memory.pyx&quot;, line 698, in cupy.cuda.memory.alloc File &quot;cupy/cuda/memory.pyx&quot;, line 1375, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/memory.pyx&quot;, line 1395, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/device.pyx&quot;, line 48, in cupy.cuda.device.get_device_id File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 159, in cupy_backends.cuda.api.runtime.getDevice File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 132, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInitializationError: initialization error Process ForkPoolWorker-3: Traceback (most recent call last): File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 315, in _bootstrap self.run() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 108, in run self._target(*self._args, **self._kwargs) File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/pool.py&quot;, line 114, in worker task = get() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/queues.py&quot;, line 368, in get return _ForkingPickler.loads(res) File &quot;cupy/_core/core.pyx&quot;, line 2250, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2271, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2403, in cupy._core.core._array_default File &quot;cupy/_core/core.pyx&quot;, line 171, in cupy._core.core.ndarray.__init__ File &quot;cupy/cuda/memory.pyx&quot;, line 698, in cupy.cuda.memory.alloc File &quot;cupy/cuda/memory.pyx&quot;, line 1375, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/memory.pyx&quot;, line 1395, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/device.pyx&quot;, line 48, in cupy.cuda.device.get_device_id File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 159, in cupy_backends.cuda.api.runtime.getDevice File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 132, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInitializationError: initialization error Process ForkPoolWorker-4: Traceback (most recent call last): File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 315, in _bootstrap self.run() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 108, in run self._target(*self._args, **self._kwargs) File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/pool.py&quot;, line 114, in worker task = get() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/queues.py&quot;, line 368, in get return _ForkingPickler.loads(res) File &quot;cupy/_core/core.pyx&quot;, line 2250, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2271, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2403, in cupy._core.core._array_default File &quot;cupy/_core/core.pyx&quot;, line 171, in cupy._core.core.ndarray.__init__ File &quot;cupy/cuda/memory.pyx&quot;, line 698, in cupy.cuda.memory.alloc File &quot;cupy/cuda/memory.pyx&quot;, line 1375, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/memory.pyx&quot;, line 1395, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/device.pyx&quot;, line 48, in cupy.cuda.device.get_device_id File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 159, in cupy_backends.cuda.api.runtime.getDevice File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 132, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInitializationError: initialization error Process ForkPoolWorker-5: Traceback (most recent call last): File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 315, in _bootstrap self.run() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/process.py&quot;, line 108, in run self._target(*self._args, **self._kwargs) File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/pool.py&quot;, line 114, in worker task = get() File &quot;/home/ziaee/anaconda3/envs/sbinmms/lib/python3.9/multiprocessing/queues.py&quot;, line 368, in get return _ForkingPickler.loads(res) File &quot;cupy/_core/core.pyx&quot;, line 2250, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2271, in cupy._core.core.array File &quot;cupy/_core/core.pyx&quot;, line 2403, in cupy._core.core._array_default File &quot;cupy/_core/core.pyx&quot;, line 171, in cupy._core.core.ndarray.__init__ File &quot;cupy/cuda/memory.pyx&quot;, line 698, in cupy.cuda.memory.alloc File &quot;cupy/cuda/memory.pyx&quot;, line 1375, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/memory.pyx&quot;, line 1395, in cupy.cuda.memory.MemoryPool.malloc File &quot;cupy/cuda/device.pyx&quot;, line 48, in cupy.cuda.device.get_device_id File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 159, in cupy_backends.cuda.api.runtime.getDevice File &quot;cupy_backends/cuda/api/runtime.pyx&quot;, line 132, in cupy_backends.cuda.api.runtime.check_status cupy_backends.cuda.api.runtime.CUDARuntimeError: cudaErrorInitializationError: initialization error </code></pre> <p>where am I doing wrong?</p>
<p>Adding an answer here to wrap this one up. Didn't stumble upon a Stack Overflow thread when researching this issue so I'm assuming this thread will get more views in the future.</p> <p>The issue has to do with the default start method not working with CUDA Multiprocessing. By explicitly setting the start method to spawn with <code>multiprocessing.set_start_method('spawn', force=True)</code> this issue is resolved.</p>
python|multiprocessing|cupy
0
1,907,995
69,310,106
Django large queryset return as response efficiently
<p>I have a model in django called &quot;Sample&quot; I want to query and return a large number of rows ~ 100k based on filters. However, it's taking up to 4-5 seconds to return the response and I was wondering whether I could make it faster.</p> <p>(Need to improve converting from queryset to df to response json. Not querying from DB)</p> <p>My current code looks like this:</p> <pre><code>@api_view(['POST']) def retrieve_signal_asset_weight_ts_by_signal(request): #code to get item.id here based on request qs = Sample.objects.filter( data_date__range=[start_date, end_date], item__id = item.id).values(*columns_required) df = pd.DataFrame(list(qs), columns=columns_required) response = df .to_json(orient='records') return Response(response, status=status.HTTP_200_OK) </code></pre> <p>Based on multiple test cases -- I've noticed that the slow part isn't actually getting the data from DB, it's converting it to a DataFrame and then returning as JSON. It's actually taking about 2 seconds just for this part <code>df = pd.DataFrame(list(qs), columns=columns_required)</code>. Im looking for a faster way to convert queryset to a json which I can send as part of my &quot;response&quot; object!</p> <p>Based on this <a href="https://stackoverflow.com/questions/11697887/converting-django-queryset-to-pandas-dataframe">link</a> I've tried other methods including <code>django-pandas</code> and using <code>.values_list()</code> but they seem to be slower than this, and I noticed many of the answers are quite old so I was wondering whether Django 3 has anything to make it faster.</p> <p>Thanks</p> <p>Django version : 3.2.6</p>
<p>With your code, you can't write:</p> <blockquote> <p>(Need to improve converting from queryset to df to response json. Not querying from DB)</p> <p>It's actually taking about 2 seconds just for this part</p> <p>df = pd.DataFrame(list(qs), columns=columns_required)</p> </blockquote> <p>Get data from database is a lazy operation, so the query will be executed only when data is needed <code>list(qs)</code>. According to the documentation:</p> <blockquote> <p>QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. Take a look at this example:</p> </blockquote> <p>Try to separate operation:</p> <pre><code>records = list(qs) df = pd.DataFrame(records, columns=columns_required)) </code></pre> <p>Now, you can determine which operation is time-consuming.</p> <p>Maybe, you look at <a href="https://docs.djangoproject.com/en/3.2/ref/request-response/#streaminghttpresponse-objects" rel="nofollow noreferrer"><code>StreamingHttpResponse</code></a></p>
python|django|pandas|django-models|django-3.2
1
1,907,996
55,390,298
Pandas Dataframe replace Nan from a row when a column value matches
<p>I have dataframe i.e.,</p> <pre><code>Input Dataframe class section sub marks school city 0 I A Eng 80 jghss salem 1 I A Mat 90 jghss salem 2 I A Eng 50 Nan salem 3 III A Eng 80 gphss Nan 4 III A Mat 45 Nan salem 5 III A Eng 40 gphss Nan 6 III A Eng 20 gphss salem 7 III A Mat 55 gphss Nan </code></pre> <p>I need to replace the "Nan" in "school" and "city" when a value in "class" and "section" column matches. The resultant outcome suppose to be, Input Dataframe</p> <pre><code> class section sub marks school city 0 I A Eng 80 jghss salem 1 I A Mat 90 jghss salem 2 I A Eng 50 jghss salem 3 III A Eng 80 gphss salem 4 III A Mat 45 gphss salem 5 III A Eng 40 gphss salem 6 III A Eng 20 gphss salem 7 III A Mat 55 gphss salem </code></pre> <p>Can anyone help me out in this?</p>
<p>Use forward and back filling missing values per groups with <code>lambda function</code> in columns specified in list with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="noreferrer"><code>DataFrame.groupby</code></a> - is necessary for each combination same values per groups:</p> <pre><code>cols = ['school','city'] df[cols] = df.groupby(['class','section'])[cols].apply(lambda x: x.ffill().bfill()) print (df) class section sub marks school city 0 I A Eng 80 jghss salem 1 I A Mat 90 jghss salem 2 I A Eng 50 jghss salem 3 III A Eng 80 gphss salem 4 III A Mat 45 gphss salem 5 III A Eng 40 gphss salem 6 III A Eng 20 gphss salem 7 III A Mat 55 gphss salem </code></pre>
python|python-3.x|pandas|nan
8
1,907,997
55,319,642
How to use BeautifulSoup to scrape table links from reddit
<p>I'm trying to scrape links from a Reddit table by using Beautiful Soup, and can successfully extract all of the table's contents except for the URLs. I am using <code>item.find_all('a')</code> but it's returning an empty list when using this code: </p> <pre><code>import praw import csv import requests from bs4 import BeautifulSoup def Authorize(): """Authorizes Reddit API""" reddit = praw.Reddit(client_id='', client_secret='', username='', password='', user_agent='user') url = 'https://old.reddit.com/r/formattesting/comments/94nc49/will_it_work/' headers = {'User-Agent': 'Mozilla/5.0'} page = requests.get(url, headers=headers) soup = BeautifulSoup(page.text, 'html.parser') table_extract = soup.find_all('table')[0] table_extract_items = table_extract.find_all('a') for item in table_extract_items: letter_name = item.contents[0] links = item.find_all('a') print(letter_name) print(links) </code></pre> <p>This is what it returns: </p> <pre><code>6GB EVGA GTX 980 TI [] Intel i7-4790K [] Asus Z97-K Motherboard [] 2x8 HyperX Fury DDR3 RAM [] Elagto HD 60 Pro Capture Card [] </code></pre> <p>I would like for there to be the URL where the empty list is below each table row. </p> <p>I am not sure if this makes a difference in the construct, but the end goal is to extract all of the table contents and links (keeping the association between the two) and save to a CSV as two columns. But for now I am just trying to <code>print</code> to keep it simple.</p>
<p>You were almost near. Your <code>table_extract_items</code> are HTML anchors from which you need to extract <code>text</code> &ndash; the content and attribute <code>href</code> using <code>[</code> <code>]</code> operators. I guess the inappropriate choice of variables name confused you. The line inside for-loop <code>links = item.find_all('a')</code> is wrong!</p> <p>Here is my solution:</p> <pre><code>for anchor in table.findAll('a'): # if not anchor: finaAll returns empty list, .find() return None # continue href = anchor['href'] print (href) print (anchor.text) </code></pre> <p><code>table</code> in my code is what you named <code>table_extract</code> in your code</p> <p>check this:</p> <pre><code>In [40]: for anchor in table.findAll('a'): # if not anchor: # continue href = anchor['href'] text = anchor.text print (href, "--", text) ....: https://imgur.com/a/Y1WlDiK -- 6GB EVGA GTX 980 TI https://imgur.com/gallery/yxkPF3g -- Intel i7-4790K https://imgur.com/gallery/nUKnya3 -- Asus Z97-K Motherboard https://imgur.com/gallery/9YIU19P -- 2x8 HyperX Fury DDR3 RAM https://imgur.com/gallery/pNqXC2z -- Elagto HD 60 Pro Capture Card https://imgur.com/gallery/5K3bqMp -- Samsung EVO 250 GB SSD https://imgur.com/FO8JoQO -- Corsair Scimtar MMO Mouse https://imgur.com/C8PFsX0 -- Corsair K70 RGB Rapidfire Keyboard https://imgur.com/hfCEzMA -- I messed up </code></pre>
python|python-3.x|beautifulsoup
4
1,907,998
57,489,573
Interactive slicing of dataframe columns using Bokeh
<p>I have below function which gives me an error - "expected element of list" in Python using Bokeh.</p> <pre class="lang-py prettyprint-override"><code>data = {'Name':['A', 'B', 'C', 'D'], 'Age':[20, 21, 19, 18], 'Income':[202, 213, 194, 185]} df = pd.DataFrame(data) menu=Select(title="Columns:", value=df.columns[0], options=list(df.columns.values)) def showData(df): source = ColumnDataSource(df) columns = df[[menu.value]] data_table = DataTable(source=source, columns=columns,width=900,fit_columns=True) return vform(data_table) show(column(menu,showData(df))) </code></pre> <p>I should be able to see only the column i selected from filter in the output HTML - should return the results in table format. Any help greatly appreciated.</p>
<p><code>columns</code> should be a list of <code>TableColumn</code> objects as you can see in <a href="https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#datatable" rel="nofollow noreferrer">the docs</a>. You'll have to use CustomJS or a Bokeh server to change the displayed column in the DataTable.</p> <pre><code>import pandas as pd from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import Select, DataTable, TableColumn from bokeh.layouts import column from bokeh.io import show data = {'Name':['A', 'B', 'C', 'D'], 'Age':[20, 21, 19, 18], 'Income':[202, 213, 194, 185]} df = pd.DataFrame(data) menu=Select(title="Columns:", value=list(df)[0], options=list(df.columns.values)) source = ColumnDataSource(df) data_table = DataTable(source=source, columns=[TableColumn(field=menu.value, title=menu.value)],width=900,fit_columns=True) callback = CustomJS(args=dict(), code=""" console.log('Update tablecolumns code...') """) menu.js_on_change('value', callback) show(column([menu, data_table])) </code></pre>
python|pandas|bokeh
0
1,907,999
57,466,782
AttributeError: 'MSVCCompiler' object has no attribute 'linker_exe'
<p>I'm trying to install AirFlow, but keep getting an error. The line - <code>pip install apache-airflow</code></p> <p>I installed Visual Studio with the proper packages, installed misaka, and updated both pip install version and setuptools.</p> <p>The results -</p> <pre><code>Collecting apache-airflow Using cached https://files.pythonhosted.org/packages/fc/c9/db9c285b51a58c426433787205d86e91004662d99b1f5253295619bdb0e4/apache_airflow-1.10.4-py2.py3-none-any.whl Requirement already satisfied: future&lt;0.17,&gt;=0.16.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.16.0) Requirement already satisfied: flask-appbuilder&lt;2.0.0,&gt;=1.12.5 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.13.1) Requirement already satisfied: markdown&lt;3.0,&gt;=2.5.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (2.6.11) Requirement already satisfied: alembic&lt;2.0,&gt;=1.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.0.11) Requirement already satisfied: jinja2&lt;2.11.0,&gt;=2.10.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (2.10.1) Requirement already satisfied: dill&lt;0.3,&gt;=0.2.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.2.9) Requirement already satisfied: flask&lt;2.0,&gt;=1.1.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.1.1) Requirement already satisfied: flask-login&lt;0.5,&gt;=0.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.4.1) Collecting dumb-init&gt;=1.2.2 (from apache-airflow) Using cached https://files.pythonhosted.org/packages/7e/32/817e967fa6c20d4568537016a2f27f00d9c6194778a41835e185e4feea0c/dumb-init-1.2.2.tar.gz Requirement already satisfied: sqlalchemy~=1.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.3.6) Requirement already satisfied: lazy-object-proxy~=1.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.4.1) Requirement already satisfied: thrift&gt;=0.9.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.11.0) Requirement already satisfied: configparser&lt;3.6.0,&gt;=3.5.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (3.5.3) Requirement already satisfied: croniter&lt;0.4,&gt;=0.3.17 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.3.30) Requirement already satisfied: termcolor==1.1.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.1.0) Requirement already satisfied: psutil&lt;6.0.0,&gt;=4.2.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (5.6.3) Requirement already satisfied: requests&lt;3,&gt;=2.20.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (2.22.0) Requirement already satisfied: funcsigs==1.0.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.0.0) Requirement already satisfied: python-daemon&lt;2.2,&gt;=2.1.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (2.1.2) Requirement already satisfied: flask-admin==1.5.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.5.3) Requirement already satisfied: flask-swagger==0.2.13 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.2.13) Requirement already satisfied: cached-property~=1.5 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.5.1) Requirement already satisfied: pygments&lt;3.0,&gt;=2.0.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (2.4.2) Requirement already satisfied: tenacity==4.12.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (4.12.0) Requirement already satisfied: flask-caching&lt;1.4.0,&gt;=1.3.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.3.3) Requirement already satisfied: setproctitle&lt;2,&gt;=1.1.8 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.1.10) Requirement already satisfied: tabulate&lt;0.9,&gt;=0.7.5 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.8.3) Requirement already satisfied: tzlocal&lt;2.0.0,&gt;=1.4 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.5.1) Requirement already satisfied: pendulum==1.4.4 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.4.4) Requirement already satisfied: flask-wtf&lt;0.15,&gt;=0.14.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.14.2) Requirement already satisfied: json-merge-patch==0.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.2) Requirement already satisfied: zope.deprecation&lt;5.0,&gt;=4.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (4.4.0) Requirement already satisfied: python-dateutil&lt;3,&gt;=2.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (2.8.0) Requirement already satisfied: pandas&lt;1.0.0,&gt;=0.17.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.24.2) Requirement already satisfied: gunicorn&lt;20.0,&gt;=19.5.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (19.9.0) Requirement already satisfied: unicodecsv&gt;=0.14.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.14.1) Requirement already satisfied: colorlog==4.0.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (4.0.2) Requirement already satisfied: iso8601&gt;=0.1.12 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (0.1.12) Requirement already satisfied: text-unidecode==1.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from apache-airflow) (1.2) Requirement already satisfied: colorama&lt;1,&gt;=0.3.9 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (0.4.1) Requirement already satisfied: click&lt;8,&gt;=6.7 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (7.0) Requirement already satisfied: apispec[yaml]&gt;=1.1.1&lt;2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (2.0.2) Requirement already satisfied: Flask-Babel&lt;1,&gt;=0.11.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (0.12.2) Requirement already satisfied: Flask-OpenID&lt;2,&gt;=1.2.5 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (1.2.5) Requirement already satisfied: Flask-SQLAlchemy&lt;3,&gt;=2.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (2.4.0) Requirement already satisfied: Flask-JWT-Extended&lt;4,&gt;=3.18 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (3.21.0) Requirement already satisfied: marshmallow&lt;2.20,&gt;=2.18.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (2.19.5) Requirement already satisfied: marshmallow-enum&lt;2,&gt;=1.4.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (1.4.1) Requirement already satisfied: marshmallow-sqlalchemy&gt;=0.16.1&lt;1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (0.17.0) Requirement already satisfied: prison==0.1.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (0.1.0) Requirement already satisfied: jsonschema&gt;=3.0.1&lt;4 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (3.0.2) Requirement already satisfied: PyJWT&gt;=1.7.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (1.7.1) Requirement already satisfied: Mako in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from alembic&lt;2.0,&gt;=1.0-&gt;apache-airflow) (1.1.0) Requirement already satisfied: python-editor&gt;=0.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from alembic&lt;2.0,&gt;=1.0-&gt;apache-airflow) (1.0.4) Requirement already satisfied: MarkupSafe&gt;=0.23 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from jinja2&lt;2.11.0,&gt;=2.10.1-&gt;apache-airflow) (1.1.1) Requirement already satisfied: itsdangerous&gt;=0.24 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask&lt;2.0,&gt;=1.1.0-&gt;apache-airflow) (1.1.0) Requirement already satisfied: Werkzeug&gt;=0.15 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask&lt;2.0,&gt;=1.1.0-&gt;apache-airflow) (0.15.5) Requirement already satisfied: six&gt;=1.7.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from thrift&gt;=0.9.2-&gt;apache-airflow) (1.11.0) Requirement already satisfied: chardet&lt;3.1.0,&gt;=3.0.2 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from requests&lt;3,&gt;=2.20.0-&gt;apache-airflow) (3.0.4) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,&lt;1.26,&gt;=1.21.1 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from requests&lt;3,&gt;=2.20.0-&gt;apache-airflow) (1.22) Requirement already satisfied: idna&lt;2.9,&gt;=2.5 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from requests&lt;3,&gt;=2.20.0-&gt;apache-airflow) (2.6) Requirement already satisfied: certifi&gt;=2017.4.17 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from requests&lt;3,&gt;=2.20.0-&gt;apache-airflow) (2018.1.18) Requirement already satisfied: ordereddict in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from funcsigs==1.0.0-&gt;apache-airflow) (1.1) Requirement already satisfied: lockfile&gt;=0.10 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from python-daemon&lt;2.2,&gt;=2.1.1-&gt;apache-airflow) (0.12.2) Requirement already satisfied: docutils in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from python-daemon&lt;2.2,&gt;=2.1.1-&gt;apache-airflow) (0.15.2) Requirement already satisfied: setuptools in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from python-daemon&lt;2.2,&gt;=2.1.1-&gt;apache-airflow) (41.0.1) Requirement already satisfied: wtforms in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-admin==1.5.3-&gt;apache-airflow) (2.2.1) Requirement already satisfied: PyYAML&gt;=3.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from flask-swagger==0.2.13-&gt;apache-airflow) (5.1.2) Requirement already satisfied: pytz in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from tzlocal&lt;2.0.0,&gt;=1.4-&gt;apache-airflow) (2018.9) Requirement already satisfied: pytzdata&gt;=2018.3.0.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from pendulum==1.4.4-&gt;apache-airflow) (2019.2) Requirement already satisfied: numpy&gt;=1.12.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from pandas&lt;1.0.0,&gt;=0.17.1-&gt;apache-airflow) (1.13.3) Requirement already satisfied: Babel&gt;=2.3 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from Flask-Babel&lt;1,&gt;=0.11.1-&gt;flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (2.7.0) Requirement already satisfied: python3-openid&gt;=2.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from Flask-OpenID&lt;2,&gt;=1.2.5-&gt;flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (3.1.0) Requirement already satisfied: pyrsistent&gt;=0.14.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from jsonschema&gt;=3.0.1&lt;4-&gt;flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (0.15.4) Requirement already satisfied: attrs&gt;=17.4.0 in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from jsonschema&gt;=3.0.1&lt;4-&gt;flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (19.1.0) Requirement already satisfied: defusedxml in c:\users\ben\appdata\local\programs\python\python36\lib\site-packages (from python3-openid&gt;=2.0-&gt;Flask-OpenID&lt;2,&gt;=1.2.5-&gt;flask-appbuilder&lt;2.0.0,&gt;=1.12.5-&gt;apache-airflow) (0.6.0) Installing collected packages: dumb-init, apache-airflow Running setup.py install for dumb-init ... error ERROR: Command errored out with exit status 1: command: 'c:\users\ben\appdata\local\programs\python\python36\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Ben\\AppData\\Local\\Temp\\pip-install-xfdgqfty\\dumb-init\\setup.py'"'"'; __file__='"'"'C:\\Users\\Ben\\AppData\\Local\\Temp\\pip-install-xfdgqfty\\dumb-init\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Ben\AppData\Local\Temp\pip-record-4syt09xi\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\Ben\AppData\Local\Temp\pip-install-xfdgqfty\dumb-init\ Complete output (33 lines): running install running build running build_cexe Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\Ben\AppData\Local\Temp\pip-install-xfdgqfty\dumb-init\setup.py", line 135, in &lt;module&gt; distclass=ExeDistribution, File "c:\users\ben\appdata\local\programs\python\python36\lib\site-packages\setuptools\__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\ben\appdata\local\programs\python\python36\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\command\install.py", line 545, in run self.run_command('build') File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\ben\appdata\local\programs\python\python36\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\Users\Ben\AppData\Local\Temp\pip-install-xfdgqfty\dumb-init\setup.py", line 95, in run cmd = compiler.linker_exe + [f.name, '-static', '-o', os.devnull] AttributeError: 'MSVCCompiler' object has no attribute 'linker_exe' supports -static... ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\ben\appdata\local\programs\python\python36\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Ben\\AppData\\Local\\Temp\\pip-install-xfdgqfty\\dumb-init\\setup.py'"'"'; __file__='"'"'C:\\Users\\Ben\\AppData\\Local\\Temp\\pip-install-xfdgqfty\\dumb-init\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Ben\AppData\Local\Temp\pip-record-4syt09xi\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output. </code></pre>
<p>I had the same issue. Seems like airflow 1.10.4 has a new dependency on "dumb-init" which doesn't work well on Windows. </p> <p>Install Airflow 1.10.3 worked fine for me. </p> <pre><code>pip install 'apache-airflow[postgres]==1.10.3' </code></pre>
python|installation|airflow
8