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,905,000
71,946,547
403 Forbidden BeautifulSoup Web Scraper
<p>I was building a web scraper to pull hrefs off of <a href="https://www.startengine.com/explore" rel="nofollow noreferrer">https://www.startengine.com/explore</a>, but I was struggling to get any hrefs. I decided to print the webpage and figured out why.</p> <p>Here is my code:</p> <pre><code>import pandas as pd import os import requests from bs4 import BeautifulSoup import re URL = &quot;https://www.startengine.com/explore&quot; page = requests.get(URL) soup = BeautifulSoup(page.text, &quot;html.parser&quot;) links = [] print(soup) </code></pre> <p>This is the output:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;403 Forbidden&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;center&gt;&lt;h1&gt;403 Forbidden&lt;/h1&gt;&lt;/center&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Can someone help me work around the &quot;403 Forbidden&quot;?</p>
<p>You need to inject your user-agent as header as follows:</p> <pre><code>import pandas as pd import os import requests from bs4 import BeautifulSoup import re URL = &quot;https://www.startengine.com/explore&quot; headers={'User-Agent':'mozilla/5.0'} page = requests.get(URL,headers=headers) print(page) soup = BeautifulSoup(page.text, &quot;html.parser&quot;) links = [] print(soup) </code></pre>
python|html|beautifulsoup
2
1,905,001
35,824,169
Python - AttributeError: Point instance has no attribute 'x'
<p>So I'm making a point class which I'll use to draw shapes. I'm starting by creating my points and raising an error if the x and y values are not floats:</p> <pre><code>def __init__(self, x, y): if not isinstance(x, float): raise Error ("Parameter \"x\" illegal.") if not isinstance(y, float): raise Error ("Parameter \"y\" illegal.") self.x = x self.y = y </code></pre> <p>And then in this method I'm converting the values to an int in string form. </p> <pre><code>def __str__(self): return int(round(self.x)) </code></pre> <p>The problem is for the above method, it's giving me the error:</p> <pre><code>AttributeError: Point instance has no attribute 'x' </code></pre> <p>However x should exist so I don't know why it's giving me that error. Even if I use y it says y doesn't exist. So why is that method giving me this error? </p>
<p>If the indentation in the question is actually correct, <code>x</code> and <code>y</code> are never set. The code states:</p> <pre><code> if not isinstance(y, float): raise Error ("Parameter \"y\" illegal.") self.x = x self.y = y </code></pre> <p>If the <code>if</code> evaluates to <code>True</code>, an exception will be raised, and the lines will never be reached. If it evaluates to <code>False</code>, then this whole block is not executed.</p> <p>You might have meant this:</p> <pre><code>if not isinstance(x, float): raise Error ("Parameter \"x\" illegal.") self.x = x if not isinstance(y, float): raise Error ("Parameter \"y\" illegal.") self.y = y </code></pre>
python
2
1,905,002
15,469,594
Exception 'HDFStore requires PyTables ' when using HDF5 file in iPython
<p>I am very new to Python and am trying to create a table in pandas with HDFStore as follows</p> <pre><code>store = HDFStore('store.h5') </code></pre> <p>I get the exception :</p> <pre><code>Exception Traceback (most recent call last) C:\Python27\&lt;ipython-input-11-de3060b689e6&gt; in &lt;module&gt;() ----&gt; 1 store = HDFStore('store.h5') C:\Python27\lib\site-packages\pandas-0.10.1-py2.7-win32.egg\pandas\io\pytables.pyc in __init__(self, path, mode, complevel, complib, fletcher32) 196 import tables as _ 197 except ImportError: # pragma: no cover --&gt; 198 raise Exception('HDFStore requires PyTables') 199 200 self.path = path Exception: HDFStore requires PyTables </code></pre> <p>I already have Pytables installed and it is present in site-packages. Both pandas(0.l0.1) and pytables(2.4.0) are 32 bit Windows versions. Python version is 2.7.3 for 32 bit windows</p> <p>I am running this using ipython notebook.</p> <p>I forgot to add that I have Windows 7 - 64 bit OS, but Python and all its related add-ons are 32 bit.</p>
<p>I also had the same error when using <strong>HDFStore</strong>. And I tried all the steps specified above and spent many hours to find a solution, but non of them were successful. </p> <p>Then I downloaded and installed <a href="http://conda.pydata.org/miniconda.html" rel="nofollow noreferrer">MiniConda</a>. And then I used the below command to install pytables. </p> <pre><code>conda install -c conda-forge pytables </code></pre> <p>Please refer the below screenshot.</p> <p><a href="https://i.stack.imgur.com/Y1z77.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y1z77.jpg" alt="enter image description here"></a></p>
python|pandas|hdf5
3
1,905,003
29,594,061
Pylab / matplotlib magic in IPython: supress loading message
<p>Currently in <code>IPython</code>, when you call <code>%pylab inline</code> or <code>%matplotlib inline</code> the following message displays under the code block. </p> <blockquote> <p>"Populating the interactive namespace from numpy and matplotlib"</p> </blockquote> <p>How I can suppress this message from being displayed?</p>
<p>I don't think there's a builtin way of suppressing that message since if you look at the %pylab magic function in <a href="https://github.com/ipython/ipython/blob/master/IPython/core/magics/pylab.py" rel="nofollow">this</a> file you can see that the print statement is hard coded in there.</p> <p>If this is a one-off kind of thing you can simply comment/remove that print line from your local library. (Typically it would be found at <code>/usr/local/lib/python2.7/dist-packages/IPython/core/magics/pylab.py</code>.) Or possibly redirect stdout to devnull or something like that. </p>
matplotlib|ipython|ipython-notebook|ipython-magic
2
1,905,004
46,392,006
Python simple web crawler error (infinite loop crawling)
<p>I wrote a simple crawler in python. It seems to work fine and find new links, but repeats the finding of the same links and it is not downloading the new web pages found. It seems like it crawls infinitely even after it reaches the set crawling depth limit. I am not getting any errors. It just runs forever. Here is the code and the run. I am using Python 2.7 on Windows 7 64bit.</p> <pre><code>import sys import time from bs4 import * import urllib2 import re from urlparse import urljoin def crawl(url): url = url.strip() page_file_name = str(hash(url)) page_file_name = page_file_name + ".html" fh_page = open(page_file_name, "w") fh_urls = open("urls.txt", "a") fh_urls.write(url + "\n") html_page = urllib2.urlopen(url) soup = BeautifulSoup(html_page, "html.parser") html_text = str(soup) fh_page.write(url + "\n") fh_page.write(page_file_name + "\n") fh_page.write(html_text) links = [] for link in soup.findAll('a', attrs={'href': re.compile("^http://")}): links.append(link.get('href')) rs = [] for link in links: try: #r = urllib2.urlparse.urljoin(url, link) r = urllib2.urlopen(link) r_str = str(r.geturl()) fh_urls.write(r_str + "\n") #a = urllib2.urlopen(r) if r.headers['content-type'] == "html" and r.getcode() == 200: rs.append(r) print "Extracted link:" print link print "Extracted link final URL:" print r except urllib2.HTTPError as e: print "There is an error crawling links in this page:" print "Error Code:" print e.code return rs fh_page.close() fh_urls.close() if __name__ == "__main__": if len(sys.argv) != 3: print "Usage: python crawl.py &lt;seed_url&gt; &lt;crawling_depth&gt;" print "e.g: python crawl.py https://www.yahoo.com/ 5" exit() url = sys.argv[1] depth = sys.argv[2] print "Entered URL:" print url html_page = urllib2.urlopen(url) print "Final URL:" print html_page.geturl() print "*******************" url_list = [url, ] current_depth = 0 while current_depth &lt; depth: for link in url_list: new_links = crawl(link) for new_link in new_links: if new_link not in url_list: url_list.append(new_link) time.sleep(5) current_depth += 1 print current_depth </code></pre> <p>Here is what I got when I ran it:</p> <pre><code>C:\Users\Hussam-Den\Desktop&gt;python test.py https://www.yahoo.com/ 4 Entered URL: https://www.yahoo.com/ Final URL: https://www.yahoo.com/ ******************* 1 </code></pre> <p>And the output file for storing crawled urls is this one:</p> <pre><code>https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://www.yahoo.com/ https://www.yahoo.com/lifestyle/horoscope/libra/daily-20170924.html https://policies.yahoo.com/us/en/yahoo/terms/utos/index.htm https://policies.yahoo.com/us/en/yahoo/privacy/adinfo/index.htm https://www.oath.com/careers/work-at-oath/ https://help.yahoo.com/kb/account </code></pre> <p>Any idea what's wrong?</p>
<ol> <li>You have an error here: <code>depth = sys.argv[2]</code>, <code>sys</code> return <code>str</code> not <code>int</code>. You should write <code>depth = int(sys.argv[2])</code></li> <li>Becouse of 1 point, condition <code>while current_depth &lt; depth:</code> always return <code>True</code></li> </ol> <p>Try to fix it by convert <code>argv[2]</code> to <code>int</code>. I thin error is there</p>
python|beautifulsoup|urllib2
1
1,905,005
46,206,829
Python Write Temp File to S3
<p>I am currently trying to write a dataframe to a temp file and then upload that temp file into an S3 bucket. When I run my code there currently isn't any action that occurs. Any help would be greatly appreciated. The following is my code:</p> <pre><code>import csv import pandas as pd import boto3 import tempfile import os s3 = boto3.client('s3', aws_access_key_id = access_key, aws_secret_access_key = secret_key, region_name = region) temp = tempfile.TemporaryFile() largedf.to_csv(temp, sep = '|') s3.put_object(temp, Bucket = '[BUCKET NAME]', Key = 'test.txt') temp.close() </code></pre>
<p>The file-handle you pass to the <code>s3.put_object</code> is at the final position, when you <code>.read</code> from it, it will return an empty string.</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.randint(10,50, (5,5))) &gt;&gt;&gt; temp = tempfile.TemporaryFile(mode='w+') &gt;&gt;&gt; df.to_csv(temp) &gt;&gt;&gt; temp.read() '' </code></pre> <p>A quick fix is to <code>.seek</code> back to the beginning...</p> <pre><code>&gt;&gt;&gt; temp.seek(0) 0 &gt;&gt;&gt; print(temp.read()) ,0,1,2,3,4 0,11,42,40,45,11 1,36,18,45,24,25 2,28,20,12,33,44 3,45,39,14,16,20 4,40,16,22,30,37 </code></pre> <p>Note, writing to disk is unnecessary, really, you could just keep everything in memory using a buffer, something like:</p> <pre><code>from io import StringIO # on python 2, use from cStringIO import StringIO buffer = StringIO() # Saving df to memory as a temporary file df.to_csv(buffer) buffer.seek(0) s3.put_object(buffer, Bucket = '[BUCKET NAME]', Key = 'test.txt') </code></pre>
python|amazon-s3
12
1,905,006
61,021,955
Minimum moves to reach k
<p>Given two numbers <code>m</code> and <code>n</code>, in one move you can get two new pairs:</p> <ul> <li><code>m+n, n</code></li> <li><code>m, n+m</code></li> </ul> <p>Let's intially set <code>m = n = 1</code> find the minimum number of moves so that at least one of the numbers equals <code>k</code></p> <p>it's guaranteed there's a solution (i.e. there exist a sequence of moves that leads to k)</p> <p>For example: given <code>k = 5</code> the minimum number of moves so that <code>m</code> or n is equal to <code>k</code> is 3</p> <pre><code>1, 1 1, 2 3, 2 3, 5 </code></pre> <p>Total of 3 moves.</p> <p>I have come up with a solution using recursion in python, but it doesn't seem to work on big number (i.e 10^6)</p> <pre><code>def calc(m, n, k): if n &gt; k or m &gt; k: return 10**6 elif n == k or m == k: return 0 else: return min(1+calc(m+n, n, k), 1+calc(m, m+n, k)) k = int(input()) print(calc(1, 1, k)) </code></pre> <p>How can I improve the performance so it works for big numbers?</p>
<p>This is an interesting problem in number theory, including linear Diophantine equations. Since there are solutions available on line, I gather that you want help in deriving the algorithm yourself.</p> <p>Restate the problem: you start with two numbers characterized as 1*m+0*n, 0*m+1*n. Use the shorthand (1, 0) and (0, 1). You are looking for the shortest path to <em>any</em> solution to the linear Diophantine equation</p> <pre><code>a*m + b*n = k </code></pre> <p>where (a, b) is reached from starting values (1, 1) a.k.a. ( (1, 0), (0, 1) ).</p> <p>So ... starting from (1, 1), how can you characterize the paths you reach from various permutations of the binary enhancement. At each step, you have two choices: a += b or b += a. Your existing algorithm already recognizes this binary search tree.</p> <p>These graph transitions -- edges along a lattice -- can be characterized, in terms of which (a, b) pairs you can reach on a given step. Is that enough of a hint to move you along? That characterization is the key to converting this problem into something close to a direct computation.</p>
python|algorithm
1
1,905,007
49,451,285
global name 'test' is not defined
<p>I have a two files .py File A and B, </p> <p>File A using methods from file B and file B using methods from file A</p> <p>file A</p> <pre><code>from file_b import * def abc(): # something cba() </code></pre> <p>file B</p> <pre><code>from file_a import * def cba(): # something abc() </code></pre> <p>if i trying run script for file A, i get Error</p> <blockquote> <p>global name 'cba' is not defined</p> </blockquote> <p>If i change my imports to :</p> <pre><code>import file_a </code></pre> <p>and </p> <pre><code>file_a.abc() </code></pre> <p>My script works properly</p> <p>It is possibility to use from file_a import * ? </p> <p>Did I do something wrong?</p>
<p>I have 3 files for a Python PyGame. </p> <ol> <li>settings.py</li> <li>sprites.py</li> <li>game.py</li> </ol> <p>In settings I have my global variables and some other useful constants. If I import my settings into my sprites file using</p> <pre><code>from settings import * </code></pre> <p>then in my main file, game.py, I just import my sprites. If I use </p> <pre><code>from sprites import * </code></pre> <p>then I am setting the sprites AND the content of my settings file ALSO. If I were to say</p> <pre><code>from sprites import player from sprites import enemy </code></pre> <p>then I would NOT be getting the content of settings, even though they are imported into that NameSpace... or file. If I want access to the tuples representing colours in my game.py file, I have to import them.</p> <p>I hope this clears up the problem you are having or gives a better idea of why this is happening, as mentioned in the first comment- it is a circular reference.</p>
python|python-2.7
1
1,905,008
49,732,664
Uploading and saving files in server through flask gives error
<p>So, I'm trying to make a flask mini-app that has an upload button which will upload images and then save that image in another folder named "upimgs". We need to do some image processing operation on the uploaded image later using google cloud vision api. The code is :</p> <pre><code>app = Flask(__name__) @app.route('/') def upload_file(): return '''&lt;html&gt;&lt;h1&gt;Upload a file&lt;/h1&gt; &lt;body&gt;&lt;form action = "http://35.231.238.112:8085/upload" method = "POST" enctype = "multipart/form-data"&gt; &lt;input type="file" name="file"/&gt;&lt;input type="submit"/&gt; &lt;/form&gt; &lt;/body&gt;&lt;/html&gt; ''' @app.route('/upload',methods=["GET","POST"]) def upload_lnk(): if request.method == 'POST': f = request.files['file'] f.save(os.path.join(app.config['/upimgs/'], filename)) cmd2 = "python pj2new.py upmigs/" + f.filename cmd2 = str(cmd2) #some more code to run that output in flask browser </code></pre> <p>However it shows the following error :</p> <pre><code>KeyError: '/upimgs/' </code></pre> <p>Where is the probable error? I looked up to this : <a href="https://stackoverflow.com/questions/30328586/refering-to-a-directory-in-a-flask-app-doesnt-work-unless-the-path-is-absolute">Refering to a directory in a Flask app doesn&#39;t work unless the path is absolute</a> However the problem is not similar. I'm facing issue with uploading images in the server whether that one have file path issue.</p>
<p>add this line with your images directory</p> <pre><code>app.config['upimgs'] = "/home/user/app/folder" </code></pre> <p><a href="http://flask.pocoo.org/docs/0.12/config/" rel="nofollow noreferrer">Official Docs</a></p>
python|python-3.x|flask|flask-restful
0
1,905,009
49,528,661
NodeJS and Python combined architecture?
<p>Could you give me an idea/concepts (not in code) on how could I link NodeJS and Python? </p> <p>Let's say, </p> <ul> <li>I have NodeJS up and running in PM2 (assuming I already know REST API) and I have a ton of <strong>data sets</strong> that I need to be ready to display to client side using socket.io (assumming I already know socket.io) as soon as possible. </li> </ul> <p>I'm thinking to use Python. This is for me to implement the basics of machine learning. </p> <p>In what concept should I start? I'd really love to hear your ideas.</p>
<p>Well you seem to be assuming way too many things, okay from your description I would suggest you to have a look at concept called <a href="http://microservices.io/patterns/microservices.html" rel="nofollow noreferrer">microservice architecture</a>. </p> <p>This is how it will work let us assume you want to build an online shopping application where you have 2 main scenarios first is sell all items on your website and second you want to recommend products to your user(Your ML comes into play over here)</p> <p>So as you said you already know REST API so what you would do is create a microservice (Consider it as a small nodejs application(Using either express or sails or any other framework) which has APIs exposed for all shopping related business logic) also you end up using fromtend technology viz. angularjs for your client side code. You'll show all this shopping stuff by calling your nodejs REST APIs from your angularjs client code. Node provides socket support via <a href="https://socket.io/" rel="nofollow noreferrer">socket.io</a>.</p> <p>Similarly you write a small microservice in python(using <a href="http://flask.pocoo.org/" rel="nofollow noreferrer">Flask</a> and <a href="https://github.com/miguelgrinberg/python-socketio" rel="nofollow noreferrer">Python-SocketIO</a>) which takes your huge amount of data from datastore does all ML magic and returns recommended products for the particular user(which you received from your angularjs client application), and return it using Python-SocketIO to angularjs(or node application if you're maintaining your frontend logic there instead of angular).</p> <p>You have provided very less detail so this is abstract view of what you can look into.</p>
python|node.js
1
1,905,010
62,819,851
Loophole of an if inside a while
<p>I've made this program that requires the user to input 6 different numbers and i made it so if it's not happy with the numbers he can change them. The thing is that i put this condition so it would reedit the numbers but it seems to be loopholeing in the var of the input &quot;cambio&quot; that checks if it's happy with the numbers.</p> <pre><code>import random def ingreso_numeros(): while len(nums_usuario) &lt; 6: num = int(input(&quot;Ingrese un número del 0 al 15: &quot;)) if num in range(0,15) and num not in nums_usuario: nums_usuario.append(num) elif num not in range(0,15) and num not in nums_usuario: print(&quot;El número ingresado no está entre 0 y 15&quot;) elif num in range(0,15) and num in nums_usuario: print(&quot;El número ya fue ingresado&quot;) else: (&quot;Machine Broke, contact supervisor&quot;) print(&quot;Sus números ingresados son:&quot;,nums_usuario) def quini_numeros(): while len(nums_quini) &lt; 6: x = randint(0,15) if x not in nums_quini: nums_quini.append(x) conteo+=1 else: pass #testeo# print(nums_quini) #testeo# ## ------------ main ----------------------------------------- nums_quini = [] nums_usuario = [] opcion = True ingreso_numeros() while opcion == True: cambio = input(&quot;¿Desea cambiar sus números? Sí(S)/No(N): &quot;).upper if cambio == &quot;S&quot;: nums_usuario.clear() ingreso_numeros() elif cambio == &quot;N&quot;: opcion = False quini_numeros() </code></pre>
<p>It seems you are not calling the method <code>upper</code>, then the value of <code>cambio</code> is <code>&lt;function str.upper&gt;</code>, and none of the conditions is executed which keeps you in an infinite loop.</p> <pre class="lang-py prettyprint-override"><code>cambio = input(&quot;¿Desea cambiar sus números? Sí(S)/No(N): &quot;).upper() # use () </code></pre>
python|python-3.x|boolean
0
1,905,011
62,680,413
Draw over a pygame rect with a smaller width
<p>I'm making a Sudoku Solver via pygame and I've been able to draw the whole board, however, while programming the section of code that deals with clicking on a tile, I made it so that the current tile would &quot;light up&quot; green so the user can know the current tile. However, I'm stuck figuring out how to draw over the green highlighted section when a user decides to click on a different tile. I'd like to remove that part entirely but, since it's a rect with a thickness of 4 and the base tiles have a thickness of 1, all I accomplish is having an ugly black line over the thick green line. I tried redrawing the whole board but I obtain similar results. Any help?</p> <pre class="lang-py prettyprint-override"><code>class Tile: '''Represents each white tile/box on the grid''' def __init__(self, value, window, x1, x2): self.value = value #value of the num on this grid self.window = window self.active = False self.rect = pygame.Rect(x1, x2, 60, 60) #dimensions for the rectangle def draw(self, color, thickness): '''Draws a tile on the board''' pygame.draw.rect(self.window, color, self.rect, thickness) pygame.display.flip() def main(): board = Board(screen) tiles = board.draw_board() #store the locations of all the tiles on the grid running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONUP: mousePos = pygame.mouse.get_pos() #board.draw_board() or (see next comment) for i in range(9): for j in range (9): #look for tile we clicked on #tiles[i][j].draw((0,0,0),1) #yield same results if tiles[i][j].is_clicked(mousePos): tiles[i][j].draw((50,205,50),4) #redraws that tile but with a highlighted color to show it's been clicked break main() </code></pre> <p><a href="https://i.stack.imgur.com/mjYrT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mjYrT.png" alt="Drawing over doesn't work!" /></a></p>
<p>You could simply store the highlighted tile in a variable. I also don't think you need a <code>Tile</code> class at all, since a sudoku game state is basically just a list of list of numbers.</p> <p>Here's a simple example. Note the comments:</p> <pre><code>import random import pygame TILE_SIZE = 64 # function to draw the grid def draw_board(): board_surface = pygame.Surface((9*TILE_SIZE, 9*TILE_SIZE)) board_surface.fill((255, 255, 255)) for x in range(9): for y in range(9): rect = pygame.Rect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE) pygame.draw.rect(board_surface, (0, 0, 0), rect, 1) pygame.draw.line(board_surface, (0, 0, 0), (0, 3*TILE_SIZE), (9*TILE_SIZE, 3*TILE_SIZE), 5) pygame.draw.line(board_surface, (0, 0, 0), (0, 6*TILE_SIZE), (9*TILE_SIZE, 6*TILE_SIZE), 5) pygame.draw.line(board_surface, (0, 0, 0), (3*TILE_SIZE, 0), (3*TILE_SIZE, 9*TILE_SIZE), 5) pygame.draw.line(board_surface, (0, 0, 0), (6*TILE_SIZE, 0), (6*TILE_SIZE, 9*TILE_SIZE), 5) return board_surface def main(): # standard pygame setup pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((9*TILE_SIZE, 9*TILE_SIZE)) font = pygame.font.SysFont(None, 40) # seperate the game state from the UI # create a dummy 9x9 sudoku board state = [[None for _ in range(10)] for _ in range(10)] for _ in range(15): x = random.randint(0, 9) y = random.randint(0, 9) state[y][x] = random.randint(1, 9) # a variable to hold the selected tile's position on the board # (from 0,0 to 8,8) selected = None # create the grid surface ONCE and reuse it to clear the screen board_surface = draw_board() while True: for event in pygame.event.get(): pos = pygame.mouse.get_pos() if event.type == pygame.QUIT: return # when the player clicks on a tile # we translate the screen coordinates to the board coordinates # e.g. a pos of (140, 12) is the tile at (2, 0) if event.type == pygame.MOUSEBUTTONDOWN: w_x, w_y = event.pos selected = w_x // TILE_SIZE, w_y // TILE_SIZE # clear everything by blitting the grid surface to the screen screen.blit(board_surface, (0, 0)) # print all numbers in the state to the screen # we use a Rect here so we can easily center the numbers rect = pygame.Rect(0, 0, TILE_SIZE, TILE_SIZE) for line in state: for tile in line: if tile != None: tmp = font.render(str(tile), True, (0, 0, 0)) screen.blit(tmp, tmp.get_rect(center=rect.center)) rect.move_ip(TILE_SIZE, 0) rect.x = 0 rect.move_ip(0, TILE_SIZE) # if a tile is selected, we calculate the world coordinates from the board coordinates # and draw a simple green rect if selected: rect = pygame.Rect(selected[0] * TILE_SIZE, selected[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE) pygame.draw.rect(screen, (0, 200, 0), rect, 5) clock.tick(30) pygame.display.flip() main() </code></pre> <p><a href="https://i.stack.imgur.com/jet6K.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jet6K.gif" alt="enter image description here" /></a></p> <p>Also, you shouldn't call <code>pygame.display.flip()</code> outside your main loop. It can lead to effects like flickering or images not showing up correctly.</p>
python|pygame|drawing
2
1,905,012
62,483,152
StandardScaler giving non-uniform standard deviation
<p>My problem setup is as follows: Python 3.7, Pandas version 1.0.3, and sklearn version 0.22.1. I am applying a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel="nofollow noreferrer">StandardScaler</a> (to every column of a float matrix) per usual. However, the columns that I get out do not have standard deviation =1, while their mean values are (approximately) 0. </p> <p>I am not sure what is going wrong here, I have checked whether the <code>scaler</code> got confused and standardised the rows instead but that does not seem to be the case. </p> <pre><code>from sklearn.preprocessing import StandardScaler import pandas as pd import numpy as np np.random.seed(1) row_size = 5 n_obs = 100 X = pd.DataFrame(np.random.randint(0,1000,n_obs).reshape((row_size,int(n_obs/row_size))) scaler = StandardScaler() scaler.fit(X) X_out = scaler.transform(X) X_out = pd.DataFrame(X_out) </code></pre> <p>All columns have standard deviation <code>1.1180...</code> as opposed to 1.</p> <pre><code>X_out[0].mean() &gt;&gt;Out[2]: 4.4408920985006264e-17 X_out[0].std() &gt;&gt;Out[3]: 1.1180339887498947 </code></pre> <p><strong>EDIT:</strong> I have realised as I increase <code>row_size</code> above, e.g. from 5 to 10 and 100, the standard deviation of the columns approach 1. So maybe this is to do with the bias of the variance estimator getting smaller as n increases(?). However it does not make sense that I can get unit variance by manually implementing <code>(col[i]- col[i].mean() )/ col[i].std()</code> but the StandardScaler struggles...</p>
<p>Numpy and Pandas use different definitions of standard deviation (biased vs. unbiased). Sklearn uses the numpy definition, thus the result of <code>scaler.transform(X).std(axis=1)</code> results in <code>1</code>s.</p> <p>But then you wrap the standardized values <code>X_out</code> in a pandas DataFrame and ask pandas to give you the standard deviation for the same values, which then results in your observation.</p> <p>For most cases you only care for all columns having the same spread, thus the differences are not important. But if you really want the unbiased standard deviation, you can't use the StandardScaler from sklearn.</p>
python|scikit-learn|standardized|standardization
1
1,905,013
55,055,965
Python read XML file (near 50mb)
<p>I'm parsing a XML String into CSV string but it's going very slow:</p> <pre><code>INDEX_COLUMN = "{urn:schemas-microsoft-com:office:spreadsheet}Index" CELL_ELEMENT = "Cell" DATA_ELEMENT = "Data" def parse_to_csv_string(xml): print('parse_to_csv_string') csv = [] parsed_data = serialize_xml(xml) rows = list(parsed_data[1][0]) header = get_cells_text(rows[0]) rows.pop(0) csv.append(join(",", header)) for row in rows: values = get_cells_text(row) csv.append(join(",", values)) return join("\n", csv) def serialize_xml(xml): return ET.fromstring(xml) def get_cells_text(row): keys = [] cells = normalize_row_cells(row) for elm in cells: keys.append(elm[0].text or "") while len(keys) &lt; 92: keys.append("") return keys def normalize_row_cells(row): cells = list(row) updated_cells = copy.deepcopy(cells) pos = 1 for elm in cells: strIndexAttr = elm.get(INDEX_COLUMN) index = int(strIndexAttr) if strIndexAttr else pos while index &gt; pos: empty_elm = ET.Element(CELL_ELEMENT) child = ET.SubElement(empty_elm, DATA_ELEMENT) child.text = "" updated_cells.insert(pos - 1, empty_elm) pos += 1 pos += 1 return updated_cells </code></pre> <p>The XML String sometimes miss a few columns and I need to iterate it to fill missing columns - every row must have 92 columns. That's why I have some helper functions to manipulate XML.</p> <p>Right now I'm running my function with 4GB as Lambda and still getting timeout :(</p> <p>Any idea on how to improve performance?</p>
<p>The <code>normalize_row_cells</code> constructs ElementTree Element instances but <code>get_cells_text</code> is only interested in each instance's child's text attribute, so I would consider changing <code>normalize_row_cells</code> to just return the text. Also, it's performing copies and calling <code>list.insert</code>: inserting elements into the middle of lists can be expensive, because each element after the insertion point must be moved.</p> <p>Something like this (untested code) avoids making copies and insertions and returns only the required text, making <code>get_cells_text</code> redundant.</p> <pre><code>def normalize_row_cells(row): cells = list(row) updated_cells = [] pos = 1 for _ in range(0, 92): elm = cells[pos - 1] strIndexAttr = elm.get(INDEX_COLUMN) index = int(strIndexAttr) if strIndexAttr else pos if index == pos: updated_cells.append(elm[0].text) pos += 1 else: update_cells.append("") return updated_cells </code></pre> <p>If you can match your cells to their header names then using <a href="https://docs.python.org/3/library/csv.html#csv.DictWriter" rel="nofollow noreferrer">csv.DictWriter</a> from the standard library might be even better (you need to profile to be sure).</p> <pre><code>import csv import io def parse_to_csv_string(xml): print('parse_to_csv_string') csv = [] parsed_data = serialize_xml(xml) rows = list(parsed_data[1][0]) header = get_cells_text(rows[0]) with io.StringIO() as f: writer = csv.DictWriter(f, fieldnames=header) for row in rows: row = get_cells_text(row) writer.writerow(row) f.seek(0) data = f.read() return data def get_cells_text(row): row_dict = {} for cell in row: column_name = get_column_name(cell) # &lt;- can this be done? row_dict[column_name] = elm[0].text or "" return row_dict </code></pre>
python
0
1,905,014
33,467,777
Python tkinter delete tuple tag
<p>On a tkinter window, I have a setup that has a grid, and whenever you click a square on the grid, the square changes color. If you click the same square again, the color changes back.</p> <p>To do this however, I've just been painting over the same square with the same 2 colors, creating thousands of images after enough clicks.</p> <p>To identify each grid square, I use the grid square's top left coordinate. I tried using tkinter tags by passing in the tuple of two coordinates (x, y) to a <code>create_rectangle</code> function, and then calling <code>canvas.delete(coords)</code>. However, this doesn't seem to work at all. It seems like when using</p> <p><code>canvas.create_rectangle(whatever, tags=coords)</code></p> <p>no matter what data type I make the coords, or whatever I do with them, tkinter seems to do something weird to them making me unable to delete them with any variation of</p> <p><code>canvas.delete(coords)</code></p> <p>Does anybody have a solution to this? I've been searching on the minimal tkinter documentation. All I want is to delete a colored square on a grid, rather than paint over it again.</p> <p>Here's some code to illustrate trying to delete a square using the same principle:</p> <pre><code>from tkinter import * master = Tk() canvas_width = 850 canvas_height = 650 tCanvas = Canvas(master, width=canvas_width, height=canvas_height) coordinates = (562, 130) tkinterObject = tCanvas.create_rectangle(0, 0, 100, 100, fill='black', tags=(coordinates)) tCanvas.delete(coordinates) tCanvas.pack() mainloop() </code></pre> <p>In the example above, the square is not deleted.</p>
<p>The <code>tags</code> attribute should be given a tuple of tags. The tag you are trying to create should be a tuple of the x and y coordinates. Thus, you need to give it a tuple of tuples. </p> <p>Notice the use of a comma in the tags attribute in the following example, which guarantees that the data in the parenthesis is treated as a tuple. This isn't a tkinter thing, it's just how tuples work in python. </p> <pre><code>tag = (x,y) canvas.create_rectangle(..., tags=(tag,)) </code></pre> <p>That being said, you can get the item id of the item that was clicked on by using the tag <code>current</code>:</p> <pre><code>the_item = canvas.find_withtag("current") </code></pre>
python|canvas|tkinter
0
1,905,015
33,149,120
input() and literal unicode parsing
<p>Using <code>input()</code> takes a backslash as a literal backslash so I am unable to parse a string input with unicode.</p> <p>What I mean:</p> <p>Pasting a string like <code>"\uXXXX\uXXXX\uXXXX"</code> into an <code>input()</code> call will become interpreted as <code>"\\uXXXX\\uXXXX\\uXXXX"</code> but I want it read <code>\u</code> as a single character instead of two separate characters. </p> <p>Does anyone know how or if possible to make it happen?</p> <p>Edit: I am taking input as above and converting it to ascii such as below..</p> <pre><code>import unicodedata def Reveal(unicodeSol): solution = unicodedata.normalize('NFKD', unicodeSol).encode('ascii', 'ignore') print(solution) while(True): UserInput = input("Paste Now: ") Reveal(UserInput) </code></pre> <p>Per the answer I marked, a correct solution would be:</p> <pre><code>import unicodedata import ast def Reveal(unicodeSol): solution = unicodedata.normalize('NFKD', unicodeSol).encode('ascii', 'ignore') print(solution) while(True): UserInput = ast.literal_eval('"{}"'.format(input("Paste Now: "))) Reveal(UserInput) </code></pre>
<p>If you can be sure that input would not contain quotes, you can convert the input into a string literal representation, by adding quotes in both ends , and then use <code>ast.literal_eval()</code> to evaluate it into a string. Example -</p> <pre><code>import ast inp = input("Input : ") res = ast.literal_eval('"{}"'.format(inp)) </code></pre> <p>If the input can contain quotes you can replace double quotes with <code>r'\"'</code> before evaluating using ast.literal_eval .</p>
python|python-3.x|input|unicode|unicode-literals
2
1,905,016
73,743,403
Python, plot matrix diagonal elements
<p>I have an 120x70 matrix of which I want to graph diagonal lines.</p> <p>for ease of typing here, I will explain my problem with a smaller 4x4 matrix.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>2020</th> <th>2021</th> <th>2022</th> <th>2023</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1</td> <td>2</td> <td>5</td> <td>7</td> </tr> <tr> <td>1</td> <td>3</td> <td>5</td> <td>8</td> <td>10</td> </tr> <tr> <td>0</td> <td>1</td> <td>2</td> <td>5</td> <td>3</td> </tr> <tr> <td>1</td> <td>3</td> <td>5</td> <td>8</td> <td>4</td> </tr> </tbody> </table> </div> <p>I now want to graph for example starting at 2021 index 0 so that I get the following diagonal numbers in a graphs: 2, 8, 10</p> <p>or if I started at 2020 I would get 1, 5, 5, 4.</p> <p>Kind regards!</p>
<p>You can do this with a simple for-loop. e.g.:</p> <pre><code>matrix = np.array((120, 70)) graph_points = [] column_index = 0 # Change this to whatever column you want to start at for i in range(matrix.shape[0]): graph_points.append(matrix[i, column_index]) column_index += 1 if column_index &gt;= matrix.shape[1]: break ## Plot graph_points here </code></pre>
python|matplotlib|matrix
1
1,905,017
73,773,998
Python program question snake game, box making using, random fun
<p>I am new to python. I tried to make a python snake game and I got a problem with making a small rectangle on the screen which should appear on screen every time I run the program. But the rectangle is moving very fast I don't know why. just tell me how to code so that the rectangle stays in one place and changes position every time I run the program</p> <pre><code>import pygame,sys from pygame.math import Vector2 import random pygame.init() class fruit: def __init__(self): self.x=random.randint(0,size_y-1) self.y=random.randint(0,size_y-1) self.pos=Vector2(self.x,self.y) def draw_fruit(self): fruit_draw=pygame.Rect(self.pos.x*size_x,self.pos.y*size_x,size_x,size_x) pygame.draw.rect(screen,(200,150,160),fruit_draw) size_x=30 size_y=25 screen=pygame.display.set_mode((size_y*size_x,size_y*size_x)) while True: for event in pygame.event.get(): if event.type==pygame.QUIT: quit() screen.fill(pygame.Color(&quot;dark green&quot;)) fruit().draw_fruit() pygame.display.flip() </code></pre>
<p>You are creating new fruit object every time loop does iteration. You need to initialize it outside that loop. Also class names should be uppercase.</p> <pre><code>import pygame,sys from pygame.math import Vector2 import random pygame.init() class Fruit: def __init__(self): self.x=random.randint(0,size_y-1) self.y=random.randint(0,size_y-1) self.pos=Vector2(self.x,self.y) def draw_fruit(self): fruit_draw=pygame.Rect(self.pos.x*size_x,self.pos.y*size_x,size_x,size_x) pygame.draw.rect(screen,(200,150,160),fruit_draw) size_x=30 size_y=25 screen=pygame.display.set_mode((size_y*size_x,size_y*size_x)) fruit = Fruit() # fruit is now object, while True: for event in pygame.event.get(): if event.type==pygame.QUIT: quit() screen.fill(pygame.Color(&quot;dark green&quot;)) fruit.draw_fruit() # drawing existing object. pygame.display.update() </code></pre>
python|pygame
0
1,905,018
73,716,682
how can i Improve this model using GridSearchCV with Pipeline
<p>I am trying to Improve a Regression Model using GridSearchCV with Pipeline, but I ran into an error. if i am not worn then, it points to <code>Invalid Paramaters</code>, I've cross checked the parameters properly, but still i can't debug the code.</p> <pre><code>## importing libraries import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder ## importing the model from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split, GridSearchCV ## setup random seed() import numpy as np np.random.seed(42) ## Import Data and Drop rows with Missing Labels data = pd.read_csv(&quot;Data/car-sales-extended-missing-data.csv&quot;) data.dropna(subset=[&quot;Price&quot;],inplace=True) ## Define categorical columns categorical_features = [&quot;Make&quot;, &quot;Colour&quot;] # Create categorical transformer (imputes missing values, then one hot encodes them) categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('onehot', OneHotEncoder(handle_unknown='ignore')) ]) # Define door feature door_feature = [&quot;Doors&quot;] # Create door transformer (fills all door missing values with 4) door_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value=4)), ]) # Define numeric featrue numeric_features = [&quot;Odometer (KM)&quot;] # Create a transformer for filling all missing numeric values with the mean numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='mean')) ]) # Create a column transformer which combines all of the other transformers # into one step preprocessor = ColumnTransformer( transformers=[ ('categorical', categorical_transformer, categorical_features), ('door', door_transformer, door_feature), ('numerical', numeric_transformer, numeric_features) ]) # Create the model pipeline model = Pipeline(steps=[('preprocessor', preprocessor), # this will fill our missing data and make sure it's all numbers ('regressor', RandomForestRegressor())]) # this will model our data #split data x = data.drop(&quot;Price&quot;,axis=1) y = data[&quot;Price&quot;] # Split data into train and teset sets x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) # Fit the model on the training data #(note: when fit() is called with a Pipeline(), fit_transform() is used for transformers) model.fit(X_train, y_train) # Score the model on the data # (note: when score() or predict() is called with a Pipeline(), transform() is used for transformers) model.score(X_test, y_test) </code></pre> <h3>The GridSearch Tuning</h3> <p>Tuning the model above with GridSearchCV using Pipeline</p> <pre><code>## from sklearn.model_selection import GridSearchCV ## Already Imported above. pipe_grid = { &quot;preprocessor__num__imputer__strategy&quot;: [&quot;mean&quot;, &quot;median&quot;], &quot;model__e_estimators&quot;: [100, 1000], &quot;model__max_depth&quot;: [None], &quot;model__max_features&quot;: [&quot;auto&quot;], &quot;model__min_samples_split&quot;: [2, 4] } gs_model = GridSearchCV(model,pipe_grid,cv=5,verbose=2) gs_model.fit(x_train,y_train) </code></pre> <p>Here's the Error i got, After passing some hyperparameter's to Improve on the model.</p> <pre><code>Fitting 5 folds for each of 8 candidates, totalling 40 fits --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [34], in &lt;cell line: 12&gt;() 3 pipe_grid = { 4 &quot;preprocessor__num__imputer__strategy&quot;: [&quot;mean&quot;, &quot;median&quot;], 5 &quot;model__e_estimators&quot;: [100, 1000], (...) 8 &quot;model__min_samples_split&quot;: [2, 4] 9 } 11 gs_model = GridSearchCV(model,pipe_grid,cv=5,verbose=2) ---&gt; 12 gs_model.fit(x_train,y_train) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\model_selection\_search.py:875, in BaseSearchCV.fit(self, X, y, groups, **fit_params) 869 results = self._format_results( 870 all_candidate_params, n_splits, all_out, all_more_results 871 ) 873 return results --&gt; 875 self._run_search(evaluate_candidates) 877 # multimetric is determined here because in the case of a callable 878 # self.scoring the return type is only known after calling 879 first_test_score = all_out[0][&quot;test_scores&quot;] File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\model_selection\_search.py:1375, in GridSearchCV._run_search(self, evaluate_candidates) 1373 def _run_search(self, evaluate_candidates): 1374 &quot;&quot;&quot;Search all candidates in param_grid&quot;&quot;&quot; -&gt; 1375 evaluate_candidates(ParameterGrid(self.param_grid)) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\model_selection\_search.py:822, in BaseSearchCV.fit.&lt;locals&gt;.evaluate_candidates(candidate_params, cv, more_results) 814 if self.verbose &gt; 0: 815 print( 816 &quot;Fitting {0} folds for each of {1} candidates,&quot; 817 &quot; totalling {2} fits&quot;.format( 818 n_splits, n_candidates, n_candidates * n_splits 819 ) 820 ) --&gt; 822 out = parallel( 823 delayed(_fit_and_score)( 824 clone(base_estimator), 825 X, 826 y, 827 train=train, 828 test=test, 829 parameters=parameters, 830 split_progress=(split_idx, n_splits), 831 candidate_progress=(cand_idx, n_candidates), 832 **fit_and_score_kwargs, 833 ) 834 for (cand_idx, parameters), (split_idx, (train, test)) in product( 835 enumerate(candidate_params), enumerate(cv.split(X, y, groups)) 836 ) 837 ) 839 if len(out) &lt; 1: 840 raise ValueError( 841 &quot;No fits were performed. &quot; 842 &quot;Was the CV iterator empty? &quot; 843 &quot;Were there no candidates?&quot; 844 ) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\parallel.py:1043, in Parallel.__call__(self, iterable) 1034 try: 1035 # Only set self._iterating to True if at least a batch 1036 # was dispatched. In particular this covers the edge (...) 1040 # was very quick and its callback already dispatched all the 1041 # remaining jobs. 1042 self._iterating = False -&gt; 1043 if self.dispatch_one_batch(iterator): 1044 self._iterating = self._original_iterator is not None 1046 while self.dispatch_one_batch(iterator): File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\parallel.py:861, in Parallel.dispatch_one_batch(self, iterator) 859 return False 860 else: --&gt; 861 self._dispatch(tasks) 862 return True File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\parallel.py:779, in Parallel._dispatch(self, batch) 777 with self._lock: 778 job_idx = len(self._jobs) --&gt; 779 job = self._backend.apply_async(batch, callback=cb) 780 # A job can complete so quickly than its callback is 781 # called before we get here, causing self._jobs to 782 # grow. To ensure correct results ordering, .insert is 783 # used (rather than .append) in the following line 784 self._jobs.insert(job_idx, job) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\_parallel_backends.py:208, in SequentialBackend.apply_async(self, func, callback) 206 def apply_async(self, func, callback=None): 207 &quot;&quot;&quot;Schedule a func to be run&quot;&quot;&quot; --&gt; 208 result = ImmediateResult(func) 209 if callback: 210 callback(result) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\_parallel_backends.py:572, in ImmediateResult.__init__(self, batch) 569 def __init__(self, batch): 570 # Don't delay the application, to avoid keeping the input 571 # arguments in memory --&gt; 572 self.results = batch() File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\parallel.py:262, in BatchedCalls.__call__(self) 258 def __call__(self): 259 # Set the default nested backend to self._backend but do not set the 260 # change the default number of processes to -1 261 with parallel_backend(self._backend, n_jobs=self._n_jobs): --&gt; 262 return [func(*args, **kwargs) 263 for func, args, kwargs in self.items] File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\joblib\parallel.py:262, in &lt;listcomp&gt;(.0) 258 def __call__(self): 259 # Set the default nested backend to self._backend but do not set the 260 # change the default number of processes to -1 261 with parallel_backend(self._backend, n_jobs=self._n_jobs): --&gt; 262 return [func(*args, **kwargs) 263 for func, args, kwargs in self.items] File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\utils\fixes.py:117, in _FuncWrapper.__call__(self, *args, **kwargs) 115 def __call__(self, *args, **kwargs): 116 with config_context(**self.config): --&gt; 117 return self.function(*args, **kwargs) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\model_selection\_validation.py:674, in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, return_n_test_samples, return_times, return_estimator, split_progress, candidate_progress, error_score) 671 for k, v in parameters.items(): 672 cloned_parameters[k] = clone(v, safe=False) --&gt; 674 estimator = estimator.set_params(**cloned_parameters) 676 start_time = time.time() 678 X_train, y_train = _safe_split(estimator, X, y, train) File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\pipeline.py:188, in Pipeline.set_params(self, **kwargs) 169 def set_params(self, **kwargs): 170 &quot;&quot;&quot;Set the parameters of this estimator. 171 172 Valid parameter keys can be listed with ``get_params()``. Note that (...) 186 Pipeline class instance. 187 &quot;&quot;&quot; --&gt; 188 self._set_params(&quot;steps&quot;, **kwargs) 189 return self File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\utils\metaestimators.py:72, in _BaseComposition._set_params(self, attr, **params) 69 self._replace_estimator(attr, name, params.pop(name)) 71 # 3. Step parameters and other initialisation arguments ---&gt; 72 super().set_params(**params) 73 return self File ~\Desktop\ML-course\sample_project_1\env\lib\site-packages\sklearn\base.py:246, in BaseEstimator.set_params(self, **params) 244 if key not in valid_params: 245 local_valid_params = self._get_param_names() --&gt; 246 raise ValueError( 247 f&quot;Invalid parameter {key!r} for estimator {self}. &quot; 248 f&quot;Valid parameters are: {local_valid_params!r}.&quot; 249 ) 251 if delim: 252 nested_params[key][sub_key] = value ValueError: Invalid parameter 'model' for estimator Pipeline(steps=[('preprocessor', ColumnTransformer(transformers=[('categorical', Pipeline(steps=[('imputer', SimpleImputer(fill_value='missing', strategy='constant')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]), ['Make', 'Colour']), ('door', Pipeline(steps=[('imputer', SimpleImputer(fill_value=4, strategy='constant'))]), ['Doors']), ('numerical', Pipeline(steps=[('imputer', SimpleImputer())]), ['Odometer (KM)'])])), ('regressor', RandomForestRegressor())]). Valid parameters are: ['memory', 'steps', 'verbose']. </code></pre>
<p>The prefix should be <code>regressor__</code>, not <code>model__</code>, according to your pipeline steps naming. There also seems to be a typo in <code>n_estimators</code>:</p> <pre><code>pipe_grid = { &quot;preprocessor__num__imputer__strategy&quot;: [&quot;mean&quot;, &quot;median&quot;], &quot;regressor__n_estimators&quot;: [100, 1000], &quot;regressor__max_depth&quot;: [None], &quot;regressor__max_features&quot;: [&quot;auto&quot;], &quot;regressor__min_samples_split&quot;: [2, 4] } </code></pre>
python|machine-learning|scikit-learn|pipeline
0
1,905,019
21,670,430
How to provide pemfile password in pymongo mongoclient in the connection string
<p>Question: How to provide pemfile password in pymongo mongoclient in the connection string? </p> <pre><code>import pymongo from pymongo import MongoClient sslCAFile = data['COMMON_SETTINGS']['sslCAFile'] //reading cafile path from configurationfile sslpemkeyfile = data['COMMON_SETTINGS']['sslpemkeyfile'] //reading pemfile path from configurationfile(which is encrypted with password) </code></pre> <p>// now i need to connect by giving the password . but i dont see any parameter for that in pymongo documentation and in authentication examples</p> <pre><code> connection = MongoClient(mongos_ip,int(mongos_port),ssl=True,ssl_certfile=sslpemkeyfile,ssl_ca_certs=sslCAFile) </code></pre> <p>//Help me on this!!!</p>
<p>Unfortunately the current version of pymongo doesn't support this feature</p> <p><strong>ref:</strong> <a href="https://jira.mongodb.org/browse/PYTHON-640" rel="nofollow">https://jira.mongodb.org/browse/PYTHON-640</a></p>
mongodb|python-2.7|pymongo
1
1,905,020
21,860,382
Get output of Python command using Popen
<p>I'm trying to execute a shell command from within Python (2.6.4) to evaluate a simple formula before passing it as an argument to another program. My input is something simple like this:</p> <blockquote> <p>$[2*2]</p> </blockquote> <p>I want to evaluate that expression and get the result from within my Python script so I can use it later. Currently, I'm doing this (where <code>token</code> is <code>$[2*2]</code>):</p> <pre><code>token = subprocess.Popen(["echo", token], stdout=subprocess.PIPE).communicate()[0].strip() </code></pre> <p>I expect the output to be <code>4</code>, but instead it's just giving me back my original token (<code>$[2*2]</code>). Obviously when I jump to the shell and run this command by hand (<code>echo $[2*2]</code>), I get <code>4</code> as expected.</p> <p>Is there something special about how Python executes this command that I'm missing?</p>
<p>When you run <code>echo $[2*2]</code> in your shell, the <strong>shell</strong> evaluates <code>$[2*2]</code> and passes the results of that evaluation to the <code>echo</code> command. In your Python code, you are passing the <code>$[2*2]</code> to echo directly and hence, it is returning just that.</p> <p>You can invoke a shell to evaluate your command using <code>shell=True</code> in <code>subprocess.Popen</code>:</p> <pre><code>token = subprocess.Popen(["echo " + token], stdout=subprocess.PIPE, shell=True).communicate()[0].strip() </code></pre>
python|bash|shell
2
1,905,021
41,179,077
Data scraping using python webdriver
<p><a href="https://i.stack.imgur.com/0Ayka.png" rel="nofollow noreferrer">codesample</a></p> <p>I am trying to click a button using Firefox - python - webdriver</p> <p>But every time error comes: </p> <pre class="lang-none prettyprint-override"><code>selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .pull-right show-toggle with-icon </code></pre> <p>Am I missing something here? after login and couple of steps I am reaching on one page where I need to click on the button with below class name.</p> <pre><code>child = driver.find_element_by_class_name('pull-right show-toggle with-icon') child.click() </code></pre> <p>Any other way of doing this ?</p>
<p>As per provided piece of <code>HTML</code>, you can click your button with following code:</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait button = wait(driver, 10).until(EC.visibility_of_element_located((By.XPATH,"//a[@data-toggle-text='Hide details']"))) button.click() </code></pre>
python|html|selenium|webdriver
1
1,905,022
38,194,802
Python: How to have a user input a string to test if equal to var
<p>So I am new to python and I know the very basics. I am making a sort of database, but you need a password to get in. I have a variable that is equal to the password, but I can't figure out how to have the user input something, then it tests if it is equal to the variable. I have a basic if statement, but I can't get the input. Here is my code currently:</p> <pre><code>print("Welcome to the NCPDFR Information Database. \nPlease print Password") pw = "US1151944MC" if pw = "US1151944MC": print("Please enter name of search recipient") else: print("Password Invalid") </code></pre>
<p>If you want to get user input (and mask it) you can do:</p> <pre><code>import getpass password = getpass.getpass() </code></pre> <p>For inputs that you don't want/need to mask in python, you can do:</p> <pre><code>user_input = raw_input("Please enter some text: ") </code></pre> <p>Note: <code>raw_input</code> is very much preferred over <code>input</code></p>
python|variables|input
2
1,905,023
40,310,581
Python- Calling Functions
<p>I apologise in advance that this is a really nooby question. Just out of curiosity, what is the difference between (for example) function(a) and a.function()? Thanks for any answers.</p>
<pre><code>class Example(): def __init__(self): self.x = 1 def change_x(self): self.x = 5 print(self.x) def example_function(x): print(x) a= Example() a.change_x() #calling the object function of example_function("hello") #calling the function in scope #prints &gt;&gt; 5 # &gt;&gt; hello </code></pre> <p>When you <code>something.function()</code> you are calling the function of that object.</p> <p>When you are <code>function()</code> you are calling the function within scope that is defined in your namespace.</p>
python|function
1
1,905,024
40,009,850
What is the meaning of the object in the python classes
<p>what is the meaning of the following command:</p> <pre><code>def run_initial(self) -&gt; object: </code></pre> <p>I don't know why he put <code>object</code> after the arrow. What is the meaning of the object here?</p>
<p>They are type annotations.</p> <p>Type annotations are type hints that were brought in with <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">pep-0484</a>. They were made to allow developers to use third party tools or modules that consume these to give more information to the user about types for example.</p> <p>The more obvious use case imho right now is that the Python visual editor PyCharm (which is afaik the most used pycharm editor after sublime, which is not a complete editor) supports them to give programmers information about types, and for auto complete.</p> <p>See <a href="https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html</a></p>
python|class|object
1
1,905,025
52,113,181
pandas strings ends with values of a column and then convert the beginning of the strings into a date for comparisons
<p>I have the following <code>df</code>,</p> <pre><code>cluster_id amount inv_id inv_date 1 309.9 07121830990 2018-07-12 1 309.9 07121830990 2018-07-12 2 3130.0 20180501313000B 2018-05-01 2 3130.0 20180501313000B 2018-05-01 3 3330.50 201804253330.50 2018-04-25 3 3330.50 201804253330.50 2018-04-25 4 70.0 61518 2018-06-15 4 70.0 61518 2018-06-15 5 100.0 011318 2018-01-13 5 100.0 011318 2018-01-13 6 50.0 12202017 2017-12-20 6 50.0 12202017 2017-12-20 7 101.0 0000014482 2017-10-01 7 101.0 0000014482 2017-10-01 </code></pre> <p>I want to create a boolean column <code>dummy_inv_id</code> by <code>groupby</code> <code>cluster_id</code>, and set <code>dummy_invoice_id</code> to <code>True</code> if for each group,</p> <pre><code>1. inv_id (stripped non-numerics) ends with amount and the remaining part of inv_id can be coerced into a valid date which is +/- 180 days of the inv_date </code></pre> <p>or </p> <pre><code>2. inv_id (stripped non-numerics) can be coerced into a date which is +/- 180 days of the inv_date </code></pre> <p>First, I will remove any non-numerics chars from <code>inv_id</code> and <code>groupby</code> <code>cluster_id</code></p> <pre><code>df['inv_id_stp'] = df.inv_id.str.replace(r'\D+', '') grouped = df.groupby('cluster_id') </code></pre> <p>then convert <code>amount</code> * 100 to string to facilitate matching</p> <pre><code>df['amount'] = df['amount']*100 df['amt_str'] = df['amount'].apply(str) </code></pre> <p>e.g. <code>309.9</code> to <code>'30990'</code>, <code>3130.0</code> to <code>'313000'</code>, here I am wondering how to check the <code>inv_id</code> ends with <code>amount</code> here, and then how to check if the remaining part of <code>inv_id</code> can be converted into <code>datetime</code> and within +/-180 days of <code>inv_date</code>, or if <code>inv_id</code> can be directly converted to date. especially there are a few of date formats, i.e.</p> <pre><code>071218 - 2018-07-12 20180501 - 2018-05-01 61518 - 2018-06-15 12202017 - 2017-12-20 0000014482 - cannot be converted to date </code></pre> <p>the result <code>df</code> will look like,</p> <pre><code>cluster_id amount inv_id inv_date dummy_inv_id 1 309.9 07121830990 2018-07-12 True 1 309.9 07121830990 2018-07-12 True 2 3130.0 20180501313000B 2018-05-01 True 2 3130.0 20180501313000B 2018-05-01 True 3 3330.50 201804253330.50 2018-04-25 True 3 3330.50 201804253330.50 2018-04-25 True 4 70.0 61518 2018-06-15 True 4 70.0 61518 2018-06-15 True 5 100.0 011318 2018-01-13 True 5 100.0 011318 2018-01-13 True 6 50.0 12202017 2017-12-20 True 6 50.0 12202017 2017-12-20 True 7 101.0 0000014482 2017-10-01 False 7 101.0 0000014482 2017-10-01 False </code></pre>
<p>Idea is create helper dictionary with possible formats of datetimes with number of letters for slicing and in list comprehension converting - <code>errors='coerce'</code> create <code>NaT</code>s for not matched values:</p> <pre><code>from functools import reduce #add zeros to length 6 s = df.inv_id.str.replace(r'\D+', '').str.zfill(6) formats = {'%m%d%y':6, '%y%m%d':6, '%Y%m%d':8, '%m%d%Y':8} L = [pd.to_datetime(s.str[:v], format=k, errors='coerce') for k,v in formats.items()] </code></pre> <p>But some formats should convert bad, so these datetimes outside of range convert to <code>NaT</code>:</p> <pre><code>L = [x.where(x.between('2000-01-01', pd.datetime.now())) for x in L] </code></pre> <p>And combine all non NaT values togther by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>Series.combine_first</code></a>:</p> <pre><code>s2 = reduce(lambda l,r: pd.Series.combine_first(l,r), L) print (s2) 0 2018-07-12 1 2018-07-12 2 2018-05-01 3 2018-05-01 4 2018-04-25 5 2018-04-25 6 2018-06-15 7 2018-06-15 8 2018-01-13 9 2018-01-13 10 2017-12-20 11 2017-12-20 12 NaT 13 NaT Name: inv_id, dtype: datetime64[ns] </code></pre> <p>Last check <code>+-180</code> days:</p> <pre><code>df['new'] = s2.between(s2 - pd.Timedelta(180, unit='d'), s2 + pd.Timedelta(180, unit='d')) </code></pre> <hr> <pre><code>print (df) cluster_id amount inv_id inv_date new 0 1 309.9 07121830990 2018-07-12 True 1 1 309.9 07121830990 2018-07-12 True 2 2 3130.0 20180501313000B 2018-05-01 True 3 2 3130.0 20180501313000B 2018-05-01 True 4 3 3330.5 201804253330.50 2018-04-25 True 5 3 3330.5 201804253330.50 2018-04-25 True 6 4 70.0 61518 2018-06-15 True 7 4 70.0 61518 2018-06-15 True 8 5 100.0 011318 2018-01-13 True 9 5 100.0 011318 2018-01-13 True 10 6 50.0 12202017 2017-12-20 True 11 6 50.0 12202017 2017-12-20 True 12 7 101.0 0000014482 2017-10-01 False 13 7 101.0 0000014482 2017-10-01 False </code></pre> <p>EDIT:</p> <p>Added solution for remove substrings from ends:</p> <pre><code>import re from functools import reduce df['amt_str'] = (df['amount']*100).round().astype(int).astype(str) df['inv_str'] = df.inv_id.str.replace(r'\D+', '').str.zfill(6) #https://stackoverflow.com/a/1038845/2901002 df['inv_str'] = df.apply(lambda x: re.sub('{}$'.format(x['amt_str']),'', x['inv_str']),axis=1) print (df) cluster_id amount inv_id inv_date amt_str inv_str 0 1 309.9 07121830990 2018-07-12 30990 071218 1 1 309.9 07121830990 2018-07-12 30990 071218 2 2 3130.0 20180501313000B 2018-05-01 313000 20180501 3 2 3130.0 20180501313000B 2018-05-01 313000 20180501 4 3 3330.5 201804253330.50 2018-04-25 333050 20180425 5 3 3330.5 201804253330.50 2018-04-25 333050 20180425 6 4 70.0 61518 2018-06-15 7000 061518 7 4 70.0 61518 2018-06-15 7000 061518 8 5 100.0 011318 2018-01-13 10000 011318 9 5 100.0 011318 2018-01-13 10000 011318 10 6 50.0 12202017 2017-12-20 5000 12202017 11 6 50.0 12202017 2017-12-20 5000 12202017 12 7 101.0 0000014482 2017-10-01 10100 0000014482 13 7 101.0 0000014482 2017-10-01 10100 0000014482 </code></pre> <hr> <pre><code>formats = {'%m%d%y':6, '%y%m%d':6, '%Y%m%d':8, '%m%d%Y':8} L=[pd.to_datetime(df['inv_str'].str[:v],format=k, errors='coerce') for k,v in formats.items()] L = [x.where(x.between('2000-01-01', pd.datetime.now())) for x in L] s2 = reduce(lambda l,r: pd.Series.combine_first(l,r), L) df['new'] = s2.between(s2 - pd.Timedelta(180, unit='d'), s2 + pd.Timedelta(180, unit='d')) print (df) cluster_id amount inv_id inv_date amt_str inv_str new 0 1 309.9 07121830990 2018-07-12 30990 071218 True 1 1 309.9 07121830990 2018-07-12 30990 071218 True 2 2 3130.0 20180501313000B 2018-05-01 313000 20180501 True 3 2 3130.0 20180501313000B 2018-05-01 313000 20180501 True 4 3 3330.5 201804253330.50 2018-04-25 333050 20180425 True 5 3 3330.5 201804253330.50 2018-04-25 333050 20180425 True 6 4 70.0 61518 2018-06-15 7000 061518 True 7 4 70.0 61518 2018-06-15 7000 061518 True 8 5 100.0 011318 2018-01-13 10000 011318 True 9 5 100.0 011318 2018-01-13 10000 011318 True 10 6 50.0 12202017 2017-12-20 5000 12202017 True 11 6 50.0 12202017 2017-12-20 5000 12202017 True 12 7 101.0 0000014482 2017-10-01 10100 0000014482 False 13 7 101.0 0000014482 2017-10-01 10100 0000014482 False </code></pre>
python|python-3.x|pandas|dataframe|pandas-groupby
1
1,905,026
52,142,180
Saving pages with Selenium
<p>I will try again. </p> <p>The code below I copied from another site and the user say it works (shows a screenshot).<a href="https://sqa.stackexchange.com/questions/33407/how-to-save-an-webpage-as-a-xml-file-using-python-and-selenium">Original code</a></p> <p>I tested the code: No error, but no file save.</p> <p>All questions use this answer to save a file: <a href="https://stackoverflow.com/questions/44664044/keystrokes-with-google-chrome-firefox-and-selenium-not-working-in-python">A question!</a></p> <p>why the page is not saved or, if it is, where is the file?</p> <p>Thanks</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Selenium\chromedriver.exe") driver.get("http://www.example.com") saveas = ActionChains(driver).key_down(Keys.CONTROL).send_keys('S').key_up(Keys.CONTROL) saveas.perform() </code></pre>
<pre><code>from selenium import webdriver driver = webdriver.Chrome(executable_path=r&quot;C:\Program Files (x86)\Selenium\chromedriver.exe&quot;) driver.get(&quot;http://www.example.com&quot;) with open('page.html', 'w+') as f: f.write(driver.page_source) </code></pre> <p>Must work</p>
python|selenium|google-chrome
4
1,905,027
52,153,256
DLL load failed in Pycharm/Anaconda/Scipy
<p>I'm trying this import from scikit-learn in Pycharm with Anaconda:</p> <pre><code>from sklearn.datasets import make_blobs </code></pre> <p>but I get this error:</p> <blockquote> <blockquote> <p>Traceback (most recent call last): File "D:/Google Drive/Apoyo/Proactivo/Afilar la sierra/Programación/Curso Udemy Tensorflow/pruebas.py", line 4, in from sklearn.datasets import make_blobs File "C:\Users\alvar\AppData\Roaming\Python\Python36\site-packages\sklearn__init__.py", line 134, in from .base import clone File "C:\Users\alvar\AppData\Roaming\Python\Python36\site-packages\sklearn\base.py", line 13, in from .utils.fixes import signature File "C:\Users\alvar\AppData\Roaming\Python\Python36\site-packages\sklearn\utils__init__.py", line 11, in from .validation import (as_float_array, File "C:\Users\alvar\AppData\Roaming\Python\Python36\site-packages\sklearn\utils\validation.py", line 18, in from ..utils.fixes import signature File "C:\Users\alvar\AppData\Roaming\Python\Python36\site-packages\sklearn\utils\fixes.py", line 144, in from scipy.sparse.linalg import lsqr as sparse_lsqr # noqa File "D:\Users\alvar\Anaconda3\lib\site-packages\scipy\sparse\linalg__init__.py", line 114, in from .isolve import * File "D:\Users\alvar\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve__init__.py", line 6, in from .iterative import * File "D:\Users\alvar\Anaconda3\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 10, in from . import _iterative ImportError: DLL load failed: No se puede encontrar el módulo especificado.</p> </blockquote> </blockquote> <p>I tried to uninstall and reinstall Numpy, Scipy, Scikit-Learn, update it, tried with numpy-mkl... with no success. The code works in Spyder.</p> <p>Thanks</p>
<p>Finally, I reinstalled all environment (IDE, Anaconda, TF...) and it works since then.</p> <p>Thanks you</p>
python|scikit-learn|scipy|pycharm|anaconda
0
1,905,028
51,997,777
Sykpe For Business message sending through Python
<p>how should i use in python3 to connect to Sky for Business and send some messages to user over it</p>
<p>The Official <a href="https://dev.skype.com/" rel="nofollow noreferrer">Skype Developer website</a> can give you the features it supports. But unfortunately the one you need is not there.</p> <p><a href="https://github.com/Skype4Py/Skype4Py" rel="nofollow noreferrer">Skype4Py</a> should do the trick. Its not an official library. Based on the docs:</p> <pre><code>from Skype4Py import Skype import sys client = Skype() client.Attach() user = sys.argv[1] message = ' '.join(sys.argv[2:] client.SendMessage(user, message) </code></pre> <p>This snippet should ideally help you out.</p> <p>[<strong>Update:</strong> Library compatibility with python 3.x is still a question. Alternatively you can also check <strong><a href="https://skpy.t.allofti.me/" rel="nofollow noreferrer">Skpy</a></strong> which also supports python 3.x]</p> <p>Hope it helped.</p>
python|python-3.x|skypedeveloper|skype4py
3
1,905,029
51,649,611
Spark fp growth is not giving multiple items in consequent
<p>I am using spark fp growth algorithm. I have given minsupport and confidence as o, so all combinations i should get</p> <pre><code>from pyspark.ml.fpm import FPGrowth df = spark.createDataFrame([ (0, [1, 2, 5]), (1, [1, 2, 3, 5]), (2, [1, 2]) ], ["id", "items"]) fpGrowth = FPGrowth(itemsCol="items", minSupport=0.0, minConfidence=0.0) model = fpGrowth.fit(df) # Display generated association rules. model.associationRules.show() </code></pre> <p>First problem is always my consequent contain only one element</p> <p>[1] -> [5, 2] should be a sample output freq of 1 is 3, freq of 5,2 is 2 and freq of [5, 2, 1]| is 2. so This should come in rules</p>
<p>The spark implementation is such that it would only return 1 element in the consequent. You can check the same in the below link. <a href="https://github.com/apache/spark/blob/master/mllib/src/main/scala/org/apache/spark/mllib/fpm/AssociationRules.scala" rel="nofollow noreferrer">https://github.com/apache/spark/blob/master/mllib/src/main/scala/org/apache/spark/mllib/fpm/AssociationRules.scala</a></p> <pre><code>//the consequent contains always only one element itemSupport.get(consequent.head)) </code></pre> <p>This is from the MLlib package(ML package uses MLlib implementation).</p> <p>Cheers,</p>
python-3.x|apache-spark|pyspark|apache-spark-ml
0
1,905,030
18,834,567
Conventions for amount of detail to put in Python exception messages?
<p>I am trying to determine some guidelines for how to write exception messages.</p> <p>For example, let us suppose a hypothetical function which must receive a constant number of bytes (as a <code>bytes</code> object), and we call it with <code>[1, 2, 3]</code>. The following are all potential exceptions:</p> <pre><code>1. TypeError 2. TypeError: argument must be 16 bytes 3. TypeError: argument must be 16 bytes; got 'list' 4. TypeError: argument must be 16 bytes; got 'list' [1, 2, 3] </code></pre> <p>Generally, I feel that the message should always explain the condition that wasn't met, but I'm on the fence about how much information to include about the offending object.</p> <p>Are there any guidelines on this subject?</p>
<p>Excellent question!</p> <p>When I am generally creating custom exceptions I usually go look at the Python set which is generally exhaustive. </p> <p>Now as for the question as to provide how much detail, I wouldn't make them too specific because you don't know what would be triggering them or causing them. </p> <p>In example:</p> <pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str' </code></pre> <p>is descriptive enough to let me know that the <code>+</code> operator isn't supported, I don't need know to know what the string contains. </p> <p>So in your example first two are perfectly fine, second two are overkill IMO.</p> <p>Goodluck.</p>
python|exception|conventions
2
1,905,031
18,936,436
Python-Twitter and access_token and access_token_secret
<p>I'm trying to use python-twitter to read my twitter feed and display it on my website. Everything worked fine until twitter required oAuth. I'm in the process of updating by scripts, but the python-twitter docs call for this:</p> <pre><code>api = twitter.Api(consumer_key='consumer_key', consumer_secret='consumer_secret', access_token_key='access_token', access_token_secret='access_token_secret') </code></pre> <p>I created an Twitter App (not sure of that is what I was supposed to do) and I have the <code>consumer_key</code> and the <code>consumer_secret</code>, but I don't know where to find the <code>access_token</code> or the <code>access_token_secret</code>. Am I missing something obvious?</p> <p>I just need to read my twitter feed. I don't need to post to it.</p>
<p>I was missing something obvious. You go to the oAuth Tools tab on the twitter dev site and you can find the <code>access_token</code> and the <code>access_token_secret</code>.</p>
python|twitter
1
1,905,032
36,290,330
Python for loop returning IndexError: list index out of range
<p>I have just recently began to learn python. I am trying to find the lowest integer in the digits list. Instead I get this error:</p> <pre><code>Traceback (most recent call last): File "H:/Python/untitled/08_python.py", line 32, in &lt;module&gt; if digits[e] &lt; temp: IndexError: list index out of range </code></pre> <p>I realize that you can use min(digits) but I thought I would challenge my knowledge so far. I most likely made a simple mistake and am not diagnosing it properly. If I throw 0 in the list everything works fine.</p> <pre><code>digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] low = 0 temp = 0 for e in digits: if digits[e] &lt; temp: low = digits[e] temp = digits[e] print(low) </code></pre>
<p><code>for e in digits</code> iterates over the <em>contents</em> of the list directly. You don't need to use <code>digits[e]</code> at that point since <code>e</code> is already the value, not the index. And that's also why it fails, since <code>digits[10]</code> is past the end of your list. </p> <p>Other minor note - your code will only work with positive numbers since you're starting with <code>low = 0</code>; if the list has negatives only you'll still get <code>0</code> as your result.<br> One way to avoid that by setting it to <code>None</code> at the beginning and checking for that as well:</p> <pre><code>low = None for e in digits: if low is None or low &lt; e: low = e print(low) </code></pre>
python|list|for-loop
6
1,905,033
13,507,989
how to write a function to add the integer of corresponding letter in python?
<p>how to write a function to add the integer of corresponding letter in python?</p> <p>for example:</p> <pre><code> L=[('a',3),('b',4),('c',5),('a',2),('c',2),('b',1)] </code></pre> <p>How to solve it by just loop over the item in L?</p>
<p>I guess the clearest way is just to loop through and add them up. </p> <pre><code>&gt;&gt;&gt; L=[('a',3),('b',4),('c',5),('a',2),('c',2),('b',1)] &gt;&gt;&gt; import collections &gt;&gt;&gt; d=collections.defaultdict(int) &gt;&gt;&gt; for key,n in L: ... d[key] += n ... &gt;&gt;&gt; sorted(d.items()) [('a', 5), ('b', 5), ('c', 7)] </code></pre>
python
4
1,905,034
22,385,701
Matplotlib triangles (plot_trisurf) color and grid
<p>I'm trying to plot a 3D surface with plot_trisurf like this:</p> <pre><code>xs = NP.array([ 0.00062 0.00661 0.02000 0.01569 0.00487 0.01784]) ys = NP.array([ 0.99999 0.66806 0.50798 0.61230 0.83209 0.86678]) zs = NP.array([-0.24255 -0.42215 -0.31854 -0.77384 -0.77906 -0.98167]) ax=fig.add_subplot(1,2,1, projection='3d') ax.grid(True) ax.plot_trisurf(xs, ys, zs, triangles = triangles, alpha = 0.0, color = 'grey') </code></pre> <p>This gives me<img src="https://i.stack.imgur.com/YhX55.png" alt="this plot"></p> <p>Now I have two problems:</p> <ol> <li>The triangles are black, can I change this problem? (It works in 2D with triplot with <code>color = 'grey'</code> but this doesn't seem to work here.</li> <li>(If it is visible) The grid of the 3D plot leaves traces in the triangles: it seems like the grid is printed on top of the triangles, while I (of course) want the triangles to be plotted on top of the grid.</li> </ol>
<p>change the last line to:</p> <pre><code>ax.plot_trisurf(xs, ys, zs, triangles=triangles, color=(0,0,0,0), edgecolor='Gray') </code></pre> <p>the <code>color</code> that you are specifying is used as <code>facecolor</code>; if you want to have transparent faces, instead of <code>alpha=0</code> pass <code>color=(r,g,b,0)</code>; the <code>0</code> in the tuple would be the alpha of the facecolor; so it will results in transparent faces;</p>
python|matplotlib|grid|geometry
4
1,905,035
22,425,855
Widgets not showing up on a Grid layout (PySide)
<p>I have some code that displays a few widgets in the window. The widgets, however do not appear on the window:</p> <pre><code>#!/usr/bin/python import sys from PySide import QtGui class Window(QtGui.QMainWindow): def __init__(self): super(Window,self).__init__() self.initUI() def initUI(self): self.setGeometry(200,500,400,400) self.setWindowTitle("A Grid Layout") l1 = QtGui.QLabel("Label 1") l2 = QtGui.QLabel("Label 2") l3 = QtGui.QLabel("Label 3") le1 = QtGui.QLineEdit() grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(l1,1,0)#widget,row,column grid.addWidget(l2,2,1) grid.addWidget(l3,3,2) grid.addWidget(le1,4,0,1,2)#row,column span self.setLayout(grid)#sets layout self.show() def main(): app = QtGui.QApplication(sys.argv) win = Window() exit(app.exec_()) if __name__ == "__main__": main() </code></pre> <p>I'm new to layouts in PySide so any help is much appreciated.</p>
<p>A <a href="http://pyside.github.io/docs/pyside/PySide/QtGui/QMainWindow.html#detailed-description" rel="noreferrer"><code>QMainWindow</code></a> isn't supposed to be used with a layout, but with a central widget containing it's content. Try this:</p> <pre><code>#!/usr/bin/python import sys from PySide import QtGui class Window(QtGui.QMainWindow): def __init__(self): super(Window,self).__init__() self.initUI() def initUI(self): self.setGeometry(200,500,400,400) self.setWindowTitle("A Grid Layout") l1 = QtGui.QLabel("Label 1") l2 = QtGui.QLabel("Label 2") l3 = QtGui.QLabel("Label 3") le1 = QtGui.QLineEdit() grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(l1,1,0)#widget,row,column grid.addWidget(l2,2,1) grid.addWidget(l3,3,2) grid.addWidget(le1,4,0,1,2)#row,column span centralWidget = QtGui.QWidget() centralWidget.setLayout(grid) self.setCentralWidget(centralWidget) self.show() def main(): app = QtGui.QApplication(sys.argv) win = Window() exit(app.exec_()) if __name__ == "__main__": main() </code></pre>
python|pyside|qgridlayout
7
1,905,036
22,388,528
Summing values with a for loop
<p>Instructions:</p> <p>Define a function called summer() that sums the elements in a list of numbers. summer() takes a single list argument. First you need to initialize an accumulator to zero, then use a for-loop to add the value of each element in the list, and finally return the total sum to the calling program.</p> <p>Question: </p> <p>I know how to do this very easily with the sum() function but I am not allowed to use this. I must find a way to sum a lists value and print that sum.</p> <p>i.e</p> <pre><code>&gt;&gt;&gt; x = [9, 3, 21, 15] &gt;&gt;&gt; summer(x) 48 </code></pre> <p>What I've tried:</p> <pre><code>xlist=[9,3,21,15] sumed=0 def summer(x): for i in x: sumed+=i print(sumed) summer(xlist) </code></pre> <p>I keep getting 'sumed' ref. before assignment with this one</p>
<p>Let me translate the instructions step by step:</p> <ul> <li>Step1</li> </ul> <blockquote> <p>Define a function called summer() that sums the elements in a list of numbers.</p> </blockquote> <pre><code>def summer(): "This function sums the elements in a list" </code></pre> <ul> <li>Step2</li> </ul> <blockquote> <p>summer() takes a single list argument.</p> </blockquote> <pre><code>def summer(a_list): "This function sums the elements in a list" </code></pre> <ul> <li>Step3</li> </ul> <blockquote> <p>First you need to initialize an accumulator to zero</p> </blockquote> <pre><code>def summer(a_list): "This function sums the elements in a list" accumulator = 0 </code></pre> <ul> <li>Step4</li> </ul> <blockquote> <p>, then use a for-loop to add the value of each element in the list,</p> </blockquote> <pre><code>def summer(a_list): "This function sums the elements in a list" accumulator = 0 for elem in a_list: accumulator+= elem </code></pre> <blockquote> <p>and finally return the total sum to the calling program.</p> </blockquote> <pre><code>def summer(a_list): "This function sums the elements in a list" accumulator = 0 for elem in a_list: accumulator+= elem return accumulator </code></pre> <p>Now, you can try in the shell:</p> <pre><code>&gt;&gt;&gt; def summer(a_list): ... "This function sums the elements in a list" ... accumulator = 0 ... for elem in a_list: ... accumulator+= elem ... return accumulator ... &gt;&gt;&gt; x = [9, 3, 21, 15] &gt;&gt;&gt; summer(x) 48 </code></pre>
python|for-loop|python-3.x|sum
1
1,905,037
58,161,870
Python Sockets send an integer value greater than 127 as a single byte
<p>I am using Python 3 and I wish to send an integer greater than 127 as a single byte. As expected, I can't do that with the chr() function as this function converts it into 2 bytes. When I use str() it converts it to 3 separate bytes that I don't want. I have tried but I can't seem to get any solution. </p>
<p>In general, you should try to keep byte-oriented operations done on bytestrings (<code>bytes</code>) and text-oriented (or at least USV-oriented) operations done on strings (<code>str</code>). So instead of trying to construct your message as a string for a single final encode:</p> <pre><code>message_identifier = chr(50) message_name = 'Hello ' message_data_size = '160'.encode().decode() # clueless here frame = (message_identifier + message_name + (message_data_size)) # don't know what to do with message_data_size byt = frame.encode() </code></pre> <p>encode when the logic passes the boundary from text to bytes:</p> <pre><code>message_identifier = bytes([50]) # or b'\x32', or b'2' message_name = 'Hello ' message_data_size = bytes([160]) frame = message_identifier + message_name.encode('utf-8') + message_data_size </code></pre>
python|sockets
0
1,905,038
54,563,637
I need to know the number of serialized lists in the file. help me please
<p>I need to know the number of serialized lists in the file.</p> <pre><code>n = 0 f = open('comics', 'rb') while pickle.load(f): n+=1 </code></pre>
<p>You want to catch "EOFError" since you will run out of pickled lists. It's also better to use with statement for opening files since you don't have to worry about closing the open files.</p> <pre><code>n = 0 with open('comics', 'rb') as f: while True: try: pickle.load(f): n+=1 except EOFError: break </code></pre>
python|serialization|pickle
0
1,905,039
39,175,288
Passing all elements of tuple in function 1 (from *args) into function 2 (as *args) in python
<p>I am writing a function to take *args inputs, assess the data, then pass all inputs to the next appropriate function (align), also taking *args</p> <p>*args seems to be a tuple. I have tried various ways of passing each element of the tuple into the next function, the latest two being:</p> <pre><code> for x in args: align(*x) </code></pre> <p>and</p> <pre><code> for x in args: align(args[0:len(args)]) </code></pre>
<p>You "unpack them" with <code>*args</code>. Then the receiving function can mop them up into a tuple again (or not!). </p> <p>These examples should enlighten things: </p> <pre><code>&gt;&gt;&gt; def foo(*f_args): ... print('foo', type(f_args), len(f_args), f_args) ... bar(*f_args) ... &gt;&gt;&gt; def bar(*b_args): ... print('bar', type(b_args), len(b_args), b_args) ... &gt;&gt;&gt; foo('a', 'b', 'c') ('foo', &lt;type 'tuple'&gt;, 3, ('a', 'b', 'c')) ('bar', &lt;type 'tuple'&gt;, 3, ('a', 'b', 'c')) </code></pre> <p>Now, let's redefine <code>bar</code> and break the argspec:</p> <pre><code>&gt;&gt;&gt; def bar(arg1, arg2, arg3): ... print('bar redefined', arg1, arg2, arg3) ... &gt;&gt;&gt; foo('a', 'b', 'c') ('foo', &lt;type 'tuple'&gt;, 3, ('a', 'b', 'c')) ('bar redefined', 'a', 'b', 'c') &gt;&gt;&gt; foo('a', 'b') ('foo', &lt;type 'tuple'&gt;, 2, ('a', 'b')) ---&gt; TypeError: bar() takes exactly 3 arguments (2 given) </code></pre>
python|function|tuples|args
1
1,905,040
47,823,141
Looking for a better algorithm or data structure to improve conversion of connectivity from ID's to indices
<p>I'm working with Python 3.6.2 and numpy.</p> <p>I'm writing code to visualize a finite element model and results.</p> <p>The visualization code requires the finite element mesh nodes and elements to be identified by indices (starting a zero, no gaps) but the input models are based on ID's and can have very large gaps in the ID space.</p> <p>So I'm processing all of the nodes and elements and changing them to use indices instead of ID's.</p> <p>The nodes are </p> <p>First step is to process the array of nodes and node coordinates. This comes to me sorted so I don't specifically have to do anything with the coordinates - I just use the indices of the nodal coordinate array. But I do need to then redefine the connectivity of the elements to be index base instead of ID based.</p> <p>To do this, I create a dictionary by iterating over the array of node ids and adding each node to the dictionary using it's ID as the key and its index as the value</p> <p>In the following code fragment,</p> <ol> <li><p>model.nodes is a dictionary containing all of the Node objects, keyed by their id</p></li> <li><p>nodeCoords is a pre-allocated numpy array where I store the nodal coordinates for later use in visualization. It's the indices of this array that I need to use later to redefine my elements</p></li> <li><p>nodeIdIndexMap is a dictionary that I populate using the Node ID as the key and the index of nodeCoords as the value</p></li> </ol> <p>Code:</p> <pre><code>nodeindex=0 node_id_index_map={} for nid, node in sorted(model.nodes.items()): nodeCoords[nodeIndex] = node.xyz nodeIdIndexMap[nid] = nodeIndex nodeIndex+=1 </code></pre> <p>Then I iterate over all of the elements, looking up each element node ID in the dictionary, getting the index and replacing the ID with the index. </p> <p>In the following code fragment, </p> <ol> <li>tet4Elements is a dictionary containing all elements of type tet4, keyed using the element id</li> <li>n1, n2, n3 and n4 are pre-allocated numpy arrays that hold the element nodes</li> <li>element.nodes[n].nid gets the element node ID </li> <li>n1[tet4Index] = nodeIdIndexMap[element.nodes[0].nid looks up the element node ID in the dictionary created in the previous fragment, returns the corresponding index and stores it in the numpy array </li> </ol> <p>Code:</p> <pre><code>tet4Index = 0 for eid, element in tet4Elements.items(): id[tet4Index] = eid n1[tet4Index] = nodeIdIndexMap[element.nodes[0].nid] n2[tet4Index] = nodeIdIndexMap[element.nodes[1].nid] n3[tet4Index] = nodeIdIndexMap[element.nodes[2].nid] n4[tet4Index] = nodeIdIndexMap[element.nodes[3].nid] tet4Index+=1 </code></pre> <p>The above works, but it's slow......It takes about 16 seconds to process 6,500,000 tet4 elements (each tet4 element has four nodes, each node ID has to be looked up in the dictionary, so that's 26 million dictionary lookups in a dictionary with 1,600,000 entries.</p> <p>So the question is how to do this faster? At some point I'll move to C++ but for now I'm looking to improve performance in Python.</p> <p>I'll be grateful for any ideas to improve performance.</p> <p>Thanks,</p> <p>Doug </p>
<p>With the numbers you are quoting and reasonable hardware (8GB ram) the mapping can be done in less than a second. The bad news is that getting the data out of the original dicts of objects takes 60 x longer at least with the mock objects I created.</p> <pre><code># extract 29.2821946144104 map 0.4702422618865967 </code></pre> <p>But maybe you can find some way of bulk querying your nodes and tets?</p> <p>Code:</p> <pre><code>import numpy as np from time import time def mock_data(nn, nt, idf): nid = np.cumsum(np.random.randint(1, 2*idf, (nn,))) nodes = np.random.random((nn, 3)) import collections node = collections.namedtuple('node', 'nid xyz') tet4 = collections.namedtuple('tet4', 'nodes') nodes = dict(zip(nid, map(node, nid, nodes))) eid = np.cumsum(np.random.randint(1, 2*idf, (nt,))) tet4s = nid[np.random.randint(0, nn, (nt, 4))] tet4s = dict(zip(eid, map(tet4, map(lambda t: [nodes[ti] for ti in t], tet4s)))) return nodes, tet4s def f_extract(nodes, tet4s, limit=15*10**7): nid = np.array(list(nodes.keys())) from operator import attrgetter ncoords = np.array(list(map(attrgetter('xyz'), nodes.values()))) tid = np.array(list(tet4s.keys())) tnodes = np.array([[n.nid for n in v.nodes] for v in tet4s.values()]) return nid, ncoords, tid, tnodes, limit def f_lookup(nid, ncoords, tid, tnodes, limit): nmx = nid.max() if nmx &lt; limit: nlookup = np.empty((nmx+1,), dtype=np.uint32) nlookup[nid] = np.arange(len(nid), dtype=np.uint32) tnodes = nlookup[tnodes] del nlookup else: nidx = np.argsort(nid) nid = nid[nidx] ncoords = ncoords[nidx] tnodes = nid.searchsorted(tnodes) tmx = tid.max() if tmx &lt; limit: tlookup = np.empty((tmx+1,), dtype=np.uint32) tlookup[tid] = np.arange(len(tid), dtype=np.uint32) else: tidx = np.argsort(tid) tid = tid[tidx] tnodes = tnodes[tidx] return nid, ncoords, tid, tnodes data = mock_data(1_600_000, 6_500_000, 16) t0 = time() data = f_extract(*data) t1 = time() f_lookup(*data) t2 = time() print('extract', t1-t0, 'map', t2-t1) </code></pre>
python|numpy|dictionary|finite-element-analysis
2
1,905,041
37,239,596
Python/Installing cvxpy package error - setup.py egg_info with error code 1
<p>I'm trying to install cvxpy on my Mac through pip and through PyCharm and I'm getting the following error: "Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-azdpOA/CVXcanon/". Would anyone know what's that and how to fix this?</p> <p>My python is 2.7<br> My pip is 8.1.2 <br> My PyCharm is 4.5.4<br> My OSX is 10.8.5</p>
<p>The module <code>CVXcanon</code> is a dependency by the <a href="http://www.cvxpy.org/en/latest/install/index.html" rel="nofollow">official installation instructions</a>.</p> <blockquote> <p>We recommend using Anaconda rather than the Python that comes with the Mac and installing pip, nose, NumPy, SciPy, and CVXOPT through Anaconda (i.e., conda install pip nose numpy scipy cvxopt). But it is not necessary to have Anaconda to install CVXPY, and the instructions below assume you do not have Anaconda.</p> </blockquote> <p>Install the command line tools <code>xcode-select --install</code> and then install the module with all dependencies <code>pip install cvxpy</code>. You can use the <code>Terminal</code> tab in PyCharm.</p>
python-2.7|pip|cvxpy
1
1,905,042
37,364,818
Errors installing pyspotify
<p>Hi I am having problems installing <code>pyspotify</code>. I think i have installed the development headers and <code>libffi</code> package but I am still getting errors, here is what happens when I try and install it using pip:</p> <pre><code>warning: manifest_maker: standard file '-c' not found reading manifest file 'pyspotify.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'examples/tmp' warning: no previously-included files matching '__pycache__/*' found anywhere in distribution writing manifest file 'pyspotify.egg-info/SOURCES.txt' copying spotify/api.h -&gt; build/lib.linux-armv7l-3.4/spotify copying spotify/api.processed.h -&gt; build/lib.linux-armv7l-3.4/spotify running build_ext generating cffi module 'build/temp.linux-armv7l-3.4/spotify._spotify.c' creating build/temp.linux-armv7l-3.4 building 'spotify._spotify' extension creating build/temp.linux-armv7l-3.4/build creating build/temp.linux-armv7l-3.4/build/temp.linux-armv7l-3.4 arm-linux-gnueabihf-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.4m -c build/temp.linux-armv7l-3.4/spotify._spotify.c -o build/temp.linux-armv7l-3.4/build/temp.linux-armv7l-3.4/spotify._spotify.o build/temp.linux-armv7l-3.4/spotify._spotify.c:422:28: fatal error: libspotify/api.h: No such file or directory #include "libspotify/api.h" </code></pre> <blockquote> <pre><code>Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-f_0drg24/pyspotify/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-dn3q3awz-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-f_0drg24/pyspotify/ </code></pre> </blockquote>
<p>This shows that it cannot find the development headers:</p> <pre><code>build/temp.linux-armv7l-3.4/spotify._spotify.c:422:28: fatal error: libspotify/api.h: No such file or directory </code></pre> <p>Have you considered installing the precompiled python-spotify Debian package from <a href="http://apt.mopidy.com" rel="nofollow">http://apt.mopidy.com</a>, or even just installing libspotify-dev from there, to get development headers installed properly?</p>
python|debian|pip
1
1,905,043
7,572,243
Learning wxPython, basic thing
<p>I want to display a button that when I click adds to the main panel a static text that automatic adds to the BoxSizer of the panel. I have this code but dosen't work good. Anyone can help me? I am desperate. Thanks</p> <pre><code>import wx class MyApp(wx.App): def OnInit(self): self.frame = MainFrame(None,title='') self.SetTopWindow(self.frame) self.frame.Show() return True class MainFrame(wx.Frame): def __init__(self, *args, **kwargs): super(MainFrame, self).__init__(*args, **kwargs) #Atributos self.panel = MainPanel(self) self.CreateStatusBar() #Layout self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.panel,1,wx.EXPAND) self.SetSizer(self.sizer) class MainPanel(wx.Panel): def __init__(self, parent): super(MainPanel, self).__init__(parent) #Atributos bmp = wx.Bitmap('./img.png',wx.BITMAP_TYPE_PNG) self.boton = wx.BitmapButton(self,bitmap=bmp) # Layout self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.boton) self.SetSizer(self.sizer) self.Bind(wx.EVT_BUTTON,self.add,self.boton) def add(self,event): self.sizer.Add(wx.StaticText(self,label='Testing')) if __name__ == "__main__": app = MyApp(False) app.MainLoop() </code></pre>
<p>If your problem is that your text initially shows up behind the button when it is clicked, you can force the sizer to update by adding a call to your Panel's <code>Layout</code> method.</p> <pre><code>class MainPanel(wx.Panel): def __init__(self, parent): super(MainPanel, self).__init__(parent) #Atributos bmp = wx.Bitmap('./img.png',wx.BITMAP_TYPE_PNG) self.boton = wx.BitmapButton(self,bitmap=bmp) # Layout self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.boton) self.SetSizer(self.sizer) self.Bind(wx.EVT_BUTTON,self.add,self.boton) def add(self,event): self.sizer.Add(wx.StaticText(self,label='Testing')) self.Layout() </code></pre>
python|wxpython
4
1,905,044
7,021,954
Safe using user input as key_name?
<p>I would like to use a string that was input by the user in a web form as part of a key name:</p> <pre><code>user_input = self.request.POST.get('foo') if user_input: foo = db.get_or_insert(db.Key('Foo', user_input[:100], parent=my_parent)) </code></pre> <p>Is this safe? Or should I do some inexpensive encoding or hash? If yes, which one?</p>
<p>It's safe as long as you don't care about a malicious user filling up your database with junk. <code>get_or_insert</code> won't let them overwrite existing entries, just add new ones.</p> <p>Make sure you limit it's length (both in the UI and after it's been recieved), even if you do no other validation on it, so at least they can't just give you crazy big keys either to fill up the database quickly or to crash your app.</p> <p>Edit: You just commented that you do, in fact, verify that it's a reasonable key. In that case, yes, it's safe.</p> <p>Keep in mind that the user can probably still figure out what key are already in your database, based on how long it takes you to respond to what they've provided, and you still need to make sure they're authorized to see whatever content they request, or limit them to a small number of requests to they can't just brute-force retrieve all the information linked to the keys you're generating.</p>
python|google-app-engine|google-cloud-datastore
3
1,905,045
7,217,405
Turtle Graphics Not Responding
<p>I am creating diagrams with the turtle package in Python, and it is successful to some extent, except for one problem. Once turtle generates the diagram that I have in code, it causes the program to say "Not responding" and eventually I have to end the task. I am using Windows 7.</p> <p>Have any of you experienced this or know the root cause? I tried reinstalling Python completely, but that didn't seem to affect the problem.</p> <p>Here is some example code that will make it fail to respond:</p> <pre><code>import turtle from turtle import forward, right, left forward(50) </code></pre>
<p>I had the same problem (I was on Win 7 as well, and I then got the same problem on Win XP), and I just figured it out.</p> <p>You have to say <code>turtle.done()</code> when you're done.</p> <p>Now that I know this, it makes more sense, because since Python doesn't know that the turtle is done, it's probably waiting for another command for the turtle.</p> <p>Here's the documentation (in Python 2.7) of what library I assume you're using. It's how I figured that out. It says Python 2.7 but this also works for Python 2.5.<br/> <a href="http://docs.python.org/library/turtle.html" rel="noreferrer">http://docs.python.org/library/turtle.html</a></p> <p>Hope that helps (for you or anyone else reading this),<br/> Alex</p>
python|windows-7|turtle-graphics
24
1,905,046
72,511,459
voting game for raspberry pi using python
<p>I'm new at python and raspberry pi. I was looking to make a visual voting game using graphics and the PI and python. I will be using a non touch screen hdmi in display, the Pi, and two physical buttons hooked up to the Pi's gpio ports. i was going to start with an introductory screen, and wait for a voter to push one of the buttons, which would then bring him to the first 2 choice voting screen. When he/she pushes a button to vote, it would refresh the screen to the results for those 2 choices for a few seconds, then bring up the 2nd voting screen. This would loop for however many voting screens i make. At the end I would display a &quot;high score&quot; like tally of all the votes. And then it would loop back to the introductory screen again.</p> <p>I am having issues with the wait time for the first voting selection screen. I can get it to display, and am using the add_event_detect for the GPIO buttons, but i don't know how to &quot;pause&quot; the voting selection screen on screen without delaying the program from running, thus not allowing the button selection to be made. The program loops too fast and goes back to the intro screen and does not wait for user input on the voting screen.</p> <p>Below is a sample of what i have so far. I have omitted the voting variables and incrementing and displaying the text as that works ok. I just need to figure out how to keep each voting screen displayed until user input and then move onto the next. Mahalo for the help!</p> <pre><code>import RPi.GPIO as GPIO2 import time import pygame BUTTON_1 = 3 BUTTON_2 = 5 GPIO2.setmode(GPIO2.BOARD) pygame.init() pygame.display.init() WIDTH = 1900 HEIGHT = 1000 display = pygame.display.set_mode((WIDTH, HEIGHT)) intro = pygame.image.load('intro.png') voting1 = pygame.image.load('voting1.png') def button_callback(channel): pygame.time.delay(1000) while True: display.fill((125,125,125)) display.blit(intro, (0,0)) #display intro game screen pygame.display.update() while True: if (BUTTON_1.is_pressed or BUTTON_2.is_pressed): #start game and switch to first voting screen display.blit(voting1,(0,0)) pygame.display.update() pygame.time.delay(1000) while True: #wait for user vote if Button_1.is_pressed: *** increment couting variables here and vote 1 results screen for a few secs *** elif Button_2.is_pressed: *** increment couting variables here and vote 1 results screen for a few secs *** *** display 2nd, 3rd voting screen, looped til last screen *** display high score screen for a few secs, kick back to intro screen *** GPIO2.setup(BUTTON_1, GPIO2.IN) GPIO2.setup(BUTTON_2, GPIO2.IN) GPIO2.add_event_detect(BUTTON_1, GPIO2.FALLING, callback=button_callback,bouncetime=50) GPIO2.add_event_detect(BUTTON_2, GPIO2.FALLING, callback=button_callback,bouncetime=50) try: while True: time.sleep(0.01) print(&quot;in while&quot;) except KeyboardInterrupt: GPIO2.cleanup() </code></pre>
<p>It is usually bad practice to hold up callbacks with a lot of code, otherwise you'll prevent further callbacks - as you've found out.</p> <p>As mentioned in the comments - you could run the main program as a state machine - and the button presses would cause the state to change, and move through the program.</p> <p>For example - I've taken your code and written a quick state machine that would take you through the voting screens. (I've taken out the pygame code for simplicity to concentrate on the state machine).</p> <p>You should be able to follow the main application through the state changes, and see how the buttons affect the state whilst the application is currently waiting for input.</p> <p>Please note - I haven't tried to run this program as I don't have a Pi to hand with buttons attached, so if you have any issues let me know.</p> <p>Hopefully this will help you progress your voting game.</p> <pre><code>import RPi.GPIO as GPIO2 import time BUTTON_1 = 3 BUTTON_2 = 5 GPIO2.setmode(GPIO2.BOARD) VOTING_RESULT_TIME = 2 # The different states the application could be in (could use an Enum class for this) STATE_WELCOME=0 STATE_WAITING_TO_START=1 STATE_SHOWING_NEXT_SCREEN=2 STATE_WAITING_TO_VOTE=3 STATE_SHOWING_VOTE_RESULTS=4 STATE_SHOWING_FINAL_RESULTS=5 current_state = STATE_WELCOME welcome_screen = &quot;Press any button to start ...&quot; voting_screens = [&quot;Cats or Dogs&quot;, &quot;Cars or Bikes?&quot;, &quot;Apples or Pears?&quot;] current_screen = 0 def button_callback(channel): if current_state == STATE_WAITING_TO_START: current_state = STATE_SHOWING_NEXT_SCREEN elif current_state == STATE_WAITING_TO_VOTE: if channel == BUTTON_1: # do counting for button 1 pass elif channel == BUTTON_2: # do counting for button 2 pass current_state = STATE_SHOWING_VOTE_RESULTS else: # buttons won't have any effect whilst the main app is not waiting for input pass GPIO2.setup(BUTTON_1, GPIO2.IN) GPIO2.setup(BUTTON_2, GPIO2.IN) GPIO2.add_event_detect(BUTTON_1, GPIO2.FALLING, callback=button_callback,bouncetime=50) GPIO2.add_event_detect(BUTTON_2, GPIO2.FALLING, callback=button_callback,bouncetime=50) try: while True: if current_state == STATE_WELCOME: print(welcome_screen); current_state == STATE_WAITING_TO_START; elif current_state == STATE_WAITING_TO_START: pass # button callback will change state. elif current_state == STATE_SHOWING_NEXT_SCREEN: print(voting_screens[current_screen]) current_state = STATE_WAITING_TO_VOTE elif current_state == STATE_WAITING_TO_VOTE: pass # button callback will change state elif current_state == STATE_SHOWING_VOTE_RESULTS: print(&quot;Here are the voting results&quot;) time.sleep(2000) current_screen += 1 if ( current_screen &gt;= len(voting_screens) ): current_state = STATE_SHOWING_FINAL_RESULTS else: current_state = STATE_SHOWING_NEXT_SCREEN elif current_state == STATE_SHOWING_FINAL_RESULTS: print(&quot;Here are the final results ....&quot;) time.sleep(2000) current_screen = 0 current_state = STATE_WELCOME time.sleep(0.01) except KeyboardInterrupt: pass finally: GPIO2.cleanup() </code></pre>
python|pygame|raspberry-pi
1
1,905,047
16,310,288
pymongo returns less fields
<p>I have a following problem. Pymongo returns less fields than it should.</p> <p>Here is my query: <code>db.users.findOne({'e.email': 'xxx@gmail.com', application: 'App1'})</code></p> <p>Directly from mongo db I get: <code>{ "_id" : ObjectId("51803128e4b092fd00c8899b"), "application": "App1", "d" : ISODate("2013-04-30T21:01:28.084Z"), "e" : [ { "email" : "xxx@gmail.com", "isValidated" : true } ], "fn" : "XXX", "l" : "en_US", "ln" : YYY", "si" : [ { "isTokenExpired" : true, "oAuth" : { "value" : "", "permissions" : [ ] }, "sIden" : { "id" : "123", "network" : 0 } } ], "tz" : "Etc/UTC" }</code></p> <p>But pymongo doesn't return "si" array on the same query and fields ln,fn are empty:</p> <p><code>query = collection.find_one({'e.email': 'xxx@gmail.com', application: 'App1'})<br> print query</code></p> <p><code>[{u'application': 'App1', u'tz': u'Etc/UTC', u'd': datetime.datetime(2013, 4, 30, 22, 52, 45, 916000), u'ln': u'', u'l': u'en_US', u'e': [{u'isValidated': True, u'email': u'xxx@gmail.com'}],u'_id': ObjectId('51804b3de4b092fd00c88d1b'), u'fn': u''}]</code></p> <p>What the problem? Thanks!</p>
<p>In PyMongo you are calling <strong>findOne</strong>, which will return only 1 document. Whereas when you are natively querying MongoDB, you are not calling findOne and thus getting more results. From your results it is apparent you are using <strong>find()</strong> for natively making the query. Here is the difference between <strong>findOne</strong> and <strong>find</strong> as per official MongoDB <a href="http://docs.mongodb.org/manual/reference/" rel="nofollow">documentation</a>. </p> <pre><code>findOne() One document that satisfies the query specified as the argument to this method. If the projection argument is specified, the returned document contains only the projection fields, and the _id field if you do not explicitly exclude the _id field. find() A cursor to the documents that match the query criteria. If the projection argument is specified, the matching documents contain only the projection fields, and the _id field if you do not explicitly exclude the _id field. </code></pre>
python|mongodb|python-2.7|pymongo
1
1,905,048
16,498,367
SQLAlchemy creating two databases in one file with two different models
<p>I want to initialize two databases with total different models in my database.py file.</p> <p>database.py </p> <pre><code>engine1 = create_engine(uri1) engine2 = create_engine(uri2) session1 = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine1)) session2 = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine2)) Base = declarative_base(name='Base') Base.query = session1.query_property() LogBase = declarative_base(name='LogBase') LogBase.query = session2.query_property() </code></pre> <p>and the two model structures:</p> <p>models.py </p> <pre><code>class MyModel(Base): pass </code></pre> <p>models2.py </p> <pre><code>class MyOtherModel(LogBase): pass </code></pre> <p>back to the database.py where i want to create/initialize the databases after importing the models </p> <pre><code># this does init the database correctly def init_db1(): import models Base.metadata.create_all(bind=engine1) # this init function doeas not work properly def init_db2(): import models2 LogBase.metadata.create_all(bind=engine2) </code></pre> <p>if I change the import in the second init function it does work </p> <pre><code>def init_db2(): from models2 import * LogBase.metadata.create_all(bind=engine2) </code></pre> <p>but there is a warning:</p> <blockquote> <p>database.py:87: SyntaxWarninyntaxWarning: import * only allowed at module level</p> </blockquote> <p>Everthing does work properly, I have the databases initialized, but the Warning tells me, that there is something wrong with it.</p> <p>If someone can explain me why the first attempt isn't correct I would be grateful. Thanks.</p>
<p>You are indeed discouraged from using the <code>from ... import *</code> syntax inside functions, because that makes it impossible for Python to determine what the local names are for that function, breaking scoping rules. In order for Python to make things work anyway, certain optimizations have to be disabled and name lookup is a lot slower as a result.</p> <p>I cannot reproduce your problem otherwise. Importing just <code>models2</code> makes sure that everything defined in that module is executed so that the <code>LogBase</code> class has a registry of all declarations. There is no reason for that path to fail while the <code>models.py</code> declarations for <code>Base</code> do work.</p> <p>For the purposes of SQLAlchemy and declarative table metadata, there is <strong>no</strong> difference between the <code>import models2</code> and the <code>from models2 import *</code> syntax; only their effect on the local namespace differs. In <strong>both</strong> cases, the <code>models2</code> top-level code is run, classes are defined, etc. but in the latter case then the top-level names from the module are added to the local namespace as direct references, as opposed to just a reference to the module object being added.</p>
python|sqlalchemy
2
1,905,049
40,638,918
Pandas Start/End Date Data Transformation
<p>was wondering if somebody can help me make the following data transformation.</p> <p>I have the following data in this format:</p> <pre><code>ID Value Start Date End Date A 1 1/31/2015 6/30/2015 B 2 3/31/2015 4/30/2015 And would like it to be in this format instead: Date ID Value 1/31/2015 A 1 2/28/2015 A 1 3/31/2015 A 1 4/30/2015 A 1 5/31/2015 A 1 6/30/2015 A 1 3/31/2015 B 2 4/30/2015 B 2 </code></pre> <p>Thanks in advance</p>
<p>You provide too little info, really to be sure of what you want. But something as simple as re-indexing works, followed by sorting.</p> <pre><code>data.index = data.dates data.sort(by='ID') </code></pre> <p>Of course, now you still have your date columns in the dataframe, but both of those can be dropped as needed. It doesn't look like you are doing anything too substantial here, did I miss something?</p>
python|datetime|pandas
0
1,905,050
40,645,351
Python: my polynomial coefficients are off by a factor of 10
<p>I am learning scientific computing with python. In the exercise, I am supposed to generate a polynomial by using its roots with this formula:</p> <p><a href="https://i.stack.imgur.com/4NdgF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4NdgF.png" alt="enter image description here"></a></p> <p>Here is my implementation:</p> <pre><code>def poly(x,roots): #Pass real and/or complex roots x = symbols(x) f = 1 for r in roots: f = f*(x - r) return expand(f) </code></pre> <p>When I test it:</p> <pre><code>from sympy import expand poly('x',[(-1/2), 5, (21/5), (-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)]) </code></pre> <p>I get:</p> <pre><code>x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0 </code></pre> <p>But I should get:</p> <pre><code>10*x**5 - 17.0*x**4 - 505.0*x**3 + 1775.0*x**2 - 248.999999999999*x - 630.0 </code></pre> <p>Hence, everything is off by a factor of 10. If I set <code>f = 10</code>, it works, but I don't see why I should do that. Am I making an obvious mistake? Thank you!</p>
<p>While <code>10x**5 + ...</code> is correct, that is <code>10 * p(x)</code>, which isn't really what is needed. The answer you are getting is fine right now as well and you can test that as for each <code>r</code> in <code>roots</code>, <code>p(r)</code> is <code>0</code>.</p>
python|python-3.x|math|polynomial-math
1
1,905,051
26,370,781
pycallgraph with pycharm does not work on windows
<p>I m using Windows 7, Python 3.4.1, Anaconda 2.0.1 , Pycharm 3.4.<br> Graphviz and dot work normally in the console. </p> <p>However, when trying to use pycallgraph it finishes with an error. </p> <pre><code>"C:\Users\John\Anaconda3\python.exe" C:/PycharmProjects/myprojectname/abilities.py Traceback (most recent call last): File "C:/PycharmProjects/myprojectname/abilities.py", line 1247, in &lt;module&gt; with PyCallGraph(output=GraphvizOutput()): File "C:\Users\John\Anaconda3\lib\site-packages\pycallgraph\pycallgraph.py", line 32, in __init__ self.reset() File "C:\Users\John\Anaconda3\lib\site-packages\pycallgraph\pycallgraph.py", line 53, in reset self.prepare_output(output) File "C:\Users\John\Anaconda3\lib\site-packages\pycallgraph\pycallgraph.py", line 97, in prepare_output output.sanity_check() File "C:\Users\John\Anaconda3\lib\site-packages\pycallgraph\output\graphviz.py", line 63, in sanity_check self.ensure_binary(self.tool) File "C:\Users\John\Anaconda3\lib\site-packages\pycallgraph\output\output.py", line 97, in ensure_binary 'The command "{}" is required to be in your path.'.format(cmd)) pycallgraph.exceptions.PyCallGraphException: The command "dot" is required to be in your path. Process finished with exit code 1 </code></pre> <p>What can i do to fix this?<br> I checked <a href="https://stackoverflow.com/questions/20333530/pycallgraph-with-pycharm-does-not-work">this</a> but it's for mac.</p>
<p>Please make sure you have the path for dot.exe in your PATH variable. In your computer properties, you can go to Advanced System Settings -> Advanced (tab) -> Environmental Variables then edit the PATH variable.</p> <p>Make sure you have "C:\Program Files (x86)\Graphviz2.38\bin" (I just installed Graphviz so your path might be a little different) in your list. The list is semi-colon separated and you should not have a space in-between entries nor a trailing backslash.</p> <p>My PATH environmental variable looks like:</p> <pre><code>C:\Users\&lt;censored&gt;\AppData\Roaming\npm;C:\Program Files (x86)\Java\jre7\bin;C:\Program Files (x86)\Graphviz2.38\bin </code></pre> <p>And after re-opening a windows terminal, I was able to run pycallgraph like:</p> <pre><code>C:\Python27\python.exe C:\Python27\Scripts\pycallgraph --stdlib graphviz --output-file=ninja_mol2.png -- script.py "-f SampleDat/blah.txt -s stuff/ -v" </code></pre> <p>And that put a nice PNG in the current working directory I was in.</p> <p>I hope this helps.</p>
windows|python-3.x|pycharm|anaconda|pycallgraph
0
1,905,052
26,197,144
Auto Starting a python script on boot (RPi)
<p>I have a python script on my RPi that needs to run on boot</p> <p>I added it to rc.local, and it used to work fine</p> <p>A few days ago, I added a functionality to the program, and it now uses open() to read a txt file</p> <p>Now every time I restart the Pi, python gives me and error:</p> <pre><code>File "home/pi/client.py", line 13, in &lt;module&gt; stats=open('stats.txt') IOError: [Errno 2] No such file or directory: 'stats.txt' </code></pre> <p>When I manually launch the script with:</p> <pre><code>sudo python client.py </code></pre> <p>it works fine with no problems.</p> <p>Any suggestions?</p>
<p>Your <code>rc.local</code> probably does not start your script in the correct directory. So you should either:</p> <ul> <li>use something like <code>cd my/dir &amp;&amp; python /path/to/home/pi/client.py</code></li> <li>call <code>os.chdir("/path/to/some_dir")</code> in your script</li> <li>use an absolute path when opening the file: <code>stats = open('/path/to/stats.txt')</code></li> </ul>
python|python-2.7|raspberry-pi
0
1,905,053
1,616,767
PIL Best Way To Replace Color?
<p>I am trying to remove a certain color from my image however it's not working as well as I'd hoped. I tried to do the same thing as seen here <a href="https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent">Using PIL to make all white pixels transparent?</a> however the image quality is a bit lossy so it leaves a little ghost of odd colored pixels around where what was removed. I tried doing something like change pixel if all three values are below 100 but because the image was poor quality the surrounding pixels weren't even black.</p> <p>Does anyone know of a better way with PIL in Python to replace a color and anything surrounding it? This is probably the only sure fire way I can think of to remove the objects completely however I can't think of a way to do this.</p> <p>The picture has a white background and text that is black. Let's just say I want to remove the text entirely from the image without leaving any artifacts behind.</p> <p>Would really appreciate someone's help! Thanks </p>
<p>The best way to do it is to use the "color to alpha" algorithm used in <a href="http://www.gimp.org/tutorials/Changing_Background_Color_1/" rel="noreferrer">Gimp</a> to replace a color. It will work perfectly in your case. I reimplemented this algorithm using PIL for an open source python photo processor <a href="http://photobatch.wikidot.com/" rel="noreferrer">phatch</a>. You can find the full implementation <a href="http://bazaar.launchpad.net/~stani/phatch/trunk/annotate/head:/phatch/actions/color_to_alpha.py#L50" rel="noreferrer">here</a>. This a pure PIL implementation and it doesn't have other dependences. You can copy the function code and use it. Here is a sample using Gimp:</p> <p><img src="https://www.gimp.org/tutorials/Changing_Background_Color_1/pr.png" alt="alt text"> to <img src="https://www.gimp.org/tutorials/Changing_Background_Color_1/pr_red.png" alt="alt text"></p> <p>You can apply the <code>color_to_alpha</code> function on the image using black as the color. Then paste the image on a different background color to do the replacement.</p> <p>By the way, this implementation uses the ImageMath module in PIL. It is much more efficient than accessing pixels using getdata.</p> <p><strong>EDIT: Here is the full code:</strong></p> <pre><code>from PIL import Image, ImageMath def difference1(source, color): """When source is bigger than color""" return (source - color) / (255.0 - color) def difference2(source, color): """When color is bigger than source""" return (color - source) / color def color_to_alpha(image, color=None): image = image.convert('RGBA') width, height = image.size color = map(float, color) img_bands = [band.convert("F") for band in image.split()] # Find the maximum difference rate between source and color. I had to use two # difference functions because ImageMath.eval only evaluates the expression # once. alpha = ImageMath.eval( """float( max( max( max( difference1(red_band, cred_band), difference1(green_band, cgreen_band) ), difference1(blue_band, cblue_band) ), max( max( difference2(red_band, cred_band), difference2(green_band, cgreen_band) ), difference2(blue_band, cblue_band) ) ) )""", difference1=difference1, difference2=difference2, red_band = img_bands[0], green_band = img_bands[1], blue_band = img_bands[2], cred_band = color[0], cgreen_band = color[1], cblue_band = color[2] ) # Calculate the new image colors after the removal of the selected color new_bands = [ ImageMath.eval( "convert((image - color) / alpha + color, 'L')", image = img_bands[i], color = color[i], alpha = alpha ) for i in xrange(3) ] # Add the new alpha band new_bands.append(ImageMath.eval( "convert(alpha_band * alpha, 'L')", alpha = alpha, alpha_band = img_bands[3] )) return Image.merge('RGBA', new_bands) image = color_to_alpha(image, (0, 0, 0, 255)) background = Image.new('RGB', image.size, (255, 255, 255)) background.paste(image.convert('RGB'), mask=image) </code></pre>
python|image|replace|colors|python-imaging-library
28
1,905,054
32,544,169
Pandas isin anywhere in a sentence
<p>I have a standard pandas DataFrame consisting of string sentences (shown below) and I want to show the rows that have the word "world" anywhere in the 'body' of it. <code>df.isin(['world'])</code> won't work because that only matches exact labels. I want to return <code>True</code> if the word "world" shows up anywhere within the text of the 'body'.</p> <pre><code> body 0 'Hello world hi hi' 1 'My name is David, hello' 2 ... </code></pre> <p><strong>The code that I tried was:</strong></p> <pre><code>df.isin(['world']) </code></pre> <p>which produces:</p> <pre><code> body 0 False 1 False 2 ... </code></pre> <p><strong>What I'd like it to produce would be:</strong></p> <pre><code> body 0 True 1 False 2 ... </code></pre> <p>because row <code>0</code> has the word "world" in it.</p>
<p>You can just use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html#pandas.Series.str.contains" rel="nofollow">str.contains</a> as illustrated below.</p> <pre><code># Test data df = pd.DataFrame({'body': ['Hello world hi hi', 'My name is David, hello']}) df['body'].str.contains('world') # Result 0 True 1 False </code></pre>
python|pandas
1
1,905,055
44,106,493
Python vs C++ for CUDA web server?
<p>I am planning on writing some software for a web server that uses machine learning to process large amounts of data. This will be real estate data from a MySQL server. I will be using the CUDA framework from Nvidia with python/caffe or the c++ library. I will be using a Tesla P100. Although python is more widely used for machine learning I presume it is hard to write a server app in python without sacrificing performance. Is this true? Is c++ well supported for machine learning? Will anything be sacrificed by writing a professional server app in python (ex: connecting to MySQL database)?</p>
<p>Python is a language that performs worse than c++ in terms of runtime for several reasons:</p> <p>First and foremost, Python is a scripting language that runs with an interpreter as opposed to c++ which compiled into machine code before running.</p> <p>Secondly: python runs in the background a garbage collector system while in c++ the memory management is done manually by the programmer.</p> <p><strong>In your case, I recommend that you work with Python for several reasons:</strong></p> <ol> <li>Writing in Python in CUDA allows you to compile the code even though it is Python (CUDA provides JIT - Just In Time compiler, as well as a compiler and other effective tools), Which greatly improves performance</li> <li>Python provides many, rich varied libraries that will help you a lot in the project, especially in the field of machine learning.</li> <li>The development time and code length will be significantly shorter in Python.</li> </ol> <p>From my experience with working at CUDA in the Python language I recommend you use numba and numbapro libraries, they are comfortable to work with and provide support for many libraries like numpy.</p> <p>Best of luck.</p>
python|c++|cuda
1
1,905,056
32,749,436
How can I use 2d array in Django's template in jQuery?
<p>I have a 2d array named "pre" in views.py . I have passed the same array in the template.html . I want to use the values of second column of each row of pre array as initial value for text boxes. Script is shown below. </p> <p>Variable i.toString() is working fine with name of input tag but in values it is not working. I want the value of {{pre.0.2}} as values of 1st textbox,{{ pre.1.2}} as value of second one and so on. How can I achieve that ?</p> <pre><code>&lt;script&gt; $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = {{branches}}; //initlal text box count for (var i = 1; i &lt;= x; i++) { if(x &lt; max_fields){ //max input box allowed $(wrapper).append('&lt;input name="main_address_'+i.toString()+'" value="{{pre.'+i.toString()+'.2}}" type="text" required=""&gt;&lt;br&gt;'); //add input box } } &lt;/script&gt; </code></pre> <p>If you have any other way to achieve the same result please share it with me. </p>
<p>That's very true that I don't need to use jQuery here. It can be easily implemented by {% for loop %} {% endfor %} in Django. Thanks for your comments.</p> <pre><code>{% for p in pre %}&lt;input name="main_address_{{forloop.counter}}" value="{{p.2}}" type="text" required=""&gt;{% endfor %} </code></pre>
jquery|python|django
0
1,905,057
34,522,743
How to verify a downloaded file is real image?
<p>For example,I use vim to create a test.jpg file in my server, and <code>http://www.somedomain.com/test.jpg</code> could be visit and return 200 http response code but in fact, this 'test.jpg' is not a real image file and it doesn't show anything when opened.</p> <p>How to judge that was not a correct image file by python?</p>
<p>give <a href="https://github.com/ahupp/python-magic" rel="nofollow">python-magic</a> a try. the libraries are used to examine the actual file, regardless of file extensions and tells you what they are.</p>
python|http
0
1,905,058
34,555,706
Python: How to move forward or backward together in String printable
<p>How to shift forward or backward in <code>string.printable</code> whithout <code>string.maketrans</code>?<br /></p> <p>for example:</p> <pre><code>&gt;&gt; chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" </code></pre> <p>and then output is:</p> <pre><code>123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0 </code></pre>
<pre><code>&gt;&gt;&gt; chars[2:] + chars[:2] '23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01' &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; chars[-2:] + chars[:-2] 'YZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX' &gt;&gt;&gt; </code></pre> <p>You can even define a function for that, with your string, the steps and direction as parameters:</p> <pre><code>&gt;&gt;&gt; def shift(s, step, side='Right'): step %= len(s) #Will generate correct steps even step &gt; len(s) if side == 'Right': return s[-step:]+s[:-step] elif side == 'Left': return s[step:]+s[:step] else: print 'Please, Specify either Right or Left shift' return -1 #as exit code &gt;&gt;&gt; shift(chars, 2, 'Right') 'YZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX' &gt;&gt;&gt; shift(chars, 2, 'Left') '23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01' &gt;&gt;&gt; f(chars, 2, 'No_Direction') Please, Specify either Right or Left shift -1 </code></pre> <p>Another way is to use <a href="https://docs.python.org/3/library/collections.html?highlight=counter#collections.deque" rel="nofollow"><code>deque</code></a> class of the <code>collections</code> module, which has <code>rotate</code> method, this way:</p> <pre><code>&gt;&gt;&gt; from collections import deque &gt;&gt;&gt; &gt;&gt;&gt; d = deque(chars) &gt;&gt;&gt; d deque(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) &gt;&gt;&gt; &gt;&gt;&gt; d.rotate(1) &gt;&gt;&gt; d deque(['Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']) &gt;&gt;&gt; d.rotate(-1) &gt;&gt;&gt; d deque(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']) &gt;&gt;&gt; d.rotate(3) &gt;&gt;&gt; ''.join(list(d)) 'XYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW' </code></pre>
python
1
1,905,059
34,424,605
How to match either or group in Regex in Python?
<p>I have this regex.</p> <pre><code>([01]?[0-9]+:?[0-9]*(?:[AP]M)?)\s?(?:-|TO)\s?([01]?[0-9]+:?[0-9]*(?:[AP]M)?) </code></pre> <p>which works for to capture from and to time.</p> <pre><code>8-8:30AM MON TUES THURS FRI NO PARKING (SANITATION BROOM SYMBOL) 7AM-7:30AM EXCEPT SUNDAY </code></pre> <p>However, I want it to be able to capture either the number or the word <code>MIDNIGHT</code></p> <pre><code>NO PARKING (SANITATION BROOM SYMBOL) MOON &amp; STARS (SYMBOLS) TUESDAY FRIDAY MIDNIGHT-3AM </code></pre> <p>How do I extend that. This is what I've got so far. </p> <p><a href="https://regex101.com/r/fC0lI5/7" rel="nofollow">https://regex101.com/r/fC0lI5/7</a></p> <p>Here's what my input is</p> <pre><code>NO PARKING (SANITATION BROOM SYMBOL) MOON &amp; STARS (SYMBOLS) TUESDAY FRIDAY MIDNIGHT-3AM </code></pre> <p>I expect the first group to be <code>MIDNIGHT</code> and second would be <code>3AM</code></p>
<p>You can use the following regex:</p> <pre><code>(MIDNIGHT|[01]?[0-9]+:?[0-9]*(?:[AP]M)?)\s*(?:-|TO)\s*(MIDNIGHT|[01]?[0-9]+:?[0-9]*(?:[AP]M)?) </code></pre> <p>See <a href="https://regex101.com/r/xD9eX2/1" rel="nofollow">regex demo</a></p> <p>I just moved the <code>MIDNIGHT</code> into the first and second capturing groups as an alternative, and replaced <code>?</code> with <code>*</code> quantifiers on both sides of <code>TO</code> or the hyphen (just in case there can be more than one space there).</p>
python|regex
2
1,905,060
12,406,240
Python function to extract multiple segments of a file path
<p>I would like to write a Python function that is capable of taking a file path, like:</p> <blockquote> <p>/abs/path/to/my/file/file.txt</p> </blockquote> <p>And returning three string variables:</p> <ul> <li><code>/abs</code> - the root directory, plus the "top-most" directory in the path</li> <li><code>file</code> - the "bottom-most" directory in the path; the parent of <code>file.txt</code></li> <li><code>path/to/my</code> - everything in between the top- and bottom-most directories in the path</li> </ul> <p>So something with the following pseudo-code:</p> <pre><code>def extract_path_segments(file): absPath = get_abs_path(file) top = substring(absPath, 0, str_post(absPath, "/", FIRST)) bottom = substring(absPath, 0, str_post(absPath, "/", LAST)) middle = str_diff(absPath, top, bottom) return (top, middle, bottom) </code></pre> <p>Thanks in advance for any help here!</p>
<p>You are looking for <a href="http://docs.python.org/library/os.html#os.sep" rel="nofollow"><code>os.sep</code></a>, together with various <code>os.path</code> module functions. Simply split the path by that character, then re-assemble the parts you want to use. Something like:</p> <pre><code>import os def extract_path_segments(path, sep=os.sep): path, filename = os.path.split(os.path.abspath(path)) bottom, rest = path[1:].split(sep, 1) bottom = sep + bottom middle, top = os.path.split(rest) return (bottom, middle, top) </code></pre> <p>This does <em>not</em> deal very well with Windows paths, where both <code>\</code> <em>and</em> <code>/</code> are legal path separators. In that case you <em>also</em> have a drive letter, so you'd have to special-case that as well anyway.</p> <p>Output:</p> <pre><code>&gt;&gt;&gt; extract_path_segments('/abs/path/to/my/file/file.txt') ('/abs', 'path/to/my', 'file') </code></pre>
python|string|filepath
5
1,905,061
33,877,577
Distributed Powerset
<p>Considering the <em>powerset</em> operation (generate all possible subsets of a given set) and its massiveness (time complexity of O(n*2^n) ), I'm trying to scale it horizontally (distributed solution). Don't know if this is easily achievable (hence the question), but I'll try to break down the problem and make it as clear as possible.</p> <p>Consider the following example using python:</p> <pre><code>import itertools s = [1, 2, 3, 4, 5] for l in range(1, len(s)+1): # this can be distributed for subset in itertools.combinations(s, l): print(subset) </code></pre> <p>It's possible (and easy) to distribute the workload based on the subsets length. For instance, if we have a set of length 5, we can make each worker calc all subsets of length N - in this case we would have 5 workers. Why this doesn't appeal to me is quite obvious - workload distribution is not balanced at all. A set of length 20 will generate 184756 subsets of length 10 and only 20 subsets of length 1 (this means that the middle workers will always have a lot more processing to do).</p> <p><strong>Question</strong></p> <p>Is there a way to distribute the workload linearly in this case, and how? Rephrasing the problem - for a set of length L can I distribute the work to compute the powerset using N well balanced workers?</p>
<p>First, this is not a good way to solve the problem. Exponential growth means that the number of needed machines will grow exponentially as well. In virtually every case, the right answer is, "Figure out how not to compute the power set."</p> <p>That said, here is the simplest way to break things up. Take the first 'x' elements, and compute all of the subsets of those things. This gives you '2^x' jobs. Distribute those jobs to <code>y</code> machines relatively evenly. Each machine finishes computing subsets for each job and produces output.</p> <p>As a further optimization, distribute jobs as workers finish. That way if some workers are running slowly, you'll keep everyone working until you finish.</p> <p>(There are more balanced ways to go, but they involve worrying about what your powerset algorithm is.)</p>
python|algorithm|distributed|powerset
2
1,905,062
46,837,646
A dictionary controls a turtle's movement
<p>I'm new to programming and I'm trying to solve a task that I got from school. I have to build a function that uses a turtle to draw something, from an argument of type string (such as 'fdltfd' - move forward, left and forward again). These commands are in a dictionary, so I have to compare the elements from the string with the dictionary keys. If they match, command the turtle to move. The code that I wrote: </p> <pre><code>def execute(turtle, length, args, *cmd): map = {'fd': turtle.fd(length), 'lt': turtle.lt(args), 'bk': turtle.bk(length), 'rt': turtle.rt(args), 'nop':None} for command in cmd: if command in map.keys(): map[command]() execute(bob, 50, 45, 'fdltfd' ) </code></pre> <p>The problem is that the turtle does just what's in the dictionary, moves forward, backward, left and right, it does not even bother looking at my <code>for</code> loop.</p> <p>Can you please give me some ideas of how I could make this work? Or if I am thinking about it right? Of course, not the code for that :)...Thank you very much</p>
<p>Specific problems with your code: The asterisk in front of the <code>cmd</code> argument is incorrect:</p> <pre><code>def execute(turtle, length, args, *cmd): </code></pre> <p>given the way you're invoking it:</p> <pre><code>execute(bob, 50, 45, 'fdltfd') </code></pre> <p>So get rid of the asterisk. The parameter <code>turtle</code> is also the name of a package so change it, e.g. <code>my_turtle</code>. Similarly <code>map</code> is the name of a Python built-in, so change it.</p> <p>Your dictionary should contain functions to call, not the results of calling functions. I.e. instead of:</p> <pre><code>map = {'fd': turtle.fd(length), 'lt': turtle.lt(args), 'bk': turtle.bk(length), 'rt': turtle.rt(args), 'nop':None} </code></pre> <p>I'd expect something more like:</p> <pre><code>commands = {'fd': turtle.fd, 'lt': turtle.lt, 'bk': turtle.bk, 'rt': turtle.rt, 'nop': None} </code></pre> <p>or:</p> <pre><code>LENGTH = 50 ANGLE = 45 commands = { \ 'fd': lambda t: t.fd(LENGTH), \ 'lt': lambda t: t.lt(ANGLE), \ 'bk': lambda t: t.bk(LENGTH), \ 'rt': lambda t: t.rt(ANGLE), \ } </code></pre> <p>Given the value of <code>cmd</code>, <code>'fdltfd'</code>, I don't see how you expect this to work:</p> <pre><code>for command in cmd: </code></pre> <p>as it would lookup 'f', 'd', 'l', 't', etc. in the dictionary instead of 'fd', 'lt', etc. You probably want something more like:</p> <pre><code># 'fdltfd' -&gt; ['fd', 'lt', 'fd'] for command in [a + b for a, b in zip(cmd[0::2], cmd[1::2])]: </code></pre> <p>Putting all the above together, we get a rough implementation that basically works:</p> <pre><code>import turtle LENGTH = 50 ANGLE = 45 commands = { \ 'fd': lambda t: t.fd(LENGTH), \ 'lt': lambda t: t.lt(ANGLE), \ 'bk': lambda t: t.bk(LENGTH), \ 'rt': lambda t: t.rt(ANGLE), \ } def execute(my_turtle, cmd): for command in [a + b for a, b in zip(cmd[0::2], cmd[1::2])]: if command in commands: commands[command](my_turtle) execute(turtle.Turtle(), 'fdltfdltfdltfdltfdltfdltfdltfd') turtle.mainloop() </code></pre>
python|string|function|dictionary|turtle-graphics
2
1,905,063
46,804,666
TF: how to create a dataset from user input data
<p>I've started recently to play with tensorflow and, more specifically, with the new dataset API. I've successfully used a dataset to feed training data to my simple model by plugging dataset's iterators to the nodes of my graph representing input and label. Something like:</p> <pre><code>input = input_dataset.make_one_shot_iterator().get_next() label = label_dataset.make_one_shot_iterator().get_next() </code></pre> <p>Now I'm wondering what to do when I have to do inference on a user input, that is, the user gives me one single input value and I have to make my prediction. If I had a placeholder I would just put the user input in a feed_dict, but with the dataset api I have very little idea how to do something similar. Shall I have a separate graph only for inference in which my <code>input</code> variable is a placeholder?</p> <p>I've tried already to make a feedable iterator as described <a href="https://www.tensorflow.org/programmers_guide/datasets" rel="nofollow noreferrer">here</a> but that only works with a placeholder for strings, while my input are int32. </p> <p>Thanks for any advice.</p>
<p>For that specific purpose, tensorflow provides <code>tf.placeholder_with_default</code> API</p> <pre><code># Create a Dataset dataset = tf.data.Dataset.zip((input_dataset, label_dataset)).batch(32).repeat(...) # Create Iterator input, label = dataset.make_one_shot_iterator() # Create Placholders x = tf.placeholder_with_default(input, shape=[...], name='input') y = tf.placeholder_with_default(label, shape-[...], name='label') def nn_model(features, labels): logits = ... loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=logits)) optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss) return optimizer, loss # Create Model train_op, loss_op = nn_model(x, y) # Training sess.run(train_op) # Inference sess.run(logits, feed_dict={x:..., y:...}) </code></pre>
python|tensorflow|tensorflow-datasets
0
1,905,064
46,748,282
make a list from followers screen name tweepy
<p>I am trying to make a list from my Twitter followers with the code:</p> <pre><code>users = tweepy.Cursor(api.followers).items() l=[] for user in users: l.append(user.screen_name) time.sleep(1) </code></pre> <p>The result of l is an empty list. Why?</p>
<p>It seems with the limited information at hand that you are either not authenticated or don't have any followers. There are a million other things that could be wrong but without the whole program, it is impossible to deduce what.</p> <p>For efficiency &amp; simplicity why not run:</p> <pre><code> my_followers = [] for follower in tweepy.Cursor(api.followers).items(): my_followers.append(follower.screen_name) time.sleep(1) </code></pre> <p><strong>Note:</strong> <a href="https://www.python.org/dev/peps/pep-0008/#names-to-avoid" rel="nofollow noreferrer">PEP 8</a> Recommends you "Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names."</p> <p><strong>Update:</strong> To get the user id you could do something like:</p> <pre><code> my_followers = [] for follower in tweepy.Cursor(api.followers).items(): user_key = [follower.screen_name,follower.user_id] my_followers.append(user_key) time.sleep(1) </code></pre> <p>This way allows you to save both the User Id and Name in an array together. A perhaps, better way, would be to make these dictionary items depending on what you intend to do with the data. </p>
python|list|tweepy
1
1,905,065
61,574,325
Issues importing pandas and matplotlib in anaconda spyder
<p>I tried installing pandas and matplotlib using the pip-command in Anaconda prompt <code>pip install matplotlib</code> and it gave me the following: </p> <pre><code>Requirement already satisfied: matplotlib in c:\programdata\anaconda3\lib\site-p ackages (3.1.3) Requirement already satisfied: python-dateutil&gt;=2.1 in c:\programdata\anaconda3\ lib\site-packages (from matplotlib) (2.8.1) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,&gt;=2.0.1 in c:\pr ogramdata\anaconda3\lib\site-packages (from matplotlib) (2.4.6) Requirement already satisfied: kiwisolver&gt;=1.0.1 in c:\programdata\anaconda3\lib \site-packages (from matplotlib) (1.1.0) Requirement already satisfied: cycler&gt;=0.10 in c:\programdata\anaconda3\lib\site -packages (from matplotlib) (0.10.0) Requirement already satisfied: numpy&gt;=1.11 in c:\programdata\anaconda3\lib\site- packages (from matplotlib) (1.18.1) Requirement already satisfied: six&gt;=1.5 in c:\programdata\anaconda3\lib\site-pac kages (from python-dateutil&gt;=2.1-&gt;matplotlib) (1.14.0) Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-p ackages (from kiwisolver&gt;=1.0.1-&gt;matplotlib) (45.2.0.post20200210) </code></pre> <p>And when trying to import in Spyder, it says no module found. What should I do? Thanks in advance.</p>
<p>Make sure your spyder points to your anaconda environment. Currently it is not pointing to your anaconda env that is the reason you are getting this error.</p>
python|pandas|matplotlib|pip|python-import
0
1,905,066
20,352,628
Pydoop Java home not set installation issue
<p>When I echo <code>$JAVA_HOME</code> I am getting the path of Java. Hadoop is also running, but pydoop installation fails due to this error.</p> <pre><code>Traceback (most recent call last): File "setup.py", line 54, in &lt;module&gt; raise RuntimeError("java home not found, try setting JAVA_HOME") RuntimeError: java home not found, try setting JAVA_HOME </code></pre> <p>I run setup command with <code>sudo python setup.py install --skip-build</code>. As a non root user getting this error running install running install_lib creating /usr/local/lib/python2.7/dist-packages/pydoop error: could not create '/usr/local/lib/python2.7/dist-packages/pydoop': Permission denied</p>
<p>As you run your setup with sudo, it is run under root account, where possibly no JAVA_HOME is defined. </p> <p>You can opt to:</p> <ul> <li>export correct JAVA_HOME for root;</li> <li>or use <a href="https://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a> to install pydoop in an virtual environment under your current user without need to sudo; </li> <li>or use setup <a href="http://docs.python.org/2/install/#alternate-installation" rel="noreferrer">options</a> to specify build and install directory with no root privileges needed.</li> </ul>
java|python|hadoop
5
1,905,067
48,203,834
Input a matrix from user in python
<pre><code>rows = int(input("Enter No. of rows&gt;&gt;&gt;")) columns = int(input('Enter No. of columns&gt;&gt;&gt;')) l=[0]*columns l2=[] for x in range(rows): l2.append(l) print(l2) for i in range(3): for j in range(4): print('enter',i,'x',j,'entry:') l2[i][j] = int(input()) print(l2) </code></pre> <p>This code print similar values in l2. For example if user enters <code>1,2,3,4,5,6,7,8,9,10,11,12</code> it produces a result with <code>[[9, 10, 11, 1], [9, 10, 11, 1], [9, 10, 11, 1]]</code> How do i fix this please help</p>
<p><code>l2.append(l)</code> , This line reference one list many time. If any value of <code>l</code> is change all values in reference are changes at the same time replace this line with</p> <pre><code>l2.append(l+[]) </code></pre>
python
0
1,905,068
51,337,842
Why can't I use the max() function in a global variable in Python?
<p>I am continuously getting <em>NameError: name 'max_col' is not defined</em>. After some research I realized that if I wanted to use max_col inside a function as a global variable I had to declare it that way. However, even after that modification, it seems not to work.</p> <p>After banging my head for over an hour I put the variable max_col inside an array, popped it inside explore_color and and then used max. For some funny reason that seemed to work. Does someone know what I am missing here. Why can't I use the max function in a global variable?</p> <pre><code>def max_area(grid): max_col = float('-inf') def explore_color(color, row, col, size): grid[row][col] = float('inf') global max_col max_col = max(max_col, size) directions = [(-1,0), (1,0), (0,1), (0,-1)] for dir in directions: next_x, next_y = row + dir[0], col + dir[1] if next_x &gt;= 0 and next_x &lt; len(grid) and next_y &gt;= 0 and next_y &lt; len(grid[0]) and grid[next_x][next_y] == color: explore_color(color, next_x, next_y, size + 1) for row in range(len(arr)): for col in range(len(arr[0])): if grid[row][col] != float('inf'): explore_color(grid[row][col], row, col, 1) </code></pre>
<p><code>global</code> does not work here, because <code>max_col</code> is <em>not</em> in the global scope; it is just "one scope up". Try <code>nonlocal</code> instead (Python 3 only). Minimal example:</p> <pre><code>def outer(): foo = 1 def inner(): nonlocal foo foo = max(foo, 10) print("in inner", foo) inner() print("in outer", foo) outer() </code></pre> <p>This prints <code>10</code> both times.</p> <p>Also see <a href="https://stackoverflow.com/q/1261875/1639625">here</a> for more information and examples.</p>
python|python-3.x|scope
3
1,905,069
51,523,395
Python virtualenv activation working but interpreter doesn't
<p>I've just setup a new environment for my project and uploaded a python repository including <code>bin</code>, <code>lib</code> and project folder. I'm pretty sure I did same previously and it worked without problem. Now when doing the same on an AWS environment I get the error <code>-bash: /projects/scrapy/bin/python2.7: cannot execute binary file</code>. However when doing <code>source /projects/scrapy/bin/activate</code> it successfully activates the environment.</p> <p>From what I understand, python should be able to execute without any issue no matter the environment ?</p> <p>Any help or pointing to the right direction would be much appreciated!</p>
<blockquote> <p>python should be able to execute without any issue no matter the environment ?</p> </blockquote> <p>No, the Python binary is tied to your specific OS and computer architecture. Python <em>source code</em> can usually be run on different machines (provided you didn't use OS-specific features), but that's only made possible by compiling a Python interpreter for the specific target environment <em>first</em>.</p> <p>In other words, a Python binary compiled to run on macOS will <em>not</em> work on Linux.</p> <p>All that <code>source bin/activate</code> achieves is that it configures your terminal setting to use the <code>bin</code> directory as the first directory on the <code>PATH</code> search path. This doesn't make <code>bin/python</code> work in another environment, it just means that both environments have a working shell interpreter that can run that script.</p> <p>Create a new virtualenv with a Python binary compiled for Linux, and install the same packages there. Use <a href="https://pipenv.kennethreitz.org/" rel="nofollow noreferrer">Pipenv</a> or <a href="https://pip.readthedocs.io/en/1.1/requirements.html" rel="nofollow noreferrer">a requirements.txt file</a> to transfer the dependencies from Mac to Linux.</p> <p>For example, using Pipenv you'd copy over the <code>Pipfile</code> and <code>Pipfile.lock</code> files to the other computer, then run <code>pipenv install</code> in the directory there and re-create the virtualenv and dependencies from those files.</p> <p>I recommend you read up on Python development best practices in the <a href="https://docs.python-guide.org/" rel="nofollow noreferrer"><em>The Hitchhiker’s Guide to Python</em></a>; this includes such topics on how to manage an environment for a project.</p>
python|virtualenv
2
1,905,070
64,230,821
How to solve this problem without using a strucure? (Getting Time Limit Exceeded)
<p>Recently I took part in a competition for middle school girls. I ran across this problem and I have been working on it for a few weeks. Here is the problem:</p> <p>I. Ventilator Shipments</p> <p>At the local hospital, Gabriela keeps track of all the ventilator shipments. Recently, a new factory has been established to produce ventilators. She knows that the new factory is almost extraordinary in its production, as on a certain day Di, it produces the same amount of ventilators as the product of the previous K days' production. However, the hospital's computer can only handle non-negative numbers less than P, a prime number. Gabriela knows the production value, Di, for each of the first K days. Accordingly, Gabriela wants to know how many ventilators are produced after N days. If this number is greater than or equal to P, the computer displays the remainder of the number of ventilators produced divided by P.</p> <p>Input</p> <pre><code>Line 1: Three space-separated integers N, K, P Lines 2...K+1: A single integer Di </code></pre> <p>Output</p> <pre><code>Line 1: Number of ventilators produced after N days as displayed by the computer </code></pre> <p>Example Input:</p> <pre><code>5 2 7 1 3 </code></pre> <p>Output:</p> <pre><code>6 </code></pre> <p>Note:</p> <pre><code>2 ≤ N ≤ 1000000 1 ≤ K ≤ N 2 ≤ P ≤ 1000003 (where P is guaranteed to be prime) 1 ≤ Di ≤ P−1 </code></pre> <p>The time limit for this problem has been extended to 2000 ms.</p> <p>I have tried 3 different methods</p> <p>Here is the first:</p> <pre><code>import math import sys string=sys.stdin.readline() string=string.rstrip() arr=[0]*3 arr=string.split(' ') n=int(arr[0]) k=int(arr[1]) p=int(arr[2]) mylist=[0]*k for i in range (k): a=int(sys.stdin.readline()) mylist[i]=a%p product=math.prod(mylist) for start in range (n-k): smallest=mylist[start%k] mylist[start%k]=(product%p) product=product*(product%p) product=product//smallest sys.stdout.write (str(mylist[start%k])) </code></pre> <p>In another method I used a queue:</p> <pre><code> import math from collections import deque import sys string=sys.stdin.readline() string=string.rstrip() arr=[0]*3 arr=string.split(' ') n=int(arr[0]) k=int(arr[1]) p=int(arr[2]) q=deque() for i in range (k): a=int(sys.stdin.readline()) q.append(a%p) product=math.prod(q) for i in range (n-k): q.append(product%p) product=product*(product%p) smallest=q.popleft() product=product//smallest sys.stdout.write (str(q.pop())+'\n') </code></pre> <p>However, I'm still getting time limit exceeded on test cast 8. Given the time and space constraints, I don't think I can any kind of structure (list, queue, etc.) to solve this problem. Can someone give me an idea on how to solve this problem?</p>
<p>The problem is not with your data structures so much as your algorithmic overhead. Your first attempt includes a multiplication and five divisions in each loop, plus two list accesses and four assignments. Your second attempt has three divisions, three assignments, and two list-changing operations.</p> <p>You might want to experiment a little to determine roughly how many operations you can perform in 2 seconds. How long does it take you to run 10*6 loop iterations with a trivial body? I suspect that you're not going be able to carry out an iterative solution.</p> <p>Instead of carrying out each iterative computation individually, try focusing on the problem as given. You do <em>not</em> need each day's output; you need only to compute the <em>final</em> day's output, modulo <code>p</code>. That production is a high-order product of the input production sequence (the &quot;seed&quot; days of production). How many times does each of those days appear in that final product? For large <code>n</code>, what is the cycle of values produced? Most importantly, what factor gives you a modular residue of 1? (It's <code>p-1</code> for any factor)</p> <p>Compute how many times each factor appears in the final product; call it <code>use</code>. Reduce that mod <code>p-1</code>. Now you have an expression such as</p> <pre><code>product = k[0] ** (use[0] % (p-1) ) * k[1] ** (use[1] % (p-1) ) * ... print(product % p) </code></pre>
python|arrays|queue
0
1,905,071
69,674,267
How do I add a column which 'differences out' a cumulative variable by category?
<p>My first time posting so bear with me. I have a COVID dataset that looks like this:</p> <pre><code>date | county | confirmed 2021-05-01 Bexar 1200 2021-05-01 Travis 1500 2021-05-01 Harris 1300 2021-05-02 Bexar 1250 2021-05-02 Travis 1550 2021-05-02 Harris 1350 </code></pre> <p>Where the 'confirmed' column is cumulative.</p> <p>In reality it's a much bigger dataset (several dates and over 200 counties). I want to add a column to the dataset which gives the difference (new cases) each day, by the county. So that it ends up like:</p> <pre><code>date | county | confirmed | new_cases 2021-05-01 Bexar 1200 N/A 2021-05-01 Travis 1500 N/A 2021-05-01 Harris 1300 N/A 2021-05-02 Bexar 1250 50 2021-05-02 Travis 1530 30 2021-05-02 Harris 1340 40 </code></pre> <p>I've tried figuring out how to loop the df.diff() command over county, and adding the result to the df each time. But I'm so new to Python that I can't figure it out.</p>
<p>Assuming you are working with <code>pandas</code>:</p> <pre><code>df = df.sort_values(by=['date']) df['diff'] = df.groupby(['county'])['confirmed'].diff().fillna(0) </code></pre>
python|pandas
0
1,905,072
69,788,940
Single row (from flatten DataFrame) into a DataFrame in Python
<p>I have a .csv file containing one million of rows. Each row corresponds to two flatten DataFrames and the index correspond to a unique attribute.</p> <p>For example in my .csv file my the first two rows are like :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>S1_1d_A</th> <th>S1_2d_A</th> <th>S1_3d_A</th> <th>S1_1d_B</th> <th>S1_2d_B</th> <th>S1_3d_B</th> <th>S1_1d_C</th> <th>S1_2d_C</th> <th>S1_3d_C</th> <th>S2_1d_A</th> <th>S2_2d_A</th> <th>S2_3d_A</th> <th>S2_1d_B</th> <th>S2_2d_B</th> <th>S2_3d_B</th> <th>S2_1d_C</th> <th>S2_2d_C</th> <th>S2_3d_C</th> </tr> </thead> <tbody> <tr> <td>1657</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> <td>15</td> <td>16</td> <td>17</td> <td>18</td> </tr> </tbody> </table> </div> <p>The convention used for the name of the columns is the following: SX_R_C.</p> <ul> <li>X the type of DataFrame for the corresponding index (each index has two DataFrame)</li> <li>R : The corresponding row in the original DataFrame</li> <li>C: The corresponding column in the original DataFrame</li> </ul> <p>I would like to recreate the corresponding DataFrames for each rows.</p> <p>So, for example, for the index 1657 I would like to obtain the two following DataFrames :</p> <p>For S1 :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: left;">A</th> <th style="text-align: left;">B</th> <th style="text-align: left;">C</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1d</td> <td style="text-align: left;">1</td> <td style="text-align: left;">4</td> <td style="text-align: left;">7</td> </tr> <tr> <td style="text-align: left;">2d</td> <td style="text-align: left;">2</td> <td style="text-align: left;">5</td> <td style="text-align: left;">8</td> </tr> <tr> <td style="text-align: left;">3d</td> <td style="text-align: left;">3</td> <td style="text-align: left;">6</td> <td style="text-align: left;">9</td> </tr> </tbody> </table> </div> <p>For S2 :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: left;">A</th> <th style="text-align: left;">B</th> <th style="text-align: left;">C</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1d</td> <td style="text-align: left;">10</td> <td style="text-align: left;">13</td> <td style="text-align: left;">16</td> </tr> <tr> <td style="text-align: left;">2d</td> <td style="text-align: left;">11</td> <td style="text-align: left;">14</td> <td style="text-align: left;">17</td> </tr> <tr> <td style="text-align: left;">3d</td> <td style="text-align: left;">12</td> <td style="text-align: left;">15</td> <td style="text-align: left;">18</td> </tr> </tbody> </table> </div> <p>I could do it very easily with loops but the execution time would be too high with 1 million lines. Is there a way to do it easily without looping?</p> <p>N.B.1: I think the method used to create my .csv file was similar to that one : <a href="https://stackoverflow.com/questions/50556537/flatten-dataframe-into-a-single-row">Flatten DataFrame into a single row</a></p> <p>N.B 2 : I have more than 3 rows and 3 columns in reality. It's around 10x10+</p> <p>Thank you for your help!</p>
<p>You can rework the column index to MultiIndex, the rest is a simple reshaping (here using <code>stack</code>) and grouping to split the dataframe:</p> <pre><code>df.columns = pd.MultiIndex.from_arrays(zip(*df.columns.map(lambda x: x.split('_')))) dfs = {k:g for k,g in df.stack(level=[0,1]).droplevel(0).groupby(level=0)} </code></pre> <p>output:</p> <pre><code>&gt;&gt;&gt; dfs {'S1': A B C 1d 1 4 7 2d 2 5 8 3d 3 6 9, 'S2': A B C 1d 10 13 16 2d 11 14 17 3d 12 15 18} &gt;&gt;&gt; dfs['S1'] A B C 1d 1 4 7 2d 2 5 8 3d 3 6 9 </code></pre>
python|pandas|dataframe|numpy
0
1,905,073
72,923,262
Mapping all tables on SQLAlchemy Core
<p>A dumb question but I couldn't get why it does not work. I have a DB with several tables. I can map it manually</p> <pre><code>Earnings = Table ('Earnings', metadata, autoload=True, autoload_with=engine) </code></pre> <p>or automatically using a loop.</p> <pre><code>tablenames = inspect(engine).get_table_names() for tabname in tablenames: tabname = Table (tabname, metadata, autoload=True, autoload_with=engine) </code></pre> <p>I can use this code to see the mapped tables :</p> <pre><code>for tab in metadata.tables: print (tab) ... &gt;&gt;&gt; Earnings ... </code></pre> <p>So far, no problem.</p> <p>The question is that if try use the automatically mapped tables, it does not locate it.</p> <pre><code>Lista_colunas = Earnings.columns.items() for col in Lista_colunas: print (col) --------------------------------------------------------------------------- NameError Traceback (most recent call last) c:\Users\fabio\Banco do Brasil S.A\DINED Parcerias Digitais - General\Python\Amazon\SQLA_Access_Test.ipynb Cell 13' in &lt;cell line: 1&gt;() ----&gt; 1 Lista_colunas = Earnings.columns.items() 2 for col in Lista_colunas: 3 print (col) NameError: name 'Earnings' is not defined </code></pre> <p>I realized that the auto mode is not creating the variables with the 'tabnames', but why not?</p> <p>Somehow, VSCODE identifies that the 'Earnings' is a table objetc (see the picture), but does not let me call for it.</p> <p><a href="https://i.stack.imgur.com/XiqiH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XiqiH.png" alt="VScode mouseover" /></a></p>
<p>Once the loop has completed, <code>tabname</code> will always be the table that corresponds to the final entry tin <code>tablenames</code>. You could collect the tables in a <code>dict</code> keyed on <code>tabname</code>, but SQLAlchemy already provides a way to do this:</p> <pre class="lang-py prettyprint-override"><code>metadata = MetaData() metadata.reflect(bind=engine) # Reflect all tables in the database. Earnings = metadata.tables['Earnings'] </code></pre> <p>The docs for reflection in general are <a href="https://docs.sqlalchemy.org/en/14/core/reflection.html#" rel="nofollow noreferrer">here</a>, the docs for <code>MetaData.reflect</code> are <a href="https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.MetaData.reflect" rel="nofollow noreferrer">here</a>.</p>
python|sqlalchemy
2
1,905,074
55,692,323
How to add python module to Python installations via Pyenv?
<p>I'm using pyenv to deal with different python installations. For that, I'd like to add my local python scripts (module) into the python path library. So, for all the python installations within Pyenv, when it's in use I'd like to "hook" the 'sys.path' and add my custom location. Does someone know where I can make it general for all python version? If it's not possible, where to hook it for a single python installation? </p>
<p>For a single installation on <code>/usr/lib/pythonx.x/</code>, for example, you can add the code:</p> <p><code>sys.path.append("my_modules_path")</code></p> <p>in <code>/usr/lib/pythonx.x/site.py</code>.</p> <p>For more background on the site module, <a href="https://docs.python.org/3/library/site.html" rel="nofollow noreferrer">check</a>.</p>
python|pyenv
0
1,905,075
65,254,142
How to get features importances with variable labels
<p>I'm training a Decision Tree regressor, but when I get the features importances, only the value comes.</p> <p>Does anyone know how to get a dataframe with the name of the variables too?</p> <p>Below is the main part of the code:</p> <pre><code>num_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy=&quot;median&quot;)), ('std_scaler', StandardScaler()), ]) cat_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy=&quot;most_frequent&quot;)), ('oneHot', OneHotEncoder(handle_unknown='ignore')), ]) num_attribs = x_train.select_dtypes(include=np.number).columns.tolist() cat_attribs = x_train.select_dtypes(include='object').columns.tolist() full_pipeline = ColumnTransformer([ (&quot;num&quot;, num_pipeline, num_attribs), (&quot;cat&quot;, cat_pipeline, cat_attribs), ]) train_prepared = full_pipeline.fit_transform(x_train) param_grid = {'max_leaf_nodes': list(range(2, 100)), 'min_samples_split': [2, 3, 4], 'max_depth': list(range(3, 20))} dtr = DecisionTreeRegressor() grid_search = GridSearchCV(dtr, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1, return_train_score=True, n_jobs=-1) grid_search = grid_search.fit(train_prepared, y_train) grid_search.best_estimator_.feature_importances_ </code></pre> <p>Here is the output of feature_importances_:</p> <pre><code>array([2.59182901e-03, 5.08807106e-04, 1.46808641e-03, 2.20756886e-03, 1.48878361e-01, 5.65411415e-03, 5.16351699e-03, 9.37444882e-03, 0.00000000e+00, 7.19228983e-03, 1.00581364e-03, 1.05073934e-03, 2.63424620e-03, 9.41587243e-03, 7.22742602e-02, 0.00000000e+00, 2.41075666e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.12861715e-02, 3.39987538e-03, 5.27924849e-04, 2.20562317e-03, 4.14808367e-03, 5.82557008e-04, 1.40134963e-03, 0.00000000e+00, 0.00000000e+00, 1.08351677e-03, 0.00000000e+00, 0.00000000e+00, 1.58022433e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 2.79779634e-02, 5.94436576e-01, 3.72725666e-02, 1.11665462e-03, 2.39049915e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.15314788e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,...]) </code></pre>
<p>While you can't directly call a method to get the labels from the model, they are the same and indexed in the same way as how <code>x_train</code> is, therefore you can obtain the names by using:</p> <pre><code>x_train.select_dtypes(include=np.number).columns </code></pre> <p>Or you can create a dictionary for example:</p> <pre><code>feature_importances = {x_train.select_dtypes(include=np.number).columns[x]:grid_search.best_estimator_.feature_importances_[x] for x in range(len(grid_search.best_estimator_.feature_importances_))} </code></pre>
python|machine-learning|scikit-learn|feature-selection
1
1,905,076
62,719,951
weighted numpy bincount for 2D IDs array and 1D weights
<p>I am using numpy_indexed for applying a vectorized numpy bincount, as follows:</p> <pre><code>import numpy as np import numpy_indexed as npi rowidx, colidx = np.indices(index_tri.shape) (cols, rows), B = npi.count((index_tri.flatten(), rowidx.flatten())) </code></pre> <p>where <code>index_tri</code> is the following matrix:</p> <pre><code>index_tri = np.array([[ 0, 0, 0, 7, 1, 3], [ 1, 2, 2, 9, 8, 9], [ 3, 1, 1, 4, 9, 1], [ 5, 6, 6, 10, 10, 10], [ 7, 8, 9, 4, 3, 3], [ 3, 8, 6, 3, 8, 6], [ 4, 3, 3, 7, 8, 9], [10, 10, 10, 5, 6, 6], [ 4, 9, 1, 3, 1, 1], [ 9, 8, 9, 1, 2, 2]]) </code></pre> <p>Then I map the binned values in the corresponding position of the following initialized matrix <code>m</code>:</p> <pre><code>m = np.zeros((10,11)) m array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]) m[rows, cols] = B m array([[3., 1., 0., 1., 0., 0., 0., 1., 0., 0., 0.], [0., 1., 2., 0., 0., 0., 0., 0., 1., 2., 0.], [0., 3., 0., 1., 1., 0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 1., 2., 0., 0., 0., 3.], [0., 0., 0., 2., 1., 0., 0., 1., 1., 1., 0.], [0., 0., 0., 2., 0., 0., 2., 0., 2., 0., 0.], [0., 0., 0., 2., 1., 0., 0., 1., 1., 1., 0.], [0., 0., 0., 0., 0., 1., 2., 0., 0., 0., 3.], [0., 3., 0., 1., 1., 0., 0., 0., 0., 1., 0.], [0., 1., 2., 0., 0., 0., 0., 0., 1., 2., 0.]]) </code></pre> <p>However, this considers that the weight of each value in <code>index_tri</code> per column is 1. Now if I have a weights array, providing a corresponding weight value per column in <code>index_tri</code> instead of 1:</p> <p><code>weights = np.array([0.7, 0.8, 1.5, 0.6, 0.5, 1.9])</code></p> <p>how to apply a weighted bincount so that my output matrix <code>m</code> becomes as follows:</p> <pre><code>array([[3., 0.5, 0., 1.9, 0., 0., 0., 0.6, 0., 0., 0.], [0., 0.7, 2.3, 0., 0., 0., 0., 0., 0.5, 2.5, 0.], [0., 4.2, 0., 0.7, 0.6, 0., 0., 0., 0., 0.5, 0.], [0., 0., 0., 0., 0., 0.7, 2.3, 0., 0., 0., 3.], [0., 0., 0., 2.4, 0.6, 0., 0., 0.7, 0.8, 1.5, 0.], [0., 0., 0., 2.3, 0., 0., 2.4, 0., 1.3, 0., 0.], [0., 0., 0., 2.3, 0.7, 0., 0., 0.6, 0.5, 1.9, 0.], [0., 0., 0., 0., 0., 0.6, 2.4, 0., 0., 0., 3.], [0., 3.9, 0., 0.6, 0.7, 0., 0., 0., 0., 0.8, 0.], [0., 0.6, 2.4, 0., 0., 0., 0., 0., 0.8, 2.2, 0.]]) </code></pre> <p>any idea?</p> <hr /> <p>By using a <code>for</code> loop and the numpy <code>bincount()</code> I could solve it as follows:</p> <pre><code>for i in range(m.shape[0]): m[i, :] = np.bincount(index_tri[i, :], weights=weights, minlength=m.shape[1]) </code></pre> <p>I am trying to adapt the vectorized provided solution from <a href="https://stackoverflow.com/a/60046212/1476932">here</a> and <a href="https://stackoverflow.com/a/46256361/1476932">here</a> respectively but I cannot figure out what the <code>ix2D</code> variable corresponds to in the first link. Could someone elaborate a bit if possible.</p> <hr /> <p>Update (solution):</p> <p>Based on the @Divakar's solution below, here is an updated version where it takes an extra input parameter in case that your indices input matrix does not cover the full range of the output initialized matrix:</p> <pre><code> def bincount2D(id_ar_2D, weights_1D, sz=None): # Inputs : 2D id array, 1D weights array # Extent of bins per col if sz == None: n = id_ar_2D.max() + 1 N = len(id_ar_2D) else: n = sz[1] N = sz[0] # add offsets to the original values to be used when we apply raveling later on id_ar_2D_offsetted = id_ar_2D + n * np.arange(N)[:, None] # Finally use bincount with those 2D bins as flattened and with # flattened b as weights. Reshaping is needed to add back into &quot;a&quot;. ids = id_ar_2D_offsetted.ravel() W = np.tile(weights_1D, N) return np.bincount(ids, W, minlength=n * N).reshape(-1, n) </code></pre>
<p>Inspired by <a href="https://stackoverflow.com/a/46256361/"><code>this post</code></a> -</p> <pre><code>def bincount2D(id_ar_2D, weights_1D): # Inputs : 2D id array, 1D weights array # Extent of bins per col n = id_ar_2D.max()+1 N = len(id_ar_2D) id_ar_2D_offsetted = id_ar_2D + n*np.arange(N)[:,None] # Finally use bincount with those 2D bins as flattened and with # flattened b as weights. Reshaping is needed to add back into &quot;a&quot;. ids = id_ar_2D_offsetted.ravel() W = np.tile(weights_1D,N) return np.bincount(ids, W, minlength=n*N).reshape(-1,n) out = bincount2D(index_tri, weights) </code></pre>
python|binning|weighted|numpy-indexed
1
1,905,077
62,007,356
Gradients of a neural network is only 1d
<p>I have a neural network with input tf_x with shape <code>[None, 100]</code> and output tf_y with shape <code>[None,2]</code>. I would like to calculate the gradient of tf_y with respect to tf_x. </p> <p>Howeverm when I run</p> <pre><code>tf.gradients(tf_y,tf_x) </code></pre> <p>I get a one-dimensional list with shape [None,100]. Why don't I have the derivative of both components? (i.e. shape [None, 2, 100])</p>
<p>In TensorFlow 2, you can use <code>GradientTape</code> with <code>batch_jacobian</code>. From the <a href="https://www.tensorflow.org/api_docs/python/tf/GradientTape#batch_jacobian" rel="nofollow noreferrer">official website</a>:</p> <pre><code>with tf.GradientTape() as g: x = tf.constant([[1., 2.], [3., 4.]], dtype=tf.float32) g.watch(x) y = x * x batch_jacobian = g.batch_jacobian(y, x) </code></pre>
python|tensorflow
0
1,905,078
70,111,607
How to merge columns vertically?
<p>Hi I have a df with columns that looks like this:</p> <pre><code> E F G 0 10516894 0000 10523438 0000 10531813 0003 1 10334414 0007 12082512 0000 12058004 0004 2 05 00 03 3 07 00 04 4 02 08 05 </code></pre> <p>But I want it like this, all in one column:</p> <pre><code> E 0 10516894 0000 1 10334414 0007 2 05 3 07 4 02 5 10523438 0000 6 12082512 0000 7 00 8 00 9 08 10 10531813 0003 11 12058004 0004 12 03 13 04 14 05 </code></pre> <p>Im quite new to pandas so I'm not sure the best way to go about this.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unstack</code></a>:</p> <pre><code>df = df.unstack().to_frame('E').reset_index(drop=True) print (df) E 0 10516894 0000 1 10334414 0007 2 05 3 07 4 02 5 10523438 0000 6 12082512 0000 7 00 8 00 9 08 10 10531813 0003 11 12058004 0004 12 03 13 04 14 05 </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with set new column name by <code>value_name</code>:</p> <pre><code>df = df.melt(value_name='E')[['E']] print (df) E 0 10516894 0000 1 10334414 0007 2 05 3 07 4 02 5 10523438 0000 6 12082512 0000 7 00 8 00 9 08 10 10531813 0003 11 12058004 0004 12 03 13 04 14 05 </code></pre>
python|pandas
2
1,905,079
60,876,430
Convert dataframe column with Json Array content into separate columns
<p>i have a column dataframe with a json array that i want to split in columns for every row.</p> <p><strong>Dataframe</strong></p> <pre><code> FIRST_NAME CUSTOMFIELDS 0 Maria [{'FIELD_NAME': 'CONTACT_FIELD_1', 'FIELD_VALU... 1 John [{'FIELD_NAME': 'CONTACT_FIELD_1', 'FIELD_VALU... ... </code></pre> <p><strong>Goal</strong></p> <p>I need convert the json content in that column into a dataframe </p> <pre><code>+------------+-----------------+-------------+-----------------+ | FIRST NAME | FIELD_NAME | FIELD_VALUE | CUSTOM_FIELD_ID | +------------+-----------------+-------------+-----------------+ | Maria | CONTACT_FIELD_1 | EN | CONTACT_FIELD_1 | | John | CONTACT_FIELD_1 | false | CONTACT_FIELD_1 | +------------+-----------------+-------------+-----------------+ </code></pre>
<p>The code snippet below should work for you.</p> <pre><code>import pandas as pd df = pd.DataFrame() df['FIELD'] = [[{'FIELD_NAME': 'CONTACT_FIELD_1', 'FIELD_VALUE': 'EN', 'CUSTOM_FIELD_ID': 'CONTACT_FIELD_1'}, {'FIELD_NAME': 'CONTACT_FIELD_10', 'FIELD_VALUE': 'false', 'CUSTOM_FIELD_ID': 'CONTACT_FIELD_10'}]] temp_dict = {} counter = 0 for entry in df['FIELD'][0]: temp_dict[counter] = entry counter += 1 new_dataframe = pd.DataFrame.from_dict(temp_dict, orient='index') new_dataframe #outputs dataframe </code></pre> <p><strong>Edited answer to reflect edited question:</strong> </p> <p>Under the assumption that each entry in CUSTOMFIELDS is a list with 1 element (which is different from original question; the entry had 2 elements), the following will work for you and create a dataframe in the requested format. </p> <pre><code>import pandas as pd # Need to recreate example problem df = pd.DataFrame() df['CUSTOMFIELDS'] = [[{'FIELD_NAME': 'CONTACT_FIELD_1', 'FIELD_VALUE': 'EN', 'CUSTOM_FIELD_ID': 'CONTACT_FIELD_1'}], [{'FIELD_NAME': 'CONTACT_FIELD_1', 'FIELD_VALUE': 'FR', 'CUSTOM_FIELD_ID': 'CONTACT_FIELD_1'}]] df['FIRST_NAME'] = ['Maria', 'John'] #begin solution counter = 0 dataframe_solution = pd.DataFrame() for index, row in df.iterrows(): dataframe_solution = pd.concat([dataframe_solution, pd.DataFrame.from_dict(row['CUSTOMFIELDS'][0], orient = 'index').transpose()], sort = False, ignore_index = True) dataframe_solution.loc[counter,'FIRST_NAME'] = row['FIRST_NAME'] counter += 1 </code></pre> <p>Your dataframe is in <code>dataframe_solution</code></p>
python|json
1
1,905,080
65,999,969
struct.unpack returning very large value python
<p>I feel like this should be simple, and because it's so simple, I can't wrap my head around why it's not working.</p> <p>I have a basic function that uses struct.unpack to turn a bytearray into an integer. So we can see that in hex notation x90 = 144 in decimal. So I would expect that if I ask unpack to convert to integer, I get 144, but I'm getting this ridiculously large number. I'm happy to read whatever reference material you can provide, as the <a href="https://docs.python.org/3/library/struct.html" rel="nofollow noreferrer">struct documentation</a> does not provide any clues.</p> <p>See example below:</p> <pre><code>unpack_signed_integer, = struct.unpack('i', b'\x00\x00\x00\x90') unpack_unsigned_integer, = struct.unpack('I', b'\x00\x00\x00\x90') print(f&quot;signed integer: {unpack_signed_integer}&quot;) print(f&quot;unsigned integer: {unpack_unsigned_integer}&quot;) </code></pre> <p>Output:</p> <pre><code>signed integer: -1879048192 unsigned integer: 2415919104 </code></pre>
<p>You are unpacking the value 0x90_00_00_00, that is, a 64 bit number in little-endian order. It is large because it has 7 hexadecimal zeros, each representing a power of sixteen.</p> <p>Either reverse the order of your bytes, or <a href="https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment" rel="nofollow noreferrer">pick a different byte order</a>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; struct.unpack('I', b'\x00\x00\x00\x90') (2415919104,) &gt;&gt;&gt; struct.unpack('I', b'\x90\x00\x00\x00') (144,) &gt;&gt;&gt; struct.unpack('&gt;I', b'\x00\x00\x00\x90') (144,) </code></pre> <p>In the above example, the <code>&gt;</code> in <code>'&gt;I'</code> tells <code>struct.unpack()</code> to use big-endian ordering instead. If you are dealing with data you received from some network protocol, you should probably use <code>!</code> instead, which represents the default byte order for network communications as per the <a href="https://www.rfc-editor.org/rfc/rfc1700" rel="nofollow noreferrer">IETF RFC</a>; this is the same as <code>&gt;</code> big-endian order, but codified to avoid confusion.</p> <p>Without an explicit byte order marker, <code>@</code>, or <em>native</em> byte order, is assumed. In your specific case, your machine native byte order is little-endian, but that is a property of the specific machine architecture of your computer, not of Python.</p>
python|arrays|python-3.x|struct|unpack
6
1,905,081
69,044,476
Jupyter notebook does not connect to kernel(2) + Windows 10 Enterprise + ImportError: cannot import name 'constants' --formatted
<p>I installed Anaconda, and created a second environment (i.e. vamp_env) to run my script in Python 3.6.</p> <p>I build my script a couple of years ago using Python 3.6, and older versions of the packages listed below. I used my script on numerous occasions, it runs well however only with the package versions listed below.</p> <p>When launching jupyter notebook kernel(1) connects normally, however kernel(2) (vamp_env) does not.</p> <p>Can someone please help??</p> <p>My default browser is Google Chrome</p> <p>Default path: C:\Users\MyName</p> <p>I followed these steps in Anaconda Prompt:</p> <pre><code>conda create --name vamp_env conda activate vamp_env conda install python=3.6 conda install numpy==1.13.3 conda install scipy==0.19.1 conda install pandas==0.20.3 conda install xlrd matplotlib jinja2 conda install -c anaconda ipykernel python -m ipykernel install --user --name=vamp_env </code></pre> <p>Then I added the following paths to my environment variables:</p> <pre><code>C:\Users\MyName\Anaconda3 C:\Users\MyName\Anaconda3\Library\mingw-w64\bin C:\Users\MyName\Anaconda3\Library\bin C:\Users\MyName\Anaconda3\Scripts C:\Users\MyName\Anaconda3\bin </code></pre> <p>The following messages appear on Anaconda Prompt:</p> <pre><code>[I 12:49:35.090 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports Traceback (most recent call last): File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\runpy.py&quot;, line 195, in _run_module_as_main &quot;main&quot;, mod_spec) File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\runpy.py&quot;, line 87, in _run_code exec(code, run_globals) File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\ipykernel_launcher.py&quot;, line 15, in from ipykernel import kernelapp as app File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\ipykernel_init_.py&quot;, line 2, in from .connect import * File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\ipykernel\connect.py&quot;, line 18, in import jupyter_client File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\jupyter_client_init_.py&quot;, line 4, in from .connect import * File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\jupyter_client\connect.py&quot;, line 21, in import zmq File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\zmq_init_.py&quot;, line 55, in from zmq import backend File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\zmq\backend_init_.py&quot;, line 40, in reraise(*exc_info) File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\zmq\utils\sixcerpt.py&quot;, line 34, in reraise raise value File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\zmq\backend_init_.py&quot;, line 27, in _ns = select_backend(first) File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\zmq\backend\select.py&quot;, line 28, in select_backend mod = import(name, fromlist=public_api) File &quot;C:\Users\MyName\Anaconda3\envs\vamp_env\lib\site-packages\zmq\backend\cython_init_.py&quot;, line 6, in from . import (constants, error, message, context, ImportError: cannot import name 'constants' [W 12:49:38.122 NotebookApp] KernelRestarter: restart failed [W 12:49:38.123 NotebookApp] Kernel 248bb278-4e77-42df-8399-25f7e2b0db9a died, removing from map. [W 12:49:59.815 NotebookApp] Timeout waiting for kernel_info reply from f2b6c540-69d3-46e5-857c-66b244a2e7d9 [E 12:49:59.817 NotebookApp] Error opening stream: HTTP 404: Not Found (Kernel does not exist: f2b6c540-69d3-46e5-857c-66b244a2e7d9) [W 12:50:01.018 NotebookApp] Replacing stale connection: 248bb278-4e77-42df-8399-25f7e2b0db9a:1e0dfb64a2384c8e915c30bbf6b9ec23 [W 12:50:23.362 NotebookApp] Timeout waiting for kernel_info reply from 248bb278-4e77-42df-8399-25f7e2b0db9a [E 12:50:23.363 NotebookApp] Error opening stream: HTTP 404: Not Found (Kernel does not exist: 248bb278-4e77-42df-8399-25f7e2b0db9a) [W 12:50:23.370 NotebookApp] 404 GET /api/kernels/248bb278-4e77-42df-8399-25f7e2b0db9a/channels?session_id=1e0dfb64a2384c8e915c30bbf6b9ec23 (::1): Kernel does not exist: 248bb278-4e77-42df-8399-25f7e2b0db9a [W 12:50:23.391 NotebookApp] 404 GET /api/kernels/248bb278-4e77-42df-8399-25f7e2b0db9a/channels?session_id=1e0dfb64a2384c8e915c30bbf6b9ec23 (::1) 22376.820000ms referer=None [W 12:50:25.405 NotebookApp] Replacing stale connection: 248bb278-4e77-42df-8399-25f7e2b0db9a:1e0dfb64a2384c8e915c30bbf6b9ec23 [W 12:50:25.710 NotebookApp] Replacing stale connection: 248bb278-4e77-42df-8399-25f7e2b0db9a:1e0dfb64a2384c8e915c30bbf6b9ec23 [I 12:50:59.521 NotebookApp] Saving file at /test case/STEP_1_3.ipynb </code></pre>
<p>Problem solved! Reinstalling Anaconda v5.2 does the trick!</p>
python|jupyter-notebook
0
1,905,082
59,159,168
Python - Parse semi structured text and extract to structed data
<p>with semi-structure data like below, need to convert specific portions in to structured data for further use</p> <pre><code>%MOBILE PARSED MESSAGE FILE %PARX VERSION : PARX 06.30.80 patch 69 %RAYN VERSION : RAYN_9.83 %LOG FILE NAME : C:\Final\Bbi_10-31.11-36.dng %Somethin Proprietary and Confidential. 2019 Oct 31 04:32:55.139 [02] 0xB0B3 LTE PDCP UL Cipher Data PDU Subscription ID = 1 Version = 1 Num Subpackets = 1 Subpacket[0] Subpacket ID = PDCP PDU with Ciphering (0xC3) Subpacket Version = 26 Subpacket Size = 60 bytes SRB Ciphering Keys (hex) = 6B 6E 77 04 68 A5 30 D2 E3 68 86 0E 1D 35 8C D1 DRB Ciphering Keys (hex) = 98 1A 2E 33 E6 9A 85 2B C1 1F A2 CC 3D 31 45 8F SRB Cipher Algo = LTE AES DRB Cipher Algo = LTE AES Num PDUs = 1 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | | | | | | | | | | | | |els | | | | | | | |cfg| |sn |bearer|valid|pdu |logged| | |count | |compressed| |mini|packet | | | | | |PDCPUL CIPH DATA |idx|mode|length|id |pdu |size |bytes |sys_fn|sub_fn|(hex) |sn |pdu |pdu type|sign|action |checksum|e |option|log_buffer (hex) | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |PDCPUL CIPH DATA | 4 | AM |12 bit| 3 | Yes | 62 | 4 | 245 | 1 | 0x3A | 58 | No | DEFAULT|n/a | n/a | n/a |n/a| n/a | 80 3A 45 00 | Cipher Subpacket[0] PDU[0] Encrypted Data: Unable to encrypt 2019 Oct 31 04:32:55.169 [B0] 0xB0A3 LTE PDCP DL Cipher Data PDU Subscription ID = 1 Version = 1 Num Subpackets = 1 Subpacket[0] Subpacket ID = PDCP PDU with Ciphering (0xC3) Subpacket Version = 24 Subpacket Size = 60 bytes PDCP DL Data PDU with Ciphering { SRB Ciphering Keys (hex) = 6B 6E 77 04 68 A5 30 D2 E3 68 86 0E 1D 35 8C D1 DRB Ciphering Keys (hex) = 98 1A 2E 33 E6 9A 85 2B C1 1F A2 CC 3D 31 45 8F SRB Cipher Algo = LTE AES DRB Cipher Algo = LTE AES Num PDUs = 1 ------------------------------------------------------------------------------------------------------------------------ | | | | | | | | | | | | |els | | | |cfg| |sn |bearer|valid|pdu |logged| | |count | |mini| | |PDCPDL CIPH DATA|idx|mode|length|id |pdu |size |bytes |sys_fn|sub_fn|(hex) |sn |sign|log_buffer (hex) | ------------------------------------------------------------------------------------------------------------------------ |PDCPDL CIPH DATA| 4 | AM |12 bit| 3 | Yes | 62 | 4 | 248 | 0 | 0x3A | 58 |n/a | 80 3A 2F BC | } Cipher Subpacket[0] PDU[0] Decrypted Data: Unable to decrypt 2019 Oct 31 04:32:56.168 [4F] 0xB0A3 LTE PDCP DL Cipher Data PDU Subscription ID = 1 Version = 1 Num Subpackets = 1 Subpacket[0] Subpacket ID = PDCP PDU with Ciphering (0xC3) Subpacket Version = 24 Subpacket Size = 60 bytes PDCP DL Data PDU with Ciphering { SRB Ciphering Keys (hex) = 6B 6E 77 04 68 A5 30 D2 E3 68 86 0E 1D 35 8C D1 DRB Ciphering Keys (hex) = 98 1A 2E 33 E6 9A 85 2B C1 1F A2 CC 3D 31 45 8F SRB Cipher Algo = LTE AES DRB Cipher Algo = LTE AES Num PDUs = 1 ------------------------------------------------------------------------------------------------------------------------ | | | | | | | | | | | | |els | | | |cfg| |sn |bearer|valid|pdu |logged| | |count | |mini| | |PDCPDL CIPH DATA|idx|mode|length|id |pdu |size |bytes |sys_fn|sub_fn|(hex) |sn |sign|log_buffer (hex) | ------------------------------------------------------------------------------------------------------------------------ |PDCPDL CIPH DATA| 4 | AM |12 bit| 3 | Yes | 62 | 4 | 348 | 0 | 0x3B | 59 |n/a | 80 3B 86 3B | } Cipher Subpacket[0] PDU[0] Decrypted Data: Unable to decrypt %MOBILE PARSED MESSAGE FILE %PARX VERSION : PARX 06.30.80 patch 69 %RAYN VERSION : RAYN_9.83 %LOG FILE NAME : C:\Final\Abi_10-31.11-39.dng %Somethin Proprietary and Confidential. 2019 Oct 31 04:36:04.543 [85] 0xB0B3 LTE PDCP UL Cipher Data PDU Subscription ID = 1 Version = 1 Num Subpackets = 1 Subpacket[0] Subpacket ID = PDCP PDU with Ciphering (0xC3) Subpacket Version = 26 Subpacket Size = 60 bytes SRB Ciphering Keys (hex) = BC 61 5B 1C 05 1F 92 C6 83 F2 68 E6 00 A3 D7 DC DRB Ciphering Keys (hex) = 6B 25 EE 8D 1C 48 B2 3A 07 9A 9D 22 AA 77 33 76 SRB Cipher Algo = LTE AES DRB Cipher Algo = LTE AES Num PDUs = 1 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | | | | | | | | | | | | |els | | | | | | | |cfg| |sn |bearer|valid|pdu |logged| | |count | |compressed| |mini|packet | | | | | |PDCPUL CIPH DATA |idx|mode|length|id |pdu |size |bytes |sys_fn|sub_fn|(hex) |sn |pdu |pdu type|sign|action |checksum|e |option|log_buffer (hex) | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |PDCPUL CIPH DATA | 4 | AM |12 bit| 3 | Yes | 62 | 4 | 135 | 8 | 0xF9 | 249 | No | DEFAULT|n/a | n/a | n/a |n/a| n/a | 80 F9 45 00 | Cipher Subpacket[0] PDU[0] Encrypted Data: Unable to encrypt 2019 Oct 31 04:36:04.568 [58] 0xB0A3 LTE PDCP DL Cipher Data PDU Subscription ID = 1 Version = 1 Num Subpackets = 1 Subpacket[0] Subpacket ID = PDCP PDU with Ciphering (0xC3) Subpacket Version = 24 Subpacket Size = 60 bytes PDCP DL Data PDU with Ciphering { SRB Ciphering Keys (hex) = BC 61 5B 1C 05 1F 92 C6 83 F2 68 E6 00 A3 D7 DC DRB Ciphering Keys (hex) = 6B 25 EE 8D 1C 48 B2 3A 07 9A 9D 22 AA 77 33 76 SRB Cipher Algo = LTE AES DRB Cipher Algo = LTE AES Num PDUs = 1 ------------------------------------------------------------------------------------------------------------------------ | | | | | | | | | | | | |els | | | |cfg| |sn |bearer|valid|pdu |logged| | |count | |mini| | |PDCPDL CIPH DATA|idx|mode|length|id |pdu |size |bytes |sys_fn|sub_fn|(hex) |sn |sign|log_buffer (hex) | ------------------------------------------------------------------------------------------------------------------------ |PDCPDL CIPH DATA| 4 | AM |12 bit| 3 | Yes | 62 | 4 | 138 | 7 | 0xF8 |248 |n/a | 80 F8 23 41 | } Cipher Subpacket[0] PDU[0] Decrypted Data: Unable to decrypt </code></pre> <p>I have the pseudo code to extract the data as follows. What I'm looking for is help with specific steps of the pseduo code marked as <code>#need_help</code> - these are primarily around identifying specific part of the text and capturing them into variables.</p> <pre><code>intialize a list, data = [] for each text block ( text block starts with time format `yyyy MMM dd hh:mm:ss.mil`) #need_help if ending with `0xB0B3 LTE PDCP UL Cipher Data PDU` #need_help if `size pdu` field value `== 62` #need_help store 62 to variable pdu_size store 'ulPdu' to variable type Extract the `yyyy MMM dd hh:mm:ss.mil` and store the value as `datetime` type in a variable `datetime` #need_help Extract the field `seq` and store as variable `seq` #need_help store ulPdu = {"datetime": datetime, "pDuType": type, "pDuSize": pdu_size", "seq": seq} add ulPdu to data else pass # try next text block else if ending with `0xB0A3 LTE PDCP DL Cipher Data PDU` if `size pdu` field value `== 62` store 62 to variable pdu_size store 'dlPdu' to variable type Extract the `yyyy MMM dd hh:mm:ss.mil` and store the value as `datetime` type in a variable `datetime` Extract the field `seq` and store as variable `seq` store dlPdu = {"datetime": datetime, "pDuType": type, "pDuSize": pdu_size", "seq": seq} add dlPdu to data else pass # try next text block else pass # try next text block </code></pre>
<p>You can use <a href="https://github.com/dmulyalin/ttp" rel="nofollow noreferrer">TTP</a> to parse above text, here is the code:</p> <pre><code>from ttp import ttp ttp_template=""" &lt;group name="results"&gt; %PARX VERSION : {{ PARX_VERSION | PHRASE }} %RAYN VERSION : {{ RAYN_VERSION }} %LOG FILE NAME : {{ LOG_FILE_NAME }} &lt;group name="Something Proprietary and Confidential"&gt; %Somethin Proprietary and Confidential. {{ _start_ }} &lt;group name="{{ date }} {{ time }}"&gt; {{ date | PHRASE | _start_ }} {{ time }} [{{ ignore }}] {{ ignore }} LTE PDCP UL Cipher Data PDU {{ date | PHRASE | _start_ }} {{ time }} [{{ ignore }}] {{ ignore }} LTE PDCP DL Cipher Data PDU Subscription ID = {{ Subscription_ID }} Version = {{ version }} Num Subpackets = {{ Num_Subpackets }} Subpacket ID = {{ Subpacket_ID | PHRASE }} Subpacket Version = {{ Subpacket_Version }} Subpacket Size = {{ Subpacket_Size | PHRASE }} SRB Ciphering Keys (hex) = {{ SRB_Ciphering_Keys_hex | PHRASE }} DRB Ciphering Keys (hex) = {{ DRB_Ciphering_Keys_hex | PHRASE }} SRB Cipher Algo = {{ SRB_Cipher_Algo | PHRASE }} DRB Cipher Algo = {{ DRB_Cipher_Algo | PHRASE }} Num PDUs = {{ Num_PDUs }} &lt;group name="PDCPUL_CIPH_DATA" method="table"&gt; |PDCPUL CIPH DATA | {{ cfg_idx | DIGIT }} | {{ mode }} |{{ sn_length }} bit| {{ bearer_id }} | {{ valid_pdu }} | {{ pdu_size | DIGIT }} | {{ logged_bytes }} | {{ sys_fn }} | {{ sub_fn }} | {{ count }} | {{ sn }} | {{ compressed_pdu }} | {{pdu_type}}|{{ els }} | {{ packet_act }} | {{ checksum }} |{{ e }}| {{ option }} | {{ log_buffer | PHRASE }} | |PDCPDL CIPH DATA| {{ cfg_idx | DIGIT }} | {{ mode }} |{{ sn_length }} bit| {{ bearer_id }} | {{ valid_pdu }} | {{ pdu_size | DIGIT }} | {{ logged_bytes }} | {{ sys_fn }} | {{ sub_fn }} | {{ count }} |{{ sn }} |{{ els }} | {{ log_buffer | PHRASE }} | |PDCPDL CIPH DATA| {{ cfg_idx | DIGIT }} | {{ mode }} |{{ sn_length }} bit| {{ bearer_id }} | {{ valid_pdu }} | {{ pdu_size | DIGIT }} | {{ logged_bytes }} | {{ sys_fn }} | {{ sub_fn }} | {{ count }} | {{ sn }} |{{ els }} | {{ log_buffer | PHRASE }} | &lt;/group&gt; &lt;/group&gt; &lt;/group&gt; &lt;/group&gt; """ parser = ttp(data="/absolute/os/path/to/data.txt", template=ttp_template) parser.parse() print(parser.result(format="json")[0]) </code></pre> <p>that code would produce:</p> <pre><code>[ { "results": [ { "LOG_FILE_NAME": "C:\\Final\\Bbi_10-31.11-36.dng", "PARX_VERSION": "PARX 06.30.80 patch 69", "RAYN_VERSION": "RAYN_9.83", "Something Proprietary and Confidential": { "2019 Oct 31 04:32:55.139": { "DRB_Cipher_Algo": "LTE AES", "DRB_Ciphering_Keys_hex": "98 1A 2E 33 E6 9A 85 2B C1 1F A2 CC 3D 31 45 8F", "Num_PDUs": "1", "Num_Subpackets": "1", "PDCPUL_CIPH_DATA": { "bearer_id": "3", "cfg_idx": "4", "checksum": "n/a", "compressed_pdu": "No", "count": "0x3A", "e": "n/a", "els": "n/a", "log_buffer": "80 3A 45 00", "logged_bytes": "4", "mode": "AM", "option": "n/a", "packet_act": "n/a", "pdu_size": "62", "pdu_type": "DEFAULT", "sn": "58", "sn_length": "12", "sub_fn": "1", "sys_fn": "245", "valid_pdu": "Yes" }, "SRB_Cipher_Algo": "LTE AES", "SRB_Ciphering_Keys_hex": "6B 6E 77 04 68 A5 30 D2 E3 68 86 0E 1D 35 8C D1", "Subpacket_ID": "PDCP PDU with Ciphering (0xC3)", "Subpacket_Size": "60 bytes", "Subpacket_Version": "26", "Subscription_ID": "1", "version": "1" }, "2019 Oct 31 04:32:55.169": { "Num_Subpackets": "1", "PDCPUL_CIPH_DATA": { "bearer_id": "3", "cfg_idx": "4", "count": "0x3A", "els": "n/a", "log_buffer": "80 3A 2F BC", "logged_bytes": "4", "mode": "AM", "pdu_size": "62", "sn": "58", "sn_length": "12", "sub_fn": "0", "sys_fn": "248", "valid_pdu": "Yes" }, "Subpacket_ID": "PDCP PDU with Ciphering (0xC3)", "Subpacket_Size": "60 bytes", "Subpacket_Version": "24", "Subscription_ID": "1", "version": "1" }, "2019 Oct 31 04:32:56.168": { "Num_Subpackets": "1", "PDCPUL_CIPH_DATA": { "bearer_id": "3", "cfg_idx": "4", "count": "0x3B", "els": "n/a", "log_buffer": "80 3B 86 3B", "logged_bytes": "4", "mode": "AM", "pdu_size": "62", "sn": "59", "sn_length": "12", "sub_fn": "0", "sys_fn": "348", "valid_pdu": "Yes" }, "Subpacket_ID": "PDCP PDU with Ciphering (0xC3)", "Subpacket_Size": "60 bytes", "Subpacket_Version": "24", "Subscription_ID": "1", "version": "1" } } }, { "LOG_FILE_NAME": "C:\\Final\\Abi_10-31.11-39.dng", "PARX_VERSION": "PARX 06.30.80 patch 69", "RAYN_VERSION": "RAYN_9.83", "Something Proprietary and Confidential": { "2019 Oct 31 04:32:55.169": { "DRB_Cipher_Algo": "LTE AES", "DRB_Ciphering_Keys_hex": "6B 25 EE 8D 1C 48 B2 3A 07 9A 9D 22 AA 77 33 76", "Num_PDUs": "1", "Num_Subpackets": "1", "PDCPUL_CIPH_DATA": { "bearer_id": "3", "cfg_idx": "4", "checksum": "n/a", "compressed_pdu": "No", "count": "0xF9", "e": "n/a", "els": "n/a", "log_buffer": "80 F9 45 00", "logged_bytes": "4", "mode": "AM", "option": "n/a", "packet_act": "n/a", "pdu_size": "62", "pdu_type": "DEFAULT", "sn": "249", "sn_length": "12", "sub_fn": "8", "sys_fn": "135", "valid_pdu": "Yes" }, "SRB_Cipher_Algo": "LTE AES", "SRB_Ciphering_Keys_hex": "BC 61 5B 1C 05 1F 92 C6 83 F2 68 E6 00 A3 D7 DC", "Subpacket_ID": "PDCP PDU with Ciphering (0xC3)", "Subpacket_Size": "60 bytes", "Subpacket_Version": "26", "Subscription_ID": "1", "version": "1" }, "2019 Oct 31 04:36:04.543": {}, "2019 Oct 31 04:36:04.568": { "Num_Subpackets": "1", "PDCPUL_CIPH_DATA": { "bearer_id": "3", "cfg_idx": "4", "count": "0xF8", "els": "n/a", "log_buffer": "80 F8 23 41", "logged_bytes": "4", "mode": "AM", "pdu_size": "62", "sn": "248", "sn_length": "12", "sub_fn": "7", "sys_fn": "138", "valid_pdu": "Yes" }, "Subpacket_ID": "PDCP PDU with Ciphering (0xC3)", "Subpacket_Size": "60 bytes", "Subpacket_Version": "24", "Subscription_ID": "1", "version": "1" } } } ] } ] </code></pre>
python|text-parsing
1
1,905,083
62,914,945
Hashing a value in response data from a REST API endpoint to frontend
<p>We are using video call/chat services from a third-party company and we create tokens and channel names to use their chat services in our platform. After our FE requested from our BE for credentials (token and channel name) endpoint responses back with token and channel name information. The third-party system does not create the tokens for specific channel name so it is quite possible to obtain one chat token and as long as you know or guess the chat channel name you can join and text freely. In order to prevent this happening, we are to hash/encrypt the channel names sent in our responses to FE so that the actual channel name won't be visible in plain text.</p> <p>What's the best way to do this?</p> <p>BE: Django FE: Vue.js</p> <p>Thanks</p>
<p>You can use python's builtin lib: hmac. An example:</p> <p>CHAT_SERVICE_SECRET_KEY is a key you set yourself in your settings.py</p> <pre><code> hashed_channel_name = hmac.new( settings.CHAT_SERVICE_SECRET_KEY.encode('utf8'), channel_name.encode('utf8'), channel_token.encode('utf8'), digestmod=hashlib.sha256 ).hexdigest() </code></pre> <p>this value can be the response in the frontend.</p>
python|django|security|web|hash
1
1,905,084
48,897,461
How to arrange the statement accordingly in dictionary?
<p>a function which gives statements of commentary, the problem is they contain <code>&lt;br&gt; and &lt;/br&gt;</code> tags, I want to arrange these in a new line</p> <pre><code>from pycricbuzz import Cricbuzz c = Cricbuzz() commentary1 = [] current_game3 = {} matches = c.matches() for match in matches: if(match['mchstate'] != 'nextlive'): col= (c.commentary(match['id'])) for my_str in col['commentary']: current_game3[ "commentary2"] = my_str commentary1.append(current_game3) current_game3 = {} print(commentary1) </code></pre> <p>when I print this I get output as below</p> <pre><code>{'commentary2': 'Preview by Tristan Lavalette&lt;br/&gt;&lt;br/&gt;The Twenty20 tri-series decider between Australia and New Zealand is set to finish with a bang at the tiny Eden Park on Wednesday (February 21), as another bout of belligerent batting is expected in Auckland.&lt;br/&gt;&lt;br/&gt;In a preview of the final, the teams clashed at Eden Park last Friday and produced a run-fest with the rampaging Australia successfully chasing down a record target of 244. The unbeaten Australia head into the final as favourites after a dazzling campaign from their new look side brimming with in-form Big Bash League players and headed by skipper David Warner, whose inventive captaincy has been inspirational.&lt;br/&gt;&lt;br/&gt;Astoundingly, Australia is on the brink of leapfrogging into the No.1 T20 ranking having started the tournament a lowly No.7. A victory would be their sixth straight in the format equalling their best ever streak.&lt;br/&gt;&lt;br/&gt;Australia\'s hard-hitting batting has relished chasing in every match and New Zealand\'s brains trust might deeply consider bowling first if skipper Kane Williamson wins the toss. Packed with firepower, Australia ooze with match-winners and chased down the record target with relative ease, confirming their penchant to chase. At the comically miniature Eden Park ground, Australia\'s powerful batting will be confident no matter the situation of the match.&lt;br/&gt;&lt;br/&gt;Of course, the beleaguered bowlers aren\'t quite as cheery after copping a flogging last start especially to New Zealand dynamo Martin Guptill. Much like their counterparts, the Black Caps boast a high-octane batting order that has been inconsistent throughout the tournament but, ominously, has the artillery to spearhead New Zealand to a triumph.&lt;br/&gt;&lt;br/&gt;Australia\'s attack has been settled throughout the tri-series but selectors might be tempted to tweak it in a bid to ruffle the Black Caps. Legspinner Adam Zampa could be given a call-up on the wearing pitch - the same one used for Friday\'s encounter - which is set to be helpful for spin.&lt;br/&gt;&lt;br/&gt;If Zampa gets the nod, Australia will be faced with a dilemma of culling one of their frontline quicks of Billy Stanlake, Kane Richardson and Andrew Tye, who have each starred at various stages during the tri-series. Australia\'s fresh team has matured quickly but the pressure will be intensified in an away final amid an electrifying atmosphere.&lt;br/&gt;&lt;br/&gt;Even they though endured a rocky tournament yielding just one win, New Zealand squeaked past England to reach the decider but will need to lift their game if they are to cause an upset. The Black Caps have been unable to consistently recapture their best after coming into the tri-series ranked No. 2 in the world.&lt;br/&gt;&lt;br/&gt;New Zealand\'s eclectic bowling has struggled although the spin combination of Mitchell Santner and Ish Sodhi could prove a handful on this deck. For such a composed and experienced team, New Zealand has looked occasionally rattled having agonisingly lost consecutive matches.&lt;br/&gt;&lt;br/&gt;Despite their struggles, New Zealand know one strong performance is enough for them to claim glory in front of their parochial home crowd desperate for some revelry.&lt;br/&gt;&lt;br/&gt;With all to play for, the stage is set for a memorably entertaining finish for this inaugural tri-series tournament.&lt;br/&gt;&lt;br/&gt;When: Wednesday, February 21, 2018; 7PM local, 11.30AM IST&lt;br/&gt;&lt;br/&gt;Where: Eden Park, Auckland&lt;br/&gt;&lt;br/&gt;What to expect: There is a chance of showers intervening. Once again, there should be plenty of runs on offer on the small ground although the pitch is tipped to produce some turn.&lt;br/&gt;&lt;br/&gt;Team News&lt;br/&gt;&lt;br/&gt;New Zealand: Despite agonisingly losing their last couple of games, New Zealand are set to stick with the same line-up.&lt;br/&gt;&lt;br/&gt;Probable XI: Martin Guptill, Colin Munro, Kane Williamson (c), Colin de Grandhomme, Mark Chapman, Ross Taylor, Tim Seifert (wk), Mitchell Santner, Tim Southee, Ish Sodhi, Trent Boult&lt;br/&gt;&lt;br/&gt;Australia: Zampa could be in line to play with the pitch possibly providing some turn. However, a red hot Australia may not want to disturb a winning combination.&lt;br/&gt;&lt;br/&gt;Probable XI: David Warner, D\'Arcy Short, Chris Lynn, Glenn Maxwell, Aaron Finch, Marcus Stoinis, Alex Carey (wk), Ashton Agar, Kane Richardson, Andrew Tye, Billy Stanlake&lt;br/&gt;&lt;br/&gt;Did you know&lt;br/&gt;&lt;br/&gt;- Australia\'s greatest winning streak in T20Is is their six straight victories at the 2010 World T20 before losing the final to England&lt;br/&gt;&lt;br/&gt;- David Warner has won 8 of 9 as T20 captain. The best record overall - minimum 10 matches - is Pakistan\'s Sarfraz Ahmed\'s 14 wins from 17 matches&lt;br/&gt;&lt;br/&gt;- New Zealand have lost their last four T20I matches at Eden Park&lt;br/&gt;&lt;br/&gt;What they said&lt;br/&gt;&lt;br/&gt;"We\'ve had three pretty close T20 games, Australia batting exceptionally well at Eden Park and chasing down a score that was pretty formidable. But you\'ve got to be in the final and give yourself a chance" - Mike Hesson, the New Zealand coach.&lt;br/&gt;&lt;br/&gt;"You\'ve just got to find a way to get one or two wickets in the first six (overs), it\'s as simple as that" - David Warner, the Australia captain, said about bowling at the tiny Eden Park.'}, </code></pre> <p>I want to arrange like this</p> <pre><code>Preview by Tristan Lavalette The Twenty20 tri-series decider between Australia and New Zealand is set to finish with a bang at the tiny Eden Park on Wednesday (February 21), as another bout of belligerent batting is expected in Auckland. In a preview of the final, the teams clashed at Eden Park last Friday and produced a run-fest with the rampaging Australia successfully chasing down a record target of 244. The unbeaten Australia head into the final as favourites after a dazzling campaign from their new look side brimming with in-form Big Bash League players and headed by skipper David Warner, whose inventive captaincy has been inspirational. Astoundingly, Australia is on the brink of leapfrogging into the No.1 T20 ranking having started the tournament a lowly No.7. A victory would be their sixth straight in the format equalling their best ever streak.&lt;br/&gt;&lt;br/&gt;Australia\'s hard-hitting batting has relished chasing in every match and New Zealand\'s brains trust might deeply consider bowling first if skipper Kane Williamson wins the toss. Packed with firepower, Australia ooze with match-winners and chased down the record target with relative ease, confirming their penchant to chase. At the comically miniature Eden Park ground, Australia\'s powerful batting will be confident no matter the situation of the match. Of course, the beleaguered bowlers aren\'t quite as cheery after copping a flogging last start especially to New Zealand dynamo Martin Guptill. Much like their counterparts, the Black Caps boast a high-octane batting order that has been inconsistent throughout the tournament but, ominously, has the artillery to spearhead New Zealand to a triumph. Australia\'s attack has been settled throughout the tri-series but selectors might be tempted to tweak it in a bid to ruffle the Black Caps. Legspinner Adam Zampa could be given a call-up on the wearing pitch - the same one used for Friday\'s encounter - which is set to be helpful for spin. If Zampa gets the nod, Australia will be faced with a dilemma of culling one of their frontline quicks of Billy Stanlake, Kane Richardson and Andrew Tye, who have each starred at various stages during the tri-series. Australia\'s fresh team has matured quickly but the pressure will be intensified in an away final amid an electrifying atmosphere. Even they though endured a rocky tournament yielding just one win, New Zealand squeaked past England to reach the decider but will need to lift their game if they are to cause an upset. The Black Caps have been unable to consistently recapture their best after coming into the tri-series ranked No. 2 in the world. New Zealand\'s eclectic bowling has struggled although the spin combination of Mitchell Santner and Ish Sodhi could prove a handful on this deck. For such a composed and experienced team, New Zealand has looked occasionally rattled having agonizingly lost consecutive matches. Despite their struggles, New Zealand knows one strong performance is enough for them to claim glory in front of their parochial home crowd desperate for some revelry. </code></pre>
<p>Use this:</p> <pre><code>from pycricbuzz import Cricbuzz c = Cricbuzz() commentary1 = [] current_game3 = {} matches = c.matches() for match in matches: if match['mchstate'] != 'nextlive': col= (c.commentary(match['id'])) for my_str in col['commentary']: current_game3["commentary2"] = my_str.replace('&lt;br/&gt;', '\n') commentary1.append(current_game3) current_game3 = {} for comment in commentary1: print(comment['commentary2']) </code></pre> <p>Partial Output:</p> <blockquote> <p>Preview by Tristan Lavalette</p> <p>The Twenty20 tri-series decider between Australia and New Zealand is set to finish with a bang at the tiny Eden Park on Wednesday (February 21), as another bout of belligerent batting is expected in Auckland.</p> <p>In a preview of the final, the teams clashed at Eden Park last Friday and produced a run-fest with the rampaging Australia successfully chasing down a record target of 244. The unbeaten Australia head into the final as favourites after a dazzling campaign from their new look side brimming with in-form Big Bash League players and headed by skipper David Warner, whose inventive captaincy has been inspirational.</p> <p>Astoundingly, Australia is on the brink of leapfrogging into the No.1 T20 ranking having started the tournament a lowly No.7. A victory would be their sixth straight in the format equalling their best ever streak.</p> </blockquote>
python|python-3.x
1
1,905,085
60,252,465
Can Orca be used to operate on a DolphinDB stream table?
<p>I was trying to append data to a stream table through the Orca API (pandas project of DolphinDB).</p> <p>It seems that it doesn't work. Will Orca support operations on streams tables?</p> <p>e.g.</p> <pre><code>orca.load_table(THE_STREAM_TABLE) </code></pre> <p>is not working.</p>
<p>I believe read_share_table is for reading stream table:</p> <pre><code>orca.read_shared_table(THE_STREAM_TABLE) </code></pre>
python|database|pandas|dolphindb
1
1,905,086
50,758,637
UlrLib Downloading image Unsupported Format
<p>wanted to make a tool in order to save images from a specific link, but ecountered a problem.</p> <p>My code is the following:</p> <pre><code>import urllib urllib.urlretrieve(url, &quot;img.jpg&quot;) </code></pre> <p>The thing is that if I use any link from google it works flawlessly.</p> <p>For example:</p> <p><a href="https://i.stack.imgur.com/L29FU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L29FU.png" alt="link" /></a><br /> <sub>(source: <a href="https://web.archive.org/web/20180609184439/https://leader.pubs.asha.org/data/Journals/ASHANL/934378/NIB1_web.png" rel="nofollow noreferrer">asha.org</a>)</sub></p> <ul> <li>works</li> </ul> <p>But if I want to get this specific image:</p> <p><a href="https://i.stack.imgur.com/SUx5N.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SUx5N.jpg" alt="link" /></a><br /> <sub>(source: <a href="https://asset.keepeek-cache.com/medias/domain21/_pdf/media3473/533503-b2d468sq50/large/0.jpg" rel="nofollow noreferrer">keepeek-cache.com</a>)</sub></p> <p>It saves the file as .jpg, but when I want to open it I get unsupported file format. Any ideas on how to fix it or what is the reason behind?</p>
<p>The problem is that the website is blocking downloads based on the browser signature. Rename your <code>img.jpg</code> file to <code>page.html</code> and open in a browser, then you will see something like this:</p> <blockquote> <p>Error 1010 Ray ID: xxxxxxxxx • 2018-06-08 10:39:01 UTC</p> <p>Access denied</p> <p>What happened?</p> <p>The owner of this website (asset.keepeek-cache.com) has banned your access based on your browser's signature (xxxxxxxxxx).</p> <p>Cloudflare Ray ID: xxxxxxxxxx • Your IP: xx.xx.xx.xx • Performance &amp; security by Cloudflare</p> </blockquote> <p>Once you have considered if you want to perhaps contravene the web site owner's wishes, you can change your user agent by doing (for instance) </p> <pre><code>import urllib # Change user agent to look like Firefox urllib.URLopener.version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' # Download file with new user agent urllib.urlretrieve(url, "img.jpg") </code></pre> <p>which fixed the problem for me.</p>
python|python-2.7|urllib
1
1,905,087
55,244,113
Python Get Random Unique N Pairs
<p>Say I have a <code>range(1, n + 1)</code>. I want to get <code>m</code> unique pairs.</p> <p>What I found is, if the number of pairs is close to <code>n(n-1)/2</code> (maxiumum number of pairs), one can't simply generate random pairs everytime because they will start overriding eachother. I'm looking for a somewhat lazy solution, that will be very efficient (in Python's world).</p> <p>My attempt so far:</p> <pre><code>def get_input(n, m): res = str(n) + "\n" + str(m) + "\n" buffet = range(1, n + 1) points = set() while len(points) &lt; m: x, y = random.sample(buffet, 2) points.add((x, y)) if x &gt; y else points.add((y, x)) # meeh for (x, y) in points: res += "%d %d\n" % (x, y); return res </code></pre>
<p>You can use <code>combinations</code> to generate all pairs and use <code>sample</code> to choose randomly. Admittedly only lazy in the "not much to type" sense, and not in the use a generator not a list sense :-)</p> <pre><code>from itertools import combinations from random import sample n = 100 sample(list(combinations(range(1,n),2)),5) </code></pre> <p>If you want to improve performance you can make it lazy by studying this <a href="https://stackoverflow.com/questions/12581437/python-random-sample-with-a-generator-iterable-iterator">Python random sample with a generator / iterable / iterator</a></p> <p>the generator you want to sample from is this: <code>combinations(range(1,n)</code></p>
python|algorithm|math|graph|combinations
3
1,905,088
58,307,799
Transform parts of an array based on grouping
<p>I have a DataFrame, which has a column consisting of groups of <code>1</code> and <code>0</code> values (indexed by business day). An example as an array is given below.</p> <pre><code>x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1.]) </code></pre> <hr> <p>I am attempting to apply the some function to each group of <code>1</code>'s. In this case, cause each group of <code>1</code>'s to decay according to some exponential function. I currently defined the following to achieve this.</p> <pre><code># Find where the array switches from 1 to 0 and vice versa. # prepend was used to maintain the original array size. change = np.abs(np.diff(x, prepend=x[0])) # split the array into groups of `1` and `0` values. split = np.split(x, np.flatnonzero(change)) # transform groups of 1's to np.arange _range = [np.arange(arr.size) if arr[0] == 1 else arr for arr in split] # concatenate the transformed arrays new_x = np.concatenate([np.exp(-arr) if arr[-1] != 0 else arr for arr in _range]) </code></pre> <hr> <p>Giving the following (using <code>.round(3)</code>)</p> <pre><code>array([1. , 0.368, 0.135, 0.05 , 0.018, 0.007, 0.002, 0.001, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , 0.368, 0.135, 0.05 , 0.018, 0.007, 0.002, 0.001, 0. , 0. ,0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , 0.368, 0.135, 0.05 , 0.018]) </code></pre> <p>Is there a better way using either pandas or numpy to split-apply-combine a DataFrame column but "restart" some function for each separate group/window of values? As mentioned above, the data is a time series so each group of either <code>1</code> or <code>0</code> defines the start and finish of a new but similar process.</p>
<p>Here you go in pandas:</p> <pre><code>s = pd.Series(x) _range = s.groupby([s,s.ne(1).cumsum()]).cumcount() # or # _range = s.groupby(s.ne(s.shift()).cumsum()).cumcount() * s new_x = np.exp(-_range) * s </code></pre> <p>And <code>new_x.values</code> is the <code>np.array</code>:</p> <pre><code>array([1.00000000e+00, 3.67879441e-01, 1.35335283e-01, 4.97870684e-02, 1.83156389e-02, 6.73794700e-03, 2.47875218e-03, 9.11881966e-04, 3.35462628e-04, 1.23409804e-04, 4.53999298e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 3.67879441e-01, 1.35335283e-01, 4.97870684e-02, 1.83156389e-02, 6.73794700e-03, 2.47875218e-03, 9.11881966e-04, 3.35462628e-04, 1.23409804e-04, 4.53999298e-05, 1.67017008e-05, 6.14421235e-06, 2.26032941e-06, 8.31528719e-07, 3.05902321e-07, 1.12535175e-07, 4.13993772e-08, 1.52299797e-08, 5.60279644e-09, 2.06115362e-09, 7.58256043e-10, 2.78946809e-10, 1.02618796e-10, 3.77513454e-11, 1.38879439e-11, 5.10908903e-12, 1.87952882e-12, 6.91440011e-13, 2.54366565e-13, 9.35762297e-14, 3.44247711e-14, 1.26641655e-14, 4.65888615e-15, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 3.67879441e-01, 1.35335283e-01, 4.97870684e-02, 1.83156389e-02]) </code></pre>
python|pandas|numpy
2
1,905,089
28,474,492
getting hexdata back from binary format in python
<p>I'm trying to convert hexdata into binary and then back to hex. I'm getting hexdata but as byte object </p> <pre><code> hexdata='91278c4bfb3cbb95ffddc668d995bfe0' b=binascii.a2b_hex(hexdata) print (b) b"\x91'\x8cK\xfb&lt;\xbb\x95\xff\xdd\xc6h\xd9\x95\xbf\xe0" binascii.b2a_hex(b) b'91278c4bfb3cbb95ffddc668d995bfe0' </code></pre> <p>I'm expecting this to come as simple string (as my input i.e., <code>hexstring</code>) that I can use in my code.</p>
<p>Just decode the bytestring as ASCII:</p> <pre><code>binascii.b2a_hex(b).decode('ASCII') </code></pre> <p>as hex digits are limited to the characters 0-9 and a-f.</p>
python|hex|binary-data
1
1,905,090
56,927,560
How do I assign colors to clusters in kmeans?
<p>I keep getting error messages for my kmeans clustering. Note: I am extremely new to everything and coding in general, so I am also looking to improve in any way. I tried personally defining each color, but that did not work either.</p> <pre><code># create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(kclusters) ys = [i + x + (i*x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers to the map markers_colors = [] for lat, lon, poi, cluster in zip(pittsburgh_merged['Latitude'], pittsburgh_merged['Longitude'], pittsburgh_merged['Neighborhood'], pittsburgh_merged['Cluster Labels']): label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( [lat, lon], radius=5, popup=label, color=rainbow[cluster-1], fill=True, fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(map_clusters) map_clusters </code></pre> <p>I expect an output of the map_clusters to be visible. It is supposed to be a map of Pittsburgh with venues organized by colors. Hence the rainbow assignment. However, I keep getting the "TypeError: list indices must be integers or slices, not float" error for the color and fill_color assignments.</p>
<p>The error you are receiving means that the index that you are using to access the list <code>rainbow</code> is not an integer, but a float. In this case, you are trying to access element <code>cluster - 1</code> of the list <code>rainbow</code>. However, the expression <code>cluster - 1</code> seems to be a float, which in turn implies that the variable <code>cluster</code> does not contain an int, but a float. Try to make sure that you are passing in integer, for example by casting the variable to an integer: </p> <p><code>color = rainbow[int(cluster)-1]</code></p> <p>However, this depends on the actual content of the variable and will not work if <code>cluster</code> contains a nan-value like <code>inf</code>. In this case (or all cases, actually), you should take a look at the data you have and make sure that is makes sense. Since you are trying to do k-means and receive float values and even nan-values for your cluster labels, it is possible that something went wrong earlier during the clustering process. Try looking at the actual content of the <code>pittsburgh_merged</code> variable by printing its content. </p>
python|visualization|k-means
1
1,905,091
57,004,031
Why local chrome-urls like: chrome://downloads or chrome://apps doesn't work in headless mode?
<p>I am trying to visit chrome local urls. But it's not working. Does headless chrome support local urls?</p>
<p>I was looking for exactly this just today.</p> <p>Found this:</p> <blockquote> <p>Most chrome internal pages are not implemented in headless mode. This is a limitation of headless Chrome itself, and is not related to ChromeDriver. If you need a particular internal page available in headless Chrome, please file a feature request at <a href="https://crbug.com/" rel="nofollow noreferrer">https://crbug.com/</a>.</p> </blockquote> <p>:(</p> <p><a href="https://groups.google.com/d/msg/chromedriver-users/UbgIiMycjWs/fvk8jadcBQAJ" rel="nofollow noreferrer">source</a></p>
python|selenium|selenium-chromedriver|google-chrome-headless|headless-browser
2
1,905,092
25,596,371
pandas, grouping and aggregating
<p>I have grouped a dataframe:</p> <pre><code>rwp_initial.df.loc[rwp_initial.df.sample_name=='sma_initial'].groupby(by=['sample_name','pH','salt','column'])['concentration'].plot(marker = 'o', rot=30) </code></pre> <p>and get following output:</p> <pre><code>sample_name pH salt column sma_initial 5.7 50 5 Axes(0.125,0.125;0.775x0.775) 6 Axes(0.125,0.125;0.775x0.775) 100 7 Axes(0.125,0.125;0.775x0.775) 8 Axes(0.125,0.125;0.775x0.775) 200 9 Axes(0.125,0.125;0.775x0.775) 10 Axes(0.125,0.125;0.775x0.775) 400 11 Axes(0.125,0.125;0.775x0.775) 12 Axes(0.125,0.125;0.775x0.775) </code></pre> <p><img src="https://i.stack.imgur.com/aYiX1.png" alt="enter image description here"></p> <p>i would like to take the mean within each pH and salt concentration. The columns are just the same sample measured two times. If i use <code>aggregate(np.mean)</code> the average of all datapoints of one column is calculated.</p> <p>This figure maybe highlights the data points i would like to take the average of ( i would like to average along the rows):</p> <pre><code>rwp_initial.df.loc[rwp_initial.df.sample_name=='sma_initial'].groupby(by=['sample_name','pH','salt'])['concentration'].plot(marker = 'o', rot=30) </code></pre> <p><img src="https://i.stack.imgur.com/6i6iK.png" alt=""></p>
<p>OK, i found the answer:</p> <pre><code>grp_initial = rwp_initial.df.loc[rwp_initial.df.sample_name=='sma_initial'].groupby(by=['sample_name','pH','salt']).concentration for grp, val in grp_initial: print(val.groupby(level='row').aggregate(np.mean)) </code></pre> <p>works</p>
python|pandas
0
1,905,093
24,228,630
How to use docker-py (official docker client) to start a bash shell?
<p>I'm trying to use docker-py to run a docker container and drop me into a bash shell in that container. I get as far as running the container (I can see it with <code>docker ps</code>, and I can attach to it just fine with the native docker client), but when I use <code>attach()</code> from the official Python library, it just gives me an empty string in response. How do I attach to my bash shell?</p> <pre><code>&gt;&gt;&gt; import docker &gt;&gt;&gt; c = docker.Client() &gt;&gt;&gt; container = c.create_container(image='d11wtq/python:2.7.7', command='/bin/bash', stdin_open=True, tty=True, name='docker-test') &gt;&gt;&gt; container {u'Id': u'dd87e4ec75496d8369e0e526f343492f7903a0a45042d312b37859a81e575303', u'Warnings': None} &gt;&gt;&gt; c.start(container) &gt;&gt;&gt; c.attach(container) '' </code></pre>
<p>I ended up releasing a library for this: <a href="https://github.com/d11wtq/dockerpty" rel="noreferrer">https://github.com/d11wtq/dockerpty</a></p> <pre><code>import docker import dockerpty client = docker.Client() container = client.create_container( image='busybox:latest', stdin_open=True, tty=True, command='/bin/sh', ) client.start(container) dockerpty.PseudoTerminal(client, container).start() </code></pre>
python|docker|dockerpy
11
1,905,094
29,705,241
xpath for obtaining button within a row
<p>I writing some browser tests with splinter and have a page with clearly-defined rows containing their own titles, buttons, etc. Something like:</p> <p><img src="https://i.stack.imgur.com/sESQp.png" alt="enter image description here"></p> <p>In my particular case, I can obtain a single row as follows:</p> <pre><code>row = lambda title: browser.find_by_xpath("//div[@class='my-row'][contains(., '{0}')]".format(title)) row1 = row('Row 1') row2 = row('Row 2') </code></pre> <p>Then, with this lamba:</p> <pre><code>button = lambda elmt, text: elmt.find_by_xpath("//a[@class='btn'][contains(.,'{0}')]".format(text)) </code></pre> <p>I could hone in on the correct regular button or say something like:</p> <pre><code>assert button(row1, 'Special button') assert not button(row2, 'Special button') </code></pre> <p>But when I call the button lambda, it returns buttons from other rows.</p> <p>From my understanding, finding by xpath via this lamba says, "starting from elmt, look for buttons <em>nested within elmt</em> that contain the given text". Since I am getting stuff from other rows not nested within the current one, though, what am I missing here? </p> <p>What is wrong with my xpath?</p>
<p>XPath expressions that start with <code>//</code> start at the <em>root</em> node of the document, and select nodes regardless of their position in the document. The current context node of such an expression, for example</p> <pre><code>//div </code></pre> <p>has no effect on the result set that is returned. To search the <code>//</code> (descendant-or-self::) axis starting from the context node, you need to use</p> <pre><code>.//div </code></pre> <p>In your case, this means changing</p> <pre><code>button = lambda elmt, text: elmt.find_by_xpath("//a[@class='btn'][contains(.,'{0}')]".format(text)) </code></pre> <p>to</p> <pre><code>button = lambda elmt, text: elmt.find_by_xpath(".//a[@class='btn'][contains(.,'{0}')]".format(text)) </code></pre> <p>(Caveat: That's all concerning the XPath expressions in your code, I cannot comment on the rest.)</p>
python|unit-testing|selenium|xpath|splinter
1
1,905,095
53,688,300
2captcha API + selenium
<p>So i'm using this 2captcha API and testing it on a site like omegle.com. The captcha solving happens but the google captcha box doesnt get ticked and nothing happens. Wondering why that is, I know the 2captcha API runs perfectly... but does it only work for HTTP requests and not selenium? </p> <p>Here is the API link i inserted into the code below: <a href="https://github.com/2captcha/2captcha-api-examples/blob/master/ReCaptcha%20v2%20API%20Examples/Python%20Example/2captcha_python_api_example.py" rel="nofollow noreferrer">https://github.com/2captcha/2captcha-api-examples/blob/master/ReCaptcha%20v2%20API%20Examples/Python%20Example/2captcha_python_api_example.py</a></p> <pre><code>from selenium import webdriver from time import sleep from selenium.common.exceptions import InvalidElementStateException from selenium.common.exceptions import UnexpectedAlertPresentException import time,os import requests fp = webdriver.FirefoxProfile('C:\\Users\\mo\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\b0wnbtro.dev-edition-default') interest = input("Enter the interests seperate by a comma ") msg1 = "1" msg2 ="2" msg3 = "3" msg4 = "4" driver = webdriver.Firefox(fp) #2CAPTCHA API CODE INSERTED HERE FOR A TEST RUN BEFORE BEING INCORPORATED IN A LOOP def main(): try: driver.get('http://www.omegle.com') time.sleep(1) #driver.find_elements_by_xpath("//*[contains(text(), 'I'm not a robot')]") #send.click() driver.find_element_by_xpath('//textarea[@rows="3"]').clear() message = driver.find_element_by_xpath('//textarea[@rows="3"]') time.sleep(3) message.send_keys(msg1) send = driver.find_element_by_xpath('//button[@class="sendbtn"]') send.click() time.sleep(6) message.send_keys(msg2) send = driver.find_element_by_xpath('//button[@class="sendbtn"]') send.click() time.sleep(10) message.send_keys(msg3) send = driver.find_element_by_xpath('//button[@class="sendbtn"]') send.click() time.sleep(25) message.send_keys(msg4) send = driver.find_element_by_xpath('//button[@class="sendbtn"]') send.click() disconnect = driver.find_element_by_xpath('//button[@class="disconnectbtn"]') disconnect.click() disconnect = driver.find_element_by_xpath('//button[@class="disconnectbtn"]') disconnect.click() disconnect = driver.find_element_by_xpath('//button[@class="disconnectbtn"]') disconnect.click() except (InvalidElementStateException, UnexpectedAlertPresentException): main2() def main2(): try: driver.get('http://www.omegle.com') interest1 = driver.find_element_by_xpath('//input[@class="newtopicinput"]') interest1.send_keys(interest) btn = driver.find_element_by_id("textbtn") btn.click() time.sleep(5) driver.find_element_by_xpath('//textarea[@rows="3"]').clear() message = driver.find_element_by_xpath('//textarea[@rows="3"]') time.sleep(1) time.sleep(2) message.send_keys(msg1) send = driver.find_element_by_xpath('//button[@class="sendbtn"]') send.click() time.sleep(6) message.send_keys(msg2) send.click() time.sleep(10) message.send_keys(msg3) send.click() time.sleep(25) message.send_keys(msg4) send.click() send.click() disconnect = driver.find_element_by_xpath('//button[@class="disconnectbtn"]') disconnect.click() except (InvalidElementStateException,UnexpectedAlertPresentException) : disconnect = driver.find_element_by_xpath('//button[@class="disconnectbtn"]') disconnect.click() else: main2() while True: try: main2() except (InvalidElementStateException,UnexpectedAlertPresentException) : main() </code></pre>
<p>I hope you already found a solution, but want to leave a comment for those who can get stuck at the same point.</p> <ol> <li>The API does work for Selenium too. </li> <li>The checkbox will not be ticked, it is controlled by ReCaptcha javascript and you do not touch it.</li> <li>All you need to do is to place the token into <code>g-recaptcha-response</code> field. With Selenium you can do that executing JavaScript</li> </ol> <pre><code>document.querySelector('#g-recaptcha-response').textContent='token_string' </code></pre> <ol start="4"> <li>And in your case as there's nothing that submits the form you have to execute the callback function that is JavaScript too. For example:</li> </ol> <pre><code>___grecaptcha_cfg.clients[0].NY.N.callback('token_string') </code></pre> <p>The path of callback function changes so you need to find a valid one exploring <code>___grecaptcha_cfg</code> object.</p>
python|selenium|2captcha
6
1,905,096
53,448,378
Python pywinauto PuTTy how to wait till the task is over
<p>I use Application from pywinauto.application After logging in i want it to execute commads like :</p> <pre><code> putty.type_keys("ls") putty.type_keys("{ENTER}") </code></pre> <p>To execute next command i need to wait for this one to end. Instead of typing something like :</p> <pre><code> time.sleep(5) </code></pre> <p>I need the program to know when the command is done and ready for next command, not to wait X seconds and hope the running task will be over untill that(for example downloadign a file). I looked up into "wait()", but didn't find anything useful. Any help?</p>
<p>You don’t need pywinauto for executing console commands by ssh! Just do something like this:</p> <pre><code>import subprocess output = subprocess.check_output(“ssh user:password@hostname ls -l /home”) for line in output.split(“\n”): subpath = “ “.join(line.split(“ “)[1:]) print(subpath) </code></pre>
python|putty|pywinauto
0
1,905,097
54,723,820
Conditioning over list element in Data Frame columns
<p>Getting data from API, and for one item there is lots of data so I decided to put them into a List. Now I have Data Frame with a column containing <code>List</code> elements. I want to write a function which is checking some conditions, e.g. who is the best based on ability and stats. Something like <code>whoIsTheBest('fire-punch', 'speed')</code>, where fire-punch is in "move" column, and speed value in "speed" column (it has most speed and can do that "move").</p> <p>I have an issue accessing elements List elements from a column "move". This is how I fetched the data: </p> <pre><code>for x in elements: url = "https://pokeapi.co/api/v2/pokemon/" + str(x["entry_number"]) + "/" get_pokemon = requests.get(url) get_pokemon_json = get_pokemon.json() d = {'id': x["entry_number"], 'name': x["pokemon_species"]["name"], 'special_defense': get_pokemon_json["stats"][1]["base_stat"], 'special_attack': get_pokemon_json["stats"][2]["base_stat"], 'defense': get_pokemon_json["stats"][3]["base_stat"], 'attack': get_pokemon_json["stats"][4]["base_stat"], 'hp': get_pokemon_json["stats"][5]["base_stat"], 'move': list(y['move']['name'] for y in get_pokemon_json['moves']), 'type': list(z['type']['name'] for z in get_pokemon_json['types']) } all_data.append(d) df1 = pd.DataFrame(all_data) move name \ 0 [razor-wind, swords-dance, cut, bind, vine-whi... bulbasaur 1 [swords-dance, cut, bind, vine-whip, headbutt,... ivysaur </code></pre> <p>Tried with the following: </p> <pre><code>if 'fire-punch' in str(df1["move"]): </code></pre> <p>but getting <code>TypeError: 'list' object is not callable</code></p> <p>Is there maybe better approach for creating column values instead of List or is there some way I can access each element? And is there a reason that elements are in <code>[]</code> parentheses?</p>
<p>df1["move"] is a column and has a set of values (can be considered Series as per pandas). So its not a string. Thats throwing the error.</p> <p>Instead you can check it like this:</p> <pre><code>for item in df1.move.values: if 'fire-punch' in item: print("Yes, its found in: ", item) </code></pre> <p>Also, I see each row is a <code>list</code> in this case.</p>
python|pandas
1
1,905,098
38,381,391
Putting values into SQL Server Database Table using PYMSSQL
<p>I am trying to put values into the Table of a Database on SQL Server.</p> <p>My program will subscribe to an MQTT Server and whenever it receives a message, it will put the message into the table of the database.</p> <p>The following is my code:</p> <pre><code>import paho.mqtt.client as mqtt import signal import sys import pymssql from os import getenv from time import gmtime, strftime #Signal Handler def signal_handler(signal, frame): print("\nProgram has been interrupted!") sys.exit(0) #MQTT Subscribe ON_CONNECT def on_connect(client, userdata, flags, rc): if str(rc) == '0': print ("Connected Successfully") else: print ("Connection has a problem") #CLIENT SUBSCRIPTION client.subscribe("topic1") #MQTT Subscribe ON_MESSAGE def on_message(client, userdata, msg): print("[" + msg.topic + "] " + str(msg.payload) ) deviceID = msg.payload time = strftime("%Y%m%d%H%M%S", gmtime()) #Puts the data into the SQL Server DB Table "Topic" cursor.execute(""" IF OBJECT_ID('Topic', 'U') IS NOT NULL DROP TABLE Topic CREATE TABLE Topic( id INT NOT NULL, deviceID INT NOT NULL, dateTime INT NOT NULL, PRIMARY KEY(id) ) """) cursor.execute( "INSERT INTO Topic VALUES (%d)", [(id, deviceID, time)] conn.commit() #Signal Handler signal.signal(signal.SIGINT, signal_handler) #Connect to the SQL Server server = 'mqtt.server.address.com' user = 'sa' password = 'pwd' database = 'topics' #SQL Server Connection Established conn = pymssql.connect(server, user, password, database) cursor = conn.cursor() #Establishing MQTT Subscribe Connection client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("mqtt.server.address.com", 1883, 60) client.loop_forever() </code></pre> <p>And I have been getting the following error:</p> <p><a href="https://i.stack.imgur.com/VO3VC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VO3VC.png" alt="enter image description here"></a></p> <p>Thanks for your help in advance.</p>
<ol> <li><p>You should post your error as text directly in your question.</p></li> <li><p>The error clearly suggests that the <code>query_params</code> argument should be a<br> tuple or a dictionary and not a list.</p> <pre><code>cursor.execute("INSERT INTO Topic VALUES (%d)", [(id, deviceID, time)]) </code></pre> <p>You are trying to insert a list with one tuple into a single column. </p> <p>Also note that you are missing a closing <code>)</code> in this line.</p> <p>Instead you should insert to each column individually, and use a tuple for your arguments:</p> <pre><code>cursor.execute("INSERT INTO Topic VALUES (%d, %d, %d)", (id, deviceID, time)) </code></pre></li> </ol>
python|mqtt|pymssql
2
1,905,099
52,198,872
Paser XML in python
<p>I am getting this xml response, can anybody help me in getting the token from the xml tags?</p> <pre><code>&lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;s:Body&gt;&lt;LoginResponse xmlns="http://videoos.net/2/XProtectCSServerCommand"&gt;&lt;LoginResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;&lt;RegistrationTime&gt;2018-09-06T07:30:38.4571763Z&lt;/RegistrationTime&gt;&lt;TimeToLive&gt;&lt;MicroSeconds&gt;3600000000&lt;/MicroSeconds&gt;&lt;/TimeToLive&gt;&lt;TimeToLiveLimited&gt;false&lt;/TimeToLiveLimited&gt;&lt;Token&gt;TOKEN#xxxxx#&lt;/Token&gt;&lt;/LoginResult&gt;&lt;/LoginResponse&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt; </code></pre> <p>I have it as a string</p> <p>Tried lxml and other libs too like ET but wasn't able to extract the token field. HELPPP</p> <p>Update with a format xml to make you easy to read, FYI.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;s:Body&gt; &lt;LoginResponse xmlns="http://videoos.net/2/XProtectCSServerCommand"&gt; &lt;LoginResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;RegistrationTime&gt;2018-09-06T07:30:38.4571763Z&lt;/RegistrationTime&gt; &lt;TimeToLive&gt; &lt;MicroSeconds&gt;3600000000&lt;/MicroSeconds&gt; &lt;/TimeToLive&gt; &lt;TimeToLiveLimited&gt;false&lt;/TimeToLiveLimited&gt; &lt;Token&gt;TOKEN#xxxxx#&lt;/Token&gt; &lt;/LoginResult&gt; &lt;/LoginResponse&gt; &lt;/s:Body&gt; &lt;/s:Envelope&gt; </code></pre>
<pre><code>text = """ &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;s:Body&gt; &lt;LoginResponse xmlns="http://videoos.net/2/XProtectCSServerCommand"&gt; &lt;LoginResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;RegistrationTime&gt;2018-09-06T07:30:38.4571763Z&lt;/RegistrationTime&gt; &lt;TimeToLive&gt; &lt;MicroSeconds&gt;3600000000&lt;/MicroSeconds&gt; &lt;/TimeToLive&gt; &lt;TimeToLiveLimited&gt;false&lt;/TimeToLiveLimited&gt; &lt;Token&gt;TOKEN#xxxxx#&lt;/Token&gt; &lt;/LoginResult&gt; &lt;/LoginResponse&gt; &lt;/s:Body&gt; &lt;/s:Envelope&gt; """ from bs4 import BeautifulSoup parser = BeautifulSoup(text,'xml') for item in parser.find_all('Token'): print(item.text) </code></pre>
python|xml
1