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,904,800
49,344,811
How to find contours of white and black boxes?
<p>I'm currently working on an image where I have to find the box outer region. But I failed to find the white and black boxes regions. </p> <p>input image: <a href="https://i.imgur.com/gec9eP5.png" rel="nofollow noreferrer">https://i.imgur.com/gec9eP5.png</a></p> <p>output image: <a href="https://i.imgur.com/Giz1DAW.png" rel="nofollow noreferrer">https://i.imgur.com/Giz1DAW.png</a></p> <p>Update edit: if I use HLS instead of HSV I can find 3 more box region but 2 is still missing. here is new output: <a href="https://i.imgur.com/eUqltKI.png" rel="nofollow noreferrer">https://i.imgur.com/eUqltKI.png</a></p> <p>and here is my code:</p> <pre><code>import cv2 import numpy as np img = cv2.imread("1.png") imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_blue = np.array([0,50,0]) upper_blue = np.array([255,255,255]) mask_blue = cv2.inRange(imghsv, lower_blue, upper_blue) _, contours, _ = cv2.findContours(mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) im = np.copy(img) cv2.drawContours(im, contours, -1, (0, 255, 0), 2) cv2.imwrite("contours_blue.png", im) </code></pre>
<p>The mask you're generating with </p> <pre><code>mask_blue = cv2.inRange(imghsv, lower_blue, upper_blue) </code></pre> <p>does not include the bottom row at all, so it's impossible to detect these outlines with </p> <pre><code>_, contours, _ = cv2.findContours(mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) </code></pre> <p>You could try to work with multiple masks / thresholds to account for the different color ranges and merge the detected contours.</p>
python|opencv
0
1,904,801
21,392,991
How To Match Alpha, Numeric and Alphanumeric Values
<p>I've had a look around and seen people use: <strong>^\W\d_</strong> for an alpha match however, if you enter an alpha character first, then follow it with numeric characters, the match doesn't fail.</p> <p>Here's the code I'm trying:</p> <pre><code>alpha = compile('[a-zA-Z]') numeric = compile('[0-9]') alphanumeric = compile('[a-zA-Z0-9]') def alpha_test(): #Checks for alpha values cell = input('Enter an alpha value: ') alpha_valid = alpha.match(cell) if alpha_valid: print('The cell contains only alpha values.\n') else: print('Invalid. The cell contains other characters.\n') def numeric_test(): #Checks for numeric values cell = input('Enter a numeric value: ') numeric_valid = numeric.match(cell) if numeric_valid: print('The cell contains only numeric values.\n') else: print('Invalid. The cell contains other characters.\n') def alphanumeric_test(): #Checks for alphanumeric values cell = input('Enter an alphanumeric value: ') alphanumeric_valid = alphanumeric.match(cell) if alphanumeric_valid: print('The cell contains only alphanumeric values.\n') else: print('Invalid. The cell contains other characters.\n') alpha_test() numeric_test() alphanumeric_test() </code></pre> <p>Maybe I have the wrong angle on what the match function provides? I understand that it can be used to match email formats and ensure they're correct but I thought it could also match character input.</p>
<p>I believe this is the answer to my question - <a href="https://stackoverflow.com/questions/15156198/regex-matches-but-shouldnt?rq=1">Regex matches but shouldn&#39;t</a></p> <p>Should have looked around a little longer, sorry all.</p>
python|regex|match
1
1,904,802
45,929,690
Python, import package module when class inherit abstract class
<pre><code>bank __init__.py Account.py SavingAccount.py main.py </code></pre> <p>The SavingAccount class is inherit from Account(abstract class). When main.py import SavingAccount as below:</p> <p>from bank.SavingAccount import SavingAccount</p> <p>It appear "No module named 'Account'". Could someone know how to solve it?</p> <p>The complete error code in output window as below:</p> <pre><code>Traceback (most recent call last): File "main.py", line 5, in &lt;module&gt; from bank.SavingAccount import SavingAccount File "\bank\SavingAccount.py", line 1, in &lt;module&gt; from Account import Account ModuleNotFoundError: No module named 'Account' </code></pre> <p>Acccount.py</p> <pre><code>from abc import ABCMeta,abstractmethod class Account(metaclass=ABCMeta): _id = 0 _name = '' _balance = 0 __next = 0 def __init__(self,name,initBal = 1000): self._name=name; self._balance = initBal </code></pre> <p>SavingAccount.py</p> <pre><code>from Account import Account class SavingAccount(Account): _interestRate = 0 def __init__(self,name,initBal=0): super(SavingAccount,self).__init__(name,initBal) @classmethod def interestRate(cls): _interestRate = 0 @classmethod def interestRate(cls,rate): cls._interestRate = rate </code></pre>
<p>You should change </p> <pre><code>from Account import Account </code></pre> <p>to </p> <pre><code>from .Account import Account </code></pre> <p>The latter relative import approach is recommended inside a package.</p>
python|class|inheritance|package|abstract
2
1,904,803
45,877,981
tkinter list and scrollbar
<p>Lately I am using tkinter to make a GUI and using a list and a scrollbar. So far I have the following</p> <pre><code>scrollbar-Scrollbar(root) scrollbar.pack(side=RIGTH, fill=Y) mylist=Listbox(root, yscrollcommand=scrollbar.set) mylist.pack(side=LEFT, fill=BOTH) scrollbar.config(command=mylist.yview) </code></pre> <p>that works well, but since the rest of my widgets use grid and not pack to place it, I would like to use grid and replace the packs above. </p> <p>However I haven't found any example with grid. </p> <p>Can someone give me an example??</p> <p>My geometry is some sliders on the left and I want to place this listbox on the right</p>
<p>Here is the sample code I asked. (Hope it serves someone with the same problem as me- I like to be useful :) )</p> <pre><code>scrollbar= Scrollbar(root) scrollbar.grid(row-1,column=3, rowspan=5, sticky=N+S) mylist=Listbox(root, height=17, width=25, yscrollcommand=scrollbar.set) mylist.grid(row=1,column=2,rowspan=5,sticky=E+W) scrollbar.config(command=mylist.yvies) </code></pre> <p>the key was the "sticky" part. </p>
python|tkinter
0
1,904,804
45,944,241
Setting up a virtual environment for python3 using virtualenv on Ubuntu
<p>I want to learn Django so for that, as per the instructions on the <a href="https://docs.djangoproject.com/en/1.11/intro/contributing/" rel="nofollow noreferrer">website</a>, you need to create a virtual environment. I've heard enough horror stories about people corrupting their OS cause they didn't set up the virtual environments properly so it's safe to say I'm sufficiently paranoid.</p> <p>I've created a separate folder/directory VirtualE at located at Academics/CS/VirtualENV and I want to create all my virtual environments there. As per the <a href="https://docs.djangoproject.com/en/1.11/intro/contributing/" rel="nofollow noreferrer">website</a>, the following command should be used -</p> <pre><code>virtualenv --python=`which python3` ~/.virtualenvs/djangodev </code></pre> <p>I'm not sure what exactly I should write in place of the single quotes (the which python3 part). I wrote the following -</p> <pre><code>virtualenv --python=3.5.2 ~/Academics/CS/VirtualENV/DjangoDev </code></pre> <p>It says </p> <pre><code>The path 3.5.2 (from --python=3.5.2) does not exist </code></pre> <p>Where exactly am I going wrong?</p>
<p>In the command line, type "which python3" and it will give you the path to python3. You just need to copy and paste that in the command. For example:</p> <pre><code>virtualenv --python=/path/to/python3/bin/python ~/Academics/CS/VirtualENV/DjangoDev </code></pre>
django|python-3.x|ubuntu|virtualenv
3
1,904,805
54,726,572
python analysing data csv file
<p>I have been trying to simply the way I analyse the data for response times as it would be impossible to do it manual for each participant. However, my code does not seem to work for some reason. So basically want to look at the response times for blocks 1 to 4 with accuracy of 1 and prob_trial of 1, however my code is obviously not allowing me to do it. Do you have any suggestions?</p> <p>My csv file content looks like this:</p> <pre><code>Block,Trial_number,Position,Probability Position,Probability State,Probability trial,Response,Accuracy,RT (ms) 1,1,N,None,None,1,N,1,976.451326394 1,2,X,None,None,1,X,1,935.360659205 1,3,M,0.9,0.81,2,M,1,936.700751889 1,4,Z,0.81,None,2,Z,1,904.942057532 1,5,X,0.9,0.81,2,X,1,952.641545009 1,6,Z,0.81,None,2,Z,1,553.098919248 </code></pre> <p>My code is this:</p> <pre><code>for fnam in d_list: if fnam[-4:] == '.csv': f_in = path1 + '/' + fnam with open(f_in) as csvfile: reader = csv.DictReader(csvfile) for row in reader: block_no.append(int(row['Block'])) trial_no.append(int(row['Trial_number'])) prob_trial.append(int(row['Probability trial'])) accuracy.append(int(row['Accuracy'])) rt.append(float(row['RT (ms)'])) for x in block_no: if x &lt; 5:f for y in accuracy: if y == 1: for z in prob_trial: if z == 1: epoch1_improbable.append(rt) epoch1_improbable_rt = mean(epoch1_improbable) </code></pre>
<p>This is the perfect use case for <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a> with which your desired result would be obtained as</p> <pre><code>import pandas as pd df = pd.read_csv('data.csv') mask = (df['Block'] &lt; 5) &amp; (df['Accuracy'] == 1) &amp; (df['Probability trial'] == 1) print(df[mask]['RT (ms)'].mean()) # 955.9059927994999 </code></pre>
python|median
1
1,904,806
54,823,447
What is Wrong with my Django logging configuration? No logs are seen in the log file
<pre><code>LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'server_logger': { 'level': 'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'maxBytes': 1024*1024*100, 'backupCount': 20, 'filename': os.path.join(BASE_DIR, 'server.log'), 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['server_logger'], 'level': 'DEBUG', 'propagate': True, }, }, } </code></pre> <p>What is wrong with the above configuration and why don't I see my logs? Any thoughts?</p>
<p>Use the empty string <code>''</code> as the key under <code>'loggers'</code> to mark that as the root logger and capture messages from all loggers.</p>
python|django|python-3.x|logging|django-logging
1
1,904,807
73,638,877
How to insert multiple rows of complex data into a dataframe in pandas?
<p>I am quite new to data engineering and want to see if I can plot the daily streams for a number of tracks in order to find a common model that mimics the streaming pattern over years for a song.</p> <p>I got input data in the form of:</p> <pre><code>{ &quot;date&quot;: &quot;2021-06-13&quot;, &quot;streams_total&quot;: 1600432, }, { &quot;date&quot;: &quot;2021-06-14&quot;, &quot;streams_total&quot;: 1600432, } .. </code></pre> <p>It is not daily data since release of the song but rather it depends on how new song it is. Some songs I miss like 1-2 initial years of data.</p> <p>My first task is trying to read this into a DataFrame using pandas. I am unsure how to structure the data also how I can compare multiple songs. One idea I am having is instead of date, use release date and calculate number of days since release. Also, I am thinking of scale each son so that they sum up to 1.0. That way I can compare multiple songs that I got different data from and that have different total number of streams.</p> <p>Given this, I am thinking of using the number of days since release as the column &quot;header&quot; and each row is the song. I could set the days I don't have data for to 0 or NaN</p> <pre><code> +-------+-------+--------+--------+------------+ | Day0 | Day1 | Da2 | Day4 | ISCR Code | +-------+-------+--------+--------+------------+ | 23231 | 23111 | 19232 | 19233 | USRCAB123B | | 0 | 0 | 160131 | 159923 | USHDB1232H | +-------+-------+--------+--------+------------+ </code></pre> <p>Would this be a good idea? I maybe have to clean the data some and removing extreme outliers. How can I do that without messing up the correct columns etc so the data is in sync?</p> <p>Would it be possible to do a geometrical curve fit to this kind of data?</p>
<p>as a first remark, I feel like you should maybe consider doing with in two steps: storing data then processing it. I think storing data is coherent to do in a dataframe.</p> <p>When it comes to processing, I would say as a second remark that indexing data on columns is not a good thing, generally speaking.</p> <p>From where I stand, I would:</p> <ol> <li>Store all data in a one (or several) dataframe(s)</li> <li>Use a script to work on these df for comparisons purposes</li> </ol> <p>When it comes to the storage itself, you can either store everything (song id, release date, date and streams to this date) in one dataframe, but with the growing size of your sampling data, you may end up with massive df hence massive process times.</p> <p>It really depends on what you want to achieve ultimately, but you could for instance have a first dataframe whose columns would be: <code>song_id | song_name | release_date | db_name</code></p> <p>Each song would hence have its own &quot;db&quot; (i.e. dumped dataframe) file (as reported in the last column above) that would contain all existing samples (typically <code>date | streams</code>). And appending new samples to it should be trivial.</p> <p>Finally, you processing script will just have to look into the db to be able to compare things...</p> <p>Once again, it really depends on what you want to achieve, the amount of data, the persistence (or not) of the data, the number of time you want to run this, etc.</p>
python|pandas|machine-learning
1
1,904,808
73,642,624
Selenium's element returns text too slow
<ul> <li>Chrome version: 105.0.5195.102</li> <li>Selenium == 4.4.3</li> <li>Python == 3.9.12</li> </ul> <p>In a certain page, <em><strong>'element.text'</strong></em> takes ~0.x seconds which is unbearable. I suppose <em><strong>'element.text'</strong></em> should return literally just a text from a cached page so couldn't understand it takes so long time. <strong>How can I make it faster?</strong></p> <p>Here are similar QNAs but I need to solve the problem just with Selenium.</p> <ul> <li><a href="https://stackoverflow.com/a/55055124/12472146">Parse text with BeatufulSoup</a></li> <li><a href="https://stackoverflow.com/a/27594210/12472146">Parse text with lxml</a></li> </ul> <p>Another question: <strong>Why every 'element.text' takes different times?</strong></p> <p>For example,</p> <pre><code>import chromedriver_autoinstaller import time from selenium import webdriver chromedriver_autoinstaller.install(cwd=True) options = webdriver.ChromeOptions() options.add_argument(&quot;--headless&quot;) options.add_argument('--no-sandbox') options.add_argument('--ignore-certificate-errors') options.add_argument('--disable-dev-shm-usage') options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-logging&quot;]) wd = webdriver.Chrome(options=options) wd.get(&quot;https://www.bbc.com/&quot;) t0 = time.time() e = wd.find_element(By.CSS_SELECTOR, &quot;#page &gt; section.module.module--header &gt; h2&quot;) print(time.time()-t0) for i in range(10): t0 = time.time() txt = e.text print(time.time()-t0) # This prints different result for every loop. wd.quit() </code></pre>
<p>Selenium can be a bit slow because it does NOT work directly with Chrome. The communication is made via channel which is the Chrome web driver.</p> <p>If you wish to work with a faster and better plugin for Automation try using <code>PlayWright</code>.</p> <p>Another thing you can try is to find your element directly, and not using a long CSS or long Xpath expression. The longer your expression will be -&gt; the longer it will take to find it and its text</p>
python|selenium|selenium-webdriver|selenium-chromedriver
0
1,904,809
21,503,147
Changing from PIL to PILLOW on a mac
<p>I'm having trouble upgrading from PIL to PILLOW on my mac. I tried "brew install libtiff lbjpeg webp littlecms" but homebrew couldn't find the lbjpeg - any tips?</p>
<ol> <li>Reinstall X11 from XQuartz.org </li> <li>Install the latest XCode </li> <li><p>Install the command line tools:</p> <h1>xcode-select --install</h1></li> </ol> <p>Worked for me on mavericks</p>
python|macos|python-imaging-library|pillow
2
1,904,810
24,776,073
How to skip AttributeError in for loop python and continue the loop
<p>I using a 'for loop' to record the IMEI number from multiple files in an array. </p> <p>When, but when no IMEI is detected the for loop stops indicating AttributeError:rint.</p> <pre><code> result = getattr(asarray(obj), method)(*args, **kwds) AttributeError: rint </code></pre> <p>I have used this method:</p> <pre><code>for IMEI in file(): try: detect the IMEI from the files() Append them to the array() exception AttributeError: print 'File name' pass </code></pre> <p>What I would like to do is to skip the error if the IMEI is not detected in the file and then continue with the loop looking for IMEI in other files.</p> <p>IMEI refers to 16Digit AlphaNumeric code. I use it as a 'string'.</p> <p>There are 3200 '.dat' files which I processed for finding such a Alpha Numeric text in each file. Each dat file has some HEX data in it.</p>
<pre><code>try: execute_something() except AttributeError: caught_error() </code></pre> <p>This is how we catch an error in python. Just add the above code snippet in your for loop. Replace the functions i used with your own code.</p> <p>Please ask more if something is still wrong.</p>
python|for-loop|error-handling|try-except
3
1,904,811
41,170,360
Importing Pywinauto causes debug messages to appear twice
<p>I have an old python script that uses logging that I have just been updating by adding pywinauto.</p> <p>Any log lines are written as expected to the log file but once pywinauto is imported I get 2 copies of the line written to the console.</p> <p>Commenting out the import pywinauto line fixes the problems (but is not a real solution as I need to make use of the library)</p> <pre><code>import logging import pywinauto # Set up a script_logger. script_logger = logging.getLogger('test') script_logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) script_logger.addHandler(ch) logFilename = "debug.log" fh = logging.FileHandler(logFilename) fh.setLevel(logging.DEBUG) ch.setFormatter(formatter) script_logger.addHandler(fh) script_logger.debug("Hello world") </code></pre> <p>Typical output (first line expected, second line not)</p> <pre><code>2016-12-15 17:43:09,056 - test - DEBUG - Hello world 2016-12-15 17:43:09,056 DEBUG: Hello world </code></pre> <p>I can see that the second line is created within </p> <blockquote> <p>Lib\site-packages\pywinauto\actionlogger.py </p> </blockquote> <p>Any thoughts?</p> <p>Thanks</p>
<p>Now it should be fixed in master branch. Can you try it with <code>pip install https://github.com/pywinauto/pywinauto/archive/master.zip</code>?</p>
python|logging|pywinauto
0
1,904,812
52,118,454
automatically making matplotlib image flush with other subplot label
<h2>The problem</h2> <p>I am trying to plot an image next to some data. However, I would like the image to expand to be flush with the plot labels. For example, the following code (using <a href="https://matplotlib.org/_images/stinkbug.png" rel="nofollow noreferrer" title="stinkbug image from the matplotlib tutorial">this tutorial image</a>):</p> <pre><code># make the incorrect figure import matplotlib.pyplot as plt import matplotlib.image as mpimg fig = plt.figure(figsize=(8,3)) ax_image = plt.subplot(1,2,1) plt.imshow(mpimg.imread('stinkbug.png')) plt.subplot(1,2,2) plt.plot([0,1],[2,3]) plt.ylabel("y") plt.xlabel("want image flush with bottom of this label") fig.tight_layout() ax_image.axis('off') fig.savefig("incorrect.png") </code></pre> <p>yields this plot, with extra whitespace:</p> <p><a href="https://i.stack.imgur.com/f1rq4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f1rq4.png" alt="incorrect image"></a></p> <h2>The hacky attempt at a solution</h2> <p>I would like a plot that doesn't waste whitespace. The following hacky code (in the vein of <a href="https://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib" title="severalquot;">this SO link</a>) accomplishes this: </p> <pre><code># make the correct figure with manually changing the size import matplotlib.pyplot as plt import matplotlib.image as mpimg fig = plt.figure(figsize=(8,3)) ax_image = fig.add_axes([0.02,0,0.45,1.0]) plt.imshow(mpimg.imread('stinkbug.png')) plt.subplot(1,2,2) plt.plot([0,1],[2,3]) plt.ylabel("y") plt.xlabel("want image flush with bottom of this label") fig.tight_layout() ax_image.axis('off') fig.savefig("correct.png") </code></pre> <p>yielding the following figure:</p> <p><a href="https://i.stack.imgur.com/dMbDK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dMbDK.png" alt="correct image"></a></p> <h2>The question</h2> <p>Is there any way to plot an image flush with other subplots, without having to resort to manual adjustment of figure sizes? </p>
<p>You may get the union of the bounding box of the right axes and its label and set the position of the left axes such that it starts at the vertial position of the union bounding box. The following assumes some automatic aspect on the image, i.e. the image is skewed in one direction. </p> <pre><code>import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.transforms as mtrans fig, (ax_image, ax) = plt.subplots(ncols=2, figsize=(8,3)) ax_image.imshow(mpimg.imread('https://matplotlib.org/_images/stinkbug.png')) ax_image.set_aspect("auto") ax.plot([0,1],[2,3]) ax.set_ylabel("y") xlabel = ax.set_xlabel("want image flush with bottom of this label") fig.tight_layout() ax_image.axis('off') fig.canvas.draw() xlabel_bbox = ax.xaxis.get_tightbbox(fig.canvas.get_renderer()) xlabel_bbox = xlabel_bbox.transformed(fig.transFigure.inverted()) bbox1 = ax.get_position().union((ax.get_position(),xlabel_bbox)) bbox2 = ax_image.get_position() bbox3 = mtrans.Bbox.from_bounds(bbox2.x0, bbox1.y0, bbox2.width, bbox1.height) ax_image.set_position(bbox3) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/DTOdL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DTOdL.png" alt="enter image description here"></a></p> <p>When keeping the aspect constant, you may let the image scale up in width-direction. This has the drawback that it might overlay the right axes or exceed the figure to the left. </p> <pre><code>import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.transforms as mtrans fig, (ax_image, ax) = plt.subplots(ncols=2, figsize=(8,3)) ax_image.imshow(mpimg.imread('https://matplotlib.org/_images/stinkbug.png')) ax.plot([0,1],[2,3]) ax.set_ylabel("y") xlabel = ax.set_xlabel("want image flush with bottom of this label") fig.tight_layout() ax_image.axis('off') fig.canvas.draw() xlabel_bbox = ax.xaxis.get_tightbbox(fig.canvas.get_renderer()) xlabel_bbox = xlabel_bbox.transformed(fig.transFigure.inverted()) bbox1 = ax.get_position().union((ax.get_position(),xlabel_bbox)) bbox2 = ax_image.get_position() aspect=bbox2.height/bbox2.width bbox3 = mtrans.Bbox.from_bounds(bbox2.x0-(bbox1.height/aspect-bbox2.width)/2., bbox1.y0, bbox1.height/aspect, bbox1.height) ax_image.set_position(bbox3) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/Ad2wT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ad2wT.png" alt="enter image description here"></a></p>
python|image|numpy|matplotlib|data-science
1
1,904,813
59,600,944
Django form.is_valid() failing class based views - Form, SingleObject, DetailMixins
<p>I have two apps, here we will call them blog and comments.</p> <p>Comments has a Comment model. Blog has a blog Model. Comments has a CommentForm. Blog has a DetailView.</p> <p>I want my CommentForm to appear on by Blog DetailView, so people can submit comments from the blog detail page. </p> <p>The form renders OK - it makes a POST request, it redirects to get_success_url() but (I've added a couple of prints to views.py - see below) in testing in views.py to see if the form data is received I see the form.is_valid() path is not met, and I don't understand why. </p> <p>I'm essentially trying to follow this, the 'alternative better solution': <a href="https://docs.djangoproject.com/en/2.2/topics/class-based-views/mixins/#using-formmixin-with-detailview" rel="nofollow noreferrer">https://docs.djangoproject.com/en/2.2/topics/class-based-views/mixins/#using-formmixin-with-detailview</a></p> <p><strong>blog/views.py</strong></p> <pre><code>class CommentLooker(SingleObjectMixin, FormView): template_name = 'blogs/blog_detail.html' form_class = CommentForm model = blog def get_object(self): #self.team = get_object_or_404(team, team_id=self.kwargs['team_id']) #queryset_list = blog.objects.filter(team = self.team) team_id_ = self.kwargs.get("team_id") blog_id_ = self.kwargs.get("blog_id") return get_object_or_404(blog, blog_id=blog_id_, team=team_id_) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() return super(CommentLooker, self).post(request, *args, **kwargs) def get_success_url(self): return reverse('blogs:teams') class blogDisplay(View): def get(self,request,*args,**kwargs): view = blogFromteamContentView.as_view() return view(request, *args, **kwargs) def post(self,request,*args,**kwargs): view = CommentLooker.as_view() return view(request,*args,**kwargs) class blogFromteamContentView(LoginRequiredMixin, DetailView): model = blog template_name = 'blogs/blog_detail.html' # override get_object so we can use blog_id when we use this class in urls.py # otherwise DetailViews expect 'pk' which defaults to the primary key of the model. def get_object(self): team_id_ = self.kwargs.get("team_id") blog_id_ = self.kwargs.get("blog_id") return get_object_or_404(blog, blog_id=blog_id_, team=team_id_) def get_context_data(self, **kwargs): context = super(blogFromteamContentView, self).get_context_data(**kwargs) team_id_ = self.kwargs.get("team_id") blog_id_ = self.kwargs.get("blog_id") # get the list of blogs for a given blog id and team id combination. context['queryset'] = get_object_or_404(blog, blog_id=blog_id_, team=team_id_) # get and set things related to ability to associate comments to a blog. initial_data = { "content_type": blog.get_content_type, "object_id": blog.blog_id } comments = blog.comments # uses the @property set in this class. comment_form = CommentForm(self.request.POST or None, initial=initial_data) if comment_form.is_valid(): print(comment_form.cleaned_data) else: print('invalido!') context['comment_form'] = comment_form return context </code></pre> <p><strong>blog/models.py</strong></p> <pre><code>class Blog(models.Model): team= models.ForeignKey(Team, on_delete=CASCADE) blog_id = models.AutoField(primary_key=True) blog_name = models.CharField( max_length=100, verbose_name='Blog Name') </code></pre> <p><strong>blog/urls.py</strong></p> <pre><code>path('teams/&lt;int:team_id&gt;/blogs/&lt;int:blog_id&gt;/', blog.blogDisplay.as_view(), name='detail'), </code></pre> <p><strong>blog_detail.html</strong></p> <pre><code>&lt;div&gt; &lt;p class="lead"&gt; Comments &lt;/p&gt; &lt;form method="POST" action="."&gt; {% csrf_token %} {{ comment_form}} &lt;input type="submit" value="Post Comment" class="btn btn-primary"&gt; &lt;/form&gt; &lt;hr/&gt; {% for comment in blog.comments.all %} &lt;blockquote class="blockquote"&gt; &lt;p&gt;{{ comment.content }}&lt;/p&gt; &lt;footer class="blockquote-footer"&gt; {{ comment.user }} | {{ comment.timestamp|timesince }} ago &lt;/footer&gt; &lt;/blockquote&gt; &lt;hr/&gt; {% endfor %} </code></pre> <p></p> <p><strong>comments/forms.py</strong></p> <p>from django import forms</p> <pre><code>class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False) content = forms.CharField(widget=forms.Textarea) </code></pre> <p>edit:</p> <p>after using print(comment_form.errors): <li>object_id<li>Enter a whole number.</li></li></p> <p>suggesting my initial_data might be the problem. In fact both content_type and object_id in my initial_data were problems. I was asking for blog.blog_id - I.e. using the class, not an instance. So I changed </p> <p><strong>get_context_data:</strong></p> <pre><code>def get_context_data(self, **kwargs): context = super(blogFromteamContentView, self).get_context_data(**kwargs) team_id_ = self.kwargs.get("team_id") blog_id_ = self.kwargs.get("blog_id") # get the list of blogs for a given blog id and team id combination. context['queryset_list_recs'] = get_object_or_404(blog, blog_id=blog_id_, team=team_id_) instance = get_object_or_404(blog, blog_id=blog_id_, team=team_id_) initial_data = { "content_type": instance.get_content_type, "object_id": blog_id_ } </code></pre> <p>and to my <strong>views.py:</strong></p> <pre><code>def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): print('valido') c_type = comment_form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = comment_form.cleaned_data.get('object_id') content_data = comment_form.cleaned_data.get("content") new_comment, created = Comment.objects.get_or_create( user = self.request.user, content_type = content_type, object_id = obj_id, content = content_data ) else: print('postinvalido!') return super(CommentLooker, self).post(request, *args, **kwargs) </code></pre> <p>This (inappropriate print statements aside) now appears to give intended behaviour.</p>
<p>after using print(comment_form.errors):</p> <ul> <li>object_id </li> <li>List item</li> </ul> <p>Enter a whole number.</p> <p>suggesting my initial_data might be the problem. In fact both content_type and object_id in my initial_data were problems. I was asking for blog.blog_id - I.e. using the class, not an instance. So I changed</p> <p><strong>get_context_data:</strong></p> <pre><code>def get_context_data(self, **kwargs): context = super(blogFromteamContentView, self).get_context_data(**kwargs) team_id_ = self.kwargs.get("team_id") blog_id_ = self.kwargs.get("blog_id") # get the list of blogs for a given blog id and team id combination. context['queryset_list_recs'] = get_object_or_404(blog, blog_id=blog_id_, team=team_id_) instance = get_object_or_404(blog, blog_id=blog_id_, team=team_id_) initial_data = { "content_type": instance.get_content_type, "object_id": blog_id_ } </code></pre> <p>and to my <strong>views.py</strong>:</p> <pre><code>def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): print('valido') c_type = comment_form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = comment_form.cleaned_data.get('object_id') content_data = comment_form.cleaned_data.get("content") new_comment, created = Comment.objects.get_or_create( user = self.request.user, content_type = content_type, object_id = obj_id, content = content_data ) else: print('postinvalido!') return super(CommentLooker, self).post(request, *args, **kwargs) </code></pre> <p>This (inappropriate print statements aside) now appears to give intended behaviour. I'm unclear why an instance of CommentForm needs to be created inside the post method - it feels like I'm doing something wrong here.</p>
python|django|django-forms
0
1,904,814
59,881,511
Different behavior between a click Selenium and Mouse click
<p><strong>Current Behavior</strong></p> <p>Using this piece of code</p> <pre><code> from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By browser = webdriver.Firefox() button_value = '/html/body/div/div[2]/div/div/div/div/div[1]/div/form/div/div[3]/div[3]/a[2]' ......... browser.find_element(By.XPATH, pin_box).send_keys(pin) browser.find_element(By.XPATH,, button_value).click() #Click NEXT Button </code></pre> <p>on this page</p> <p><a href="https://i.stack.imgur.com/Cuyz1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cuyz1.png" alt="enter image description here"></a></p> <p>I end up going back to the login <a href="https://www.mymanulife.com.hk" rel="nofollow noreferrer">page</a></p> <p>Whereas if I put a break point on </p> <pre><code>browser.find_element(button_type, button_value).click() </code></pre> <p>and I click with the mouse manually <a href="https://i.stack.imgur.com/XHUek.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XHUek.png" alt="enter image description here"></a></p> <p>I am going to the desired page</p> <p><strong>Expected Behavior</strong></p> <p>To end up on the desired page (i.e not the login page) via Selenium like if I was manually clicking on the next button</p> <p>PS: PIN <a href="http://www.mediafire.com/file/8b4dzun57uam2kg/Welcome_-_Manulife_Customer_Web_Site.7z/file" rel="nofollow noreferrer">html source</a> in case you need </p>
<p>Try to click with <code>webdriver wait</code> or with send <code>ENTER</code> key on <code>next</code> button. As last option you can try to click with Javascript .</p> <pre><code>from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC element = WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, "//a[.='NEXT']"))) element.click() </code></pre> <p><strong>try click using <code>Enter</code> or <code>Return</code></strong></p> <pre><code>element.send_keys(Keys.RETURN) </code></pre> <p><strong>OR</strong></p> <pre><code>element.send_keys(Keys.ENTER) </code></pre> <p><strong>OR (try to click with Java script but without wait as it can be fail on wait)</strong></p> <pre><code>element=browser.find_element(By.XPATH, "//a[.='NEXT']") browser.execute_script("arguments[0].click();", element) </code></pre>
python|python-3.x|selenium|selenium-firefoxdriver
3
1,904,815
68,876,501
Storing items in a module-level list
<p>How can I save the items in lists because when using <code>Sign_in</code> function, it prints &quot;invalid&quot; not &quot;success&quot;?</p> <pre><code>import lists_module def Sign_in(): email = input(&quot;Enter Your Email&quot;).strip() password = input(&quot;Enter your password&quot;).strip() if email in lists_module.emails and int(password) in lists_module.passwords: print(&quot;success&quot;) else : print(&quot;invalid&quot;) def Sign_up(): first_name = input(&quot;Enter Your First Name&quot;).strip().capitalize() last_name = input(&quot;Enter Your Last Name&quot;).strip().capitalize() new_email = input(&quot;Enter Your Email&quot;).strip().capitalize() new_password = input(&quot;Enetr New Password&quot;).strip().capitalize() lists_module.Fname.append(first_name) lists_module.Lname.append(last_name) lists_module.emails.append(new_email) lists_module.passwords.append(new_password) print(&quot;Sign-In Page&quot;) Sign_in() </code></pre> <p>Note: <code>Fname</code> and <code>Lname</code> and <code>email</code> are empty lists in another module.</p>
<p>The appended values are just temporary. Use file I/O for permanent changes. I.e.:</p> <pre><code>def Sign_in(): email = input(&quot;Enter Your Email&quot;).strip() password = input(&quot;Enter your password&quot;).strip() emails = open('emails.txt','r').readlines() passwords = open('passwords.txt','r').readlines() if email in emails and password in passwords: print(&quot;success&quot;) else : print(&quot;invalid&quot;) def Sign_up(): first_name = input(&quot;Enter Your First Name&quot;).strip().capitalize() last_name = input(&quot;Enter Your Last Name&quot;).strip().capitalize() new_email = input(&quot;Enter Your Email&quot;).strip() new_password = input(&quot;Enetr New Password&quot;).strip() open('fnames.txt','a+').write(first_name+'\n') open('lnames.txt','a+').write(first_name+'\n') open('emails.txt','a+').write(new_email+'\n') open('passwords.txt','a+').write(new_password+'\n') print(&quot;Sign-In Page&quot;) Sign_in() </code></pre> <p>This will write the values to files on your computer, then read them from those files, that way, when you run the prorgam a second time, the changes are permanent.</p>
python|list
1
1,904,816
67,323,469
Remove observations based on count of values within an ID column
<p>i have a dataframe called <code>df</code> and i want to remove values races that have less than 2 dogs in the race. how can i do this?</p> <p>input</p> <pre><code>race_id dog_id 1 1 1 2 1 3 2 1 2 3 3 1 3 2 3 4 3 5 4 1 4 4 </code></pre> <p>output</p> <pre><code>race_id dog_id 1 1 1 2 1 3 3 1 3 2 3 4 3 5 </code></pre> <p>i've tried</p> <pre><code>df.loc[lambda x:x.race_id.isin(df.groupby('race_id').dog_id.nunique().gt(2).index.tolist())] </code></pre> <p>but this didn't work? looking for a simpler solution nonetheless, thanks!</p>
<pre><code>print(df.loc[df.groupby(&quot;race_id&quot;)[&quot;dog_id&quot;].transform(&quot;nunique&quot;).gt(2)]) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> race_id dog_id 0 1 1 1 1 2 2 1 3 5 3 1 6 3 2 7 3 4 8 3 5 </code></pre>
python|pandas
1
1,904,817
36,663,459
Parsing Api Response Django Module
<p>I am using this magic the gathering api in django. Instead of using requests to call the url I can use the built in functions. But the response is confusing me. </p> <p>When I call </p> <pre><code>cards = Card.where(page=50).where(pageSize=500).all() </code></pre> <p>Then print out <code>cards</code></p> <p>I get data that looks like this in my terminal.</p> <pre><code>mtgsdk.card.Card object at 0x10696bcc0&gt;, &lt;mtgsdk.card.Card object at 0x10696bcf8&gt;, &lt;mtgsdk.card.Card object at 0x10696bd30&gt;, &lt;mtgsdk.card.Card object at 0x10696bd68&gt;, &lt;mtgsdk.card.Card object at 0x10696bda0&gt;] </code></pre> <p>I was thinking I maybe need to decode it and it's a dict but I basically throwing darts blindly and have no clue if I am getting any closer. </p> <p>Someone please shed some light here. What format is this response in and how would I handle it? </p> <pre><code>def graphs(request): data = [] cards = Card.where(page=50).where(pageSize=500).all() mtg_data = str(cards) print(mtg_data) data.append(cards) return render(request, 'graphs/graphs.html', {'data': data}) </code></pre> <p>Then I am trying to access the card in the template like this, but I get nothing.</p> <pre><code>&lt;div class="frame" id="basic"&gt; &lt;ul class="clearfix"&gt; {% for cards in data %} &lt;li&gt;&lt;a href="#"&gt;&lt;img src="{{cards.image_url }}" /&gt;&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><a href="https://docs.magicthegathering.io" rel="nofollow">API HERE</a></p> <p><a href="https://github.com/MagicTheGathering/mtg-sdk-python" rel="nofollow">GITHUB</a></p>
<p>You've appended the list of cards to an empty list, so now <code>data</code> is a list consisting of a single item, which is itself a list. Instead, you just want to send the cards list itself to the template.</p> <pre><code>return render(request, 'graphs/graphs.html', {'data': cards}) </code></pre>
python|django
2
1,904,818
36,302,677
Twitter Bot is restarting after Heroku dyno recharges
<p>I have a twitter bot which is reading a text file and tweeting. Now, a free Heroku dyno sleeps after every 18 hours for 6 hours, after which it restarts with the same command. So, the text file is read again and the tweets are repeated.</p> <p>To avoid this, everytime a line was read out of the list of lines from the file, I was removing the line from the list (after tweeting) and putting the remaining list into a new file which is then renamed to the original file. </p> <p>I thought this might work, but when the dyno restarted, it started from the beginning. Am I missing something here? It would be great if someone could help me with this.</p>
<p>When the dyno restarts, it's a new one. The filesystem on Heroku is ephemeral and is not persisted across dynos; so your file is lost.</p> <p>You need to store it somewhere more permanent - either somewhere like S3, or one of the database add-ons. Redis might be suitable for this.</p>
python|heroku
0
1,904,819
36,429,609
MQTT Paho Python reliable reconnect
<p>I'm trying to get my MQTT Paho Python script to stay connected (and reconnect when it gets disconnected). Sadly, I'm not sure how to go about this.</p> <p>That said, the machine is connected through WiFi so in the case the signal falls out or the USB dongle is janked out I don't want the code to bork out on me, so I'm trying to cover all exceptions/errors.</p> <p>Here's the a chunk of the code I'm trying to work with:</p> <pre><code>mqttc = mqtt.Client(machine_id, clean_session=False) mqttc.username_pw_set(machine_id, mqtt_pwd) mqttc.connect(mqtt_host, mqtt_port) mqttc.subscribe(machine_id, qos=1) def on_disconnect(client, userdata, rc): if rc != 0: print "Unexpected MQTT disconnection. Attempting to reconnect." try: mqttc.reconnect() except socket.error: ?????? mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.on_disconnect = on_disconnect mqttc.loop_forever() </code></pre> <p>I wasn't able to get much further because I don't know how I can get it to connect again? Unless it's able to reconnect the first time, i can't seem to get a proper reconnecting loop going.</p> <p>Any advise would be really helpful!</p> <p>Thanks!</p>
<p>Reading the source(<a href="https://github.com/eclipse/paho.mqtt.python/blob/1.1/src/paho/mqtt/client.py#L1227" rel="noreferrer">1</a>), the <code>loop_forver()</code> method, calls <code>loop()</code> method in an infinite blocking loop. It is the <code>loop()</code> method which ensures that pub/sub messages and mqtt keepalive traffic is maintained with broker. <code>loop_forver()</code> also does automatic re-connections, if connection is broken.</p> <p>Also note that <code>loop_forever()</code> blocks until client explicitly calls <code>disconnect()</code>. So it will be useful if you only want to run MQTT client in your program. I prefer <code>loop_start()</code>/<code>loop_stop()</code> methods.</p> <pre><code>mqttc = mqtt.Client(machine_id, clean_session=False) mqttc.username_pw_set(mqtt_user, mqtt_pwd) mqttc.connect(mqtt_host, mqtt_port) mqttc.subscribe(mqtt_topic, qos=1) def on_disconnect(client, userdata, rc): if rc != 0: print(&quot;Unexpected MQTT disconnection. Will auto-reconnect&quot;) mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.on_disconnect = on_disconnect mqttc.loop_forever() </code></pre> <p><sub>Not sure why you used <code>machine_id</code> in <code>username_pw_set()</code> and <code>subscribe()</code> calls. Changed them.</sub></p>
python|mqtt
13
1,904,820
36,678,241
How can I force update the Python locals() dictionary of a different stack frame?
<p>In Python 2 (not sure about 3), the locals dictionary only gets updated when you actually call locals(). So e.g.</p> <pre><code>l=locals() x=2 l['x'] </code></pre> <p>fails because <code>l</code> doesn't have the key "x" in it, but</p> <pre><code>l=locals() x=2 locals() l['x'] </code></pre> <p>returns 2. </p> <p>I'm looking for a way to force an update of the locals dictionary, but the trick is that I'm in a different stack frame. So e.g. I'm looking to do</p> <pre><code>l=locals() x=2 force_update() l['x'] </code></pre> <p>and I need to write the <code>force_update()</code> function. I know that from said function I can get the parent frame via <code>inspect.currentframe().f_back</code>, and even the parent (non-updated) locals via <code>inspect.currentframe().f_back.f_locals</code>, but how can I force an update? </p> <p>If this seems convoluted, my main goal is to write a function which is shorthand for <code>"{some} string".format(**dict(globals(),**locals()))</code> so I don't have to type that out each time, and can instead do <code>fmt("{some} string")</code>. Doing so I run into the issue above. </p> <p><em>Edit</em>: With Martjin answer below, below is essentially the solution I was looking for. One could play around with exactly how they get the stack frame of the callee, here I do it via <code>partial</code>. </p> <pre><code>from functools import partial from inspect import currentframe fmt = partial(lambda s,f: s.format(**dict(globals(),**f.f_locals)),f=currentframe()) x=2 print fmt("{x}") #prints "2" </code></pre>
<p>Simply <em>accessing <code>f_locals</code> on a frame object</em> triggers the copy, so using <code>inspect.currentframe().f_back.f_locals</code> <em>is enough</em>.</p> <p>See the <a href="https://hg.python.org/cpython/file/v3.5.1/Objects/frameobject.c#l21" rel="nofollow"><code>frame_getlocals()</code> function</a> in the <code>frameobject.c</code> implementation:</p> <pre class="lang-c prettyprint-override"><code>static PyObject * frame_getlocals(PyFrameObject *f, void *closure) { PyFrame_FastToLocals(f); Py_INCREF(f-&gt;f_locals); return f-&gt;f_locals; } </code></pre> <p><code>PyFrame_FastToLocals</code> is the function used to copy the data from the interal array tracking locals values to a dictionary. <code>frame_getlocals</code> is used to implement the <code>frame.f_locals</code> descriptor (a property); see the <a href="https://hg.python.org/cpython/file/v3.5.1/Objects/frameobject.c#l366" rel="nofollow"><code>frame_getsetlist</code> definition</a>.</p> <p>The <code>PyFrame_FastToLocalsWithError</code> function used above is <em>exactly</em> what <code>locals()</code> uses to produce the same dictionary (by <a href="https://hg.python.org/cpython/file/v3.5.1/Python/bltinmodule.c#l1465" rel="nofollow">wrapping</a> the <a href="https://hg.python.org/cpython/file/v3.5.1/Python/ceval.c#l4437" rel="nofollow"><code>PyEval_GetLocals</code> function</a>).</p>
python|python-internals|inspect|stack-frame|locals
2
1,904,821
36,553,860
How to debug Tensorflow Network weights/outputs/cost per input sample?
<p>I have made a tensor flow model. But always get a NAN loss for some reason. I would like to know how I could debug and view each value in each tensor.</p> <p>For eg:-</p> <pre><code> out = tf.add(tf.matmul(outputs[-1], _weights['out']), _biases['out']) </code></pre> <p>During Run time I'd like to View the values in this tensor and see where things go wrong. I have found something similar in this <a href="https://stackoverflow.com/questions/33633370/how-to-print-the-value-of-a-tensor-object-in-tensorflow">post</a></p> <p>Where they do something like this </p> <pre><code>out = tf.add(tf.matmul(outputs[-1], _weights['out']), _biases['out']) out = tf.Print(out, [out], message="This is softmax Output: ") </code></pre> <p>But this gives and out put like this </p> <pre><code>I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [2.148583e-08 5.9002307e-08 -9.90654e-08...] I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [nan nan nan...] I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [nan nan nan...] Iter 64, Minibatch Loss= nan, Training Accuracy= 0.01562 Testing Accuracy: 0.0 I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [nan nan nan...] I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [nan nan nan...] I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [nan nan nan...] I tensorflow/core/kernels/logging_ops.cc:79] This is softmax Output: [nan nan nan...] </code></pre> <p>Which is not really that Useful as I cant view all the values. I'd like to know if there is a step by step debugging option ?</p>
<p>TensorFlow now has a builtin debugger called <em>tfdbg</em>. It exposes the intermediate tensors in the graph, along with the graph structure, which should make it easier for you to debug this type of problems. Compared to print ops, it requires less code change and provides better coverage of the graph.</p> <p>Please take a look at its documentation / tutorial at master HEAD: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/how_tos/debugger/index.md" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/how_tos/debugger/index.md</a></p>
python|machine-learning|tensorflow|deep-learning
1
1,904,822
36,480,358
What's a fast (non-loop) way to apply a dict to a ndarray (meaning use elements as keys and replace with values)
<p>At the moment I'm looping through like </p> <pre><code>new_data = [transform_dict[pt] for pt in line] for line in data] </code></pre> <p>But this is too slow. I've tried looking for a suitable <code>numpy</code> method but haven't found anything myself. Are there any matrix based implementations for this sort of thing?</p>
<p>transform your dictionary in array and use <code>np.take</code>:</p> <pre><code>Na=1000 #array Nd = 10**4 #dict data=randint(0,Nd,(Na,Na)) dic=dict(zip(range(Nd),randint(0,Nd,Nd))) dicarray=np.array(list(dic.values())) </code></pre> <p>That is generally much faster :</p> <pre><code>In [3]: %timeit np.array([[dic[x] for x in line] for line in data]) 1 loops, best of 3: 2.27 s per loop In [4]: %timeit dicarray.take(data) 10 loops, best of 3: 24.4 ms per loop </code></pre>
python|numpy|dictionary
2
1,904,823
13,637,052
What is the difference between Upstart and Supervisord?
<p>Are <a href="http://upstart.ubuntu.com/">Upstart</a> and <a href="http://supervisord.org/">Supervisord</a> interchangeable? Do they work together? I am looking to run a python program as root when my system (debian) boots. After the boot, I would like the process manager to continue running the program if it crashes. Which would be better suited to do this?</p>
<p>Upstart was developed as a replacement for the traditional init daemon. Supervisord is a process manager (with a lot of features), but it still needs to be run by an init daemon in itself. </p> <p>I personally find Upstart is enough for most of my use cases, and from your question I think it will do just fine for you as well.</p> <p>There are four upstart stanzas that should be of particular interest to you: start on, stop on, respawn and exec. You can read more about them at <a href="http://upstart.ubuntu.com/cookbook/" rel="nofollow noreferrer">http://upstart.ubuntu.com/cookbook/</a>.</p> <p>If you still prefer to go for the Supervisord route this seems like a good thread to get you started - <a href="https://serverfault.com/questions/96499/how-to-automatically-start-supervisord-on-linux-ubuntu">https://serverfault.com/questions/96499/how-to-automatically-start-supervisord-on-linux-ubuntu</a></p>
python|debian|upstart|supervisord
36
1,904,824
22,335,171
In Python, why can a lambda expression refer to the variable being defined but not a list?
<p>This is more a curiosity than anything, but I just noticed the following. If I am defining a self-referential lambda, I can do it easily:</p> <pre><code>&gt;&gt;&gt; f = lambda: f &gt;&gt;&gt; f() is f True </code></pre> <p>But if I am defining a self-referential list, I have to do it in more than one statement:</p> <pre><code>&gt;&gt;&gt; a = [a] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'a' is not defined &gt;&gt;&gt; a = [] &gt;&gt;&gt; a.append(a) &gt;&gt;&gt; a[0] is a True &gt;&gt;&gt; a [[...]] </code></pre> <p>I also noticed that this is not limited to lists but seems like any other expression other than a lambda can not reference the variable left of the assignment. For example, if you have a cyclic linked-list with one node, you can't simply go:</p> <pre><code>&gt;&gt;&gt; class Node(object): ... def __init__(self, next_node): ... self.next = next_node ... &gt;&gt;&gt; n = Node(n) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'n' is not defined </code></pre> <p>Instead, you have to do it in two statements:</p> <pre><code>&gt;&gt;&gt; n = Node(None) &gt;&gt;&gt; n.next = n &gt;&gt;&gt; n is n.next True </code></pre> <p>Does anyone know what the philosophy behind this difference is? I understand that a recursive lambda are used much more frequently, and hence supporting self-reference is important for lambdas, but why not allow it for any assignment?</p> <p>EDIT: The answers below clarify this quite nicely. The reason is that variables in lambdas in Python are evaluated each time the lambda is called, not when it's defined. In this sense they are exactly like functions defined using <code>def</code>. I wrote the following bit of code to experiment with how this works, both with lambdas and <code>def</code> functions in case it might help clarify it for anyone.</p> <pre><code>&gt;&gt;&gt; f = lambda: f &gt;&gt;&gt; f() is f True &gt;&gt;&gt; g = f &gt;&gt;&gt; f = "something else" &gt;&gt;&gt; g() 'something else' &gt;&gt;&gt; f = "hello" &gt;&gt;&gt; g() 'hello' &gt;&gt;&gt; f = g &gt;&gt;&gt; g() is f True &gt;&gt;&gt; def f(): ... print(f) ... &gt;&gt;&gt; f() &lt;function f at 0x10d125560&gt; &gt;&gt;&gt; g = f &gt;&gt;&gt; g() &lt;function f at 0x10d125560&gt; &gt;&gt;&gt; f = "test" &gt;&gt;&gt; g() test &gt;&gt;&gt; f = "something else" &gt;&gt;&gt; g() something else </code></pre>
<p>The expression inside a lambda is evaluated when the function is <em>called</em>, not when it is defined.</p> <p>In other words, Python will not evaluate the <code>f</code> inside your lambda until you call it. And, by then, <code>f</code> is already defined in the current scope (it is the lambda itself). Hence, no <code>NameError</code> is raised.</p> <hr> <p>Note that this is not the case for a line like this:</p> <pre><code>a = [a] </code></pre> <p>When Python interprets this type of line (known as an assignment statement), it will evaluate the expression on the right of the <code>=</code> immediately. Moreover, a <code>NameError</code> will be raised for any name used on the right that is undefined in the current scope.</p>
python
27
1,904,825
22,435,001
How to cluster items in a list without specifying the number of clusters
<p>My goal is to cluster the items in the list below based on distances between any two consecutive items. The number of clusters is not specified, only the maximum distance between any two consecutive items that must not be exceeded for them to be in the same cluster.</p> <p>My attempt</p> <pre><code>import itertools max_dist=20 _list=[1,48,52,59,89,94,103,147,151,165] Ideal_result= [[1],[48,52,59],[89,94,103],[147,151,165]] def clust(list_x, max_dist): q=[] for a, b in itertools.combinations(list_x,2): if b-a&lt;=20: q.append(a),(b) else:continue yield q print list(clust(_list,max_dist)) </code></pre> <p>Output:</p> <pre><code>[[48,48,52,89,89,94,147,147,151],[48,48,52,89,89,94,147,147,151],..]` </code></pre> <p>The output is completely wrong, but I just wanted to include my attempt.</p> <p>Any suggestions on how to get the ideal result? Thanks.</p>
<p>This passes your test:</p> <pre><code>def cluster(items, key_func): items = sorted(items) clusters = [[items[0]]] for item in items[1:]: cluster = clusters[-1] last_item = cluster[-1] if key_func(item, last_item): cluster.append(item) else: clusters.append([item]) return clusters </code></pre> <p>Where <code>key_func</code> returns <code>True</code> if the current and previous items should be part of the same cluster:</p> <pre><code>&gt;&gt;&gt; cluster([1,48,52,59,89,94,103,147,151,165], lambda curr, prev: curr-prev &lt; 20) [[1], [48, 52, 59], [89, 94, 103], [147, 151, 165]] </code></pre> <p>Another possibility would be to modify the <a href="http://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">"equivalent code" for <code>itertools.groupby()</code></a> to likewise take more than one argument for the key function.</p>
python|cluster-analysis|classification
2
1,904,826
16,748,885
repeating operation against multiple lists
<p>Let us assume the following lists: </p> <pre><code>totest=[2,4,5,3,6] l1=[6,8,7,9,4] l2=[3,12,21,30] l3=[2,5] </code></pre> <p>And the following function: </p> <pre><code>def evalitem(x): ...detail.... </code></pre> <p>I have to execute the function against the intersection of totest against all the other lists in a sequence unless there is an exception.<br> There is always the following option: </p> <pre><code>test1=set(totest)&amp;set(l1) try: for i in test1: evalitem(i) except: return test2=..... </code></pre> <p>But there should be a faster pythonic functional way to achieve this,with much better performance.<br> Do note that we go to evaluate test2 only if test1 does not raise an exception. </p>
<pre><code>totest = set(totest) for lst in l1, l2, l3: for item in totest.intersection(lst): evalitem(item) </code></pre> <p>If you don't know how to handle an exception (<code>except: return</code> doesn't count), there is no need to use <code>try...except</code> at all. Handle it in the code that <em>calls</em> the function in question.</p>
python
1
1,904,827
16,743,368
Python Catching Popen Output
<p>I'm experiencing some strange behavior with my Python script exiting without any error messages. Based on my debugging it is happening around a popen() call to scp a file to a server.</p> <p>The code was (I was not the original author):</p> <pre><code>logMessage(LEVEL_INFO, "copyto is " + copyto) pid = Popen(["scp", "-i", "/root/.ssh/id_rsa", "/usr/gpsw/gpslog" + self.node_addr, copyto], stdout=PIPE) __s = pid.communicate()[0] logMessage(LEVEL_INFO, "GPS log SCP complete") </code></pre> <p>In an attempt to debug I enhanced it to:</p> <pre><code>logMessage(LEVEL_INFO, "copyto is " + copyto) pid = Popen(["scp", "-i", "/root/.ssh/id_rsa", "/usr/gpsw/gpslog" + self.node_addr, copyto], stdout=PIPE, stderr=PIPE) out, err = pid.communicate() if out: print "[" + self.node_addr + "] stdout of pid: " + str(out) if err: print "[" + self.node_addr + "] stdout of pid: " + str(err) print "[" + self.node_addr + "] returncode of pid: " + str(pid.returncode) logMessage(LEVEL_INFO, "GPS log SCP complete") </code></pre> <p>Here is my console output: (The pattern should be 5dda77, 5dd9fa, 5dda0d repeatedly. This is based on physical events)</p> <pre><code>[5dda77] returncode of pid: 0 [5dd9fa] returncode of pid: 0 [5dda0d] returncode of pid: 0 [5dda77] returncode of pid: 0 [5dd9fa] returncode of pid: 0 [5dda0d] returncode of pid: 0 # (the script exited and I'm back at the prompt) </code></pre> <p>And here is my log output:</p> <pre><code>INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda77 INFO GPS log SCP complete INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dd9fa INFO GPS log SCP complete INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda0d INFO GPS log SCP complete INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda77 INFO GPS log SCP complete INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dd9fa INFO GPS log SCP complete INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda0d INFO GPS log SCP complete INFO copyto is root@192.168.20.1:/usr/scu/datafiles/gpslog5dda77 </code></pre> <p>So based on the log and output data. I believe something is going wrong during the SCP because the Python script crashes before it logs "GPS log SCP complete". What is interesting though is I see on the server end the file was copied entirely. So two questions:</p> <ol> <li>Am I using popen incorrectly?</li> <li>Why am I not seeing any error messages in stderr?</li> </ol> <p>Thanks </p> <p><strong>EDIT:</strong> This script should <em>never</em> exit. There is no "normal exit" of the process. It should run indefinitely servicing requests from the server to retrieve data from GPS nodes that are available. </p> <p>The main loop code is:</p> <pre><code>stop_flags = 0 ... (API for server and GPS nodes to interact with) def main(): ... (System initialization) while stop_flags == 0: # listen for messages xmlrpcserver.handle_request() comm.poll() if stop_flags == STOP_FLAG_RESTART: # suppress Pylint warning for reimport of Popen,PIPE # pylint: disable-msg=W0404 from subprocess import Popen, PIPE # use this instead of call to suppress output pid = Popen(["/etc/init.d/S999snap", "restart"], stdout=PIPE) __s = pid.communicate()[0] if stop_flags == STOP_FLAG_REBOOT: # suppress Pylint warning for reimport of Popen,PIPE # pylint: disable-msg=W0404 from subprocess import Popen, PIPE # use this instead of call to suppress output pid = Popen(["reboot"], stdout=PIPE) __s = pid.communicate()[0] if __name__ == '__main__': main() </code></pre>
<p>You are using <code>Popen</code> just fine.</p> <p>And, although it's impossible to be sure unless you test the same commands yourself in some other way (e.g., just run them interactively via <code>bash</code>), it's most likely that you're not seeing anything in <code>stderr</code> because there is nothing being printed to <code>stderr</code>.</p> <p>It's almost certainly not crashing, unless you've got a segfault, exception traceback, or some other reason to believe otherwise. You said that it finished all of its work successfully, so what makes you think it crashed?</p> <p>As for the last log message not showing up… you have to show us your custom <code>logMessage</code> code if you want a definite answer, but I'm willing to be you never <code>flush</code> or <code>close</code> the log file.</p> <p>Finally, you've tagged your question <code>multithreading</code>, which could easily be relevant. Again, without even a description of how you're doing the threading, much less actual code, we can't do anything but guess, but you could, e.g., be running this code in a <code>daemon=True</code> thread, and then exiting the main thread.</p>
python|multithreading|popen|scp|stderr
-1
1,904,828
16,719,971
packing objects as json with django?
<p>I've run into a snag in my views. Here "filtered_posts" is array of Django objects coming back from the model. I am having a little trouble figuring out how to get as text data that I can later pack into json instead of using serializers.serialize... What results is that the data comes double-escaped (escaped once by serializers.serialize and a second time by json.dumps). I can't figure out how to return the data from the db in the same way that it would come back if I were using the MySQLdb lib directly, in other words, as strings, instead of references to objects. As it stands if I take out the serializers.serialize, I get a list of these django objects, and it doesn't even list them all (abbreviates them with '...(remaining elements truncated)...'. I don't think I should, but should I be using the __unicode__() method for this? (and if so, how should I be evoking it?)</p> <pre><code>JSONtoReturn = json.dumps({ 'lowest_id': user_posts[limit - 1].id, 'user_posts': serializers.serialize("json", list(filtered_posts)), }) </code></pre>
<p>The Django Rest Framework looks pretty neat. I've used Tastypie before, too.</p> <p>I've also done RESTful APIs that don't include a framework. When I do that, I define <code>toJSON</code> methods on my objects, that return dictionaries, and cascade the call to related elements. Then I call <code>json.dumps()</code> on that. It's a lot of work, which is why the frameworks are worth looking at.</p>
django|python-2.7
1
1,904,829
54,632,829
How can I execute two commands in terminal using Python's subprocess module?
<p>How can I use the subprocess module (i.e. <code>call</code>, <code>check_call</code> and <code>Popen</code>) to run more than one command? </p> <p>For instance, lets say I wanted to execute the <code>ls</code> command twice in quick sucession, the following syntax does not work</p> <pre><code>import subprocess subprocess.check_call(['ls', 'ls']) </code></pre> <p>returns:</p> <pre><code>CalledProcessError: Command '['ls', 'ls']' returned non-zero exit status 2. </code></pre>
<p>You can use <code>&amp;&amp;</code> or <code>;</code>:</p> <pre><code>$ ls &amp;&amp; ls file.txt file2.txt file.txt file2.txt $ ls; ls file.txt file2.txt file.txt file2.txt </code></pre> <p>The difference is that in case of <code>&amp;&amp;</code> the second command will be executed only if the first one was successful (try <code>false &amp;&amp; ls</code>) unlike the <code>;</code> in which case the command will be executed independently from the first execution.</p> <p>So, Python code will be:</p> <pre><code>import subprocess subprocess.run(["ls; ls"], shell=True) </code></pre>
python|linux|subprocess|popen
2
1,904,830
71,151,426
PyQt5 Second Window flickers when resize event is passed to it from Main Window
<p>I am trying to figure out how to pass event data such as size of the main window to secondary windows. I was able to get this to work but my problem is the second window flickering every time the data is updated when resizing the main window and I'm struggling with getting it to stop.</p> <p>Here is my current code:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QWidget, QHBoxLayout from PyQt5.QtGui import QFont from PyQt5.QtCore import Qt # widget to which dimensions are passed class Dimensions(QWidget): def __init__(self, width, height, parent=None): super().__init__(parent) horizontal_layout = QHBoxLayout() font = QFont('Sans', 20) view_width = QLabel(self) view_width.setFont(font) view_width.setText(str(width)) view_width.adjustSize() view_width.setAlignment(Qt.AlignCenter) view_height = QLabel(self) view_height.setFont(font) view_height.setText(str(height)) view_height.adjustSize() view_height.setAlignment(Qt.AlignCenter) horizontal_layout.addWidget(view_width) horizontal_layout.addWidget(view_height) self.setLayout(horizontal_layout) class SecondWindow(QMainWindow): def __init__(self, width, height): super().__init__() self.setWindowTitle('Second Window') self.resize(640, 480) # dimensions widget applied to second window dimensions_win = Dimensions(width, height) self.setCentralWidget(dimensions_win) self.setWindowFlags(Qt.WindowStaysOnTopHint) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Main Window') self.setGeometry(0,0,640,480) def resizeEvent(self, event): self.width = event.size().width() self.height = event.size().height() # dimensions of main window passed to second window self.second_window = SecondWindow(self.width, self.height) self.second_window.show() if __name__ == &quot;__main__&quot;: app = QApplication(sys.argv) Main_Window = MainWindow() Main_Window.show() sys.exit(app.exec_()) </code></pre>
<p>You shouldn't create <code>SecondWindow()</code> in <code>resizeEvent</code> because when you resize main window then <code>resizeEvent</code> creates again and again <code>SecondWindow()</code> and Python removes old second window (assigned to <code>self.second_window</code>) - and there is short time when old window is already removed and new window still doesn't exist - and you see it as <code>flickering</code>.</p> <p>You shoud create second window only once - in <code>__init__</code> - and later only replace text in <code>QLabel</code> in <code>Dimensions()</code>. But you use local variables (without <code>self.</code>) <code>dimensions_win</code>, <code>view_width</code>, <code>view_height</code> so it can't be accessed outside <code>Dimensions()</code> and <code>SecondWindow()</code>.</p> <p>So you should use <code>self.</code> in</p> <ul> <li><code>self.dimensions_win</code></li> <li><code>self.view_width</code></li> <li><code>self.view_height</code></li> </ul> <p>and then you can change text in <code>Dimensions()</code> without creating <code>SecondWindow()</code> again.</p> <pre><code># dimensions of main window passed to second window self.second_window.dimensions_win.view_width.setText(str(width)) self.second_window.dimensions_win.view_height.setText(str(height)) </code></pre> <hr /> <p>Full working code</p> <pre><code>import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QWidget, QHBoxLayout from PyQt5.QtGui import QFont from PyQt5.QtCore import Qt # widget to which dimensions are passed class Dimensions(QWidget): def __init__(self, width, height, parent=None): super().__init__(parent) horizontal_layout = QHBoxLayout() font = QFont('Sans', 20) self.view_width = QLabel(self) self.view_width.setFont(font) self.view_width.setText(str(width)) self.view_width.adjustSize() self.view_width.setAlignment(Qt.AlignCenter) self.view_height = QLabel(self) self.view_height.setFont(font) self.view_height.setText(str(height)) self.view_height.adjustSize() self.view_height.setAlignment(Qt.AlignCenter) horizontal_layout.addWidget(self.view_width) horizontal_layout.addWidget(self.view_height) self.setLayout(horizontal_layout) class SecondWindow(QMainWindow): def __init__(self, width, height): super().__init__() self.setWindowTitle('Second Window') self.resize(640, 480) # dimensions widget applied to second window self.dimensions_win = Dimensions(width, height) self.setCentralWidget(self.dimensions_win) self.setWindowFlags(Qt.WindowStaysOnTopHint) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Main Window') self.setGeometry(0, 0, 640, 480) self.second_window = SecondWindow(640, 480) self.second_window.show() def resizeEvent(self, event): width = event.size().width() height = event.size().height() # dimensions of main window passed to second window self.second_window.dimensions_win.view_width.setText(str(width)) self.second_window.dimensions_win.view_height.setText(str(height)) if __name__ == &quot;__main__&quot;: app = QApplication(sys.argv) Main_Window = MainWindow() Main_Window.show() sys.exit(app.exec_()) </code></pre> <hr /> <p><strong>EDIT:</strong></p> <p>You can also check if second window is not closed and reopen it.</p> <pre><code> def resizeEvent(self, event): width = event.size().width() height = event.size().height() # if closed then reopen if not self.second_window.isVisible(): self.second_window.show() # dimensions of main window passed to second window self.second_window.dimensions_win.view_width.setText(str(width)) self.second_window.dimensions_win.view_height.setText(str(height)) </code></pre> <hr /> <p><strong>EDIT:</strong></p> <p>Keep <code>MainWindow</code> size in <code>SecondWindow</code></p> <p><code>SecondWindow</code> in <code>__init__</code> set at start</p> <pre><code> self.main_window_width = width self.main_window_height = height </code></pre> <p><code>MainWindow</code> in <code>resizeEvent</code> change it later</p> <pre><code> self.second_window.main_window_width = width self.second_window.main_window_height = height </code></pre> <pre><code>class SecondWindow(QMainWindow): def __init__(self, width, height): super().__init__() self.setWindowTitle('Second Window') self.resize(640, 480) # keep MainWindow values in SecondWindow self.main_window_width = width self.main_window_height = height # dimensions widget applied to second window self.dimensions_win = Dimensions(width, height) self.setCentralWidget(self.dimensions_win) self.setWindowFlags(Qt.WindowStaysOnTopHint) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Main Window') self.setGeometry(0, 0, 640, 480) self.second_window = SecondWindow(640, 480) self.second_window.show() def resizeEvent(self, event): width = event.size().width() height = event.size().height() # dimensions of main window passed to second window self.second_window.dimensions_win.view_width.setText(str(width)) self.second_window.dimensions_win.view_height.setText(str(height)) # keep MainWindow values in SecondWindow self.second_window.main_window_width = width self.second_window.main_window_height = height </code></pre> <p>Or you can add extra function <code>update_data(width, height)</code> in <code>SecondWindow</code>.</p> <p>And then <code>resizeEvent</code> has to run only <code>self.second_window.update_data(width, height)</code></p> <pre><code>class SecondWindow(QMainWindow): def __init__(self, width, height): super().__init__() self.setWindowTitle('Second Window') self.resize(640, 480) # keep MainWindow values in SecondWindow self.main_window_width = width self.main_window_height = height # dimensions widget applied to second window self.dimensions_win = Dimensions(width, height) self.setCentralWidget(self.dimensions_win) self.setWindowFlags(Qt.WindowStaysOnTopHint) def update_data(self, width, height): self.main_window_width = width self.main_window_height = height self.dimensions_win.view_width.setText(str(width)) self.dimensions_win.view_height.setText(str(height)) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Main Window') self.setGeometry(0, 0, 640, 480) self.second_window = SecondWindow(640, 480) self.second_window.show() def resizeEvent(self, event): width = event.size().width() height = event.size().height() self.second_window.update_data(width, height) </code></pre> <hr /> <p>Other idea is to send <code>MainWidow</code> (<code>self</code>) to <code>SecondWindow</code> and keep it as i.e. <code>self.parent</code> and then <code>SecondWindow</code> will have access to values in <code>MainWidow</code> - ie. <code>self.parent.width()</code></p> <pre><code>class SecondWindow(QMainWindow): def __init__(self, parent, width, height): super().__init__() self.parent = parent self.setWindowTitle('Second Window') self.resize(640, 480) # dimensions widget applied to second window self.dimensions_win = Dimensions(width, height) self.setCentralWidget(self.dimensions_win) self.setWindowFlags(Qt.WindowStaysOnTopHint) def update_data(self): width = self.parent.width() height = self.parent.height() print(width, height) self.dimensions_win.view_width.setText(str(width)) self.dimensions_win.view_height.setText(str(height)) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Main Window') self.setGeometry(0, 0, 640, 480) self.second_window = SecondWindow(self, 640, 480) self.second_window.show() def resizeEvent(self, event): self.second_window.update_data() </code></pre>
python|pyqt5|resize|parameter-passing|popupwindow
0
1,904,831
52,814,880
Neuron freezing in Tensorflow
<p>I need to implement <strong>neurons freezing</strong> in CNN for a deep learning research, I tried to find any function in the Tensorflow docs, but I didn't find anything. How can I freeze specific neuron when I implemented the layers with tf.nn.conv2d?</p>
<p>A neuron in a dense neural network layer simply corresponds to a column in a weight matrix. You could therefore redefine your weight matrix as a concatenation of 2 parts/variables, one trainable and one not. Then you could either:</p> <ol> <li>selectively pass only the trainable part in the <code>var_list</code> argument of the <code>minimize</code> function of your optimizer, or</li> <li>Use <code>tf.stop_gradient</code> on the vector/column corresponding to the neuron you want to freeze.</li> </ol> <p>The same concept could be used for convolutional layers, although in this case the definition of a "neuron" becomes unclear; still, you could freeze any column(s) of a convolutional kernel.</p>
python|tensorflow|deep-learning
0
1,904,832
52,713,952
How to check if a file name contains a correct amount of numbers in python?
<p>I am writing a program which filters files placed in a specific folder and I need to check whether they have this structure: some_name/+++/++/++++.format, where + represents any digit.</p> <p>Here is how my code starts:</p> <pre><code>import glob path = "_path_" File_list = glob.glob(path+"/*") for item in File_list: if item == path + *something*: &lt;-------- This is my problem print (True) </code></pre> <p>I would appreciate any help. I am working with Python 3.6.</p>
<p>How about some regex to match that pattern:</p> <pre><code>import re pat = re.compile(".*\/\d{3}\/\d{2}\/\d{4}\.format") if pat.match(item): # Your code here </code></pre>
python|file-read
3
1,904,833
47,791,879
How do I run a multiarch Docker image for a foreign architecture?
<p>With the new multiarch Docker infrastructure, you can run, say, <code>python:3.6</code> and it will automatically choose the right image you based on the host architecture. Now, how can I override this and run a variant of the image built for another architecture, assuming that I have the appropriate qemu and binfmt support in place?</p>
<p>I'm not sure if this is consistent across all images, but for <a href="https://github.com/docker-library/official-images" rel="nofollow noreferrer">official images</a> all it takes is prefixing an image name with the architecture:</p> <pre><code>docker run s390x/python:3.7-alpine3.8 python --version docker run arm64v8/alpine uname -a </code></pre> <p>You can check the above repo for supported architectures for each release.</p>
python|docker|qemu
1
1,904,834
47,861,392
Python Queues - Put returning None
<p>Been trying to read documentation and looking at online examples but my queue still returning None.</p> <pre><code> from collections import defaultdict from Queue import Queue -- in my init self.tickerPrices = dict() queue = Queue(maxsize=5) queue.put((0.00097073, 67689.70942763)) self.tickerPrices['a'] = queue def appendToTickerDict(self, tickerid, askprice, volume): if(tickerid in self.tickerPrices): tickerQueue = self.tickerPrices[tickerid].put((askprice, volume)) --RETURNS NONE </code></pre> <p>tickerQueue returns None. Before this step, I tested it and saw that if I add something to this queue in the init, it shows up with .get before executing this code</p> <p>Any tips would be most helpful.</p>
<p>you can see python language references <a href="https://docs.python.org/3/reference/simple_stmts.html#expression-statements" rel="nofollow noreferrer">expression-statements</a>.</p>
python|python-2.7
0
1,904,835
37,600,960
anaconda env couldn't import any of the packages
<p><strong>pip list inside conda env:</strong> pip list matplotlib (1.4.0) nose (1.3.7) numpy (1.9.1) pandas (0.15.2) pip (8.1.2) pyparsing (2.0.1) python-dateutil (2.4.1) pytz (2016.4) scikit-learn (0.15.2) scipy (0.14.0) setuptools (21.2.1) six (1.10.0) wheel (0.29.0)</p> <p><strong>which python:</strong></p> <p>/Users/xxx/anaconda/envs/pythonenvname/bin/python</p> <p>(pythonenvname)pc-xx-xx:oo xxx$ <strong>which pip</strong></p> <p>/Users/xxx/anaconda/envs/pythonenvname/bin/pip</p> <p>python Python 3.4.4 |Anaconda custom (x86_64)| (default, Jan 9 2016, 17:30:09) [GCC 4.2.1 (Apple Inc. build 5577)] on darwin Type "help", "copyright", "credits" or "license" for more information.</p> <blockquote> <blockquote> <blockquote> <p>import pandas as pd <strong>error:</strong> <strong>sh: sysctl: command not found</strong></p> </blockquote> </blockquote> </blockquote>
<p>Finally, I figured out the answer. It is all about the PATH variable. It was pointing to os python rather than anaconda python. Thanks all for your time.</p>
python|python-3.x|anaconda|conda
0
1,904,836
37,402,334
Searching for hidden key-value pairs in dictionary
<p>I need to extract very specific key-value pairs from a dictionary. The keys are whole numbers and the values repeat for a certain number of keys, which varies. I must extract the last key-value pair for the repeated value. So, in this case, I need to extract the key-value pairs:</p> <pre><code>42: ['e '] 85: ['dis '] 88: ['d '] 95: ['e '] </code></pre> <p>The number of times a certain value appears is random. A value may appear again later, as is the present case with the value ['e '], and so I need to extract it twice.</p> <p>This is the example I'm using here for the type of dictonary I'm dealing with:</p> <pre><code>notes_dict = { 0: ['e '], 1: ['e '], 2: ['e '], 3: ['e '], #(...) 40: ['e '], 41: ['e '], 42: ['e '], 43: ['dis '], 44: ['dis '], 45: ['dis '], #(...) 83: ['dis '], 84: ['dis '], 85: ['dis '], 86: ['d '], 87: ['d '], 88: ['d '], 89: ['e '], 90: ['e '], 91: ['e '], 92: ['e '], 93: ['e '], 94: ['e '], 95: ['e '] } </code></pre> <p>Idea behind this: this dictionary contais information about which musical note is being played at a given time. I need to make this process automatic in order to try and plot a very simplified sheet music.</p>
<p>This might work for you:</p> <pre><code>from itertools import groupby notes_dict = { 0: ['e '], 1: ['e '], 2: ['e '], 3: ['e '], 40: ['e '], 41: ['e '], 42: ['e '], 43: ['dis '], 44: ['dis '], 45: ['dis '], 83: ['dis '], 84: ['dis '], 85: ['dis '], 86: ['d '], 87: ['d '], 88: ['d '], 89: ['e '], 90: ['e '], 91: ['e '], 92: ['e '], 93: ['e '], 94: ['e '], 95: ['e '] } for k, g in groupby(sorted(notes_dict), key=notes_dict.get): print '{}: {}'.format(list(g)[-1], k) </code></pre>
python|dictionary|iterator|keyvaluepair
2
1,904,837
34,370,574
is recursion the only solution to my algorithm implementation?
<p>this is my task:</p> <p>Create a function find_largest to implement the algorithm below</p> <ol> <li>Get a list of numbers L1, L2, L3....LN as argument</li> <li>Assume L1 is the largest, Largest = L1</li> <li>Take next number Li from the list and do the following</li> <li>If Largest is less than Li</li> <li>Largest = Li</li> <li>If Li is last number from the list then</li> <li>return Largest and come out</li> <li>Else repeat same process starting from step 3</li> </ol> <p>and this is my code:</p> <pre><code>def get_algorithm_result(n): if type(n) == type([]): largest = n[0] for item in n: if largest &lt; item: largest = item elif largest == n[-1]: return largest else: pass return largest </code></pre> <p>Although the code runs i haven't implemented step 8 which says i should repeat the same process starting from step 3. how can i do that</p>
<p>You just need to use a for loop and keep track of the largest value seen as you iterate, updating the mx each time you encounter a larger element.</p> <pre><code>def get_algorithm_result(n): mx = n[0] for item in n[1:]: if item &gt; mx: mx = item return mx </code></pre> <p>Your solution stops if <code>elif largest == n[-1]:</code> evaluates to True so for <code>[1,2,3,4,1]</code> you return 1 as the largest number which is incorrect. You reach <code>L[-1]</code> when the loops ends, checking if a number is <code>== L[-1]</code> does not mean that number is actually the last number in the list.</p> <p>There is no need for recursion but if you wanted to implement it, the logic would be the same, you would have to look at every number:</p> <pre><code>def get_rec(n, mx): if not n: return mx return get_rec(n[1:],n[0]) if n[0] &gt; mx else get_rec(n[1:], mx) </code></pre> <p>You don't take the instructions literally:</p> <pre><code>def get_algorithm_result(n): mx = n[0] # 2. Assume L1(n[0]) is the largest for item in n[1:]: # 3/8 get next number/ Else repeat same process starting from step 3 if item &gt; mx: 4 # If Largest is less than Li mx = item # 5 Largest = Li return mx # 6/7 If Li is last number from the list then return Largest and come out </code></pre>
python|algorithm|python-3.x
1
1,904,838
72,758,787
Django Model Instance as Template for Another Model that is populated by Models
<p>I'm trying to create a workout tracking application where a user can:</p> <ol> <li>Create an instance of an <code>ExerciseTemplate</code> model from a list of available <code>Exercise</code> models. I've created these as models so that the user can create custom <code>Exercises</code> in the future. There is also an <code>ExerciseInstance</code> which is to be used to track and modify the <code>ExerciseTemplate</code> created by the user, or someone else. I'm stripping the models of several unimportant fields for simplicity, but each contains the following:</li> </ol> <pre><code>class Exercise(models.Model): # Basic Variables name = models.CharField(max_length=128) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class ExerciseTemplate(models.Model): # Foreign Models workout = models.ForeignKey( 'Workout', on_delete=models.SET_NULL, null=True, blank=True ) exercise = models.ForeignKey( Exercise, on_delete=models.SET_NULL, null=True, blank=True ) recommended_sets = models.PositiveIntegerField(null=True, blank=True) class ExerciseInstance(models.Model): &quot;&quot;&quot; Foreign Models &quot;&quot;&quot; exercise_template = models.ForeignKey( ExerciseTemplate, on_delete=models.SET_NULL, null=True, blank=True ) workout = models.ForeignKey( 'Workout', on_delete=models.SET_NULL, null=True, blank=True ) &quot;&quot;&quot; Fields &quot;&quot;&quot; weight = models.PositiveIntegerField(null=True, blank=True) reps = models.PositiveIntegerField(null=True, blank=True) </code></pre> <ol start="2"> <li>Create a <code>WorkoutInstance</code> from a <code>WorkoutTemplate</code>. The <code>WorkoutTemplate</code> is made up of <code>ExerciseTemplates</code>. But the <code>WorkoutInstance</code> should be able to take the <code>WorkoutTemplate</code> and populate it with <code>ExerciseInstances</code> based on the <code>ExerciseTemplates</code> in the <code>WorkoutTemplate</code>. Here are the models that I have so far:</li> </ol> <pre><code>class WorkoutTemplate(models.Model): name = models.CharField(max_length=128) description = models.TextField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) #category... exercises = models.ManyToManyField( Exercise, through=ExerciseTemplate ) def __str__(self): return self.name class WorkoutInstance(models.Model): # Foreign Models workout_template = models.ForeignKey( 'WorkoutTemplate', on_delete=models.SET_NULL, null=True, blank=True ) </code></pre> <p>But this is where I get stuck. I'm not sure how to proceed. My intuition is one of the following:</p> <ol> <li>I need to create a more simple architecture to do this. I'll take any suggestions.</li> <li>I need to create a method within the model that solves this issue. If this is the case, I'm not sure what this would actually look like.</li> </ol>
<p>When you create a new WorkoutInstance object which references a given WorkoutTemplate object you get all its related ExerciseTemplate objects. Then you just create a new object (row) for each ExerciseInstance in another model (table)</p> <p>If you link your ExerciseInstance to WorkoutInstance via 'workout' you could do something like:</p> <pre><code>wt = WorkoutTemplate.get(id=1) wi = WorkoutInstance.create(workout_template=wt) for e in wt.exercisetemplate_set.all: ExerciseInstance.create(exercise_template=e, workout=wi) </code></pre> <p>You can implent this in the method that creates the new WorkoutInstance or take a look at <a href="https://docs.djangoproject.com/en/4.0/ref/signals/" rel="nofollow noreferrer">signals</a></p> <p><a href="https://docs.djangoproject.com/en/4.0/topics/db/optimization/#create-in-bulk" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4.0/topics/db/optimization/#create-in-bulk</a></p>
python|django|django-models|foreign-keys
0
1,904,839
16,495,221
Directory file listing sorted in output :(
<p>I have a list of xml files in a directory for example:</p> <pre><code>file1.xml file2.xml file3.xml file4.xml file5.xml file10.xml file11.xml file12.xml file22.xml file23.xml file24.xml file31.xml file32.xml file33.xml </code></pre> <p>When I use os.listdir(path) and print the file names, the output is as follows:</p> <pre><code>file1.xml file10.xml file11.xml file12.xml file2.xml file22.xml file23.xml file24.xml file3.xml file31.xml file32.xml file33.xml file4.xml file5.xml </code></pre> <p>Expected Outptut</p> <pre><code>file1.xml file2.xml file3.xml file4.xml file5.xml file10.xml file11.xml file12.xml file22.xml file23.xml file24.xml file31.xml file32.xml file33.xml </code></pre> <p>Can any1 tell me if there is a solution for this problem. Thanks in advance!!</p>
<p>As per the docs for <a href="http://docs.python.org/2/library/os.html#os.listdir" rel="nofollow">os.listdir</a> (emphasis mine):</p> <p><strong>os.listdir(path)</strong></p> <blockquote> <p>Return a list containing the names of the entries in the directory given by path. <em>The list is in arbitrary order</em>. It does not include the special entries '.' and '..' even if they are present in the directory.</p> </blockquote> <p>Given your example, perhaps the easiest way is to sort the list by extracting the numbers from the name, and sorting by those:</p> <pre><code>import os, re filenames = os.listdir('/path/to/your/files') filenames.sort(key=lambda L: map(int, re.findall('\d+', L))) </code></pre>
sorting|python-2.7|xml-parsing|directory
0
1,904,840
16,090,146
Sympy library solve to an unknown variable
<p>I have derived some equations with some variables. I want to solve to an unknown variable. I am using Sympy. My code is as follows:</p> <pre><code>import sympy as syp import math as m #this is the unknown variable that I want to find C0 = syp.Symbol('C0') #Known variables D0 = 0.874 theta2 = 10.0 fi2 = 80.0 theta1 = (theta2/180.0)*m.pi fi1 = (fi2/180.0)*m.pi #Definitions of 6 different equations all of them in respect to CO. C_t = 5*m.pi*(D0+4*C0) St123 = 1.5*theta1*(D0+2*C0) St45 = fi1*(D0+7*C0) l1 = syp.sqrt((0.5*(D0+4*C0)-0.5*D0*m.cos(theta1))**2 + (0.5*D0*m.sin(theta1))**2) l2 = syp.sqrt((0.5*(D0+6*C0)-0.5*(D0+2*C0)*m.cos(theta1))**2 + (0.5*(D0+2*C0)*m.sin(theta1))**2) l3 = syp.sqrt((0.5*(D0+8*C0)-0.5*(D0+4*C0)*m.cos(theta1))**2 + (0.5*(D0+4*C0)*m.sin(theta1))**2) #Definition of the general relationship between the above functions. Here C0 is unknown and C_b C_b = C_t + 6*C0 + 3*(l1+l2+l3) - 3*St123 - 3*St45 #for C_b = 10.4866, find C0 syp.solve(C_b - 10.4866, C0) </code></pre> <p>As observed, I want to solve the C_b relationship to C0. Until the last line my code works fine. When I ran the whole script it seems that takes ages to calculate the C0. I dont have any warning message but I dont have any solution either. Would anybody suggest an alternative or a possible solution? Thanks a lot in advance.</p>
<p>As I have mentioned in a comment this problem is numerical in nature, so it is better to try to solve it with numpy/scipy. Nonetheless it is an amusing example of how to do numerics in sympy so here is one suggested workflow.</p> <p>First of all, if it was not for the relative complexity of the expressions here, scipy would have been definitely the better option over sympy. But the expression is rather complicated, so we can first simplify it in <code>sympy</code> and only then feed it to <code>scipy</code>:</p> <pre><code>&gt;&gt;&gt; C_b 38.0∗C0 +3.0∗((0.17∗C0+0.076)∗∗2+(2.0∗C0+0.0066)∗∗2)∗∗0.5 +3.0∗((0.35∗C0+0.076)∗∗2+(2.0∗C0+0.0066)∗∗2)∗∗0.5 +3.0∗((2.0∗C0+0.0066)∗∗2+0.0058)∗∗0.5 +9.4 &gt;&gt;&gt; simplify(C_b) 38.0∗C0 +3.0∗(4.0∗C0∗∗2+0.027∗C0+0.0058)∗∗0.5 +3.0∗(4.1∗C0∗∗2+0.053∗C0+0.0058)∗∗0.5 +3.0∗(4.2∗C0∗∗2+0.08∗C0+0.0058)∗∗0.5 +9.4 </code></pre> <p>Now given that you are not interested in symbolics and that the simplification was not that good, it would be useless to continue using sympy instead of scipy, but if you insist you can do it.</p> <pre><code>&gt;&gt;&gt; nsolve(C_b - 10.4866, C0, 1) # for numerical solution 0.00970963412692139 </code></pre> <p>If you try to use <code>solve</code> instead of <code>nsolve</code> you will just waste a lot of resources in searching for a symbolic solution (that may not even exist in elementary terms) when a numeric one is instantaneous. </p>
python|sympy
1
1,904,841
16,256,149
Print lists in a dictionary based on the status of change/depchanges
<p>Following is what I am trying, not sure where I'm messing up. I have the expected output at the bottom. Can anyone provide input on what is wrong here?</p> <ol> <li><p>Create a lists in a dictionary for each master change and its dependent change</p></li> <li><p>Repeat step #1 until the depchange status is not NEW</p></li> </ol> <p>My code:</p> <pre><code>def depchange(change): depchange_status='' if change == "23456": depchange=33456 depchange_status == 'NEW' if change == "33456": depchange="" depchange_status == 'COMPLETED' return (depchange,depchange_status) def main (): master_change="23456" dep={} while True: dep_change,depchange_status=depchange(master_change) master_change = dep_change dep[master_change]=dep_change if depchange_status != 'NEW': break print dep if __name__ == '__main__': main() ''' EXPECTED OUTPUT:- dep = { '23456': ['33456'], '33456': [], } ''' </code></pre>
<p>Uh, in your depchange() function, do you actually mean to <em>compare</em> the depchange_status, or do you mean to change them? You had '==' there.</p> <p>There's that, and in that same function, depchange is switched from a string to an int. I assume you wanted it to stay a string.</p> <pre><code>def depchange(change): depchange_status='' if change == "23456": depchange="33456" depchange_status = 'NEW' if change == "33456": depchange="" depchange_status = 'COMPLETED' return (depchange,depchange_status) def main (): master_change="23456" dep={} while True: dep_change,depchange_status=depchange(master_change) dep[master_change]=[dep_change] master_change = dep_change if depchange_status != 'NEW': break print dep if __name__ == '__main__': main() </code></pre>
python
1
1,904,842
16,172,451
Compiling django project as a desktop application
<p>I have a web application that I would like to have a version of it on the desktop. It would be totally awesome if i can just compile it rather than rewrite it. (I can't give the customer the code unfortunately)</p> <p>I did some research and found some solutions to compile python in general. These solutions are:</p> <ul> <li>cx_freeze </li> <li>py2exe</li> <li>pyinstaller (this one claims it has support for django but still unreleased)</li> <li>dbuilder.py </li> </ul> <p>That desktop application will run mainly on Windows, but if I can find a solution that would make it run on Linux and Mac too it would be great. </p> <p>Did anyone manage to do this properly ? If so, can you please point me to the right direction?</p> <p>Thanks.</p>
<p>Yes, I am doing this on OSX. It's not simple and, as far as I can tell, I may be the first person to successfully do it on OSX, so YMMV.</p> <p>Pyinstaller, as of March, wasn't quite ready for Django support. I've filed a few tickets from when I tried to use it to package my application and I have admittedly not fixed those issues yet.</p> <p>I went with py2app, ultimately, because I had prior experience with it for other applications. I made a sample project with py2app and Django and put it <a href="https://github.com/kevinlondon/django-py2app-demo" rel="nofollow">on Github</a>. You may find it useful. I also linked a few of the pages that I found useful in the process, which I've included below:</p> <p><a href="https://groups.google.com/forum/?fromgroups=#!topic/django-users/-VGqvHew35g" rel="nofollow">https://groups.google.com/forum/?fromgroups=#!topic/django-users/-VGqvHew35g</a></p> <p><a href="http://misunderstandings.wordpress.com/2008/06/26/django-desktop-app/" rel="nofollow">http://misunderstandings.wordpress.com/2008/06/26/django-desktop-app/</a></p> <p><a href="https://bitbucket.org/Lawouach/cherrypy-recipes/src/9c35b4b62ef1/frameworks/django_?at=default" rel="nofollow">https://bitbucket.org/Lawouach/cherrypy-recipes/src/9c35b4b62ef1/frameworks/django_?at=default</a></p> <p>If I had to do it again, I would probably use SQLAlchemy and wxPython or PySide. I'd recommend thinking carefully about what you'd like to achieve using Django as a packaged application because it introduces a lot of complexity.</p>
python|django
2
1,904,843
38,589,668
getting last n items from queue
<p>everything I see is about lists but this is about <code>events = queue.queue()</code> which is a queue with objects that I want to extract, but how would I go about getting the last N elements from that queue?</p>
<p>By definition, you can't.</p> <p>What you can do is use a loop or a comprehension to <code>get</code> the <strong>first</strong> (you can't <code>get</code> from the end of a <code>queue</code>) N elements:</p> <pre><code>N = 2 first_N_elements = [my_queue.get() for _ in range(N)] </code></pre>
python|queue
4
1,904,844
1,718,442
limiting number of optional, positional arguments to a function/method
<p>what is an appropriate solution to limit the number of optional, positional arguments for a function or method? E.g. I'd like to have a function that takes either two or three positional arguments (but not more). I cannot use an optional keyword argument (because the function needs to accept an unlimited number of arbitrarily named keyword arguments). What I've come up with so far is something like this:</p> <pre><code>def foo(x, y, *args, **kwargs): if len(args) == 1: # do something elif len(args) &gt; 1: raise TypeError, "foo expected at most 3 arguments, got %d" % (len(args) + 2) else # do something else </code></pre> <p>Does this reasonable or is there a better way?</p>
<p>One way to find out what is consider "pythonic" is to search for examples in the python source code itself.</p> <pre><code>find '/usr/lib/python2.6' -name '*.py' -exec egrep 'len\(args\)' {} + | wc 156 867 12946 </code></pre> <p>If you peruse the results of the above command (without the wc), you'll find plenty of examples using exactly the technique you propose.</p>
python
2
1,904,845
1,456,617
Return a random word from a word list in python
<p>I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.</p> <pre><code>import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))], </code></pre>
<p>The random module defines choice(), which does what you want:</p> <pre><code>import random words = [line.strip() for line in open('/etc/dictionaries-common/words')] print(random.choice(words)) </code></pre> <p>Note also that this assumes that each word is by itself on a line in the file. If the file is very big, or if you perform this operation frequently, you may find that constantly rereading the file impacts your application's performance negatively.</p>
python
17
1,904,846
63,095,312
Reshape a pandas Series
<p>I have a dataframe that has a column with values like below -</p> <pre><code>[[3. , 2., 1.],[3. , 1., 2.]] </code></pre> <p>I am reading this value and passing it to a udf as a pandas Series. Below is how the values of the series looks like where type of s below is &lt;class 'pandas.core.series.Series'&gt;</p> <pre><code>s.values = [array([array([3. , 2., 1.]), array([3. , 1., 2.])], dtype=object)] </code></pre> <p>The shape of this shows as (1,). I want to it be of the shape 1 X 2 X 3, but using the below 2 way to try to do this gives errors as shown below -</p> <pre><code>#gives error - ValueError: cannot reshape array of size 1 into shape (1,2,3) s.values.reshape(1,2,3) #gives error - ValueError: cannot reshape array of size 2 into shape (1,2,3) s_array = np.array([s.tolist()]) s_array.reshape(1,2,3) </code></pre> <p>***********Added below is the sample code where I need to reshape. It's not working completely, but executing it will give an idea of the problem.</p> <pre><code> import numpy as np import pandas as pd from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import pandas_udf spark = ( SparkSession .builder .config(&quot;spark.sql.execution.arrow.enabled&quot;, &quot;true&quot;) .getOrCreate() ) l = [['s1',[[3. , 2., 1.],[3. , 1., 2.]]], ['s2',[[4. , 2., 1.],[4. , 1., 2.]]]] df = pd.DataFrame(l, columns = ['name','lst']) sparkDF = spark.createDataFrame(df) S_TYPE = ArrayType(ArrayType(DoubleType())) def test(s): s_array = np.array([s.tolist()]) #s_array.shape = (1, 1, 2) #ValueError: cannot reshape array of size 2 into shape (1,2,3) s_array.reshape(1,2,3) return s test_udf = pandas_udf(test, S_TYPE) df1 = sparkDF.withColumn(&quot;output&quot;, test_udf(sparkDF.lst)) </code></pre> <p>I think I might have to flatten the values and then reshape. Any ideas how to achieve that? Thanks.</p>
<p>Working with just the pandas part of your code:</p> <pre><code>In [138]: l = [['s1',[[3. , 2., 1.],[3. , 1., 2.]]], ['s2',[[4. , 2., 1.],[4. , 1., 2.]]]] In [139]: df = pd.DataFrame(l, columns = ['name','lst']) In [140]: df Out[140]: name lst 0 s1 [[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]] 1 s2 [[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]] </code></pre> <p>A Series with 2 elements:</p> <pre><code>In [141]: df['lst'] Out[141]: 0 [[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]] 1 [[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]] Name: lst, dtype: object </code></pre> <p><code>to_numpy</code> makes a 2 element object dtype array; one element per element of the Series:</p> <pre><code>In [142]: df['lst'].to_numpy() Out[142]: array([list([[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]]), list([[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]])], dtype=object) In [143]: _.shape Out[143]: (2,) </code></pre> <p>Or we can make a nested list from the Series:</p> <pre><code>In [144]: df['lst'].to_list() Out[144]: [[[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]], [[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]]] </code></pre> <p>Making an array from that list is easy (especially if the nesting of the sublists is all the same):</p> <pre><code>In [145]: np.array(df['lst'].to_list()) Out[145]: array([[[3., 2., 1.], [3., 1., 2.]], [[4., 2., 1.], [4., 1., 2.]]]) In [146]: _.shape Out[146]: (2, 2, 3) </code></pre> <p>The <code>to_numpy</code> list, being 1d, can also be <code>stack</code>:</p> <pre><code>In [147]: np.stack(df['lst'].to_numpy()) Out[147]: array([[[3., 2., 1.], [3., 1., 2.]], [[4., 2., 1.], [4., 1., 2.]]]) </code></pre> <p><code>np.stack</code> is a <code>concatenate</code> version that joins the lists (or lists made into arrays) on a new axis. By default it is a lot like <code>np.array</code>; here it is better from 'flattening' the nesting.</p> <p>Most of this works if <code>l</code> contained arrays instead of nested lists.</p> <h2>other</h2> <p>To makes something closer to your initial <code>s.values</code>:</p> <pre><code>In [174]: alist = [np.empty(2, object)] In [175]: alist[0][:] = [np.array([3,2,1]),np.array([3,1,2])] In [176]: alist Out[176]: [array([array([3, 2, 1]), array([3, 1, 2])], dtype=object)] </code></pre> <p><code>stack</code> of the list doesn't change much (just makes a (1,2) array):</p> <pre><code>In [177]: np.stack(alist) Out[177]: array([[array([3, 2, 1]), array([3, 1, 2])]], dtype=object) </code></pre> <p>but a <code>stack</code> of that one element in the list:</p> <pre><code>In [178]: np.stack(alist[0]) Out[178]: array([[3, 2, 1], [3, 1, 2]]) </code></pre> <p>Sometimes if the nesting of lists and arrays in complicated, we have to try several things. Pay close attention to the distinction between list and array, and to the <code>len</code> and/or <code>shape</code> at each level.</p> <h2>edit</h2> <p>Let's look at how the initial shape of an object array affects the 'stack' unpacking.</p> <pre><code>In [278]: df Out[278]: name lst 0 s1 [[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]] 1 s2 [[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]] </code></pre> <p>If I select a dataframe column by name I get a Series:</p> <pre><code>In [279]: df['lst'] Out[279]: 0 [[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]] 1 [[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]] Name: lst, dtype: object </code></pre> <p>The <code>numpy</code> rendition is a 1d array:</p> <pre><code>In [280]: df['lst'].to_numpy() Out[280]: array([list([array([3., 2., 1.]), array([3., 1., 2.])]), array([[4., 2., 1.], [4., 1., 2.]])], dtype=object) In [281]: _.shape Out[281]: (2,) </code></pre> <p>If instead I select a column by list, I get a dataframe:</p> <pre><code>In [282]: df[['lst']] Out[282]: lst 0 [[3.0, 2.0, 1.0], [3.0, 1.0, 2.0]] 1 [[4.0, 2.0, 1.0], [4.0, 1.0, 2.0]] </code></pre> <p>This <code>numpy</code> is 2d:</p> <pre><code>In [283]: df[['lst']].to_numpy() Out[283]: array([[list([array([3., 2., 1.]), array([3., 1., 2.])])], [array([[4., 2., 1.], [4., 1., 2.]])]], dtype=object) In [284]: _.shape Out[284]: (2, 1) </code></pre> <p><code>stack</code> of the 1d array unpacks it and creates a 3d array - one dimension from the outer array, and two from the inner ones:</p> <pre><code>In [285]: np.stack(_280) Out[285]: array([[[3., 2., 1.], [3., 1., 2.]], [[4., 2., 1.], [4., 1., 2.]]]) </code></pre> <p>but stack of the 2d doesn't change anything:</p> <pre><code>In [286]: np.stack(_283) Out[286]: array([[list([array([3., 2., 1.]), array([3., 1., 2.])])], [array([[4., 2., 1.], [4., 1., 2.]])]], dtype=object) </code></pre> <p>We have to first make it 1d, either with ravel, reshape, or indexing:</p> <pre><code>In [287]: np.stack(_283.ravel()) Out[287]: array([[[3., 2., 1.], [3., 1., 2.]], [[4., 2., 1.], [4., 1., 2.]]]) </code></pre> <p>I haven't followed your code in enough detail to say exactly what's going on, but hopefully this gives you an idea of what to watch out for. You need a clear idea of the shape and dtype of an array, and same for any nested arrays.</p>
python|pandas|numpy
1
1,904,847
55,140,544
Slack interactive message: POST response is not in json format
<pre><code>@csrf_exempt def slack(request): print("Testing slack") if request.method == 'POST': print('request', str(request.body)) webhook_url = 'xxxxxxxx' text = "Would you recommend it to customers?" request = unquote(unquote(request.body.decode(encoding='ascii'))) print('url', request) slack_data = { "attachments": [ { "fallback": "Would you recommend it to customers?", "title": request, "callback_id": "comic_1234_xyz", "color": "#3AA3E3", "attachment_type": "default", "actions": [ { "name": "recommend", "text": "Recommend", "type": "button", "value": "recommended" } ], } ] } test = slack_data print('slack_data', type(slack_data)) response = requests.post( webhook_url, data=json.dumps(test), headers={'Content-Type': 'application/json'} ) return HttpResponse("New comic book alert!") </code></pre> <p>In this str(request.body) I am getting output like: b'payload=%7B%22type%22%3A%22 interactive message%22%2C%</p> <p>So I encoded it using unquote(unquote(request.body.decode(encoding='ascii'))) and I am able to get the payload in this format:</p> <pre><code>payload={ "here I got all details of POST message" } </code></pre> <p>How do I parse this in Json ?</p>
<p>There's no need to get <code>request.body</code> in the first place. It looks like you are posting standard form data, with a <code>payload</code> field which contains the JSON data. So just get that:</p> <pre><code>data = json.loads(request.POST['payload']) </code></pre>
python|json|django|slack|slack-api
2
1,904,848
28,325,553
Tab Error in Python
<p>The following python code throws this error message, and I can't tell why, my tabs seem to be in line: </p> <pre><code>File "test.py", line 12 pass ^ TabError: inconsistent use of tabs and spaces in indentation </code></pre> <p>My code:</p> <pre><code>class eightPuzzle(StateSpace): StateSpace.n = 0 def __init__(self, action, gval, state, parent = None): StateSpace.__init__(self, action, gval, parent) self.state = state def successors(self) : pass </code></pre>
<p>You cannot mix tabs and spaces, according the <a href="https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces" rel="noreferrer"><strong>PEP8 styleguide</strong></a>:</p> <p><em>Spaces are the preferred indentation method.</em></p> <p><em>Tabs should be used solely to remain consistent with code that is already indented with tabs.</em></p> <p><strong><em>Python 3 disallows mixing the use of tabs and spaces for indentation.</em></strong></p> <p><strong><em>Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.</em></strong></p> <p><em>When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!</em></p>
python|python-3.x|indentation
10
1,904,849
43,989,934
Tensorflow "ValueError: setting an array element with a sequence." in sess.run()
<p>I am currently working on a program to classify 32x32 images of handwritten characters. This is my code so far:</p> <pre><code>import tensorflow as tf import numpy as np from PIL import Image import csv train_list = csv.reader(open("HCR_data/HCR_train_labels.csv"), delimiter=",") test_list = csv.reader(open("HCR_data/HCR_test_labels.csv"), delimiter=",") x = tf.placeholder(tf.float32, [None, 1024]) w = tf.Variable(tf.zeros([1024, 26])) b = tf.Variable(tf.zeros([26])) y = tf.nn.softmax(tf.matmul(x, w) + b) y_ = tf.placeholder(tf.float32, [None, 26]) train_data = [] for location, label in train_list: image = Image.open(location).convert('L') image = np.asarray(image).flatten() image = [0.0 if p==255 else 1.0 for p in image] one_hot = [0.0] * 26 one_hot[ord(label) - 65] = 1.0 train_data.append((image, one_hot)) train_data = np.asarray(train_data) np.random.shuffle(train_data) test_data = [] for location, label in test_list: image = Image.open(location).convert('L') image = np.asarray(image).flatten() image = [0.0 if p==255 else 1.0 for p in image] one_hot = [0.0] * 26 one_hot[ord(label) - 65] = 1.0 test_data.append((image, one_hot)) test_data = np.asarray(test_data) np.random.shuffle(test_data) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() tf.global_variables_initializer().run() for i in range(269): batch_xs = train_data[(i*7):((i+1)*7),0] batch_ys = train_data[(i*7):((i+1)*7),1] #print(len(batch_ys) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: test_data[:,0], y_: test_data[:,1]})) </code></pre> <p>I based it off of the MNIST tutorial on the Tensorflow website, however whenever build the program I get an error:</p> <pre><code>Traceback (most recent call last): File "C:...\HCR.py", line 57, in &lt;module&gt; sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) File "C:...\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 766, in run run_metadata_ptr) File "C:...\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 937, in _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) File "C:...\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\core\numeric.py", line 531, in asarray return array(a, dtype, copy=False, order=order) ValueError: setting an array element with a sequence. </code></pre> <p>Please help, I've tried many way at changing how I input my <code>feed_dict</code> but i cant figure out whats wrong. Batch_xs should be 7x1024 and batch_ys should be 7x26. I know only having batches of 7 wont be that accurate but i want to figure this error out first.</p>
<p>lol, okay I fixed my own problem about 20 seconds later just noticing there was no commas between the individual arrays. So I added <code>list(...)</code> around the array whenever I inputted it to <code>feed_dict</code></p> <p>Side note: my accuracy was pretty bad tho, 53%... lmao</p> <p>Update: got it to 80% just by deleting the <code>tf.nn.softmax(...)</code> for the <code>y</code></p>
python|arrays|python-3.x|numpy|tensorflow
0
1,904,850
32,796,536
Checking if a variable belongs to a class in python
<p>I have a small class which is as follows :</p> <pre><code>class Gender(object): MALE = 'M' FEMALE = 'F' </code></pre> <p>I have a parameter variable which can be only <strong>M</strong> or <strong>F</strong>.To ensure it is only that, I do the following :</p> <pre><code>&gt;&gt;&gt; parameter = 'M' &gt;&gt;&gt; if parameter not in (Gender.MALE, Gender.FEMALE) ... print "Invalid parameter" ... Invalid parameter &gt;&gt;&gt; </code></pre> <p>Now I have a class which contains all the States in USA as follows:</p> <pre><code>class States(object): ALABAMA = 'AL' ALASKA = 'AK' ARIZONA = 'AZ' ARKANSAS = 'AR' CALIFORNIA = 'CA' COLORADO = 'CO' CONNECTICUT = 'CT' DELAWARE = 'DE' DISTRICTOFCOLUMBIA = 'DC' .... .... </code></pre> <p>Like the example above,my parameter now is <strong>AL</strong>.However, since there are 50 states in the USA,I cannot practically use the tuple with 50 variables like I used above.Is there a better way of doing this ? I did read about isinstance but it did not give me the expected results.</p>
<p>You could use the <code>__dict__</code> property which composes a class, for example:</p> <pre><code>In [1]: class Foo(object): ...: bar = "b" ...: zulu = "z" ...: In [2]: "bar" in Foo.__dict__ Out[2]: True </code></pre> <p>Or as you're searching for the values use <code>__dict__.values()</code>:</p> <pre><code>In [3]: "b" in Foo.__dict__.values() Out[3]: True </code></pre> <p>As Peter Wood points out, the <a href="https://docs.python.org/2/library/functions.html#vars" rel="noreferrer"><code>vars()</code></a> built-in can also be used to retrieve the <code>__dict__</code>:</p> <pre><code>In [12]: "b" in vars(Foo).values() Out[12]: True </code></pre> <hr> <p>The <code>__dict__</code> property is used as a <a href="https://docs.python.org/2/reference/datamodel.html" rel="noreferrer">namespace for classes</a> and so will return all methods, <a href="http://www.rafekettler.com/magicmethods.html" rel="noreferrer">magic methods</a> and private properties on the class as well, so for robustness you might want to modify your search slightly to compensate.</p> <p>In your case, you might want to use a <code>classmethod</code>, such as:</p> <pre><code>class States(object): ALABAMA = "AL" FLORIDA = "FL" @classmethod def is_state(cls, to_find): print(vars(cls)) states = [val for key, val in vars(cls).items() if not key.startswith("__") and isinstance(val, str)] return to_find in states States.is_state("AL") # True States.is_state("FL") # True States.is_state("is_state") # False States.is_state("__module__") # False </code></pre> <hr> <p><strong>Update</strong> This clearly answer's the OPs question, but readers may also be interested in the <a href="https://docs.python.org/3/library/enum.html" rel="noreferrer"><code>Enum</code></a> library in Python 3, which would quite possibly be a better container for data such as this.</p>
python|class|instance
15
1,904,851
13,932,893
python literal binary to hex conversion
<p>I have a textfile containing a range of bits, in ascii:</p> <pre><code>cat myFile.txt 0101111011100011001... </code></pre> <p>I would like to write this to an other file in binary mode, so that i can read it in an hexeditor. How could I reach that? I tried already to convert it with code like:</p> <pre><code>f2=open(fileOut, 'wb') with open(fileIn) as f: while True: c = f.read(1) byte = byte+str(c) if not c: print "End of file" break if count % 8 is 0: count = 0 print hex(int(byte,2)) try: f2.write('\\x'+hex(int(byte,2))[2:]).zfill(2) except: pass byte = '' count += 1 </code></pre> <p>but that didn't achieve what I planed to do. Do you have any hint?</p>
<ul> <li><p>Reading and writing one byte at a time is painfully slow. You may get around ~45x speedup of your code simply by reading more data from the file per call to <code>f.read</code> and <code>f.write</code>:</p> <pre><code>|------------------+--------------------| | using_loop_20480 | 8.34 msec per loop | | using_loop_8 | 354 msec per loop | |------------------+--------------------| </code></pre> <p><code>using_loop</code> is the code shown at the bottom of this post. <code>using_loop_20480</code> is the code with chunksize = 1024*20. This means that 20480 bytes are read from the file at a time. <code>using_loop_1</code> is the same code with chunksize = 1. </p></li> <li><p>Regarding <code>count % 8 is 0</code>: Don't use <code>is</code> to compare numerical values; use <code>==</code> instead. Here are some examples why <code>is</code> may give you wrong results (maybe not in the code you posted, but in general, <code>is</code> is not appropriate here):</p> <pre><code>In [5]: 1L is 1 Out[5]: False In [6]: 1L == 1 Out[6]: True In [7]: 0.0 is 0 Out[7]: False In [8]: 0.0 == 0 Out[8]: True </code></pre></li> <li><p>Instead of </p> <pre><code>struct.pack('{n}B'.format(n = len(bytes)), *bytes) </code></pre> <p>you could use </p> <pre><code>bytearray(bytes) </code></pre> <p>Not only is it less typing, it is a slight bit faster too.</p> <pre><code>|------------------------------+--------------------| | using_loop_20480 | 8.34 msec per loop | | using_loop_with_struct_20480 | 8.59 msec per loop | |------------------------------+--------------------| </code></pre> <p><a href="http://dabeaz.blogspot.com/2010/01/few-useful-bytearray-tricks.html" rel="nofollow">bytearrays</a> are a good match for this job because it bridges the gap between regarding the data as a string and as a sequence of numbers.</p> <pre><code>In [16]: bytearray([97,98,99]) Out[16]: bytearray(b'abc') In [17]: print(bytearray([97,98,99])) abc </code></pre> <p>As you can see above, <code>bytearray(bytes)</code> allows you to define the bytearray by passing it a sequence of ints (in <code>range(256)</code>), and allows you to write it out as though it were a string: <code>g.write(bytearray(bytes))</code>.</p></li> </ul> <hr> <pre><code>def using_loop(output, chunksize): with open(filename, 'r') as f, open(output, 'wb') as g: while True: chunk = f.read(chunksize) if chunk == '': break bytes = [int(chunk[i:i+8], 2) for i in range(0, len(chunk), 8)] g.write(bytearray(bytes)) </code></pre> <p>Make sure chunksize is a multiple of 8.</p> <hr> <p>This is the code I used to create the tables. Note that <a href="http://code.google.com/p/prettytable/" rel="nofollow">prettytable</a> also does something similar to this, and it may be advisable to use their code rather than my hack: <a href="https://gist.github.com/4330910" rel="nofollow">table.py</a></p> <p>This is the module I used to time the code: <a href="https://gist.github.com/4330933" rel="nofollow">utils_timeit.py</a>. (It uses table.py).</p> <p>And here is the code I used to time <code>using_loop</code> (and other variants): <a href="https://gist.github.com/4330943" rel="nofollow">timeit_bytearray_vs_struct.py</a></p>
python|binary|hex
2
1,904,852
54,438,826
Java Runtime.getRuntime().exec Executing only first line
<p>I want to execute a python script from java. The code is getting in to the python file but only executes first line of the file.</p> <p>following is the code:</p> <pre><code>Process p = Runtime.getRuntime().exec("python "+dir+"/pyfiles/testfile.py"); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); value = in.readLine(); </code></pre> <p>after the first line nothing is executed. what is the solution?</p> <p>'dir' value is getting from </p> <pre><code>final String dir = System.getProperty("user.dir"); </code></pre> <p>link to python file:</p> <p><a href="https://drive.google.com/file/d/1tvkFTM_Oo5gTS7FyzeNgoeY5DLitFQjD/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1tvkFTM_Oo5gTS7FyzeNgoeY5DLitFQjD/view?usp=sharing</a></p>
<p>The problem seems, that you are only reading the first line of your <code>BufferedReader</code>. So change your code as follows:</p> <pre><code>Process p = Runtime.getRuntime().exec("python "+dir+"/pyfiles/testfile.py"); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = in.readLine()) != null) { System.out.println(line); } </code></pre>
java|python
1
1,904,853
12,096,150
Handling json Form with jQuery on Google App Engine
<p>I am having some problems with making jQuery work on GAE python 2.7 . <strong>The main problem is jQuery cant catch the json data returned by the server.</strong></p> <p>A simple comment form with nothing special:</p> <pre><code>&lt;form action="/postcomment/" method="post" id="commentform"&gt; &lt;input type="text" name="author" id="author" onfocus="if(this.value=='Name: (required)') this.value='';" onblur="if(this.value=='') this.value='Name: (required)';" {% if name %}value="{{ name }}"{% else %}value="Name: (required)"{% endif %} size="22" tabindex="1" aria-required='true' /&gt; &lt;input type="text" name="email" id="email" onfocus="if(this.value=='E-Mail: (required)') this.value='';" onblur="if(this.value=='') this.value='E-Mail: (required)';" {% if email %}value="{{ email }}"{% else %}value="E-Mail: (required)"{% endif %} size="22" tabindex="2" aria-required='true' /&gt; &lt;textarea name="comment" id="comment" cols="100%" rows="10" tabindex="3"&gt;&lt;/textarea&gt; &lt;input name="submit" type="submit" id="submit" tabindex="4" value="Submit" /&gt; &lt;/form&gt; </code></pre> <p>My jQuery code (only structure to make it simpler):</p> <pre><code>$("#submit").click(function() { $.ajax({ dataType: 'json', beforeSubmit: function() { }, timeout: 60000, error: function(request,error) { }, success: function(data) { var obj = jQuery.parseJSON(data); //blah blah... } // End success }); // End ajax method }); </code></pre> <p>On the server side:</p> <pre><code>class PostComment(BaseHandler): def post(self): self.response.headers['Content-Type'] = "application/json" response = {'errorcode': 0} self.response.out.write(json.dumps(response)) </code></pre> <p>The result is: After I click the "submit" button, My Firefox 3.6 browser says: There is "application/json" file, do you want to open it with which tool?</p> <p>I was expecting jQuery to catch this 'json' data and process it. But it didnt happen.</p> <p>I believe I am almost there but something is wrong.</p>
<p>You need to cancel the default action of the form, which is to submit (which cancels any running JavaScript AJAX query in progress):</p> <pre><code>$("#submit").click(function() { $.ajax({ dataType: 'json', beforeSubmit: function() { }, timeout: 60000, error: function(request,error) { }, success: function(data) { var obj = jQuery.parseJSON(data); //blah blah... } // End success }); // End ajax method return false; // Cancel default action. }); </code></pre> <p>By returning <code>false</code> from the click handler, the <em>normal</em> form action, which is for the browser to submit the data to the URL named in the <code>action</code> attribute, is not executed.</p>
javascript|jquery|python|json|google-app-engine
2
1,904,854
12,557,368
How to plot 500 pairs of successive random numbers in python?
<p>I am new to python and one of the problems I am working on is to plot 500 pairs of successive random numbers. I have a formula that generates the numbers seen below:</p> <h1>x-axis</h1> <pre><code>&gt;&gt;&gt; a=128 &gt;&gt;&gt; c=0 &gt;&gt;&gt; m=509 &gt;&gt;&gt; n=500 &gt;&gt;&gt; seed = 10 &gt;&gt;&gt; for i in range (1,n): new_seed=(a*seed+c)%m seed = new_seed print new_seed </code></pre> <h1>y-axis</h1> <pre><code>&gt;&gt;&gt; a=269 &gt;&gt;&gt; c=0 &gt;&gt;&gt; m=2048 &gt;&gt;&gt; n=500 &gt;&gt;&gt; seed = 10 &gt;&gt;&gt; for i in range (1,n): new_seed=(a*seed+c)%m seed = new_seed print new_seed </code></pre> <p>What I am wondering now is how I can turn these results into an array or list. I have attempted to put plt.plot(new_seed) in the loop statement but that did not work when I tried to plot. Any ideas? </p> <p>I used import matplotlib.pyplot as plt</p> <p>Thanks in advance for the help!!</p>
<p>You should probably do some (more)python tutorials.. lists are a fundamental aspect of python and it seems you dont understand them...</p> <pre><code>import matplotlib.pyplot as plt import random x = [] a,seed,c,m,n = 128,10,0,509,500 for i in range (1,n): new_seed=(a*seed+c)%m seed = new_seed x.append( new_seed) a,seed,c,m,n = 269,10,0,2048,500 y= [] for i in range (1,n): new_seed=(a*seed+c)%m seed = new_seed y.append( new_seed) plt.plot(x,y) plt.show() </code></pre>
python|matplotlib|python-2.7
4
1,904,855
12,461,087
Detecting if any command-line options were specified more than once with optparse or argparse
<p>Python optparse normally allows the user to specify an option more than once and silently ignores all occurrences of the option but the last one. For example, if the action of option <code>--foo</code> is <code>store</code> and the action of option <code>--flag</code> is <code>store_const</code>, <code>store_true</code> or <code>store_false</code>, the following commands will be equivalent:</p> <pre><code>my-command --foo=bar --foo=another --flag --foo=last --flag my-command --flag --foo=last </code></pre> <p>(Update: argparse does just the same thing by default.)</p> <p>Now, I have a lot of options, and specifying any of them more than once doesn't make sense. If a user specifies the same option more than once I'd like to warn them about the possible error.</p> <p>What is the most elegant way to detect options that were specified multiple times? Note that the same option can have a short form, a long form and abbreviated long forms (so that <code>-f</code>, <code>--foobar</code>, <code>--foob</code> and <code>--foo</code> are all the same option). It would be even better if it was possible to detect the case when multiple options that have the same <em>destination</em> were specified simultaneously, so that a warning can be given if a user specifies both <code>--quiet</code> and <code>--verbose</code> while both options store a value into the same destination and effectively override each other.</p> <p>Update: To be more user-friendly, the warning should refer to the exact option names as used on the command line. Using <code>append</code> actions instead of <code>store</code> is possible, but when we detect a conflict, we cannot say which options caused it (was it <code>-q</code> and <code>--verbose</code> or <code>--quiet --quiet</code>?).</p> <p>Unfortunately I'm stuck with optparse and cannot use argparse because I have to support Python 2.6.</p> <p>P. S. If you know of a solution that works only with argparse, please post it, too. While I try to minimize the number of external dependencies, using argparse under Python 2.6 is still an option.</p>
<p>You can use <code>action="append"</code> (<code>optparse</code>) and then check the number of appended elements. See <a href="http://docs.python.org/library/optparse.html#other-actions" rel="nofollow">http://docs.python.org/library/optparse.html#other-actions</a></p>
python|argparse|optparse
1
1,904,856
23,070,329
can numpy's digitize function output the mean or median?
<p>I have some data that I need to group into bins. Instead of representing the bins as 0,1,2,3...etc. I would like it to output the mean or median of each bin. Is there a way to do this?</p>
<p>You could speed up shx2's code by computing the statistics for each <code>bin_idx</code> only once.</p> <pre><code>import numpy as np x = np.tile(np.array([0.2, 9., 6.4, 3.0, 1.6]), 100000) bins = np.array([0.0, 1.0, 2.5, 10.0]) def binstats(x, bins): inds = np.digitize(x, bins) statistics = [] binnumber = [] seen = set() for bin_idx in inds: if bin_idx not in seen: bin_arr = x[inds==bin_idx] statistics.append([np.mean(bin_arr), np.median(bin_arr)]) binnumber.append(bin_idx) seen.add(bin_idx) return statistics, binnumber statistics, binnumber = binstats(x, bins) for (mean, median), bin_idx in zip(statistics, binnumber): print('{b}: {mean:.2f} {median:.2f}'.format(b=bin_idx, mean=mean, median=median)) </code></pre> <p>yields</p> <pre><code>1: 0.20 0.20 3: 6.13 6.40 2: 1.60 1.60 </code></pre> <hr> <p>By the way, if you have scipy, you could also use <a href="http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.stats.binned_statistic.html" rel="nofollow">scipy.stats.binned_statistic</a>, but the performance is not any better:</p> <pre><code>import scipy.stats as stats # This is a hack to return two statistics with one call to binned_statistic. It reduces the precision of the statistics to `float32`. def onecall(): statistics, bin_edges, binnumber = stats.binned_statistic( x, values=x, bins=bins, statistic=lambda grp: (np.array([grp.mean(), np.median(grp)]) .astype('float32').view('float64'))) return statistics.view('float32').reshape(-1, 2) def twocalls(): means, bin_edges, binnumber = stats.binned_statistic( x, values=x, statistic='mean', bins=bins) medians, bin_edges, binnumber = stats.binned_statistic( x, values=x, statistic='median', bins=bins) return means, medians </code></pre> <hr> <pre><code>In [284]: %timeit binstats(x, bins) 10 loops, best of 3: 85.6 ms per loop In [285]: %timeit onecall() 10 loops, best of 3: 86.6 ms per loop In [286]: %timeit twocalls() 10 loops, best of 3: 150 ms per loop </code></pre>
python|numpy
5
1,904,857
23,412,358
Match list of regular expression in python
<p>I have list of regular expressions like below:</p> <pre><code>regexes = [ re.compile(r"((intrigued)(.*)(air))"), re.compile(r"(air|ipadair)(.*)(wishlist|wish)"), re.compile(r"(replac(ed|ing|es|.*)(.*)(with)(.*)(air))"), re.compile(r"(upgrade)")] for regex in regexes: if regex.search(post): print 1 break </code></pre> <p>Suppose I have a long list of strings and I want to search for these regex in each of my string, if any of the regex matched return 1 and break. Then do the same thing for the next string. My current one is running super slow, please let me know if there are any better alternatives.</p> <p>Thanks,</p>
<p>As some of the comments have mentioned, this looks like it might not be a job for regexes. I think it's worth looking at what you are actually trying to do here. Take a look one of the regexes:</p> <pre><code>"(air|ipadair)(.*)(wishlist|wish)" </code></pre> <p>In this case we are matching "air" or "ipadair", but just "air" would match both. The same is true for "wish". As we are not making use of the capture groups the output could be simplified to:</p> <pre><code>"air.*wish" </code></pre> <p>The same is true of all of the other patterns, which begs the question: what is this regex actually doing? </p> <p>It looks like you just want to see if certain patterns of words appear in an order in your article. If that is true, then we can achieve this much faster in python without regexes:</p> <pre><code>def has_phrases(in_string, phrases): for words in phrases: start = 0 match = True # Match all words for word in words: # Each word must come after the ones before start = in_string.find(word, start) if start == -1: match = False break if match: return True phrases = [ ['upgrade'], ['air', 'wish'], ['intrigued', 'air'], ['replac', 'with', 'air' ], ] print has_phrases("... air ... wish ...", phrases) # True! print has_phrases("... horse ... magic ...", phrases) # None </code></pre> <p>Of course, if you were just giving a simplified example and you plan to use crazy complicated regexes, this won't cut it.</p> <p>Hope that helps!</p>
python|regex
2
1,904,858
8,271,484
Why does text retrieved from pages sometimes look like gibberish?
<p>I'm using urllib and urllib2 in Python to open and read webpages but sometimes, the text I get is unreadable. For example, if I run this:</p> <pre><code>import urllib text = urllib.urlopen('http://tagger.steve.museum/steve/object/141913').read() print text </code></pre> <p>I get some unreadable text. I've read these posts: </p> <p><a href="https://stackoverflow.com/questions/7964726/gibberish-from-urlopen">Gibberish from urlopen</a></p> <p><a href="https://stackoverflow.com/questions/3947120/dose-python-urllib2-will-automaticly-uncompress-gzip-data-from-fetch-webpage">Does python urllib2 automatically uncompress gzip data fetched from webpage?</a></p> <p>but can't seem to find my answer.</p> <p>Thank you in advance for your help!</p> <hr> <p>UPDATE: I fixed the problem by 'convincing' the server that my user-agent is a brower and not a crawler. </p> <pre><code>import urllib class NewOpener(urllib.FancyURLopener): version = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.120 Chrome/15.0.874.120 Safari/535.2' nop = NewOpener() html_text = nop.open('http://tagger.steve.museum/steve/object/141913').read() </code></pre> <p>Thank you all for your replies.</p>
<p>This gibberish is a real server response for the request to <code>'http://tagger.steve.museum/steve/object/141913'</code>. Actually, it looks like obfuscated JavaScript, which, if executed by a browser, loads page content.</p> <p>To get this content, you need to execute this JavaScript, and this can be a really difficult task within Python. If you still want to do this, take a look at <a href="http://code.google.com/p/pywebkitgtk/" rel="nofollow"><code>pywebkitgtk</code></a>.</p>
python|urllib2|urllib|urlopen
2
1,904,859
784,584
Convincing others of Ruby over Python and PHP
<p>G'day folks. I'm trying to introduce Ruby at work, and a few people are interested. However, I've been asked to present the benefits of Ruby over Python and PHP.</p> <p>I've broken this down into 2 parts: 1) show Python and Ruby's advantages over PHP; 2) show Ruby's advantages over Python.</p> <p>The first is easy. I'll explain things like:</p> <ul> <li>Everything's an object.</li> <li>Python and Ruby are easier to read and write.</li> </ul> <p>For the second, I'm thinking of:</p> <ul> <li>Ruby has many conveniences, which makes it easier to read and write. Eg: Optional brackets, and being able to open built-ins, allows for things like 2.days.from_now</li> <li>RSpec is miles ahead of Python's TDD and BDD frameworks.</li> <li>GitHub and RubyForge are fantastic resources for finding, releasing, and collaborating on software.</li> </ul> <p>Do you have any suggestions? I'm all ears!</p>
<p>If your goal is to show why language X is <strong>better</strong> than language Y, you're stuck in subjective-land where there are no right answers.</p> <p>No, Ruby is not <strong>better</strong> than PHP or Python. It might be more suited for a given purpose, and for that you can give specific examples. PHP is a poor choice for writing an SMTP server; Ruby and Python will serve you better (in fact, in Python it can be done in just a few lines, can't speak for Ruby though). On the other hand, PHP is better suited than Ruby for writing a one-off, short backend for an email submission form. The code is short, easy to maintain, quick to write, etc.</p> <p>PHP has an absolutely huge developer base, making programmers easy to find, which comes in handy if you ever want to out-source any aspect of the development chain. On the other hand, it's also terrifically easy to write horrible code in PHP, and there is more than enough of that going around.</p> <p>Python has a much larger user base than Ruby, and indeed is the primary language that RedHat uses for developing system tools. So if you're on a RedHat derived server (and statistically, chances are pretty good that you are if you're using Linux) then Python is guaranteed to be already in-place and working properly, etc.</p> <p>In short, weigh the benefits, make a decision, but don't assume that people will agree with you; after all it's just an opinion.</p> <hr> <p><strong>Edit</strong></p> <p>It just occurred to me that I failed to state the whole point: you shouldn't be trying to <strong>convince</strong> other people that they should use Ruby over Python/PHP. Instead you should be trying to <strong>determine</strong> whether you should use Ruby over Python/PHP. </p> <p>You can't go fact-finding like this having already determined what the answer will be -- that's not helpful. Instead you should be gathering information on the benefits and drawbacks of each language and weighing that against the requirements of your company. Once you come to a conclusion, you'll already have a preponderance of evidence showing it was the correct one.</p>
python|ruby
29
1,904,860
41,954,338
Unable to Plot graph using pyplot, pandas: _tkinter.TclError: no display name and no $DISPLAY environment variable
<p>This code connects to MySQL and fetches a dataset which I read using pandas. Once the dataset is in a pandas dataframe, I need to plot it. But that throws an error. Here's the snipper</p> <pre><code>#!/usr/bin/python import MySQLdb as mdb import pandas as pd import matplotlib.pyplot as plt con = mdb.connect('hostname', 'username', 'password', 'database'); with con: cur = con.cursor() cur.execute("select month, post, comment, reply, dm, review") rows = cur.fetchall() df = pd.DataFrame( [[ij for ij in i] for i in rows] ) df.rename(columns={0: 'Month', 1: 'Post', 2: 'Comment', 3: 'Reply', 4: 'DM', 5: 'Review'}, inplace=True); print(df.head(20)) df=df.set_index('Month') df=df.astype(float) df.plot(subplots=True) plt.show() </code></pre> <hr> <pre><code>Traceback (most recent call last): File "random-exmaple.py", line 7, in &lt;module&gt; plt.plot(x, y, "o") File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3307, in plot ax = gca() File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 950, in gca return gcf().gca(**kwargs) File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 586, in gcf return figure() File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 535, in figure **kwargs) File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager return new_figure_manager_given_figure(num, figure) File "/usr/local/lib/python2.7/site- packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure window = Tk.Tk() File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable </code></pre> <p>How to fix this?</p> <p>Sorry for the duplicate - <a href="https://stackoverflow.com/questions/41951310/issue-with-tkinter-python-and-seaborn-tkinter-tclerror-no-display-name-and-n?noredirect=1#comment71095010_41951310">Issue with tkinter, python and seaborn: _tkinter.TclError: no display name and no $DISPLAY environment variable</a></p>
<p>This kind of error appears when we try to run GUI applications or plot something on remote machine, which has not connected display device. In this case, you can save your plots on remote machines and copy them on local machine via scp. You can do it this way:</p> <p>Save plots:</p> <pre><code>ax = df.plot(subplots=True) fig = ax.get_figure() fig.savefig('plots_name.png') </code></pre> <p>Copy images from remote machine to local directory:</p> <pre><code>scp {remote_username}@{remote_host}:{path_to_image} {path_to_local_directory} </code></pre> <p>where <code>{remote_host}</code> is the IP address or domain name that you are trying to connect to, <code>{remote_user}</code> is your username on remote machine, <code>{path_to_image}</code> is path on remote machine to image you want to copy (use <code>pwd</code> command to find it) and <code>{path_to_local_directory}</code> is path to local directory, where you want your plot will appear.</p> <p>EDIT:</p> <p>For newcomers. It's more complicated solution. Author of this question has provided simple solution to solve this problem. Check this: <a href="https://stackoverflow.com/questions/41951310/issue-with-tkinter-python-and-seaborn-tkinter-tclerror-no-display-name-and-n?noredirect=1#comment71095010_41951310">Issue with tkinter, python and seaborn: _tkinter.TclError: no display name and no $DISPLAY environment variable</a></p>
python|mysql|pandas|matplotlib
0
1,904,861
47,318,128
separate first word in a string in python re
<p>I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:</p> <pre><code>for record in reader: s = record['trial'] patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)') source = "Footit" if patternsubgen.search(s): resultsubgen = patternsubgen.search(s) genussubgen = resultsubgen.group(1) speciessubgen = resultsubgen.group(2) subgen = '%s %s' % (genussubgen, speciessubgen) #print(subgen) else: pattern = re.compile(r'(\w+)\_(\w+)') if pattern.search(s): result = pattern.search(s) genus = result.group(1) species = result.group(2) new = '%s %s' % (genus, species) print(new) </code></pre> <p>Here are some examples of the strings:</p> <pre><code>Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a, </code></pre> <p>what I need is:</p> <pre><code>Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a, </code></pre> <p>what I am getting is:</p> <pre><code>Aphis asclepiadis, Cinara 011, Clydesmithia_canadensis 1a </code></pre>
<p>For the given strings, you could use</p> <pre><code>\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b </code></pre> <p>See <a href="https://regex101.com/r/P69Uw8/1/" rel="nofollow noreferrer"><strong>a demo on regex101.com</strong></a>. <hr> In <code>Python</code>:</p> <pre><code>import re strings = 'Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,' rx = re.compile(r'\b([^_\W]+)(?:\([^()]+\))?_(\w+)\b') strings = rx.sub("\g&lt;1&gt; \g&lt;2&gt;", strings) print(strings) # Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a, </code></pre>
python|regex|string
1
1,904,862
57,548,525
List claims to be empty but still contains an object
<p>In my application I send a list of strings <code>child</code> as arguments to a function, <code>populate()</code>. The <code>populate</code> function turns the information inside the list into an object. This is repeated multiple times. The objects are stored inside a list <code>population</code>.</p> <p>However for some reason when trying to print a value of an object's method within <code>population</code> using:</p> <pre><code> for obj in self.population: print(obj.dna) </code></pre> <p>I get a series of empty lists <code>[]</code></p> <p>But when I print the obj itself:</p> <pre><code>for obj in self.population: print(obj) </code></pre> <p>I get a series of actual objects <code>&lt;__main__.Individual object at 0x00000206A0FDFA20&gt; </code> I think I was able to trace the root of the problem to my <code>crossover</code> and <code>populate</code> functions</p> <p>When I print the child argument inside <code>populate</code> my child list isn't empty for 10 iterations then after that it becomes empty, I have no idea why.</p> <p>code:</p> <pre><code>... def crossover(self, tuple_dna): child = [] while len(self.population) &lt; self.size: for tuple in tuple_dna: gene = self.mutation(random.choice(tuple)) child.append(gene) self.populate(child) child.clear() self.generation += 1 def populate(self, child): print(&quot;child:&quot;,child) individual = (Individual(child, 0)) self.population.append(individual) </code></pre> <p>output:</p> <pre><code>... child: ['7', 't', 'B', 'b', 'Y', 'G', '3', 'T', 'r', 'n', '9'] child: ['1', 'Z', 'l', 't', 'n', 'G', 'g', '9', 'r', 'n', '5'] child: ['7', 'Z', 'B', 't', 'Y', 'G', 'g', 'T', 'r', 'n', '9'] child: [] child: [] child: [] child: [] ... </code></pre> <h1>EDIT</h1> <p>Here is code that is MRE:</p> <pre><code>import random target = &quot;hello world&quot; tuple_dna = [('K', 't'), ('a', 'k'), ('b', 'a'), ('M', 'Z'), (' ', 'w'), ('m', 'D'), ('F', 'J'), ('J', 'O'), ('Y', 'H'), ('6', 'R'), ('X', '2')] size = 3 population = [] child = [] def crossover(tuple_dna): while len(population) &lt; size: for tuple in tuple_dna: gene = random.choice(tuple) child.append(gene) populate(child) child.clear() for obj in population: print(&quot;dna&quot;, obj.dna) def populate(child): individual = Individual(child, 0) population.append(individual) class Individual: def __init__(self, dna, fitness): self.dna = dna self.fitness = fitness crossover(tuple_dna) populate(child) print(&quot;pop&quot;, population) crossover(tuple_dna) populate(child) print(&quot;pop&quot;, population) </code></pre> <p>output:</p> <pre><code>dna [] dna [] dna [] pop [&lt;__main__.Individual object at 0x0000026ECC3AB518&gt;, &lt;__main__.Individual object at 0x0000026ECC3AB588&gt;, &lt;__main__.Individual object at 0x0000026ECC3AB5F8&gt;, &lt;__main__.Individual object at 0x0000026ECC3FB780&gt;] dna [] dna [] dna [] dna [] pop [&lt;__main__.Individual object at 0x0000026ECC3AB518&gt;, &lt;__main__.Individual object at 0x0000026ECC3AB588&gt;, &lt;__main__.Individual object at 0x0000026ECC3AB5F8&gt;, &lt;__main__.Individual object at 0x0000026ECC3FB780&gt;, &lt;__main__.Individual object at 0x0000026ECC3FB7B8&gt;] </code></pre> <p>How does the population list contain objects, but when I try and access the <code>dna</code> attribute, the list is empty.</p>
<p>The culprit is that the <code>dna</code> list in each <code>Individual</code> instance is cleared after the class is instantiated inside your <code>crossover()</code> function:</p> <pre><code>def crossover(tuple_dna): while len(population) &lt; size: for tuple in tuple_dna: gene = random.choice(tuple) child.append(gene) populate(child) # &lt;-- puts the child list into the dna attribute child.clear() # &lt;-- clears that same list </code></pre> <p>Both <code>child</code> and some <code>Individual</code> share the exact same list. This is the same problem as this MCVE:</p> <pre><code>&gt;&gt;&gt; l = [] &gt;&gt;&gt; c = [l] # container holds the same list l, not a copy &gt;&gt;&gt; l.append(5) &gt;&gt;&gt; l.append(6) &gt;&gt;&gt; c # so when l is modified, the change is reflected in c [[5, 6]] &gt;&gt;&gt; l.clear() &gt;&gt;&gt; c [[]] </code></pre> <p>I don't see any particular reason that <code>child</code> should be a global variable that is modified inside functions. Typically, there's not good reasons to do that (part of the reason being that it introduces confusing bugs like you're seeing!) and I see no good reason here. Just create a new <code>child</code> list each time the loop is entered, and don't <code>clear()</code> it:</p> <pre><code>def crossover(tuple_dna): while len(population) &lt; size: child = [] # &lt;-- child gets assigned a new, clean list each time for tuple in tuple_dna: gene = random.choice(tuple) child.append(gene) populate(child) </code></pre> <p>I'm not sure why you call <code>populate(child)</code> after calling <code>crossover()</code> in your code, given that your old code cleared <code>child</code> every time. Regardless, if you want to be able to use <code>child</code> between runs of <code>crossover()</code>, just return the child you want and pass it back between functions. </p> <p>In other words, <em>don't</em> do this:</p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; modify_list(l) &gt;&gt;&gt; do_something(l) &gt;&gt;&gt; modify_list(l) </code></pre> <p>Instead, do this:</p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; l = returns_list(l) &gt;&gt;&gt; do_something(l) &gt;&gt;&gt; l = returns_list(l) </code></pre>
python
1
1,904,863
11,606,672
Django:What to use modelform,formset,model formset for the following scenario?
<p>I have this model:</p> <pre><code>class option(models.Model): warval = models.ForeignKey(war) caption = models.CharField(max_length=20) text = models.TextField(blank=True,null=True) url = models.URLField(blank=True,null=True) user = models.ForeignKey(User) </code></pre> <p>And I have few modelforms like:</p> <pre><code>class text_option(ModelForm): class Meta: model = option exclude = ('url','warval','user') class url_option(ModelForm): class Meta: model = option exclude = ('text','warval','user') def clean_url(self): #processing... </code></pre> <p>I want my users to create as many options as they want.So the my option is using "formset". But how can I instantiate all the forms in formset with the "war" instance("war" is a model).And also how to provide all the functionality of the above given modelforms in my formset? </p>
<p>You can pass the id of <code>war</code> instance either explicitly through url something like <code>http://myserver/add_options/1</code> where <code>1</code> is id of <code>war</code> and you use it in your view to update foreignkey field of options appropriately. </p> <p>Another options is passing id as implicit/hidden input field in your form and using that id to identify <code>war</code> instance in the view.</p> <p>On the side lines, may be you can make use of inheritance to simplify your model definition. like:</p> <pre><code>class base_option(models.Model): warval = models.ForeignKey(war) caption = models.CharField(max_length=20) user = models.ForeignKey(User) class text_option(base_option): text = models.TextField(blank=True,null=True) class url_option(base_option): url = models.URLField(blank=True,null=True) </code></pre>
javascript|python|django
0
1,904,864
11,651,164
While retrieving image from datastore i am getting this error
<p>I am new to google appengine.</p> <p>I have stored the image in blob field. I am trying to get the image it shows error.</p> <p>Below i have pasted my code and output.</p> <p>main.py</p> <pre><code>import cgi import webapp2 from google.appengine.api import users from google.appengine.ext.webapp.template \ import render from os import path from google.appengine.ext import db from google.appengine.api import images import urllib import re import datetime class imgstore(db.Model): name=db.StringProperty(multiline=True, default='') image=db.BlobProperty() class MainHandler(webapp2.RequestHandler): def get(self): moviequery=db.GqlQuery('SELECT * FROM imgstore') context={ 'list':moviequery } tmpl = path.join(path.dirname(__file__), 'static/html/index.html') self.response.out.write(render(tmpl, context)) def post(self): name1 =images.resize(self.request.get("file"), 32, 32) formdata = db.Blob(name1) insert = imgstore() insert.name="name" insert.image=formdata insert.put() routes=[ (r'/', MainHandler), ] app = webapp2.WSGIApplication(routes=routes,debug=True) </code></pre> <p>index.html</p> <pre><code>&gt; &lt;html&gt; &gt; &lt;head&gt;&lt;title&gt;test&lt;/title&gt;&lt;/head&gt; &gt; &lt;body&gt;hello &gt; &lt;form id="form" action="/" method="post" ENCTYPE="multipart/form-data"&gt; &gt; &lt;input type="file" name="file" &gt; &gt; &lt;input type="submit" name="submit"&gt; &gt; &lt;/form&gt; &gt; {% for lis in list%} &gt; &lt;img src="{{lis.image}}"&gt; &gt; {% endfor %} &gt; &lt;/body&gt; &gt; &lt;/html&gt; </code></pre> <p>Output</p> <pre><code>Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1536, in __call__ rv = self.handle_exception(request, response, e) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1530, in __call__ rv = self.router.dispatch(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 1102, in __call__ return handler.dispatch() File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/Users/saravase/test/main.py", line 44, in get self.response.out.write(render(tmpl, context)) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/template.py", line 92, in render return t.render(Context(template_dict)) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/template.py", line 172, in wrap_render return orig_render(context) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 173, in render return self._render(context) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 167, in _render return self.nodelist.render(context) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 794, in render bits.append(self.render_node(node, context)) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 807, in render_node return node.render(context) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/defaulttags.py", line 173, in render nodelist.append(node.render(context)) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 847, in render return _render_value_in_context(output, context) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 827, in _render_value_in_context value = force_unicode(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/utils/encoding.py", line 88, in force_unicode raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte. You passed in '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00\x14\x08\x06\x00\x00\x00\xec\x91?O\x00\x00\x066IDATx\x9c\xad\xd6i\x8c\x95W\x19\x07\xf0\xffs\xce}\xdf\xf7ns/\xb3\xdc;03\xcc\xc0\xb0\xcc\x1d\x8a\xb4\x99\xb2:\x05KS\xa8\xa4M\x00\x95\x8e\xd3\xfa\xc1%\xe9W5\xa9\xf1\x83\x89F\xe3\x17hP\x96\x84hCB\x14k\xc4b\x04\xaa\xb5j\xd0V\xa4\xd0\xa1(\x85P\x18(\xcc\xc2,\xf7\xce\x1d\xee\xdc}}\xcf\xf3\xf8\x81E\x88\xadv\xf1|?y~\xf9\xff\x9f\x9c\x1c\x12\x11\x00\x80\x08+aQJ+\x06\x88\x01\xa0\\\xae\xea\xb1\xe1+\xab*\xf9\xcc\xa2\xba\xc6\xd6\xe3\xed\xf3\xe7\x8d\x01 aV\x02\x81R\xda\xe0\x13\x1ebf\x05\x08\x88\x14\x03\x801\x8c\xc4\x8d\xe1\xee\x91\xc1\xb7\xb6M\\;\xf5\xb9Rvt)\x8c\xe8\x91\x1b\x95t\xe3\xdc\x15\xbf\xda\xf4t\xff\xee\x8eEK.\x03 \x11&amp;\x11\xa1O\x02!\x11!\x01djrb\xee\x85\xb7^\xdf:6x\xaa_J#+,OI\xdb\xb6\x03\xed\xb1\x85\xd9\x15\x9fch|&lt;I\xa9\x8c\xc7\x9d\xbd\xe0\x91\xa3\xab7\xf4m\xef\xfaT\xcf\x19\xa5\x08"\xa2DX)\xa5\xdd\x8f\x0c\x18\xba\xf4^\xec\x97\xfb^\xd8\x11\xf2\x8fo\xf0\xeb\x927P\xe7@\xdb&gt;Q\x8a\x8cV\xae\xb2-V\x8e#\x10\xe3\nC\x99\xe4tE\xb3\xa9\x10\xa0\xc4\xd8\xb1\xe3]\xbd\xcfl_\xb1\xfa\x91\xe3Z+\x11\x11%\xccJie\x00\x92\x0f\x05\xb8\xfc\xee\xa5\r\x07\xf7&gt;\xff\xa7\xdc\xf8$Z\xe6\xd4\xbb\xd19\x01j\x8e\xdaZ\x00@\x04\x86\x05\x95\xb2\x0b\xd75\xf0X\n\xa1:\r\xdb\xb1\xdcBA\xa9|6\xa7\xd2\x99&lt;\x9cP\xe7\xe9\x07{\xb7m\x7f`\xe5\xe3\xaf8^\xdb\x88\x08\t\xb3VJ\x19\xd0\x7f\x87\x90\x88`\xaa4\xb8\xe3\xec\x89C\xdf\x1a8v\xb6\x96\x9d\x98\xb0ZZ\x03X\x1c\x8b\xc00\xa1RfX\xb6\x86\xe5\x01&lt;\x1e\x8dR\xb9\x8aJ\xc5\xc0\xf1\x06\xe1x\xaaF\xab\x1a\x15KU\x8aON\x13\xac\xf9\xe7\x97\xac\xe9\xdb\xbe\xe6\xf1\'\x0e;^_\xf5\x0e\x84\x942\xf4\x01\x10\x12f\xb8\x02gd\xe4\xd8I\xedM&lt;|\xfdb\xbav\xf27oX\xd5\\\x12\xdd\xb1F45\xcfB6\'0\xb5*|\xfe H\tr\xe9\x0cf\xd5\xdb(\x95\xca(\x96\x14\x0c+\xe3\xa8\x12\x88\\\x95L\xe6\xc9\x0e\xce\xbd\xb2\xacw\xeb\x0b=\x8fn~\xc9\xf1\x05K\x10!\x16\xd6D\xff\t!fVD\xc4\xc9\x1b\xc3\xb1k\xe7\xf7\xfc\xad\xe7\xb3]\x91\xa2;\xcf}\xe3\xc8\xdb\xfa\xc4\x91?\x92\xc3\x05,\x8e\xb5"\x10\xf2\x02b \x0cd\xf35\x84\xc3\x01dRi\x04\x82\x16\x08\x04f\x03\xcbr\rA!\x93.\xa8\xa9D\x96\xac@\xf3\xf0\xb2\xb5\x9f\xff\xf1\xea\x8d\xdb\x0e\xd4\x85g\xe5\x00!\xe6\xfb!$"\x10\x11ED&lt;=v}\xf1\xd4\xd0\xfe\x83\xb3c\xee\xca\x86\xc8g\xccT\x9a\xf0\xfb\x9f\xbd\xa2/\xfe\xfdm\xb4D\x1dD"Ax}!T\xdd*\xaa\x15\x83B\xae\x86`\xd0F\xa4\xb9\x1e\xf9\xecMT\xaa.&amp;\xe3%h\xcba\xadXl\x95W\xe5R\x91*\xdc4\xb1\xf0\xe1/\xec\xd9\xb8\xf5\x8b/\xce\x8a6\xcc\x88\x08\xdd\x99I\xff~\x88D\x11\x91T\xcbU\x15\xbfz\xec\xeb.\xff\xf9\xfb\xd1E\x9d\xc1\xa0\xbf\xc7\x0c\r\x0f\xd1\xb1\xfd\xaf\xaa\xf3\xa7\xaf`v\xc4\x8bh4\x00\xcbr\xe0\xf5Y "d3\x15\x14+\x04\xad\x05\xe1\x90\rK\x0b|^A6W\xe1t\xc6p\xb1lt\xb1X\xa6j-\x90\\\xbf\xb9o\xcf\xba\xa7\x9e\xdd\xd7\xd0T\x9f\x02\x84\xee\x02\xee" \x04Rf&amp;&gt;:/9rp\x97\xbfqt\xf3\x9c\xce\x1e\xd1j\x8e9w\xfa\xac&gt;\xfc\xe2_(~#\x89\xeeX\x14A\xbf\x03Q6\xf2\x05\x83P\x90\xe1\xf1\x10&lt;\x9a\x90\xcd\xd6\x90H\xe6\x90\xc9\xb9\xc8\x97\x04\x8e\xad9\x1a\xf1K\xd0g\xd4\xe8p\x9c\xaa\xd2\x9cZ\xf7d\xff\x0f\xb7|\xe5\xb9\xbd\xf7\x01n3n\xc7\xa3\xd8\xb8\x90\xf8\xb5\xd7\xb7\xe6S/\xef\x8a,\xd0\xed\r\xd1\x1e6F\xc9_\x8f\x9e\xd6\x87\x0f\x9cB\xb9P\xc4\xc2\x05\x8dhj\x0c\xa2\\)#\x9d1\x98\x9e\xa9\xa0P\xac\xc2\xb1=\xf0\xfb-\xd4\x05m\x84\x02\x1a\xa5R\x05#\xe3y\xa9Q\xc04DZt]\x98\xe8\xab\xdf\xfc\xc1\x86\xf7\x01\xdcI\x83\x15\x01\x04R\xa6\x90\xc9\xd4%\xaf\xff\xfa;\xa0\x13\xdfhZ\xd0\xe6\x04\xeb\x16\x98\xd4t\x86\x0e\xfd\xf4\xa4:z\xe8\x9f\xd0\x9a\xd1\xda\x12\x023A\x88\x00\x114\xd4\xfb0\xbb\xc9\x01\xc4 q\xb3\x8c\xa1q\x17\xb67\x8c\x9e5\x8by\xd5\xc6v\xb5p\xe9\x923\x91\xe0\x965\x1f\x08\xb8\x07\xa2om,q:~56s\xe3\xe7?\xb2}W6E\x17v\x88\xe5\x8d\xf2\xe8\xa5\xb4:\xb0\xf7,]\xf8\xc7\x08b]MplA\xa1PF8\xe4\xc1\xf4L\x19\xc94\x83t\x1d:\x16\xb7\xe0\xb1M\xed\xe8^\x1a2\\\xcdh+\xd0\xfftSt\xf9\xcb\xff\x13p{7\x08\xb8S\x8b\xc8\xf8\xe5\xe3[\xf2\x93\x07v\x86\xc3\xc9\xce\xe6\xaen\xf6\x84\xda\xe4\xd4kc\xfa\xc8/."\x9e\x98\x81\xd7o!\x9f\xad@\xd96b=\xf3\xf1\xe9\xc7\xda\xd0\xd5m\xc3\xaa\x95j\xf1+\xa3\xd6t\xb2\xf5\xc4\xba\xfe\xdd\xeb\xb4\x87\xe8C\x01\xee\xad\x05\x00\x11)\x93\xcf\xe6\xfcc\xe7\x0e&gt;_\x9a8\xfc\xed\xb9\xb1\xa0\xbf\xe9\xa1\xe5&amp;\x9d\x04\xbd\xf9\x87\x1959\xec"S\xcb\xe0\xa1G\xdb\xd0\xd5\xe9\xc2\xaa\xa487]\xe4\xe1\x8b\xe3\x9e\xab\x97s\xc5\xb5\xcf\xfcd\xfd\x03+V\x0e\x08\xb3\xfaH\x80\xf7\xabej\xf4Z\xe7\xe8\xc0\xae=\xb3\x02\xef&lt;\xd9\xfe`\x07\xdb\x8d\xcd29\xdd\xa1\xb57\x07\xdbMq\xe2\x9d\xabr3\x91UC\x83q\xaa\xd0\xa23k\xb7}\xf7\xb9E\xcb\x96\x9f\x13aE\xa4\xf8c\x01n!\x84\x00\xd6D\xda\x18\x86\x8c\x9c\xfdm\xdf\xd4\x85}\xbb[Z3\xcds\xd7?\xcb\x89\xa1Q\x0c\x0f\x0c\xd0{\xef&amp;\xa8(-C\xb1\xde\xaf}o\xd5\xc6\xbe\x97\x1c\xc7faV\xa4n\xfd?&gt;6\xe0\x9e4\xee\xd6\x92\x99N6^xm\xe7\x0e\xe2s_N\xa5\xf2*1\xa9G\xda\x96\xf5\xed\xec}\xeaK\xfb\xeb\xc2\xa1\x92\x08k\x08\xe4\xce\xf0\xff\x0b\xe0.\x84\x8d&amp;\xa5\x98\x85d\xf0\xcc\x9b\xbd\xe9\xd4d\xfb\x92U\xeb\x7f\x17\xaeo\xc8AD\xf1\xad\xc8]"\xba\xef\xde\xbf\x00E\x15c\xc0\xf90\xc3\xa2\x00\x00\x00\x00IEND\xaeB`\x82' (&lt;class 'google.appengine.api.datastore_types.Blob'&gt;) </code></pre> <p>Please guide me how to proceed further.</p>
<p>You need to do two things. First, you need to change your HTML such that the <code>src</code> of the <code>img</code> tag contains a URL that is served by your application. Second, you need to implement a handler to server the URL.</p> <p>Let's say that your application will serve stored images with a URL like this: <code>/image/15</code> where 15 is the <code>id</code> of the <code>imgstore</code> entity. You'll need to add a route:</p> <pre><code>routes=[ (r'/image/(\d+)', ImageHandler), (r'/', MainHandler), ] app = webapp2.WSGIApplication(routes=routes,debug=True) </code></pre> <p>And then you'll need to add a new RequestHandler class:</p> <pre><code>class ImageHandler(webapp2.RequestHandler): def get(self, image_id): requestedImage = imgstore.get_by_id(int(image_id)) if requestedImage is not None: self.response.out.write(requestedImage.image) else: # return a default image when we can't located the # one that was requested? </code></pre> <p>The new route includes a numeric capture -- <code>(\d+)</code> -- that will be passed to the request handler as a parameter. We can then use that id to get the image entity directly from the datastore; it's much faster than using a query.</p> <p>So, where do we get the id from? Every entity in the datastore is automatically assigned an integer id unless you give it an id or a name when you store it.</p> <p>The last thing that you need to do is provide an easy way to embed the URL that will server your image into the template that contains the <code>img</code> tag. Add a method to your imgstore class:</p> <pre><code>class imgstore(db.Model): name=db.StringProperty(multiline=True, default='') image=db.BlobProperty() def url_for(self): return "/image/%d" % self.id </code></pre> <p>Now you can change your template to use the new method:</p> <pre><code>&lt;img src="{{lis.url_for}}"&gt; </code></pre>
python|google-app-engine
1
1,904,865
58,508,513
Count Number Of Occurence in 2D Array
<p>Let's say I have an array like this</p> <pre><code>grid: [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1]] </code></pre> <p>I want to isolate the group of "items" in this case 1's which are three groups the rule being the 0's are used to separate them like intersections. So this example has 3 groups of 1.</p> <p>If you know how to do this with python, the first question I'd be asked is what I've tried as proof of not handing my homework to the community, the idea I had was to iterate down and left but that would have a high likelihood of missing some numbers since if you think about it, it would form a cross eminating from the top left and well this group is here to learn. So for me and others who have an interest in this data science like problem be considerate.</p>
<p>If you do not need to know which sets are duplicates, you can use python's <code>set</code> built-in to determine unique items in a list. This can be a bit tricky since <code>set</code> doesn't work on a <code>list</code> of <code>list</code>s. However, you can convert this to a <code>list</code> of <code>tuple</code>s, put those back in a <code>list</code>, and then get the <code>len</code> of that list to find out how many unique value sets there are.</p> <pre><code>grid = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1]] unique = [list(x) for x in set(tuple(x) for x in grid)] unique_count = len(unique) # this will return 3 </code></pre>
python
1
1,904,866
33,547,729
Filling out a comment form and submitting with python & selenium
<p>I have a web page that I am trying to post a comment with, but I can't seem to get the text to show up in the comment box. Here is the code from the site:</p> <pre><code>&lt;form id="commentForm" class="comment_form" accept-charset="UTF-8"&gt; &lt;p class="post-error" style="display: none;"&gt;There was a problem posting your comment, please try again.&lt;/p&gt; &lt;textarea placeholder="Leave a comment..." name="comment" id="commentBox" class="commentBox" onkeyup="limitTextReverse(jQuery('.commentBox'),jQuery('.myCount'), 140);" onkeydown="limitTextReverse(jQuery('.commentBox'),jQuery('.myCount'), 140);"&gt;&lt;/textarea&gt; &lt;span class="button grey btn-submit" class="track-click" data-track="checkin_page" data-href=":comment/post" href="#"&gt;Post&lt;input type="submit" value="Post" /&gt;&lt;/span&gt; &lt;span class="comment-loading" style="display: none;"&gt;&lt;/span&gt; &lt;span class="counter"&gt;&lt;abbr class="myCount"&gt;0&lt;/abbr&gt;/140&lt;/span&gt; &lt;input type="hidden" name="checkin" value="123456789" /&gt; &lt;/form&gt; </code></pre> <p>and here is what I have so far:</p> <pre><code>box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "comment_form"))) box.click() </code></pre> <p>however, when I try to send_keys to it, it kind of freaks out and nothing goes in. Any thoughts on how to actually get text into the comments box?</p>
<p>I think what might be happening is you are clicking on the <code>form</code> element, but you are not clicking on the actual comment box. You don't want to type into the upper level <code>form</code> element, you want to type into the <code>textarea</code>.</p> <p>You can select an element by id, then type into it:</p> <p><code>elem = driver.find_element_by_id("commentBox")</code></p> <p><code>elem.send_keys("This is a comment I'd like to write!")</code></p> <p><a href="http://selenium-python.readthedocs.org/getting-started.html" rel="nofollow">The Selenium Getting Started Guide</a></p>
python|forms|selenium
1
1,904,867
46,962,636
How to expose static constexpr from cython
<p>I need to wrap the following demo example from cpp to cython for using in Python</p> <pre><code>class Foo1 : public MFoo&lt;unsigned int&gt; { public: constexpr Foo1(unsigned int val) : MFoo{val} {} } }; class Foo{ public: static constexpr Foo1 any {0}; static constexpr Foo1 one {1&lt;&lt;1}; static constexpr Foo1 two {1&lt;&lt;2}; }; </code></pre> <p>This is what I currently have file.pxd</p> <pre><code>cdef extern from "../MFoo.hpp": cdef cppclass MFoo: pass cdef extern from "../header.hpp": cdef cppclass Foo1(MFoo): pass cdef extern from "../header.hpp": cdef cppclass Foo: ###@staticmethod Foo1 _any "Foo::any" Foo1 _one "Foo::one" Foo1 _two "Foo::two" ###any=_any ### I also need to link my cpp definitions of any,one and two ###to cython file but I am facing Error:Python object cannot be declared extern </code></pre> <p>My file.pyx</p> <pre><code>def Bar(self,PyFoo1 abc) return file.Bar(######) # how would I call something like Foo::one </code></pre> <p>I need to know how to wrap this in cython. I am using <a href="https://stackoverflow.com/questions/25181964/how-to-expose-a-constexpr-to-cython">How to expose a constexpr to Cython?</a> which is similar but still not very useful</p>
<p>Your main issue is that Cython doesn't provide a way to express C++ static member variables. To solve this you can put them at the global scope and use strings to ensure that the correct C++ code is generated. The <code>constexpr</code> is irrelevant - Cython doesn't need to know about it.</p> <p>I've created a minimal example that's slightly simplified from yours (it omits the irrelevant template class that you don't provide a definition for, for example):</p> <pre><code>class C { public: constexpr C(unsigned int) {} }; class D { public: static constexpr C any {0}; static constexpr C one {1&lt;&lt;1}; static constexpr C two {1&lt;&lt;2}; }; inline void bar(const C&amp;) {} </code></pre> <p>and in cython:</p> <pre><code>cdef extern from "whatever.hpp": cdef cppclass C: pass cdef cppclass D: pass C any "D::any" C one "D::one" C two "D::two" void bar(const C&amp;) </code></pre> <p>Notice that I don't put <code>any</code>, <code>one</code> and <code>two</code> inside <code>D</code>, but ensure that the strings create C++ code <code>D::any</code> etc.</p> <hr> <p>I think there's a second question about how to call <code>bar</code> from Python. There's obviously a number of options but an easy way would be to pass a string, and have a Cython function that matches the string to the C++ value:</p> <pre><code># except NULL allows Cython to signal an error to the calling function cdef const C* get_C_instance(s) except NULL: if s=="any": return &amp;any elif s=="one": return &amp;one elif s=="two": return &amp;two raise ValueError("Unrecognised string {0}".format(s)) def py_bar(s): return bar(get_C_instance(s)[0]) </code></pre> <p>This isn't the only solution for creating a Python interface - you could create a wrapper class that holds a <code>C</code> and have instances of it called <code>any</code>, <code>one</code>, <code>two</code> for example.</p>
python|c++|static|cython|constexpr
2
1,904,868
46,815,586
Replace NULL and blank values in all Data Frame columns with the most frequent Non Null item of the respective columns
<p>I am a novice to Python - I am trying to replace NULL and blank ('') values occurring in a column of a Pandas data frame with the most frequent item in that column. But I need to be able to do it for all columns and all rows of the data frame. I have written the following code - But it takes a lot of time to execute. Can you please help me optimize?</p> <p>Thanks Saptarshi</p> <pre><code>for column in df: #Get the value and frequency from the column tempDict = df[column].value_counts().to_dict() #pop the entries for 'NULL' and '?' tempDict.pop(b'NULL',None) tempDict.pop(b'?',None) #identify the max item of the remaining set maxItem = max(tempDict) #The next step is to replace all rows where '?' or 'null' appears with maxItem #df_test[column] = df_test[column].str.replace(b'NULL', maxItem) #df_test[column] = df_test[column].str.replace(b'?', maxItem) df[column][df[column] == b'NULL'] = maxItem df[column][df[column] == b'?'] = maxItem </code></pre>
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mode.html" rel="nofollow noreferrer"><code>mode()</code></a> to find the most common value in each column:</p> <pre><code>for val in ['', 'NULL', '?']: df.replace(val, df.mode().iloc[0]) </code></pre> <p>Because there may be multiple modal values, <code>mode()</code> returns a dataframe. Using <code>.iloc[0]</code> takes first value from that dataframe. You can use <code>fillna()</code> instead of <code>replace()</code> as @Wen does if you also want to convert <code>NaN</code> values.</p>
python|pandas
0
1,904,869
65,639,511
SystemError: <built-in function imread> returned NULL without setting an error (tkinter)
<p>I am using my keras model to detect 2 categories using a modified tkinter program to that classifies butterfly species.</p> <pre><code>import tkinter as tk from tkinter import filedialog from tkinter import * from PIL import ImageTk, Image import numpy import cv2 import tensorflow as tf model = tf.keras.models.load_model(&quot;64x300-CNN.model&quot;) classes = [&quot;real&quot;, &quot;fake&quot;] top=tk.Tk() top.geometry('800x600') top.title('Butterfly Classification') top.configure(background='#CDCDCD') label=Label(top,background='#CDCDCD', font=('arial',15,'bold')) sign_image = Label(top) def prepare(filepath): IMG_SIZE = 50 # 50 in txt-based img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) # read in the image, convert to grayscale new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize image to match model's expected sizing return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1) # return the image with shaping that TF wants. def classify(file_path): global label_packed new_array = cv2.imread(file_path, 1) pred = model.predict([prepare(new_array)]) sign = classes[pred] print(sign) label.configure(foreground='#011638', text=sign) def show_classify_button(file_path): classify_b=Button(top,text=&quot;Classify Image&quot;, command=lambda: classify(file_path),padx=10,pady=5) classify_b.configure(background='#364156', foreground='white', font=('arial',10,'bold')) classify_b.place(relx=0.79,rely=0.46) def upload_image(): try: file_path=filedialog.askopenfilename() uploaded=Image.open(file_path) uploaded.thumbnail(((top.winfo_width()/2.25), (top.winfo_height()/2.25))) im=ImageTk.PhotoImage(uploaded) sign_image.configure(image=im) sign_image.image=im label.configure(text='') show_classify_button(file_path) except: pass upload=Button(top,text=&quot;Upload an image&quot;,command=upload_image, padx=10,pady=5) upload.configure(background='#364156', foreground='white', font=('arial',10,'bold')) upload.pack(side=BOTTOM,pady=50) sign_image.pack(side=BOTTOM,expand=True) label.pack(side=BOTTOM,expand=True) heading = Label(top, text=&quot;Butterfly Classification&quot;,pady=20, font=('arial',20,'bold')) heading.configure(background='#CDCDCD',foreground='#364156') heading.pack() top.mainloop() </code></pre> <p>and got this error</p> <blockquote> <p>SystemError: returned NULL without setting an error</p> </blockquote> <p>I have tried a fix from a similar question asked here but with no luck I think there is a problem when importing the image through tkinter and not through a file path?</p> <blockquote> <p><a href="https://stackoverflow.com/questions/58123915/using-cv2-imread-built-in-function-imread-returned-null-without-setting-an-e">Using cv2.imread: &quot;&lt;built-in function imread&gt; returned NULL without setting an error&quot;, as if it can&#39;t open the picture or get the data</a></p> </blockquote> <p>full error message</p> <blockquote> <p>Exception in Tkinter callback Traceback (most recent call last):<br /> File &quot;C:\Users\1rock\anaconda3\envs\machL\lib\tkinter_<em>init</em>_.py&quot;, line 1883, in <strong>call</strong> return self.func(*args) File &quot;C:/Users/1rock/anaconda3/envs/machL/fly.py&quot;, line 36, in command=lambda: classify(file_path),padx=10,pady=5) File &quot;C:/Users/1rock/anaconda3/envs/machL/fly.py&quot;, line 29, in classify pred = model.predict([prepare(new_array)]) File &quot;C:/Users/1rock/anaconda3/envs/machL/fly.py&quot;, line 22, in prepare img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) # read in the image, convert to grayscale SystemError: returned NULL without setting an error</p> <p>Process finished with exit code 0</p> </blockquote>
<p>The prepare function you implemented does the process of loading, resizing, reshaping images. The purpose of the function <code>cv2.imread</code> is to open an image from a given file path. But you fed the function <code>prepare(new_array)</code> where <code>new_array</code> is already the image itself, not the file path. I suggest two fixes, although both are conclusively equal.</p> <p>Also, <code>model.predict</code> outputs the final layer in real numbers instead of integer-type class number. Therefore you must use <code>model.predict_classes</code> in this case. Also, because these functions default to batch mode, although you only feed a single image, you must assume the prediction to be an array, and index it.</p> <p>First fix is to feed the file path and load the image inside the <code>prepare</code> function.</p> <pre><code>def prepare(filepath): IMG_SIZE = 50 # 50 in txt-based img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) # read in the image, convert to grayscale new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize image to match model's expected sizing return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1) # return the image with shaping that TF wants. def classify(file_path): global label_packed pred = model.predict_classes([prepare(file_path)]) sign = classes[pred[0,0]] print(sign) label.configure(foreground='#011638', text=sign) </code></pre> <p>Next is to perform only reshaping in the <code>prepare</code> function.</p> <pre><code>def prepare(img_array): IMG_SIZE = 50 # 50 in txt-based new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize image to match model's expected sizing return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1) # return the image with shaping that TF wants. def classify(file_path): global label_packed new_array = cv2.imread(file_path, 1) pred = model.predict_classes([prepare(new_array)]) sign = classes[pred[0,0]] print(sign) label.configure(foreground='#011638', text=sign) </code></pre> <p>I would also like to say that this type of resizing process is very inefficient. What would be a solution for an input pipeline is the preprocessing layers developed inside Tensorflow. You can create a model acting as an input pipeline.</p> <pre><code>input_pipeline=tf.keras.models.Sequential([ tf.keras.layers.experimental.preprocessing.Resizing(h,w,..), tf.keras.layers.experimental.preprocessing... ]) ... new_array=input_pipeline.predict(img_array) </code></pre> <p>or use <code>tf.image.resize</code>, since they can processes batches of images without an explicit loop, and provides more features that can be applied simply.</p>
python|tkinter|keras
1
1,904,870
36,878,018
List of points and find the closest points trouble
<p>So I am running into some trouble trying to debug this piece of code. I have a list of numbers, say [4,5,7,3,5,2,3] and I am required to find the two points who are closest together, so in this case, 3 and 3 since their difference is zero. However, it is not returning the correct output. It works if a number is not repeated in a list, but won't work if the a number appears more than once.</p> <pre><code> def closest1(num_list): if len(num_list) &lt; 2: return (None, None) else: diff = max(num_list), min(num_list) for element in num_list: for sec_element in num_list: if sec_element == element: continue if abs(sec_element - element) &lt; abs(diff[0] - diff[1]): diff = sec_element, element return diff </code></pre>
<p>Only one loop is necessary if you sort first:</p> <pre><code>def closest1(num_list): num_list = sorted(num_list) diff = num_list[0] - num_list[-1] diff_dict = {"num1":diff, "num2":diff, "diff":diff} for pos, val in enumerate(num_list[:-1]): diff = abs(num_list[pos+1] - val) if diff &lt; diff_dict["diff"]: diff_dict = {"num1":num_list[pos+1], "num2":val, "diff":diff} return diff_dict </code></pre>
python|python-2.7|for-loop|closest-points
0
1,904,871
48,858,449
Flask-SQLAlchemy fails to update data in while in thread
<p>I am building an app where users will occasionally initiate a longer-running process. While running, the process will commit updates to a database entry.</p> <p>Since the process takes some time, I am using the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow noreferrer">threading</a> module to execute it. But values updated while in the thread are never actually committed.</p> <p>An example:</p> <pre><code>from flask import Flask, url_for, redirect from flask_sqlalchemy import SQLAlchemy import time, threading, os if os.path.exists('test.db'): os.remove('test.db') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) class Item(db.Model): id = db.Column(db.Integer, primary_key=True) value = db.Column(db.Integer) def __init__(self, value): self.value = value db.create_all() item = Item(1) db.session.add(item) db.session.commit() @app.route('/go', methods=['GET']) def go(): def fun(item): time.sleep(2) item.value += 1 db.session.commit() thr = threading.Thread(target=fun, args=(item,)) # thr.daemon = True thr.start() return redirect(url_for('view')) @app.route('/view', methods=['GET']) def view(): return str(Item.query.get(1).value) app.run(host='0.0.0.0', port=8080, debug=True) </code></pre> <p>My expectation was that the item's value would be asynchronously updated after two seconds (when the <code>fun</code> completes), and that additional requests to <code>/view</code> would reveal the updated value. But this never occurs. I am not an expert on what is going on in the threading module; am I missing something?</p> <p>I have tried setting <code>thr.daemon=True</code> as pointed out in some posts; but that is not it. The closest SO post I have found is <a href="https://stackoverflow.com/questions/41580029/using-flask-sqlalchemy-from-worker-threads">this one</a>; that question does not have a minimal and verifiable example and has not been answered.</p>
<p>I guess this is due to the fact that sessions are local threaded, as mentioned in <a href="https://docs.sqlalchemy.org/en/13/orm/contextual.html#thread-local-scope" rel="nofollow noreferrer">the documentation</a>. In your case, <em>item</em> was created in one thread and then passed to a new thread to be modified directly.</p> <p>You can either use scoped sessions as suggested in the documentation, or simply change your URI config to bypass this behavior:</p> <pre><code>app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db?check_same_thread=False' </code></pre>
python|multithreading|flask|sqlalchemy|flask-sqlalchemy
4
1,904,872
66,943,847
How to use a bar chart as a "thermometer"?
<p>I created a Python script to extract sentiment in comments. Now I want to represent the general sentiment with three steps : negative, neutral and positive. I want to use a bar chart but with only one bar to act as a thermometer (the higher the bar is, the better the comments were) but I'm a bit stuck.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np # Bar chart fig = plt.figure() ax = fig.add_axes([0,0,1,1]) emotion = ['Negative', 'Neutral', 'Positive'] percentage = [23,17,60] width = 0.35 ax.bar(emotion,percentage) ax.set_ylabel('Positivity') ax.set_title('General emotion in comments') # here it's wrong but I don't know how to perform what I want ax.bar(1, percentage[0], width, color='r') ax.bar(1, percentage[1], width, color='b') ax.bar(1, percentage[2], width, color='g') ############################################### ax.set_yticks(np.arange(-100, 100, 10)) plt.show() </code></pre> <p>In this case I have hardcoded that the comments were 23% negative, 17% neutral and 60% positive but I can't figure out how:</p> <ul> <li>to print the axis informations (here Positivity)</li> <li>use my <code>percentage</code> to draw the bar because at the moment I have three kind of bar but I want one bar</li> </ul> <p>The bar chart I want to create is like this :</p> <p><a href="https://i.stack.imgur.com/ezk8y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ezk8y.png" alt="enter image description here" /></a></p> <p>Thank you for the help</p> <p>[EDIT]</p> <p>Ok I changed a bit the code :</p> <pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots(figsize=(12, 6)) emotion = ['Negative', 'Neutral', 'Positive'] percentage = [-23,17,60] plt.title('General emotion in comments') plt.xlabel(' ') plt.ylabel('Positivity') plt.ylim([-100, 100]) ax.bar(2, percentage[2], width=0.35, color='g') ax.bar(2, percentage[0], width=0.35, color='r') plt.show() </code></pre>
<p>After all the help I came out with</p> <pre class="lang-py prettyprint-override"><code>x = 1 fig, ax = plt.subplots(figsize=(12, 6)) emotion = ['Negative', 'Neutral', 'Positive'] percentage = [-23,17,60] plt.title('General emotion') plt.ylabel('Positivity') plt.ylim([-100, 100]) ax.set_xlim(0,3) plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) ax.bar(x, percentage[2], width=0.35, color='g') ax.bar(x, percentage[0], width=0.35, color='r') plt.show() </code></pre>
python|matplotlib|bar-chart
0
1,904,873
4,139,201
How to determine if an HTTP request is asynchronous in Python or Pylons
<p>I can't help but think that this is a duplicate, but if it is, I can't seem to find the doppelganger.</p> <p>I'm just starting to learn Python (focusing on Pylons) and I'd like to know if there is a way to determine if a call to a controller is done asynchronously or not. In PHP it would look something like this:</p> <pre><code>function isAjax() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; } </code></pre> <p>Is there one that works well for all of Python, or is there perhaps one that works very well only in Pylons?</p> <p>Thanks in advance!</p>
<p>To directly translate that code to python using pylons you would do something along the lines of:</p> <pre><code>def isAjax(request): return request.environ.get('HTTP_X_REQUEST_WITH') == 'XMLHttpRequest' </code></pre> <p>where request is the request object passed to the controller.</p>
python|pylons
4
1,904,874
51,264,267
Writing text in multiline in python
<p>I am working on a text editor. The only challenge left for me is to write text in next line when text width(written) exceeded from its maximum size(window). Any help will be appreciated. I have a class photo viewer that controls text font, size etc.Thanks in advance</p> <pre><code>class PhotoViewer(QtWidgets.QGraphicsView): photoClicked = QtCore.pyqtSignal(QtCore.QPoint) def __init__(self, parent): super(PhotoViewer, self).__init__(parent) self._zoom = 0 self._empty = True self._scene = QtWidgets.QGraphicsScene(self) self._photo = QtWidgets.QGraphicsPixmapItem() self._textLayer = QtWidgets.QGraphicsSimpleTextItem () self._scene.addItem(self._photo) self._scene.addItem(self._textLayer) self.setScene(self._scene) self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(80, 30, 30))) self.setFrameShape(QtWidgets.QFrame.NoFrame) self._textLayer.setFlags(QGraphicsItem.ItemIsMovable) def updateText(self,text,font_size=50): # Load the font: font_db = QFontDatabase() font_id = font_db.addApplicationFont("fonts/Summer's Victory Over Spring - TTF.ttf") #families = font_db.applicationFontFamilies(font_id) #print (families) myFont = QFont("Summers Victory Over Spring") myFont.setPixelSize(font_size*1.5) self._textLayer.setFont(myFont) self._textLayer.setText(text) class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() self.viewer = PhotoViewer(self) # 'Load image' button # Button to change from drag/pan to getting pixel info self.btnPixInfo = QtWidgets.QToolButton(self) self.btnPixInfo.setText('Create Text') self.btnPixInfo.clicked.connect(self.loadText) self.fontSize =QtWidgets.QSpinBox() self.fontSize.valueChanged.connect(self.loadText) self.editPixInfo = QtWidgets.QLineEdit(self) #self.editPixInfo.setReadOnly(True) self.viewer.photoClicked.connect(self.photoClicked) # Arrange layout VBlayout = QtWidgets.QVBoxLayout(self) HBlayout = QtWidgets.QHBoxLayout() HBlayout.setAlignment(QtCore.Qt.AlignLeft) HBlayout.addWidget(self.btnPixInfo) HBlayout.addWidget(self.editPixInfo) VBlayout.addLayout(HBlayout) VBlayout.addWidget(self.viewer) HBlayout.addWidget(self.fontSize) self.editPixInfo.setText("Sheeda") self.fontSize.setValue(20) self.loadText() self.frame = QFrame() self.frame.setFrameStyle(QFrame.StyledPanel) self.frame.setLineWidth(20) def loadText(self): #self.viewer.toggleDragMode() self.viewer.updateText(self.editPixInfo.text(),self.fontSize.value()) def photoClicked(self, pos): if self.viewer.dragMode() == QtWidgets.QGraphicsView.NoDrag: self.editPixInfo.setText('%d, %d' % (pos.x(), pos.y())) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) window = Window() window.setGeometry(500, 300, 800, 600) window.show() sys.exit(app.exec_()) </code></pre> <p>Here is my code so far.</p>
<p>I see, you are using <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qgraphicssimpletextitem.html" rel="nofollow noreferrer">QGraphicsSimpleTextItem</a> where as your easiest bet is to use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qgraphicstextitem.html" rel="nofollow noreferrer">QGraphicsTextItem</a>. Reason being, later offers a <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qgraphicstextitem.html#setTextWidth" rel="nofollow noreferrer">setTextWidth</a> method,defauls to -1. Just set this to your 'maximumSize' limit. also,you have to update your "setText" call to "setPlainText" call as per QGraphicsTextItem Docs.</p>
python|pyqt|pyqt5
1
1,904,875
51,350,349
What's the most Pythonic way to find a matching value for any key in a dictionary?
<p>Here is my dictionary structure:</p> <pre><code>{ "432701228292636694" : { "432739261603905537" : { "channels" : { "LoL Duos" : { "capacity" : 2, "rooms" : [ "432741328477093889" ] }, "LoL Quads" : { "capacity" : 4, "rooms" : [ "432741635852599297" ] }, "LoL Teams" : { "capacity" : 5, "rooms" : [ "467708831695110154" ] }, "LoL Trios" : { "capacity" : 3, "rooms" : [ "432741537890304030", "468096902055985152" ] } }, "perms" : { "453625621604728839" : { "read_messages" : false }, "461654834689474560" : { "read_messages" : false } } }, "432739461475074049" : { "channels" : { "FN Duos" : { "capacity" : 2, "rooms" : [ "432740789660155904" ] }, "FN Squads" : { "capacity" : 4, "rooms" : [ "432740857268142081" ] }, "FN Trios" : { "capacity" : 3, "rooms" : [ "467707010746417172" ] } }, "perms" : { "453625621604728839" : { "read_messages" : false }, "461654872815697931" : { "read_messages" : false } } }, "436634548051378186" : { "channels" : { "OW Duos" : { "capacity" : 2, "rooms" : [ "436636544229441567" ] }, "OW Quads" : { "capacity" : 4, "rooms" : [ "436636615167705089" ] }, "OW Teams" : { "capacity" : 5, "rooms" : [ "467707823954984971" ] }, "OW Trios" : { "capacity" : 3, "rooms" : [ "436636575036866570" ] } }, "perms" : { "453625621604728839" : { "read_messages" : false }, "461654908329000972" : { "read_messages" : false } } } } } </code></pre> <p>What I'm wanting to do is check if a string matches any of the values of any <code>rooms</code>. I've found a really messy way to do it like this:</p> <pre><code> for category_id in self.gaming_db[server.id]: channel_names = self.gaming_db[server.id][category_id]['channels'] for channel_name in channel_names: room_ids.extend([server.get_channel(x) for x in self.gaming_db[server.id][category_id]['channels'][channel_name]['rooms']]) </code></pre> <p>This is if you assume <code>self.gaming_db</code> is this dictionary. Is there a more Pythonic way to do this? I think it has something to do with list comprehensions using lambda? I really don't understand that much so far.</p>
<p>You can use recursion:</p> <pre><code>import json def search(d, _search, _key='rooms'): return any(search(b, _search) if isinstance(b, dict) else _search in [[], b][a== _key] for a, b in d.items()) print(search(json.loads(source_dict), '436636544229441567')) </code></pre> <p>Output:</p> <pre><code>True </code></pre>
python|dictionary|list-comprehension|dictionary-comprehension
0
1,904,876
17,632,977
Audio sniffing in python?
<p>I was wondering if there was a way to "sniff" the music that is going out to the local computers' speakers. I was hoping to do this in python because I want to port it over to the raspberry pi, although it isn't strictly required.</p> <p>The idea is basically have something you run that is totally separate from your music player. So it wouldn't launch the music file, just look at the stream going from the other program to the computers speakers and act on it. </p> <p>P.S. python please :)</p>
<p>PyAudio is a good tool for audio manipulation in Python. This person: <a href="https://stackoverflow.com/questions/2046663/record-output-sound-in-python">record output sound in python</a> was able to record sound output from their computer with PyAudio without access to the original file.</p>
c++|python|audio
3
1,904,877
64,427,278
Django REST Framework, only Admin can DELETE or PUT
<p>I'd like to ask how I can control object permissions within Django Rest Framework with the effect that:</p> <ul> <li><code>User</code> has no ability to <code>DELETE</code> nor <code>PUT</code></li> <li><code>Admin</code> is a <code>User</code> that also can <code>DELETE</code> and <code>PUT</code></li> <li>In order access API / <code>SAFE_METHODS</code> <code>User</code> must be <code>Authenticated</code></li> </ul> <p>I have tried standard permissions, such as <code>permissions.IsAdminUser</code> and <code>IsAuthenticatedOrReadOnly</code>, but no match.</p> <p>Is there a standard Permission to achieve below? If not, what is the best next step, to control permissions via Django models or via DRF?</p> <pre><code>| API end-points | HTTP Method | Authenticate | Permissions | Result | |---------------------- |------------- |------------ |------------ |------------------------------------------ | | /products | GET | User | User | List of product | | /products | POST | User | User | Create new product | | /products/{product_pk}| GET | User | User | Retrieve details of particular product | | /products/{product_pk}| PUT | Admin | Admin | Fully update particular product's info | | /products/{product_pk}| PATCH | User | User | Partially update particular product's info | | /products/{product_pk}| DELETE | Admin | Admin | Delete particular product's details from DB | </code></pre> <p>Serializers.py</p> <pre><code>class ProductSerializer(HyperlinkedModelSerializer): class Meta: model = Product fields = '__all__' </code></pre> <p>views.py</p> <pre><code>class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer authentication_classes = [authentication.SessionAuthentication, authentication.TokenAuthentication] permission_classes = (permissions.IsAdminUser,) </code></pre> <p>urls.py</p> <pre><code>router_v1 = routers.DefaultRouter() router_v1.register('products', ProductView) urlpatterns = [ path('v1/', include(router_v1.urls)), path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'), path('api-auth/', include('rest_framework.urls')) ] </code></pre>
<p>Override the <strong><code>get_permissions(...)</code></strong> method as</p> <pre><code>class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer authentication_classes = [authentication.SessionAuthentication, authentication.TokenAuthentication] <strike>permission_classes = (permissions.IsAdminUser,)</strike> <b>def get_permissions(self): if self.request.method in ['PUT', 'DELETE']: return [permissions.IsAdminUser()] return [permissions.IsAuthenticated()]</b></code></pre>
python|django|rest|django-rest-framework
7
1,904,878
64,405,461
Keras AttributeError: 'Functional' object has no attribute 'shape'
<p>Trying to add Densenet121 functional block to the model. I need Keras model to be written in this format, not using</p> <pre><code>model=Sequential() model.add() </code></pre> <p>method What's wrong the function, build_img_encod</p> <pre><code>--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-62-69dd207148e0&gt; in &lt;module&gt;() ----&gt; 1 x = build_img_encod() 3 frames /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name) 164 spec.min_ndim is not None or 165 spec.max_ndim is not None): --&gt; 166 if x.shape.ndims is None: 167 raise ValueError('Input ' + str(input_index) + ' of layer ' + 168 layer_name + ' is incompatible with the layer: ' AttributeError: 'Functional' object has no attribute 'shape' </code></pre> <pre><code>def build_img_encod( ): base_model = DenseNet121(input_shape=(150,150,3), include_top=False, weights='imagenet') for layer in base_model.layers: layer.trainable = False flatten = Flatten(name=&quot;flatten&quot;)(base_model) img_dense_encoder = Dense(1024, activation='relu',name=&quot;img_dense_encoder&quot;, kernel_regularizer=regularizers.l2(0.0001))(flatten) model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder) return model </code></pre>
<p>The reason why you get that error is that you need to provide the <code>input_shape</code> of the <code>base_model</code>, instead of the <code>base_model</code> per say.</p> <p>Replace this line: <code>model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)</code></p> <p>with: <code>model = keras.models.Model(inputs=base_model.input, outputs = img_dense_encoder)</code></p>
tensorflow|keras|deep-learning|transfer-learning
3
1,904,879
64,348,977
PyQt5 TypeError for openPersitentEditor
<p>Hi everyone so I was doing some exam prep with PYQT5 and I created an application from an exercise in my workbook where we have to make it display a list of courses and when you click them it opens a message box with the course name also there is a button so that the user can add a course to the list. The add button is suppoused to open a QlineEdit on the last item in the listWidget, so the user can edit the field however I keep getting a TypeError message:</p> <p>line 67, in onAddButton self.mylistWidget.openPersistentEditor(self, modelItem) TypeError: openPersistentEditor(self, QListWidgetItem): argument 1 has unexpected type 'UNISACourses'</p> <pre><code>import sys from PyQt5.QtWidgets import (QListWidget, QLineEdit, QWidget, QMessageBox, QHBoxLayout, QAbstractItemView, QApplication, QVBoxLayout, QPushButton, QButtonGroup) from PyQt5.QtCore import pyqtSlot from PyQt5 import Qt, QtGui class MyListWidget(QListWidget, QLineEdit, QWidget): &quot;&quot;&quot; Subclassed QListWidget to allow for the closing of open editors and other modifications &quot;&quot;&quot; def __init__(self, parent=None): super().__init__(parent=parent) self.setSelectionMode(QAbstractItemView.ExtendedSelection) def keyPressEvent(self, event): if event.key() == Qt.Key_Return: print(&quot;Closing any persistent editor&quot;) self.closePersistentEditor(self.model().index(self.count() - 1)) else: super().keyPressEvent(event) class UNISACourses(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # Main Window Settings self.setGeometry(300, 300, 350, 250) self.setWindowTitle('Courses') # Layout self.main_layout = QVBoxLayout(self) self.setLayout(self.main_layout) # Main Widget self.mylistWidget = MyListWidget() self.mylistWidget.addItems([&quot;COS1511&quot;, &quot;COS1521&quot;, &quot;COS1512&quot;, &quot;MNB1512&quot;, &quot;INF1505&quot;, &quot;FAC1502&quot;]) self.main_layout.addWidget(self.mylistWidget) # Define a layout for the other buttons to exist in for flexibility with resizing self.btn_add = QPushButton(&quot;Add&quot;, clicked=self.onAddButton) self.btn_delete = QPushButton(&quot;Delete&quot;, clicked=self.onDeleteButton) hbox = QHBoxLayout() hbox.addWidget(self.btn_add) hbox.addWidget(self.btn_delete) self.main_layout.addLayout(hbox) # Define any additional behavior of the list self.mylistWidget.itemDoubleClicked.connect(self.onClicked) def onClicked(self, item): QMessageBox.information(self, &quot;Info&quot;, item.text()) @pyqtSlot() def onAddButton(self): &quot;&quot;&quot; Opens a QLineEdit editor on the last item in the listwidget, allowing the user to edit the field. NOTE: The user must click outside of the editor field then press Enter in order to close the editor &quot;&quot;&quot; self.mylistWidget.addItem('') modelItem = self.mylistWidget.model().index(self.mylistWidget.count() - 1) self.mylistWidget.openPersistentEditor(self, modelItem) @pyqtSlot() def onDeleteButton(self): for item in self.mylistWidget.selectedItems(): self.mylistWidget.takeItem(self.mylistWidget.row(item)) if __name__ == '__main__': app = QApplication(sys.argv) ex = UNISACourses() ex.show() sys.exit(app.exec_()) </code></pre>
<p>You are passing two incorrect arguments (<code>self</code> and a QModelIndex) to <code>QListWidget.openPersistentEditor</code> which accepts <em>one</em> QListWidgetItem. Use the <code>QListWidget.item</code> method to get the item. You can also add <code>QListWidget.setCurrentItem</code> so it gets selected right away and ready to edit.</p> <pre><code>def onAddButton(self): self.mylistWidget.addItem('') modelItem = self.mylistWidget.item(self.mylistWidget.count() - 1) self.mylistWidget.openPersistentEditor(modelItem) self.mylistWidget.setCurrentItem(modelItem) </code></pre> <p>Same fix here:</p> <pre><code>def keyPressEvent(self, event): if event.key() == Qt.Key_Return: print(&quot;Closing any persistent editor&quot;) self.closePersistentEditor(self.item(self.count() - 1)) else: super().keyPressEvent(event) </code></pre> <p>Also the Qt Namespace class for <code>Qt.Key_Return</code> is inside the QtCore Module.</p> <pre><code>from PyQt5.QtCore import pyqtSlot, Qt from PyQt5 import QtGui </code></pre>
python|pyqt|pyqt5|qlistwidget|qlistwidgetitem
0
1,904,880
70,523,397
How to correctly arrange data for keras.model.fit()
<p>I'm working in a neural network using keras (from tensorflow) for a college project. I'm pretty new to the library, so I don't really know how should I feed the data into the model in order for the training to work. I've been searching the internet for hours and I can't find a proper tutorial / documentation on how to do it.</p> <p>Here's the model I'm using, one of the simplest possible ones:</p> <pre><code>model = keras.Sequential([ keras.layers.Dense(20, input_dim=1,activation = activations.relu), keras.layers.Dense(10, activation= activations.relu), keras.layers.Dense(8, activation= activations.sigmoid) ]) model.compile(optimizer = &quot;adam&quot;, loss = &quot;sparse_categorical_crossentropy&quot;, metrics = [&quot;accuracy&quot;]) </code></pre> <p>The input to the network is a list of 20 floats, and the output a list of 8 floats ranged from 0 to 1 (confidence level), so I think this model is OK, please let me know if I'm wrong.</p> <p>Here's a diagram of the model i'm trying to build and train: <a href="https://i.stack.imgur.com/KOEdv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KOEdv.png" alt="network" /></a></p> <p>Let's say I have:</p> <ul> <li>10 input examples (10 lists of 20 floats) for the expected output [1,0,0,0,0,0,0,0]</li> <li>10 input examples for the expect output [0,1,0,0,0,0,0,0,0,0]</li> <li>...</li> <li>10 input examples for the expected output [0,0,0,0,0,0,0,1]</li> </ul> <p>How should I prepare this data in order to use it with</p> <p><code>model.fit(training_inputs,expected_outputs,epochs = NUM_EPOCHS)</code> ?</p> <p>What should training_inputs exactly be? and expected_outputs?</p> <p>Any help will be appreciated. Thank you for your time!</p>
<p>First of all, you have two issues in your model. According to your description, your input data is 20-dimensional, so in the first layer you should have <code>input_dim=20</code>. Then, you have a cross-entropy loss, so I'm assuming that you are training a 8-class classifier. If that's the case, then instead of <code>keras.layers.Dense(8, activation= activations.sigmoid)</code> you should use</p> <pre><code>keras.layers.Dense(8, activation=None), keras.layers.Softmax() </code></pre> <p>as that ensures that you get a distribution over classes for each input data point.</p> <p>Now regarding your input data question, <code>training_inputs</code> should a tensor (or numpy array, which will be readily converted) with shape <code>(n_points, 20)</code> in your case. Accordingly, <code>expected_outputs</code> should have shape <code>(n_points, 8)</code>. So, just concatenate/stack your input data along the first dimension (<code>axis=0</code>), such that each row corresponds to your 20-dimensional data points. You do the same for <code>expected_outputs</code>, maybe something like,</p> <pre><code>expected_outputs = np.r_[ np.tile([[1,0,0,0,0,0,0,0]], (10, 1)), np.tile([[0,1,0,0,0,0,0,0]], (10, 1)), ... np.tile([[0,0,0,0,0,0,0,1]], (10, 1)), ] </code></pre> <p>Remember to set <code>batch_size</code> and <code>shuffle</code>!</p>
python|tensorflow|keras
2
1,904,881
55,593,177
Viewing the text inside Pyspark object
<p>I am able to load an log file using the following command:</p> <pre><code>logFile = sc.textFile("/resources/jupyterlab/labs/BD0211EN/LabData/notebook.log") </code></pre> <p>But when I try to see the <code>log</code> file contents, I am not able to do. I checked <code>dir(logFile)</code>, but I am not able to see the content inside. Now when I run the code in the Jupyter cell, I get the following:</p> <pre><code>/resources/jupyterlab/labs/BD0211EN/LabData/notebook.log MapPartitionsRDD[1] at textFile at NativeMethodAccessorImpl.java:0 </code></pre> <p>Is it possible to see the contents of the log file?</p> <p>Thanks</p>
<p>I guess what you need is the following:</p> <pre><code>logFile.collect() </code></pre> <p>This will show you the content's that are split line wise.</p>
python|python-3.x|pyspark
0
1,904,882
66,598,177
If statement not working despite having triggered the appropriate boolean value | Python
<p>I want to get this if statement to execute when <code>good_view_list</code> is <code>True</code>, I'm aware that it's a list but whenever I print out its boolean it gives me a <code>True</code> value (I'm assuming because there are strings inside), why then doesn't this <code>if good_view_time is True:</code> if statement work if <code>good_view_time</code> is in fact <code>True</code>.</p> <p>I'm aware of other alternatives, just want to know why THIS one doesn't work.</p> <pre><code>good_view_time = ['https://www.instagram.com/p/CKmTcvmHYkY/', 'https://www.instagram.com/p/CKcOxtlHJsy/' , 'https://www.instagram.com/p/CKpHBAcHkhl/'] #returns True print(bool(good_view_time)) if good_view_time is True: for post in good_view_time: print(post) </code></pre>
<p><code>bool(good_view_time)</code> returns <code>True</code>, but <code>good_view_time</code> itself is a list, it can't be <em>literally</em> <code>True</code>. <code>good_view_time</code> is <em>not</em> <code>True</code>, but converting it to Boolean gives True because non-empty lists are truthy. In the same vein, <code>bool(&quot;Hello&quot;) is True</code>, but the string <code>&quot;Hello&quot;</code> itself is most definitely not equal to True (why would it be? It's a string!), nor is it exactly equivalent to <code>True</code> as the <code>is</code> operator would check.</p> <p>So, you should be comparing:</p> <pre><code>if bool(good_view_time) is True: </code></pre> <p>Or, which is equivalent:</p> <pre><code>if good_view_time: </code></pre>
python|python-3.x|list
2
1,904,883
64,726,804
How to end an edit session with QPlainTextEdit editor?
<p>Here's an MRE:</p> <pre><code>from PyQt5.QtCore import QRect, Qt, QAbstractTableModel from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QWidget, QVBoxLayout, QStyledItemDelegate, QPlainTextEdit, QShortcut import sys, types from PyQt5.QtGui import QFont class HistoryTableViewDelegate( QStyledItemDelegate ): def __init__( self, history_table_view ): super().__init__( history_table_view ) def createEditor(self, parent, option, index): editor = QPlainTextEdit( parent ) editor.setSizeAdjustPolicy( QPlainTextEdit.SizeAdjustPolicy.AdjustToContents ) self.model = index.model() column = index.column() row = index.row() parent.parent().verticalHeader().resizeSection( row, 150 ) parent_font = QFont( self.parent().font() ) parent_font.setPointSize( self.parent().font().pointSize() ) editor.setFont( parent_font ) def end_edit(): print( f'end edit...') self.setModelData( editor, self.model, index ) # how to end the edit session programmatically at this point? # self.destroyEditor( editor, index ) end_edit_shortcut = QShortcut( 'Alt+E', editor, context = Qt.ShortcutContext.WidgetShortcut ) end_edit_shortcut.activated.connect( end_edit ) return editor def setEditorData(self, editor, index ): # NB superclass method sets the editor's text to empty string... self.original_text = index.model().data( index, Qt.DisplayRole ) editor.insertPlainText( str( self.original_text ) ) class HistoryTableModel( QAbstractTableModel ): def __init__( self ): super(HistoryTableModel, self).__init__() data = [ [4, 9, 2], [1, 0, 0], [3, 5, 0], ] self._data = data def data(self, index, role): if role == Qt.DisplayRole: return self._data[index.row()][index.column()] def rowCount(self, index): return len(self._data) def columnCount(self, index): return len(self._data[0]) def flags(self, index): return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable def setData(self, index, value, role ): if role == Qt.EditRole: self._data[ index.row() ][ index.column() ] = value return True class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.resize(600, 700 ) self.centralwidget = QWidget(MainWindow) self.verticalLayoutWidget = QWidget(self.centralwidget) self.verticalLayoutWidget.setGeometry( QRect(20, 20, 500, 500)) self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget) self.comps = [] self.table_view = QTableView(self.verticalLayoutWidget) self.comps.append( self.table_view ) self.table_view.setGeometry(QRect(20, 20, 200, 200)) self.verticalLayout.addWidget(self.table_view) self.table_view.setModel( HistoryTableModel() ) self.table_view.setTabKeyNavigation(False) self.table_view.setItemDelegate( HistoryTableViewDelegate( self.table_view )) MainWindow.setCentralWidget(self.centralwidget) class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) app = QApplication(sys.argv) application = MainWindow() application.show() sys.exit(app.exec()) </code></pre> <p>I want to have a multi-line editor so I think I have understood the way to go is <code>QPlainTextEdit</code>. Although, with the above, pressing Alt-E commits the data to the model, it doesn't actually end the session. If, for example, you click with the mouse on another cell you can see that the edited multi-line data remains in the edited cell, and doing that somehow also ends the edit session.</p> <p>How can I end the session programmatically?</p> <p>NB pressing Escape after pressing Alt-E is a way to do this (in two keystrokes)... but I essentially want to do whatever programmatic thing pressing Enter does with a <code>QLineEdit</code> editor.</p>
<p>Got it...</p> <pre><code>def end_edit(): self.setModelData( editor, self.model, index ) self.closeEditor.emit( editor ) </code></pre>
python|pyqt5|edit|qtableview
0
1,904,884
64,809,088
Python OS library getProperty
<p>I am trying to get line.seperator and file.seperator for python using the OS library for file input for my program.</p> <p>I am trying to set a string to assign that property such as in Java you can do</p> <pre><code> public static final String linefeed = System.getProperty(&quot;line.separator&quot;); </code></pre> <p>and</p> <pre><code> public static final String fileSeparator = System.getProperty(&quot;file.separator&quot;); </code></pre> <p>I have trouble finding documentation to do this in Python. Is there a proper way to do this using the OS library.</p> <p>Can I do <code>linefeed = os.sep</code>?</p>
<p>If you are using Jython, then you can use</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from java.lang import System print(System.getProperty('os.name'))</code></pre> </div> </div> </p>
python|file|operating-system
0
1,904,885
63,999,034
Error when using pca to reduce dimensionality
<pre><code>from sklearn.decomposition import PCA pca =PCA(n_components =2) X_PCA =PCA.fit(data_x) </code></pre>
<p>python is case sensitive - thus if your object is named pca, you cna't use PCA instead. try:</p> <pre><code>from sklearn.decomposition import PCA pca =PCA(n_components =2) X_PCA =pca.fit(data_x) </code></pre>
python-3.x|typeerror|pca|dimensionality-reduction
0
1,904,886
65,467,935
How to receive continuous stream of data
<p>I have create a django-server(using django-channels) from which a continuous stream of data would be sent on the channel-layer where the client is connected on.</p> <p>The below code represent the client, in which the &quot;generate.sepsis&quot; will trigger the function on the server-side to send json on the channel; I am simply receiving all the transmitted data from the server and printing it into the console.</p> <pre><code>async def receive_data_from_start_sepsis(): ws_pat=websocket.WebSocket() ws_pat.connect('ws://localhost:8000/sepsisDynamic/?token=1fe10f828b00e170b3a9c5d41fc168a31facefc3') #time.sleep(7) await ws_pat.send(json.dumps({ 'type':'generate.sepsis', 'data': { &quot;heart_rate&quot;: 55, &quot;oxy_saturation&quot;: 26.5, &quot;temperature&quot;: 50, &quot;blood_pressure&quot;: 95.48, &quot;resp_rate&quot;: 156, &quot;mean_art_pre&quot;: 85, &quot;user_id&quot;: 15 } })) #time.sleep(2) while True: greeting = await ws_pat.recv() print(f&quot;&lt; {greeting}&quot;) asyncio.sleep(2) # asyncio.run(receive_data_from_start_sepsis()) try: asyncio.get_event_loop().run_forever() finally: asyncio.get_event_loop().run_until_complete(receive_data_from_start_sepsis()) </code></pre> <p>but I get the following error</p> <pre><code>--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-6-9fdd3245dd6e&gt; in &lt;module&gt; 24 try: ---&gt; 25 asyncio.get_event_loop().run_forever() 26 finally: ~\anaconda3\lib\asyncio\base_events.py in run_forever(self) 524 if self.is_running(): --&gt; 525 raise RuntimeError('This event loop is already running') 526 if events._get_running_loop() is not None: RuntimeError: This event loop is already running During handling of the above exception, another exception occurred: RuntimeError Traceback (most recent call last) &lt;ipython-input-6-9fdd3245dd6e&gt; in &lt;module&gt; 25 asyncio.get_event_loop().run_forever() 26 finally: ---&gt; 27 asyncio.get_event_loop().run_until_complete(receive_data_from_start_sepsis()) ~\anaconda3\lib\asyncio\base_events.py in run_until_complete(self, future) 568 future.add_done_callback(_run_until_complete_cb) 569 try: --&gt; 570 self.run_forever() 571 except: 572 if new_task and future.done() and not future.cancelled(): ~\anaconda3\lib\asyncio\base_events.py in run_forever(self) 523 self._check_closed() 524 if self.is_running(): --&gt; 525 raise RuntimeError('This event loop is already running') 526 if events._get_running_loop() is not None: 527 raise RuntimeError( RuntimeError: This event loop is already running </code></pre> <p>But when the async code on the server completes its (iteration of)sending data; the socket receives all the data like so. (which is the very first data item sent.)</p> <pre><code>{&quot;type&quot;: &quot;echo.message&quot;, &quot;data&quot;: {&quot;id&quot;: 147, &quot;heart_rate&quot;: 155.0, &quot;oxy_saturation&quot;: 150.0, &quot;temperature&quot;: 43.0, &quot;blood_pressure&quot;: 94.0, &quot;resp_rate&quot;: 174.0, &quot;mean_art_pre&quot;: 186.0, &quot;patient&quot;: 10}} </code></pre> <p>The async function in django is:-</p> <pre><code>async def generating_patient_sepsis(self, message): # get the data from message data = message.get('data') print(f&quot;THE INITIAL DATA {data}&quot;) # get the patient's id get_pat_id_in_data = await self._convert_user_id_to_patient_id(data) data = get_pat_id_in_data while True: time.sleep(5) await asyncio.sleep(1) # random sepsis data generated and `data` variable is mutated data.update({'heart_rate': random.randint(24, 200)}) data.update({'oxy_saturation': random.randint(24, 200)}) data.update({'temperature': random.randint(24, 200)}) data.update({'blood_pressure': random.randint(24, 200)}) data.update({'resp_rate': random.randint(24, 200)}) data.update({'mean_art_pre': random.randint(24, 200)}) print(f&quot;THE DATA --&gt; {data}&quot;) # serializing and saving the data x = await self.serializer_checking_saving_data(data) # send the data to the channel await self.channel_layer.group_send( group=self.pat_grp_id, message={ 'type': 'echo.message', 'data': x } ) </code></pre> <p>I also want to learn how I would receive the same data in javascript so that I can represent the changes in a dynamic graphs fashion;</p> <p><a href="https://i.stack.imgur.com/L4snf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L4snf.png" alt="enter image description here" /></a></p>
<p>the reason why the test failed at</p> <pre><code>greeting = await ws_pat.recv() </code></pre> <p>is because the websocket receive function is a synchronous function and I was trying to await it. If I choose to remove the await keyword it would receive the stream of data but it only hold the the very first value in that stream of json-data.</p> <p>the way I was able to receive those json-data is by defining a function which is asynchronous and receiving the websocket data their; so whenever the websocket data will be broadcasted from the server.</p> <pre><code>async def receive_sepsis(ws_pat): return ws_pat.recv() </code></pre> <p>The issue with this implementation is the event-loop for broadcasting never gets completed because the while-loop is True; thereby all the json-data that is broadcasted from the server to the group(ie <em><strong>self.pat_grp_id</strong></em>) gets clogged up at the</p> <pre><code>await self.channel_layer.group_send(&lt;grp-name&gt;,&lt;message&gt;) </code></pre> <p><strong>Can anyone please help me, how should I actually work on this;</strong><br/> all I want to is connect patient and doctor to the same group(ie a grp_id attribute inside the patient model, which is a UUID field); once connected the patient will request &quot;start_diagnosis&quot; on the websocket; which will generates pseudo-random data of the illness; gets saved in the DB, returns the serialized version of the same data and then broadcasts it to the group-name with grp_id of the patient.</p>
javascript|websocket|python-asyncio|django-channels
0
1,904,887
72,129,372
What is the best way to aggregate 100 columns in pandas?
<p>I have a data frame with 101 columns currently. The first column is called &quot;Country/Region&quot; and the other 100 are dates in MM/DD/YY format from 1/22/20 to 4/30/20 like the example below. I would like to combine repeat country entries such as 'Australia' below and have its values in the date columns to be added together so that there is one row per country. I would like to keep ALL date columns.I have tried to use the groupby() and agg() functions but I do not know how to sum() together that many columns without calling every single one. Is there a way to do this without calling all 100 columns individually?</p> <pre><code>Country/Region | 1/22/20 | 1/23/20 | ... | 4/29/20 | 4/30/20 Afghanistan 0 0 ... 1092 1176 Australia 0 0 10526 12065 Australia 0 0 ... 56289 4523 </code></pre>
<p>This should work:</p> <pre><code>df.pivot_table(index='Country/Region', aggfunc='sum') </code></pre>
python|pandas
2
1,904,888
68,540,790
popen.kill not closing browser window
<p>I have spent the past few days trying to automate the process of flattening a PDF and this function is the one I have found works best. The only issue is that the a.kill() command is not being read, resulting in the browser remaining open after the function is complete. How can I close the browser window after the save process is finished?</p> <pre><code>import time import subprocess import keyboard def chrome(): test = &quot;test&quot; name = &quot;file:///C://Users//akcgo//Documents//CARB//ARBER//PDFS//Company A.pdf&quot; a = subprocess.Popen(&quot;C://Program Files (x86)//Google//Chrome//Application//chrome.exe&quot;) time.sleep(1) keyboard.write(name) time.sleep(1) keyboard.press_and_release('enter') time.sleep(1) keyboard.press_and_release(['ctrl', 'p']) time.sleep(1) keyboard.press_and_release('enter') time.sleep(1) keyboard.write(test) time.sleep(.5) keyboard.press_and_release('enter') time.sleep(2) a.kill() # keyboard.press_and_release(['ctrl', 'w']) doesn't work either </code></pre>
<p>You could get the subprocess' PID by using <code>pid = a.pid</code>, then calling <code>os.kill(pid, signal.SIGTERM)</code> or <code>os.kill(pid, signal.SIGKILL)</code>.</p>
python|subprocess|popen|kill
0
1,904,889
71,759,325
Create a function that multiplies the keys and values of a dictionary while under the constraint of additional conditons?
<p>To preface, I'm not very experienced with python. I'm currently trying to learn with what I know and the tools at my disposal.</p> <p><strong>Summary</strong></p> <p>I want to make a function that takes in a dictionary then afterwards multiplies the keys and values of said-dictionary together. However, there are external conditions that I want that are making this problem difficult.</p> <p>These conditions are:</p> <ul> <li><p>if one of the values are negative, instead of multiplying the value by it's respective key, it multiples x amount of asterisks where x is the amount of characters in the corresponding key by abs(value).</p> </li> <li><p>the function can only use basic for/while loops and if statements. I am somewhat familiar with list comprehension from viewing similar questions online but I'm not great at it. Instead, I'd like to practice using more simpler methods.</p> </li> </ul> <p><strong>The function itself should look something like</strong> <code>dict_multiply(dict):</code> and a test trial should look like <code>dict_multiply({'Terra': 6, 'Cloud': -7, 'Squall': 8})</code> which returns <code>'TerraTerraTerraTerraTerraTerra***********************************SquallSquallSquallSquallSquallSquallSquallSquall'</code>. Terra is repeated 6 times, the letters in ‘Cloud’ are converted into asterisks and multiplied by abs(-7), and Squall is repeated 8 times.</p> <p><strong>What I'm Trying</strong></p> <p>What I have tried doing is breaking down the problem into steps. I haven't put any of my code into a function yet for the convenience of not having to rerun it, but I've been experimenting with variables.</p> <p>for instance, I wanted to try creating a condition for where negative values in the dictionary would be read as asterisks.</p> <pre><code>dictionary = {'Terra': 6, 'Cloud': -7, 'Squall': 8} keylist = list(dictionary.keys()) valuelist = list(dictionary.values()) for values in valuelist: if values &lt; 0: valuelist[valuelist.index(values)] = abs(values) * ('*') valuelist </code></pre> <p>which returns <code>[6, '*******', 8]</code>. This is only a single component that I want from the function, but I think I'm getting somewhere. keylist is a list containing <code>['Terra', 'Cloud', 'Squall']</code> which I want to multiply by the valuelist I returned. I know I can multiply strings such as 'Terra' by int values such as 6, but I know multiplying two strings together such as '*******' and 'Cloud' is impossible. Instead, I would just want the asterisks returned but I'm unsure on how to create this condition.</p> <p>The issue of actually multiplying the lists of ints by the list of strings is something I'm concerned about too. I've seen explanations for this step online but none of the explanations are at my level of coding (basic for/while loops).</p> <p>disregarding this and assuming that multiplication somehow succeeds, I think it I should be left with a list of strings separated by commas which I know I can merge into a single string using <code>''.join(c)</code> (assuming that c is the result of the step I'm having trouble with).</p> <p>I'm sorry if my thought process may be confusing. I'm still in the process of learning python. Going forward, I want to be able to break down problems like these into steps and determine which steps I should think about first. Any feedback is appreciated.</p>
<p>You can try running the following code:</p> <pre class="lang-py prettyprint-override"><code>def dict_multiply(d: dict): s = &quot;&quot; for key, val in d.items(): if val &gt; 0: s += key * val else: s += &quot;*&quot; * abs(val) * len(key) return s print(dict_multiply({'Terra': 6, 'Cloud': -7, 'Squall': 8})) </code></pre> <p>Here, we loop through the keys and values of the input dict. If the value is greater than 0 (so positive), we add the key a value number of times. If it isn’t, we add the asterisk the absolute value of value times.</p>
python|dictionary|for-loop|if-statement
0
1,904,890
71,638,395
How to query and append a list of users emails linked with a manytomany relation to other Model
<p>First please take a look on the data structure. there are Three models</p> <pre><code>class Partner(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group = models.OneToOneField( Group, on_delete=models.DO_NOTHING, blank=True, null=True) class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) partner = models.ManyToManyField( Partner, blank=True) class Quote(models.Model): partner = models.ManyToManyField( Partner, blank=True, related_name='quote_partners') </code></pre> <p>There can be multiple partners inside the Quote and CustomUser partner field. I want to make a list of users email who are linked with Partner inside the partner field set in the quote model. This is how I'm doing;</p> <pre><code> quote = Quote.objects.get(id=id) partners = quote.partner.all() for partner in partners: recipient_list = [] for user in CustomUser.objects.filter(groups__partner=partner): recipient_list.append(user.email) </code></pre> <p>Currently quote object has 3 partners and collectively 4 users linked to these partners then there should be 4 emails in the the <code>recipient_list</code>, But this returning empty array []. Please highlight what I'm doing wrong and how to fix it.</p>
<p>You can <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter" rel="nofollow noreferrer"><strong><code>.filter(…)</code></strong> <sup>[Django-doc]</sup></a> with:</p> <pre><code>CustomUser.objects.filter(<b>groups__partner__quote_partners__id=<i>id</i></b>)</code></pre> <p>This looks for <code>CustomUser</code>s linked to a <code>Group</code> linked to a <code>Partner</code> linked to a <code>Quote</code> with the given <code>id</code>.</p> <p>You can query with:</p> <pre><code>CustomUser.objects.filter(<b>partner__quote_partners__id=<i>id</i></b>)</code></pre> <p>To look for <code>CustomUser</code>s that have a related <code>Partner</code> that has a related <code>Quote</code> with <code>id</code> as primary key.</p>
python|django|django-queryset
2
1,904,891
67,321,485
problem while processing username and email in django-rest
<p>I am getting username and email from user but even if user sends any one of username or email then I want to pass through the check below. but right now it is working only if user sends both of the username and email.</p> <pre><code> username = request.GET.get('username') email = request.GET.get('email') print(username) if not username or not email: return Response({ 'message': &quot;username or email missing.&quot;, }, status.HTTP_400_BAD_REQUEST) </code></pre> <p>Is there any way to fix this issue?</p>
<p>Try with <code>if not username and not email:</code>. This coundition will be <code>True</code> if both username and email are missing.</p>
python|django-rest-framework
0
1,904,892
67,279,627
Sorting elements from txt and group results
<p>Sorry for maybe so stupid question, but I have a problem: I have a inputs 1 from txt file and I sort inputs to categories by keyword and get output 1, but if I try input 2 without content for one of categories I get output 2</p> <p>Code:</p> <pre><code>def my_sort(conts): social_folders = {'engine': 1, 'wormix_mm': 2, 'wormix_ok': 3} line_fields = conts.strip().split(&quot;/&quot;) social = line_fields[3] return social_folders[social] numbers = 'First', 'Second', 'Third'#, 'Fourth' folds = ['engine', 'wormix_mm', 'wormix_ok'] with open('./testsort.txt') as testsortf, open('./test_out999.txt', &quot;w&quot;) as test_out: contents = testsortf.readlines() contents[-1] = f'{contents[-1]}\n' contents.sort(key=my_sort) # It needs 2 for loops for k, fold in enumerate(numbers): # Put enter before every category, except the first one if k != 0: test_out.write(f'\n') # Put the label of each category test_out.write(f'{numbers[k]}:\n') for i, line in enumerate(contents): # Put the right label in each category if line.strip().split(&quot;/&quot;)[3] == folds[k]: test_out.write(f'{line}') </code></pre> <p>My inputs 1:</p> <pre><code>https://markus.rmart.ru/engine/preloader/somefold https://markus.rmart.ru/wormix_ok/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold1 https://markus.rmart.ru/wormix_ok/preloader/somefold4 https://markus.rmart.ru/wormix_mm/preloader/somefold2 https://markus.rmart.ru/wormix_mm/preloader/somefold1 https://markus.rmart.ru/engine/preloader/somefold2 https://markus.rmart.ru/engine/preloader/somefold5 https://markus.rmart.ru/wormix_mm/preloader/somefold5 https://markus.rmart.ru/wormix_ok/preloader/somefold1 </code></pre> <p>My output 1</p> <pre><code>First: https://markus.rmart.ru/engine/preloader/somefold https://markus.rmart.ru/engine/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold1 https://markus.rmart.ru/engine/preloader/somefold2 https://markus.rmart.ru/engine/preloader/somefold5 Second: https://markus.rmart.ru/wormix_mm/preloader/somefold2 https://markus.rmart.ru/wormix_mm/preloader/somefold1 https://markus.rmart.ru/wormix_mm/preloader/somefold5 Third: https://markus.rmart.ru/wormix_ok/preloader/somefold1 https://markus.rmart.ru/wormix_ok/preloader/somefold4 https://markus.rmart.ru/wormix_ok/preloader/somefold3 </code></pre> <p>My inputs 2:</p> <pre><code>https://markus.rmart.ru/engine/preloader/somefold https://markus.rmart.ru/engine/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold1 https://markus.rmart.ru/wormix_mm/preloader/somefold2 https://markus.rmart.ru/wormix_mm/preloader/somefold1 https://markus.rmart.ru/engine/preloader/somefold2 https://markus.rmart.ru/engine/preloader/somefold5 https://markus.rmart.ru/wormix_mm/preloader/somefold5 </code></pre> <p>My output 2:</p> <pre><code>First: https://markus.rmart.ru/engine/preloader/somefold https://markus.rmart.ru/engine/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold1 https://markus.rmart.ru/engine/preloader/somefold2 https://markus.rmart.ru/engine/preloader/somefold5 Second: https://markus.rmart.ru/wormix_mm/preloader/somefold2 https://markus.rmart.ru/wormix_mm/preloader/somefold1 https://markus.rmart.ru/wormix_mm/preloader/somefold5 Third: </code></pre> <p>So, in second case I get nothing in the third category, but title of third category are exist What condition I must add for this output?</p> <p>Input:</p> <pre><code>https://markus.rmart.ru/engine/preloader/somefold https://markus.rmart.ru/engine/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold1 https://markus.rmart.ru/engine/preloader/somefold2 https://markus.rmart.ru/engine/preloader/somefold5 </code></pre> <p>Desired output:</p> <pre><code>First: https://markus.rmart.ru/engine/preloader/somefold https://markus.rmart.ru/engine/preloader/somefold3 https://markus.rmart.ru/engine/preloader/somefold1 https://markus.rmart.ru/engine/preloader/somefold2 https://markus.rmart.ru/engine/preloader/somefold5 </code></pre> <p>So, if second and third category is empty, titles for this categories does not print</p>
<p>You can just add the following line to test that category exists:</p> <pre><code>if any(line.strip().split(&quot;/&quot;)[3] == folds[k] for line in contents): </code></pre> <p>New code becomes:</p> <pre><code>def my_sort(conts): social_folders = {'engine': 1, 'wormix_mm': 2, 'wormix_ok': 3} line_fields = conts.strip().split(&quot;/&quot;) social = line_fields[3] return social_folders[social] numbers = 'First', 'Second', 'Third'#, 'Fourth' folds = ['engine', 'wormix_mm', 'wormix_ok'] with open('./testsort.txt') as testsortf, open('./test_out999.txt', &quot;w&quot;) as test_out: contents = testsortf.readlines() contents[-1] = f'{contents[-1]}\n' contents.sort(key=my_sort) # It needs 2 for loops for k, fold in enumerate(numbers): # Put enter before every category, except the first one if k != 0: test_out.write(f'\n') # Put the label of each category # Conditional to test that category exists if any(line.strip().split(&quot;/&quot;)[3] == folds[k] for line in contents): test_out.write(f'{numbers[k]}:\n') for i, line in enumerate(contents): # Put the right label in each category if line.strip().split(&quot;/&quot;)[3] == folds[k]: test_out.write(f'{line}') </code></pre>
python|python-3.x|sorting
0
1,904,893
67,315,017
New column as list from other columns, but without nans
<p>Basically, I have dataframe like this:</p> <pre><code> c1 c2 0 a x 1 b NaN </code></pre> <p>and I want to have column <code>c</code> like this:</p> <pre><code> c1 c2 c 0 a x [a, x] 1 b NaN [b] </code></pre> <p>Here is my solution:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'c1': ['a', 'b'], 'c2': ['x', np.nan]}) df['c'] = df[['c1', 'c2']].values.tolist() df['c'] = df['c'].apply(lambda x: [i for i in x if i is not np.nan]) </code></pre> <p>but I suppose something shorter, simpler and more pandonic exists. Could you help me with one-liner for this?</p>
<pre><code>df[&quot;c&quot;] = df.apply(lambda x: x[x.notna()].tolist(), axis=1) print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> c1 c2 c 0 a x [a, x] 1 b NaN [b] </code></pre>
python|pandas|list|numpy
1
1,904,894
71,318,410
how to remove a tuple based on its elements when the elements are np.array and my code raises value error "The truth value of an array with more
<p>how to remove a tuple based on its elements when the elements are np.array and my code raises value error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</p> <p>I want my code to remove the first tuple and leave the 2nd one how can I do this</p> <pre><code>tuple_list = [(np.array([1,2]),np.array([3,4])),(np.array([5,6]),np.array([7,8]))] i = np.array([1,2]) j = np.array([3,4]) filtered_t_l = [ x for x in tuple_list if (x[0], x[1]) != (i,j) ] </code></pre> <p>expected output:</p> <pre><code>[(array([5, 6]), array([7, 8]))] </code></pre>
<p>You need to aggregate to a single boolean, here using <code>any</code>:</p> <pre><code>filtered_t_l = [x for x in tuple_list if (x[0]!=i).any() or (x[1] != j).any()] </code></pre> <p>output:</p> <pre><code>[(array([5, 6]), array([7, 8]))] </code></pre>
python|arrays|list|numpy|tuples
2
1,904,895
56,659,658
Linear regression on a truncated dataframe not working
<p>I have a dataframe that i have grouped and then extracted the slope between values of 2 columns. The code is as below. <code>grouped_full= data_train.groupby(['Cycle', 'Type']) slope_full = (grouped_full.apply(lambda x: linregress(x['Time'], x['Values']).slope)).reset_index(name='Slope')</code></p> <p>I get the slope in a new column called "Slope". Now, I am trying to do the same thing for just the first 1700 rows in each grouped item. To get the 1700 rows, I have used the code as follows <code>grouped_small = data_train.groupby(['Cycle', 'Type']).head(1700)</code> I have printed &amp; checked, the dataframe is good. However, when i try to extract the slope on this using <code>slope_small = (grouped_small.apply(lambda a: linregress(a['Time'], a['Values']).slope)).reset_index(name='Slope2')</code> i encounter the error </p> <pre><code>KeyError: ('Time', 'occurred at index Cycle') </code></pre> <p>It is exactly the same code. I am not sure why i am encountering this error. What should i do to fix it?</p>
<p>"grouped_full" is a <code>pandas.core.groupby.generic.DataFrameGroupBy</code> hence apply comman will work on that.grouped_small is a complete dataframe <code>pandas.core.frame.DataFrame</code> &amp; apply will not work. So i did the following &amp; it is working <code>grouped_small = data_train.groupby(['Cycle', 'Type']).head(1700) grouped_small2 = grouped_small.groupby(['Cycle', 'Type']) slope_small = (grouped_small2.apply(lambda x: linregress(x['Time'], x['Values']).slope)).reset_index(name='Slope_small')</code></p>
pandas|pandas-groupby
0
1,904,896
18,081,506
Copying URLs to file that contain specific term
<p>So I'm trying to get all the urls in the range whose pages contain either the term "Recipes adapted from" or "Recipe from". This copies all the links to the file up until about 7496, then it spits out HTTPError 404. What am I doing wrong? I've tried to implement BeautifulSoup and requests, but I still can't get it to work.</p> <pre><code>import urllib2 with open('recipes.txt', 'w+') as f: for i in range(14477): url = "http://www.tastingtable.com/entry_detail/{}".format(i) page_content = urllib2.urlopen(url).read() if "Recipe adapted from" in page_content: print url f.write(url + '\n') elif "Recipe from" in page_content: print url f.write(url + '\n') else: pass </code></pre>
<p>Some of the URLs you are trying to scrape do not exist. Simply skip perhaps, by ignoring the exception:</p> <pre><code>import urllib2 with open('recipes.txt', 'w+') as f: for i in range(14477): url = "http://www.tastingtable.com/entry_detail/{}".format(i) try: page_content = urllib2.urlopen(url).read() except urllib2.HTTPError as error: if 400 &lt; error.code &lt; 500: continue # not found, unauthorized, etc. raise # other errors we want to know about if "Recipe adapted from" in page_content or "Recipe from" in page_content: print url f.write(url + '\n') </code></pre>
python|python-2.7|web-crawler|urllib2
1
1,904,897
66,152,894
Selenium Element not interactable exception- How to overcome this?
<p>I am working on scraping the price of a product from a website using Selenium with Python. As I run the application,the chromewebdriver opens, as soon as it opens a Notification/message pops up on the website which says to &quot;Accept Cookies&quot;, I accept it programmatically however my program stops it execution soon after. The intention is to accept cookies-&gt; Enter the product name(which is done programmatically)-&gt;after product is displayed-&gt; The price of product is displayed on my terminal. Here is my code for the same.</p> <pre><code>def scrape_currys(product_name): website_address = 'https://www.currys.co.uk/gbuk/index.html' options = webdriver.ChromeOptions() options.add_argument('start-maximized') options.add_argument(&quot;window-size=1200x600&quot;) options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-automation&quot;]) options.add_experimental_option('useAutomationExtension', False) browser = webdriver.Chrome(ChromeDriverManager().install(), options=options) browser.get(website_address) time.sleep(2) # browser.implicitly_wait(30) browser.find_element_by_id('onetrust-accept-btn-handler').click() browser.find_element_by_name('search-field').send_keys(product_name) browser.find_elements_by_class_name('Button__StyledButton-bvTPUF hfufmD Button-jyKNMA GZkwS')[0].submit() page_source = browser.page_source print(page_source) soup = BeautifulSoup(page_source, 'lxml') product_price_list = soup.find_all('div', class_='ProductCardstyles__PriceText-gm8lcq-14 lhwdnp') return product_price_list[0].text if __name__ == '__main__': product_name_list = ['Canon EF 24-105mm f/4L IS II USM Lens'] for product in product_name_list: scrape_currys(product) </code></pre> <p>The error further reads as <code>selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable </code> Here is the complete stacktrace</p> <pre><code>Traceback (most recent call last): File &quot;scrapeCurrys.py&quot;, line 34, in &lt;module&gt; scrape_currys(product) File &quot;scrapeCurrys.py&quot;, line 22, in scrape_currys browser.find_element_by_name('search-field').send_keys(product_name) File &quot;/home/mayureshk/PycharmProjects/Selenium-Scraper/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py&quot;, line 479, in send_keys 'value': keys_to_typing(value)}) File &quot;/home/mayureshk/PycharmProjects/Selenium-Scraper/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py&quot;, line 633, in _execute return self._parent.execute(command, params) File &quot;/home/mayureshk/PycharmProjects/Selenium-Scraper/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py&quot;, line 321, in execute self.error_handler.check_response(response) File &quot;/home/mayureshk/PycharmProjects/Selenium-Scraper/venv/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py&quot;, line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable (Session info: chrome=74.0.3729.108) (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Linux 5.0.0-1034-oem-osp1 x86_64) </code></pre> <p>I have gone through several answers here regarding the same however none of the attempts have so long been successfull. I have tried everything. I am hopeful to get an answer on this since most of the folks here are really knowledgeable. Thanks in advance!</p>
<p>You have to try other element locators when you get an error related to finding the element. This will work:</p> <pre><code>from selenium.webdriver.common.keys import Keys def scrape_currys(product_name): website_address = 'https://www.currys.co.uk/gbuk/index.html' options = webdriver.ChromeOptions() options.add_argument('start-maximized') options.add_argument(&quot;window-size=1200x600&quot;) options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-automation&quot;]) options.add_experimental_option('useAutomationExtension', False) browser = webdriver.Chrome(ChromeDriverManager().install(), options=options) browser.get(website_address) time.sleep(2) # browser.implicitly_wait(30) browser.find_element_by_id('onetrust-accept-btn-handler').click() browser.find_element_by_xpath('//*[@id=&quot;header&quot;]/div[1]/form/div/div/input').send_keys(product_name + Keys.ENTER) time.sleep(2) page_source = browser.page_source print(page_source) soup = BeautifulSoup(page_source, 'lxml') product_price_list = soup.find_all('div', class_='ProductCardstyles__PriceText-gm8lcq-14 lhwdnp') return product_price_list[0].text if __name__ == '__main__': product_name_list = ['Canon EF 24-105mm f/4L IS II USM Lens'] for product in product_name_list: scrape_currys(product) </code></pre>
python|python-3.x|selenium|selenium-webdriver
2
1,904,898
69,131,672
AnalysisException: Using PythonUDF in join condition of join type LeftSemi is not supported
<p>I am not doing LeftSemi join anywhere, neither am I using a python UDF. Still I am getting this error when joining two dataframes.</p> <p>df1 - one column, is primary key of the table, say &quot;customerHash&quot;. It may be empty(In fact in my current case, it is empty).</p> <p>df2 - a table which also has customerHash column, but it's primary key column is different.</p> <pre><code>result = df1\ .select(&quot;customerHash&quot;)\ .distinct()\ .join(df2, [&quot;customerHash&quot;], 'inner') </code></pre> <p>The code runs successfully, but when I try to display/collect/persist the result table, it throws the mentioned error. I have absolutely no idea why it's happening - My guess will be because the df1 is empty. But joins don't throw errors when tables are empty, right?</p> <p>My main goal is to get only those rows of df2 whose customerHash is in df1. I could use</p> <pre><code>df2.filter(F.col(&quot;customerHash&quot;).isin(df1.select(&quot;customerHash&quot;).distinct().collect()....)) </code></pre> <p>but I don't want to use it as it is very slow.</p> <p>Please help!</p>
<p>I met this error,I divided it into two joins to settle. for example A leftjoin B:</p> <p>step 1. A innerjoin B get C (use udf)</p> <p>step 2. A leftjoin C for final result</p>
python|join|pyspark|inner-join|semi-join
1
1,904,899
62,993,928
Pandas read data with incorrect number of separators
<p>I want to read a <code>csv</code> file into <code>Pandas</code> <code>DataFrame</code> and the file contains several rows with an incorrect number of separators. I know that it's possible to skip these rows via setting up <code>error_bad_line=False</code>. But I want to read them in this way:</p> <ul> <li>Correct data: <code>some text,label</code>, in this case <code>1st column</code> = <code>some text</code>, <code>2nd column</code> = <code>label</code></li> <li>Incorrect data: <code>some text, another text, again some text,label</code>, in this case, I want <code>1st column</code> = <code>some text, another text, again some text</code>, <code>2nd column</code> = <code>label</code></li> </ul> <p>Is this possible to handle incorrect data in this way using Pandas?</p>
<p>You can just split the columns for example:</p> <pre><code>df['some text, another text, again some text'] = (df['some text'] + df['another text'] + df['again some text']) print(df) </code></pre> <p>which will transform this:</p> <pre><code>some text another text again some text label;;;;; \ 0 ;;;;; NaN NaN NaN 1 ;;;;; NaN NaN NaN 2 ;;;;; NaN NaN NaN 3 ;;;;; NaN NaN NaN 4 ;;;;; NaN NaN NaN 5 ;;;;; NaN NaN NaN 6 ;;;;; NaN NaN NaN </code></pre> <p>Into this:</p> <pre><code> some text, another text, again some text 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN </code></pre> <p>I didn't filled the rows, so some random ; and NaN appears, but it is separated!</p> <p>Does anyone have a better approach to this? Thanks</p>
pandas|csv
0