Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
4,400
23,257,237
Remove bash formatting in text using python
<p>I'm having text file containing data from bash output, so it contains formatted data, more specifically, color codes like this:</p> <pre><code>[0;31m16521[0;0m [0;32mDesktop/business-models-for-data-economy.pdf[0;0m </code></pre> <p>I want to strip down the formating, that is, get it in plain text:</p> <pre><code...
<p>You can do that with a regex:</p> <pre><code>import re s = '[0;31m16521[0;0m [0;32mDesktop/business-models-for-data-economy.pdf[0;0m' new_s = re.sub(r'\[.*?;.*?m', '', s) &gt;&gt;&gt; print new_s 16521 Desktop/business-models-for-data-economy.pdf </code></pre> <p><a href="http://repl.it/RmH" rel="nofollow"><h2>...
python|bash
2
4,401
7,735,502
Why my strange results rendering the user object?
<p>For some reason, my variable <code>{{current_user.name}}</code> doesn't display anything and the variable <code>{{username}}</code> displays instead of Niklas R it displays `(u'Niklas R',) on the page that I render with django. Here is the method from the basehandler that I hope you can tell me what's wrong with:</p...
<p>This happens to me all the time, you have an extra , and the variable becomes a tuple.</p> <p>change the lines to: </p> <pre><code>data[u'current_user']=self.current_user data[u'username']=self.current_user.name </code></pre>
python|google-app-engine|facebook-graph-api|bug-tracking
2
4,402
306,313
"is" operator behaves unexpectedly with integers
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257...
<p>Take a look at this:</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; id(a) 9987148 &gt;&gt;&gt; id(b) 9987148 &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; id(a) 11662816 &gt;&gt;&gt; id(b) 11662828 </code></pre> <p>Here's what I found in the Python 2 documentation, <a href="https://...
python|int|operators|identity|python-internals
439
4,403
41,953,839
Python - I cannot get a comma to write to a dictionary
<p>I am writing a program that takes a sentence that has been inputted, puts it in a dictionary with the position of each word and punctuation and then the sentence is recreated exactly like the original but i cannot get the program to put a comma into the dictionary with a position. It does however work with all other...
<p>Since you use the comma as separator here: <code>punctuation = r"[ {},:'[\]1-5]+"</code> , he will not appears in your dictionary because he will not be returned as a word by the <code>re.split(punctuation, sentence)</code>.</p> <p>You have to find another way to split your word if you want <code>','</code> to app...
python|dictionary
0
4,404
47,214,594
Does Django hit the database when I access an object's attributes?
<p>Does the following code query the database every time I call question.name?</p> <pre><code>class Question(models.Model): name=models.CharField() test=models.ForeignKey(Test) questions = Question.objects.filter(test=some_test) for question in questions: question_name = question.name </code></pre> <p>My...
<p>Well, your question is unclear but one thing for sure, at least one hit to the database will be required. Indeed, in your code sample your using:</p> <pre><code>question_name = question.name </code></pre> <p>But I don't see this working if <code>question</code> is not an instance of <code>Question</code> model bef...
python|django|django-models
1
4,405
47,305,618
What is the role of TimeDistributed layer in Keras?
<p>I am trying to grasp what TimeDistributed wrapper does in Keras.</p> <p>I get that TimeDistributed "applies a layer to every temporal slice of an input."</p> <p>But I did some experiment and got the results that I cannot understand.</p> <p>In short, in connection to LSTM layer, TimeDistributed and just Dense laye...
<p>In <code>keras</code> - while building a sequential model - usually the second dimension (one after sample dimension) - is related to a <code>time</code> dimension. This means that if for example, your data is <code>5-dim</code> with <code>(sample, time, width, length, channel)</code> you could apply a convolutional...
python|machine-learning|keras|neural-network|deep-learning
103
4,406
70,749,184
The particle is not moving so what is the problem?
<p>I follow a youtube video 'https://www.youtube.com/watch?v=cCiXqK9c18g' and in the video he make a class that represent a ball and he used pymunk to make a body and added it to the space and after that he created a method inside the ball class that will use pygame to draw the ball and I did almost like him</p> <pre><...
<p>You error is both a typo and using the wrong variable.</p> <p>Inside your particles draw function...</p> <pre><code># OLD def draw(self): pygame.draw.circle(display, self.color, convert_cor(self.pos), self.r) # New def draw(self): pygame.draw.circle(display, self.color, convert_cor(self.body.positio...
python|pygame|pymunk
2
4,407
11,553,131
Get system volume (Sound level) in linux using Python
<p>I am using Fedora 16 and modifying a program in python 2.7.</p> <p>How do I get the systems volume (Sound level)?</p>
<p>For ALSA, use <a href="http://pyalsaaudio.sourceforge.net/libalsaaudio.html#mixer-objects" rel="nofollow"><code>pyalsaaudio</code></a></p> <p>For Pulse, its a bit raw. There are <a href="https://github.com/Valodim/python-pulseaudio" rel="nofollow">ctype bindings</a></p>
python|linux|audio|volume
2
4,408
58,260,776
Parsing Command Line Output in Windows with Python
<p>I essentially want to get some values from a command like 'ipconfig', but when I print the output of the command I get alot of newline characters and spaces.</p> <p>Code I've Tried:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; output = subprocess.getstatusoutput("ipconfig") &gt;&gt;&gt; print(output)...
<p>We get the output, decode it so it's a <code>str</code>, then iterate over its lines.</p> <p>We'll store each separate adapter as a <code>dict</code> in a <code>dict</code> named <code>adapters</code>.</p> <p>In the output, preceding the details of each adapter is a line starting with <code>"Ethernet adapter "</co...
python|python-3.x|parsing
1
4,409
58,516,257
How can I convert binary to heximal while keeping the zeros in the beginning?
<p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = int(input("Enter some numbers with 1's and 0's: ")) Enter some numbers with 1's and 0's: 001 10100 00010 1100100 1000 &gt;&gt;&gt; y = # some code here &gt;&gt;&gt; print(y) 001 14 0002 64 8 </code></pre> <p>What would I assig...
<p>Use regex to get the leading zeroes, then convert the rest to an int but format it as hex.</p> <pre><code>import re def formatter(s): """Convert binary string s to hex, but keep leading zeroes.""" zeroes = re.match(r'0*', s)[0] binary = s[len(zeroes):] i = int(binary, 2) return '{}{:x}'.format(...
python|python-3.x|python-3.7
0
4,410
46,885,157
Somewhere inside my loop it's not appending results to a list. Why?
<p>So I have two files/dictionaries I want to compare, using a binary search implementation (yes, this is very obviously homework).</p> <p>One file is</p> <p><strong>american-english</strong></p> <pre><code>Amazon Americana Americanization Civilization </code></pre> <p>And the other file is </p> <p><strong>british...
<p>You don't have an <code>else</code> suite for your <code>if</code> statement. Your <code>if</code> statement does nothing (it uses <code>pass</code> when the test is true, skipped otherwise).</p> <p>You do have an <code>else</code> suite for the <code>for</code> loop:</p> <pre><code>for entry in wordlist_1: # ...
python|python-3.x
4
4,411
37,952,928
How to have two variables in one regex?
<p>How can I get two variables into one regular expression?</p> <p>So far:</p> <pre><code>var1 = "Taco" x = re.findall('(?&lt;=\|)%s\|(?=\|)' % var1, string) </code></pre> <p>This works great for the one variable but I need to have something like:</p> <pre><code>x = re.findall('(?&lt;=\|)%s\|%s(?=\|)' % var1 % var2...
<pre><code>x = re.findall('(?&lt;=\|)%s\|%s(?=\|)' % (var1, var2), string) </code></pre>
python|regex
1
4,412
37,940,607
What is it DNSQR?
<p>I looked for a script that send a DNS request. I found out a script using "DNSQR", but I'm not sure what is this command, and I didn't find a good documentation for it.<br> this is the entire command: <code>qd=DNSQR(qname="www.facebook.com")</code>. </p> <p>this is the whole script:</p> <pre><code> my_packet = sr1...
<p>Let's open the source code:</p> <pre><code>class DNSQR(Packet): name = "DNS Question Record" fields_desc = [ DNSStrField("qname",""), ShortEnumField("qtype", 1, dnsqtypes), ShortEnumField("qclass", 1, dnsclasses) ] </code></pre> <p>where <code>ShortEnumField</code> a...
python|python-2.7|scapy
4
4,413
37,955,929
Mangled tkinter
<p>While trying to get scipy installed under OS X, I temporarily installed Anaconda, and wound up having two versions of Tk. To resolve the complaints this generated, I moved the original version of some Tk or tkinter file (like _tkinter.so or some such, and nested under /System or maybe /Library) to a temporary locat...
<p>Got to your terminal and type:</p> <pre><code>sudo apt-get python-tk </code></pre> <p>And if this doesn't work you could just remove the package anaconda like:</p> <pre><code>apt-get remove [anaconda] </code></pre> <p>And then reinstall Tkinter like:</p> <pre><code>sudo apt-get python-tk </code></pre>
python|tkinter|tk
0
4,414
37,646,733
Tensorflow import error: module 'imp' has no attribute 'find_module'
<p>I am trying to import tensorflow (I have installed on 14.04 LTS and tensorflow 0.8) but it shows </p> <pre><code> atributeError: module 'imp' has no attribute 'find_module' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/prayalankar/anaconda3/envs/tensorflow/lib/...
<p>Seems that I had a <code>imp.py</code> in home directory which was confusing the imp of python so I had to change the name of <code>imp.py</code></p>
python-3.x|tensorflow
2
4,415
30,238,305
Python re.sub not returning match
<p>In my brain, the following:</p> <pre><code>&gt;&gt;&gt; re.sub('([eo])', '_\1_', 'aeiou') </code></pre> <p>should return:</p> <pre><code>'a_e_i_o_u' </code></pre> <p>instead it returns:</p> <pre><code>'a_\x01_i_\x01_u' </code></pre> <p>I'm sure I'm having a brain cramp, but I can't for the life of me figure ou...
<p><code>\1</code> produces <code>\x01</code> in Python string literals. Double the slash, or use a raw string literal:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub('([eo])', '_\1_', 'aeiou') 'a_\x01_i_\x01_u' &gt;&gt;&gt; re.sub('([eo])', '_\\1_', 'aeiou') 'a_e_i_o_u' &gt;&gt;&gt; re.sub('([eo])', r'_\1_...
python|regex
4
4,416
30,026,332
Why do two different objects contain the same lists?
<p>I just expierenced a weird problem I don't understand: </p> <pre><code>class A: a_number = 666 a = A() a2= A() a.a_number = 555 print a2.a_number # =&gt; 666 </code></pre> <p>This situation is totally clear to me. But have a look at the next example:</p> <pre><code>class B: a_list = [1,2] b = B() b2 =...
<p>As all of the other other answers point out, <code>a_list</code> is a class attribute, shared among all instances.</p> <p>But <code>a_number</code> is <em>also</em> a class attribute, shared among all instances. So, why is this different?</p> <p>Because of this:</p> <pre><code>a.a_number = 555 </code></pre> <p>T...
python|object
1
4,417
65,531,277
Python selenium error randomly occours: element is not attached to the page document
<p>An error randomly occours in my python selenium project, where i scrape data from websites. It fetches date, temperature, wind and rainfall. The script sometimes run normally, but other times the error pops up:</p> <blockquote> <p>selenium.common.exceptions.StaleElementReferenceException: Message: stale element refe...
<p>what i am confused about its that you are looping through <code>dates</code>, which is a <strong>string</strong> in your code.</p> <pre><code>dates = &quot;forecast-day-view-date-bar__date&quot; date = driver.find_elements_by_class_name(dates) for klikk in dates: # 1st loop -&gt; klikk = 'f' # 2st loop -&gt...
python|selenium
0
4,418
43,061,345
python game highscore calculation
<p>Is there a formula I can use for python code to calculate a score with the variables <code>moves</code> and <code>time</code>? The higher the time the lower the score, or if the number of moves is more, then the time should be lower.</p> <p>I did this but if the time is higher the score becomes lower:</p> <pre><co...
<p>There are tons of functions that do what you want. What you are building can be modeled by a simple curve. So how do you want the curve to behave?</p> <p>You can have a linear curve that goes straight towards zero. Or you can have an exponential decay where the score approaches zero but never reaches it. </p> <p><...
python
0
4,419
37,033,114
Kivy TextInput cursor control problems
<p>I'm trying to make a quick fix for the black-line <code>TextInput</code> glitch (<a href="https://github.com/kivy/kivy/issues/4166" rel="nofollow">issue</a>). I want it to insert a newline and move the cursor to the next line whenever the 100th character in the line is typed. It does insert the newline, but doesn't ...
<p>I don't know how to change it without writing a custom function that handles inserting text the way it should work by default. I can tell you why it doesn't work however and it's because of <a href="https://github.com/kivy/kivy/blob/master/kivy/uix/textinput.py#L650" rel="nofollow">this</a> and particulary the line ...
python|python-3.x|kivy
0
4,420
36,889,110
"No such device" error using pyvisa with pyvisa-py backend
<p>I'm trying to set up pyvisa with Python backend <code>rm=ResourceManager('@py')</code>.</p> <p>When I launch <code>rm.list_resources()</code></p> <p>I receive the following error:</p> <pre><code>libgpib: error locking board mutex! Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;modul...
<p>This is a known bug and here is tracker. I had a similar problem and this link helped.</p> <p><a href="https://github.com/hgrecco/pyvisa-py/issues/78" rel="nofollow noreferrer">https://github.com/hgrecco/pyvisa-py/issues/78</a></p>
python|linux|visa|gpib
2
4,421
69,382,757
Finding eigenvalues of a matrix with unknown variables using numpy.linalg.eig
<p>As an example, I have the following matrix:</p> <p>$$\begin{bmatrix}a+1&amp;1\1&amp;1\end{bmatrix}$$</p> <p>I would like to find the eigenvalue of the matrix with python. This is my attempt:</p> <pre><code>arr = np.array( [[ a+1, 1], [ 1, 1]] ) print(np.linalg.eig(arr)) </code></pre> <p>Obviously, pytho...
<p>ddejohn is right. What you want is a symbolic operation so use sympy:</p> <pre><code>from sympy import var, Matrix var('a') arr = Matrix( [[ a+1, 1], [ 1, 1]] ) arr.eigenvals() </code></pre> <p>gives</p> <pre><code>{a/2 - sqrt(a**2 + 4)/2 + 1: 1, a/2 + sqrt(a**2 + 4)/2 + 1: 1} </code></pre>
python|numpy|matrix|numerical-methods
2
4,422
70,438,960
ValueError: Columns must be same length as key with multiple outputs
<p>I am extracting a substring from an Excel cell and the entire string says this:</p> <pre><code>The bolts are 5&quot; long each and 3&quot; apart </code></pre> <p>I want to extract the length of the bolt which is <code>5&quot;</code>. And I use the following code to get that</p> <pre><code>df['Bolt_Length'] = df['Des...
<p>Your problem is that you have two capture groups in your second regular expression <code>(\s(\d{1,2})&quot;)</code>, not one. So basically, you're telling Python to get the number <em>with</em> the <code>&quot;</code>, <em>and</em> the same number <em>without</em> the <code>&quot;</code>:</p> <pre><code>&gt;&gt;&gt;...
python|excel|regex|pandas
0
4,423
72,878,671
Is there a way to create a python foreground service on android?
<p>I am developing an AI Voice assistant using python. I made an app using kivy to connect with my ai using python sockets. I can control my mobile phone using the AI. But, when the application goes to sleep or closed. My app client is not listening for any commands from AI. Is there a way to create a foreground servic...
<p>You should try using <a href="https://developer.android.com/training/scheduling/wakelock" rel="nofollow noreferrer">Wake Lock</a>, you can read the official documentation here. I assume that you are using <code>buildozer</code> to create the <code>APK</code>, so for this in order to work, you will need to give your ...
python|java|android
0
4,424
55,720,665
google cloud function import errors in function view log
<p>I have create a google cloud function in python runtime environment which is triggered by the google cloud pubsub and i have also add requirement dependencies but when i run the function it works properly but it logged some import error so how do i solve this problem. </p> <p>python code :</p> <pre><code>import ba...
<p>You can either suppress the log message:</p> <pre><code>import logging logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)` </code></pre> <p>Or set <code>cache_discovery=False</code> when using <code>discovery.build()</code>:</p> <pre><code>self.client = discovery.build( service_name,...
python-3.x|google-cloud-platform|google-cloud-functions
0
4,425
73,230,623
How to add xlwings to VBA reference automatically from python side
<p>To activate UDFs on excel book, we need <code>Tools</code> &gt; <code>References</code> &gt; check <code>xlwings</code> as shown in <a href="https://docs.xlwings.org/en/stable/addin.html" rel="nofollow noreferrer">https://docs.xlwings.org/en/stable/addin.html</a></p> <p>I would like to know is there any way to do th...
<p>Seems following will work:</p> <pre class="lang-py prettyprint-override"><code>if &quot;xlwings&quot; not in [i.Name for i in wb.api.VBProject.References]: xlam_path = os.path.expanduser('~') + &quot;\\anaconda3\\&quot; + env_name xlam_path += &quot;\\lib\\site-packages\\xlwings\\addin\\xlwings.xlam&quot; ...
python|python-3.x|xlwings
0
4,426
66,675,711
REST API Authentification
<p>I am trying to authenticate to a <a href="https://github.com/sorare/api" rel="nofollow noreferrer">REST API</a> with a post method as stated in their docs. I am doing so using python; I get the error</p> <pre><code>Bad Request: 784: unexpected token at 'user=email&amp;user=password' </code></pre> <p>Here is my code,...
<p>We need to convert the payload to json string</p> <pre><code>import json payload = json.dumps(payload) </code></pre>
python-3.x|python-requests|endpoint
0
4,427
64,898,733
How to delete everything after a certain character for whole column in df?
<p>I have a df with one column (SKUID) where I want to remove all the characters that are not numerical. Here is an sample of the column:</p> <p><a href="https://i.stack.imgur.com/5baZO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5baZO.png" alt="SKUID" /></a></p> <p>Essentially I want to remove t...
<p>This should do for number extraction:</p> <pre><code>sku_data.SKUID = sku_data.SKUID.str.extract('(\d+)') </code></pre> <p><strong>Note</strong>: don't forget to add the <code>str</code> operator if you want to perform string operations on a <code>DataFrame</code> column</p>
python|split
1
4,428
64,959,812
How to check if all items in a list satisfies some property?
<p>So im trying to check if some lists are close enough to each other. But i dont know how to make it go through every single value before deciding if its close or not.</p> <pre><code>import math A=[5.230001, 6.8300001, 10.000001,11.33] B=[5.23, 7.83, 10.00, 11.31] for i in range(len(A)): if math.isclose( A[i], B[...
<p>Python has builtin functions for that:</p> <pre><code>if all(math.isclose(a, b, abs_tol=0.01) for a, b in zip(A, B)): print(&quot;close enough&quot;) else: print(&quot;not close&quot;) </code></pre> <p>If you wanted the opposite (at least 1 instead of all) you can use <code>any</code> instead.</p>
python|python-3.x|list|for-loop
1
4,429
53,153,633
How can i add headers in Qtableview
<p>Here is my code,i create a table format by using table view.It consist of 4 columns for that columns i want to add header names like filename, size,and date of modified,but i don't want to add any names to my buttons.so can you please guide me how can i add header names to only for file,date and date modified in my ...
<p>In this case it is better to have several columns and set the buttons in the last column:</p> <pre><code>import sys from PySide import QtGui, QtCore class ViewWidget(QtGui.QWidget): def __init__(self, index, parent=None): super(ViewWidget, self).__init__(parent) self.p_index = QtCore.QPersiste...
python|pyside
3
4,430
65,342,341
How to encode private key as JSON WEB TOKEN in RS256 format using python
<p>Well I have gone through a lot of questions, and their respective answers, mostly instead of private key (which starts from -----BEGIN RSA PRIVATE KEY-----) to encode in jwt, public key was being sent (which does not begin from -----BEGIN RSA PRIVATE KEY-----). I have used pyjwt library in python to encode and get t...
<p>Instead of using jwt library this worked for me My imports</p> <pre><code>from jose import jws from cryptography.hazmat.primitives import serialization as crypto_serialization </code></pre> <p>private_key_pem is path for private.pem file in which i have my private key as (-----BEGIN RSA PRIVATE KEY----- (code) -----...
python|jwt|docusignapi|jose|pyjwt
0
4,431
65,254,523
Python matlib text on bar chart
<p>I want to add text to each bar in bar chart because now I have only like 5,10,15 on the bottom.</p> <p>I am looking for solution to add text for each or just text on the top for each.</p> <pre><code>import matplotlib.pyplot as plt plt.bar([i for i in range(1, 24)], [i for i in range(1, 24)]) plt.title('Chart by ho...
<p>This is typical matplotlib: can be done, but requires some work.</p> <pre><code>def label(rects, texts): &quot;&quot;&quot;Attach a text label on each rect&quot;&quot;&quot; for rect, txt in zip(rects, texts): height = rect.get_height() if height != 0: plt.text( re...
python|matplotlib
0
4,432
68,835,685
PySimpleGUI problems with BROWSE_FILES_DELIMITER
<p>I am working on my first GUI project using PySimpleGUI. It is basically meant to be a wizard for importing and reading scanned files. I have each step of the wizard as a new function which is called and opens a new window. My problem is that some of the files I expect to import will contain a semicolon(;) character....
<p>You cannot change the default value for the default argument, it's value is assigned when function defined, not when function called.</p> <pre class="lang-py prettyprint-override"><code>def FilesBrowse(button_text='Browse', target=(ThisRow, -1), file_types=((&quot;ALL Files&quot;, &quot;*.*&quot;), ), disabled=F...
python|pysimplegui
0
4,433
71,654,785
How to customize Python domain in Sphinx?
<p>I’d like to customize the Sphinx Python domain to recognize a custom field within a docstring for a method and generate custom HTML for it.</p> <p>For example, let’s say I want to add a category for each method in a module. I want to be able to write a doc string like this:</p> <pre class="lang-py prettyprint-overri...
<p>Yes, it is, but it will require code (a custom extension) and might not be easy.</p> <p>There might be a simpler way, but by subclassing <a href="https://github.com/sphinx-doc/sphinx/blob/b4276edd848d112b4e981011c334d27cbcb20018/sphinx/domains/python.py#L740" rel="nofollow noreferrer"><code>PyClassLike</code></a>, p...
python|python-sphinx
0
4,434
62,892,802
Pandas cumulative sum starting last row where condition was satisfied
<p>I have a dataframe of the following form:</p> <pre><code>|----------|----|------| |date |type|inflow| |----------|----|------| |2017-01-01|I | 3500| |2017-02-01|A | 23| |2017-07-01|A | 44| |2017-09-01|A | 55| |2017-12-01|A | 12| |2018-01-01|I | 3800| |2018-03-01|A | 87| |2018-05-0...
<p>Let's try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.cumsum.html" rel="nofollow noreferrer"><code>GroupBy.cumsum</code></a>:</p> <pre><code>df['inflow_cumsum'] = df.groupby(df['type'].eq('I').cumsum())['inflow'].cumsum() df date type inflow in...
python|pandas
5
4,435
61,944,423
How to make a standalone Python executable with selenium/chrome webdriver on MacOS using PyInstaller
<p>I am trying to make a standalone executable of a webscraping script that using selenium and webdriver, and I want to be able to share the file to other users without them having to manually install chromedriver and specify its path. </p> <p>When I run the exectuable with chromedriver in the same directory, I get t...
<p>Maybe use <a href="https://pypi.org/project/webdrivermanager/" rel="nofollow noreferrer">WebDriverManager</a>, it will download the latest webdriver at runtime, so you do not need to ship it at all. This also solves the issue your users might have when they upgrade their Chrome version, because the Chrome version an...
python|selenium|selenium-webdriver|selenium-chromedriver|pyinstaller
2
4,436
60,651,378
Loop over rows with date and other conditions
<pre><code>Date Product Quantity 01.01.2020 Apple 1 02.01.2020 Apple 2 03.01.2020 Apple 3 04.01.2020 Apple 7 05.01.2020 Orange 8 06.01.2020 Orange 1 07.01.2020 Orange 7 08.01.2020 Orange 9 </code></pre> <p>My requirement is </p> <p...
<p>You can try of either <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.rolling.html" rel="nofollow noreferrer">rolling sum</a> or <a href="https://pandas.pydata.org/pandas-docs/version/0.23.1/generated/pandas.Series.cumsum.html" rel="nofollow noreferrer">Cummulative sum</a> on indivi...
python|pandas
2
4,437
68,982,751
Downloading multiple tickers data from Yahoo Finance
<p>I saw this code that Andrej Kesely posted on StackOverflow. I really find it very helpful, but I am trying to download multiple tickers instead of one ticker. <a href="https://stackoverflow.com/questions/68263449/cannot-scrape-from-table-in-yahoo-finance?answertab=votes#tab-top">Cannot scrape from table in yahoo fi...
<p>you can try also yfinace:</p> <pre><code>import yfinance as yf etf = ['AXP','AAPL','BA','CAT','CSCO','CVX','XOM','GS','HD','IBM','INTC','JNJ','KO'] #and any tickers you'd add to be retrived tit = yf.download(tickers=etf, period='max') </code></pre>
python|yahoo-finance
1
4,438
68,347,501
TensorFlow/Keras Using specific class recall as metric for Sparse Categorical Cross Entropy
<p>*<strong>Update at bottom</strong></p> <p>I am trying to use recall on 2 of 3 classes as a metric, so class B and C from classes A,B,C.</p> <p>(The original nature of this is that my model is highly imbalanced in the classes [~90% is class A], such that when I use accuracy I get results of ~90% for prediciting class...
<p>Your problem is quite simple. I have put together a example for you:</p> <pre><code>import tensorflow as tf from sklearn.datasets import make_classification data = make_classification(n_samples=1000, n_features=20, n_classes=3, n_clusters_per_class=1) model = tf.keras.Sequential([ tf.keras.layers.InputLayer(in...
python|tensorflow|machine-learning|neural-network|tf.keras
2
4,439
58,821,599
Splitting a data set for K-fold Cross Validation in Sci-Kit Learn
<p>I was assigned a task that requires creating a Decision Tree Classifier and determining the accuracy rates using the training set and 10-fold cross-validation. I went over the documentation for <code>cross_val_predict</code> as I believe that this is the module I am going to need.</p> <p>What I am having trouble wi...
<p>It depends. My personal opinion is yes you have to split your dataset into training and test set, then you can do a cross-validation on your training set with K-folds. Why ? Because it is interesting to test after your training and fine-tuning your model on unseen example.</p> <p>But some guys just do a cross-val. ...
python|machine-learning|scikit-learn|decision-tree|k-fold
4
4,440
59,675,400
Dataframe to key/value Dict as tuple/object format
<p>I got the following pandas df:</p> <pre><code>id1 id2 f1 f2 f3 1 1 a b c 1 2 d e f </code></pre> <p>The result I would like is:</p> <pre><code>{ (1, 1): {"f1": "a", "f2": "b", "f3": "c"}, (1, 2): {"f1": "d", "f2": "e", "f3": "f"} } </code></pre> <p>I managed to get somewhere with </p> <pre...
<p>Use <code>.to_dict</code> with <code>orient=index</code>:</p> <pre><code>df.set_index(['id1','id2']).to_dict('index') </code></pre> <blockquote> <p>index’ : dict like {index -> {column -> value}}</p> </blockquote> <hr> <pre><code>{(1, 1): {'f1': 'a', 'f2': 'b', 'f3': 'c'}, (1, 2): {'f1': 'd', 'f2': 'e', 'f3':...
python|pandas
3
4,441
70,988,695
why does append not append the parameter
<p>I was doing a bit of Leetcode and do not understand why <code> res.append(subset)</code> does not append the subset to res. Could somebody explain the reason behind this?</p> <pre><code>def solve(arr): res = [] def dfs(arr,subset): if len(arr) == 0: # why does the following line not appen...
<p>Your problem is that you have assumed that <code>res.append(subset)</code> will append the <em>items</em> in <code>subset</code>. Python assignments for compound objects behave differently and so appending a list to a list is not the same as appending the <em>values</em> of a list to a list.</p> <p>In this example, ...
python|append|depth-first-search
0
4,442
66,958,378
ksqlDB Querying at Best Practice
<p>I am currently building a ksqlDB instance and I target to deploy it in interactive mode.</p> <p>I created streams and table to serve windowed aggregations with RocksDB.</p> <p>I would like to query the cache with REST API calls (i.e. Python wrapper for KSQL Rest API), yet I am not sure if this is the right approach ...
<p>Your initial problem is not clear to me. You are not just requesting the cache)</p> <p>I will assume that the cache is needed, for example, to enrich the data.</p> <p>In this case, the best practice would be to create a stream with data that needs to be enriched and join by key. <a href="https://docs.ksqldb.io/en/la...
apache-kafka|confluent-platform|ksqldb|rocksdb|confluent-kafka-python
0
4,443
42,753,089
Thinkpython book exercise
<pre><code>price_book = 24.95 number_books = 60.0/100 first_book_cost = 3 additional_copy = 0.75 discounted_books = price_book*number_books total_price = discounted_books*(first_book_cost*1+additional_copy*(60-1)) print "The total price of 60 copies of book is %s$."%(total_price) Suppose the cover price of a book is ...
<p>Sometimes books, especially free ones, have typos and errors.</p> <p>According to the information you provided, the total wholesale cost should be:</p> <pre><code>&gt;&gt;&gt; cover_price_of_book = 24.95 &gt;&gt;&gt; shipping_cost_for_first_book = 3.00 &gt;&gt;&gt; shipping_cost_for_additional_books = 0.75 &gt;&gt...
python
0
4,444
50,876,502
How to change data type of a graph operation in tensorflow?
<p>I am trying to build a decoder which requires Conv2DTranspose , but tensorflow iOS does not have operation MUL for int32 types. Is there a way I can change the data type of the input to MUL in my protobuf file or in keras saved model?</p>
<p>In the creation of the model:</p> <ul> <li>Use <code>K.cast(tensor, K.floatx())</code> </li> <li>Or <code>tf.cast(tensor, tf.float32)</code></li> </ul> <p>If the model is already created, replicate it, adding the operation at the right place (when in Keras, use a <code>Lambda</code> layer for that: <code>Lambda(...
tensorflow|keras
4
4,445
26,896,477
How to write in a specific column
<p>So this is pretty simple I think but I can't seem to get it working.</p> <p>The objective is to simply define a function that will print a string, and the last letter of that string must be in the column <code>70</code>.</p> <p>I did this.</p> <pre><code>def fun(s): print(70*' ' -len(s) , s) </code></pre> <...
<pre><code>def fun(s): print(' '*(70 - len(s)) + s) </code></pre> <p>(if <code>len(s) &gt; 70</code>, you will have a problem)</p>
python|string
2
4,446
57,684,310
Obtain inner functions names
<p>Retrieving inner function names </p> <p>I have tried to use dis.Bytecode and checking for call_function and other instruction values but couldn't obtain the inner function names.</p> <pre><code>def hello(): a = [1,2] b = ["apple", "banana"] for i,v in enumerate(a): print(i,v) print(tuple(zip(a,b))) </c...
<p><code>dis.code_info(hello)</code> solves it!</p>
python-3.x
0
4,447
58,267,752
puffadder (Lombok's alternative for Python) not maintained?
<p>I am looking for some Python library similar to Java's Lombok. I found puffadder 0.1, from 2016, but now that I tried to install it with pip, it does not work.</p> <p>Links:</p> <ul> <li><a href="https://pypi.org/project/puffadder/" rel="noreferrer">https://pypi.org/project/puffadder/</a></li> <li><a href="https:/...
<p>Python 3.7 added <a href="https://docs.python.org/3/library/dataclasses.html" rel="noreferrer">dataclasses</a> Which reminds me of the Lombok in Java. It generates _<em>init</em>_, _<em>repr</em>_ and some more.</p> <pre class="lang-py prettyprint-override"><code>@dataclass() class Name: first_name: str last...
python|lombok|boilerplate
8
4,448
41,402,889
Pyo - How to Play two Sound Files read from RAM Sequentially?
<p>I have two sound files of the same length that I want to play sequentially. Specifically, I want the first file to play three times, and the second file to play once.</p> <p>I can achieve this through a <code>SfPlayer</code> and a <code>TrigFunc</code>, but I'm under the impression that this will read the sound fil...
<p>To play sound files sequentially from RAM, I just needed to call <code>append</code> on the <code>SndTable</code>, like this:</p> <pre><code>from pyo import * s = Server().boot() DOWNLOADS = 'C:\\Users\\mmoisen\\Downloads\\' first = DOWNLOADS + 'first.wav' second = DOWNLOADS + 'second.wav' # Using an array like th...
python|pyo
0
4,449
54,954,172
Correct way to create shareable module (package imports)
<p>I want to create a module that I will share with others however I am quite new to this and am having issues with the final step of tidying it up for other's use. Imagine it is called something like <code>my_module.py</code> and looks like this:</p> <pre><code>import pandas as pd def function_1(a,b): return a*b...
<p>There's nothing inherently wrong with what you are doing. Your module <strong>requires</strong> <code>pandas</code> so you must import it. PEP8 specifies imports should go at the top, not nested within the functions. Doing this will add it as an attribute when you then <code>import my_module</code>. Because you are ...
python|pandas|module
1
4,450
73,580,117
Schedule tasks only in business days Celery
<p>Is it possible to configure scheduling celery tasks to execute only during business days ( not in week days but in business days e.g by accessing a giving business days dataset for example ) using celery beat?</p>
<p>You can do it using a crontab schedule and the <code>day_of_week</code> parameter:</p> <pre class="lang-py prettyprint-override"><code>from celery.schedules import crontab CELERYBEAT_SCHEDULE = { 'businessdays': { 'task': 'your_task_here', 'schedule': crontab(hour=7, minute=30, day_of_week='1-5'), ...
python|celery|celerybeat
0
4,451
41,000,881
Drop rows where column contains a certain value conditional on the value of the columns on the row above
<p>I have the following dataframe</p> <pre><code>df = pd.DataFrame({'State': {0: "case_created", 1: "case_reopened", 2:"email_sent", 3: "case_reopened", 4: "email_sent", 5: "case_reopened", 6 : "email_sent", 7: "case_reopened"}, 'date': {0: '2016-10-13T14:10:41Z', 1: '2016-10-13T14:10:41Z', 2:'2016-10-13T1...
<p>Maybe you could try to locate the rows with 'email_sent'. Then calculate the time difference between 'email_sent' and the entry after last 'email_sent'. Something as follows:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) email_sent = df['State']=='email_sent' rs = [0,] for idx, v in email.iteritems(): if ...
python|pandas
1
4,452
54,412,289
async twisted, synchronous requests per domain (with delay)
<p>let's say i have 10 domains, but every domain need to have delay between requests (to avoid dos situations and ip-banning). </p> <p>I was thinking about async twisted that call a class, requests from requests module have delay(500) , but then another request to the same domain make it delay(250) and so on, and so o...
<p>while using <code>asyncio</code> for async, </p> <pre><code>import asyncio async def nested(x): print(x) await asyncio.sleep(1) async def main(): # Schedule nested() to run soon concurrently # with "main()". for x in range(100): await asyncio.sleep(1) task = asyncio.create_tas...
web-scraping|async-await|python-requests|twisted|python-3.7
0
4,453
52,503,895
Could not successfully extract text from site html
<p>I need to scrape small business information from a public site</p> <p>This is the html format</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="listings"&gt; &lt;ul&gt; &lt;li&gt; &lt;h3&gt;Machine Machine Company Inc&lt;/h3&gt; &lt;/li&gt; &lt;li&gt;&lt;a...
<p>You can try using the text directly as the find_all argument. <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer">https://www.crummy.com/software/BeautifulSoup/bs4/doc/</a> </p> <p>Example:</p> <pre><code>strings_to_search_for = ["Phone", "Estimated Number of Employees"] bus...
python|html|beautifulsoup
1
4,454
37,585,514
How to use Global Variable in Python
<p>I'm trying to write a simple code that uses a global variable. I'm getting the following error</p> <blockquote> <p>UnboundLocalError: local variable 'x' referenced before assignment</p> </blockquote> <pre><code>global x def update(): x = x + 1 x = 0 update() print(x) </code></pre>
<p>Your error occurred because in the function <code>update</code>, you are trying to edit a variable (<code>x</code>) that is not defined, at least not locally. The <code>global</code> keyword should be inside the function, and hence tell that the <code>x</code> you are speaking about is the one defined outside of the...
python-3.x|global-variables
0
4,455
38,543,989
I have a list of strings (html codes) and I want to extract all the emails in each of the string of my list
<p>I have a list of strings:</p> <pre><code>urls = ["url1","url2","url3"] </code></pre> <p>in order to generate another list of strings:</p> <pre><code>for i in range (0,2): htmlist = [urllib.urlopen(url[i]).read() for i in range(0,2) ] </code></pre> <p>When I try to extract the emails from the texts htmlist[i]...
<p>That's because <code>emails</code> takes the value of the last iteration (at <code>htmlist[2]</code>). Move the print statement into the <code>for</code> loop to see <code>emails</code> at each iteration:</p> <pre><code>for i in range (0, 3) : emails = re.findall(r'[\w\.-]+@[\w\.-]+', htmlist[i]) print emai...
python|string|text
0
4,456
26,201,906
Color Pygame integer?
<p>Hi I'm trying to make a black an white gradient in Pygame it works just fine, from the start of surface to the end, but when I try to start after some pixels</p> <pre><code>from pygame import gfxdraw surf = pygame.Surface([256,16], pygame.SRCALPHA, 32) screen.blit(surf,(0,0)) for y in range(0,16,1): for x i...
<p>Because for values of <code>x</code> greater than or equal to <code>192</code>, the result of <code>int(1/(colPos[1]-colPos[0])*x)</code> is larger than <code>255</code>, and therefore not a valid argument.</p> <pre><code>&gt;&gt;&gt; for x in range(190, 195): print x, int(x / 0.75) # I simplified the equation ...
python|colors|integer|pygame|gradient
1
4,457
28,379,607
plot time series with pandas ATTRIBUTE ERROR
<p>I am having a problem with plotting a data frame. The data frame looks like this: </p> <pre><code> 0 1 0 2012-01-01 00:00:00 123900.776741 1 2012-01-01 00:00:05 123900.776741 2 2012-01-01 00:00:10 123900.776741 3 2012-01-01 00:00:15 123900.776741 4 2012-01-01 00:00:20 1239...
<p>Most likely it's because your column with the time is not the index.</p> <p>Assuming the exact same dataframe, try the following :</p> <pre><code># Renaming the columns for more clarity df.columns = ['Time', 'Data'] # setting Time as index df = df.set_index('Time') # Plotting df['Data'].plot() </code></pre>
python|python-2.7|pandas
0
4,458
34,475,014
How to create a Shared Access Signature for a container with the Azure Python SDK
<p>I am trying to create a valid Shared Access Signature URL for a container in Azure storage, using the Azure Python SDK. I'm trying to generate it to be effective immediately, to expire after 30 days, and to give read &amp; write access to the whole container (not just the blob). The below code works fine, and it p...
<p>The isoformat method appends microseconds to the string, AFAICT this is not valid in ISO8601.</p> <p>If you modify your code like this:</p> <pre><code>todayPlusMonthISO = todayPlusMonth.replace(microsecond=0).isoformat() + 'Z' </code></pre> <p>The generated string becomes valid.</p> <p>For example, before you ha...
python|azure|sdk|azure-storage|azure-blob-storage
3
4,459
70,617,179
Python sqlite3 how to dynamically search for null
<p>I am try select, modify, or delete rows using sqlite3 which can have a null value in a column. I am also trying to this dynamically so I can search for null value by using the Python literal <code>None</code>.</p> <p>This works just fine:</p> <pre class="lang-py prettyprint-override"><code>name = &quot;John&quot; cu...
<p>While you could conjure up a one-liner to construct the right query, it's simpler to branch based on the value.</p> <pre class="lang-py prettyprint-override"><code>if name is None: stmt = 'DELETE FROM users WHERE name IS NULL' cursor.execute(stmt) else: stmt = 'DELETE FROM users WHERE name = ?' curso...
python|sqlite
1
4,460
73,148,327
Merging multiple dictionaries that have dictionaries in list
<p>I have several dictionaries (perhaps 10s of them) that formed like below:</p> <pre><code>{'stdout': [{'foo': 'A', 'bar': 'B', 'host': None, 'count': 135}, {'foo': 'C', 'bar': 'B', 'host': 'egg', 'count': 28}, {'foo': 'D', 'bar': 'E', 'host': 'apple', 'count': 1}, {'foo': 'A', 'bar...
<h3>One approach</h3> <pre><code>from collections import defaultdict from operator import itemgetter # creat a dictionary (defaultdict) to put the dictionaries with matching foo, bar, host in the same list groups = defaultdict(list, {(d['foo'], d['bar'], d['host']): [d] for d in dictB['stdout']}) for d in dictA[&quot;...
python|dictionary
5
4,461
55,618,050
getting a NameError error with my recursive binary search method?
<p>Hi I'm trying to write a recursive binary search but I'm getting an NameError. My code is as follows:</p> <p>This is for a self development project im working on in python.</p> <pre class="lang-py prettyprint-override"><code> def search(self, list, list_start, list_end, search_for): if list_end &gt;= li...
<p>It looks like your search function is inside a class. You need to call your search function using <code>self.search(self, list, list_start, list_end, search_for)</code></p>
python|recursion|search|binary
2
4,462
49,848,261
Python - Loop printing too many times when reading from an imported file
<p>Im writing a program to output a table that calculates pay roll. it is reading from an imported file. </p> <p>The file I'm using to test contains:</p> <ul> <li>Barb,Moran,51,12.85</li> <li>Joy,Rinehimer,30,9.35</li> <li>Joe,Bellucci,45,9.55</li> <li>Dave,Flaim,37,17.70</li> </ul> <p>The idea here was to take each...
<p>The inner loop of <code>outputs()</code> is the culprit. Remove it.</p> <pre><code>def outputs(infile): paylist = [] count = 0 for lines in infile: individual = lines.split(",") first = ("{0:7}".format (individual[0])) print(first, end = "") last = ("{0:12}".format(indiv...
python|list|loops
0
4,463
66,523,464
find more than one value of average on list python
<p>There is a list on python that i want to try to find the average of each value in [],there is 3 value in each [] and i want to find the average of it,so how is it?</p> <pre><code>[[8.07, 8.06, 8.07], [8.27, 8.34, 8.32], [8.64, 8.98, 8.8], [9.27, 9.29, 9.3], [9.52, 9.58, 9.52], [9.69, 9.7, 9.05], [10.19, 10.16, 10.17...
<p>For an array containing each averages:</p> <pre><code>averages = [len(arr)] for arr in myArray: averages.append(sum(arr) / len(arr)) </code></pre>
python
2
4,464
64,088,811
AJAX is not passing hard-coded data
<p>In <code>index.js</code> I have:</p> <pre><code> $(&quot;#weather_form&quot;).on(&quot;submit&quot;, function(event){ event.preventDefault(); $.ajax({ url: &quot;/weather/&quot;, type: &quot;POST&quot;, data: {type_of_person: &quot;1&quot;, exercise: &quot;2&quot;, unit: &q...
<p>I think the form could not read data as you are sending <code>contentType</code> of <code>json</code>. Just removing that line should work. Also, you have to add <code>csrf</code> header to post request. So:</p> <pre><code>$.ajax({ url: &quot;/weather/&quot;, type: &quot;POST&quot;, data: { ...
javascript|python|json|django|ajax
1
4,465
53,202,350
beginner, netmiko from bash awk sed question
<p>Greets.</p> <p>I understand that python isn't shell. I'm using this project as an excuse to get a boost into python though. But I'm stuck. Code is below, with embedded questions</p> <p>If it matters I'm working in a jupyter notebook in python 3.something on centos7 and cisco 3650 switches.</p> <pre><code>impor...
<p>You probably should look into the network-tools library which has a small set of command-line tools that use Netmiko. One of those tools is netmiko-grep. See here:</p> <p><a href="https://pynet.twb-tech.com/blog/automation/netmiko-grep.html" rel="nofollow noreferrer">https://pynet.twb-tech.com/blog/automation/netmi...
python|sed|grep|paramiko|cisco
0
4,466
53,053,602
Which technique is most appropriate for identifing various sentiments in the same text using python?
<p>I'm studying NLP and as example I'm trying to identify what feelings are in customer feedback in the online course platform.</p> <p>I was able to identify the feelings of the students with only simple sentence, such as "The course is very nice, I learned a lot from it", "The teaching platform is complete and I real...
<p>You can think that comas, other punctuation marcs and some conjunctions and prepositions actually split sentences. This actually goes beyond code into the field of linguistics as they sometimes, but not always, separate sentences.</p> <p>In the 2nd case you actually have two sentences: "The course is very good" -, ...
python|scikit-learn|deep-learning|nlp|supervised-learning
1
4,467
71,586,860
torch matrix equaity sum operation
<p>I want to do an operation similar to matrix multiplication, except instead of multiplying I want to check equality. The effect that I want to achieve is similar to the following:</p> <pre class="lang-py prettyprint-override"><code>a = torch.Tensor([[1, 2, 3], [4, 5, 6]]).to(torch.uint8) b = torch.Tensor([[1, 2, 3], ...
<p>You can use <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.repeat.html#torch.Tensor.repeat" rel="nofollow noreferrer">torch.repeat</a> and <a href="https://pytorch.org/docs/stable/generated/torch.repeat_interleave.html#torch.repeat_interleave" rel="nofollow noreferrer">torch.repeat_interleave</a>:</...
pytorch
3
4,468
5,587,816
Extracting XML nodes in Python
<p>This is part of an XML document that I have:</p> <pre><code>&lt;tr&gt;&lt;td&gt;Image:&lt;/td&gt;&lt;td&gt; &lt;a href="http://live.astrometry.net/status.php?job=alpha-201104-6758393&amp;amp;get=fullsize.png"&gt;fullsize.png&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>I need to extract the href attribute "of ...
<p>OK, the final elegant (I hope ;) answer with a single XPath expression</p> <pre><code>from lxml import etree root = etree.fromstring(your_text) print root.xpath("//td[contains(text(), 'Image')]/following-sibling::td/a/@href")[0] </code></pre>
python|xml
2
4,469
5,459,896
Low volume Open source Message Board suggestions?
<p>Looking for a low volume, probably no more that 20-30 users, Open Source message/bulletin board. Obviously must be written in something which our web server supports, PHP/Python/Ruby etc. Any suggestions?</p> <p>Thanks, Nick</p>
<ul> <li><a href="http://fudforum.org/forum/" rel="nofollow">FUDForum</a></li> <li><a href="http://www.phpbb.com/" rel="nofollow">phpBB</a></li> </ul> <p>and lots more. The above are designed to handle very large boards, but can be used with low traffic websites. All PHP</p>
php|python|html|ruby
2
4,470
62,882,561
String to pandas Dataframe based on columns
<p>I am sending an ajax GET request to a flask server (<code>http://localhost:5000/req/?q=139,2,10,60,5,1462,7,5,6,9,17,78</code>) in order to retrieve some values and assign them to a Dataframe. Doing it manually, it works fine:</p> <pre><code>df = pd.DataFrame(data=[[139,2,10,60,5,1462,7,5,6,9,17,78]],columns=['col1'...
<p>The args is resolved as a string, so after <code>t = request.args[&quot;q&quot;]</code>, <code>t</code> is <code>&quot;139,2,10,60,5,1462,7,5,6,9,17,78&quot;</code>, you need a list of int</p> <pre><code>@app.route('/req') # GET only is default method def foo(): t = request.args[&quot;q&quot;] t = [int(val) ...
python|pandas|numpy|dataframe|flask
1
4,471
67,604,174
What to use instead of DO_NOTHING to only delete one field?
<p>I want to link two models like this</p> <pre><code>class t_data(models.Model): receiver = models.TextField() file_desc = models.TextField() file = models.FileField(upload_to='files') </code></pre> <p>another model :</p> <pre><code>class transaction_detail(models.Model): transaction_id = models.Foreig...
<p>Check options under on_delete argument in <a href="https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ForeignKey" rel="nofollow noreferrer">this link</a>. You can use the <code>SET_NULL</code> option which sets the data as <code>NULL</code> but as described the field should nullable. <code>DO_...
python|sql|django|database|django-models
1
4,472
67,318,688
Using help() on a string instance shows "No Python documentation found for 'x'"
<p>I have a program like this</p> <pre><code>&gt;&gt;&gt; str1 = 'Python' &gt;&gt;&gt; help(str1) No Python documentation found for 'Python'. Use help() to get the interactive help utility. Use help(str) for help on the str class. </code></pre> <p>even if I modify this <code>str1</code> with other strings I get the sam...
<p>From the <a href="https://docs.python.org/3/library/functions.html#help" rel="nofollow noreferrer"><code>help()</code> docs</a>:</p> <blockquote> <p>If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed ...
python|python-3.x
2
4,473
60,352,880
How to get all values from a list of dict that matches key prefix?
<p>I have a list of dictionaries, for example:</p> <pre><code>[ { 'id': '11110110011', 'a_dept_performance': 3, 'a_group_performance': 2, 'a_user_performance': 3, 'f_service': 4, 'f_facility_service': 2, 'k_helpful': 2 ... }, { 'id': '11110110012', 'a_dept_performance': 3, 'a_group_performance...
<p>you can use <code>collections.defaultdict</code> to store your values:</p> <pre><code>from collections import defaultdict my_prefixes = {'a_', 'f_', 'k_'} result = defaultdict(list) for d in my_list: for k, v in d.items(): if k[:2] in my_prefixes: result[k[:2]].append(v) print(result) </cod...
python|list|dictionary
1
4,474
11,396,216
What are the limitations of using Django nonrel with Google App Engine?
<p>I understand that full django can be used out of the box with CloudSQL. But I'm interested in using HRD. I'd like to learn more about what percentage of django can be used with nonrel. Does middleware work? How about other features of the framework like i18n, forms, etc. Also does nonrel work with NDB?</p> <p>The b...
<p>The big limitation is that the datastore doesn't do JOINs, so anything that uses JOINS, like many-to-many relations won't work.</p> <p>Any packages/middleware that uses many-to-many won't work, but others will.</p> <p>For example, the sessions/auth middleware will work. But if you use permissions with auth, it wo...
django|google-app-engine|google-cloud-datastore|python-2.7
2
4,475
10,997,239
avoid expensive setup in timeit.repeat() benchmark
<p>I'm trying to measure the execution time of a small Python code snippet of mine and I'm wondering what's the best way to do so.</p> <p>Ideally, I would like to run some sort of setup (which takes a loooong time), then run some test code a couple of times, and get the minimum time of these runs.</p> <p><code>timeit...
<p>Have you tried using <code>datetime</code> to do your timing for you?</p> <pre><code>start = datetime.datetime.now() print datetime.datetime.now() - start #prints a datetime.timedelta object` </code></pre> <p>That will give you the time elapsed and you can control where it started with tiny overhead.</p> <p>Edit:...
python|profiling|benchmarking|timing|timeit
1
4,476
11,028,599
exposing constant in Boost.Python outside of any class scope
<p>I have following constant in C++ code</p> <pre><code>enum { BOUNDARY_NONE = -1, }; </code></pre> <p>I would like to expose it to Python with Boost.Python so that it will be available in Python as just <code>BOUNDARY_NONE</code>. I dont want to define it under any aditional scope.</p> <p>I found how to do this...
<p>I haven't found anything better than:</p> <pre><code>scope().attr("BOUNDARY_NONE") = BOUNDARY_NONE; </code></pre>
python|boost|boost-python
9
4,477
63,697,207
ask pip to use ssh instead of https when doing pip freeze for local module's source repo url
<p>I am using local packages in my project. My code is version controlled on GitLab.</p> <p>When I do pip freeze on my project, I get below output in my requirements.txt file:</p> <pre><code>-e git+https://gitlab.com/someuser/someproject.git@1234567890#egg=commonlogger&amp;subdirectory=svcs/common/commonlogger </code><...
<p><code>pip</code> cannot do it so you need to use an external tool. For example with <code>sed</code>:</p> <pre><code>pip freeze | sed &quot;s!git+https://!git+ssh://!&quot; &gt;requirements.txt </code></pre>
python|pip|gitlab
1
4,478
17,800,796
Free PaaS without / with less port forwarding to bind to custom ports?
<p>I am currently engaged in a project which has the following requirements. </p> <ol> <li><p>The application is written in Python, </p></li> <li><p>The Application has two threads running at any instance, one is the 'server' and the other is the 'app-logic'. </p></li> <li><p>The server listens on port 6000 (or any su...
<p>I have found one way! That is to use the DIY cartridge (Do it yourself) in Openshift, install Python and run "Websockets". Of course this still means that the transmissions should be of HTTP. </p> <p>The other option is to move to IaaS (infrastructure as a service) rather than PaaS. </p>
python-2.7|httprequest|openshift|paas
0
4,479
61,013,645
InvalidArgumentError- was explicitly assigned to /device:GPU:1 but available devices are [ /job:localhost/replica:0/task:0/device:CPU:0,
<p>Any help would be appreciated. I am new to the tensorflow and programing in general. I am following an instruction in github (<a href="https://github.com/experiencor/keras-yolo3" rel="nofollow noreferrer">https://github.com/experiencor/keras-yolo3</a>) to learn object detection by YOLO-3. after running code below.Pl...
<p>Check your config.json file, if you are only using a single GPU, you should change the &quot;gpu&quot; argument under &quot;train&quot; to &quot;0&quot; instead of the default &quot;0,1&quot;</p> <pre><code>&quot;train&quot;: { &quot;gpu&quot;: &quot;0&quot; } </code></pre>
python|tensorflow|error-handling|gpu
1
4,480
60,878,959
AttributeError: 'numpy.ndarray' object has no attribute 'save'
<p>i have short code for crop image all image in folder that i labeled and save as csv using opencv like this:</p> <pre><code>import os, sys from PIL import Image import cv2 import pandas as pd # The annotation file consists of image names, text label, # bounding box information like xmin, ymin, xmax and ymax. ANNOT...
<p>try using </p> <pre><code>cv2.imwrite(path,img_to_save) </code></pre> <p>in the last line.</p>
python|pandas|opencv
12
4,481
66,294,870
Is there a way to get legal moves for the person whos turn its not? python-chess
<p>I am interested in making a chess algorithm. For this, I will be using the python-chess library. However, to make a good algorithm I need to be able to return the opposing persons legal moves even if it isn't their turn. So in the start of the game it would return</p> <p>board.legal_moves() -&gt; [A2A4, A2A1, B2B4, ...
<p>A solution would be to keep track of the legal moves in a list from the beginning of the game:</p> <pre><code>legal_moves = [] current_legal_moves = board.legal_moves() legal_moves.append(current_legal_moves) </code></pre> <p>Then you can simply get the list of your enemy's legal moves by:</p> <pre><code>enemy_lega...
python|python-3.x|chess|python-chess
1
4,482
72,694,718
Automatically fill in the previous value in an excel cell in Python
<p>I'm a beginner in Python. I have some excel issue.</p> <p>1.I have excel file.</p> <pre><code> | Name | Score | |Alex | 83.5 | |Annie | | |Bob | | |Lucy | 243.1 | |David | | |Kate | | |Cathrine | | |Rose | 757.5 | ...
<p>You can use</p> <pre><code>df.ffill(axis = 0) </code></pre> <p>Example</p> <pre><code>import pandas as pd df=pd.DataFrame({&quot;A&quot;:[5,3,None,4], &quot;B&quot;:[None,2,4,3], &quot;C&quot;:[4,3,8,5], &quot;D&quot;:[5,4,2,None]}) df.ffill(axis=0) </code></pre...
python|excel
0
4,483
72,552,764
How can I use return of fixture function and data which will be used as parameterized in pytest test case
<p>I get some parameters from command lines. Then I want to use these parameters as variables in test cases. I want to use parametrised test in same test case. Is it correct to run it as below?</p> <p>conftest.py</p> <pre><code>import pytest def pytest_adoption(parser): parser(&quot;--arg1&quot;,action=&quot;store...
<p>I found answer as fixture function will be given as a test argument:</p> <pre><code>@pytest.mark.parametrize(&quot;name,surname,age&quot;,test_data) def test_example(getArg,name,surname,age): assert type(getArg) == tuple arg1,arg2 = getArg if arg1 == &quot;first&quot; &amp;&amp; arg2 == &quot;second&quot...
python|fixtures|parameterized-unit-test
0
4,484
59,420,708
How to print list value in same line?
<p>How Can i print only value of list in same line ? My Code is:</p> <pre><code>t = int(input()) for case_no in range(1, t+1): n = int(input()) li = list() for i in range(1, n+1): if n % i == 0: li.append(i) print("Case {}: {}".format(case_no, li, sep=' ', end='')) </code></pre> <p...
<p>You can use print to do it:</p> <pre><code>data = [[1,2,3,4], [2,4,6]] for idx,d in enumerate(data,1): print( f"Case {idx}:", *d) # "splat" the list </code></pre> <p>prints:</p> <pre><code>Case 1: 1 2 3 4 Case 2: 2 4 6 </code></pre> <p>Using the splat (<a href="https://stackoverflow.com/questions/2322355/...
python|list
0
4,485
59,216,243
Argument not defined despite it being defined above
<p>i am currently experimenting with some code that depicts a sales report. Below is my current code:</p> <pre><code>total = 0 items = "" def adding_report(report_type): report_type = input("Define the type of report: ") while True: adding_report("A") project = input("Input an integer to add to the tota...
<p>Your issue here is one of scope: <code>report_type</code> is only defined in the <code>adding_report</code> function. When you call the function, it defines <code>report_type</code> - but when the function returns, that definition is lost. </p> <p>Try returning <code>report_type</code> from the function, and then a...
python
3
4,486
59,429,218
Why does putting the word "Admin" in the route of a flask application cause the page to 404?
<p>I'm creating a new route in our flask application. When I go to add an 'n' to the end of 'tableAdmi', it causes the new route to 404. What in the world could be causing this?</p> <p>I have the following routes</p> <pre><code>@application.route('/console/tableAdmi') def tableAdmin2wtf(): return flask.render_t...
<p>It's not the n letter that's causing the error, but the <code>/</code> at the end of the URL. </p> <p><code>example.com/tableAdmin</code> and <code>example.com/tableAdmin/</code> are different URLs in this context. You need to handle them separately or add to the same handler.</p> <p>You can do this:</p> <pre cla...
python|flask|uwsgi
3
4,487
59,378,424
IndexError: string index out of range while working with random module
<p>I'm making password generator in python and this is the error I'm stuck with. Here's my code:</p> <pre><code>import random symbols = 'qwertyuiopasdfghjklzxcvbnm' choosing_len = int(input('&gt; ')) def password_generating(): def random_letter(): zero = 0 lenght = len(symbols) letter_i...
<p>The error is here:</p> <pre><code>letter_index = random.randint(zero, lenght+1) </code></pre> <p>Unlike <code>range(a, b)</code>, that gives numbers from a upto b, not including b, i.e. <code>a &lt;= x &lt; b</code>, <a href="https://docs.python.org/3/library/random.html#random.randint" rel="nofollow noreferrer"><...
python|python-3.x|string|random|index-error
4
4,488
73,144,272
TypeError: 'NoneType' object is not iterable in Phyton
<p>My program removes the substring 'rotten' from the string list:</p> <pre><code>bag_of_fruits = [&quot;apple&quot;,&quot;rottenBanana&quot;,&quot;apple&quot;] def remove_rotten(bag_of_fruits): bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits] return [x.lower() for x in bag_of_fruits] pr...
<p>Try to change the name of the variable to avoid the error</p> <pre><code>bag_of_fruits = [&quot;apple&quot;,&quot;rottenBanana&quot;,&quot;apple&quot;] def remove_rotten(bag_of_fruits): # ---- &gt; variable name should be changed bag_of_fruits_edited = [x.removeprefix('rotten') for x in bag_of_fruits] ...
python|typeerror|nonetype
0
4,489
62,350,290
Sending email using Python Script
<p>I am trying to write out a function that will automate sending emails to a specific account. When I run my code I get the error message:</p> <pre><code>Email could not send Traceback (most recent call last): File "email.py", line 1, in &lt;module&gt; import smtplib File "C:\Users\User\Anaconda3\lib\smtplib....
<p>Most likely one of your own modules in the module search path (including the current working directory) is actually called <code>email</code>. This will cause Python to pick up that module instead, and it will shadow the <code>email</code> module from the standard library, leading to that import error.</p> <p>Renam...
python|smtplib
3
4,490
62,413,933
Type hinting for ctypes
<p>Can I type hint a <em>ctype</em> type?</p> <pre><code>from ctypes import * def wrap_function(library: str, name: str, restype, argtypes) -&gt; *What goes here*: """Simplify wrapping ctypes functions""" func = library.__getattr__(name) func.restype = restype func.argtypes = argtypes return func ...
<p><code>CFUNCTYPE</code> is a function prototype not a <code>ctypes</code> type. You can use <code>CFUNCTYPE</code> to define a function type and then wrap it in a pointer e.g.</p> <pre><code>from ctypes import * POINTER(CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))) </code></pre> <p>You can use the defined type ...
python|ctypes|type-hinting
2
4,491
35,352,924
Keep the order of list in sql pagination
<p>I have a list with an order of insertion. I want to paginate the results using the same order. As you can see currently the output will be a different order. </p> <pre><code>following_companies_list_data = Company.query.filter(Company.id.in_(['2', '24', '1', '7', '373'])).paginate( page, per_page=10, er...
<p>Solution based on <a href="https://stackoverflow.com/a/9475755/5341877">this answer</a> from related question</p> <pre><code>company_ids = ['2', '24', '1', '7', '373'] order_expressions = [(Company.id==i).desc() for i in company_ids] query = Company.query.filter(Company.id.in_(company_ids)).order_by(*order_expressi...
python|postgresql|flask|sqlalchemy|flask-sqlalchemy
8
4,492
58,839,769
How to set AWS lambda timeout using request parameters?
<p>I want to build an API where end user can set timeout. Not to be confused with the usual timeout setting in serverless.yml file.</p> <pre class="lang-py prettyprint-override"><code>def main(event, context): timeout=event["timeout"] # use this </code></pre>
<p>One solution would be to globally configure your lambda functions to time out at the maximum (15 minutes, currently).</p> <p>Then your handler would need to fork your lambda process, and have the parent process kill the child process (which is where your actual application code will be) after the user-specified amo...
python|amazon-web-services|aws-lambda|serverless-framework
2
4,493
31,543,164
Django url.py rewrite to a different host
<p>this was my <strong>url.py</strong></p> <pre><code>urlpatterns = patterns('', url(r'/newm/$', views.CreateManView.as_view(), name='create_man'), </code></pre> <p>I've changed it to:</p> <pre><code>url(r'http://y.y.y.y/newm/$', views.CreateManView.as_view(), name='create_man'), </code></pre> <p>but result in a ca...
<p>Check out <a href="https://github.com/jezdez/django-hosts" rel="nofollow">django-hosts</a>, it does exactly that.</p> <p>As for having it as a feature in Django, a core dev commented on <a href="https://code.djangoproject.com/ticket/8896" rel="nofollow">this question</a>:</p> <blockquote> <p>This has been solved...
python|django|django-urls
1
4,494
31,677,345
Add jar to pyspark when using notebook
<p>I'm trying the mongodb hadoop integration with spark but can't figure out how to make the jars accessible to an IPython notebook.</p> <p>Here what I'm trying to do:</p> <pre><code># set up parameters for reading from MongoDB via Hadoop input format config = {"mongo.input.uri": "mongodb://localhost:27017/db.collect...
<p>Very similar, please let me know if this helps: <a href="https://issues.apache.org/jira/browse/SPARK-5185" rel="noreferrer">https://issues.apache.org/jira/browse/SPARK-5185</a></p>
python|jar|apache-spark|ipython-notebook|pyspark
5
4,495
31,651,759
What is the relationship between Python 3 built-in types?
<p>In python 3 everything is a object. I drew a diagram about relation of classes. Is this diagram correct?</p> <p><a href="https://i.stack.imgur.com/pJrhx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pJrhx.jpg" alt="enter image description here"></a></p> <p>the hard part is about type and objec...
<p>As far as I know, the class relations are kind of like this in Python 3:</p> <ul> <li>Every class is a <strong>subclass</strong> of <code>object</code></li> <li>Every class is an <strong>instance</strong> of <code>type</code></li> </ul> <p>Every class is created by the <code>type</code> class or an other metaclass...
python
3
4,496
15,694,231
A* Search - least number of hops?
<p>I'm trying to create an A* pathfinding algorithm, however I'm having a little trouble getting off the ground with it. A little background:</p> <p>I am by no means versed in pathfinding algorithms, however I did touch upon this subject a couple years ago (I've since forgotten everything I've learned). I play EVE Onl...
<p>If the number of "hops" is what matters to you, then consider that to be your distance, meaning that if the two locations are connected by a single hop, the distance is one. </p> <p>For A*, you'll need two things:</p> <ol> <li><p>The costs from one location to each neighbor, in your case, this seems to be constant...
php|python|path-finding|a-star
4
4,497
49,163,167
Rename a sequence of names in pandas dataframe
<p>I have a dataframe in pandas containing 11 columns. These columns are all named "subsidence".</p> <p>I would like to rename the columns "subsidence 1", "subsidence 2", "subsidence 3" etc. Is there a quicker way to do this than using <code>df.rename</code>. </p>
<p>You can set <code>df.columns</code> directly with a list comprehension:</p> <pre><code>df.columns = ['subsidence '+str(i) for i in range(1, 12)] </code></pre>
python|pandas|variables|dataframe|rename
1
4,498
49,328,869
Please explain Python's "pass-by-pointer" approach
<pre><code>a = 5 </code></pre> <p>a is not holding the value 5 itself but only an address to the object 5, correct? So it is a reference variable.</p> <pre><code>b = a </code></pre> <p>Now it seems to me that <code>b</code>, instead of again holding the address of <code>a</code>, is actually holding the <code>"valu...
<p>There is no discrepancy. </p> <p>Think of the assignment <code>a=5</code> as putting a labelled tag 'a' around 5.</p> <p>Now if you set <code>b=a</code>, python looks what is labelled <code>a</code> (5) and attaches a new label <code>b</code> to it.</p> <p>Assignment operators never reference the <em>name</em> of...
python|variables|pass-by-reference|pass-by-value
2
4,499
25,297,203
Python- list with arrays shape issues
<p>I'm creating a code to run a perceptron algorithm and I can't create a random matrix the way I need it:</p> <pre><code>from random import choice from numpy import array, dot, random unit_step = lambda x: -1 if x &lt; 0 else 1 import numpy as np m=3 #this will be the number of rows allys=[] for j in range(m): aa...
<p>The error message actually tells you what is wrong. The result of your multiplication is a (1,3) array (2D array, one row, three columns), whereas you try to add it into a 3-element vector.</p> <p>Both arrays have three elements in a row, so if you do this:</p> <pre><code>w = w + eta * error * x </code></pre> <p>...
python|numpy|shapes|dimensions
3