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
2,200
68,598,191
Working on Kivy App for expense tracking... unable to align the gridlayout
<p>I am working on an expense app for myself. in the second screen i want to move &quot;January&quot; and &quot;year-to-date&quot; label above close to &quot;available balance&quot; and move below section above. I have spent few days but unable to find a solution. I was wondering if you someone could help me on this.</...
<p>Here is a modified version of the <code>&lt;IndividualExpense&gt;:</code> rule in your <code>kv</code>:</p> <pre><code>&lt;IndividualExpense&gt;: name: 'indExp' BoxLayout: orientation: 'vertical' spacing: '8dp' MDToolbar: title: 'Cell Phone' GridL...
python|web-applications|kivy
0
2,201
67,283,354
Running a for loop for higher number of iterations in python
<p>I have written a piece of code which I am trying to run in my local machine of 8GB ram.</p> <pre><code>import numpy as np tasks = ['A','B','C','D'] tasks_pass_prob = [0.7,0.1,0.5,0.3] task_probs = tuple(zip(tasks,tasks_pass_prob)) N = 1000000 n = 1 results_dict = {} for _ in range(N): for t,p in task_probs: ...
<p>Actually, your code is not hanging but your processes are so big that it's taking a long time to run...<br /> It is not the issue of RAM...</p> <p>And why did you use <code>for _ in range(N)</code>?</p> <p>I suggest you write it like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np tasks...
python|python-3.x|numpy|dictionary|tuples
2
2,202
66,214,155
Python Code Not Selecting Correct Dictionary
<p>I am trying to loop through and select the two <code>class_id</code> values I want, and then compare their <code>center_x</code> and <code>center_y</code> values together. If they are within a certain range, which I now have set at 0.10 it will print within range. However when I run my code now and print out the <c...
<p>I think the problem with the code is using <code>object1</code> and <code>object2</code> which are initialised in the loop and outside the loop they will have the value of the last element before the loop ends. In your case the loops</p> <pre><code>for _class in results: for object1 in _class[&quot;objects&quot;...
python|json|function|loops|dictionary
0
2,203
69,121,808
flask-sqlalchemy Get difference between 2 date from database
<p>i want to calculate the difference between 2 days from <em>mysql</em> database i have the script like this</p> <pre><code>@app.route('/',methods=['GET','POST']) def show(): dura= [] dates_start=(MyTask.query.get('dates_start')) d1=(MyTask.query.with_entities(MyTask.date...
<p>Get date between in two date:</p> <p>from datetime import datetime</p> <pre><code>date1_ = datetime.timedelta(days=1) # 1 or another number date2_ = dadtime.timedelta(days=10) # 10 or another number Model.filter(Model.date_column.between(date1_,date2_),).all() </code></pre> <p>Get differance date between in two da...
python|html|mysql|flask-sqlalchemy
0
2,204
63,286,615
Matching pandas dataframe rows in a spreadsheet with Xlwings
<p>I am writing a script to:</p> <ul> <li>import spreadsheets as pandas dataframes</li> <li>export, sort and compile them in a single XL spreadsheet via Xlwings</li> </ul> <p>My issue is that the inputs do not have the exact same number and values of indexes. I am trying to ensure that every row would be matching to sh...
<p>I honestly did not understand your issue, may you check and revise it ? It sounds nonsense to me.</p> <blockquote> <p>My issue is that the inputs do not have the exact same number and values of indexes. I am trying to ensure that every row would be matching to show the right values in the right rows for all datafram...
python|excel|pandas|dataframe|xlwings
0
2,205
49,095,038
Can't make dynamic dimension in tensorflow variable
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>a = tf.placeholder(dtype = tf.float64, shape = (10, None)) b = tf.Variable(tf.random_normal((20, 10), dtype = tf.float64), dtype = tf.float64) c = tf.matmul(b, a) d = tf.shape(a)[1] e = tf.Variable(tf.random_normal((d, d), dtype = tf.flo...
<p>No, it's not possible. Tensorflow doesn't allow <em>dynamic</em> shape in variable definition, because it can't allocate the memory of arbitrary size during graph definition. So the dimensions of <code>e</code> must be known <em>statically</em>.</p>
python|variables|tensorflow|initialization|tensor
0
2,206
72,460,993
Is it possible to write a code in Python for a USB stick so when you plug it it downloaded all the files from the pc?
<p>was interested is it possible to wirte a code in Python for a USB stick so when you plug the USB in a pc, it downloades every file from the pc without showing any message boxes that are like “Files are being downloaded”?</p>
<p>that was probably possible back in windows XP, however on anything newer than that then answer is <strong>NO</strong>, because a computer won't simply run any software without the user permission.</p>
python|usb
0
2,207
45,132,963
Adding on values to a key based on different lengths
<p>I'm trying to add on values to a key after making a dictionary.</p> <p>This is what I have so far: </p> <pre><code>movie_list = "movies.txt" # using a file that contains this order on first line: Title, year, genre, director, actor in_file = open(movie_list, 'r') in_file.readline() def list_maker(in_file): ...
<p>Sorry if the output isn't completely what you want, but here's how you should do it:</p> <pre><code>d = {} for line in in_file: l = line.split(",") title_year = (l[0], l[1]) people = [] for i in range(4, len(l)): people.append(l[i]) # we append items to the list... d = {title_year: peo...
python|python-3.x
0
2,208
61,369,275
mypy "Optional[Dict[Any, Any]]" is not indexable inside standard filter, map
<p>Given the following code:</p> <pre class="lang-py prettyprint-override"><code>from typing import Optional, Dict def foo(b: bool) -&gt; Optional[Dict]: return {} if b else None def bar() -&gt; None: d = foo(False) if not d: return filter(lambda x: d['k'], []) </code></pre> <p>mypy 0.770...
<p>The type-narrowing that happens after an <code>if</code> or <code>assert</code> doesn't propagate down to inner scopes that you've bound that variable in. The easy workaround is to define a new variable bound with the narrower type, e.g.:</p> <pre><code>def bar() -&gt; None: d = foo(False) if not d: ...
python|python-3.x|type-hinting|mypy
2
2,209
57,761,300
How to apply bearer token with a get?
<p>I'm trying to access an API that requires a bearer token. I am able to get the bearer token, but I do not understand the next steps. The token is required in the header, but a get only accepts 2 parameters which would be my url and parameters?</p> <p>I have been trying to mimic the companies javascript example. <a ...
<p>if i understand the problem correctly you have got a bearer token from the post request and have to use the same token in the next GET API call in the header. To pass the headers use headers as keyword argument to the requests.get method</p> <p>One example of headers with bearer token: {'Authorization': 'Bearer &lt;...
python-3.x|python-requests
0
2,210
58,024,895
Python: Only return matching values in up to three lists but ignore empty lists
<p>I've created three lists of integers (a, b and c) and these may or may not contain any values. I want to create a new list (newList) based on these existing lists:</p> <ul> <li>If all three lists contain values, I want to populate newList with only the values that are common to every list (e.g. a = [1,2,3], b = [2,...
<p>You could approach it like this, generalized, and using sets:</p> <pre><code>def inner_join_nonempty(*iterables): sets = (set(iterable) for iterable in iterables) nonempty_sets = [s for s in sets if s] return set.intersection(*nonempty_sets) if nonempty_sets else set() </code></pre> <p>Usage for your e...
python|list|inner-join
3
2,211
42,191,147
Posting a default value with serializer in DRF
<p>I am attempting to post a default value.</p> <p>In plain English, this is how I want it to work:</p> <ol> <li>If data has no "tag" field (s)</li> <li>Check to see if tag "none" exists (for 'owner')</li> <li>If tag "none" exists, create the m2m</li> <li>If tag "none' doesn't exist, create the tag none (for 'owner')...
<p>Try setting <code>default=None</code> in your tag field of ItemSerializer.</p> <p>Your ItemSerializer should now looks like:</p> <pre><code>class ItemSerializer(serializers.ModelSerializer): tag = TagSerializer(default=None, many=True, read_only=False) info = InfoSerializer(many=True, read_only=True) ....
python|django|django-rest-framework
0
2,212
22,773,884
Python asking game
<p>I'm making a question game(along the lines of 20 questions) but I want my program to only ask a question once. I have tried using enumerate to give each string in ques a value then had an if statement saying if i = i: i != 1 hoping that that would change the value of i to something else so that it doesn't repeat the...
<p>Do something like this:</p> <pre><code>for question in random.shuffle(ques): #your code here, for each question </code></pre> <p>BTW if your code is as-is, as you wrote it, it generates an endless loop. Try to reformule it.</p>
python
3
2,213
45,639,240
Getting same value for Precision and Recall (K-NN) using sklearn
<p>Updated question: I did this, but I am getting the same result for both precision and recall is it because I am using <code>average ='binary'</code>?</p> <p>But when I use <code>average='macro'</code> I get this error message:</p> <blockquote> <p>Test a custom review messageC:\Python27\lib\site-packages\sklea...
<p>To calculate <strong><a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html#sklearn.metrics.precision_score" rel="nofollow noreferrer">precision</a></strong> and <strong><a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html#sklearn.metr...
python-2.7|scikit-learn|knn
0
2,214
45,273,575
Code under conditional statement is not executing despite condition being met
<p>maybe it's because I haven't coded for a few days, but I can't understand why this isn't working. The condition of if i == enemy_spaceship_index is being met once in the for loop, and yet the code beneath that conditional if statement is not executing. When I print out the list, it's just giving me seven 2s. Wh...
<p>I think your indentation is messed up. Otherwise, it looks to me like your code works just fine...</p> <pre><code>&gt;&gt;&gt; from random import randint &gt;&gt;&gt; for x in range(7): # test all possible values ... enemy_spaceship_index = x ... appearancesLeft = [] ... for i in range(7): ... i...
python|list|if-statement
1
2,215
20,616,563
Python - Merge two lists with a simultaneous concatenation
<pre><code>ListA = [1,2,3] ListB = [10,20,30] </code></pre> <p>I want to add the contents of the lists together <code>(1+10,2+20,3+30)</code> creating the following list:</p> <pre><code>ListC = [11,22,33] </code></pre> <p>Is there a function that merges lists specifically in this manner?</p>
<p>This works:</p> <pre><code>&gt;&gt;&gt; ListA = [1,2,3] &gt;&gt;&gt; ListB = [10,20,30] &gt;&gt;&gt; list(map(sum, zip(ListA, ListB))) [11, 22, 33] &gt;&gt;&gt; </code></pre> <p>All of the built-ins used above are explained <a href="http://docs.python.org/3.2/library/functions.html" rel="nofollow noreferrer">here<...
python|python-3.x|merge|concatenation
9
2,216
46,518,882
TypeError when assigning a non-existent path to a string
<p>this is my first post here so i am welcome to criticism regarding the post itself in terms of layout etc.</p> <p>I am writing a script to automatically sort files. For that I have to ask for a source where the files are.</p> <pre><code>import os import os.path import shutil import time def main(): src = get_s...
<p>In the <code>get_source</code> function, when you recursively call <code>get_source()</code>, you haven't specified it to return the result and the statement has no effect. Add the <code>return</code> keyword in those two instances, like this:</p> <pre><code>def get_source(): path_source = input("Where are the file...
python|string|if-statement|typeerror
0
2,217
36,361,570
Issue regarding a for loop based off an Access table
<p>Essentially what is supposed to happen is it takes from a database table some information containing IDs. In the condition that one of the input.text() elements are found on the Database as one of the IDs, I expect it to run X, but instead bypasses and runs Y </p> <pre><code>`DBConnect = pyodbc.connect('Driver={Mic...
<p>You have a bug. Update == True should be Update = True, inside the loop</p>
python|sql
0
2,218
36,649,000
Making attributes that calculates with the value of other attributes
<p>I´m writing a program where you can put in home team, away team, and the result of a game. I want to make the data of the teams to change according to this and most of it does. But I can´t make the "points", "goal difference" and "played"(games) to change! This is the code i wrote so far:</p> <pre><code>class team...
<p>If you update your <code>team</code> class to make the calculated fields properties, then the property functions will always return the correct result. You will also get an error if you try to set those properties, as they are not settable, i.e., they are the result of a calculation on other set data.</p> <pre><co...
python|python-3.x
3
2,219
37,420,417
Tricky Python 3.5 CSV Puzzle - efficiently create 100 lists from a CSV file without referencing criteria each time
<p>My project was to take 100 different colors and collect people's one-word reactions to them. So there are two columns: Color and Reaction. There are about 600 cases. <strong>My goal is to take every reaction for the same color and merge them into some sort of list.</strong> </p> <p>So, I'd need to take all reaction...
<p><strong>Use a dictionary.</strong></p> <p>Create a dictionary with <code>color</code> as key and list of reactions as <code>value</code>. This way, iterating over it will be a breeze.</p> <p><strong>Pro tip -</strong></p> <p>Use <code>collections.defaultdict</code> instead of a regular <code>dict</code>.</p>
python|csv
2
2,220
37,612,239
I cannot reach Entry's values from tkinter, the last one corrupt others
<p>I am a new Python user. I try to make a serie of entries identified by labels and gets the values inserted. The callback functions seem well done but it's allways the third entry's value which I reach. I am Python/Linux user, version 2.7.6 It seem to be lambda's declaration issue, can you help me ?</p> <pre><code>i...
<p>One problem is this line of code:</p> <pre><code>self.ents[i].entry["textvariable"] = self.ents[i].val </code></pre> <p>The <code>textvariable</code> attribute must be set to an instance of <code>StringVar</code> (or one of the other tkinter variables), <em>not</em> the value of such an instance. You need to remov...
python|lambda|tkinter|bind
2
2,221
51,157,908
Python processes fail to start
<p>I'm running the following code block in my application. While running it with python3.4 I get 'python quit unexpectedly' popup on my screen. The data missing from the aOut file is for a bunch of iterations and it is in chunks. Say 0-1000 items in the list are not present and others have the data. The other items ru...
<p>To avoid the 'unexpected quit' perhaps try to ignore the exception with</p> <pre><code>try: your_loop() except: pass </code></pre> <p>Then, put in some logging to track the root cause.</p>
python|python-3.x|python-2.7|subprocess|python-multiprocessing
0
2,222
64,310,842
Need help converting number and a base to binary?
<p>so i wrote this code to take a base that is inputted by the user and a number inputted by the user and it is supposed to print the num with that base to binary. It does do what its supposed to do but it asks me for the base 3 times and then gives me the correct number here's the code</p>
<p>So I believe this is a duplicate of <a href="https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-to-a-string-in-any-base/28666223#28666223">This question</a> if so then the code from their answer will work, you just need to use a base 2 to their function:</p> <pre class="lang-py prettyprint-overrid...
python|python-3.x|binary
0
2,223
70,678,496
How do I close pop-up windows with Selenium in Python when I don't know when they will pop up?
<p>I am trying to scrape historical weather data from this website: <a href="https://www.worldweatheronline.com/taoyuan-weather-history/tai-wan/tw.aspx" rel="nofollow noreferrer">https://www.worldweatheronline.com/taoyuan-weather-history/tai-wan/tw.aspx</a></p> <p>Using this code:</p> <pre><code> driver.find_element...
<p>Here's a Python Selenium solution that uses <a href="https://github.com/seleniumbase/SeleniumBase" rel="nofollow noreferrer">SeleniumBase</a>:</p> <p>First <code>pip install seleniumbase</code>, then copy the example below into a Python file, eg <code>weather_test.py</code>. Then run it with <code>pytest</code>:</p>...
python-3.x|selenium|popup
1
2,224
69,938,833
How to save a dataframe as csv file in filefield
<p>I am trying to save a dataframe as a csv file in a model object's filefield but it is not saving it correctly, the file that is getting saved, contains some other language characters!! please tell what I am doing wrong??</p> <pre><code>new_df = df.to_csv(columns=['A', 'B'], index=False) doc.csvfile.save(f'{doc.id}.c...
<p>Hello you can try to save csv file with below code</p> <pre><code>import csv from io import StringIO from django.core.files.base import ContentFile new_df = df.to_csv(columns=['A', 'B'], index=False) csv_buffer = StringIO() csv_writer = csv.writer(csv_buffer) csv_writer.writerow(new_df) csv_file = ContentFile(csv...
django|pandas|dataframe|django-models|filefield
2
2,225
72,865,799
Convert SVG image to PNG image by python
<p>I have use svglib with this code :</p> <pre><code>from svglib.svglib import svg2rlg from reportlab.graphics import renderPM drawing = svg2rlg('''E:/img/1926_S1_style_1_0_0.svg''') renderPM.drawToFile(drawing, 'image.jpg', fmt='jpg') </code></pre> <p>But what i receive <a href="https://i.stack.imgur.com/uD9Ux.png" r...
<p>try using <a href="http://cairosvg.org/" rel="nofollow noreferrer">cairosvg</a></p> <pre class="lang-py prettyprint-override"><code>from cairosvg import svg2png svg_code = &quot;&quot;&quot; &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;24&quot; height=&quot;24&quot; viewBox=&quot;0 0 24 24&q...
python|svg
1
2,226
55,836,694
Opening a document in text widget tkinter
<p>The example code opens a .txt file but is there a way to open a word document, preferably a .docx file? </p> <pre><code>from Tkinter import * import Pmw, sys filename = "textfile.txt" root = Tk() top = Frame(root); top.pack(side='top') text = Pmw.ScrolledText(top, borderframe=5, vscrollmo...
<p>No, the text widget can't display a .docx file. At the name implies, it is for displaying plain text.</p>
python|tkinter|ms-word|docx
0
2,227
73,489,810
How to parallelize for loop with multiple functions inside - Python - AWS Glue
<p>Here is my question.</p> <p>I have created several functions, and those functions will be <strong>run per each UserID</strong> (that is the reason of the for loop below running the functions). It will be run in AWS Glue.</p> <p>I need to do <strong>scalable</strong> this code in Python / AWS Glue, working with milli...
<p>Since your logic is already defined for one listIdUser, all you have to do is wrap this logic with <a href="https://github.com/fugue-project/fugue/" rel="nofollow noreferrer">Fugue</a>. We can separate the partitioning and execution. I don't have data to test on but it will look like this.</p> <pre class="lang-py pr...
python|amazon-web-services|pyspark|aws-glue
1
2,228
65,457,463
Understanting what the syntax for {:.2} means in python
<p>I am working on creating a linear regression model for a specific data set, I am following an example I found on you tube, at some point I calculate the kurtosis and the skewness as below:</p> <pre><code># calculate the excess kurtosis using the fisher method. The alternative is Pearson which calculates regular kur...
<p>The <code>kurtosis</code> and <code>skew</code> functions are doing the calculation, while the <code>display</code> function is probably just some form of <code>print()</code> for that environment!</p> <p><code>&quot;.. {:.2}&quot;.format(x)</code> is a string formatter which rounds floating points to 2 significant ...
python|string|format
2
2,229
72,083,806
Non-interactive authentication fails with WsTrust server issue MSIS7068
<p>Setup:</p> <ul> <li>Users are created on On-Prem AD and synced to Azure AD via Azure AD Connect</li> <li>I have a single-tenant app set up on Azure AD</li> <li>I created a user (On-Prem, synced to AAD) that can authenticate without MFA (we need to use username-password authentication due to an internal limitation).<...
<p>First, no guesswork! You would need to login to Azure AD with elevated privilege (Security Reader at the least if not Global Administrator).</p> <ol> <li>Go to Enterprise Applications and locate your application by client id.</li> <li>One you are at the application, go to Sign-in tab/pane.</li> <li>Review the sign-i...
python|azure-active-directory|msal
1
2,230
71,855,892
Is it possible to expose replay buffer in A2C Stable Baselines 3 to include human judgements?
<p>I am using A2C (Advantage Actor Critic) framework from stable-baselines3 (<a href="https://stable-baselines3.readthedocs.io/en/master/modules/a2c.html" rel="nofollow noreferrer">package link here</a>) package for solving a reinforcement problem where reward is +1 or 0. I have an automatic mechanism to allocate rewar...
<p>Of course! The environment is a simple python script in which, somewhere at the end of <code>env.step</code>, the reward is calculated and returned, to be then added along with the state and the action to the replay buffer.</p> <p>You could then manually insert the reward value each time an action is taken, using si...
python|reinforcement-learning|stable-baselines
0
2,231
68,825,494
Data visualization of CSV file with dash
<p>I am new to Python. <a href="https://realpython.com/python-dash" rel="nofollow noreferrer">https://realpython.com/python-dash</a> provides code for visualizing a line graph from a CSV file using Python's dash.</p> <p>I ran the code below, but receive an error.</p> <pre><code>import dash_core_components as dcc import...
<ul> <li>I didn't see it had been fixed in comments. A couple of small changes to make it reproducible <ol> <li>dynamically get data from <strong>github</strong> rather than hoping it's on file system</li> <li>used <strong>JupyterDash</strong> which works out of box with <strong>plotly</strong> 5.x.y</li> </ol> </li> ...
python|plotly|dashboard|linegraph
1
2,232
71,686,820
Cuda:0 device type tensor to numpy problem for plotting graph
<p>as mentioned in the title, I am facing the problem of</p> <p>TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.</p> <p>I found out that that need to be a .cpu() method to overcome the problem, but tried various ways and still unable to solve the pro...
<p>I guess during loss calculation, when you try to save the loss, instead of</p> <pre><code>train_loss.append(loss) </code></pre> <p>it should be</p> <pre><code>train_loss.append(loss.item()) </code></pre> <p>item() returns the value of the tensor as a standard Python number, therefore, train_loss will be a list of nu...
python|python-3.x|numpy|matplotlib|pytorch
2
2,233
71,606,253
ValueError: shapes (3,3,1) and (3,1) not aligned: 1 (dim 2) != 3 (dim 0)
<p>I am trying to multiply some matrices in python, using the np.dot function.I have a three by three array that I want to multiply by a three by one</p> <p>ValueError: shapes (3,3,1) and (3,1) not aligned: 1 (dim 2) != 3 (dim 0)</p> <p>What exactly does the third dimension on the array mean? Is there a way to get rid ...
<p>A (3,3,1) means that you have a vector of 3 two dimensional vectors. Take this as example:</p> <pre><code>a = np.random.rand(3,3,1) print(a) [[[0.08233029] [0.21532053] [0.88495997]] [[0.59743708] [0.97966668] [0.44927175]] [[0.40792714] [0.85891152] [0.22584841]]] </code></pre> <p>As above, there a...
python|numpy|valueerror
0
2,234
5,395,948
Incredibly basic lxml questions: getting HTML/string content of lxml.etree._Element?
<p>This is such a basic question that I actually can't find it in the docs :-/</p> <p>In the following:</p> <pre><code>img = house_tree.xpath('//img[@id="mainphoto"]')[0] </code></pre> <p>How do I get the HTML of the <code>&lt;img/&gt;</code> tag?</p> <p>I've tried adding <code>html_content()</code> but get <code>A...
<p>I suppose it will be as simple as:</p> <pre><code>from lxml.etree import tostring inner_html = tostring(img) </code></pre> <p>As for getting content from inside <code>&lt;p&gt;</code>, say, some selected element <code>el</code>:</p> <pre><code>content = el.text_content() </code></pre>
python|lxml
65
2,235
61,835,752
Web scraping a hidden table using Python
<p>I am trying to scrape the &quot;Traits&quot; table from this website <a href="https://www.ebi.ac.uk/gwas/genes/SAMD12" rel="nofollow noreferrer">https://www.ebi.ac.uk/gwas/genes/SAMD12</a> (actually, the URL can change according to my necessity, but the structure will be the same).</p> <p>The problem is that my know...
<p>Desired data is available within API call.</p> <pre class="lang-py prettyprint-override"><code>import requests data = { "q": "ensemblMappedGenes: \"SAMD12\" OR association_ensemblMappedGenes: \"SAMD12\"", "max": "99999", "group.limit": "99999", "group.field": "resourcename", "facet.field": "res...
python|web-scraping|beautifulsoup
3
2,236
67,413,064
Masking dataframe text column to a new column in pandas dataframe
<p>I have pandas dataframe below and I would like to mask ProductId column with a new column. Assign each id to a new numeric value. How can I do that? Thanks</p> <pre><code>import pandas as pd df=pd.DataFrame({'ProductId':['AXX11','CS22','AXX11','FV34','FV34','DF23','CS22'],'Sales': [10,34,23,45,23,54,65]}) df </cod...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Categorical.html" rel="nofollow noreferrer"><code>categorical</code></a>:</p> <pre><code>In [96]: df['Mask_ProductId'] = df.ProductId.astype('category').cat.codes In [97]: df Out[97]: ProductId Sales Mask_ProductId 0 AXX11 10 ...
python|pandas
3
2,237
60,566,086
Function call does not change value
<pre><code>def divide_by_2(number): number /= 2 ... def main(): n = 42 divide_by_2(n) print(n) </code></pre> <p>The result is 42, not 21. Why is this the case? Thanks in advance.</p>
<p>You have to return the value from your function</p> <pre><code>def divide_by_2(number): return number / 2 # return the calculation ... def main(n): n = divide_by_2(n) print(n) &gt;&gt; 21 main(42) # call main with variable number </code></pre>
python
3
2,238
71,250,098
Writing a hashtag to a file
<p>I am using a python script to create a shell script that I would ideally like to annotate with comments. If I want to add strings with hashtags in them to a code section like this:</p> <pre><code>with open(os.path.join(&quot;location&quot;,&quot;filename&quot;),&quot;w&quot;) as f: file = f.read() file += &quot...
<p>You already have a <code>#</code> character in that string literal, in <code>$#</code>, so I'm not sure what the problem is.</p> <p>Python considers a <code>&quot;&quot;&quot;</code> string literal as one big string, newlines, comment-esque sequences and all, as you've noticed, until the ending <code>&quot;&quot;&qu...
python|string|bash
1
2,239
71,402,910
Extract value from first column in pandas dataframe and add it in file name while saving
<p>I have following dataframe</p> <pre><code>year city population 2002 Chicago 100000 2002 Dallas 150000 2002 Denver 200000 </code></pre> <p>I want to extract &quot;2002&quot; (One file will have same value in each row in first column) from first column and add it in file name I will sa...
<p>You can do it with a variable and some f-string formatting.</p> <pre><code>year = df.at[0, 'year'] df.to_csv(f'{year}_city_population.csv') </code></pre>
python|pandas
1
2,240
64,192,776
What is wrong with this SQL statement in Python?
<p>I am using Python and a MySQL database and am attempting to itterate through rows in a CSV file and insert them in my database. I have the following:</p> <pre><code>import mysql.connector import pandas as pd mydb = mysql.connector.connect( host=&quot;localhost&quot;, user=&quot;root&quot;, passwd=&quot;...
<p>I think you better use pandas to_sql function.<br> I'm not sure whether <code>mysql.connector</code> works so i'll use <code>sqlalchemy</code>.<br> It looks like that:</p> <pre><code>ENGINE = sqlalchemy.create_engine('mysql+pymysql://root:root@localhost:3306/mydb') with ENGINE.connect() as connection: ENGINE.exe...
python|mysql|pandas
1
2,241
63,512,787
selenium count divs inside one div
<p>I want to count divs inside one div with selenium.</p> <p><a href="https://i.stack.imgur.com/eyWIC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eyWIC.png" alt="enter image description here" /></a></p> <p>This is my code so far, but I don't understand why this is not working. It returns length o...
<p>To count <code>&lt;div&gt;</code> tags with value of <em>alt</em> attribute as <strong>Closed</strong> within its parent <code>&lt;div&gt;</code> using <a href="https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491">Selenium</a> you can use either of the following <a h...
python|html|selenium|xpath|webdriver
2
2,242
56,770,064
Pandas throwing an OSError on PyCharm
<p>I have been getting the following error on my PyCharm:</p> <pre><code>Traceback (most recent call last): File "C:/Users/security/Downloads/AP/Boston-Kaggle/Boston.py", line 1, in &lt;module&gt; import pandas as pd File "C:\Users\security\AppData\Roaming\Python\Python37\site-packages\pandas\__init__.py", lin...
<p>In <code>***\core\__init__.py: line23</code> The initialization script loads a dll, located at your path: <code>"C:\Users\security\AppData\Roaming\Python\Python37\site-packages\numpy\.libs\*openblas*dll"</code>, If you're using a 32bit DLL with 64bit Python, or vice-versa, then you'll probably get errors. I recommen...
python|pandas|winapi|jetbrains-ide
0
2,243
17,707,710
findAll() in BeautifulSoup missing nodes
<p>The method <strong>findAll()</strong> in BeautifulSoup does not return all elements in XML. If you look the code below and open URL, you can see that there are 10 <em>PubmedArticle</em> nodes in XML. However the findAll method only finds 6 of them. There is only 6 * on the output instead of 10. What am I doing wrong...
<p>I solved this by adding <code>xml</code> argument. Make sure you have <code>lxml</code> installed.</p> <pre><code>soup = BeautifulSoup(xmlData, 'xml') </code></pre>
python-2.7|beautifulsoup|findall
0
2,244
66,144,154
"numpy.linspace" for second time after excluding some point by first "linspace"
<p>I am building a model and I need to get the positions of some points inside a box (known volume). I am thinking on using a) <code>numpy.linspace(start,stop,30)</code> b) <code>numpy.linspace(start,stop,3000)</code> from the same box, I think I need a tool to exclude the points from a) process.</p> <p>Example as [2D]...
<p>This solution is the only one that worked for me:</p> <ol> <li>get the <code>xyz</code> file, by any other software like jmole.</li> <li>you have the orientations of the model. I wrote the orientations into my program to avoid overlapping.</li> </ol>
python|numpy|linspace
1
2,245
66,330,052
Rounding up a dataframe consist of string and float both
<p>I have a dataframe : <code>df = pd.DataFrame([[&quot;abcd&quot;, 1.9923], [2.567345454, 5]])</code></p> <p>I want to round it up to 2 decimal places for all the floats. I am using: <code>df.round(decimals=2)</code></p> <p>However, I am observing that it is working only if the entire dataframe is either <code>float</...
<p>If there are mixed numeric with strings values is possible use custom lambda function:</p> <pre><code>#first column is filled by strings, so 1. solution not working df = df.applymap(lambda x: round(x, 2) if isinstance(x, (float, int)) else x) print (df) 0 1 0 abcd 1.99 1 2.57 5.00 </code></pre> <p>If n...
python|pandas
2
2,246
72,848,359
Unable to pass/exit a python function
<p>Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via &quot;no&quot; or False) once in the loop:</p> <p><strong>main_menu.py</strong></p> <pre><code>from functions import * def menu(): print(&quot;Press 1 for movies.&quot;) print(&quot;Press 2 to exit.&quot;) me...
<pre><code>global movies movies = {} def fun_movies(): name = input(&quot;Insert movie name: &quot;) genre = input(&quot;Input genre: &quot;) movies [name] = [genre] a = True while a: query = input(&quot;Do you want to input another movie? (yes/no) &quot;) if query == &quot;yes&q...
python|function
1
2,247
62,203,582
Retrieving text content from Javascript URL
<p>I am modifying the <a href="https://pypi.org/project/play-scraper/" rel="nofollow noreferrer">play-scraper</a> API to scrape play-store app details. It uses <code>BeautifulSoup</code> to parse HTML pages [<a href="https://github.com/danieliu/play-scraper/blob/master/play_scraper/scraper.py#L78" rel="nofollow norefer...
<p>If I understand the question correctly you are trying to scrape the data from a modal. And when the website loads for the first time these modals data aren't available inside html. They are fetched after you click the view details button. That's why the parser doesn't get the data inside the modal, in your case the ...
javascript|python
2
2,248
62,160,622
Renaming multiple columns using their index
<p>How can i rename multiple columns of a dataframe using their index? For example i want to rename the columns at positions 5,6,7,8 to 'five','six','seven','eight' respectively. I don't want to enter the keys in the dictionary individually.</p>
<p>In the case of already having a dictionary, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer"><code>rename</code></a> to map to the new axis values:</p> <pre><code>df = pd.DataFrame(columns=range(10)) d = {5:'five', 6:'six', 7:'se...
python|pandas|dataframe|rename
2
2,249
62,203,125
How can I apply a function to each row in a pandas dataframe?
<p>I am pretty new to coding so this may be simple, but none of the answers I've found so far have provided information in a way I can understand. </p> <p>I'd like to take a column of data and apply a function (a x e^bx) where a > 0 and b &lt; 0. The (x) in this case would be the float value in each row of my data. </...
<p>Your code is almost correct.</p> <pre class="lang-py prettyprint-override"><code># normalization formula (exponential) = a x e ^bx where a &gt; 0, b &lt; 0 def normalize(x): x = A * E ** (B * x) return x def plot_data(): # read the file data = pd.read_excel(FILENAME) # convert to pandas dataf...
python|pandas|data-visualization|neuroscience
2
2,250
31,243,623
Doctest fails due to unicode leading u
<p>I am writing a doctest for a function that outputs a list of tokenized words.</p> <pre><code>r''' &gt;&gt;&gt; s = "This is a tokenized sentence s\u00f3" &gt;&gt;&gt; tokenizer.tokenize(s0) ['This', 'is', 'a', 'tokenized', 'sentence', 'só'] ''' </code></pre> <p>Using <strong>Python3.4</strong> my test passes wit...
<p>Python 3 uses different string literals for Unicode objects. There is no <code>u</code> prefix (in the canonical representation) and some non-ascii characters are shown literally e.g., <code>'só'</code> is a Unicode string in Python 3 (it is a bytestring on Python 2 if you see it in the output).</p> <p>If all you i...
python|unicode|portability|doctest
4
2,251
15,761,715
GAE dev_appserver throws HTTP 504 Gateway Timeout
<p>I just upgraded my GAE SDK to 1.7.6 (Linux, Python). Now, using dev_appserver.py, my apps are loaded just fine, but as soon as I go to localhost:8080 in the browser, there is an uncaught HTTP 504 Gateway Timeout Exception. I've reproduced it with the helloworld sample code. Everything works like before using old_dev...
<p>Might be too late, but I hope this helps anyone who might have the same problem.</p> <p>Same thing happened to me, and the problem for me was that my system was set on using proxy. So, GAE dev_appserver was not able to connect to itself (it uses ip and port combination to connect to itself and manage some API stuf...
python|google-app-engine
3
2,252
59,742,004
How to find the columns that at least contain one negative element?
<p>In Python, for an array how can I find the columns that at least contain one negative element? Additionally, how can I find the median of rows that include at least one negative value? Let's say that this is our array:</p> <pre><code>import numpy as np a = np.array([[1,2,0,-4],[-3,4,-4,1],[3,6,2,9]]) </code></pre> ...
<pre><code>&gt;&gt;&gt; (a &lt; 0).any(axis=0) array([ True, False, True, True]) # Columns. &gt;&gt;&gt; np.median(a[:, (a &lt; 0).any(axis=0)], axis=0) array([1., 0., 1.]) # Rows. &gt;&gt;&gt; np.median(a[:, (a &lt; 0).any(axis=0)], axis==1) array([ 0., -3., 3.]) # Median of rows where row contains at least one ...
python|arrays|function|numpy
4
2,253
60,095,926
How to do formatting changes in an table using pptx in python?
<p>I have a dataframe that looks like this:</p> <pre><code> c sp k1 k2 k3 k4 k5 k6 0 c1 70.73 0.3% 0.6% 0.7% 0.8% 0.7% 0.5% 1 c2 149.71 0.7% 0.6% 0.4% 0.6% 0.7% 1.0% 2 c3 -1.00 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 3 c4 24.88 0.1% 0.9% 0.5% 0.7% 0.7% 0.9% 4 c5 276...
<p>1+2 ... Do you know how to do this in PowerPoint? If so, you could compare two files with and without thick border to find which part of the xml-file has to be changed.</p> <p>3+4 ... you have to change the font color of the corresponding paragraphs. You could do this directly via <a href="https://python-pptx.readt...
python|python-3.x|powerpoint|python-pptx
0
2,254
60,195,140
Python/Pandas: TypeError: float() argument must be a string or a number, not 'function'
<p>I am trying to generate a plot from two columns in a .csv file. The column for the x-axis is in the short date format mm/dd/yyyy while the column for the y-axis corresponds to absorption measurement data as regular numerical values. From this, I am also trying to gather a linear regression line from this plot. Here ...
<p>Functions in Python can be used as variables, which is what you are doing here. If you want to use the result of a function for something, you need to call it by adding () after the function name.</p> <p>mydateparser is a function, mydateparser() is the result of calling that function.</p> <p>Additionally, I don'...
python|pandas|matplotlib
1
2,255
60,004,277
How to properly implement disjoint set data structure for finding spanning forests in Python?
<p>Recently, I was trying to implement the solutions of google kickstater's 2019 programming questions and tried to implement Round E's Cherries Mesh by following the analysis explanation. Here is the link to the question and the analysis. <a href="https://codingcompetitions.withgoogle.com/kickstart/round/0000000000050...
<p>You are getting an incorrect answer, because you're calculating the count incorrectly. The it takes <code>n-1</code> edges to connect <code>n</code> nodes into a tree, and <code>num_clusters-1</code> of those have to be red.</p> <p>But if you fix that, your program will still be very slow, because of your disjoint ...
python|algorithm|data-structures|disjoint-sets|disjoint-union
1
2,256
2,483,569
MySQL UTC Date format
<p>I am pulling data from Twitter's API and the return date is UTC in the following form:</p> <blockquote> <p>Sat Jan 24 22:14:29 +0000 2009</p> </blockquote> <p>Can MySQL handle this format specifically or do I need to transform it? I am pulling the data using Python.</p>
<p>Yes, if you are not willing to transform it in Python, MySQL can handle this with the <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date" rel="nofollow noreferrer"><code>STR_TO_DATE()</code></a> function, as in the following example:</p> <pre><code>INSERT INTO your...
python|mysql|twitter|utc
3
2,257
2,506,883
Why can't my Apache see my media folder?
<pre><code>Alias /media/ /home/matt/repos/hello/media &lt;Directory /home/matt/repos/hello/media&gt; Options -Indexes Order deny,allow Allow from all &lt;/Directory&gt; WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi </code></pre> <p>/media is my directory. When I go to mydomain.com/media/, it says 403 Forbi...
<p>You have Indexes disabled, so Apache won't generate a listing of the files when you request the directory /media (instead, it shows the 403 Forbidden error). Try accessing a file directly within there, e.g.: <a href="http://localhost/media/some_image.jpg" rel="nofollow noreferrer">http://localhost/media/some_image....
python|linux|django|apache|unix
4
2,258
5,794,728
Python: Error Freezing ctypes
<p>I get the following error trying to freeze a python script that imports ctypes:</p> <pre><code> Warning: unknown modules remain: _bisect _ctypes _hashlib _heapq _locale _random _socket _ssl _struct _tkinter _weakref array binascii cStringIO collections datetime fcntl itertools math operator pyexpat readline select ...
<p>I suggest you use py2exe or something similar instead of freeze.</p>
python|ctypes|freeze
0
2,259
67,847,245
Pandas - Groupby with cumsum or cumcount
<p>I have the following dataframe:</p> <pre><code> Vela FlgVela 0 R 0 1 V 1 2 V 1 3 R 1 4 R 1 5 V 0 6 R 1 7 R 1 8 R 1 </code></pre> <p>What is the best way to get the result ...
<p>I think you're close, here is one way:</p> <pre><code>df[&quot;AddCol&quot;] = df.groupby(&quot;Vela&quot;).ngroup().diff().ne(0).cumsum() </code></pre> <p>where we first get the group number each distinct <code>Vela</code> belongs to (kind of factorize) then take the first differences and see if they are not equal ...
python|pandas|dataframe|cumsum
2
2,260
30,582,044
Delete rows from python panda dataframe
<p>My dataframe has columns like ticket, host, drive model, Chassis, Rack, etc.</p> <p>I want all the rows with value in the Chassis column equal to <code>'1025C-M3B'</code>, <code>'1026T-M3FB'</code>, <code>'2026TT-DLRF'</code> or <code>'SYS-2027TR-D70RF+'</code>. I want to delete the rest.</p> <p>I tried</p> <pre>...
<p>Use bitwise or (<code>|</code>) instead of logical <code>or</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>data2 = data1[(data1.Chassis == '1025C-M3B') | (dat...
python|pandas|dataframe
2
2,261
30,674,526
matplotlib: getting coordinates in 3D plots by a mouseevent
<p>I want to get coordinates (x,y,z) in 3D plots by a mouse event such as a click. MATLAB has this function, <code>datacursormode</code>. A good image is in the following link.</p> <p><a href="http://www.mathworks.com/help/matlab/ref/datacursormode.html" rel="nofollow">http://www.mathworks.com/help/matlab/ref/datacurs...
<p>According to the file "changelog.rst" at the link you suggested (<a href="https://github.com/joferkington/mpldatacursor" rel="nofollow noreferrer">https://github.com/joferkington/mpldatacursor</a>) this function has been added in July 2015. Unfortunately it looks like it extracts the data points from the location wh...
python|matlab|matplotlib|3d|mouseevent
0
2,262
63,859,763
how to run powershell script in python
<p>'''$Session = New-Object -ComObject &quot;Microsoft.Update.Session&quot;</p> <p>$Searcher = $Session.CreateUpdateSearcher()</p> <p>$historyCount = $Searcher.GetTotalHistoryCount()</p> <p>$Result = $Searcher.QueryHistory(0, $historyCount) | Select-Object Date,</p> <p>@{name=&quot;Operation&quot;; expression={switch($...
<p>You can pass a command to PowerShell and retrieve the output in your python script.</p> <p><strong>Step 1</strong> Write a PowerShell script</p> <pre><code> Write-Host 'Hello, World!' </code></pre> <blockquote> <p>save it as script.ps1</p> </blockquote> <p><strong>PS: This will output</strong></p> <pre><code> ...
python|powershell
1
2,263
42,832,143
Curl -u in scrapy
<p>How to do this curl on scrapy?</p> <pre><code>curl –i -u account_id:api_key "https://xecdapi.xe.com/v1/convert_from.json/?from=USD&amp;to=CAD,EUR &amp;amount=110.23" </code></pre>
<p>You can use <code>scrapy fetch</code> command:</p> <pre><code>scrapy fetch http://stackoverflow.com --nolog &gt; output.html </code></pre> <p>To use authentication you can try passing credentials via url itself:</p> <pre><code>scrapy fetch "http://username:password@stackoverflow.com" --nolog &gt; output.html </co...
python|curl|web-scraping|scrapy|scrapy-spider
1
2,264
42,874,778
Django on Mac with mysql
<p>I’m new in Django on Mac. I faced a problem in configuring Django environment with mysql on Mac.</p> <p>The error is “</p> <pre><code>django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/david/david-env/lib/python2.7/site-packages/_mysql.so, 2): Symbol not found: _mysql_shutdown...
<p>Downgrade your MySQL to 5.5 or below.</p> <p>Refer to the <a href="https://pypi.python.org/pypi/MySQL-python/1.2.5" rel="nofollow noreferrer">MySQL-python 1.2.5 intro page</a>:</p> <blockquote> <p>MySQL-3.23 through 5.5 and Python-2.4 through 2.7 are currently supported. Python-3.0 will be supported in a futur...
python|mysql|django
0
2,265
42,751,001
How to apply different functions to a groupby object?
<p>I have a dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'id': [1, 2, 1, 1, 2, 1, 2, 2], 'min_max': ['max_val', 'max_val', 'min_val', 'min_val', 'max_val', 'max_val', 'min_val', 'min_val'], 'value': [1, 20, 20, 10, 12, 3, -10, -5 ]}) id min_max value 0...
<p>Here's a slightly tongue-in-cheek solution:</p> <pre><code>&gt;&gt;&gt; df.groupby(['id', 'min_max'])['value'].apply(lambda g: getattr(g, g.name[1][:3])()).unstack() min_max max_val min_val id 1 3 10 2 20 -10 </code></pre> <p>This applies a function that...
python|pandas|dataframe|group-by
6
2,266
66,645,153
Selenium keyboard.send key to a specific windows only
<p>I have my code working on selenium but the problem is that when the code is running I can't switch to another chrome windows because it will send keybord key to the new one. I need to send the key only to a specific windows where the code is running</p> <pre><code>driver = webdriver.Chrome('chromedriver') driver.get...
<p>So I had a similar issue to this a while back. The issue that you are running into is that you need to make sure that you are working with the correct window handle.</p> <p>Your answer should be pretty easily solved here: <a href="https://stackoverflow.com/questions/10629815/how-to-switch-to-new-window-in-selenium-...
python|selenium|webdriver
0
2,267
72,385,869
What is the meaning of this asterisk? Python Pandas 100 question trying. str.contaubs
<p>I am really new to python. I have to use python for my research class, so I WAS learning pandas by using resource of Pandas Data Science 100 questions.</p> <p>I was working on a question that</p> <p>&quot;P-015: From dataset(df_cutomer), retrieve data in (status_cd)which starts from A-F, and end by 1-9. Displays the...
<p>Let's look at an online regex visualizer</p> <p><a href="https://i.stack.imgur.com/INCb6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/INCb6.png" alt="enter image description here" /></a></p> <p><a href="https://regexper.com/#%27%5E%5BA-F%5D.*%5B1-9%5D%24%27" rel="nofollow noreferrer">https://re...
python|pandas
0
2,268
72,446,269
Creating a new column in a data frame based on row values
<p>I want to be able to get the following result without using a for loop or df.apply()</p> <p>The result for each row should be the row values up until the group index.</p> <pre><code> group 0 1 2 3 4 5 6 7 0 2 a b c d e f g h 1 5 s t u v w x y z 2 7 a b c d e f g h ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a>, filter <code>group</code> column and variable column in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="no...
python|pandas
0
2,269
65,529,508
locust run showing ModuleNotFound for Python module
<p>Follow-up from earlier question <a href="https://stackoverflow.com/questions/65523535/multipledispatch-modulenotfounderror-running-from-command-line">here</a></p> <p>Running a <code>locust</code> (<a href="https://locust.io" rel="nofollow noreferrer">locust.io</a>) script from the command line.</p> <p><code>locust</...
<p>Placed periods (full stops) before the package names in the <code>import</code> statements.</p> <p>I then was able to run the <code>locust</code> script from within PyCharm.</p> <p>Running from the DOS shell, I was able to accomplish the same by first running</p> <pre><code>&lt;project directory&gt;\venv\Scripts\act...
python|pycharm|dependencies|locust|modulenotfounderror
0
2,270
51,031,623
Error: 'NoneType' object has no attribute '_inbound_nodes'
<p>[enter image description here][1]I am trying to make a parallel ANN network. I plan to :</p> <ul> <li>input a 120X120 image.</li> <li>disintegrate it into 9 40x40 images.</li> <li>Run Convolutional Net.</li> <li>Merge output in same pattern.</li> <li>Run another conv-net on merged layer.</li> </ul> <p></p> <pre><...
<p>Finally arrived at an answer. Although I am still wondering why my previous code threw error, I just add lambda layers to split. </p> <pre><code> def conv_net(self): # Add dropout if Overfiting input_shape = [120,120,1] inp=Input(shape=input_shape) col_layers = [] def sliced(x,i,j): ...
python|neural-network|keras|deep-learning|convolutional-neural-network
1
2,271
35,192,997
canopy/ipython run script - no output?
<p>I am very new to IPython, but not new to py itself. I am going through some code examples from a book called datadrivensecurity and trying to run one of the code examples. When i create a new file in IPython (using cannopy), then click run, i get the following output in the console window. </p> <pre><code>In [9]: %...
<p>As a convenience, if you type an expression at the prompt, the value of the expression will be printed. But if you just write the same expression in a python file, it will be evaluated, but the value will not be printed. You should <code>print x</code> if you want the value of x to be printed from a file that you ar...
python|ipython|canopy
1
2,272
44,844,333
pywinauto access methods from ListBoxWrapper
<p>I'm using pywinauto do automate some tests on a GUI app. There is a list box that I need to check for some data. The ListBoxWrapper class has these methods:</p> <pre><code>ListBoxWrapper.GetItemFocus ListBoxWrapper.ItemCount ListBoxWrapper.ItemData ListBoxWrapper.ItemTexts </code></pre> <p><a href="https://pywinau...
<p>It looks like you use <code>backend="uia"</code> but the docs link you provided is for <code>backend="win32"</code>. There are 2 different wrappers for these backends. This is <a href="https://pywinauto.readthedocs.io/en/latest/code/pywinauto.controls.uia_controls.html#pywinauto.controls.uia_controls.ListItemWrapper...
python|pywinauto
0
2,273
69,381,850
Why is this Python script failing? (xml.etree)
<p>First: I know that anyone who wants to help will ask for code that demonstrates the error. That will require a ZIP of the project, and I don't see how to attach a file to a StackOverflow question. I'll be happy to upload the file when someone tells me how.</p> <p>This is one of those things where &quot;I didn't chan...
<p>You have to use this syntax:</p> <pre><code>from xml.etree import ElementTree _parser = ElementTree.XMLParser(encoding=&quot;iso-8859-1&quot;) </code></pre> <p>As @Fred Larson explained in his comment, you have to import the module itself, and <code>etree</code> is a package.</p>
python|pycharm|xml.etree
2
2,274
69,535,163
Removing a particular pattern of a text file in python
<p>I have an input file named file1 which contains:</p> <blockquote> <p>Student 0 : Performed well but can do better. [76.50%]</p> <p>Student 1 : Brilliant performance. [98.50%]</p> </blockquote> <p>In this particular file I just want to remove the % part so that it produces output like:</p> <blockquote> <p>Student 0 :...
<p>You still need regex:</p> <pre><code>import re with open('file1', 'r') as infile, open('file2', 'w') as outfile: temp = re.sub(&quot;\[[\d+\.%]+\]&quot;, &quot;&quot;, infile.read()) outfile.write(temp) </code></pre>
python|python-3.x|regex|file
1
2,275
69,597,052
makemigration - Create model and insert data only once
<p>I've a model as below:</p> <pre><code>from django.db import models class Country(models.Model): cid = models.SmallAutoField(primary_key=True) label = models.CharField(max_length=100) abbr = models.CharField(max_length=3) countries = { &quot;AFG&quot;: &quot;Afghanistan&quot;, &quot;ALB&quot;: &quot;Alb...
<p>You can add <a href="https://docs.djangoproject.com/en/3.2/topics/migrations/#data-migrations" rel="nofollow noreferrer">data migrations</a> that create data, these get run once when the migration is applied. This is an example where your data migration is added to the migration that also adds the model</p> <pre><co...
python|python-3.x|django
2
2,276
57,546,019
Text-based adventure game, attacking causes game to crash
<p>I have set up the function for a player to attack an enemy, which seems to work okay. The problem is the actual action of attacking. In my main game code, it throws an AttributeError.</p> <p>Here is the block of code that I think is the culprit (at least, this is the block that's referenced by the error):</p> <pre...
<p>It would be better if you added the <code>get_available_actions(arg1, arg2)</code> function. It appears that this function does not return a value or returns None (which is the same this).</p> <p>If you can add more of your code we can analyze this error further. Otherwise, you should try to change the return to so...
python|python-3.x
2
2,277
57,446,401
Appending multiple button clicks to a list using Flask
<p>First time posting. I appreciate any help. I'm taking a list of items and displaying them on a page using a for loop. Each item is a button instead of a hyperlink. I'm trying to make it so the user can click multiple buttons as "choices" and have the value for each button appended to a list for further processing. S...
<p>Use <code>request.form['choice']</code></p> <p>Also just a note, if you need this route to handle the GET request, you need to add <code>methods=['GET', 'POST']</code> as right now the route will only handle the POST request.</p>
python|flask
0
2,278
42,169,854
How to safely store users' credentials to third party websites when no authentication API exists?
<p>I am developing a web app which depends on data from one or more third party websites. The websites do not provide any kind of authentication API, and so I am using unofficial APIs to retrieve the data from the third party sites. </p> <p>I plan to ask users for their credentials to the third party websites. I under...
<p>There’s no such thing as a safe design when it comes to storing passwords/secrets. There’s only, how much security overhead trade-off you are willing to live with. Here is what I would consider the minimum that you should do:</p> <ol> <li>HTTPS-only (all passwords should be encrypted in transit)</li> <li>If possi...
python|django|postgresql|security|encryption
3
2,279
22,763,055
Django - Reference data from another model using a foreign key
<p>I'm new to Django so please tell me if I'm not on the right track. I have a Django project that I'm building and just wanted to ask what is the correct Django way to retrieve data from one model and use it in another. </p> <p>I have a for loop to assign the required fields to variables but I was looking for a clean...
<p>Still, not hundred percent know what you want, since there are some missing info out there. For you Class1, You should do what you have done to Class2, using foreign key to store tag.</p> <p>For you code at bottom, there is a easy way to do it. (Assume you have used foreign key)</p> <pre><code>tag_number = int(ins...
python|django
1
2,280
22,599,377
Putting objects into a string then into a list in Python
<p>The title may be a little confusing here, so let me explain.</p> <p>Firstly I have a model of a list of items which is a foreign key of another model. The foreign key object has access wh_item_id and wh_item_name. I am trying to put that information into this format</p> <pre><code>wh_item_id=wh_item_name </code></...
<p>I believe Django has a <code>model_to_dict</code> feature which lets you iterate over the object as you would a <code>dict</code>.</p> <pre><code>from django.forms.models import model_to_dict char_dict = model_to_dict(Your_Model_Instance) </code></pre> <p>You can then iterate over that dict and get what you're lo...
python|django|list
0
2,281
28,453,810
Django fails to create superuser in other db than 'default'
<p>Is it a bug or am I wrong ? I am at the step to create a superuser, but django want a table in wrong db despite my router seems to work :</p> <p>settings.py</p> <pre><code>DATABASES = { 'intern_db': { 'ENGINE': 'mysql.connector.django', 'NAME': 'django_cartons', 'USER': 'root', ...
<p>The thing is the system is somewhat broken : it respects the config for some task but not for others (the 2 first "TRUE" in the output) but it doesn't for other and use default.</p> <p>This is perhaps intended even if weird (actually nothing forbid to have several admin db, and that permits not have automatic dark ...
python|django|multi-database
4
2,282
14,666,566
How do I determine if a pixel is black or white in OpenCV?
<p>I have this code in Python:</p> <pre><code>width = cv.GetSize(img_otsu)[0] height = cv.GetSize(img_otsu)[1] #print width,":",height for y in range(height): for x in range(width): if(img_otsu[y,x]==(255.0)): CountPixelW+=1 if(img_otsu[y,x]==(0.0)): CountPixelB+=1 </code></...
<p>You can use the <code>at()</code> function for <code>Mat</code> objects (see <a href="http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-at" rel="nofollow">OpenCV docs</a>).</p> <p><code>img_otsu.at&lt;uchar&gt;(y,x)</code> will return the value of the element in the matrix at that position. Note tha...
c++|python|opencv
0
2,283
41,570,995
How to encode string on Python 3.0 and decode it on Python 2.7 correctly over socket
<p>I'm writing an online multiple player console game by Python. The server uses Python 3.0 and the client uses Python 2.7(because I want to use my smartphone and I can only find Python 2.7 on it). However, I have trouble converting the encoding of string between server and client.</p> <p>I wrote two function, <code>s...
<p>You have one problem that your Python2 program is dealing with Byte strings all the time (that is - not Unicode string) but for the payload you try to decode where you get the error.</p> <p>If this is a small application, maybe just skip the decode step, and program your client app to deal with utf-8 encoded byte-st...
python|python-2.7|python-3.x|encoding|utf-8
0
2,284
56,907,298
I'm trying to make an array in python but i cannot print all the elements in the array?
<p>Trying to make a function to print all the arrays that are dynamically stored inside. But I'm not able to make a function to print all the elements in the array</p> <pre><code>import ctypes class myArray(object): def __init__(self): self.length = 0 self.capacity = 1 self.Array = self.make_array(self.ca...
<p><strong>Approach 1:</strong> Add a <code>print_all()</code> method</p> <pre><code>def print_all(self): print(self.Array[:self.length]) </code></pre> <p><strong>Approach 2:</strong> Create a string representation of the class</p> <pre><code>def __str__(self): return str(self.Array[:self.length]) </code></p...
python-3.x|data-structures
1
2,285
57,080,088
To extract content of 1st column (all rows) from an .xlsx file and replace it with the extracted information from each column
<p>I have to replace first entire column (all rows) with information extracted from each column itself. Last digit is missing for each column with my code.</p> <p>I have coded but had to save the output to a different file. I am unable to figure out how to replace the first column of the existing file itself. I need ...
<p>I suggest using python's builtin <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow noreferrer"><code>string.split</code></a> method:</p> <pre><code>import openpyxl fname = 'output.xlsx' wb = openpyxl.load_workbook(fname) sheet = wb.active d = [cell.value for cell in sheet['A']] #...
excel|python-3.x|csv|parsing
1
2,286
57,278,327
How do I access class variables?
<p>In this program I want a user to enter credentials and then based on the inputs validate whether it is correct. I am using tkinter to provide a GUI. I want to be able to take the auth function outside of the class so I can shut the tkinter dialog once the account has been logged in, however, the problem here is that...
<p>You're accessing the instance variable correctly, just in the wrong "order". Meaning, the answer must be checked only after the button is clicked. Basically, when your GUI loads, or directly after making the frame, the button isn't clicked, so the variable isn't defined, yet you're trying to access it immediately </...
python-3.x|class|tkinter
0
2,287
24,158,886
python find elements using selenium.webdriver
<p>I want to find the following element:</p> <pre><code>&lt;input type="text" value="" action-data="text=邮箱/会员帐号/手机号" action-type="text_copy" class="W_input " name="username" ... </code></pre> <p>And here is the html tags section, there are multiple <code>input</code> with the same name and class properties. So I wan...
<p>Try this:</p> <pre><code>browser.find_element_by_xpath("//div[@class='info_list']//input") </code></pre>
python|selenium|selenium-webdriver
0
2,288
20,485,948
How to use python for curl alternative
<p>in curl i do this:</p> <pre><code>curl -d "text=great" http://text-processing.com/api/sentiment/ </code></pre> <p>How i can do this same thing in python?</p>
<p>Using the <a href="https://pypi.python.org/pypi/requests" rel="nofollow">requests</a> library you can do somethng like this:</p> <pre><code>from requests import get get("http://text-processing.com/api/sentiment/", data={"text": "great"}) </code></pre>
python|curl|urllib
1
2,289
46,575,210
Trouble Inserting DataFrame Into InfluxDB Using Python
<p>I'm trying to insert a very large CSV file into InfluxDB and am inserting it as such in Python:</p> <pre><code>influx_pd = influxdb.DataFrameClient(host, port, user, password, db, verify_ssl=False) for frame in pd.read_csv(infile, chunksize=batch_count): frame.set_index(pd.DatetimeIndex(frame[date_pk]), inplac...
<p>So I realized that I had to explicitly specify the protocol to be json, as such:</p> <pre><code>influx_pd.write_points(frame, measurement='enroll_pd', protocol='json') </code></pre> <p>in addition to filling in NaN values (JSON has no support for those) with an imputation method. I thought the docs I was under the...
python|python-3.x|influxdb|influxdb-python
0
2,290
46,372,312
Faster estimation of logarithm operation
<p>I have a fairly simple function involving a logarithm of base 10 (<code>f1</code> shown below). I need it to run as fast as possible since it is called millions of times as part of a larger code.</p> <p>I tried with a <a href="https://www.wolframalpha.com/input/?i=taylor%20log(1%2B10%5Ex)&amp;rawformassumption=%7B%...
<p>Replace all of those exponentiations in <code>f2</code> with multiplication:</p> <pre><code>def f2(m1, m2): """ Taylor expansion of 'f1'. """ x = -0.4 * (m2 - m1) x2 = x * x x4 = x2 * x2 x6 = x4 * x2 return m1 - 2.5 * ( 0.30102999 + .5 * x + 0.2878231366 * x2 - 0.0635...
python|performance|numpy|logarithm
3
2,291
61,017,543
How to represent the number like '1.108779411784206406864790428E-69', between 0-1 in Python
<p>I have a number that comes from Sigmoid function like '1.108779411784206406864790428E-69' but it's naturally should be between 0-1. How can I represent it in that way? Thanks</p>
<p>The number that you got is the scientific notation of this number: 0.0000000000000000000000000000000000000000000000000000000000000000000011087794117842064068647904281594</p> <p>To get the number like that, you need to do this:</p> <pre><code>x = 1.108779411784206406864790428E-69 print("%.100f" % x) </code></pre> ...
python|python-3.x
1
2,292
49,497,589
Django OneToOneField initialization
<p>I'm building a django-based application that receives some information from client-computers (e.g. memory) and saves it into the database.</p> <p>For that I created the following model:</p> <pre><code>class Machine(models.Model): uuid = models.UUIDField('UUID', primary_key=True, default=uuid.uuid4, editable=Fal...
<p>Fields accept a <code>default</code> keyword argument. This can be a callable that returns a value. You can make a callable that returns the appropriate value; in this case, the primary key of a newly created <code>Memory</code> object.</p> <pre><code>def default_memory(): mem = Memory() mem.save() retu...
python|django|model|initialization|one-to-one
5
2,293
49,783,669
Fastest way to update table nulls in postgresql from dataframe
<p>I have a pandas dataframe and matching postgresql table, where every cell in both is either null or a timestamp. For each cell in the table where the cell value equals null, and the corresponding dataframe cell value is a timestamp, I want to update the table cell value. What's the fastest way to do this?</p> <p>Cu...
<p>IIUC, you can merge the two databases but maintain a record of what records come from each. Then you can check if your A column is empty and fill in the B column with the B from df2.</p> <pre><code>outdf = df1.join(df2, on=columns, how="outer", rsuffix='_df2', lsuffix='_df1') outdf['B'] = outdf.apply(lambda x: x['B...
python|postgresql|pandas|dataframe|merge
1
2,294
20,927,325
Why is there a difference between binascii.b2a_base64() and base64.b64encode()?
<p>I'm trying to understand some divergent behavior I'm seeing with the following two functions:</p> <pre><code>def hex_to_64(string): hex_string = binascii.a2b_hex(string) return binascii.b2a_base64(hex_string) def hex_to_64_2(string): hex_string = binascii.a2b_hex(string) return base64.b64encode(hex...
<p>Nothing special, the implementators decided to do it that way. It is documented at <a href="http://docs.python.org/2/library/binascii.html#binascii.b2a_base64" rel="nofollow">binascii module</a>.</p> <blockquote> <p>Convert binary data to a line of ASCII characters in base64 coding. The return value is the conver...
python|python-2.7
3
2,295
62,833,123
Python Output to TKinter Entry has Float64
<p>I am loading a CSV into a data frame, doing some calculations and then outputting the results to a grid of tkinter Entry boxes. This all works fine and the output is correct but it has a proceeding '0' and is followed by 'dtype:float64'. The data in the Entry looks like this (xxxx being the only data I want to displ...
<p>The above comment answers solved the problem with my <code>Tkinter</code> GUI. I have subsequently upgraded to a <code>PyQt5</code> QT Desinger GUI, the final code to send the formatted text the text_box in that case is:</p> <pre><code>self.Q_BGO_Y.setText(str(BGO_Y.iloc[0])) self.Q_BGO_Y.repaint() #repaint to overc...
python|dataframe|tkinter
0
2,296
53,628,125
How to share my Tkinter app with other users?
<p>I have developed a tkinter application but I need other users (with Windows 10 OS) to use it. Some have a python interpreter installed but others don't. I tried to create an executable through py2exe and auto py-to-exe but none worked. I also tried to run the tkinter through pythonanywhere.com but it also didn't wor...
<p>I would use <a href="https://www.pyinstaller.org/" rel="nofollow noreferrer">pyinstaller</a></p> <p>run cmd.exe as Administartor and type:</p> <p><code>pip install pyinstaller</code></p> <p>then run with:</p> <p><code>pyinstaller --onefile --noconsole --name your_script.py</code></p> <p>This creates a single fi...
python|tkinter|windows-10|executable
2
2,297
45,864,924
in python test this string("\x04\x01\x00PÀcö60\x00") with startswith or re, but returns false
<p>I am working on a webserver access log analysis tool. Sometimes i get malformed requests hitting the web server. I want to be able to identify these. However when trying to test whether this string "\x04\x01\x00PÀcö60\x00" starts with \x0. Python reports no match.</p> <p>I am doing:</p> <pre><code>&gt;&gt;&gt; t =...
<p>The first character of the input string <code>'\x04\x01\x00P\xC0c\xF660\x00'</code> is <code>'\x04'</code> as the escape sequence has the format <code>\xhh</code>.</p> <p><code>'\\x0'</code> in your example is actually a string composed of 3 characters: <code>'\'</code>, <code>'x'</code> and <code>'0'</code>. Compa...
python|string|hex
3
2,298
45,927,228
Unexpected result while looping through pandas DataFrame
<p>I load content of a csv to a dataframe.</p> <pre><code>data = pd.read_csv("census.csv") </code></pre> <p>Then I check data size</p> <pre><code>print( data.size) --&gt; 633108 </code></pre> <p>Then I loop through DataFrame</p> <pre><code>counter = 0 for index, row in data.iterrows(): counter += 1 </code></pr...
<p><code>size</code> isn't the correct attribute to use. <code>size</code> is the total number of elements.</p> <pre><code>df = pd.DataFrame(np.zeros((3, 4))) df.size 12 </code></pre> <p><code>size</code> will coincidentally be correct if there is only one column</p> <pre><code>df.iloc[:, [0]].size 3 </code></pre...
python|pandas|dataframe
2
2,299
54,809,388
How to give client mac for BOOTP, in DHCP scapy?
<p>clientMac = "00:00:01:00:11:03" bootp = BOOTP(op = opcode,chaddr = clientMac, ciaddr = "0.0.0.0",xid = 0x01020304,flags= 0x8000)</p> <p>Here, I try to create bootp part for a DHCP offer packet. But in the packet capture, the clientMac is shown as 30 30 3a 30 30 3a. I get a junk mac address. When I convert m...
<p>On BOOTP only (I assume for historical reasons), you need to pass the raw MAC value to chafe rather than the literal one.</p> <p>Use <code>clientMac = str2mac("...")</code></p>
python|scapy|dhcp|bootp
0