input_text_instruct
stringlengths
282
37.9k
output_text
stringlengths
37
27.3k
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Django Template curly brackets inside curly brackets<pre class="lang-html prettyprint-override"><code>{% if hosts %} &lt;div class=&quot;row&quot;&gt; {% for host in hosts %} {% if host.type_of == &quot;Backend&quot; %} &lt;div class=&quot;col-sm-3&quot;&gt;{{ host.type_of }}&lt;/div&gt; {{ headers.{{ forloop.counter0 }} }} {% endif %} {% endfor %} &lt;/div&gt; {% endif %} </code></pre> <p>I am sending arrays, hosts and headers from views to my template, I need to get element of header with the current index (getting the header[i])</p> <p>Error says</p> <pre><code>Could not parse the remainder: '{{ forloop.counter0' from 'headers.{{ forloop.counter0' </code></pre> <p>Can't seem to find any examples regarding to this. How can I achieve what I want ?</p>
<p>Are there an equal number of hosts and headers? If so, you could use zip(), in your view, to zip them together as follows:</p> <pre><code>headers_and_hosts = zip(headers, hosts) </code></pre> <p>Then this would allow you to do something like this in your template:</p> <pre><code>{% for host, header in headers_and_hosts %} {% if host.type_of == &quot;Backend&quot; %} &lt;div class=&quot;col-sm-3&quot;&gt;{{ host.type_of }}&lt;/div&gt; {{ header }} {% endif %} {% endfor %} </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: In my code, why doesn't my list sort from the earliest to the latest in dates?<pre><code>from datetime import date, timedelta, time, datetime # 1 Complete read_date() def read_date(date_object): &quot;&quot;&quot;Read a string representing a date in the format 2121-04-12, create a date object from the input string, and return the date object &quot;&quot;&quot; dt_string = '2121-04-12' date_object = datetime.strptime(date_object, '%Y-%m-%d').date() return date_object # 2. Use read_date() to read four (unique) date objects, putting the date objects in a list date1 = input() date2 = input() date3 = input() date4 = input() date1_read = read_date(date1) date2_read = read_date(date2) date3_read = read_date(date3) date4_read = read_date(date4) list_date = [] list_date.append([date1, date2, date3, date4]) split_list = # 3. Use sorted() to sort the dates, earliest first list_sorted = sorted(list_date) print(list_sorted) # 4. Output the sorted_dates in order, earliest first, in the format mm/dd/yy new_format = # 5. Output the number of days between the last two dates in the sorted list # as a positive number # 6. Output the date that is 3 weeks from the most recent date in the list # 7. Output the full name of the day of the week of the earliest day </code></pre> <p>Under #3, I need to sort the dates from earliest in a specific format. I need help sorting the list as my code does not sort it. I also need help in formatting the entire list in a specific way.</p>
<p>The dates are not sorted because you are assigning the datetime object to the variables <strong>date?_read</strong>, which are never added to the <strong>list_date</strong> before applying the <strong>sorted()</strong> built-in function. That means the list elements are sorted as strings, not as dates. Here are the steps you asked for, that are kind of self-explanatory, I'd like though to have more datails about point 6, which doesn't tell much, 3 weeks in the past? In the future?</p> <pre><code>from datetime import date, timedelta, time, datetime import sys # 1 Complete read_date() def read_date(date_object): &quot;&quot;&quot;Read a string representing a date in the format 2121-04-12, create a date object from the input string, and return the date object &quot;&quot;&quot; date_object = datetime.strptime(date_object, '%Y-%m-%d').date() return date_object # 2. Use read_date() to read four (unique) date objects, putting the date objects in a list list_date = [] n_dates = 4 # Here you could check with an infinite loop the inputs # Not being the main request, I opted for a more straightforward version try: for _ in range(n_dates): list_date.append(read_date(input())) except ValueError: print('Invalid format') sys.exit(1) # 3. Use sorted() to sort the dates, earliest first list_sorted = sorted(list_date) print(list_sorted) # 4. Output the sorted_dates in order, earliest first, in the format mm/dd/yy for date in list_sorted: print(date.strftime('%m/%d/%y')) # 5. Output the number of days between the last two dates in the sorted list # as a positive number print(abs((list_sorted[-1] - list_sorted[-2]).days)) # 6. Output the date that is 3 weeks from the most recent date in the list # 3 weeks ?? # 7. Output the full name of the day of the week of the earliest day print(list_sorted[0].strftime('%A')) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: how to add elements in the list in python with one loops or without loops or any direct functions<p>I need code to sum lists. Example: [[1,2,3],[1,2,3]]. answer be like [2,4,6]. [[1,1,1],[2,2,2],[3,3,3]] answer: [6,6,6]</p>
<p>Refer <a href="https://www.adamsmith.haus/python/answers/how-to-add-two-lists-element-wise-in-python" rel="nofollow noreferrer">this</a> this can work for <code>n</code> number of list too and please try first, read docs, and provide relevant resources that you tried or code snippet.</p> <pre class="lang-py prettyprint-override"><code>[a+b+c for a,b,c in zip([1,1,1],[2,2,2],[3,3,3])] </code></pre> <p>Output: <code>[6,6,6]</code></p> <p>if you are okay with using packages use <a href="https://numpy.org/doc/" rel="nofollow noreferrer">numpy</a> and apply it but read it's documentation beforehand.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python how to filter a csv based on a column value and get the row count<p>I want to do data insepction and print count of rows that matches a certain value in one of the columns. So below is my code</p> <pre><code>import numpy as np import pandas as pd data = pd.read_csv(&quot;census.csv&quot;) </code></pre> <p>The census.csv has a column &quot;income&quot; which has 3 values '&lt;=50K', '=50K' and '&gt;50K' and i want to print number of rows that has income value '&lt;=50K'</p> <p>i was trying like below</p> <pre><code>count = data['income']='&lt;=50K' </code></pre> <p>That does not work though.</p>
<p>Sum Boolean selection</p> <pre><code>(data['income'].eq('&lt;50K')).sum() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Getting TypeError When Trying To Write To A File And Append It To a Zip folder at same time<p>I want to write some information to a text file and after my loop is done writing information to this text file, throw that file to a zip folder. Here's what I have right now.</p> <pre><code>import zipfile file_names = ['oranges.txt', 'lemonade.txt', 'mango.txt'] for file in file_names: text_file_name = f&quot;{file}.txt&quot; counter = 1 zf = zipfile.ZipFile('food_data.zip', &quot;w&quot;, zipfile.ZIP_DEFLATED) response = requests.get(f&quot;api.farmers.com?page={counter}&quot;) if response.json != []: with ZipFile(&quot;food_data.zip&quot;, &quot;w&quot;) as zip: with zip.open(file, &quot;w&quot;) as f: f.write(&quot;Confirmed API is working!&quot;) counter += 1 zf.writestr(file_name, json.dumps(response.json())) &gt;&gt;&gt;&gt; **TypeError: a bytes-like object is required, not 'str'** I've tried to add &quot;rb&quot; to the write mode in `ZipFile(&quot;food_data.zip&quot;, &quot;w&quot;) as zip:` but then I get the error message `ValueError: ZipFile requires mode 'r', 'w', 'x', or 'a'` </code></pre> <p>This is the documentation for ZipFile that I was reading about: <a href="https://docs.python.org/3/library/zipfile.html" rel="nofollow noreferrer">https://docs.python.org/3/library/zipfile.html</a></p>
<p>Try this method:</p> <pre><code>file = 'file.txt' zipfile.ZipFile('food_data.zip', &quot;w&quot;, zipfile.ZIP_DEFLATED) zf.writestr(file, &quot;Hello! Confirmed that API is working!&quot;) zf.close() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python BOTO3 script is not returning name inside the tag<p>I need to extract the name, instance id, state of AWS EC2 and export it to csv. By using the below code I got the instance id and state. The name is inside the tags and I am having multiple key-value in my tags like below:</p> <p>&quot;Tags&quot;: [ { &quot;Value&quot;: &quot;ggggg&quot;, &quot;Key&quot;: &quot;bbbb&quot; }, { &quot;Value&quot;: &quot;rrrrrr&quot;, &quot;Key&quot;: &quot;eeeee&quot; }, { &quot;Value&quot;: &quot;uyyyutu&quot;, &quot;Key&quot;: &quot;hhhhhh&quot; }, { &quot;Value&quot;: &quot;xxxxxxx&quot;, &quot;Key&quot;: &quot;NAME&quot; }, { &quot;Value&quot;: &quot;GREEN&quot;, &quot;Key&quot;: &quot;STATE&quot; }, { &quot;Value&quot;: &quot;xxxxx&quot;, &quot;Key&quot;: &quot;yyyyy&quot; } ]</p> <p>How can I get the name from particular KEY=NAME. While using the following code I am getting all values in the tags it is not giving particular value.</p> <pre><code>import boto3 import csv client = boto3.client('ec2') response = client.describe_instances( Filters=[ { 'Name':'tag:STATE','Values':['GREEN'] } ] ) detail=[] for Reservations in response[&quot;Reservations&quot;]: for Instances in Reservations[&quot;Instances&quot;]: detail.append({ 'ID':Instances['InstanceId'], 'Status':Instances['State']['Name'], 'Name':Instances['Tags']['Key'=='Name']['Value'] }) header=['ID','Status','Name'] with open('EC2_Detail.csv','w') as file: writer=csv.DictWriter(file, fieldnames=header) writer.writeheader() writer.writerows(detail) </code></pre>
<p>Try:</p> <pre><code>[x for x in Instances['Tags'] if x['Key'] == 'NAME'][0]['Value'] </code></pre> <p>This will break, if the tag name isn't defined for a specific instance.</p> <pre><code>tag_names = [x for x in Instances['Tags'] if x['Key'] == 'NAME'] if len(tag_names) &gt; 0: name = tag_names[0] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Why HTML file that I got from Google Translate using my script, is different from what I really want?<p>I want to make a web scraper that will automatically take the translation of a word from Google Translate, in my console environment using my python script.</p> <p>I saw that HTML code which I got from python <code>Requests</code> module, is very different from what it is on the website, you can see the <a href="https://www.diffchecker.com/5NfF30hG" rel="nofollow noreferrer">differences</a>.</p> <p>After some researches about this subject, I learned <a href="https://stackoverflow.com/a/14339352/12532854">from this answer</a> that Google has some security features that won't let me have access to its HTML contents using my scripts.</p> <p>But I have a chrome extension <code>ImTranslator</code>, which can give me translate of whatever word I selected from a web page, directly from Google Translate.</p> <p>So, how this extension can do this?! Why I can't have a script that will do this for me?</p> <p>I also tried using <code>urllib</code> for making requests and sending headers with my request.</p> <p>Also, this is my code:</p> <p>First, using <code>urllib</code> module:</p> <pre><code>headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive' } url = 'https://translate.google.com/#view=home&amp;op=translate&amp;sl=en&amp;tl=fa&amp;text=space' req = urllib.request.Request(url, None, headers) respone = urllib.request.urlopen(req) </code></pre> <p>Second, using <code>Requests</code>:</p> <pre><code>url = 'https://translate.google.com/#view=home&amp;op=translate&amp;sl=en&amp;tl=fa&amp;text=space' res = requests.get(url) </code></pre>
<p>You can use <a href="https://pypi.org/project/googletrans/" rel="nofollow noreferrer">googletrans</a> module of Python to translate some text through free API.</p> <p>But if you want to scrape the Google Translate then you can do the following</p> <pre><code>import requests_html from bs4 import BeautifulSoup as BS url = &quot;https://translate.google.com/#view=home&amp;op=translate&amp;sl=en&amp;tl=hy&amp;text={}&quot; text = input(&quot;text: &quot;) with requests_html.HTMLSession() as session: response = session.get(url.format(text)) response.html.render() content = response.html.html soup = BS(content, &quot;html.parser&quot;) translation = soup.find(&quot;span&quot;, &quot;translation&quot;).text print(translation) </code></pre> <p>Using <strong>asynchronous</strong> programming</p> <pre><code>import asyncio import pyppeteer from bs4 import BeautifulSoup as BS URL = &quot;https://translate.google.com/#view=home&amp;op=translate&amp;sl=en&amp;tl=hy&amp;text={}&quot; async def main() -&gt; None: text = input(&quot;text to translate: &quot;) browser = await pyppeteer.launch(headless=True) page = await browser.newPage() await page.goto(URL.format(text)) html = await page.content() soup = BS(html, &quot;html.parser&quot;) tranlation = soup.find(&quot;span&quot;, &quot;translation&quot;).text print(tranlation) await browser.close() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How can I find what time of day it is in python?<p>what time of day is it ? [morning/afternoon/evening/night]</p> <pre><code>#example: a = day() print(&quot;The time is &quot;) + a </code></pre> <p>Should Output</p> <pre> The time is Morning/evening/afternoon/night </pre>
<p>It's kinda easy!</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>import datetime as dt def day(han): #find what time of day is it? t = han.datetime.now() h = t.strftime(&quot;%H&quot;) h = int(h) if h &lt; 12: return &quot;morning&quot; h = 0 t = 0 if h &lt; 16: return &quot;afternoon&quot; h = 0 t = 0 if h &lt; 19: return &quot;evening&quot; h = 0 t = 0 if h &lt; 24: return &quot;night&quot; h = 0 t = 0 return &quot;midnight&quot; h = 0 t = 0 a = day(dt) print(&quot;The time is &quot; + dt) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Google Drive API seems to return wrong modified time<p>I am basically getting the modified time like this:</p> <pre><code>request = service.files().get_media(fileId=file_id) data = service.files().get(fileId=l, fields='*').execute() meta = service.files().get(fileId=l, fields=&quot;*&quot;, supportsTeamDrives=True).execute() print(meta[&quot;modifiedTime&quot;]) </code></pre> <p>But the printed modified time is different than what the web interface for the Google Drive shows:</p> <p>u'2020-08-02T12:29:14.658Z'</p> <p><a href="https://i.stack.imgur.com/ReSof.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ReSof.png" alt="enter image description here" /></a></p> <p>Why do the date times differ? Am I doing it incorrectly?</p>
<p>The file attribute <code>modifiedTime</code> and the latest revision timestamp don’t always store the same value, that’s expected behavior.</p> <p>The code provided fetches the Drive file item attribute <code>modifiedTime</code>, however the screenshot attached shows the revision list. The <code>modifiedTime</code> attribute stores the timestamp of the latest modification of an item in Google Drive. Any change to that item would update its value. A revision timestamp however stores the datetime when a new version of the file contents is updated/uploaded.</p> <p>You can find more information <a href="https://developers.google.com/drive/api/guides/change-overview" rel="nofollow noreferrer">here</a>.</p> <p>For example, after uploading a new revision of a binary file to Drive, let’s say <code>modifiedTime</code> is <code>X</code> and the latest revision timestamp would also be <code>X</code>. However if I change that item’s description using Drive UI, <code>modifiedTime</code> is now <code>Y</code> but the latest revision timestamp would still be <code>X</code>.</p> <p>On an additional note, timestamps returned from the API are always in UTC timezone whether timestamps displayed on Drive UI are usually displayed in the local time zone.</p> <p>If you want to audit/inspect all changes to a specific file in Drive, I’d recommend using <a href="https://developers.google.com/drive/activity/v2/reference/rest/v2/activity/query" rel="nofollow noreferrer">Drive Activity API</a>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: TypeError: 'Pipeline' object is not callable in custom classifier<p>I am working on a classification problem. I have created a class for my classifier. I am having an issue with this class. I have a get_clf_pipeline method which returns the classifier pipeline, which is used by the train method. This method doesn`t require access to an instance or class data and I tried making it a staticmethod but that approach didn`t work as well. How can I fix this issue?</p> <pre><code>class Event_classifier: def __init__(self): self.clf_pipeline = self.get_clf_pipeline() def get_clf_pipeline(self): &quot;&quot;&quot; Return the pipeline &quot;&quot;&quot; categorical_features = ['CRole', 'Clevel', 'Gender'] categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) preprocessor = ColumnTransformer( transformers=[ ('cat', categorical_transformer, categorical_features)]) estimators = [ ('rf',RandomForestClassifier(n_estimators=200,class_weight='balanced')), ('mnb', MultinomialNB()), ('svr', make_pipeline(StandardScaler(with_mean=False), LinearSVC(random_state=42))) ] stacked_clf = StackingClassifier( estimators=estimators, final_estimator=LogisticRegression(class_weight='balanced') ) clf_pipeline = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', stacked_clf)]) return clf_pipeline def train(self, X,y): &quot;&quot;&quot;Trains the classifier on input data &quot;&quot;&quot; print(type(self.clf_pipeline)) self.clf_pipeline(X,y) def predict(self): &quot;&quot;&quot;Predict on test data &quot;&quot;&quot; if (X.shape) == 1: X = X.T y_pred = self.clf_pipeline.predict(X) return y_pred </code></pre> <p>Creating a class instance and training on data</p> <pre><code>ec = Event_classifier() ec.train(X_train, y_train) print('Model training complete') </code></pre> <p>I get the following error</p> <pre><code>&lt;class 'sklearn.pipeline.Pipeline'&gt; --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-129-36d8dfcdfc12&gt; in &lt;module&gt; 1 ec = Event_classifier() 2 ----&gt; 3 ec.train(X_train, y_train) 4 print('Model training complete') 5 &lt;ipython-input-126-de5f651c0a3d&gt; in train(self, X, y) 35 &quot;&quot;&quot; 36 print(type(self.clf_pipeline)) ---&gt; 37 self.clf_pipeline(X,y) 38 39 def predict(self): TypeError: 'Pipeline' object is not callable </code></pre>
<p>Your <code>self.clf_pipeline</code> is a <code>Pipeline</code> object, so <code>self.clf_pipeline(X,y)</code> is trying to <em>call</em> the pipeline on the inputs <code>X, y</code>, but (as the error says) <code>Pipeline</code>s aren't functions. Presumably you want something like <code>self.clf_pipeline.fit(X, y)</code> instead.</p> <p>One more thing jumps out: when is <code>X.shape == 1</code> (in your <code>predict</code> method)?</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: ImportError: No module named alc Python<p>I'm need to inject option 18 to a DHCPv6 traffic, I found this code, <a href="https://documentation.nokia.com/html/0_add-h-f/93-0098-HTML/7750_SR_OS_Triple_Play_Guide/Appendix-Python.pdf" rel="nofollow noreferrer">source</a>,</p> <pre><code>from alc import dhcpv6 import struct packet = dhcpv6.get_relaymsg()# Extract the original DHCPv6 packet within LDRA. msgType = ord(packet.msg_type) # Get the message type. ia_na = packet.get_iana() # Store the IA-NA option for further processing later on. ia_pd = packet.get_iapd() # Store the IA-PD option for further processing later on. if msgType == 3: # If the message in the LDRA packet is DHCPv6 Request, insert the lease related times in address/prefic options. ia_na[0][1] = '\x00\x00\x07\xd0'# Set the renew time (T1) in IA-NA to 2000sec. ia_na[0][2] = '\x00\x00\x0b\xb8'# Set the rebind time (T2) in IA-NA to 3000sec. ia_na[0][3][5][0][1] = '\x00\x00\x0f\xa0' # Set the preferred time in IA-NA to # 4000sec. ia_na[0][3][5][0][2] = '\x00\x00\x0f\xa0'# Set the valid time in IA-NA to 4000sec. packet.set_iana(ia_na) # Update the stored packet with the new values for IA-NA. ia_pd[0][1] = '\x00\x00\x07\xd0'# Set the renew time (T1) in IA-PD to 2000sec. ia_pd[0][2] = '\x00\x00\x0b\xb8'# Set the rebind time (T2) in IA-PD to 3000sec. ia_pd[0][3][26][0][0] = '\x00\x00\x0f\xa0' # Set the preferred time in IA-PD to # 4000sec. ia_pd[0][3][26][0][1] = '\x00\x00\x0f\xa0'# Set the valid time in IA-PD to 4000sec. packet.set_iapd(ia_pd) # Update the stored packet with the new values for IA-PD. dhcpv6.set_relaymsg(packet) # Insert the packet in the LDRA message. </code></pre> <p>but when I run it I got this error:</p> <pre><code> from alc import dhcpv6 ImportError: No module named 'alc' </code></pre> <p>the problem is that when I tried to install this module I couldn't find it, I installed this package <code>dhcp-leases-0.1.6.tar.gz</code> but it didn't solve the problem. where can I find the <code>alc</code> module ?</p>
<blockquote> <p><strong>alc</strong> — The SR OS-provided packages provide access to various ESM objects such as DHCPv4, DHCPv6 or RADIUS packets.</p> </blockquote> <p>Found <a href="https://documentation.nokia.com/html/0_add-h-f/93-0098-HTML/7750_SR_OS_Triple_Play_Guide/Appendix-Python.pdf" rel="nofollow noreferrer">here</a> on page 3 of 42 in the pdf.</p> <p>It seems that the alc module is included in SR OS. So you'll need to run this python code using <a href="https://www.nokia.com/networks/products/service-router-operating-system/" rel="nofollow noreferrer">Nokia's SR OS</a></p> <p>EDIT: Reading the documentation a little bit more, it seems that this PDF is part of the SR OS manual. Thus the use of the alc module outside of the aforementioned operationg system is probably not possible.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to perform on global dataframe in the target function of multiprocessing in python?<p>I have the following code. I want to calculate values of all pairs using <strong>calculate_mi</strong> function on global dataframe <strong>df</strong> with python multiprocess.</p> <pre><code>from multiprocess import Pool def calculate_mi(pair): global df from pyitlib import discrete_random_variable as drv import numpy as np i, j = pair val = ( 2*drv.information_mutual(df[i].values.astype(np.int32), df[j].values.astype(np.int32)) ) / ( drv.entropy(df[i].values.astype(np.int32)) + drv.entropy(df[j].values.astype(np.int32)) ) return (i,j), val def calculate_value(t_df): global df df = t_df all_pair = [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')] pool = Pool() pair_value_list = pool.map(calculate_mi, all_pair) pool.close() print(pair_value_list) def calc(): data = {'1':[1, 0, 1, 1], '2':[0, 1, 1, 0], '3':[1, 1, 0, 1], '0':[0, 1, 0, 1] } t_df = pd.DataFrame(data) calculate_value(t_df) if __name__ == '__main__': calc() </code></pre> <p>This code gives me the expected output in <strong>google colab</strong> platform. But it gives the following error while I run it in my Local machine. (I am using windows 10 ,anaconda, jupyter notebook,python 3.6.9). How can i solve this or is there another way to do it? <a href="https://i.stack.imgur.com/Q74Tl.png" rel="nofollow noreferrer">RemoteTraceback Traceback (most recent call last), ... NameError: name 'df' is not defined</a></p>
<p>First, a couple of things:</p> <ol> <li>It should be: <code>from multiprocessing import Pool</code> (not <code>from multiprocess</code>)</li> <li>It appears you have left out the import of the <code>pandas</code> library.</li> </ol> <p>Moving on ...</p> <p>The problem is that under Windows the creation of new processes is not done using a <code>fork</code> call and consequently the sub-processes do not automatically inherit global variables such as <code>df</code>. Therefore, you must initialize each sub-process to have global variable <code>df</code> properly initialized by using an initializer when you create the <code>Pool</code>:</p> <pre><code>from multiprocessing import Pool import pandas as pd def calculate_mi(pair): global df from pyitlib import discrete_random_variable as drv import numpy as np i, j = pair val = ( 2*drv.information_mutual(df[i].values.astype(np.int32), df[j].values.astype(np.int32)) ) / ( drv.entropy(df[i].values.astype(np.int32)) + drv.entropy(df[j].values.astype(np.int32)) ) return (i,j), val # initialize global variable df for each sub-process def initpool(t_df): global df df = t_df def calculate_value(t_df): all_pair = [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')] # make sure each sub-process has global variable df properly initialized: pool = Pool(initializer=initpool, initargs=(t_df,)) pair_value_list = pool.map(calculate_mi, all_pair) pool.close() print(pair_value_list) def calc(): data = {'1':[1, 0, 1, 1], '2':[0, 1, 1, 0], '3':[1, 1, 0, 1], '0':[0, 1, 0, 1] } t_df = pd.DataFrame(data) calculate_value(t_df) if __name__ == '__main__': calc() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python integer and float multiplication error<p>The question seems dummy, but I cannot get it right. The output <code>cm1</code> is expected to be floats, but I only get zeros and ones.</p> <pre><code>import numpy as np import scipy.spatial.distance sim = scipy.spatial.distance.cosine a = [2, 3, 1] b = [3, 1, 2] c = [1, 2, 6] cm0 = np.array([a,b,c]) ca, cb, cc = 0.9, 0.7, 0.4 cr = np.array([ca, cb, cc]) cm1 = np.empty_like(cm0) for i in range(3): for j in range(3): cm1[i,j] = cm0[i,j] * cr[i] * cr[j] print(cm1) </code></pre> <p>And I get:</p> <pre><code>[[1 1 0] [1 0 0] [0 0 0]] </code></pre>
<p><code>empty_like()</code> <a href="https://www.geeksforgeeks.org/numpy-empty_like-python/" rel="nofollow noreferrer">matches the type</a> of the given numpy array by default, as <a href="https://stackoverflow.com/users/901925/hpaulj">hpaulj</a> suggested in the comments. In your case <code>cm0</code> is of type integer.</p> <p>The <code>empty_like</code> function accepts multiple arguments though, one of wich is <code>dtype</code>. Setting <code>dtype</code> to <code>float</code> should solve the problem:</p> <pre><code>cm1 = np.empty_like(cm0, dtype=float) </code></pre> <p>And also Python truncates floating point numbers at the decimal point when <a href="https://stackoverflow.com/questions/6569528/python-float-to-int-conversion">converting to integers</a>. In your case, every multiplication done results in a number between <code>1.89</code> and <code>0.36</code>, so flooring the results will result in <code>0</code>s and <code>1</code>s respectively.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to count the number of days a stock price is higher than the other<p>I would Like to get a count of the number of days for which (VZ) stock return is larger than the stock index return (INX)</p> <p>I already calculated the return using the <code>pct_change</code> function. Now I want to get the number of days VZ is larger than INX. I don't know how to go about this.</p> <pre><code>Dates VZ INX 2016-03-21 NaN NaN 2016-03-22 -0.004304 -0.000877 2016-03-23 -0.005638 -0.006386 2016-03-24 0.012285 -0.000378 2016-03-28 -0.002987 0.000545 2016-03-29 0.012172 0.008817 2016-03-30 -0.000185 0.004350 2016-03-31 0.000740 -0.002040 2016-04-01 -0.001294 0.00633 </code></pre> <p>1</p>
<p>To do this you can check which times the &quot;VZ&quot; value is higher than the &quot;INX&quot; value using a column operation, and get the sum of the output:</p> <pre class="lang-py prettyprint-override"><code>temp = df[&quot;VZ&quot;] &gt; df[&quot;INX&quot;] print(temp.sum()) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Plotting a violin plot with lists<p>I would like to plot a violin plot using Python for a multivariate regression problem. I attempt to obtain a prediction scalar value for time series input. The libraries of choice are probably matplotlib and / or seaborn but I'm open to alternative suggestions well.</p> <p>This is what I have:</p> <ol> <li>A list [g_1,g_2,...g_n] of n ground truth values for each of my n subjects.</li> <li>k time series inputs (i.e. lists) consisting of j elements for each of my n subjects. Please note that k and j don't have to be equal for each subject.</li> <li>k predictions for each of my n subjects.</li> </ol> <p>Example input:</p> <ul> <li>Ground truth: [14,67,342,5]</li> <li>Time series input: [[19,2434,23432,-123,-54],[99,23,4,-6],[1,2,3,4,5,6,7,8],[-1,-2,-3]]</li> </ul> <p>Example output after performing a regression:</p> <ul> <li>Predictions: [17,54,312,-2]</li> </ul> <p>What I would like to obtain is a nice violin plot as shown in <a href="https://www.geeksforgeeks.org/violin-plot-for-data-analysis/" rel="nofollow noreferrer">this tutorial</a>. This is how my pandas data frame looks like:</p> <pre><code>dataframe = pd.DataFrame( {'Predictions': predictions, # This is a list of k elements 'Subject IDs': subjectIDs, # This is a list of n strings 'Ground truths': groundtruths # This is a list of n float values }) </code></pre> <p>Attempting to draw a plot with </p> <pre><code>sns.violinplot( ax = ax, y = dataframe["Predictions"] ) </code></pre> <p>only results in:</p> <blockquote> <p>TypeError: No loop matching the specified signature and casting was found for ufunc add</p> </blockquote> <p>Additionally, I also already tried to follow the official <a href="https://seaborn.pydata.org/generated/seaborn.violinplot.html#seaborn.violinplot" rel="nofollow noreferrer">seaborn documentation</a>, using the command </p> <pre><code>ax = sns.violinplot(x="Subject IDs", y="Predictions", data=dataframe) </code></pre> <p>instead. However, this only results in</p> <blockquote> <p>TypeError: unhashable type: 'list'</p> </blockquote> <hr> <p>Update: If I treat the "Predictions" list as a tuple, I manage to create a plot without errors but unfortunately it's completely messed up as it puts all prediction values on the y-axis (see below for a snippet).</p> <p><a href="https://i.stack.imgur.com/ZSyRl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZSyRl.png" alt="Messed up violin plot"></a></p> <hr> <p>Thus, my question is: How can I draw a plot with all subject IDs on the x-axis, the ground truths on the y-axis and the probability distribution of my predictions, the corresponding mean values and a confidence interval as violin plot?</p>
<p>OK, I solved my problem. The problem was with my input pandas dataframe. I had to make sure that each of my observation was assigned exactly one single prediction and <strong>not</strong> a complete list.</p> <p>This is what my data frame should have looked like:</p> <pre><code>data = pd.DataFrame( {'groundtruths': groundtruthsList, 'predictions': predictionsList, 'subjectIDs': subjectIDsList }) print(data.head()) groundtruths predictions subjectIDs 0 70 75.864983 01 1 70 50.814903 01 2 70 80.715569 01 3 70 70.627260 01 4 70 49.516285 01 . . . . . . . . . . . . </code></pre> <p>Now, as the data frame has the right format, I can easily draw nice violin plots with</p> <pre><code>sns.violinplot(x="subjectIDs", y="predictions", data=data) </code></pre> <p>A simple <a href="https://seaborn.pydata.org/generated/seaborn.scatterplot.html" rel="nofollow noreferrer">seaborn scatterplot</a> can be used to nicely put the ground truth for each subject in this plot as well.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How Can make PyCharm's autocomplete work on django?<p>I am using pycharm community , I make test project on django and in template I make degree.html file. I have the following code in degree.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;welcome to degree site of {{student_id}}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {%for item in degree%} &lt;h4&gt; {{item.student_dgree}} &lt;/h4&gt; &lt;h4&gt; {{item.student_id}} &lt;/h4&gt; {%endfor%} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I can't complete instruction like "for , endfor , .. etc" I install django from cmd and from pycharm's terminal too using pip.</p> <p>and from <strong>File -> Settings -> Project Interpreter</strong> I add django Package and install it </p> <p>help please !</p>
<p>PyCharm Community has no built in support for Django Template language (only Pro version). You could try an Extension/Plugin like Djaneiro:</p> <p><a href="https://plugins.jetbrains.com/plugin/9295-djaneiro-for-pycharm" rel="nofollow noreferrer">https://plugins.jetbrains.com/plugin/9295-djaneiro-for-pycharm</a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Image segmentation python opencv<p>I want to ask for some advice about the procedure that I should implement for image segmentation working with opencv in python.</p> <p>I have this kind of image <a href="https://i.stack.imgur.com/pPjY2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pPjY2.jpg" alt="image" /></a>and my purpose is to detect the white fiber like here <a href="https://i.stack.imgur.com/vzuNG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzuNG.jpg" alt="image2" /></a></p> <p>Does anyone have a proposition of the steps of image processing that I should do?</p>
<p>Since I can notice that object's color is different than the background, I found <a href="https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/" rel="nofollow noreferrer">this guide</a> helpful. The concept is the following : 1.apply RGB filters to your image, 2.grab contours using OpenCV, then 3.apply some handcraft conditions to them so as to fit your desired output, and finally 4.produce the box.</p> <p>If all of your images share the same color patterns, this should work.. If not, it will prove noisy ..</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Discordbot with discord.py doesn`t deletes messages with command ctx.channel.purge(*amount*)<p>I got the problem, that when I use the purge command in my Bot using discord.py rewriting method, it doesn't work. What I mean by that is that when I run the code, and then write 'clear' in the discord channel, it simply doesn't deletes the given amount of messages, and it also doesn't raises an error. I've also tried to put print('test') in the definition, but then it only prints test...</p> <p>That is the Code I used to do this:</p> <pre><code>@client.command async def clear(ctx, amount=5): await ctx.channel.purge(limit=amount) </code></pre>
<p>the proper use of <code>@client.command</code> is <code>@client.command()</code>. See if that fixes it.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Allocate the first row of a group in Pandas<p>I want to allocate the first row of a group.</p> <p>The input:</p> <pre><code>df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B'], 'col2': [1, 1, 2, 3], 'col3': ['value1', 'value2', 'value3', 'value4']}) </code></pre> <p>I tried:</p> <pre><code>df.groupby(['col1', 'col2']).first() </code></pre> <p>But I only get the first row back.</p> <p>I want this output:</p> <pre> col1 col2 col3 first_row A 1 value1 True A 1 value2 False B 2 value3 True B 3 Value4 True </pre>
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby.cumcount</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>eq</code></a>. If the cumulative count is equal to 0, then it's the first row:</p> <pre><code>df['first_row'] = df.groupby(['col1', 'col2']).cumcount().eq(0) </code></pre> <p>[out]</p> <pre><code> col1 col2 col3 first_row 0 A 1 value1 True 1 A 1 value2 False 2 B 2 value3 True 3 B 3 value4 True </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Counting the occurrence of words in a dataframe column using a list of strings<p>I have a list of strings and a dataframe with a text column. In the text column, I have lines of text. I want to count how many times each word in the list of strings occurs in the text column. I am aiming to add two columns to the dataframe; one column with the word and the other column having the number of occurrences. If there is a better solution, I am open to it. It would be great to learn different ways to accomplish this. I would ideally like one dataframe in the end.</p> <pre><code>string_list = ['had', 'it', 'the'] </code></pre> <p>Current dataframe:</p> <p><a href="https://i.stack.imgur.com/L3UEL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L3UEL.png" alt="enter image description here" /></a></p> <p>Dataframe in code:</p> <pre><code>pd.DataFrame({'title': {0: 'book1', 1: 'book2', 2: 'book3', 3: 'book4', 4: 'book5'}, 'text': {0: 'His voice had never sounded so cold', 1: 'When she arrived home, she noticed that the curtains were closed.', 2: 'He was terrified of small spaces and she knew', 3: &quot;It was time. She'd fought against it for so long&quot;, 4: 'As he took in the view from the twentieth floor, the lights went out all over the city'}, 'had': {0: 1, 1: 5, 2: 5, 3: 2, 4: 5}, 'it': {0: 1, 1: 3, 2: 2, 3: 1, 4: 2}, 'the': {0: 1, 1: 4, 2: 5, 3: 3, 4: 3}}) </code></pre> <p>Attempting to get a dataframe like this:</p> <p><a href="https://i.stack.imgur.com/HvWTt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HvWTt.png" alt="enter image description here" /></a></p>
<p>Define a custom regex, <code>extractall</code>, <code>join</code>, and <code>melt</code>:</p> <pre><code>regex = '|'.join(fr'(?P&lt;{w}&gt;\b{w}\b)' for w in string_list) (df[['title', 'text']] .join(df['text'].str.extractall(regex).notna().groupby(level=0).sum()) .fillna(0) .melt(id_vars=['title', 'text'], var_name='word', value_name='word count') ) </code></pre> <p>Output:</p> <pre><code> title text word word count 0 book1 His voice had never sounded so cold had 1.0 1 book2 When she arrived home, she noticed that the cu... had 0.0 2 book3 He was terrified of small spaces and she knew had 0.0 3 book4 It was time. She'd fought against it for so long had 0.0 4 book5 As he took in the view from the twentieth floo... had 0.0 5 book1 His voice had never sounded so cold it 0.0 6 book2 When she arrived home, she noticed that the cu... it 0.0 7 book3 He was terrified of small spaces and she knew it 0.0 8 book4 It was time. She'd fought against it for so long it 1.0 9 book5 As he took in the view from the twentieth floo... it 0.0 10 book1 His voice had never sounded so cold the 0.0 11 book2 When she arrived home, she noticed that the cu... the 1.0 12 book3 He was terrified of small spaces and she knew the 0.0 13 book4 It was time. She'd fought against it for so long the 0.0 14 book5 As he took in the view from the twentieth floo... the 4.0 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to call a variable outside a validate() function which is inside the FlaskForm class<p>I have two <code>def validate(self)</code> functions within the <code>RegistrationForm(FlaskForm)</code>. First function validates the user input if the car range is over 400km. The other function validates if the user lives far or close to work by calculating the distance between the user's address and work address by means of geopy module. I've been told that <code>def validate_field(self, field):</code> function takes only one attribute which must be the same as the field name. In that function I have an extra variable <code>total_travel_km</code> that stores distance between work and user's home. If user is validated than I need to store <code>total_travel_km</code> variable in DB.</p> <p>Now the server brings me this message: <em>'RegistrationForm' object has no attribute 'total_travel_km'</em></p> <p>How can I call that <code>total_travel_km</code> variable correctly and write it inside DB</p> <p><strong>Here is the cut out from my code:</strong></p> <pre><code>class RegistrationForm(FlaskForm): car_range = IntegerField('Car Range, km') home_address = StringField('Home Address') submit = SubmitField('Register User/Car') def validate_car_range(self, car_range): if car_range.data &gt; 400: raise ValidationError('Your car range does not meet our requirements') def validate_home_address(self, home_address): user_loc = locator.geocode(home_address.data) user_coords = (user_loc.latitude, user_loc.longitude) one_way = geopy.distance.geodesic(tco_coords, user_coords).km total_travel_km = one_way*4 if total_travel_km &lt; self.car_range.data: raise ValidationError('You live too close to work') return total_travel_km @app.route(&quot;/register&quot;, methods=['POST', 'GET']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(car_range=form.car_range.data, home_address=form.home_address.data, car_travel_km=form.total_travel_km) db.session.add(user) db.session.commit() </code></pre> <blockquote> <p>EDIT: I figured out. I had to pass form. instead of self. in validation method. Below is the correct code:</p> </blockquote> <pre><code>def validate_home_address(form, home_address): user_loc = locator.geocode(home_address.data) user_coords = (user_loc.latitude, user_loc.longitude) one_way = geopy.distance.geodesic(tco_coords, user_coords).km form.total_travel_km = one_way*4 if form.total_travel_km &lt; self.car_range.data: raise ValidationError('You live too close to work') return form.total_travel_km </code></pre>
<p>Set a form instance variable in the validation method:</p> <pre><code>class RegistrationForm(FlaskForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.total_travel_km = None def validate_home_address(self, home_address): user_loc = locator.geocode(home_address.data) user_coords = (user_loc.latitude, user_loc.longitude) one_way = geopy.distance.geodesic(tco_coords, user_coords).km total_travel_km = one_way * 4 if total_travel_km &lt; self.car_range.data: raise ValidationError('You live too close to work') # all good save the total travel in the form self.total_travel_km = total_travel_km </code></pre> <p>Also, you might not want to hard code the car range limit, you can pass a value when you instance the form:</p> <pre><code>class RegistrationForm(FlaskForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.total_travel_km = None self.required_car_range = kwargs.get('required_car_range', 400) def validate_car_range(self, car_range): if car_range.data &gt; self.required_car_range: raise ValidationError('Your car range does not meet our requirements') </code></pre> <p>and use as follows:</p> <pre><code>@app.route(&quot;/register&quot;, methods=['POST', 'GET']) def register(): form = RegistrationForm(required_car_range=600) if form.validate_on_submit(): user = User(car_range=form.car_range.data, home_address=form.home_address.data, car_travel_km=form.total_travel_km) db.session.add(user) db.session.commit() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Update a DataFrame with duplicate destination<p>I would like to update a dataframe with another one but with multiple &quot;destination&quot;. Here is an example</p> <pre><code>df1 = pd.DataFrame({'name':['A', 'B', 'C', 'A'], 'category':['X', 'X', 'Y', 'Y'], 'value1':[None, 1, None, None], 'value2':[None, 10, None, None]}) name category value1 value2 0 A X NaN NaN 1 B X 1.0 10.0 2 C Y NaN NaN 3 A Y NaN NaN df2 = pd.DataFrame({'name':['A', 'C'], 'value1':[2, 3], 'value2':[11, 12]}) name value1 value2 0 A 2 11 1 C 3 12 </code></pre> <p>And the desired result would be</p> <pre><code> name category value1 value2 0 A X 2.0 11.0 1 B X 1.0 10.0 2 C Y 3.0 12.0 3 A Y 2.0 11.0 </code></pre> <p>I don't think pd.update works since there are two time 'A' in my first DataFrame.</p> <p>pd.merge creates other columns and I think there is probably a more elegant way than to merge these columns manually after their creation</p> <p>Thanks in advance for your help!</p>
<p>You can use <code>fillna</code> after mapping the column <code>A</code> in <code>df1</code> with the corresponding values from <code>df2</code>:</p> <pre><code>mapping = df2.set_index('name')['value'] df1['value'] = df1['value'].fillna(df1['name'].map(mapping)) </code></pre> <p>If you want to <code>map</code> multiple columns:</p> <pre><code>mapping = df2.set_index('name') for col in mapping: df1[col] = df1[col].fillna(df1['name'].map(mapping[col])) </code></pre> <p>Alternatively you can try <code>merge</code>:</p> <pre><code>df = df1.merge(df2, on='name', how='left', suffixes=['', '_r']) df.groupby(df.columns.str.rstrip('_r'), axis=1, sort=False).first() </code></pre> <hr /> <pre><code> name category value1 value2 0 A X 2.0 11.0 1 B X 1.0 10.0 2 C Y 3.0 12.0 3 A Y 2.0 11.0 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Check if a Python list has X number of consecutive values equal to Y<p>I have a collection of lists each containing 16 items, and I want to find lists with 12 consecutive values either &gt; or &lt; than a specified threshold. For now, I have iterated through the lists and put 1 for values greater and -1 for values less than the threshold, and I used to following to eliminate those that don't have 12 of either.</p> <p><code>if list.count(-1) &gt;= 12 or list.count(1) &gt;= 12:</code></p> <p>How do I efficiently check for 12 consecutive values? (12 values can loop around) for example this would count</p> <p><code>[1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]</code></p> <p>Currently I have 2 nested for loops, but I know this checks the same value multiple times.</p> <pre><code> for i in range(16): light = 0 dark = 0 for j in range(12): index = i + j if index &gt; 15: index -= 15 if list[index] == 1: light += 1 elif list[index] == -1: dark += 1 else: break if dark &gt; 0 and light &gt; 0: break if dark == 12 or light == 12: return True </code></pre>
<p>I would harness <code>itertools.groupby</code> following way</p> <pre><code>import itertools data = [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1] runs = [len(list(g)) for _,g in itertools.groupby(data)] if data[0] == data[-1]: runs[0] += runs.pop() print(max(runs) &gt;= 12) # True </code></pre> <p>Explanation: I use <code>itertools.groupby</code> to get length of runs (in this case <code>[7,4,5]</code>) - <code>itertools.groupby</code> does group only adjacent equal elements, then if first and last values of <code>data</code> are equal I extract last element from <code>runs</code> and add it to first element (as you allow wraparound), then I check if longest run is equal or greater <code>12</code>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: web scraping / web crawling showing 403 error on the site i want to crawl<pre><code>import requests from bs4 import BeautifulSoup url ='https://www.vesselfinder.com/vessels' headers= {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)'} response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') response.status_code </code></pre> <p>i tried different user agent but still not working, i tried other sites it work but this website not working, help me to crawl all vessel data from this site. thanks in advance!!!</p>
<p>Server wants an additional header for language</p> <pre><code>import requests headers = { 'user-agent': 'Mozilla/5.0', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } response = requests.get('https://www.vesselfinder.com/vessels', headers=headers) response.status_code </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Why does flake8 give different results for the same command locally and within tox?<p>I have a Python project and I use <code>flake8</code> to lint my code.</p> <p>Locally, there is a warning rightly raised by <code>flake8</code>:</p> <pre><code>$ flake8 scripts src tests --ignore=W503,E501 src/projectname/workers/utils.py:22:20: W291 trailing whitespace </code></pre> <p>However, the same command in <code>tox</code> does not raise any warning:</p> <pre><code>$ tox -e flake8 </code></pre> <p>gets the following output:</p> <pre><code>flake8 develop-inst-noop: /home/username/Projects/projectname flake8 installed: alembic==0.9.8, ..., zipp==0.5.2 flake8 runtests: PYTHONHASHSEED='2190899390' flake8 runtests: commands[0] | flake8 scripts src tests --ignore=W503,E501 ________________________________ summary _________________________________ flake8: commands succeeded congratulations :) </code></pre> <p>This is the content of my <code>tox.ini</code> file:</p> <pre><code>[tox] envlist = flake8,py36 [testenv] changedir = {toxworkdir}/{envname} usedevelop = True install_command = pip install {opts} {packages} deps = py36: pytest-cov py36: pytest flake8: flake8 setenv = COVERAGE_FILE = {toxinidir}/.coverage.{envname} commands = py36: pytest {toxinidir}/tests --cov=projectname {posargs} flake8: flake8 scripts src tests --ignore=W503,E501 ; E501: line too long ; W503: line break before binary operator </code></pre> <p>I checked, and in both experiments, I have <code>flake8==3.7.9</code><br> Why does <code>flake8</code> and <code>tox</code> not return any error code in this case when they should?</p>
<p>your <code>tox.ini</code> has:</p> <pre><code>changedir = {toxworkdir}/{envname} </code></pre> <p>this means that when you run <code>flake8</code> in tox, it's linting (non-existent) <code>.tox/flake8/scripts</code> / <code>.tox/flake8/src</code> / <code>.tox/flake8/tests</code> and so you don't see an error (the 3.7.x behaviour is to silently ignore non-existent things)</p> <p>note that in flake8 3.8 (at the time of writing, unreleased) this will yet-again become an error (E902):</p> <pre><code>$ flake8 does-not-exist does-not-exist:0:1: E902 FileNotFoundError: [Errno 2] No such file or directory: 'does-not-exist' </code></pre> <hr> <p>disclaimer: I'm the current maintainer of flake8, and one of the maintainers of tox</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Convert list type dictionary to pandas dataframe - python<p>I want to convert dictionary which has two rows. The values are in the first row and keys are in the second row.</p> <p>Here is my dictionary:</p> <pre class="lang-json prettyprint-override"><code>{'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']], 'columns': ['id', 'gender', 'array_userid' ,'location']} </code></pre> <p>I want to convert it into a pandas data framelike below:</p> <pre><code> id gender array_userid location 0 1 Male ['a,b,c'] USA 1 2 Male ['r,g,e'] JAPAN 3 3 Female ['f,r,b'] UK </code></pre>
<p>Use <code>DataFrame</code> constructor with select values of dictionary:</p> <pre><code>d = {'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']], 'columns': ['id', 'gender', 'array_userid' ,'location']} </code></pre> <hr /> <pre><code>df = pd.DataFrame(data=d['data'], columns=d['columns']) print (df) id gender array_userid location 0 1 Male [a,b,c] USA 1 2 Male [r,g,e] JAPAN 2 3 Female [f,r,b] UK </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Replacing table content using beautifulsoup<p>I want to parse a HTML document which has tabular data also in it using beautiful soup. I am doing some NLP over it.</p> <p>The table cells might have just numbers or might be text heavy. So before doing soup.get_text(), I wish to change the content of the tabular data as per the following condition.</p> <p>Condition: If the cell has more than two words( we can consider a number to be one word), then only keep it, else change the cell contents to an empty string.</p> <pre><code>&lt;code to change table data based on condition&gt; soup = BeautifulSoup(html) text = soup.get_text() </code></pre> <p>Here is something that I have tried.</p> <pre><code> tables = soup.find_all('table') for table in tables: table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') for ele in cols: if len(ele.text.split(' ')&lt;3): ele.text = '' </code></pre> <p>However, we can't set ele.text so it throws an error. </p> <p>Here's a simple HTML Structure with Table</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;HTML Tables&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border = "1"&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 1, Column 1, This should be kept because it has more than two tokens&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;not kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 2, Column 1, should be kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 2, Column 2, should be kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Once you found the element then use <code>ele.string.replace_with("")</code></p> <p>Based on your sample html</p> <pre><code>html='''&lt;html&gt; &lt;head&gt; &lt;title&gt;HTML Tables&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border = "1"&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 1, Column 1, This should be kept because it has more than two tokens&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;not kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 2, Column 1, should be kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 2, Column 2, should be kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;''' soup=BeautifulSoup(html,'html.parser') tables = soup.find_all('table') for table in tables: rows = table.find_all('tr') for row in rows: cols = row.find_all('td') for ele in cols: if len(ele.text.split(' '))&lt;3: ele.string.replace_with("") print(soup) </code></pre> <p><strong>Output</strong>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;HTML Tables&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 1, Column 1, This should be kept because it has more than two tokens&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 2, Column 1, should be kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;p&gt;&lt;span&gt;Row 2, Column 2, should be kept&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pyinstaller exe error "win32com\client\dynamic.py", line 543, in __getattr__ pywintypes.com_error: (-2147221168, 'Could not read key from registry'<p>I have converted the .py to .exe file using pyinstaller to distribute to my users Hence my users do not have Python installed.</p> <p>I used win32com to open excel &amp; run macro in excel which will also open SAP</p> <p>In my laptop I have no issue but when my user run the exe file, an error briefly pop up in console then it immediately closed. I had to run in cmd to see the error below</p> <pre><code> File &quot;AutoTQCRevB.5.py&quot;, line 76, in &lt;module&gt; File &quot;win32com\client\dynamic.py&quot;, line 543, in __getattr__ pywintypes.com_error: (-2147221168, 'Could not read key from registry', None, None) </code></pre> <p>So I checked line 76 in module</p> <pre><code>TQCmacrowb = xl.Workbooks.Open(os.getcwd()+ &quot;\\&quot; +TQCfilename) </code></pre> <p>So its trying to open excel workbook. And then I checked what is in dynamic.py line 543</p> <pre><code> try: ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) except pythoncom.com_error as details: if details.hresult in ERRORS_BAD_CONTEXT: # May be a method. self._olerepr_.mapFuncs[attr] = retEntry return self._make_method_(attr) raise debug_attr_print(&quot;OLE returned &quot;, ret) </code></pre> <p>Line 543 is ret = self.<em>oleobj</em>.Invoke(retEntry.dispid,0,invoke_type,1) so its already under a try &amp; except. I dont understand why it doesnt catch the error.</p> <p>Im using Python 3.8.10 32bit, Pyinstaller 4.3, pywin32 301, OS 64bit, Windows 7</p> <p>My user is using OS 64bit, Windows 10</p>
<p>Issue resolved! The real issue is with the excel VBA. Below is the line that's causing error</p> <pre><code> Set Connection = Appl.OpenConnectionByConnectionString(&quot;XX.XXX.XX.XXX XX&quot;, True) </code></pre> <p>Excel VBA trying to connect to SAP but there's a problem. I found a solution link below where I have to untick &quot;Notify when a script opens a connection&quot; <a href="https://stackoverflow.com/a/37372388/16493039">https://stackoverflow.com/a/37372388/16493039</a></p> <p><a href="https://i.stack.imgur.com/jqJ3J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jqJ3J.png" alt="SAP Script Notify Option Screenshot" /></a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to select one row for each distinct value for a particular column and merge to form a new dataframe in Python?<p>The dataset I am using looks like this. It is a video captioning data set with captions under the column 'Description'.</p> <pre><code>Video_ID Description mv89psg6zh4 A bird is bathing in a sink. mv89psg6zh4 A faucet is running while a bird stands. mv89psg6zh4 A bird gets washed. mv89psg6zh4 A parakeet is taking a shower in a sink. mv89psg6zh4 The bird is taking a bath under the faucet. mv89psg6zh4 A bird is standing in a sink drinking water. R2DvpPTfl-E PLAYING GAME ON LAPTOP. R2DvpPTfl-E THE MAN IS WATCHING LAPTOP. l7x8uIdg2XU A woman is pouring ingredients into a bowl. l7x8uIdg2XU A woman is adding milk to some pasta. l7x8uIdg2XU A person adds ingredients to pasta. l7x8uIdg2XU the girls are doing the cooking. </code></pre> <p>However, the number of captions for each video is different and not uniform. </p> <p>I intend to extract one row for one unique Video_ID and form a new dataframe merging these unique rows. Also, to delete the same row from the existing dataframe.</p> <p>The result I want should look like this:</p> <p>Dataframe 1-</p> <pre><code>Video_ID Description mv89psg6zh4 A faucet is running while a bird stands. mv89psg6zh4 A bird gets washed. mv89psg6zh4 A parakeet is taking a shower in a sink. mv89psg6zh4 The bird is taking a bath under the faucet. mv89psg6zh4 A bird is standing in a sink drinking water. R2DvpPTfl-E THE MAN IS WATCHING LAPTOP. l7x8uIdg2XU A woman is adding milk to some pasta. l7x8uIdg2XU A person adds ingredients to pasta. l7x8uIdg2XU the girls are doing the cooking. </code></pre> <p>Dataframe 2-</p> <pre><code>Video_ID Description mv89psg6zh4 A bird is bathing in a sink. R2DvpPTfl-E PLAYING GAME ON LAPTOP. l7x8uIdg2XU A woman is pouring ingredients into a bowl. </code></pre> <p>So that the rows are basically moved from the existing dataframe to form a new dataframe.</p>
<p>You can use <code>groupby()</code> to sample the index:</p> <pre><code>s = df.index.to_series().groupby(df['Video_ID']).apply(lambda x: x.sample(n=1)) # random unique df.loc[s] # rest of data df.drop(s) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Azure ML PipelineData with DataTransferStep results in 0 bytes file<p>I am building an Azure ML pipeline with the azureml Python SDK. The pipeline calls a PythonScriptStep which stores data on the workspaceblobstore of the AML workspace. </p> <p>I would like to extend the pipeline to export the pipeline data to an Azure Data Lake (Gen 1). Connecting the output of the PythonScriptStep directly to Azure Data Lake (Gen 1) is not supported by Azure ML as far as I understand. Therefore, I added an extra DataTransferStep to the pipeline, which takes the output from the PythonScriptStep as input directly into the DataTransferStep. According to the Microsoft documentation this should be possible.</p> <p>So far I have built this solution, only this results in a file of 0 bytes on the Gen 1 Data Lake. I think the output_export_blob PipelineData does not correctly references the test.csv, and therefore the DataTransferStep cannot find the input. How can I connect the DataTransferStep correctly with the PipelineData output from the PythonScriptStep?</p> <p>Example I followed: <a href="https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.ipynb" rel="nofollow noreferrer">https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.ipynb</a></p> <p>pipeline.py</p> <pre><code>input_dataset = delimited_dataset( datastore=prdadls_datastore, folderpath=FOLDER_PATH_INPUT, filepath=INPUT_PATH ) output_export_blob = PipelineData( 'export_blob', datastore=workspaceblobstore_datastore, ) test_step = PythonScriptStep( script_name="test_upload_stackoverflow.py", arguments=[ "--output_extract", output_export_blob, ], inputs=[ input_dataset.as_named_input('input'), ], outputs=[output_export_blob], compute_target=aml_compute, source_directory="." ) output_export_adls = DataReference( datastore=prdadls_datastore, path_on_datastore=os.path.join(FOLDER_PATH_OUTPUT, 'test.csv'), data_reference_name='export_adls' ) export_to_adls = DataTransferStep( name='export_output_to_adls', source_data_reference=output_export_blob, source_reference_type='file', destination_data_reference=output_export_adls, compute_target=adf_compute ) pipeline = Pipeline( workspace=aml_workspace, steps=[ test_step, export_to_adls ] ) </code></pre> <p>test_upload_stackoverflow.py</p> <pre><code>import os import pathlib from azureml.core import Datastore, Run parser = argparse.ArgumentParser("train") parser.add_argument("--output_extract", type=str) args = parser.parse_args() run = Run.get_context() df_data_all = ( run .input_datasets["input"] .to_pandas_dataframe() ) os.makedirs(args.output_extract, exist_ok=True) df_data_all.to_csv( os.path.join(args.output_extract, "test.csv"), index=False ) </code></pre>
<p>The code example is immensely helpful. Thanks for that. You're right that it can be confusing to get <code>PythonScriptStep -&gt; PipelineData</code>. Working initially even without the <code>DataTransferStep</code>.</p> <p>I don't know 100% what's going on, but I thought I'd spitball some ideas:</p> <ol> <li>Does your <code>PipelineData</code>, <code>export_blob</code>, contain the "test.csv" file? I would verify that before troubleshooting the <code>DataTransferStep</code>. You can verify this using the SDK, or more easily with the UI. <ol> <li>Go to the PipelineRun page, click on the <code>PythonScriptStep</code> in question.</li> <li>On "Outputs + Logs" page, there's a "Data Outputs" Section (that is slow to load initially)</li> <li>Open it and you'll see the output PipelineDatas then click on "View Output"</li> <li>Navigate to given path either in the Azure Portal or Azure Storage Explorer. <a href="https://i.stack.imgur.com/9LaEq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9LaEq.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/XbnhC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XbnhC.png" alt="enter image description here"></a></li> </ol></li> <li>In <code>test_upload_stackoverflow.py</code> you are treating the <code>PipelineData</code> as a directory when call <code>.to_csv()</code> as opposed to a file which would be you just calling <code>df_data_all.to_csv(args.output_extract, index=False)</code>. Perhaps try defining the <code>PipelineData</code> with <code>is_directory=True</code>. Not sure if this is required though.</li> </ol>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Why is Python still garbage-collecting my Tkinter image?<p>I'm aware that this is a question that has been asked before on this site. However, <strong>I've made an honest attempt to implement the solutions put forward in those answers</strong>, and I'm still running into the same problem: <strong>Python seems to keep garbage-collecting my image</strong>, and I get an empty slot in my window where the image ought to be, as shown in the attached screenshot.</p> <p><a href="https://i.stack.imgur.com/Wxz31.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wxz31.png" alt="screenshot"></a> </p> <p>This is the part of my code where I attempt to import an image:</p> <pre class="lang-py prettyprint-override"><code>def make_top_title(self): result = Frame(self.top) text_lbl = Label(result, text="Proserpine", font=(main_font, title_pt, "bold")) arms_image = PhotoImage("icon.png") arms_lbl = Label(result, image=arms_image, height=200) arms_lbl.image = arms_image arms_lbl.pack() text_lbl.pack() return result </code></pre> <p>You'll notice that I've already attempted to use the trick of preserving the image by anchoring it onto a property of a label object. You may also notice, from the attached screenshot, that I have no problem importing a custom icon - using the same image file - for this window.</p> <p>I'm happy to share any more code from this program, as required.</p> <hr> <p>A couple of people have suggested I share a bit more of my code. This is the whole file in which the code above is located:</p> <pre class="lang-py prettyprint-override"><code>### This code holds a class which allows the user to inspect a the coldstore ### object attached to its parent. # GUI imports. from tkinter import * # Custom imports. from sibstructures import data_storage from sibstructures.numerals import index_to_label_column, \ index_to_label_row, \ index_to_label_layer # Imports import time from threading import Thread # Local constants. main_font = "Arial" title_pt = 60 subtitle_pt = 30 big_pt = 20 standard_pt = 15 diddy_pt = 10 standard_pad = 10 inner_pad = 5 tile_width = 15 details_height = 10 details_width = 30 grid_border = 5 spot_stack_width = tile_width+5 ############## # MAIN CLASS # ############## # The class in question. class CS_Viewer: def __init__(self, parent): self.parent = parent self.parent_window = self.parent.get_top() self.code = self.parent.coldstore.code self.parent.coldstore.reconstruct() self.max_max_layers = self.parent.coldstore.get_max_max_layers() self.layer = 0 self.top = Frame(self.parent_window) self.top_title = self.make_top_title() self.subtitle = Label(self.top, text="code="+self.code, font=(main_font, subtitle_pt, "bold")) self.main_container = Frame(self.top) self.spot_grid = Spot_Grid(self, self.main_container) self.box_details = Text(self.main_container, height=details_height, width=details_width, state=DISABLED) self.spot_stack = Spot_Stack(self.main_container, None, self.box_details) self.add_headings() self.arrange() # Ronseal. def make_top_title(self): result = Frame(self.top) text_lbl = Label(result, text="Proserpine", font=(main_font, title_pt, "bold")) arms_image = PhotoImage("icon.png") arms_lbl = Label(result, image=arms_image, height=200) arms_lbl.image = arms_image arms_lbl.pack() text_lbl.pack() return result # Add headings to the holster widgets. def add_headings(self): spot_grid_label = Label(self.main_container, text="Coldstore", font=(main_font, big_pt, "bold")) spot_stack_label = Label(self.main_container, text="Spot", font=(main_font, big_pt, "bold"), width=spot_stack_width) box_details_label = Label(self.main_container, text="Box", font=(main_font, big_pt, "bold")) spot_grid_label.grid(column=0, row=0) spot_stack_label.grid(column=1, row=0) box_details_label.grid(column=2, row=0) # Ronseal. def place_spot_stack(self): self.spot_stack.get_top().grid(column=1, row=1, padx=standard_pad, pady=standard_pad) # Arrange the object's elements. def arrange(self): self.top_title.pack() self.subtitle.pack() self.spot_grid.get_top().grid(column=0, row=1, sticky=N, padx=standard_pad, pady=standard_pad, ipadx=inner_pad, ipady=inner_pad) self.place_spot_stack() self.box_details.grid(column=2, row=1, sticky=N, padx=standard_pad, pady=standard_pad) self.main_container.pack() # Replace the spot stack widget. def replace_spot_stack(self): self.spot_stack.get_top().grid_forget() self.place_spot_stack() # Ronseal. def get_top(self): return self.top ################################ # HELPER CLASSES AND FUNCTIONS # ################################ # A class which holds the grid of spots. class Spot_Grid: def __init__(self, parent, parent_window): self.parent = parent self.parent_window = parent_window self.top = Frame(self.parent_window, borderwidth=grid_border, relief="solid") Thread(target=self.make_grid).start() # Fill the grid with boxes. def make_grid(self): cs = self.parent.parent.coldstore for i in range(len(cs.columns)): column_label = Label(self.top, text=str(index_to_label_column(i)), font=(main_font, big_pt, "bold")) column_label.grid(column=(i+1), row=0, padx=standard_pad) for j in range(len(cs.columns[0].spots)): if i == 0: row_label = Label(self.top, text=str(index_to_label_row(j)), font=(main_font, big_pt, "bold")) row_label.grid(column=0, row=(j+1), padx=standard_pad) tile = Spot_Tile(self, self.parent, cs.columns[i].spots[j], self.parent.box_details) tile.get_top().grid(column=(i+1), row=(j+1)) # Ronseal. def get_top(self): return self.top # A class which holds a clickable representation of a spot. class Spot_Tile: def __init__(self, parent, main_ref, spot_obj, box_details_ref): self.parent = parent self.main_ref = main_ref self.spot_obj = spot_obj self.box_details_ref = box_details_ref self.parent_window = self.parent.get_top() self.top = Frame(self.parent_window) Thread(target=self.make_filling).start() # Fill the object with either a tile or a label. def make_filling(self): if self.spot_obj.max_layers == 0: filling = Label(self.top, text="VOID", font=(main_font, diddy_pt), width=tile_width) elif self.spot_obj.layers() == 0: filling = Button(self.top, text="free", command=None, font=(main_font, diddy_pt, "italic"), width=tile_width, state=DISABLED) else: filling = self.make_filling_button() filling.pack() # Make the filling object if it is a button. def make_filling_button(self): result = Button(self.top, text=self.make_filling_button_text(), command=self.inspect, font=(main_font, diddy_pt), width=tile_width) return result # Make the text portion of the filling button. def make_filling_button_text(self): growers = set() varieties = set() fields = set() for box in self.spot_obj.boxes: current_epc = box.epc current_data = data_storage.fetch_most_recent_crop(current_epc) growers.add(current_data["grower"]) varieties.add(current_data["variety"]) fields.add(current_data["field"]) result = (set_to_string(growers)+"\n"+set_to_string(varieties)+"\n"+ set_to_string(fields)+"\n"+str(len(self.spot_obj.boxes))) return result # Inspect a given spot. def inspect(self): self.main_ref.spot_stack = Spot_Stack(self.main_ref.main_container, self.spot_obj, self.box_details_ref) self.main_ref.replace_spot_stack() # Ronseal. def get_top(self): return self.top # A class which holds a representation of the boxes on a given spot. class Spot_Stack: def __init__(self, parent_window, spot_obj, box_details_ref): self.parent_window = parent_window self.spot_obj = spot_obj self.box_details_ref = box_details_ref self.top = Frame(self.parent_window) if self.spot_obj is None: self.fill_empty() else: Thread(target=self.add_boxes).start() # "Fill in" the representation if the spot object is empty. def fill_empty(self): label = Label(self.top, text="Select spot", font=(main_font, standard_pt, "italic"), width=tile_width) label.pack() # Add representations of the spot's boxes. def add_boxes(self): no_of_boxes = len(self.spot_obj.boxes) if no_of_boxes == 0: empty_label = Label(self.top, text="Empty spot", font=(main_font, standard_pt, "italic"), width=tile_width) empty_label.pack() else: for i in range(no_of_boxes): backwards_index = (no_of_boxes-1)-i box_tile = Box_Tile(self.top, self.spot_obj.boxes[backwards_index], backwards_index, self.box_details_ref) box_tile.get_top().pack() # Ronseal. def get_top(self): return self.top # A class which holds a clickable representation of a box. class Box_Tile: def __init__(self, parent_window, box, index, box_details_ref): self.parent_window = parent_window self.box = box self.index = index self.box_details_ref = box_details_ref self.top = Frame(self.parent_window) self.make_filling() # Fill the object with either a tile or a label. def make_filling(self): label = Label(self.top, text=str(index_to_label_layer(self.index)), font=(main_font, standard_pt)) filling = Button(self.top, text=self.box.epc, command=self.inspect, font=(main_font, standard_pt), width=tile_width) label.grid(column=0, row=0, padx=standard_pad) filling.grid(column=1, row=0) # Ronseal. def get_top(self): return self.top # Inspect the data for this particular box in more detail. def inspect(self): text_to_insert = data_storage.fetch_most_recent_crop(self.box.epc) self.box_details_ref.config(state=NORMAL) self.box_details_ref.delete("1.0", END) self.box_details_ref.insert(END, text_to_insert) self.box_details_ref.config(state=DISABLED) # Turns a set into a string, with items thereof separated by commas. def set_to_string(the_set): result = "" the_list = list(the_set) # Reversal is necessary, since .add() seems to add items to the FRONT of # the set. the_list.reverse() for item in the_list: if the_list.index(item) == 0: result = item else: result = result+", "+item return result </code></pre> <p>This is the other file, which, with its fellow, makes up the whole program:</p> <pre class="lang-py prettyprint-override"><code>### This code holds a class which manages transitions between windows, and ### also oversees their interactions with the Coldstore object. # Imports. from pathlib import Path # GUI imports. from tkinter import * # Custom imports. from sibstructures.coldstore import Coldstore # Local imports. from cs_viewer import CS_Viewer # Constants. path_to_db = str(Path.home())+"/cseye/source/proserpine/data.db" ############## # MAIN CLASS # ############## # The class in question. class Comptroller: def __init__(self): self.coldstore = Coldstore(proserpine_mode=True, proserpine_path=path_to_db) self.gui = Tk() self.top = Frame(self.gui) self.window = CS_Viewer(self) self.arrange() # Return the top-level GUI object. def get_top(self): return self.top # Arrange the widgets. def arrange(self): self.window.get_top().pack() self.top.pack() # Run the "mainloop" method on the GUI object. def run_me(self): self.gui.title("Proserpine") self.gui.iconphoto(True, PhotoImage(file="icon.png")) self.gui.mainloop() ################### # RUN AND WRAP UP # ################### def run(): comptroller = Comptroller() comptroller.run_me() if __name__ == "__main__": run() </code></pre>
<p>The argument to <code>PhotoImage("...")</code> is wrong. It should be <code>PhotoImage(file="...")</code>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: solving for a ratio while eliminating specific variables in a set of linear equations<p>I am still having a problem, a different one than my previous <a href="https://stackoverflow.com/questions/71074627/symbolic-solution-of-linear-equations-using-sympy/71080015#71080015">post</a>.</p> <p>Basically I have [5x5][5x1]=[0] and would like to have the symbolic expression of the solution.</p> <p>Here is my code.</p> <pre><code>from sympy import symbols, solve gm1, gm2, gm4 = symbols(['gm1', 'gm2', 'gm4']) gds1, gds2, gds3, gds4, gds5 = symbols(['gds1', 'gds2', 'gds3', 'gds4', 'gds5']) s = symbols('s') Cd, CF , Cin, Ct = symbols(['Cd', 'CF', 'Cin', 'Ct']) K = symbols('K') vb, vc, ve, vout, iin = symbols(['vb', 'vc', 've', 'vout', 'iin']) sol = solve([-(gds1+gds3+(s*Cd))*vb + (gm1+gds1)*ve + -gm1*vout, \ -gm4*vb + (gds4-gds2-(s*Cin)-(s*CF))*vc + (gds2+gm2)*ve + s*CF*vout + iin, \ gds1*vb + gds2*vc + (-(s*Ct)-gds5-gds1-gm1-gm2-gds2)*ve + gm1*vout, \ K*vc + vout, 0], [vout]) print(sol) </code></pre> <p>I am expecting</p> <pre><code>vout/iin = f(gm1, gm2, gm4, gds1, gds2, gds3, gds4, gds5, s, Cd, CF , Cin, Ct, K) </code></pre> <p>In other words, <code>vb, vc, ve</code> are <strong>eliminated</strong>.</p> <p>Is there any specific command to do that?</p>
<p>The problem is that you have 4 equations and you've only specified one unknown (vout). The system is generically unsolvable for most values of <code>vb, vc, ve</code> so asking to solve only for <code>vout</code> leads to no solution (in the generic case).</p> <p>Ask to solve for <code>vout, vb, vc, ve</code> as 4 unknowns for the 4 equations and you can get a solution for all 4:</p> <pre><code>linsolve(eqs, [vout, vb, vc, ve]) </code></pre> <p>(The output is long so I have omitted it)</p> <p>I'm using linsolve since the equations are linear although solve will also work.</p> <p>It's not entirely clear what you want but some variation of the above should do it. You said you wanted vout and vin in terms of the other symbols but with vb, vc and ve eliminated. That would require 5 independent equations but since your 5th equation is just 0 you don't have that.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Calling python script with config file from node.js as a child process<p>I am calling a python script as a child process from node.js, the python script uses a config.ini file for some reason the python script does not call the config file when its called as a child process, but when I launch the python script 'using python script.py' it works, and when a replace the value from the config.ini file with an actual value inside the script.py it works also, how do I fix this?</p> <pre><code>from configparser import ConfigParser import sys import re import json file = 'config.ini' config = ConfigParser() config.read(file) rCARD_NUMBER = r&quot;number:\s(\d+\*+\d+).*?&quot; regex = rCARD_NUMBER*int(config['atm']['bCARD_NUMBER']) # re.DOTALL to match any characters including newline input = open(sys.argv[1], &quot;r&quot;) # print(input.read()) matches = re.findall(regex, input.read(), re.DOTALL) print(json.dumps(matches)) </code></pre> <p>config.ini</p> <pre><code>[atm] bCARD_NUMBER = 1 </code></pre> <p>Here is how I call the python script as a child process from node :</p> <pre><code> var largeDataSet = []; // spawn new child process to call the python script // pass the python script the uploaded file as an argument const python = spawn(&quot;python&quot;, [ &quot;./config/script.py&quot;, req.file.path, ]); // collect data from script python.stdout.on(&quot;data&quot;, function (data) { console.log(&quot;Pipe data from python script ...&quot;); largeDataSet.push(data); }); </code></pre>
<p>What seems to be happening is that <code>ConfigParser().read(file)</code> reads based off of the current working directory, which would be where the JavaScript file is, not inside the <code>config</code> folder.</p> <p>You can get around that by using <code>pathlib</code> (pre-installed, core library)</p> <pre class="lang-py prettyprint-override"><code>from configparser import ConfigParser from pathlib import Path import sys import re import json file = 'config.ini' config = ConfigParser() config.read((Path(__file__).parent / &quot;config.ini&quot;).absolute()) rCARD_NUMBER = r&quot;number:\s(\d+\*+\d+).*?&quot; regex = rCARD_NUMBER*int(config['atm']['bCARD_NUMBER']) # re.DOTALL to match any characters including newline input = open(sys.argv[1], &quot;r&quot;) # print(input.read()) matches = re.findall(regex, input.read(), re.DOTALL) print(json.dumps(matches)) </code></pre> <p>Your JavaScript and <code>config.ini</code> file should remain the same.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Aging Clock running python script<p>Hi Stack Overflow Community,</p> <p>I have very little experience with Python, but want to run the following script which I found on Github: <a href="https://github.com/Meyer-DH/AgingClock" rel="nofollow noreferrer">https://github.com/Meyer-DH/AgingClock</a></p> <p>It is an aging predictor for RNA-Seq data, which I want to apply on my own dataset. To test out the script I first wanted to just use the example given on github. However, I already failed at running the script even with this data.</p> <p>Here is what I got:</p> <pre><code>import numpy as np import pandas as pd cd /Users/.... df = pd.read_csv('GSE65765_CPM.csv', sep='\t') </code></pre> <p>Now calling the data frame I have imported works and I want to apply the first function to make it binary:</p> <pre><code>make_binary(df, filter_genes='WBG') </code></pre> <p>The return when I call the function however looks like this: <a href="https://i.stack.imgur.com/arpjN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/arpjN.png" alt="enter image description here" /></a></p> <p>So instead of having it binarized I only receive the column with the gene name ID's. The question is probably very silly, but perhaps someone can help me with it.</p> <p>Thank you in advance!</p>
<p>tl;dr: You're doing it wrong. ;-)</p> <p>The <code>test_predict()</code> function already knows the proper calling sequence. Recommend you follow its lead.</p> <p>Correct input dataframe should look like this:</p> <pre><code>(Pdb) l 13 :return: A binarized copy of the original data without meta-information 14 ''' 15 breakpoint() 16 -&gt; df_bin = df.copy() 17 df_bin = df_bin.filter(regex=filter_genes) # get the gene columns 18 df_bin[df_bin == 0] = np.nan # mask 0-genes that skew the median (Pdb) p df WBGene00197333 WBGene00198386 ... WBGene00010967 WBGene00014473 SRR1793993 0.0 0.0 ... 78.117815 0.000000 SRR1793991 0.0 0.0 ... 59.618577 0.000000 SRR1793994 0.0 0.0 ... 86.492735 0.016913 SRR1793992 0.0 0.0 ... 76.459508 0.000000 [4 rows x 46755 columns] (Pdb) </code></pre> <p>OTOH presenting an input dataframe of improper shape will yield the zero-column output that you see. This transpose is an important step:</p> <p><a href="https://github.com/Meyer-DH/AgingClock/blob/b6980/src/biological_age_prediction.py#L72" rel="nofollow noreferrer">https://github.com/Meyer-DH/AgingClock/blob/b6980/src/biological_age_prediction.py#L72</a></p> <pre><code> cpm_df = cpm_df.T </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas Multiindex subtract based on only two index level matchings<p>Say I have a Pandas multi-index data frame with 3 indices:</p> <pre><code>import pandas as pd import numpy as np arrays = [['UK', 'UK', 'US', 'FR'], ['Firm1', 'Firm1', 'Firm2', 'Firm1'], ['Andy', 'Peter', 'Peter', 'Andy']] idx = pd.MultiIndex.from_arrays(arrays, names = ('Country', 'Firm', 'Responsible')) df_3idx = pd.DataFrame(np.random.randn(4,3), index = idx) df_3idx 0 1 2 Country Firm Responsible UK Firm1 Andy 0.237655 2.049636 0.480805 Peter 1.135344 0.745616 -0.577377 US Firm2 Peter 0.034786 -0.278936 0.877142 FR Firm1 Andy 0.048224 1.763329 -1.597279 </code></pre> <p>I have furthermore another pd.dataframe consisting of unique combinations of multi-index-level 1 and 2 from the above data:</p> <pre><code>arrays = [['UK', 'US', 'FR'], ['Firm1', 'Firm2', 'Firm1']] idx = pd.MultiIndex.from_arrays(arrays, names = ('Country', 'Firm')) df_2idx = pd.DataFrame(np.random.randn(3,1), index = idx) df_2idx 0 Country Firm UK Firm1 -0.103828 US Firm2 0.096192 FR Firm1 -0.686631 </code></pre> <p>I want to subtract the values from <code>df_3idx</code> by the corresponding value in <code>df_2idx</code>, so, for instance, I want to subtract from every value of the first two rows the value -0.103828, as index 1 and 2 from both dataframes match.</p> <p>Does anybody know how to do this? I figured I could simply unstack the first dataframe and then subtract, but I am getting an error message.</p> <pre><code>df_3idx.unstack('Responsible').sub(df_2idx, axis=0) ValueError: cannot join with no overlapping index names </code></pre> <p>Unstacking might anyway not be a preferable solution as my data is very big and unstacking might take a lot of time.</p> <p>I would appreciate any help. Many thanks in advance!</p>
<p><a href="https://stackoverflow.com/q/53217607/2336654">related question but not focused on <code>MultiIndex</code></a></p> <p>However, the answer doesn't really care. The <code>sub</code> method will align on the matching index levels.</p> <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>pd.DataFrame.sub</code></a> with parameter <code>axis=0</code></p> <pre><code>df_3idx.sub(df_2idx[0], axis=0) 0 1 2 Country Firm Responsible FR Firm1 Andy 0.027800 3.316148 0.804833 UK Firm1 Andy -2.009797 -1.830799 -0.417737 Peter -1.174544 0.644006 -1.150073 US Firm2 Peter -2.211121 -3.825443 -4.391965 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: PyQt5 all button signals/events?<p>The signal for MOUSE1 on the button is widget.clicked, what are the ones for MOTION and MOUSE2? Also if anyone knows a site with all signals listed it would really help</p> <pre><code>import sys, pyautogui from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def pressed_mouse2(): pass def window(): app = QApplication(sys.argv) root = QMainWindow() root.setGeometry(200, 200, 500, 500) root.setWindowTitle('Test') root.setWindowFlags(QtCore.Qt.FramelessWindowHint) root.setAttribute(Qt.WA_TranslucentBackground) button = QtWidgets.QPushButton(root) #i need here to signal when user has pressed on MOUSE2 on the button button.clicked.connect(clicked) button.move(50,50) root.show() sys.exit(app.exec_()) window() </code></pre>
<p>You just need to connect the button's <code>clicked</code> signal to your function. </p> <pre><code>button.clicked.connect(pressed_mouse2) </code></pre> <p>Now when you click the button you can execute any code here:</p> <pre><code>def pressed_mouse2(): print('Button clicked') </code></pre> <p>There are many kinds of widgets, each with different signals. You can find them in the Qt documentation. <a href="https://doc.qt.io/qt-5/qabstractbutton.html#signals" rel="nofollow noreferrer">Here</a> are the signals for QAbstractButton, which is inherited by QPushButton. </p> <p>There is no predefined signal for a right click on the button, but you can subclass QPushButton and emit your own signal in the <code>mousePressEvent()</code>.</p> <pre><code>class Button(QPushButton): right_clicked = pyqtSignal() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def mousePressEvent(self, event): super().mousePressEvent(event) if event.button() == Qt.RightButton: self.right_clicked.emit() </code></pre> <p>And it will respond with:</p> <pre><code>button = Button(root) button.right_clicked.connect(pressed_mouse2) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: python celery invalid value for -A unable to load application<p>I have a following project directory:</p> <pre><code>azima: __init.py main.py tasks.py </code></pre> <p>task.py</p> <pre><code>from .main import app @app.task def add(x, y): return x + y @app.task def mul(x, y): return x * y @app.task def xsum(numbers): return sum(numbers) </code></pre> <p>main.py</p> <pre><code>from celery import Celery app = Celery('azima', backend='redis://localhost:6379/0', broker='redis://localhost:6379/0', include=['azima.tasks']) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start() </code></pre> <p>When I run a command to initialize celery workers, I get this error:</p> <pre><code>(azima_venv) brightseid@darkseid:~$ celery -A azima worker -l INFO Usage: celery [OPTIONS] COMMAND [ARGS]... Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'azima' has no attribute 'celery' </code></pre> <p>But when I rename <code>main.py</code> to <code>celery.py</code> as it was earlier there's no issue.</p> <p>What am I missing here?</p>
<p>There are two approaches</p> <ol> <li>import your <code>app</code> to <code>azima/__init__.py</code></li> </ol> <pre class="lang-py prettyprint-override"><code>from azima.main import app celery = app # you can omit this line </code></pre> <p>You can omit the last line, celery will recognize the celery app from the import. Then you call <code>celery -A azima worker -l INFO</code></p> <ol start="2"> <li>Call you application like <code>celery -A azima.main worker -l INFO</code></li> </ol>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: StaleElementReferenceException: Message: stale element reference: element is not attached to the page document error when using Selenium and Python<p>I'm writing a selenium program in python to get links from a website, it runs the first time but when I re-run it, it opens the website in browser properly then it gives an error</p> <p>This is my code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service headers = { &quot;User-Agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582&quot;, &quot;Accept-Language&quot;: &quot;fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3&quot;, &quot;Connection&quot;: &quot;keep-alive&quot;, &quot;Accept-Encoding&quot;: &quot;gzip, deflate, br&quot;, } edge_driver = './msedgedriver.exe' s = Service( edge_driver ) browser = webdriver.Edge( service=s ) browser.get( &quot;https://www.jumia.ug/always/&quot; ) all_links = browser.find_elements( By.CLASS_NAME, &quot;core&quot; ) working_links = [] for l in all_links: if l.get_attribute( &quot;href&quot; ) is not None: working_links.append(l.get_attribute('href')) print(working_links) </code></pre> <p>this is the error i got after running it every other time</p> <pre><code>C:\Users\eliHeist\PycharmProjects\webscraping\venv\Scripts\python.exe C:/Users/eliHeist/PycharmProjects/webscraping/getlinks.py Traceback (most recent call last): File &quot;C:/Users/eliHeist/PycharmProjects/webscraping/getlinks.py&quot;, line 34, in &lt;module&gt; if l.get_attribute( &quot;href&quot; ) is not None: File &quot;C:\Users\eliHeist\PycharmProjects\webscraping\venv\lib\site-packages\selenium\webdriver\remote\webelement.py&quot;, line 155, in get_attribute attribute_value = self.parent.execute_script( File &quot;C:\Users\eliHeist\PycharmProjects\webscraping\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py&quot;, line 878, in execute_script return self.execute(command, { File &quot;C:\Users\eliHeist\PycharmProjects\webscraping\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py&quot;, line 424, in execute self.error_handler.check_response(response) File &quot;C:\Users\eliHeist\PycharmProjects\webscraping\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py&quot;, line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document (Session info: MicrosoftEdge=96.0.1054.57) Stacktrace: Backtrace: Microsoft::Applications::Events::ILogConfiguration::ILogConfiguration [0x00007FF60587CB62+56946] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6054AA597+949863] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6054AD788+962648] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6054AE3EA+965818] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF605516D9F+1394287] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF605501546+1306134] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF605515D5D+1390125] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6055013BF+1305743] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6054D6AA9+1131385] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6054D7B8F+1135711] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF60556C2E5+1743797] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF60556A771+1736769] Microsoft::Applications::Events::EventProperty::EventProperty [0x00007FF60574B519+2521] Microsoft::Applications::Events::EventProperty::to_string [0x00007FF6055420AE+1571198] Microsoft::Applications::Events::ILogConfiguration::ILogConfiguration [0x00007FF60587576C+27260] Microsoft::Applications::Events::ILogConfiguration::ILogConfiguration [0x00007FF6058750E4+25588] Microsoft::Applications::Events::ILogConfiguration::ILogConfiguration [0x00007FF605874F36+25158] Microsoft::Applications::Events::EventProperties::GetName [0x00007FF6057D02DC+211724] BaseThreadInitThunk [0x00007FFF89E254E0+16] RtlUserThreadStart [0x00007FFF8AF2485B+43] Process finished with exit code 1 </code></pre> <p>What should I be changing or not doing, the page does not refresh at all?</p>
<p>To print the value of the <em>href</em> attribute you have to induce <a href="https://stackoverflow.com/questions/49775502/webdriverwait-not-working-as-expected/49775808#49775808">WebDriverWait</a> for the <a href="https://stackoverflow.com/questions/21631116/python-selenium-wait-for-several-elements-to-load/64770041#64770041"><em>visibility_of_all_elements_located()</em></a> and you can use either of the following <a href="https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890">Locator Strategies</a>:</p> <ul> <li><p>Using <em>CSS_SELECTOR</em>:</p> <pre><code>driver.get(&quot;https://www.jumia.ug/always/&quot;) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, &quot;button[aria-label='newsletter_popup_close-cta']&quot;))).click() print([my_elem.get_attribute(&quot;href&quot;) for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, &quot;a.core[data-brand='Always'][href]&quot;)))]) </code></pre> </li> <li><p>Using <em>XPATH</em>:</p> <pre><code>driver.get(&quot;https://www.jumia.ug/always/&quot;) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, &quot;//button[@aria-label='newsletter_popup_close-cta']&quot;))).click() print([my_elem.get_attribute(&quot;href&quot;) for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, &quot;//a[@class='core' and @data-brand='Always'][@href]&quot;)))]) </code></pre> </li> <li><p>Console Output:</p> <pre><code>['https://www.jumia.ug/always-maxi-long-7s-15736010.html', 'https://www.jumia.ug/always-roxanne-maxi-duo-long-16s-15736015.html', 'https://www.jumia.ug/always-ultra-long-s3-8s-15736020.html', 'https://www.jumia.ug/always-roxanne-dreamz-maxi-ex-long-8s-15736016.html', 'https://www.jumia.ug/stainless-steel-thermos-flask-3-litres-silver-always-mpg51110.html', 'https://www.jumia.ug/always-roxanne-dreamz-maxi-ex-long-16s-15736017.html', 'https://www.jumia.ug/always-ultra-new-12s-vp-sup-pr-african-15736026.html', 'https://www.jumia.ug/travel-vacuum-thermo-cup-450ml-red-always-mpg59272.html', 'https://www.jumia.ug/pressing-flask-3litres-silver-always-mpg49765.html', 'https://www.jumia.ug/stainless-steel-travel-mug-silver-always-mpg69987.html', 'https://www.jumia.ug/unbreakable-2.5-litres-vaccum-flask-silver-always-mpg54323.html', 'https://www.jumia.ug/stainless-steel-vacuum-flask-pressing-3.5l-silver-always-mpg56188.html', 'https://www.jumia.ug/always-dailies-flexistyle-slim-panty-liners-breathable-flexible-with-fresh-scent-pack-of-26-10968170.html', 'https://www.jumia.ug/stainless-steel-vacuum-flask-500ml-black-always-mpg48945.html', 'https://www.jumia.ug/always-flask-pressing-colour-silver-16418821.html', 'https://www.jumia.ug/vaccum-travel-flask-450ml-blue-always-mpg73899.html', 'https://www.jumia.ug/500mls-vacuum-hot-cold-bottle-flask-sliver-always-mpg54381.html', 'https://www.jumia.ug/always-ultra-lw-14s-vp-sup-pr-african-15736025.html', 'https://www.jumia.ug/pressing-2.0-litres-unbreakable-vaccum-jar-flask-stainless-steel-always-mpg56170.html', 'https://www.jumia.ug/stainless-steel-travel-cap-black-always-mpg65745.html', 'https://www.jumia.ug/always-stainless-steel-travel-mug-0.48l-navy-blue-8224366.html', 'https://www.jumia.ug/always-thermal-flask-cup-silver-black-20572534.html', 'https://www.jumia.ug/stainless-vacuum-travel-mug-450ml-black-always-mpg56189.html', 'https://www.jumia.ug/0.5l-insulated-stainless-steel-travel-mug-colour-varies-always-mpg73677.html', 'https://www.jumia.ug/stainless-steel-travel-mug-0.5l-gold-always-mpg67096.html', 'https://www.jumia.ug/ultra-platinum-long-7-pads-always-mpg59273.html', 'https://www.jumia.ug/life-travel-flask-450ml-red-always-mpg72907.html', 'https://www.jumia.ug/always-xtra-protection-feminine-panty-liners-extra-long-92-pieces-us-4766946.html', 'https://www.jumia.ug/always-zzz-overnight-pads-for-women-size-6-with-wings-for-worry-free-nights-20ct-14336082.html', 'https://www.jumia.ug/portable-vacuum-thermos-flask-bottle-0.5ltr-silver-always-mpg48676.html', 'https://www.jumia.ug/stainless-steel-vacuum-flask-700ml-silver-always-mpg59271.html', 'https://www.jumia.ug/always-vacuum-hot-cold-bottle-flask-500mls-always-mpg46382.html', 'https://www.jumia.ug/stainlesss-steel-side-pressing-vaccum-flask-3litres-silver-always-mpg65748.html', 'https://www.jumia.ug/always-stainless-steel-thermos-flask-jug-silver-always-mpg42506.html', 'https://www.jumia.ug/always-450ml-thermal-flask-maroon-5494832.html', 'https://www.jumia.ug/always-food-flask-18949481.html', 'https://www.jumia.ug/always-portable-vacuum-1.0ltr-thermos-flask-bottle-silver-8032566.html', 'https://www.jumia.ug/always-stainless-vaccum-flask-3-litre-silver-black-always-mpg46820.html', 'https://www.jumia.ug/stainless-steel-vaccum-flask-3.5l-silver-always-mpg48943.html', 'https://www.jumia.ug/always-stainless-steel-vacuum-flask-silver-5196899.html'] </code></pre> </li> <li><p><strong>Note</strong> : You have to add the following imports :</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC </code></pre> </li> </ul>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to transform this repeated code in into a function<p>I have a bit of repeated code. I'm trying to check if each sentence in a list of sentences contains a certain word at the beginning. If not, I want it do something and then print the values in a dictionary. Else, I want it to do something else and then print another dictionary.</p> <p>But I can't figure out how to transform the repeated code in question into a function because I need a variable at the beginning of the first loop inside the repeated code.</p> <p>Here's my code so far:</p> <pre><code>if not audio_keyword_dictionary: for index, sentence in enumerate(sentences): keyword_set_inside_dict = set() for each_keyword in complete_keyword_list: if each_keyword in sentence: keyword_set_inside_dict.add(each_keyword) keyword_dict[sentence] = keyword_set_inside_dict for key, value in keyword_dict.items(): print(f'{value} - {key}\n') else: for index, sentence in enumerate(sentences): keyword_set_inside_dict = set() for each_keyword in complete_keyword_list: if each_keyword in sentence: keyword_set_inside_dict.add(each_keyword) keyword_dict[sentence] = keyword_set_inside_dict for each_value in audio_keyword_dictionary.values(): if each_value in sentences[index - 1] and sentences[index - 1] != '': audio_nested_dictionary[each_value] = keyword_dict for k, v in audio_nested_dictionary.items(): for key, value in v.items(): print(f'{k} - {value} {key}\n') </code></pre> <p>Here's the function I created:</p> <pre><code>def iterate_sentences(sentences, keyword_list): keyword_dict = dict() for index, sentence in enumerate(sentences): keyword_list_inside_dict = list() for each_keyword in complete_keyword_list: if each_keyword in sentence: keyword_list_inside_dict.append(each_keyword) keyword_set = set(keyword_list_inside_dict) keyword_dict[sentence] = keyword_set return keyword_dict </code></pre> <p>Bu how can I I use it if I need 'index' outside the repeated part?</p> <p>In this part, to be precise, right after where the repeated part ends:</p> <pre><code> for each_value in audio_keyword_dictionary.values(): if each_value in sentences[index - 1] and sentences[index - 1] != '': audio_nested_dictionary[each_value] = keyword_dict </code></pre> <p>Not sure if it needs to be said, but sentence is a list of sentences that follows a pattern. It begins with a string that contains <code>audio{positive_number_here}</code>, followed by another string with actual meaning, followed by another <code>audio{positive_number_here + 1}</code> and so on, alternating between the two. The list ends with a string with meaning.</p>
<p>You don't need a function to get rid of the duplication. Just move the <code>if</code> statement.</p> <pre><code>for index, sentence in enumerate(sentences): keyword_set_inside_dict = set() for each_keyword in complete_keyword_list: if each_keyword in sentence: keyword_set_inside_dict.add(each_keyword) keyword_dict[sentence] = keyword_set_inside_dict if audio_keyword_dictionary: for each_value in audio_keyword_dictionary.values(): if each_value in sentences[index - 1] and sentences[index - 1] != '': audio_nested_dictionary[each_value] = keyword_dict if audio_keyword_dictionary: for k, v in audio_nested_dictionary.items(): for key, value in v.items(): print(f'{k} - {value} {key}\n') else: for key, value in keyword_dict.items(): print(f'{value} - {key}\n') </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Get number of files in directory with pathlib python<p>I have a two directories with csv files. Both should be of the same length, as I am looping over both of them with zip. Therefor I have a check to see if the length of them are the same. The code looks like this:</p> <pre><code>from pathlib import Path def check(): base = Path('home/user/src/log').rglob('*.csv') test = Path('home/user/src/log').rglob('*.csv') print(list(base)) if len(list(base)) != len(list(test): print(f&quot;Wrong number of files in {str(base)} and {str(test)}&quot;) return -1 for base, test in zip(base, test): x = pd.read_csv(base) y = pd.read_csv(test) print(x) print(y) if __name__ == '__main__': check() </code></pre> <p>The <code>list(base)</code> gives the list of files, but it also silent kills the program. So if I have <code>print(list(base))</code> it will print the files in base and then the program terminates. The <code>str(base)</code> does also not work, but this is because I havent found a way to print out the directory path without the program terminating afterwards. Any tips to get the length of the list and print the directory without killing the program.</p> <p>Note: I now I can use 'os' but would like to use pathlib if possible</p>
<p><code>rglob</code> returns a generator. Calling <code>list</code> on the generator consumes all items.</p> <p>You could however convert it to a list initially and then keep working with the list afterwards:</p> <pre><code>from pathlib import Path def check(): base = list(Path('home/user/src/log').rglob('*.csv')) test = list(Path('home/user/src/log').rglob('*.csv')) print(base) if len(base) != len(test): print(f&quot;Wrong number of files in {str(base)} and {str(test)}&quot;) return -1 for base, test in zip(base, test): x = pd.read_csv(base) y = pd.read_csv(test) print(x) print(y) if __name__ == '__main__': check() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How can I assign data from a list to pandas DataFrame?<p>I created a df with different courses, and list with prices. What I need is to assign prices to all courses in dataframe - for example, all English courses in df should have first price from price list, all finance courses should have second price from price list etc. (order doesn't matter). Any suggestions?</p> <pre><code>import random import pandas as pd import numpy as np courses_list = ['Programming', 'Data Science', 'Data Analytics', 'Business Management', 'English', 'Design', 'Finance'] courses = [] for i in range(500): courses.append(random.choice(courses_list)) price = np.random.randint(50000, 100000, 7) name = np.arange(500) df = pd.DataFrame({'used_id':name, 'course_name':courses}) df </code></pre>
<p>Use <a href="https://www.programiz.com/python-programming/dictionary-comprehension" rel="nofollow noreferrer"><code>dict comprehension</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a>:</p> <pre><code># Create a dict with key as course_name and value as price In [2358]: course_price = {i:price[c] for c, i in enumerate(courses_list)} # Use `map` function to map the price for each course from dict to df In [2360]: df['price'] = df.course_name.map(course_price) In [2361]: df Out[2361]: used_id course_name price 0 0 Business Management 56022 1 1 Data Analytics 85224 2 2 Programming 64843 3 3 Business Management 56022 4 4 Data Science 65005 .. ... ... ... 495 495 Business Management 56022 496 496 Data Analytics 85224 497 497 English 95012 498 498 Business Management 56022 499 499 Data Analytics 85224 [500 rows x 3 columns] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Transform schedule to comprehensive report with Python<p>I'm trying to turn a schedule with the following format into a report format. </p> <p>Currently the data is stored as follows:</p> <pre><code>Person Name Jun 1 Jun 2 Jun 3 Jun 4 Jun 5 Jun 6 Jun 7 Jun 8 Jun 9 Jun 10 ... John Smith X X X X O O O X X X ... Aaron Roberts O O X X X X O O O O ... Jess Lewis O O O O X X X X X X ... Edgar Blue X X X X X O O O O X ... Lara Irvin X X O O O O X X X X ... </code></pre> <p>The X represent days that they're "ON" and the O represent days that they're off.</p> <p>What I want is to run a python script that summarizes the schedule in a report of this format:</p> <pre><code>Person Name From: To: John Smith Jun 1 Jun 4 John Smith Jun 8 Jun 10 Aaron Roberts Jun 3 Jun 6 Jess Lewis Jun 5 Jun 10 Edgar Blue Jun 1 Jun 5 Edgar Blue Jun 10 Jun 13 Lara Irvin Jun 1 Jun 2 Lara Irvin Jun 7 Jun 10 </code></pre> <p>What I've tried is to create a unique names list</p> <pre><code>names = ["John Smith", "Aaron Roberts", "Jess Lewis", "Edgar Blue", "Lara Irvin"] </code></pre> <p>And then do </p> <pre><code>for name in names: df.iloc["Person Name"] == name </code></pre> <p>Then I'm not sure how to proceed, I'm trying to look if the i position is an X or an O, then look if the i-1 position is an X or an O</p> <p>Then...</p> <pre><code>if i == "X" &amp;&amp; i-1 == "O" </code></pre> <p>Populate that header date in the other table's "From:" column</p> <p>and...</p> <pre><code>if == "O" &amp;&amp; i-1 == "X" </code></pre> <p>Populate that header date in the other table's "To:" column</p> <p>Then repeat the same process using a nested for loop across all "Person Name" and all dates.</p> <p>Thank you in advance for any help.</p>
<p>This will need the <code>cumsum</code> create the subgroup then we stack , <code>groupby</code> with <code>agg</code> </p> <pre><code>df=df.set_index('PersonName') s1=df.eq('O').cumsum(1).stack().reset_index() s=s1[df.stack().ne('O').values].groupby(['PersonName',0])['level_1'].agg(['first','last']).reset_index(level=1,drop=True) s first last PersonName AaronRoberts Jun3 Jun6 EdgarBlue Jun1 Jun5 EdgarBlue Jun10 Jun10 JessLewis Jun5 Jun10 JohnSmith Jun1 Jun4 JohnSmith Jun8 Jun10 LaraIrvin Jun1 Jun2 LaraIrvin Jun7 Jun10 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Appending a values of a list to a list of lists<p>I have a list <code>list1 = [1, 2, 3]</code> and I would like to append it to another list, such that I get <code>list_of_lists = [[1, 2, 3]]</code>. I would like then to append more and get something like <code>list_of_lists = [[1, 2, 3], [4, 5, 6]]</code>.</p> <p>My problem is that I am doing this in a loop and I am using the same list to be appended many times with different values, however when I clear the list with <code>list1.clear()</code>, then also the values I appended are cleared. Here the full code</p> <pre><code>list_of_lists = [] list1 = [1, 2, 3] list_of_lists.append(list1) list1.clear() print(list_of_lists) </code></pre> <p>the output is [[]]. How should I fix this? Thanks</p>
<p>Everything is fine, the only thing you would need to change is when you add list1 to list_of_lists add it as such:</p> <pre><code>list_of_lists.append(list(list1)) </code></pre> <p>Everything should work after that.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How do you properly implement gravity to a free floating space object and some sort of friction when thrusting in opposite direction<p>I am trying to program movement that is basically like Asteroids where once UP button is pressed you accelerate to a certain speed and then because in space you don't stop and can only slow down by thrusting in opposite direction. On top of that, I would like gravity to be pulling you towards the bottom of the screen. I have this accomplished for the most part but the issue I have is:</p> <ol> <li>When I turn around and thrust opposite direction, it doesn't slow down first going backwards before starting to move forwards again, it just shoots off in opposite direction at full speed</li> </ol> <p>Any suggestions of how to handle this and make movement smoother in general?</p> <pre><code>import pygame as pg import os vec = pg.math.Vector2 TITLE = &quot;GRAVITAR&quot; WIDTH = 800 HEIGHT = 600 FPS = 60 GREY = (211, 211, 211) # Player properties ROCKET_SHIP = 'Images/Rocket_Ship.png' # &lt;a href='https://pngtree.com/so/spaceship-clipart'&gt;spaceship # clipart png from pngtree.com&lt;/a&gt; PLAYER_ACC = 0.5 PLAYER_FRICTION = -0.00 PLAYER_GRAV = 0.1 PLAYER_ROT_SPEED = 200 PLAYER_SPEED = 5 class Player(pg.sprite.Sprite): def __init__(self, game, x, y): pg.sprite.Sprite.__init__(self) self.game = game self.image = game.rocket_ship self.rect = self.image.get_rect() self.rect.center = (x, y) self.vel = vec(0, 0) self.pos = vec(x, y) self.rot = 0 def get_keys(self): self.rot_speed = 0 self.acc = vec(0, PLAYER_GRAV) keys = pg.key.get_pressed() if keys[pg.K_LEFT]: self.rot_speed = PLAYER_ROT_SPEED if keys[pg.K_RIGHT]: self.rot_speed = -PLAYER_ROT_SPEED if keys[pg.K_UP]: self.vel = vec(PLAYER_SPEED, 0).rotate(-self.rot) if keys[pg.K_SPACE]: self.shoot() self.acc += self.vel * PLAYER_FRICTION self.vel += self.acc if self.vel[1] &gt;= 2: self.vel[1] = 2 self.pos += self.vel + 0.5 * self.acc def shoot(self): pass def update(self): self.get_keys() self.rot = (self.rot + self.rot_speed * self.game.dt) % 360 self.image = pg.transform.rotate(self.game.rocket_ship, self.rot - 90) self.rect = self.image.get_rect() self.rect.center = self.pos self.pos += self.vel * self.game.dt if self.pos.x &gt; WIDTH: self.pos.x = 0 if self.pos.x &lt; 0: self.pos.x = WIDTH if self.pos.y &gt; HEIGHT: self.pos.y = 0 if self.pos.y &lt; 0: self.pos.y = HEIGHT class Game: def __init__(self): # Initialize pygame and create window pg.init() pg.mixer.init() pg.key.set_repeat(10, 50) os.environ['SDL_VIDEO_WINDOW_POS'] = '568, 101' self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption(TITLE) self.clock = pg.time.Clock() self.running = True self.load_data() def load_data(self): self.rocket_ship = pg.image.load(ROCKET_SHIP).convert_alpha() self.rocket_ship = pg.transform.scale(self.rocket_ship, (32, 32)) def new(self): # Start a new game self.all_sprites = pg.sprite.Group() self.player = Player(self, WIDTH / 2, HEIGHT / 4) self.all_sprites.add(self.player) self.run() def run(self): # Game loop self.playing = True while self.playing: self.dt = self.clock.tick(FPS) / 1000.0 self.events() self.update() self.draw() def update(self): # Game loop update self.all_sprites.update() def events(self): # Game loop events for event in pg.event.get(): if event.type == pg.QUIT: if self.playing: self.playing = False self.running = False def draw(self): # Game loop draw pg.display.set_caption(&quot;{:.2f}&quot;.format(self.clock.get_fps())) self.screen.fill(GREY) self.all_sprites.draw(self.screen) # After drawing everything, flip display pg.display.flip() def show_start_screen(self): pass def show_go_screen(self): pass g = Game() g.show_start_screen() while g.running: g.new() g.show_go_screen() pg.quit() </code></pre>
<p>When you press <kbd>UP</kbd> you don't have to change the speed, but you have to set the acceleration:</p> <p><s><code>self.vel = vec(PLAYER_SPEED, 0).rotate(-self.rot)</code></s></p> <pre class="lang-py prettyprint-override"><code>self.acc += vec(PLAYER_ACC, 0).rotate(-self.rot) </code></pre> <p>Add the acceleration to the velocity:</p> <pre class="lang-py prettyprint-override"><code>self.vel += self.acc </code></pre> <p>I recommend limiting the maximum. However, I recommend doing this separately for each direction:</p> <pre class="lang-py prettyprint-override"><code>max_vel = 2 self.vel[0] = max(-max_vel, min(max_vel, self.vel[0])) self.vel[1] = max(-max_vel, min(max_vel, self.vel[1])) </code></pre> <p>Apply this to the method <code>get_keys</code>:</p> <pre class="lang-py prettyprint-override"><code>class Player(pg.sprite.Sprite): # [...] def get_keys(self): self.rot_speed = 0 self.acc = vec(0, PLAYER_GRAV) keys = pg.key.get_pressed() if keys[pg.K_LEFT]: self.rot_speed = PLAYER_ROT_SPEED if keys[pg.K_RIGHT]: self.rot_speed = -PLAYER_ROT_SPEED if keys[pg.K_UP]: self.acc += vec(PLAYER_ACC, 0).rotate(-self.rot) if keys[pg.K_SPACE]: self.shoot() self.vel += self.acc + self.vel * PLAYER_FRICTION max_vel = 2 self.vel[0] = max(-max_vel, min(max_vel, self.vel[0])) self.vel[1] = max(-max_vel, min(max_vel, self.vel[1])) self.pos += self.vel </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Change url in python<p>how can I change the activeOffset in this url? I am using Python and a while loop</p> <p><a href="https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&amp;orderBy=kh&amp;orderDirection=ASC" rel="nofollow noreferrer">https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&amp;orderBy=kh&amp;orderDirection=ASC</a></p> <p>It first should be 10, then 20, then 30 ...</p> <p>I tried urlparse but I don't understand how to just increase the number</p> <p>Thanks!</p>
<p>If this is a fixed URL, you can write <code>activeOffset={}</code> in the URL then use <code>format</code> to replace <code>{}</code> with specific numbers:</p> <pre><code>url = &quot;https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset={}&amp;orderBy=kh&amp;orderDirection=ASC&quot; for offset in range(10,100,10): print(url.format(offset)) </code></pre> <p>If you cannot modify the URL (because you get it as an input from some other part of your program), you can use regular expressions to replace occurrences of <code>activeOffset=...</code> with the required number (<a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">reference</a>):</p> <pre><code>import re url = &quot;https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&amp;orderBy=kh&amp;orderDirection=ASC&quot; query = &quot;activeOffset=&quot; pattern = re.compile(query + &quot;\\d+&quot;) # \\d+ means any sequence of digits for offset in range(10,100,10): # Replace occurrences of pattern with the modified query print(pattern.sub(query + str(offset), url)) </code></pre> <p>If you want to use <code>urlparse</code>, you can apply the previous approach to the <code>fragment</code> part returned by <code>urlparse</code>:</p> <pre><code>import re from urllib.parse import urlparse, urlunparse url = &quot;https://www.dieversicherer.de/versicherer/auto---reise/typklassenabfrage#activeOffset=10&amp;orderBy=kh&amp;orderDirection=ASC&quot; query = &quot;activeOffset=&quot; pattern = re.compile(query + &quot;\\d+&quot;) # \\d+ means any sequence of digits parts = urlparse(url) for offset in range(10,100,10): fragment_modified = pattern.sub(query + str(offset), parts.fragment) parts_modified = parts._replace(fragment = fragment_modified) url_modified = urlunparse(parts_modified) print(url_modified) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to split the value of a field in a Python dataframe, add it to a new row, and use the existing value to add it to a new field<pre><code> STUDY Teacher UPDATE_DATE COMPARE_DATE INTERVAL_DAYS 0 entertainment C 2022-03-02 2022-01-01 0.61 1 entertainment B, C 2022-03-02 2022-04-10 0.39 2 math A 2022-02-25 2022-01-01 0.56 3 math A, C 2022-02-25 2022-04-10 0.44 4 science D 2022-01-03 2022-01-01 0.02 5 science A 2022-01-03 2022-02-20 0.48 6 science A, B, E 2022-02-20 2022-04-10 0.49 7 technology E 2021-09-01 2022-09-01 0.00 </code></pre> <p>Q. when there are more than 2 teacheres, I want to create a row by splitting based on &quot;,&quot; and divide the value of the INTERVAL_DAYS field by the number of teachers to add. I thought it had a similar structure to the compare_date function you helped and tried to apply it, but the desired output did not come out, so I had to raise an additional question.</p> <pre><code> STUDY Teacher UPDATE_DATE COMPARE_DATE INTERVAL_DAYS 0 entertainment C 2022-03-02 2022-01-01 0.61 1 entertainment B 2022-03-02 2022-04-10 0.2 2 entertainment C 2022-03-02 2022-04-10 0.2 3 math A 2022-02-25 2022-01-01 0.56 4 math A 2022-02-25 2022-04-10 0.22 5 math C 2022-02-25 2022-04-10 0.22 6 science D 2022-01-03 2022-01-01 0.02 7 science A 2022-01-03 2022-02-20 0.48 8 science A 2022-02-20 2022-04-10 0.16 9 science B 2022-02-20 2022-04-10 0.16 </code></pre> <p>10 science E 2022-02-20 2022-04-10 0.16 11 technology E 2021-09-01 2022-09-01 1.00</p> <p>The final thing you want to get is the sum of interval days for each Teacher.</p> <pre><code> Teacher WORKING_COUNTS 0 A 2 1 B 0.36 2 C 1.03 3 D 0.02 4 E 1.16 </code></pre>
<p>First split value by <code>, </code>and use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a>, divide rows by counts by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> and last aggrgate <code>sum</code>:</p> <pre><code>df = df.assign(Teacher = df['Teacher'].str.split(', ')).explode('Teacher') df['INTERVAL_DAYS'] /= df.groupby(level=0)['INTERVAL_DAYS'].transform('size') print (df) STUDY Teacher UPDATE_DATE COMPARE_DATE INTERVAL_DAYS 0 entertainment C 2022-03-02 2022-01-01 0.610000 1 entertainment B 2022-03-02 2022-04-10 0.195000 1 entertainment C 2022-03-02 2022-04-10 0.195000 2 math A 2022-02-25 2022-01-01 0.560000 3 math A 2022-02-25 2022-04-10 0.220000 3 math C 2022-02-25 2022-04-10 0.220000 4 science D 2022-01-03 2022-01-01 0.020000 5 science A 2022-01-03 2022-02-20 0.480000 6 science A 2022-02-20 2022-04-10 0.163333 6 science B 2022-02-20 2022-04-10 0.163333 6 science E 2022-02-20 2022-04-10 0.163333 7 technology E 2021-09-01 2022-09-01 0.000000 out = df.groupby('Teacher')['INTERVAL_DAYS'].sum().reset_index(name='WORKING_COUNTS') print (out) Teacher WORKING_COUNTS 0 A 1.423333 1 B 0.358333 2 C 1.025000 3 D 0.020000 4 E 0.163333 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Euclidean distance of all pandas rows to single row<p>I have a dataset that gives the values of some songs, ie something that looks like:</p> <pre><code> acousticness danceability energy instrumentalness key liveness loudness 0 0.223 0.780 0.72 0.111 1 0.422 0.231 1 0.4 0.644 0.88 0.555 0.5 0.66 0.555 2 0.5 0.223 0.145 0.76 0 0.144 0.567 . . . </code></pre> <p>I want to find the songs/ rows that are numerically closest to another song, such as song <code>0</code>, using the <em>euclidean distance</em>.So I'd like to obtain something like:</p> <pre><code> acousticness danceability energy instrumentalness key liveness loudness Euclidean to song 0 0 0.223 0.780 0.72 0.111 1 0.422 0.231 0 1 0.4 0.644 0.88 0.555 0.5 0.66 0.555 1.334 2 0.5 0.223 0.145 0.76 0 0.144 0.567 1.442 . . . </code></pre>
<p>The usual procedure for what you're trying to do, is to use one of sklearn's <a href="https://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics.pairwise" rel="nofollow noreferrer">pairwise metrics</a>, such as the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html" rel="nofollow noreferrer"><code>cosine_similarity</code></a>, and build a similarity matrix with it:</p> <pre><code>from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances cosine_similarity(df) array([[1. , 0.86597679, 0.38431913], [0.86597679, 1. , 0.71838491], [0.38431913, 0.71838491, 1. ]]) </code></pre> <p>This gives you a square matrix with the indices representing the dataframe <em>song</em> index.</p> <hr /> <p><strong>Similarity with a single item</strong></p> <p>If you're only interested in the similarities with a specific song, say song <code>0</code>, you can specify a second a array as, so that the similarities are obtained using all items in the input matrix with a given item.</p> <p>Since you mentioned the euclidean distance, here's one using sklearn's <code>euclidean_distances</code>. Note that we have tu subtract the result from <code>1</code>, since we have distances. If we want the actual distance, we can just keep the resulting array:</p> <pre><code>1-euclidean_distances(df, df.to_numpy()[0,None]) array([[ 1. ], [-0.16977006], [-1.15823261]]) </code></pre> <p>For the distance, just:</p> <pre><code>euclidean_distances(df, df.to_numpy()[0,None]) array([[0. ], [1.43266989], [2.64328432]]) </code></pre> <p>To update as a new column:</p> <pre><code>df['Similarity with song 0'] = 1-euclidean_distances(df, df.to_numpy()[0,None]).squeeze() </code></pre> <hr /> <pre><code>print(df) acousticness danceability energy instrumentalness key liveness \ 0 0.223 0.780 0.720 0.111 1.0 0.422 1 0.400 0.644 0.880 0.555 0.5 0.660 2 0.500 0.223 0.145 0.760 0.0 0.144 loudness Similarity with song 0 0 0.231 1.000000 1 0.555 -0.169770 2 0.567 -1.158233 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How pip manages same packages over different environments for space efficiency<p>I am using a huge pip environment <code>env1</code>, and I would like to create a new one (<code>env2</code>) that only has one different package, the rest is the same as <code>env1</code>.</p> <p>Is it necessary to reinstall all packages again in <code>env2</code>? Will it take the same space in my hard drive as <code>env1</code> or pip manages automatically the space efficiency via something like symbolic links for same packages over all environments?</p> <p>My objective is to reduce the space that takes the second environment as much as possible.</p> <hr> <p>Just in case I created the environments with:</p> <pre><code>python3 -m venv env1 python3 -m venv env2 </code></pre>
<blockquote> <p>Is it necessary to reinstall all packages again in env2?</p> </blockquote> <p>Yes.</p> <blockquote> <p>Will it take the same space in my hard drive as env1</p> </blockquote> <p>Yes.</p> <blockquote> <p>or pip manages automatically the space efficiency</p> </blockquote> <p>No. There is no way to symlink from other environments because they could be different — different Python versions, different package versions, different compilation flags.</p> <p>Another problem: how would <code>pip</code> find <code>env1</code> from <code>env2</code>? <code>pip</code> doesn't track existing environments, they could be anywhere.</p> <p>Yet another problem: what you gonna do in env <code>env2</code> if you delete <code>env1</code>? The symlinks in <code>env2</code> would become dangling.</p> <p>Short resume: disk space is cheaper than solving major problems from trying to manage space.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python - Extracting only necessary elements from a string<p>I'm trying to extract only the parts I need from the table.</p> <pre><code> 2555 texttext 0 100 100 0 0 0 0 lowness 0 2557 texttext 10 650 660 0 0 0 0 lowness 0 2564 texttext 0 30 30 0 0 0 0 lowness 0 2566 texttext 0 0 0 0 0 0 0 lowness 0 2567 texttext 10 70 80 0 0 0 0 lowness 0 </code></pre> <p>All I need is 'text text' and/ immediately followed by two numbers and 'low' as shown below.</p> <pre><code> texttext 0 100 lowness texttext 10 650 lowness texttext 0 30 lowness texttext 0 0 lowness texttext 10 70 lowness </code></pre> <p>I tried this but failed.</p> <pre><code>text = &quot;&quot;&quot; 2555 texttext 0 100 100 0 0 0 0 lowness 0 2557 texttext 10 650 660 0 0 0 0 lowness 0 2564 texttext 0 30 30 0 0 0 0 lowness 0 2566 texttext 0 0 0 0 0 0 0 lowness 0 2567 texttext 10 70 80 0 0 0 0 lowness 0 &quot;&quot;&quot; for a in text.split('\n'): if a == &quot;&quot;: continue else: print(a) m = re.match('(^\D\d*\D)(\w*\s)(\d*\s)(\d*\s)(\d*\s\d*\s\d*\s\d*\s\d*\s)(\w+)', a) print(m) print(m.group(2), m.group(3), m.group(4), m.group(6)) </code></pre> <p>I tried to group by regex and get the parts, but I got the following error: Help / print(m.group(2), m.group(3), m.group(4), m.group(6)) AttributeError: 'NoneType' object has no attribute 'group'</p>
<p>If you absolutely want to use a regular expression:</p> <pre class="lang-py prettyprint-override"><code>import re text = &quot;&quot;&quot; 2555 texttext 0 100 100 0 0 0 0 lowness 0 2557 texttext 10 650 660 0 0 0 0 lowness 0 2564 texttext 0 30 30 0 0 0 0 lowness 0 2566 texttext 0 0 0 0 0 0 0 lowness 0 2567 texttext 10 70 80 0 0 0 0 lowness 0 &quot;&quot;&quot; pattern = re.compile( r&quot;\s*\d+\s+(\w+)\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\w+)\s+&quot; ) for line in text.strip().split('\n'): match = re.search(pattern, line) print(*match.groups()) </code></pre> <p>Output:</p> <pre><code>texttext 0 100 lowness texttext 10 650 lowness texttext 0 30 lowness texttext 0 0 lowness texttext 10 70 lowness </code></pre> <p>But if it is really the case that it's always the same number of space-separated substrings of characters, then you might really be better off just splitting the lines by spaces:</p> <pre class="lang-py prettyprint-override"><code>for line in text.strip().split('\n'): parts = line.split() print(parts[1], parts[2], parts[3], parts[9]) </code></pre> <p>Same output.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Does sklearn time cpu time or wall time<p>Are the returned timing values for the random and grid search implementations of sklearn in CPU or wall time? All I can find in the documentation is the following:</p> <blockquote> <p>The mean_fit_time, std_fit_time, mean_score_time and std_score_time are all in seconds.</p> </blockquote> <p>So I am assuming that would mean wall time as the default, is this correct? </p>
<p>After going through the <a href="https://github.com/scikit-learn/scikit-learn/blob/95d4f0841/sklearn/model_selection/_search.py#L1154" rel="nofollow noreferrer">source code</a>...</p> <p>Line 748:</p> <pre class="lang-py prettyprint-override"><code>self.cv_results_ = results </code></pre> <p>Okay, what is <code>results</code>?</p> <p>Line 706:</p> <pre class="lang-py prettyprint-override"><code>results = self._format_results( all_candidate_params, scorers, n_splits, all_out) return results </code></pre> <p>Okay, what is <code>all_out</code>? </p> <p>Line 703:</p> <pre class="lang-py prettyprint-override"><code>all_out.extend(out) </code></pre> <p>and then <code>out</code> is:</p> <p>Line 682:</p> <pre><code>out = parallel(delayed(_fit_and_score)(clone(base_estimator), </code></pre> <p>and <code>_fit_and_score</code> is imported from <code>sklearn.model_selection._validation.py</code> so we look in <a href="https://github.com/scikit-learn/scikit-learn/blob/95d4f0841d57e8b5f6b2a570312e9d832e69debc/sklearn/model_selection/_validation.py" rel="nofollow noreferrer">there</a>...</p> <p>Line 543:</p> <pre class="lang-py prettyprint-override"><code>fit_time = time.time() - start_time </code></pre> <p>Aha! There we go. It's wall time, as <code>Python</code>'s <code>time.time()</code><a href="https://docs.python.org/3/library/time.html" rel="nofollow noreferrer">gives you the current Unix time</a>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python: how to remove leading zeros after string in pandas column?<p>I have a dataframe that looks like the following</p> <pre><code>df id 0 IT030 1 IT4 2 IT022 3 BE34 </code></pre> <p>I would like to remove all the <code>zeros</code> after the characters and have this</p> <pre><code>df id 0 IT30 1 IT4 2 IT22 3 BE34 </code></pre>
<p>You can use a regex:</p> <pre><code># if 0s after a non digit, remove them df['id'] = df['id'].str.replace(r'(\D)0+', r'\1', regex=True) </code></pre> <p>or:</p> <pre><code># if 0s between a non digit and a digit, remove them df['id'] = df['id'].str.replace(r'(\D)0+(\d+)', r'\1\2', regex=True) </code></pre> <p>output (as new column <code>id2</code> for clarity):</p> <pre><code> id id2 0 IT030 IT30 1 IT4 IT4 2 IT022 IT22 3 BE34 BE34 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to run a Python Script from Deno?<p>I have a python script with the following code:</p> <pre><code>print("Hello Deno") </code></pre> <p>I want to run this python script (test.py) from test.ts using Deno. This is the code in test.ts so far:</p> <pre><code>const cmd = Deno.run({cmd: ["python3", "test.py"]}); </code></pre> <p>How can I get the output, of the python script in Deno?</p>
<p><code>Deno.run</code> returns an instance of <a href="https://doc.deno.land/https/github.com/denoland/deno/releases/latest/download/lib.deno.d.ts#Deno.Process" rel="noreferrer"><code>Deno.Process</code></a>. In order to get the output use <code>.output()</code>. Don't forget to pass <code>stdout/stderr</code> options if you want to read the contents.</p> <pre><code>// --allow-run const cmd = Deno.run({ cmd: ["python3", "test.py"], stdout: "piped", stderr: "piped" }); const output = await cmd.output() // "piped" must be set const outStr = new TextDecoder().decode(output); const error = await p.stderrOutput(); const errorStr = new TextDecoder().decode(error); cmd.close(); // Don't forget to close it console.log(outStr, errorStr); </code></pre> <hr> <p>If you don't pass <code>stdout</code> property you'll get the output directly to <code>stdout</code></p> <pre><code> const p = Deno.run({ cmd: ["python3", "test.py"] }); await p.status(); // output to stdout "Hello Deno" // calling p.output() will result in an Error p.close() </code></pre> <hr> <p>You can also send the output to a File</p> <pre><code>// --allow-run --allow-read --allow-write const filepath = "/tmp/output"; const file = await Deno.open(filepath, { create: true, write: true }); const p = Deno.run({ cmd: ["python3", "test.py"], stdout: file.rid, stderr: file.rid // you can use different file for stderr }); await p.status(); p.close(); file.close(); const fileContents = await Deno.readFile(filepath); const text = new TextDecoder().decode(fileContents); console.log(text) </code></pre> <hr> <p>In order to check status code of the process you need to use <code>.status()</code></p> <pre><code>const status = await cmd.status() // { success: true, code: 0, signal: undefined } // { success: false, code: number, signal: number } </code></pre> <hr> <p>In case you need to write data to <code>stdin</code> you can do it like this:</p> <pre><code>const p = Deno.run({ cmd: ["python", "-c", "import sys; assert 'foo' == sys.stdin.read();"], stdin: "piped", }); // send other value for different status code const msg = new TextEncoder().encode("foo"); const n = await p.stdin.write(msg); p.stdin.close() const status = await p.status(); p.close() console.log(status) </code></pre> <hr> <p>You'll need to run Deno with: <code>--allow-run</code> flag in order to use <code>Deno.run</code></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to filter out the stocks whose price has been increasing for 3 consecutive days<p>I want to filter out the the strong performance stocks among a bunch of companies by the attribute of price increasing for 3 consecutive days. Below the code so far. Appreciate if any help.</p> <p>In other words, i want get a list of stock names whose price has been been increasing continuously for the past 3 days.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import pandas_datareader as web tick = ['AMZN', 'AAPL', 'NFLX', 'XOM', 'T'] df = web.get_data_yahoo(tick, start = '2020-01-01', end = '2020-12-16')['Adj Close'] </code></pre>
<p>You can compare if the difference is increasingly changing by using a <code>rolling</code> approach:</p> <pre><code>increase_table = df.rolling(3).apply(lambda x: np.all(np.diff(x) &gt; 0)).astype('boolean') </code></pre> <p>Output for the first 10 rows:</p> <pre><code>Symbols AMZN AAPL NFLX XOM T Date 2020-01-02 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 2020-01-03 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 2020-01-06 False False False False True 2020-01-07 True False False False True 2020-01-08 False False False False True 2020-01-09 False True False False False 2020-01-10 False True False False False 2020-01-13 False True False False False 2020-01-14 False False False False False 2020-01-15 False False False False False </code></pre> <hr /> <p>I didn't get the logic from what you want to get your lists. But something useful here is to verify how much consecutive-3-days is increasing per stock:</p> <pre><code>increase_table.sum() </code></pre> <p>which returns:</p> <pre><code>Symbols AMZN 74 AAPL 59 NFLX 57 XOM 40 T 58 dtype: int64 </code></pre> <p>so that we know that &quot;AMZN&quot; has more days with increasing in the last 3 days.</p> <hr /> <p><strong>Note:</strong> For correct interpretation, the <code>True</code> values here is telling us that the last two values and itself (current value; total = 3 values) are increasing. To correctly place the <code>True</code> values to indicate that the last three rows (and the row itself) are increasing, just do <code>increase_table.shift()</code>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: youtube_dl error: Failed to parse JSON (caused by JSONDecodeError('Expecting value: line 1 column 1 (char 0)')) disocrd error<p>Error:</p> <p>youtube_dl.utils.DownloadError: ERROR: query &quot;song&quot;: Failed to parse JSON (caused by JSONDecodeError('Expecting value: line 1 column 1 (char 0)')</p> <p>Play command:</p> <pre class="lang-py prettyprint-override"><code> @commands.command(name='play',aliases=['p'] ) async def _play(self, ctx: commands.Context, *, search: str): async with ctx.typing(): try: source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop) except YTDLError as e: await ctx.send('Error: {}'.format(str(e))) else: song = Song(source) await ctx.voice_state.songs.put(song) </code></pre> <p>Youtube-DL Class:</p> <pre class="lang-py prettyprint-override"><code>class YTDLSource(discord.PCMVolumeTransformer): YTDL_OPTIONS = { 'format': 'bestaudio/best', 'extractaudio': True, 'audioformat': 'mp3', 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s', 'restrictfilenames': True, 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'logtostderr': False, 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0', } FFMPEG_OPTIONS = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn', } ytdl = youtube_dl.YoutubeDL(YTDL_OPTIONS) </code></pre> <p>Please guide me how to fix this error This error started for me last week and my youtube_dl is also updated</p> <p>If you need another code, tell me, but please fix my problem</p> <p>I also do not know how to get error message including stack trace</p>
<p>You have this error because <a href="https://github.com/ytdl-org/youtube-dl" rel="nofollow noreferrer"><code>youtube-dl</code></a> was taken down, which means that it's not accessible to public anymore.<br></p> <p>Instead of directly using <code>youtube-dl</code>, you can use libraries like <a href="https://pypi.org/project/pafy/" rel="nofollow noreferrer"><code>pafy</code></a> that uses the command-line version of <code>youtube-dl</code>:</p> <pre class="lang-py prettyprint-override"><code>from pafy import new @client.command(pass_context=True) async def play(ctx): ffmpeg_opts = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} channel = ctx.author.voice.channel voice = await channel.connect() video = new(&quot;youtube video link&quot;) audio = video.getbestaudio().url voice.play(FFmpegPCMAudio(audio, **ffmpeg_opts)) voice.is_playing() </code></pre> <p><code>pafy</code> doesn't include youtube search so you'll have to do your own. For this you have multiple choices:</p> <ul> <li>Doing some webscraping using <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer"><code>bs4</code></a></li> <li>Using libraries like <a href="https://pypi.org/project/fast-youtube-search/" rel="nofollow noreferrer"><code>fast-youtube-search</code></a></li> <li>Use <a href="https://docs.aiohttp.org/en/stable/" rel="nofollow noreferrer"><code>aiohttp</code></a> (which is the async version of <code>requests</code>) and <a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer"><code>re</code></a> to find the video id. This last option is probably the fastest one.</li> </ul> <p>If you want an easier solution, you can use <a href="https://python-pytube.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>pytube</code></a> but it's slower and supports up to python 3.7.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Best practices on python conditionals<p>When it comes to best practices on conditionals, which of the following examples is recommended?</p> <pre><code>def sum(arg1,arg2): if arg1&gt;3: return else: return arg1+agr2 </code></pre> <p>or</p> <pre><code>def sum(arg1,arg2): if arg1&lt;3: return arg1+agr2 else: return </code></pre> <p>Thanks in advance!</p>
<p>Consider using a ternary expression:</p> <pre class="lang-py prettyprint-override"><code>def sum(arg1, arg2): return arg1 + arg2 if arg1 &lt; 3 else None </code></pre> <p>As an addendum, if one of the cases is unexpected or undesirable, I like to follow the <a href="https://en.wikipedia.org/wiki/Guard_(computer_science)" rel="nofollow noreferrer">guard pattern</a>, which involves checking for these cases first before performing your normal logic.</p> <p>For example,</p> <pre class="lang-py prettyprint-override"><code>def safe_divide(a, b): # Check preconditions at top of function definition if b == 0: return None # Checks passed, perform normal logic return a / b </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Conda create virtual environtment with pypy as interpreter in VSCode<p>I have successfully installed conda and pypy because of this <a href="https://stackoverflow.com/questions/29056963/how-to-install-pypy-in-anaconda">previous question</a>, I'm using VSCode as text editor. Yes I can use pypy but it seems installed for global environtment instead of virtual environtment. I want use pypy in virtual environtment with conda so the package will insttalled locally instead of globally.</p> <p>The tutor I saw in previous stackoverflow will created virtual environtment with common python interpreter instead of pypy.</p>
<p>You can create a conda environment first:</p> <pre><code>conda create -n pypy3 -c conda-forge pypy3.5 </code></pre> <p>Afterwards you have to link to the pypy3 interpreter within the bin directory of the env:</p> <pre><code>ln -s pypy3 python </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: sorting a concatenation of sorted arrays<p>What is the sorting algorithm most optimized for sorting an array that consists of 2 sorted sub-arrays?</p> <p>This question came up when I was solving: <a href="https://leetcode.com/problems/squares-of-a-sorted-array/" rel="nofollow noreferrer">https://leetcode.com/problems/squares-of-a-sorted-array/</a></p> <p>My solution is as follows:</p> <pre><code> def sortedSquares(self, nums: List[int]) -&gt; List[int]: n = len(nums) l, r = 0, n-1 res = [0] * n for i in range(n-1, -1, -1): if abs(nums[l]) &gt; abs(nums[r]): res[i] = nums[l] ** 2 l += 1 else: res[i] = nums[r] ** 2 r -= 1 return res </code></pre> <p>However this solution beats mine:</p> <pre><code> def sortedSquares(self, nums: List[int]) -&gt; List[int]: return sorted([i * i for i in nums]) </code></pre> <p>If timsort is doing insertion sort on small chunks, then wouldn't an array like this cause O(n^2) on half the runs? How is that better than my supposedly O(n) solution?</p> <p>Thank you!</p>
<p>In this case, the theoretical time complexity is O(n) because you don't need to sort at all (merely merge two ordered lists). Performing a sort generally has a O(NlogN) complexity.</p> <p>Complexity and performance are two different things however. Your O(n) solution in Python code is competing with O(NlogN) in highly optimized low level C code. In theory there should be a point where the size of the list is large enough for the Python based O(n) solution to catch up with the O(NlogN) profile of the native sort but you can expect that this would be a very large number of elements (probably larger than your computer's memory can hold). If Python's native sort is smart enough to switch to a radix sorting algorithm for integers or if its sorting algorithm benefits from partially sorted data, it will be impossible to catch up.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Pandas stacked bar creating many individual plots with incorrect bottom values<p>Given a Dataframe (this is generated from a csv that contains the names and orders and updated everyday):</p> <pre><code># Note that this is just an example df and the real can have N names in n shuffled orders df = pd.read_csv('names_and_orders.csv', header=0) print(df) names order 0 mike 0 1 jo 1 2 mary 2 3 jo 0 4 mike 1 5 mary 2 6 mike 0 7 mary 1 8 jo 2 </code></pre> <p>I am turning this into a stacked bar plot using pandas' stacked bar functionality and a for loop, as shown below.</p> <pre><code># Create list of names from original df names1 = df['names'].drop_duplicates().tolist() N = len(names1) viridis = cm.get_cmap('viridis', 100) # Get count of each name at each order df_count = df_o.groupby(['order', 'names']).size().reset_index(name='count') # Plot count vs order in a stacked bar with the label as the current name for i in range(len(names1)): values = list(df_count[df_count['names'] == names1[i]].loc[:, 'count']) df_count[df_count['names'] == names1[i]].plot.bar(x='order', y='count', color=viridis(i / N), stacked=True, bottom=values, edgecolor='black', label=names1[i]) values += values # Add ticks, labels, title, and legend to plot plt.xticks(np.arange(0, N, step=1)) plt.xlabel('Order') plt.yticks(np.arange(0, df_count['count'].max(), step=1)) plt.ylabel('Count') plt.title('How many times each person has been at each order number') plt.legend() plt.show() </code></pre> <p>Given this code, there are two main issues I am having:</p> <ol> <li>It is currently plotting every name on a different figure instead of making one stacked bar plot</li> <li>I don't believe the <code>values</code> use for the <code>bottom</code> kwarg is correct</li> </ol>
<p>I think you're overthinking this. Just <code>unstack</code> the groupby and plot:</p> <pre><code>df_count = df.groupby(['order', 'names']).size().unstack('names') df_count.plot.bar(stacked=True) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/u3bdM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3bdM.png" alt="enter image description here" /></a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Typing: Inferred type too general during class inheritance<p>I'm facing the following problem. Suppose I want to define generic class for <code>Dataset</code> and its <code>Sample</code>s. Then, I want to create specific subclasses of these that will in the end be instantiated (E.g. <code>DatasetOfSpecificSamples</code> that contains <code>MoreSpecificSample</code> samples). To save some LoC, I want to implement common functionality in <code>Dataset</code> class.</p> <p>Yet, I can't get the typehints in the inherited sublcasses right. They are too general. See the following example, where I would expect that <code>__iter__</code> return type of <code>DatasetOfSpecificSamples</code> would be <code>MoreSpecificSample</code>, yet MyPy infers just <code>Sample</code>.</p> <p>Is there a way to enforce <em>more specific</em> hint without redifining the method itself?</p> <pre class="lang-py prettyprint-override"><code>from typing import Mapping, Iterator class Sample: pass class MoreSpecificSample(Sample): pass class Dataset: def __init__(self, samples: Mapping[str, Sample]): self.samples = samples def __iter__(self) -&gt; Iterator[Sample]: yield from self.samples.values() class DatasetOfSpecificSamples(Dataset): samples: Mapping[str, MoreSpecificSample] # def __iter__(self) -&gt; Iterator[CommonCriteriaCert]: &lt;-- This fixes the problem, as it specifies the type # yield from self.certs.values() dset = DatasetOfSpecificSamples() for sample in dset: # &lt;-- the inferred type of &quot;sample&quot; is Sample, not MoreSpecificSample pass </code></pre>
<p>Make <code>Dataset</code> class Generic:</p> <pre><code>T = TypeVar(&quot;T&quot;) class Dataset(Generic[T]): def __init__(self, samples: Mapping[str, T]): self.samples = samples def __iter__(self) -&gt; Iterator[T]: yield from self.samples.values() class DatasetOfSpecificSamples(Dataset[MoreSpecificSample]): samples: Mapping[str, MoreSpecificSample] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to return data from a Python process to the process that requested it<p>How can I get data back from one (provider) Process to another (requester) Process that made a request of it? This needs to work when the requester process may not have been running when the provider process was started.</p> <p>I know the provider process can have a Queue to receive requests from multiple requesters, but how can it return data to the requester process that put the request on the queue? How can the requester process know when the data is available?</p> <p>Simplified Example</p> <p>Process A requests data from Process Z and waits for Z to return it. Process B is started and independently requests data from Process Z. Process Z handles the requests in order, returning one set of data to A and another to B.</p> <p>Process Z needs to run continually while Processes A, B, C ... etc. may come and go.</p> <p>N.B. Briefly, this is needed because Process Z is managing requests to an external resource which does not handle concurrent requests.</p> <p>Thanks for any help and suggestions.</p> <p>Julian</p>
<p>In the following demo I have chosen to make &quot;Process Z&quot; a <em>daemon</em> process, meaning that it will automatically terminate when all <em>non-daemon</em>, i.e. &quot;regular&quot; processes, terminate. Alterntively, you can make this a regular process and put in its input queue a special <em>sentinel</em> request value such as <code>(None, None)</code> to signal to it to terminate.</p> <p>The idea is that Process Z will be initialized with an input queue to which other processes will <code>put</code> requests. Each request is a tuple. For this demo the first element of the tuple is a value to be squared and the second element is a queue to which the result is to be <code>put</code> to. So each process that is making a request of Process Z will be passing its <em>own</em> result queue instance. The important thing to note here is that you cannot <code>put</code> an instance of a <code>multiprocessing.Queue</code> object to another <code>multiprocessing.Queue</code> instance: you will get a <em>RuntimeError: Queue objects should only be shared between processes through inheritance</em>. Therefore, these result queues must instead be <em>managed</em> queue instances created by an instance of a <code>multiprocessing.SynchManager</code>, which is returned by calling <code>multiprocessing.Manager()</code>:</p> <pre class="lang-py prettyprint-override"><code>from multiprocessing import Process, Queue, Manager def process_z(input_q): while True: x, result_q = input_q.get() result_q.put(x ** 2) def process_a(input_q, result_q): input_q.put((3, result_q)) result = result_q.get() print('3 ** 2 =', result) def process_b(input_q, result_q): input_q.put((7, result_q)) result = result_q.get() print('7 ** 2 =', result) input_q.put((5, result_q)) result = result_q.get() print('5 ** 2 =', result) for x in range(10, 14): input_q.put((x, result_q)) for x in range(10, 14): result = result_q.get() print(f'{x} ** 2 =', result) # required by Windows: if __name__ == '__main__': with Manager() as manager: input_q = Queue() # make &quot;Process Z&quot; a daemon process that will end when all non-daemon processes end: Process(target=process_z, args=(input_q,), daemon=True).start() result_q_a = manager.Queue() p_a = Process(target=process_a, args=(input_q, result_q_a)) p_a.start() result_q_b = manager.Queue() p_b = Process(target=process_b, args=(input_q, result_q_b)) p_b.start() # wait for completion of non-daemon processes: p_a.join() p_b.join() </code></pre> <p>Prints:</p> <pre><code>3 ** 2 = 9 7 ** 2 = 49 5 ** 2 = 25 10 ** 2 = 100 11 ** 2 = 121 12 ** 2 = 144 13 ** 2 = 169 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python 3.8 (Hangman Game Input)<p>From the question I’m about to ask you will realize that I’m just a beginner. Anyways, so I’m assigning a input function to a variable <code>word</code>. I then def a function and in that function I say:</p> <pre class="lang-py prettyprint-override"><code>if ' ' or '-' in word: print('Error cannot...') </code></pre> <p>My issue here is whenever I run this and enter a word for my input it always prints <code>Error cannot...</code> even when I don’t have spaces or <code>'-'</code> in my word. That’s all thanks if you decide to help me out.</p>
<p>Try using this: <code>if &quot; &quot; in word or &quot;-&quot; in word:</code>. The reason you got the outcome you did is because a non-empty string is &quot;truthy,&quot; in other words, it is considered true. If you have true on one side of an or and false on the other, the or will still output true.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to find subgraphs of strongly connected components using networkx<p>as <code>nx.strongly_connected_component_subgraphs()</code> is now removed in version 2.4, I have tried using <code>(G.subgraph(c) for c in strongly_connected_components(G))</code> similar to what we do for connected component subgraphs. but this just shows strongly_connected_component_subgraphs is deprecated. What to do for strongly connected subgraphs in networkx? sorry if this question is repeated.</p>
<p>Using <a href="https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.strongly_connected_components.html#networkx.algorithms.components.strongly_connected_components" rel="nofollow noreferrer"><code>nx.strongly_connected_components</code></a> as in your shared approach, should be fine:</p> <pre><code>(G.subgraph(c) for c in nx.strongly_connected_components(G)) </code></pre> <p>This function is included in the <a href="https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.strongly_connected_components.html#networkx.algorithms.components.strongly_connected_components" rel="nofollow noreferrer">latest version, 2.5</a>, and does not rely on any other deprecated methods, as you can see in the <a href="https://networkx.github.io/documentation/stable/_modules/networkx/algorithms/components/strongly_connected.html#strongly_connected_components" rel="nofollow noreferrer">source code</a>. So make sure you aren't using the method that is actually raising the deprecation warning, <code>nx.strongly_connected_component_subgraphs</code>.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Need help to understand why the for loop only loops once<p>The code I use below is a function that allows me to get data from an API:</p> <pre><code>def get_evt(adresse, id_machine, bucket_size, token, data): TO_DATE = datetime.strptime("25/11/2019, 22:00:00", "%d/%m/%Y, %H:%M:%S").timetuple() param = { "from": int((mktime(TO_DATE) - (60 * 60 * HOUR_DIFF)) * 1000), "to": int(mktime(TO_DATE) * 1000), "bucketSize": bucket_size, "queries": [ { "signal": data, "aggregationFunction": "raw", "groupBy": { "type": "machine", "id": id_machine } } ] } liste = [] resp = requests.post(adresse, headers=token, json=param) if resp.status_code != 200: # This means something went wrong. print('ERROR ', resp.status_code, ': ', resp.json()["message"]) print(resp.json()["message"]) else: signalsData = resp.json() for param in range(len(signalsData)): values = signalsData[param]['timeseries'] print(values) for value in values: timestamp = int(value['time']/bucket_size) valeur = value['value'] return timestamp, valeur </code></pre> <p>However in this code this for loop only loops once:</p> <pre><code>for value in values: timestamp = int(value['time']/bucket_size) valeur = value['value'] return timestamp, valeur </code></pre> <p>What I would like to achieve is to somehow get the first and last value of the list "values" but I don't understand why the loop only works once even though values contains multiple values.</p>
<p>Try returning out of the for loop, therefore after you have looped through all the values: ie</p> <pre><code>for value in values: timestamp = int(value['time']/bucket_size) valeur = value['value'] return timestamp, valeur </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Force streamlit to run in specific python version (or under specific environment)<p>I have a streamlit app that is set to run by doubleclicking a *.bat file that contains the command to start the app: streamlit run myApp.py. Does anyone know how to force that app to run in specific python version? My base python is 3.9, I created an environment (conda env create ...) based on python 3.6 where I installed streamlit and created the app and I want it to run there. I open sypder using that environment, double-checked that the env is active (!python --version in the spyder console) but when I run the app using the *bat file, it shows that is running in python 3.8!</p>
<p>Although Streamlit is a Python library (and used to be a stand-alone company), <code>streamlit run myApp.py</code> in that context is a reference to an executable <code>streamlit</code>. In cases where there are multiple, you can specify the exact one you want to use:</p> <p><code>/path/to/conda/env/streamlit run myApp.py</code></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python: call pandas_datareader with isin or wkn or translate this into ticker symbol?<p>I have a real big list of stocks with ISIN and WKN-Number. My aim is to use pandas_datareader to get now historical data from that stocks. My problem is, the function e.g.</p> <pre><code>import pandas_datareader as web stock = web.DataReader('ALB', data_source=&quot;yahoo&quot;, start=&quot;01.01.2021&quot;, end=&quot;30.10.2021&quot;) </code></pre> <p>only can work with ticker-symbols. Is there some way (maybe other library) to solve that or some algorithm to transform the Numbers into ticker symbols?</p>
<p>At least for the <strong>ISIN</strong> you can use <a href="https://investpy.readthedocs.io/" rel="nofollow noreferrer"><code>investpy</code></a> <code>stocks.search_stocks</code> function, which returns a <em>pandas.DataFrame</em> containing (among others information) the <em>symbol</em> for that ISIN code.</p> <pre class="lang-py prettyprint-override"><code>import investpy df = investpy.stocks.search_stocks(by='isin', value='US0126531013') print(df) # country name full_name isin currency symbol # 0 mexico Albemarle Albemarle Corp US0126531013 MXN ALB # 1 united states Albemarle Albemarle Corp US0126531013 USD ALB # 2 germany Albemarle Albemarle Corporation US0126531013 EUR ALLE </code></pre> <pre class="lang-py prettyprint-override"><code>from pandas_datareader import data as pdr symbol = df.loc[df['country']=='united states','symbol'].values[0] print(symbol) # ALB stock = pdr.DataReader(symbol, data_source=&quot;yahoo&quot;, start=&quot;2021-01-01&quot;, end=&quot;2021-10-30&quot;) print(stock.head()) </code></pre> <pre class="lang-py prettyprint-override"><code> Open High Low Close Adj Close Volume Date 2021-01-04 152.899994 156.759995 150.289993 152.630005 151.645477 2898700 2021-01-05 152.669998 166.779999 152.669998 162.929993 161.879028 2628000 2021-01-06 165.500000 178.589996 165.500000 175.100006 173.970535 3335500 2021-01-07 183.479996 187.250000 180.550003 184.000000 182.813126 2947800 2021-01-08 184.490005 186.929993 178.660004 184.100006 182.912491 1659400 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: ctypes binding call throws segmentation fault<p>I'm trying to create simple bindings to the <a href="https://github.com/mity/md4c" rel="nofollow noreferrer">MD4C</a> project but get a weird segmentation fault thrown when I attempt to call <code>md_parse</code>. I'm not too well versed in C so the code bellow describes my best attempt to tackle this issue. I acquired <code>libmd4c.dylib</code> by cloning and building the project with <code>cmake</code> according to their instructions:</p> <pre><code>brew install cmake git clone https://github.com/mity/md4c.git cd md4c mkdir build cd build cmake .. make </code></pre> <p>My best guess about what's wrong is the actual arguments I'm passing to the final call. Here is the full code:</p> <pre><code>import ctypes import sys lib = ctypes.CDLL('libmd4c.dylib') def generic_cb(*args, **kwargs): print(args, kwargs) def block_cb(code, detail, udata): generic_cb(code, details, udata) return 0 c_func_block_cb = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p ) c_func_block_cb_p = ctypes.POINTER( c_func_block_cb ) c_func_text_cb = ctypes.CFUNCTYPE( ctypes.c_int, ctypes.c_wchar_p, ctypes.c_uint, ctypes.c_void_p ) c_func_text_cb_p = ctypes.POINTER( c_func_text_cb ) c_func_debug_log_cb = ctypes.CFUNCTYPE( ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p, ) c_func_debug_log_cb_p = ctypes.POINTER( c_func_debug_log_cb ) c_func_syntax_cb = ctypes.CFUNCTYPE( ctypes.c_void_p, ctypes.c_void_p, ) c_func_syntax_cb_p = ctypes.POINTER( c_func_syntax_cb ) class Structure(ctypes.Structure): _fields_ = [ ( 'abi_version', ctypes.c_uint ), ( 'flags', ctypes.c_uint ), ( 'enter_block', c_func_block_cb_p ), ( 'leave_block', c_func_block_cb_p ), ( 'enter_span', c_func_block_cb_p ), ( 'leave_span', c_func_block_cb_p ), ( 'text', c_func_text_cb_p ), ( 'debug_log', c_func_debug_log_cb_p ), ( 'syntax', c_func_syntax_cb_p ) ] StructurePointer = ctypes.POINTER(Structure) c_block_cb = c_func_block_cb(block_cb) c_block_cb_p = c_func_block_cb_p(c_block_cb) c_text_cb = c_func_text_cb(generic_cb) c_text_cb_p = c_func_text_cb_p(c_text_cb) c_debug_log_cb = c_func_debug_log_cb(generic_cb) c_debug_log_cb_p = c_func_debug_log_cb_p(c_debug_log_cb) c_syntax_cb = c_func_syntax_cb(generic_cb) c_syntax_cb_p = c_func_syntax_cb_p(c_syntax_cb) struct = Structure( 0, 0, c_block_cb_p, c_block_cb_p, c_block_cb_p, c_block_cb_p, c_text_cb_p, c_debug_log_cb_p, None ) value = '**hello**' value_p = ctypes.c_wchar_p(value) struct_p = StructurePointer(struct) size = ctypes.c_uint(len(value)) func = lib.md_parse func.argtypes = [ ctypes.c_wchar_p, ctypes.c_uint, StructurePointer, ctypes.c_void_p ] func.restype = ctypes.c_int func.errcheck = print udata = ctypes.c_int() udata_p = ctypes.byref(udata) result = lib.md_parse(value_p, size, struct_p, udata_p) print(result) </code></pre> <p>Please let me know if you have any insights to share.</p>
<p>The following changes to the python code in this question prevent various segfaults and exceptions.</p> <pre><code>--- md_parse.py 2020-01-22 22:47:31.802934477 -0500 +++ md_parse.py 2020-01-22 23:56:50.874006725 -0500 @@ -7,7 +7,9 @@ print(args, kwargs) -def block_cb(code, detail, udata): + return 0 + +def block_cb(code, details, udata): generic_cb(code, details, udata) @@ -27,7 +29,7 @@ c_func_text_cb = ctypes.CFUNCTYPE( ctypes.c_int, - ctypes.c_wchar_p, + ctypes.c_wchar, ctypes.c_uint, ctypes.c_void_p ) @@ -72,28 +74,28 @@ ( 'enter_block', - c_func_block_cb_p + c_func_block_cb ), ( 'leave_block', - c_func_block_cb_p + c_func_block_cb ), ( 'enter_span', - c_func_block_cb_p + c_func_block_cb ), ( 'leave_span', - c_func_block_cb_p + c_func_block_cb ), ( 'text', - c_func_text_cb_p + c_func_text_cb ), ( 'debug_log', - c_func_debug_log_cb_p + c_func_debug_log_cb ), ( 'syntax', @@ -127,12 +129,12 @@ struct = Structure( 0, 0, - c_block_cb_p, - c_block_cb_p, - c_block_cb_p, - c_block_cb_p, - c_text_cb_p, - c_debug_log_cb_p, + c_block_cb, + c_block_cb, + c_block_cb, + c_block_cb, + c_text_cb, + c_debug_log_cb, None ) </code></pre> <p>The first patch chunk fixes a discrepancy in the <code>block_cb</code> argument list, and fixes <code>generic_cb</code> to return the expected type (omitting the changes in the first chunk will reveal some exceptions hidden behind the segfaults).</p> <p>The other changes in the patch prevent a couple of different segfaults, and amount to not using pointer types in various places. There is some dead code left behind by those changes, but removing that dead code would make the patch bigger, with no relevance to the segfaults which are the focus of this question.</p> <p>I performed my testing on a Debian system, but I wouldn't expect the results to vary materially on other platforms.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: What is the correct format for my datetime object in python?<p>I'm trying to turn a string into a datetime object, however, I don't know what format I should use. No matter what I try I get this error: time data '2022-02-19 16:58:39.937000' does not match format &lt;&quot;the format I input&quot;&gt;. Do you know what format I have to use for this date: &quot;2022-02-19 16:58:39.937000&quot;?</p>
<p>To turn a string into a datetime object you need to do this:</p> <pre class="lang-py prettyprint-override"><code>import datetime origin = '2022-02-19 16:58:39.937000' time_converted= datetime.datetime.strptime(origin, &quot;%Y-%m-%d %H:%M:%S.%f&quot;) print(type(time_converted)) &lt;class 'datetime.datetime'&gt; </code></pre> <p>Your problem must be the separation between the formatting.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Dynamic interaction between Rectangle Selector and a matplotlib figure<p>I am working on a an interactive program which displays an image and lets the user select a part of this image through a <code>RectangleSelector</code>. The goal is that the program </p> <ol> <li>first, displays in real time the minimum value of the three canals in the selected part of the image</li> <li>save the coordinates of the rectangle when the user is happy with it, in order the program continues</li> </ol> <p>Because my program project is big and covers much more than that, I have split it in several files. Here are they :</p> <ul> <li>settings.py</li> </ul> <pre class="lang-py prettyprint-override"><code>import numpy as np def init(): global img # image global text_sig_red, text_sig_green, text_sig_blue # text_sig_red, text_sig_green, text_sig_blue = '', '', '' img = np.array([]) </code></pre> <ul> <li>functions.py</li> </ul> <pre class="lang-py prettyprint-override"><code>import numpy as np import settings def line_select_callback(eclick, erelease): # 'eclick and erelease are the press and release events' x1, y1 = int(eclick.xdata), int(eclick.ydata) # start position x2, y2 = int(erelease.xdata), int(erelease.ydata) # end position crop_img = settings.img[x1:x2,y1:y2] #print('shape film temoin', np.shape(film_temoin)) sig_red = np.min(crop_img[:,:,0]) sig_green = np.min(crop_img[:,:,1]) sig_blue = np.min(crop_img[:,:,2]) text_red = 'min red signal' + str(sig_red) text_green = 'min green signal' + str(sig_green) text_blue = 'min blue signal' + str(sig_blue) settings.text_sig_red.set_text(text_red) settings.text_sig_green.set_text(text_green) settings.text_sig_blue.set_text(text_blue) def toggle_selector(event): if event.key in ['Q', 'q'] and toggle_selector.RS.active: toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: toggle_selector.RS.set_active(True) </code></pre> <ul> <li>main.py</li> </ul> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.image as mpim import matplotlib.animation as animation import matplotlib.patches as patches from matplotlib.widgets import RectangleSelector from matplotlib import pyplot as plt import functions as fct import settings settings.init() settings.img = mpim.imread('pattern.png') fig, ax = plt.subplots(1, 1) ax_red = plt.axes([0.05, 0.5, 0.05, 0.02]) ax_green = plt.axes([0.05, 0.3, 0.05, 0.02]) ax_blue = plt.axes([0.05, 0.1, 0.05, 0.02]) settings.text_sig_red = ax_red.text(0.5,0.5,"",transform=ax_red.transAxes) settings.text_sig_green = ax_green.text(0.5,0.5,"",transform=ax_green.transAxes) settings.text_sig_blue = ax_blue.text(0.5,0.5,"",transform=ax_blue.transAxes) ax.imshow(settings.img) fct.toggle_selector.RS = RectangleSelector(ax, fct.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True, rectprops=dict(facecolor='black', edgecolor = 'black', alpha=1., fill=None)) plt.connect('key_press_event', fct.toggle_selector) plt.show() </code></pre> <p>Currently, I have trouble with the goal (1) of my program. It doesn't display dynamically the text <code>text_sig_red</code>. </p> <p>And actually, I don't know how to save the coordinates of the rectangle when the user is happy with it. Maybe the user should stop touching the rectangle position and extents and click a button in order the program continue (This is <a href="https://stackoverflow.com/questions/56312631/wait-till-the-user-click-a-button-in-a-matplotlib-figure-to-continue-the-program">linked</a> to another problem I have)</p> <p>PS : I have given <a href="https://i.stack.imgur.com/6txlr.png" rel="nofollow noreferrer">here</a> the random image I have used in this example for my question.</p>
<p>Hope your problem was solved by now, but if not:</p> <p>The root cause of your problem with goal (1) is that the figure never explicitly gets updated after the initial show().</p> <p>So one solution to this problem would be to add the following line to the end of the line_select_callback function in functions.py:</p> <pre><code>plt.gcf().canvas.draw() </code></pre> <p><em>(of course plt would need to be imported in this module as well)</em></p> <p>Concerning the rest of your question, creating an obvious interaction such as a button is always a good choice.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Best solution for client - server architecture<p>I have an application and there are two logical parts for it.</p> <ol> <li>Core algorithm proprietary logic written in Python.</li> <li>Winform application on desktop.</li> </ol> <p>I do not want to have my core algorithm to be exposed on the client-side due to security issue. Since it is written in python want to have it in server and my Winform App (C#.net) can connect to the server through some mean.</p> <p>Please suggest some architecture diagrams to achieve this so that I can safeguard my core algorithm.</p>
<p>The most obvious solution I can think of would be to host the Python algorithm on a *aaS solution, and have that expose your algorithm via an API.</p> <p>In terms of *aaS providers for Python, there are heaps of options, e.g. <a href="https://azure.microsoft.com/en-us/services/functions/#overview" rel="nofollow noreferrer">Azure Functions</a> might be an option for you. An advantage of a platform like Azure / GCP / AWS is that they are pretty mature and will have all the tools you need to expose you algorithm through an API, manage security, etc.</p> <p><a href="https://docs.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python" rel="nofollow noreferrer">Quickstart</a>: Create a function in Azure with Python using Visual Studio Code</p> <p><strong>Basic Architecture</strong></p> <p>For the overall architecture, in simple terms, all you simply need to point your app at the API which exposes your algorithm.</p> <p><a href="https://i.stack.imgur.com/qIDSa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qIDSa.png" alt="enter image description here" /></a></p> <ul> <li>Blue elements: your code / system.</li> <li>Green element: the *aaS runtime environment, hosting, networking, storage, etc.</li> </ul> <p>In the diagram above, I have assumed that:</p> <ul> <li>When you migrate the algorithm onto the *aaS platform, you create an appropriate API for it, so that it can be called by the desktop application in a sensible way.</li> <li>You're using something like Azure Functions (as the runtime) which can be used to host the algorithm as an API, exposed to the internet directly.</li> <li>Your desktop app has a layer which neatly handles the service access - just like you might do for database access code, so that it's not littered through your app.</li> <li>You have a config file (or some other mechanism) that allows operators of the app to point to wherever the algorithm is hosted.</li> </ul> <p><strong>Production Architecture</strong></p> <p>The above (simple) architecture will work, but it's not production grade.</p> <p><a href="https://i.stack.imgur.com/tStQS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tStQS.png" alt="enter image description here" /></a></p> <ul> <li>Blue elements: your code / system.</li> <li>Green elements: the *aaS runtime environment, hosting, networking, storage, etc.</li> <li>Red element: DNS / networking, which might sit outside your *aaS provider, or inside it (or both).</li> </ul> <p>Description:</p> <ul> <li>Similar to the simple architecture except that we add some kind of API gateway to de-couple where requests hit the *aaS platform, and your service implementation. That way you can swap out service implementations without affecting consumers. A proper API gateway will also provide a more complete range of management &amp; operational features.</li> <li>DNS, e.g. <a href="http://www.myawesomepythonalgorithm.net" rel="nofollow noreferrer">www.myawesomepythonalgorithm.net</a> allows you to control which *aaS provider service traffic gets sent to, assuming you wanted to switch from Azure to GCP (and assuming the services URL structure was the same).</li> <li>Security! Not shown on the diagram, but presumably you'll need to decide how you want to protect the algorithm from unauthorized access.</li> </ul>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to use a dataframe in a PUT call in requests / aiohttp<p>I'm trying to interact with an application through its API. According to the documentation I should be able to upload a custom "csv" file through a PUT call. </p> <p>According to the documentation, a call should look like this:</p> <pre><code>PUT [URL] Host: [host domain] Accept: application/json Content-Length: 79182 Content-Type: multipart/form-data; boundary=c40cf424beg7650b --c40cf424beg7650b Content-Disposition: form-data; name="file"; filename="my_csv.csv" Content-Type: application/octet-stream 56.5770 32.5669 ... 30.9038 20.4441 --c40cf424beg7650b-- </code></pre> <p>The file should contain 8760 individual entries, which I currently have stored in a dataframe. I was wondering if someone knowns how I could pass this DataFrame in a aiohttp.ClientSession.put() call. </p> <p>Many thanks in advance! </p>
<p>I do not know what you have tried in terms of your code. But here is an example of uploading a file using aiohttp.</p> <p>example:</p> <pre class="lang-py prettyprint-override"><code>session = aiohttp.ClientSession() url = '&lt;api-url&gt;' files = {'file': open('report.xls', 'rb')} await session.put(url, data=files) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to select first item's sub-value from a nested dictionary?<p>I have a python dictionary which is described below:</p> <pre><code>dict={ &quot;Moli&quot;: {&quot;Buy&quot;: 75, &quot;Sell&quot;: 53, &quot;Quantity&quot;: 300} &quot;Anna&quot;: &quot;Buy&quot;: 55, &quot;Sell&quot;: 83, &quot;Quantity&quot;: 154} &quot;Bob&quot;: {&quot;Buy&quot;: 25, &quot;Sell&quot;: 33, &quot;Quantity&quot;: 100} &quot;Annie&quot;: {&quot;Buy&quot;: 74, &quot;Sell&quot;: 83, &quot;Quantity&quot;: 96} } </code></pre> <p>I want to select or print first item's sub-value (i.e: <code>&quot;Buy&quot;: 75</code>) of this nested dictionary.</p> <p>If I am using this code:</p> <pre><code>print(trading_portfolio[(list(trading_portfolio.keys())[0])][&quot;Buy&quot;]) </code></pre> <p>I'm getting error like this:</p> <pre><code>select first item from this nested dictionary builtins.KeyError: &quot;Buy&quot; </code></pre>
<p>you can try this code and if it not meet your expectation please ping me your exact query....</p> <pre><code>trading_portfolio={ &quot;Moli&quot;: {&quot;Buy&quot;: 75, &quot;Sell&quot;: 53, &quot;Quantity&quot;: 300}, &quot;Anna&quot;: {&quot;Buy&quot;: 55, &quot;Sell&quot;: 83, &quot;Quantity&quot;: 154}, &quot;Bob&quot;: {&quot;Buy&quot;: 25, &quot;Sell&quot;: 33, &quot;Quantity&quot;: 100}, &quot;Annie&quot;: {&quot;Buy&quot;: 74, &quot;Sell&quot;: 83, &quot;Quantity&quot;: 96} } print(trading_portfolio[(list(trading_portfolio.keys())[0])][&quot;Buy&quot;]) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Replacing NaN values in a column from a second column<p>I would like to replace <code>NaN</code> values in <code>Target</code> with the corresponding <code>Node</code> value. My data is:</p> <pre><code> Node Target Color node1 node7 Red node1 node9 Red node3 node5 Green node1 node3 Red node3 node1 Red node5 NaN Yellow </code></pre> <p>I would need to have:</p> <pre><code> Node Target Color node1 node7 Red node1 node9 Red node3 node5 Green node1 node3 Red node3 node1 Red node5 node5 Yellow # here the replacement </code></pre> <p>I think that a possible solution could be using an if statement to check if a node has <code>Target</code> equal to NaN: if yes, then it would be possible to assign itself as target.</p>
<p>Yes, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><strong><code>df.fillna(value, ...)</code></strong></a> will allow the <strong><code>value</code> (replacement) arg to be a Series (column)</strong>, not just a constant:</p> <pre><code>df['Target'] = df['Target'].fillna(df['Node']) </code></pre> <p>Note this is better than if...else logic because it does one vectorized assignment to the entire dataframe, as the testcase below shows.</p> <hr /> <ol start="2"> <li>Alternative, if <code>df.fillna()</code> hadn't allowed us to do this:</li> </ol> <p>You could also use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>df.where()</code></a> on your column of interest, where the <strong><code>df.where(... other)</code></strong> arg is your replacement column, <code>df['Node']</code>:</p> <pre><code>df['Target'] = df['Target'].where(df['Target'].notna(), df['Node']) </code></pre> <p>Note also how we use logical indexing, using <code>df['Target'].notna()</code> to get us a mask/ logical vector of rows where Target is/isn't NA.</p> <p>Better testcase:</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; Node Target Color node1 node7 Red node1 node9 Red node2 NaN Brown node3 node5 Green node1 node3 Red node3 node1 Red node5 NaN Yellow&quot;&quot;&quot; df = pd.read_csv(StringIO(df), sep=r'\s+') </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python timezone determination and manipulation with tzwhere produce objects rather than datetime64s in some situations<p>I have millions of rows containing a UTC datetime64 with timezone information and Latitude/Longitude pairs. For each row I need to know the local timezone and create a column containing the local time. To do this I use the tzwhere package.</p> <p>A simple data set that illustrates the problem:</p> <pre><code>TimeUTC,Latitude,Longitude 2021-10-11 12:16:00+00:00,42.289723,-71.031715 2021-10-11 12:16:00+00:00,0,0 </code></pre> <p>The function I use to get the timezone and then create the local time value</p> <pre><code>def tz_from_location(row, tz): # Hardcoded in an effort to circumvent the problem. The returned value is still # an object, even though row.TimeUTC is a datetime64 if (row.Latitude == 0) &amp; (row.Longitude == 0): print (&quot;0,0&quot;) ret_val = row.TimeUTC.tz_convert('UTC') return (row.TimeUTC) try: # forceTZ=True tells it to find the nearest timezone for places without one tzname = tz.tzNameAt(row.Latitude, row.Longitude, forceTZ=True) if (tzname == 'uninhabited'): return(row.TimeUTC) ret_val = row.TimeUTC.tz_convert(tzname) # ret_val = ret_val.to_pydatetime() except Exception as e: print(f'tz_from_location - Latitude: {row.Latitude} Longitude: {row.Longitude}') print(f'Error {e}') exit(-1) return(ret_val) </code></pre> <p>Call the function as follows:</p> <pre><code>from tzwhere import tzwhere from datetime import datetime bug = pd.read_csv('./foo.csv') # Initialize tzwhere tz = tzwhere.tzwhere(forceTZ=True) # Create the UTC column bug['TimeUTC'] = bug['TimeUTC'].astype('datetime64[ns]') # The original data comes in with a timezone that is of the local computer, not # the location. Turn that into UTC bug['TimeUTC'] = bug['TimeUTC'].dt.tz_localize('US/Eastern', ambiguous='NaT', nonexistent='shift_forward') # Now call the function bug['TimeLocal'] = bug.apply(geospatial.tz_from_location, tz=tz, axis=1) # We are putting this into PostgreSQL. If you try to put a TZ aware datetime # in it will automatically convert it to UTC. So, we need to make this value # naive and then upload it bug['TimeLocal'] = bug['TimeLocal'].dt.tz_localize(None, ambiguous='infer') </code></pre> <p>That last line throws an error on the row with 0,0 but not on any other rows.</p> <pre><code>--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /var/folders/8d/jp8b0rbx5rq0l8p8cnbb5k_r0000gn/T/ipykernel_49416/4161114700.py in &lt;module&gt; 4 bug['TimeUTC'] = bug['TimeUTC'].dt.tz_localize('US/Eastern', ambiguous='NaT', nonexistent='shift_forward') 5 bug['TimeLocal'] = bug.apply(geospatial.tz_from_location, tz=tz, axis=1) ----&gt; 6 bug['TimeLocal'] = bug['TimeLocal'].dt.tz_localize(None, ambiguous='infer') ~/miniforge3/envs/a50-dev/lib/python3.9/site-packages/pandas/core/generic.py in __getattr__(self, name) 5459 or name in self._accessors 5460 ): -&gt; 5461 return object.__getattribute__(self, name) 5462 else: 5463 if self._info_axis._can_hold_identifiers_and_holds_name(name): ~/miniforge3/envs/a50-dev/lib/python3.9/site-packages/pandas/core/accessor.py in __get__(self, obj, cls) 178 # we're accessing the attribute of the class, i.e., Dataset.geo 179 return self._accessor --&gt; 180 accessor_obj = self._accessor(obj) 181 # Replace the property with the accessor object. Inspired by: 182 # https://www.pydanny.com/cached-property.html ~/miniforge3/envs/a50-dev/lib/python3.9/site-packages/pandas/core/indexes/accessors.py in __new__(cls, data) 492 return PeriodProperties(data, orig) 493 --&gt; 494 raise AttributeError(&quot;Can only use .dt accessor with datetimelike values&quot;) AttributeError: Can only use .dt accessor with datetimelike values </code></pre> <p>This is because the first row contains a datetime64 but the second row is an object.</p> <p>Here is the TimeUTC value before the call:</p> <pre><code>bug.TimeUTC 0 2021-10-11 12:16:00-04:00 1 2021-10-11 12:16:00-04:00 Name: TimeUTC, dtype: datetime64[ns, US/Eastern] </code></pre> <p>Here is the dataframe with TimeLocal added:</p> <pre><code>bug.TimeLocal 0 2021-10-11 12:16:00-04:00 1 2021-10-11 12:16:00-04:00 Name: TimeLocal, dtype: object </code></pre> <p>If you look at individual rows the first one is correct but the second one is an object.</p> <p>All of my efforts to return something that doesn't appear as an object for 0,0 rows have failed. I'm sure I'm missing something simple.</p>
<p>Here's some suggestions; given the example DataFrame</p> <pre><code> TimeUTC Latitude Longitude 0 2021-10-11 12:16:00+00:00 42.289723 -71.031715 1 2021-10-11 12:16:00+00:00 0.000000 0.000000 </code></pre> <p>make sure to parse datetime column to datetime data type:</p> <pre><code>df['TimeUTC'] = pd.to_datetime(df['TimeUTC']) </code></pre> <p>Then, you can refactor the function that derives the tz from lat/long for example like</p> <pre><code>from timezonefinder import TimezoneFinder def tz_from_location(row, _tf=TimezoneFinder()): # if lat/lon aren't specified, we just want the existing name (e.g. UTC) if (row.Latitude == 0) &amp; (row.Longitude == 0): return row.TimeUTC.tzname() # otherwise, try to find tz name tzname = _tf.timezone_at(lng=row.Longitude, lat=row.Latitude) if tzname: # return the name if it is not None return tzname return row.TimeUTC.tzname() # else return existing name </code></pre> <p>I'd suggest using <code>timezonefinder</code> since I found it to be more efficient an reliable - <a href="https://timezonefinder.readthedocs.io/en/latest/" rel="nofollow noreferrer">docs</a>, <a href="https://github.com/jannikmi/timezonefinder" rel="nofollow noreferrer">github</a>.</p> <p>Now you can easily apply &amp; create a column converted to tz:</p> <pre><code>df['TimeLocal'] = df.apply(lambda row: row['TimeUTC'].tz_convert(tz_from_location(row)), axis=1) </code></pre> <p>giving you</p> <pre><code> TimeUTC Latitude Longitude TimeLocal 0 2021-10-11 12:16:00+00:00 42.289723 -71.031715 2021-10-11 08:16:00-04:00 1 2021-10-11 12:16:00+00:00 0.000000 0.000000 2021-10-11 12:16:00+00:00 </code></pre> <pre><code>df['TimeLocal'].iloc[0] Out[2]: Timestamp('2021-10-11 08:16:00-0400', tz='America/New_York') df['TimeLocal'].iloc[1] Out[3]: Timestamp('2021-10-11 12:16:00+0000', tz='UTC') </code></pre> <p><em><strong>(!) But...</strong></em> since you have mixed time zones in your <code>TimeLocal</code> column, the <em><strong>data type of the whole Series will be <code>object</code></strong></em> - no way around that, that's how pandas datetime handles mixed time zones in one Series.</p> <hr /> <p><em><strong>Addendum</strong></em></p> <p>If we also want a column with the time zone name in one go, we can make the function return a tuple and use expand in the call to apply:</p> <pre><code>def convert_to_location_tz(row, _tf=TimezoneFinder()): # if lat/lon aren't specified, we just want the existing name (e.g. UTC) if (row.Latitude == 0) &amp; (row.Longitude == 0): return (row.TimeUTC.tzname(), row.TimeUTC) # otherwise, try to find tz name tzname = _tf.timezone_at(lng=row.Longitude, lat=row.Latitude) if tzname: # return the name if it is not None return (tzname, row.TimeUTC.tz_convert(tzname)) return (row.TimeUTC.tzname(), row.TimeUTC) # else return existing name df[['tzname', 'TimeLocal']] = df.apply(lambda row: convert_to_location_tz(row), axis=1, result_type='expand') df[['tzname', 'TimeLocal']] Out[9]: tzname TimeLocal 0 America/New_York 2021-10-11 08:16:00-04:00 1 UTC 2021-10-11 12:16:00+00:00 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Unable to click on WebApp Element with Selenium due to dynamic iframe<p>I have the following external HTML for the blue &quot;Stampa fiscale&quot; button I am trying to click on within a private web app:</p> <pre><code>&lt;a id=&quot;cdgxo_Stafisc_image&quot; class=&quot;imageIconBox boxAzureCircle Stafisc_image_ctrl&quot; href=&quot;javascript:cdgxo. Stampa()&quot; target=&quot;_self&quot; title=&quot;Stampa fiscale modelli F24&quot;&gt;&lt;/a&gt; </code></pre> <p><a href="https://i.stack.imgur.com/SBehg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SBehg.png" alt="enter image description here" /></a></p> <p>I tried with:</p> <pre><code>element = driver.find_element_by_css_selector('[class=&quot;imageIconBox boxAzureCircle Stafisc_image_ctrl&quot;]').click() element = driver.find_element_by_xpath('//*[@id=&quot;cdgxo_Stafisc_image&quot;]') </code></pre> <p>But none of them seem to be working; namely, the following exceptions occur:</p> <pre><code>NoSuchElementException: Unable to locate element: [class=&quot;imageIconBox boxAzureCircle Stafisc_image_ctrl&quot;] </code></pre> <p>and:</p> <pre><code>NoSuchElementException: Unable to locate element: //*[@id=&quot;cdgxo_Stafisc_image&quot;] </code></pre> <p>In more detail, the aforementioned button is within a dynamic iframe, described as:</p> <pre><code>&lt;iframe spparentobjid=&quot;etiveixwbp_MyVersamenti_bvuza_container&quot; style=&quot;width: 100%; height: 100%;&quot; ps-stretch-height=&quot;&quot; name=&quot;../jsp/gsmd_container.jsp?containerCode=VERSAM&amp;amp;pTitle=Versamenti&quot; id=&quot;MyVersamenti_bvuza_iframe&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; src=&quot;../jsp/gsmd_container.jsp?containerCode=VERSAM&amp;amp;pTitle=Versamenti&quot; scrolling=&quot;no&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt; </code></pre> <p>Specifically, the id changes according to the word in bold <em>&quot;MyVersamenti_<strong>bvuza</strong>_iframe&quot;</em></p> <p>A workaround I've found to find the iframe of interest is the following:</p> <pre><code>html_page = driver.page_source.split(&quot; &quot;) hoi = [elem for elem in html_page if (&quot;MyVersamenti_&quot; in elem) &amp; (&quot;_iframe&quot; in elem)] iframe = hoi[0].split('&quot;')[1] </code></pre> <p>Is there an alternative (more pythonic) solution?</p>
<p>Switch to the iframe and then click the element.</p> <pre><code>iframe = driver.find_element_by_xpath(&quot;//iframe[contains(@id, 'MyVersamenti_')]&quot;) driver.switch_to.frame(iframe) driver.find_element_by_css_selector(&quot;a[title='Stampa fiscale modelli F24']&quot;).click() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Find corresponding rows with frequent itemsets<p>My dataset is an adjacency matrix comparable with customer buying information. An example toy dataset:</p> <pre><code>p = {'A': [0,1,0,1], 'B': [1,1,1,1], 'C': [0,0,1,1], 'D': [1,1,1,0]} df = pd.DataFrame(data=p) df </code></pre> <p>Now I am interested in the frequent itemset so I used an apriori fim:</p> <pre><code>from mlxtend.frequent_patterns import apriori frequent_itemsets = apriori(df, min_support=0.1, use_colnames=True) frequent_itemsets </code></pre> <p>Now we see that itemset (D,B) occurs in 75% of the dataset. But I am actually interested in which rows this itemset occurs since the index has some information (which customer bought these items).</p> <p>Shortly, I am curious how I could filter in my dataset to see which rows correspond with a specific itemset. Is there such a feature within this package/library. So that I could filter that itemset (D,B) occurs in row 0,1 and 2?</p>
<p>It doesn't appear that there's a direct way to do this via <code>apriori</code>. However, one way would be as follows:</p> <pre><code>from mlxtend.frequent_patterns import apriori frequent_itemsets = apriori(df, min_support=0.1, use_colnames=True) # lists of columns where value is 1 per row cols = df.dot(df.columns).map(set).values.tolist() # use sets to see which rows are a superset of the sets in cols set_itemsets = map(set,frequent_itemsets.itemsets.values.tolist()) frequent_itemsets['indices'] = [[ix for ix,j in enumerate(cols) if i.issubset(j)] for i in set_itemsets] </code></pre> <hr /> <pre><code>print(frequent_itemsets) support itemsets indices 0 0.50 (A) [1, 3] 1 1.00 (B) [0, 1, 2, 3] 2 0.50 (C) [2, 3] 3 0.75 (D) [0, 1, 2] 4 0.50 (A, B) [1, 3] 5 0.25 (A, C) [3] 6 0.25 (A, D) [1] 7 0.50 (C, B) [2, 3] 8 0.75 (B, D) [0, 1, 2] 9 0.25 (C, D) [2] 10 0.25 (A, B, C) [3] 11 0.25 (A, B, D) [1] 12 0.25 (C, B, D) [2] </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to map the values in first dataframe based on second dataframe?<p>I have two dataframes. The df1 is the main df and df2 is reference dataframe. The df1 look like this:</p> <pre><code>u1d Status: Partisipant status Country:Country from URL 122 2 4 123 4 11 124 1 14 </code></pre> <p>and df2 look like this which is a reference.</p> <p><a href="https://i.stack.imgur.com/y4x5b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y4x5b.png" alt="enter image description here"></a></p> <p>I want that in df1 my all values map to code for example in <strong>Status: Participant status</strong> 2 is Terminated so it should map in place of 2 as Terminated and all the other columns. I have about 2000 columns so i need also efficient way. </p>
<p>Possible solution is reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a>, add new columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a>:</p> <pre><code>df = (df1.melt('u1d', var_name='Variable_name', value_name='Value Code') .merge(df2, how='left') .pivot('u1d','Variable_name','Value Name')) </code></pre> <p>Another idea:</p> <pre><code>for c in df1.columns[1:]: s = df2[df2['Variable_name'].eq(c)].set_index('Value Code')['Value Name'] df1[c] = df1[c].map(s) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Dice outcome evaluation based on bias<p>I am trying to determine throw of dices on a bias condition, during implementing its code, i am facing this error (code and error):</p> <pre><code>from numpy import random def roll(N,bias): '''will return the dice outcome''' return random.choice(np.range(N),p=bias) &gt;&gt;N= 50 &gt;&gt;bias= (0.25, 0.2, 0.15, 0.15, 0.1, 0.25) &gt;&gt;roll(N,bias) # returns 50 outcomes of dice (1,3,4,5...) Error:--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-105-ac839882958b&gt; in &lt;module&gt; 1 N= 50 2 bias= (0.25, 0.2, 0.15, 0.15, 0.1, 0.25) ----&gt; 3 roll(N,bias) &lt;ipython-input-104-d4d7cbf35d08&gt; in roll(N, bias) 2 def roll(N,bias): 3 '''will return the dice outcome''' ----&gt; 4 return random.choice(np.range(N),p=bias) D:\anaconda\lib\site-packages\numpy\__init__.py in __getattr__(attr) 213 else: 214 raise AttributeError(&quot;module {!r} has no attribute &quot; --&gt; 215 &quot;{!r}&quot;.format(__name__, attr)) 216 217 def __dir__(): AttributeError: module 'numpy' has no attribute 'range' </code></pre> <p>The objective is to return a list of dice throw values based on bias. Can you tell me what is wrong with the code here?</p>
<p>Really?</p> <pre><code> return random.choice(np.arange(N),p=bias) </code></pre> <p><strong>Edit</strong><br /> I misunderstood the requirement. You want this to return the results of N rolls.</p> <pre><code>def roll(N,bias): return (random.choice(range(len(bias)),p=bias)+1 for _ in range(N)) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to read a .json file in pandas to export it as a readable .csv file<p>I have created a .json file by appending a number of json strings using a get request. My aim is to convert the appended .json file into a readable .csv file. The .json file has the following format:</p> <pre><code>[{ &quot;trades&quot;:[ { &quot;id&quot;: 20995465, &quot;unique_identifier&quot;: null, &quot;transaction_type&quot;: &quot;BUY&quot;, &quot;transaction_date&quot;: &quot;2016-11-08&quot;, &quot;symbol&quot;: &quot;RDSA&quot;, &quot;market&quot;: &quot;LSE&quot;, &quot;quantity&quot;: 10, &quot;price&quot;: 20.84, &quot;exchange_rate&quot;: 0.5525, &quot;brokerage&quot;: 3.619909502, &quot;brokerage_currency_code&quot;: &quot;GBP&quot;, &quot;value&quot;: 380.81, &quot;comments&quot;: null, &quot;portfolio_id&quot;: 293304, &quot;holding_id&quot;: 6258682, &quot;instrument_id&quot;: 32021, &quot;confirmed&quot;: true, &quot;links&quot;: { &quot;portfolio&quot;: &quot;https://api.sharesight.com/api/v3/portfolios/293304&quot; } } ], &quot;links&quot;:{ &quot;self&quot;:&quot;https://api.sharesight.com/api/v3/portfolios/2/trades&quot; } }, { &quot;trades&quot;:[ { &quot;id&quot;: 20995425, &quot;unique_identifier&quot;: null, &quot;transaction_type&quot;: &quot;BUY&quot;, &quot;transaction_date&quot;: &quot;2018-11-08&quot;, &quot;symbol&quot;: &quot;PDSA&quot;, &quot;market&quot;: &quot;LSE&quot;, &quot;quantity&quot;: 1, &quot;price&quot;: 2.84, &quot;exchange_rate&quot;: 0.25, &quot;brokerage&quot;: 7.619909502, &quot;brokerage_currency_code&quot;: &quot;GBP&quot;, &quot;value&quot;: 80.81, &quot;comments&quot;: null, &quot;portfolio_id&quot;: 293604, &quot;holding_id&quot;: 6258635, &quot;instrument_id&quot;: 32023, &quot;confirmed&quot;: true, &quot;links&quot;: { &quot;portfolio&quot;: &quot;https://api.sharesight.com/api/v3/portfolios/293604&quot; } } ], &quot;links&quot;:{ &quot;self&quot;:&quot;https://api.sharesight.com/api/v3/portfolios/2/trades&quot; } } ] </code></pre> <p><strong>My attempt</strong></p> <pre><code>client_id = 'ClientID' client_secret = 'ClientSecret' access_token_url='https://api.sharesight.com/oauth2/token' client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=access_token_url, client_id=client_id, client_secret=client_secret) access_token = token['access_token'] head = {'Authorization': f'Bearer {access_token}'} # Get the portfolios r = requests.get('https://api.sharesight.com/api/v2/portfolios.json', headers=head) # print(r) j = r.json() # print(j) rjs = [] for p in j['portfolios']: # print(p) name = p['name'] pid = p['id'] print(f'Retrieving {name} - {pid}') vurl = f'https://api.sharesight.com/api/v2/portfolios/{pid}/trades.json' r = requests.get(vurl, headers=head) rj = r.json() rjs.append(rj) with open('/Users/Filename.json', 'w') as json_file: json.dump(rjs, json_file) # Opening JSON file and loading the data # into the variable data with open('/Users/Filename.json') as json_file: data = json.load(json_file) trades_data = data['trades'] # now we will open a file for writing - create a blank .csv file data_file = open('/Users/Filename.csv', 'w') # create the csv writer object csv_writer = csv.writer(data_file) # Counter variable used for writing # headers to the CSV file count = 0 for emp in trades_data: if count == 0: # Writing headers of CSV file header = emp.keys() csv_writer.writerow(header) count += 1 # Writing data of CSV file csv_writer.writerow(emp.values()) data_file.close() </code></pre> <p><strong>Error Code</strong></p> <pre><code>trades_data = data['trades'] TypeError: list indices must be integers or slices, not str </code></pre> <p>I think I get this error because 'trades' is replicated twice in my .json string and thus might be viewed as a string. Is there a workaround around this issue? I'm new to python so would greatly appreciate your help!</p> <p><strong>Desired Output</strong></p> <p>A .csv file with the following structure:</p> <p><a href="https://i.stack.imgur.com/vlJPA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vlJPA.png" alt="enter image description here" /></a></p>
<p>Answer by @dsillman2000 <code>for entry in data: trades_data = entry['trades'] ... etc</code></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Create a loop to open subfolders within a folder read the json files and output as csv<p>I am trying to create a loop in python which will allow me to open a folder, iterate through the subfolders within it, read the json files and output them as a csv. Then repeat the loop for each subfolder.</p> <p>My directory looks like this:</p> <p>Main folder = &quot;Exports&quot;</p> <p>Subfolder = &quot;Folder1&quot; , &quot;Folder2&quot; etc..</p> <p>Files within subfolder = &quot;file1.json&quot; , &quot;file2.json&quot; etc...</p> <p>Currently I am running the following code within a subfolder (for example &quot;Folder1&quot;) to create an output file:</p> <pre><code>import pandas as pd import os path = os.getcwd() frame = pd.DataFrame() for filename in os.listdir(os.getcwd()): root, ext = os.path.splitext(filename) if ext == '.json': tmp_frame = pd.read_json(filename) frame = frame.append(tmp_frame, ignore_index=True) frame.to_csv(os.path.join(path + &quot;.csv&quot;)) </code></pre> <p>My question is how do I run that loop but within the <strong>main folder</strong> where it will open each subfolder, then run that loop and output the file as csv for each subfolder.</p> <p>Thanks</p>
<p>Lets try <code>pathlib</code> and <code>defaultdict</code> from the standard lib</p> <p>we can build a dictionary of subfolders as keys, and all the files as values within a list.</p> <pre><code>from pathlib import Path from collections import defaultdict your_path = 'target_directory' file_dict = defaultdict(list) for each_file in Path(p).rglob('*.csv'): # change this to `.json` file_dict[each_file.parent].append(each_file) print(file_dict) </code></pre> <p>your dictionary will be a list of Pathlib objects that will vaguely resemble this, the key is the sub folder (I've just printed the name here)</p> <pre><code>{Notebooks : [test.csv, test_file.csv, test_file_edited.csv] , test_csv : [File20200610.csv, File20201012 - Copy.csv, File20201012.csv] } </code></pre> <p>then we can just loop over the dictionary and save each object to your target folder.</p> <pre><code>for each_sub_folder,files in file_dict.items(): dfs = [] for each_file in files: j = pd.read_json(each_file) #your read method. dfs.append(j) # append to list. df = pd.concat(dfs) df.to_csv(Path(target_path).joinpath(each_sub_folder.name + '.csv'),index=False) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Assert Text Error, AssertionError: No text to speak<p>I'm working on a project that uses voice assistant to query information stored in my sql database but I keep getting this error. The voice assistant is able to display the instructions and commands but cannot query the information from mysql. Such that if you tell it to &quot;Show Databases&quot; it brings up the assertion error.</p> <pre><code>AssertionError Traceback (most recent call last) &lt;ipython-input-68-055b51b54c64&gt; in &lt;module&gt; 62 txt=query_engine(str(guess[&quot;transcription&quot;]) + &quot; Task Achieved successfuly !&quot;) 63 print(txt) ---&gt; 64 speak(txt) 65 else: 66 print(&quot;Sorry, I can't perform what you have said . Please try again! &quot;)#.format(word)) &lt;ipython-input-4-66497e4d6f75&gt; in speak(text) 1 def speak(text): ----&gt; 2 tts = gTTS(text=text, lang=&quot;en&quot;,slow = False) 3 filename = str(random.choice(list(text)))+str(random.randint(1,100))+&quot;.mp3&quot; 4 tts.save(filename) 5 playsound.playsound(filename) ~\anaconda3\lib\site-packages\gtts\tts.py in __init__(self, text, tld, lang, slow, lang_check, pre_processor_funcs, tokenizer_func) 132 133 # Text --&gt; 134 assert text, &quot;No text to speak&quot; 135 self.text = text 136 AssertionError: No text to speak </code></pre> <p>Any help will be greatly appreciated. I am using python and mysql</p> <pre><code>import os import time import playsound import speech_recognition as sr from gtts import gTTS import mysql.connector as sql import random import pandas as pd def speak(text): tts = gTTS(text=text, lang=&quot;en&quot;,slow = False) filename = str(random.choice(list(text)))+str(random.randint(1,100))+&quot;.mp3&quot; tts.save(filename) playsound.playsound(filename) def connection(status): if status: resp=(&quot;Yes! your Connection Estabilished .\n&quot; &quot;Now go head to explore your data world ! \n&quot;) print(resp) speak(resp) print(commands) else: print(&quot;There is a problem with Data Server, I am unable to reach it.&quot;) speak(&quot;There is a problem with Data Server, I am unable to reach it.&quot;) exit(0) def db_connect(): try: db_connection = sql.connect(host='localhost', database='', user='root', password='ecell123') if db_connection: return(db_connection) else: # resp=&quot;Oh! sorry, something went Wrong! while estabilshing the Connection with Database&quot; # print(resp) # speak(resp) return(False) except: connection(False) def query_engine(query): def show_dbs(): if 'connect to database' not in recorded: speak('Please wait ! I am estabilishing secure connection to database !') print('Please wait ! I am estabilishing secure connection to database !') if db_connect() : recorded.append('connect to database') sce=db_connect() db_cursor = sce.cursor() db_cursor.execute('show databases') table_rows = db_cursor.fetchall() df = pd.DataFrame(table_rows) speak(&quot;Here is the list of Databases available in your store. &quot;) print(df) return df.values.tolist() else: if db_connect() is not False: #global db_connection sce=db_connect() db_cursor = sce.cursor() db_cursor.execute('show databases') table_rows = db_cursor.fetchall() df = pd.DataFrame(table_rows) speak(&quot;Here is the list of Databases available in your store. &quot;) print(df) return df.values.tolist() else: exit(0) def db_select(): rows=show_dbs() l=[] for i in range(len(rows)): l.append(rows[i][0]) #print(&quot;rows&quot;,l) print(&quot;Please Select any one of the given databases&quot;) speak(&quot;You can select any one of the given databases&quot;) return l def db_selected(): rows=db_select() for i in range(5): dbname=ask() #print(rows) if dbname in rows : print(&quot;Yes ,&quot;, dbname, &quot; Database is in given list !&quot;) speak(&quot;Yes ,&quot;+ dbname + &quot; Database is in given list !&quot;) break else: print(dbname, &quot; Not matched in given databases list&quot;) speak(dbname+ &quot; Not matched in given databases list&quot;) db_connection2 = sql.connect(host='localhost', database=dbname, user='root', password='ecell123') if db_connection2: print(&quot;{} Selected. Now you can access the TABLES&quot;.format(dbname)) speak(str(dbname)+ &quot; Selected . Now you can access the TABLES. &quot;) return db_connection2, dbname def show_tables(): conn,dtbname=db_selected() if conn is not False: #global db_connection db_cursor = conn.cursor() db_cursor.execute('show tables') table_rows1 = db_cursor.fetchall() df1 = pd.DataFrame(table_rows1) speak(&quot;Here is the list of Tables available in &quot;+ dtbname+ &quot; Database.&quot;) print(df1) return df1.values.tolist(),conn else: exit(0) if query == 'connect to database': if query not in recorded: if db_connect(): connection(True) recorded.append(query) else: print(' Hey! Cool. I already did that :)- ') speak(' Hey! Cool. I already did that !') if query == 'show databases': show_dbs() if query == 'select database': db_selected() if query == &quot;show tables&quot;: show_tables() if query =='show table data': table,conn=show_tables() tables=[] for i in range(len(table)): tables.append(table[i][0]) print(&quot;tables&quot;,tables) for i in range(5): tbname=ask() #print(rows) if tbname in tables : print(&quot;Right! &quot;, tbname, &quot; table is in given list&quot;) speak(&quot;Right! &quot;+tbname+&quot; Table is in given list&quot;) break else: print(tbname,&quot; Not matched in given Tables list&quot;) speak(tbname +&quot; Not matched in given Tables list&quot;) db_cursor = conn.cursor() qry= 'select * from '+tbname db_cursor.execute(qry) table_rows2 = db_cursor.fetchall() df2 = pd.DataFrame(table_rows2) speak(&quot;Here is the Data of the &quot;+ tbname+&quot; Table available in your database.&quot;) print(df2) return query def recognize_speech_from_mic(recognizer, microphone): &quot;&quot;&quot;Transcribe speech from recorded from `microphone`. Returns a dictionary with three keys: &quot;success&quot;: a boolean indicating whether or not the API request was successful &quot;error&quot;: `None` if no error occured, otherwise a string containing an error message if the API could not be reached or speech was unrecognizable &quot;transcription&quot;: `None` if speech could not be transcribed, otherwise a string containing the transcribed text &quot;&quot;&quot; # check that recognizer and microphone arguments are appropriate type if not isinstance(recognizer, sr.Recognizer): raise TypeError(&quot;`recognizer` must be `Recognizer` instance&quot;) if not isinstance(microphone, sr.Microphone): raise TypeError(&quot;`microphone` must be `Microphone` instance&quot;) # adjust the recognizer sensitivity to ambient noise and record audio # from the microphone with microphone as source: recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) # set up the response object response = { &quot;success&quot;: True, &quot;error&quot;: None, &quot;transcription&quot;: None } # try recognizing the speech in the recording # if a RequestError or UnknownValueError exception is caught, # update the response object accordingly try: response[&quot;transcription&quot;] = recognizer.recognize_google(audio) except sr.RequestError: # API was unreachable or unresponsive response[&quot;success&quot;] = False response[&quot;error&quot;] = &quot;API unavailable&quot; except sr.UnknownValueError: # speech was unintelligible response[&quot;error&quot;] = &quot;Unable to recognize speech&quot; return response instructions = ( &quot;Hi There! I am your Database Interaction Voice Assistant:\n&quot; &quot;I love to help you to get the data available in Database storages.\n&quot; &quot;I'm pleased to say, You can check the following example instructions.\n &quot; ) commands=( &quot; --- Connect to Database \n&quot; &quot; --- Show Databases \n&quot; &quot; --- Select Database [Name] \n&quot; &quot; --- Show TABLES \n&quot; &quot; --- Show TABLE Data \n&quot; &quot; --- Say abort or end or terminate to exit \n&quot; ) # show instructions and wait 2 seconds before starting the game print(instructions) print(commands) speak(instructions) db_connect() time.sleep(2) </code></pre> <pre><code>def ask () : recognizer1 = sr.Recognizer() microphone1 = sr.Microphone() for j in range(5): speak(&quot;I'm Listening ....&quot;) print(&quot;Speak : I'm Listening .... for Table/DB Name &quot;) guess = recognize_speech_from_mic(recognizer1, microphone1) if guess[&quot;transcription&quot;]: break if not guess[&quot;success&quot;]: break speak(&quot;Sorry. I didn't catch that. What did you say?&quot;) print(&quot;I didn't catch that. What did you say?\n&quot;) # if there was an error, stop the game if guess[&quot;error&quot;]: print(&quot;ERROR: {}&quot;.format(guess[&quot;error&quot;])) exit() # show the user the transcription print(&quot;You said: {}&quot;.format(guess[&quot;transcription&quot;])) return(guess['transcription'].lower()) if __name__ == &quot;__main__&quot;: recorded=[] queries=[ 'connect to database', &quot;show databases&quot;, &quot;select database&quot;, &quot;show tables&quot;, &quot;show table data&quot;] # create recognizer and mic instances recognizer = sr.Recognizer() microphone = sr.Microphone() while True: for j in range(5): speak(&quot;Please Speak. I'm Listening ....&quot;) print(&quot;Speak {}. I'm Listening .... &quot;.format(j+1)) guess = recognize_speech_from_mic(recognizer, microphone) if guess[&quot;transcription&quot;]: break if not guess[&quot;success&quot;]: break speak(&quot;Sorry. I didn't catch that. What did you say?&quot;) print(&quot;I didn't catch that. What did you say?\n&quot;) # if there was an error, stop the game if guess[&quot;error&quot;]: print(&quot;ERROR: {}&quot;.format(guess[&quot;error&quot;])) break # show the user the transcription print(&quot;You said: {}&quot;.format(guess[&quot;transcription&quot;])) # determine if guess is correct and if any attempts remain if guess[&quot;transcription&quot;] is not None: guess_is_correct = guess[&quot;transcription&quot;].lower() in queries # &quot;Connect to Database&quot;.lower() if guess[&quot;transcription&quot;].lower() in ('abort', 'end', 'terminate'): speak( &quot; Thanks for Using. Have a Good day !&quot;) print( &quot; Thanks for Using. Have a Good day !&quot;) break if guess_is_correct: txt=query_engine(guess[&quot;transcription&quot;]) print(txt) speak(txt) else: print(&quot;Sorry, I can't perform what you have said . Please try again! &quot;)#.format(word)) speak(&quot;Sorry, I can't perform what you have said . Please try again!&quot;) </code></pre>
<pre><code>if guess_is_correct: txt=query_engine(guess[&quot;transcription&quot;]) print(txt) speak(txt) </code></pre> <p>&quot;speak&quot; expects &quot;txt&quot; to be a string and not none. Check what does <code>query_engine(guess[&quot;transcription&quot;])</code> returns.</p> <p>If <code>print(guess[&quot;transcription&quot;]) prints &quot;show databases&quot;</code> then you're passing a list and not a string</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to take every possible n-size square from PNG file with PIL?<p>I want to load image, crop every possible square of given size(taken from user) from png file and print average RGB values for every given crop. Right now my code looks like this:</p> <pre><code>from PIL import Image from statistics import mean print(&quot;Input height: &quot;) crop_height = int(input()) print(&quot;Input width: &quot;) crop_width = int(input()) image = Image.open('daisy/5547758_eea9edfd54_n.jpg') print(image.size) image_height, image_width = image.size for y in range(0, image_height-crop_height): for x in range(0, image_width-crop_width): box = (x, y, crop_width, crop_height) print(box) cropped_image = image.crop(box) average_color = [round(mean(cropped_image.getdata(band))) for band in range(3)] print(&quot;RGB: &quot;, average_color) </code></pre> <p>I test this for 32x32 square. How can I do this ? Right now I get this error.</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\user\PycharmProjects\testMap\RGBAvg.py&quot;, line 19, in &lt;module&gt; average_color = [round(mean(cropped_image.getdata(band))) for band in range(3)] File &quot;C:\Users\Damian\PycharmProjects\testMap\RGBAvg.py&quot;, line 19, in &lt;listcomp&gt; average_color = [round(mean(cropped_image.getdata(band))) for band in range(3)] File &quot;C:\Users\user\AppData\Local\Programs\Python\Python39\lib\statistics.py&quot;, line 315, in mean raise StatisticsError('mean requires at least one data point') statistics.StatisticsError: mean requires at least one data point </code></pre>
<p>You are passing an empty list to <code>mean()</code> - get the list and check its length before passing to <code>mean()</code> and break out of your loop if it is empty.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How do I create a Django / Ajax redirect POST request on click?<p>I have a search function in my django app using ajax. It displays all results from a model.</p> <p>I want to limit the number of results the search returns on the page though, so when the queryset is so large the user should click on a 'see all results', rather than having heaps of results in the search box.</p> <p>I'm trying to do this by adding a HTML form below, but when I click on the href it is creating a GET request. I'm not totally sure what I need to fix up here to pass the data to the view and render the new page.</p> <pre><code>resultsBox.innerHTML += ` &lt;a href=&quot;${url} ${'results'}&quot; class=&quot;item&quot;&gt; &lt;form method=&quot;POST&quot; class=&quot;post-form&quot; input type=&quot;submit&quot; {% csrf_token %} &lt;action=&quot;${url} ${'results'}&quot;&gt; &lt;/form&gt; &lt;div class=&quot;row mt-2 mb-2&quot;&gt; &lt;div class=&quot;col-2&quot;&gt; img placeholder &lt;/div&gt; &lt;div class=&quot;col-10&quot;&gt; &lt;h5&gt;See all results for &quot;${quote}&quot;&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; ` ` </code></pre>
<p>You are wrapping the entire form in the <code>href</code>, you probably just want <code>See all results</code> to be the link?</p> <pre><code>resultsBox.innerHTML += ` &lt;form method=&quot;POST&quot; class=&quot;post-form&quot; input type=&quot;submit&quot; {% csrf_token %} &lt;action=&quot;${url} ${'results'}&quot;&gt; &lt;/form&gt; &lt;div class=&quot;row mt-2 mb-2&quot;&gt; &lt;div class=&quot;col-2&quot;&gt; img placeholder &lt;/div&gt; &lt;div class=&quot;col-10&quot;&gt; &lt;h5&gt; &lt;a href=&quot;${url} ${'results'}&quot; class=&quot;item&quot;&gt; See all results for &quot;${quote}&quot; &lt;/a&gt; &lt;/h5&gt; &lt;/div&gt; &lt;/div&gt;` </code></pre> <p>Alternatively (as noted in the comments below): to avoid a GET and have a POST instead, you want to submit a form, not follow a hyperlink: <a href="https://stackoverflow.com/questions/6799533/how-to-submit-a-form-with-javascript-by-clicking-a-link">How to submit a form with JavaScript by clicking a link?</a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Python: Compound Try/Except Blocks<p>I am working on a random word picker (used in the command line). The word picker itself works perfectly (I have a text file that has a bunch of words separated by spaces. The program will take the text file and make a list, the entries being everything in the list split with spaces).</p> <p>The next step I want to take is to be able to programmatically add words to the text file. I was able to get it to add whatever the user gives from input, but now I want to make sure that the word provided from the user doesn't have spaces, numbers, or uppercase letters.</p> <p>The first attempt I took looked like this:</p> <pre><code>def add_word(): word_to_add = input(&quot;Word to add: &quot;) valid_word = False if any(char.isdigit() for char in word_to_add): valid_word = False elif any(char.isupper() for char in word_to_add): valid word = False elif any((&quot; &quot; in chars) for chars in word_to_add): valid word = False else: valid word = True </code></pre> <p>I know this is a <em>super</em> inefficient method to use. That said, I'm trying to use Try/Except blocks to clean it up a little bit. I think I have an idea of how they work. Since I'm trying to test against multiple conditions, it would be something like</p> <pre><code>try: # code for no numbers try: # code for no uppercases try: # code for no spaces except: # blah blah blah else: # blah blah blah </code></pre> <p>Now, the dilemma I'm facing is how do I route each <code>try:</code> to a specific exception? What I mean is if there is an exception with the numbers, it would print something like &quot;your word cannot contain numbers! Try again.&quot; and the same deal for spaces and uppercases. Is there a way for me to make something like this:</p> <pre><code>try: # if there's a number go to exception A try: # if there's an uppercase go to exception B try: # if there's a space go to exception C exception a: # blah blah blah exception b: # blah blah blah exception c: # blah blah blah else: # blah blah blah </code></pre> <p>Would it end up being more efficient to just have multiple try/except blocks or a &quot;compound&quot; version like the above code?</p> <p>The reason I don't want to use if/elif/else is because sometimes it will still add the user input to the word list even if <code>valid_word</code> was false.</p> <p>Sorry that I can't be more specific here, I just don't really know how to articulate what I'm trying to accomplish here. Thanks in advance for any help</p>
<p>You can <code>raise</code> an exception inside a <code>try</code> block to immediately jump to a matching <code>except</code>, e.g.:</p> <pre><code>def add_word(): while True: word_to_add = input(&quot;Word to add: &quot;) try: if any(char.isdigit() for char in word_to_add): raise ValueError(&quot;Your word cannot contain numbers!&quot;) if any(char.isupper() for char in word_to_add): raise ValueError(&quot;Your word cannot contain capitals!&quot;) if &quot; &quot; in word_to_add: raise ValueError(&quot;Your word cannot contain spaces!&quot;) except ValueError as err: print(err) print(&quot;Try again&quot;) else: break # now do whatever you need to do to add word_to_add </code></pre> <p>But you could just as easily structure this as an <code>if/elif</code> block where each error condition is an <code>elif</code> and you <code>break</code> the loop in the <code>else</code>:</p> <pre><code>def add_word(): while True: word_to_add = input(&quot;Word to add: &quot;) if any(char.isdigit() for char in word_to_add): print(&quot;Your word cannot contain numbers!&quot;) elif any(char.isupper() for char in word_to_add): print(&quot;Your word cannot contain capitals!&quot;) elif &quot; &quot; in word_to_add: print(&quot;Your word cannot contain spaces!&quot;) else: break print(&quot;Try again!&quot;) # now do whatever you need to do to add word_to_add </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to pass argument in multiprocessing function and how to use multiprocessing list?<p>I am trying to use the multiprocessing in python. I've created a function that appends the value to the list passed to that function (<strong>check_m_process</strong>). I am trying to pass a list (<strong>m</strong>) which is defined outside. Since the normal list variable won't update itself outside the multiprocessing function, I've used a multiprocessing list to see changes made my function to the list.</p> <p>While executing the function it shows argument error as shown in the below output, instead of passing the argument.</p> <pre><code>import multiprocessing # common list m = multiprocessing.Manager().list() def check_m_process(m): print('m before - ',list(m)) for i in range(5): m = m + [i] print('m in function - ',list(m)) p1 = multiprocessing.Process(target = check_m_process, args=(m)) p1.start() p1.join() </code></pre> <p>OUTPUT ERROR:</p> <blockquote> <p>Process Process-37:</p> <p>Traceback (most recent call last):</p> <p>File &quot;/usr/lib/python2.7/multiprocessing/process.py&quot;, line 258, in _bootstrap</p> <p>self.run()</p> <p>File &quot;/usr/lib/python2.7/multiprocessing/process.py&quot;, line 114, in run</p> <p>self._target(*self._args, **self._kwargs)</p> <p>TypeError: check_m_process() takes exactly 1 argument (0 given)</p> </blockquote> <p>However, the above function does execute when executed without multiprocessing as <code>check_m_process([])</code>. But when I add some extra parameter, the function does execute as shown in the below output. I am confused about how an argument in multiprocessing function works or how it should actually pass like how to pass just a single argument with multiprocessing function.</p> <pre><code>def check_m_process(tmp_str,m): print('m before - ',list(m)) for i in range(5): m = m + [i] print('m in function - ',list(m)) p1 = multiprocessing.Process(target = check_m_process, args=('',m)) p1.start() p1.join() </code></pre> <p>OUTPUT:</p> <blockquote> <p>('m before - ', [])</p> <p>('m in function - ', [0, 1, 2, 3, 4])</p> </blockquote> <p>So after the execution of the function, I was hoping the list defined (<strong>m</strong>) must have updated now after function execution as per the shown above output.</p> <pre><code>print('m outside function - ',list(m)) </code></pre> <p>OUTPUT:</p> <blockquote> <p>('m outside function - ', [])</p> </blockquote> <p>But after printing the value of list <strong>m</strong>, it shows empty instead of defining the variable as a multiprocessing list in the beginning.</p> <p>Can someone help me with how to pass a single parameter in the multiprocessing function and how to use the common list throughout the multiprocessing function? Or is there any other way to deal with it?</p>
<p>For your first problem, you need to pass <code>(m,)</code> at the argument (note the trailing comma). That is the syntax required to create a single-element tuple in Python. When you just surround a single item with parenthesis, no tuple is created.</p> <p>For your second problem, you need to just append items to the <code>multiprocessing.Manager().list()</code>, instead of re-assigning the variable repeatedly:</p> <pre class="lang-py prettyprint-override"><code>for i in range(5): m.append(i) </code></pre> <p>The way you're currently doing it is actually creating a regular Python list, and assigning <code>m</code> to that, not updating your <code>multiprocessing</code> list</p> <pre><code>&gt;&gt;&gt; i = multiprocessing.Manager().list() &gt;&gt;&gt; i &lt;ListProxy object, typeid 'list' at 0x7fa18483b590&gt; &gt;&gt;&gt; i = i + ['a'] &gt;&gt;&gt; i ['a'] </code></pre> <p>Notice how <code>i</code> is no longer a <code>ListProxy</code> after I concatenate it with <code>['a']</code>, it's just a regular <code>list</code>. Using <code>append</code> avoids this:</p> <pre><code>&gt;&gt;&gt; i = multiprocessing.Manager().list() &gt;&gt;&gt; i &lt;ListProxy object, typeid 'list' at 0x7fa18483b6d0&gt; &gt;&gt;&gt; i.append('a') &gt;&gt;&gt; i &lt;ListProxy object, typeid 'list' at 0x7fa18483b6d0&gt; &gt;&gt;&gt; str(i) "['a']" </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to plot 2x2 confusion matrix with predictions in rows an real values in columns?<p>I know that we can plot a confusion matrix with sklearn using the following sample code.</p> <pre><code>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt y_true = [1, 0, 1, 1, 0, 1] y_pred = [0, 0, 1, 1, 0, 1] print(f'y_true: {y_true}') print(f'y_pred: {y_pred}\n') cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/ZP6RC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZP6RC.png" alt="enter image description here" /></a></p> <p>What we have:</p> <pre><code>TN | FP FN | TP </code></pre> <p>But I want the prediction label placed in a row or y-axis and the true or real value label in a column or x-axis. How can I plot this using Python?</p> <p>What I want:</p> <pre><code>TP | FP FN | TN </code></pre>
<p>(1) Here is one way of reversing TP/TN.</p> <h4>Code</h4> <pre><code>&quot;&quot;&quot; Reverse True and Prediction labels References: https://github.com/scikit-learn/scikit-learn/blob/0d378913b/sklearn/metrics/_plot/confusion_matrix.py https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ConfusionMatrixDisplay.html &quot;&quot;&quot; from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt y_true = [1, 0, 1, 1, 0, 1] y_pred = [0, 0, 1, 1, 0, 1] print(f'y_true: {y_true}') print(f'y_pred: {y_pred}\n') # Normal print('Normal') cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm) disp.plot() plt.savefig('normal.png') plt.show() # Reverse TP and TN print('Reverse TP and TN') cm = confusion_matrix(y_pred, y_true, labels=[1, 0]) # reverse true/pred and label values print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[1, 0]) # reverse display labels dp = disp.plot() dp.ax_.set(ylabel=&quot;My Prediction Label&quot;) # modify ylabel of ax_ attribute of plot dp.ax_.set(xlabel=&quot;My True Label&quot;) # modify xlabel of ax_ attribute of plot plt.savefig('reverse.png') plt.show() </code></pre> <h4>Output</h4> <pre><code>y_true: [1, 0, 1, 1, 0, 1] y_pred: [0, 0, 1, 1, 0, 1] Normal [[2 0] [1 3]] </code></pre> <p><a href="https://i.stack.imgur.com/BlmMF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BlmMF.png" alt="enter image description here" /></a></p> <pre><code>Reverse TP and TN [[3 0] [1 2]] </code></pre> <p><a href="https://i.stack.imgur.com/btrrp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/btrrp.png" alt="enter image description here" /></a></p> <p>(2) Another way is by swapping values and plot it with sns/matplotlib.</p> <h4>Code</h4> <pre><code>import seaborn as sns from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt y_true = [1, 0, 1, 1, 0, 1] y_pred = [0, 0, 1, 1, 0, 1] cm = confusion_matrix(y_true, y_pred) print(cm) cm_11 = cm[1][1] # backup value in cm[1][1] cm[1][1] = cm[0][0] # swap cm[0][0] = cm_11 # swap print(cm) ax = sns.heatmap(cm, annot=True) plt.yticks([1.5, 0.5], ['0', '1'], ha='right') plt.xticks([1.5, 0.5], ['0', '1'], ha='right') ax.set(xlabel='True Label', ylabel='Prediction Label') plt.savefig('reverse_tp_tn.png') plt.show() </code></pre> <h4>Output</h4> <pre><code>[[2 0] [1 3]] [[3 0] [1 2]] </code></pre> <p><a href="https://i.stack.imgur.com/4Z7TV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Z7TV.png" alt="enter image description here" /></a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Script becomes unresponsive during work, but continues to work after that and ends correctly<p>I'm implementing chess on Python (not the best choice however) using <code>pygame</code>. To find moves, I use the standard pair minimax + alpha pruning, minimax is a recursive search tree so program most of the time will do this part.</p> <pre><code>def minimax(self, depth, alpha, beta, is_maxing_white): # recursive tree exit condition # if board in cache if self.hash_board(depth, is_maxing_white) in self.board_caches: return self.board_caches[self.hash_board(depth, is_maxing_white)] # reached the desired depth if depth == 0: #return self.quiesce(alpha, beta) return self.evaluation() # if checkmate or stalemate if not [*self.board.get_all_ligal_moves(self.side)]: self.board_caches[self.hash_board( depth, is_maxing_white)] = self.evaluation() return self.board_caches[self.hash_board(depth, is_maxing_white)] best_score = -float(&quot;inf&quot;) if is_maxing_white else float(&quot;inf&quot;) for move in self.board.get_all_ligal_moves(self.side): self.board.push(move, self.side) local_score = self.minimax(depth - 1, alpha, beta, not is_maxing_white) self.board_caches[self.hash_board( depth - 1, not is_maxing_white)] = local_score if is_maxing_white: best_score = max(best_score, local_score) alpha = max(alpha, best_score) else: best_score = min(best_score, local_score) beta = min(beta, best_score) self.board.pop() if beta &lt;= alpha: print (&quot;pruning&quot;) break return best_score </code></pre> <p>The script returns the correct evaluation values and generally works but in moments when it does not answer any input can crash it. In which direction I should think and is it possible to somehow disable not responsible behavior?</p> <p>Windows 10, python 3.7, pygame 1.9</p>
<p>When a pygame program fails to call <code>pygame.event.get()</code> or <code>pygame.event.pump()</code> for a long time, the operating system thinks that the program is crashed.</p> <blockquote> <p>There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.</p> </blockquote> <p>From <a href="https://www.pygame.org/docs/ref/event.html#pygame.event.pump" rel="nofollow noreferrer">https://www.pygame.org/docs/ref/event.html#pygame.event.pump</a></p> <p>If you make sure to call <code>pygame.event.pump()</code> occasionally in the minimax function, the OS won't think your program has crashed. So you'll be able to click on the window without getting &quot;This window is not responding&quot; or anything.</p> <p>Hopefully this gets your problem, and it isn't something else.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: AttributeError: 'TfidfVectorizer' object has no attribute 'tranform'<p>I keep on getting this error for this code,</p> <p>x_predict = ['facebook.com', 'google.com/search=phish', 'wikipedia.com']</p> <p><strong>x_predict = vectorizer.tranform(x_predict)</strong></p> <p>y_predict = lgr.predict(x_predict)</p> <p>print(y_predict)</p>
<p>This is spelling error:</p> <p>Use <code>transform</code> instead of <code>tranform</code></p> <pre><code>x_predict = vectorizer.transform(x_predict) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: 502 error deploying flask application to elastic beanstalk using CLI<p>Running into an issue with deploying a very straight-forward Hello, World type flask application to AWS Elastic Beanstalk. I'm using the eb CLI tool, installed on Mac with brew and python 3. Some sample code below:</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/&lt;username&gt;') def hello_user(username): return f'Hello, {username}!' # run the app. if __name__ == &quot;__main__&quot;: # Setting debug to True enables debug output. This line should be # removed before deploying a production app. app.debug = True app.run(port=8000) </code></pre> <p>It runs locally as expected, and I can deploy it through the CLI, but when I go to access the application I'm getting a 502 Bad Gateway.</p> <p>I've tried:</p> <ul> <li>Accessing the application using both the URL from the console, and also <code>eb open</code>.</li> <li>Specifying the port 5000 (default flask) and 8000 at the end of the URL.</li> <li>Using <code>app.run()</code>, and <code>app.run(port=8000)</code> with no success.</li> </ul> <p>I've had a look through the documentation but couldn't find a fix. If folks have any suggestions or links they think would be helpful that'd be appreciated.</p>
<p>Your application should be called <code>application</code> not <code>app</code>.</p> <p>Below is the corrected <code>application.py</code> file. I <strong>verified</strong> that it works using <code>Python 3.7 running on 64bit Amazon Linux 2/3.1.0</code> platform:</p> <pre><code>from flask import Flask application = Flask(__name__) @application.route('/') def hello_world(): return 'Hello, World!' @application.route('/&lt;username&gt;') def hello_user(username): return f'Hello, {username}!' # run the app. if __name__ == &quot;__main__&quot;: # Setting debug to True enables debug output. This line should be # removed before deploying a production app. application.debug = True application.run(port=8000) </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to modify scatter-plot figure legend to show different formats for the same types of handles?<p>I am trying to modify the legend of a figure that contains two overlayed scatter plots. More specifically, I want two legend handles and labels: the first handle will contain multiple points (each colored differently), while the other handle consists of a single point. </p> <p><a href="https://stackoverflow.com/questions/49297599/why-doesnt-the-color-of-the-points-in-a-scatter-plot-match-the-color-of-the-poi/49301633#49301633">As per this related question</a>, I can modify the legend handle to show multiple points, each one being a different color.</p> <p><a href="https://stackoverflow.com/questions/23233290/setting-numpoints-in-matplotlib-legend-does-not-work/23233368#23233368">As per this similar question</a>, I am aware that I can change the number of points shown by a specified handle. However, this applies the change to all handles in the legend. Can it be applied to one handle only?</p> <p>My goal is to combine both approaches. Is there a way to do this?</p> <p><strong>In case it isn't clear, I would like to modify the embedded figure (see below) such that <code>Z vs X</code> handle shows only one-point next to the corresponding legend label, while leaving the <code>Y vs X</code> handle unchanged.</strong></p> <p>My failed attempt at producing such a figure is below:</p> <p><a href="https://i.stack.imgur.com/b1jrK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b1jrK.png" alt="Attempt at desired figure"></a></p> <p>To replicate this figure, one can run the code below:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerTuple, HandlerRegularPolyCollection class ScatterHandler(HandlerRegularPolyCollection): def update_prop(self, legend_handle, orig_handle, legend): """ """ legend._set_artist_props(legend_handle) legend_handle.set_clip_box(None) legend_handle.set_clip_path(None) def create_collection(self, orig_handle, sizes, offsets, transOffset): """ """ p = type(orig_handle)([orig_handle.get_paths()[0]], sizes=sizes, offsets=offsets, transOffset=transOffset, cmap=orig_handle.get_cmap(), norm=orig_handle.norm) a = orig_handle.get_array() if type(a) != type(None): p.set_array(np.linspace(a.min(), a.max(), len(offsets))) else: self._update_prop(p, orig_handle) return p x = np.arange(10) y = np.sin(x) z = np.cos(x) fig, ax = plt.subplots() hy = ax.scatter(x, y, cmap='plasma', c=y, label='Y vs X') hz = ax.scatter(x, z, color='k', label='Z vs X') ax.grid(color='k', linestyle=':', alpha=0.3) fig.subplots_adjust(bottom=0.2) handler_map = {type(hz) : ScatterHandler()} fig.legend(mode='expand', ncol=2, loc='lower center', handler_map=handler_map, scatterpoints=5) plt.show() plt.close(fig) </code></pre> <p>One solution that I do not like is to create two legends - one for <code>Z vs X</code> and one for <code>Y vs X</code>. But, my actual use case involves an optional number of handles (which can exceed two) and I would prefer not having to calculate the optimal width/height of each legend box. How else can this problem be approached?</p>
<p>This is a dirty trick and not an elegant solution, but you can set the sizes of other points for Z-X legend to 0. Just change your last two lines to the following.</p> <pre><code>leg = fig.legend(mode='expand', ncol=2, loc='lower center', handler_map=handler_map, scatterpoints=5) # The third dot of the second legend stays the same size, others are set to 0 leg.legendHandles[1].set_sizes([0,0,leg.legendHandles[1].get_sizes()[2],0,0]) </code></pre> <p>The result is as shown.</p> <p><a href="https://i.stack.imgur.com/adXNq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/adXNq.png" alt="enter image description here"></a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Get ID from workItem on Azure devops using python<p>I want to get the ID of specific workItems from multiple projects in Azure DevOPS.</p> <p>I try the below code</p> <pre><code>from azure.devops.connection import Connection from azure.devops.v5_1.work_item_tracking.models import Wiql from msrest.authentication import BasicAuthentication pat = 'my_PAT' organization = 'https://dev.azure.com/ORG/PROJ' credentials = BasicAuthentication('', pat) connection = Connection(base_url=organization, creds=credentials) wit_client = connection.clients.get_work_item_tracking_client() tp_query = Wiql(query=&quot;&quot;&quot; SELECT [System.Id] FROM workitems WHERE [System.Title] CONTAINS WORDS 'ESA-2525' &quot;&quot;&quot;) for plan in wit_client.query_by_wiql(tp_query).work_items: print(f&quot;Results for {plan.id}&quot;) </code></pre> <p>The error I get is Traceback (most recent call last):</p> <p>File &quot;C:\Users\P70252\source\repos\Azure_WIKI_PostUpgrades\Azure_WIKI_PostUpgrades\devops.py&quot;, line 15, in </p> <pre><code>wit_client = connection.clients.get_work_item_tracking_client() </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\released\client_factory.py&quot;, line 170, in get_work_item_tracking_client</p> <pre><code>return self._connection.get_client('azure.devops.released.work_item_tracking.work_item_tracking_client.WorkItemTrackingClient') </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\connection.py&quot;, line 45, in get_client</p> <pre><code>self._client_cache[client_type] = self._get_client_instance(client_class) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\connection.py&quot;, line 58, in _get_client_instance</p> <pre><code>url = self._get_url_for_client_instance(client_class) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\connection.py&quot;, line 70, in _get_url_for_client_instance</p> <pre><code>resource_areas = self._get_resource_areas() </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\connection.py&quot;, line 120, in _get_resource_areas</p> <pre><code>self._resource_areas = location_client.get_resource_areas() </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\v5_1\location\location_client.py&quot;, line 107, in get_resource_areas</p> <pre><code>query_parameters=query_parameters) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 77, in _send</p> <pre><code>query_parameters=query_parameters) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 119, in _create_request_message</p> <pre><code>location = self._get_organization_resource_location(location_id) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 160, in _get_organization_resource_location</p> <pre><code>return self._get_resource_location(self.normalized_url, location_id) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 172, in _get_resource_location</p> <pre><code>Client._locations_cache[url] = self._get_resource_locations(url, all_host_types=False) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 208, in _get_resource_locations</p> <pre><code>response = self._send_request(request, headers=headers) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 68, in _send_request</p> <pre><code>self._handle_error(request, response) </code></pre> <p>File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\azure\devops\client.py&quot;, line 291, in _handle_error</p> <pre><code>url=request.url)) </code></pre> <p>azure.devops.exceptions.AzureDevOpsAuthenticationError: The requested resource requires user authentication: <a href="https://dev.azure.com/ORG/PROJ/_apis" rel="nofollow noreferrer">https://dev.azure.com/ORG/PROJ/_apis</a></p> <p>Press any key to continue . . .</p> <p>The &quot;ESA-2525&quot; is a dummy workitem on which I will replace it with a variable so I can get the ID from different projects.</p> <p>The connection works, but the wiql does not. Any ideas?</p>
<p>Regarding the issue, please refer to the following code</p> <p>1.package</p> <pre><code>azure-devops==6.0.0b4 </code></pre> <ol start="2"> <li><p>Create full access personal access token</p> </li> <li><p>code</p> </li> </ol> <pre><code>pat = '&lt;token&gt;' organization = 'https://dev.azure.com/jim0375' credentials = BasicAuthentication('', pat) connection = Connection(base_url=organization, creds=credentials) wit_client = connection.clients.get_work_item_tracking_client() tp_query = Wiql( query=&quot;SELECT [System.Id] FROM WorkItems WHERE [System.Title] CONTAINS WORDS 'test'&quot;) for plan in wit_client.query_by_wiql(tp_query).work_items: print(f&quot;Results for {plan.id}&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/BHpAl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BHpAl.png" alt="enter image description here" /></a></p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Issue with configuration of cv2.VideoWriter and GStreamer<p>I am having trouble setting up a GStreamer pipeline to forward a video stream over UDP via OpenCV. I have a laptop, and an AGX Xavier connected to the same network. The idea is to forward the webcam video feed to AGX which will do some OpenCV optical flow estimation on the GPU (in Python), draw flow vectors on the original image and send it back to my laptop. Up until now, I can configure two pipelines. As a minimum example, I have made two bash scripts and a Python script that ideally would function as pass-through over OpenCV's VideoCapture and VideoWriter objects.</p> <p>servevideo.bash:</p> <pre><code>#!/bin/bash gst-launch-1.0 v4l2src device=[device-fd] \ ! video/x-raw, width=800, height=600, framerate=24/1 \ ! jpegenc ! rtpjpegpay ! rtpstreampay \ ! udpsink host=[destination-ip] port=12345 </code></pre> <p>receivevideo.bash:</p> <pre><code>#!/bin/bash gst-launch-1.0 -e udpsrc port=12344 \ ! application/x-rtp-stream,encoding-name=JPEG \ ! rtpstreamdepay ! rtpjpegdepay ! jpegdec \ ! autovideosink </code></pre> <p>If I run these two scripts on either the same computer or on two different computers on the network, it works fine. When I throw my Python script (listed below) in the mix, I start to experience issues. Ideally, I would run the bash scripts on my laptop with the intended setup in mind while running the Python script on my Jetson. I would then expect to see the webcam video feed at my laptop after taking a detour around the Jetson.</p> <p>webcam_passthrough.py:</p> <p>#!/usr/bin/python3.6</p> <pre><code>import cv2 video_in = cv2.VideoCapture(&quot;udpsrc port=12345 ! application/x-rtp-stream,encoding-name=JPEG ! rtpstreamdepay ! rtpjpegdepay ! jpegdec ! videoconvert ! appsink&quot;, cv2.CAP_GSTREAMER) video_out = cv2.VideoWriter(&quot;appsrc ! videoconvert ! jpegenc ! rtpjpegpay ! rtpstreampay ! udpsink host=[destination-ip] port=12344&quot;, cv2.CAP_GSTREAMER, 0, 24, (800, 600), True) while True: ret, frame = video_in.read() if not ret: break video_out.write(frame) cv2.imshow('Original', frame) key = cv2.waitKey(1) &amp; 0xff if key == 27: break cv2.destroyAllWindows() video_out.release() video_in.release() </code></pre> <p>With the following Python script, I can visualise the frames via <code>cv2.imshow</code> received from the pipeline set up by the <code>servevideo.bash</code> script. So I think my problem is connected to how I am setting up the VideoWriter <code>video_out</code> in OpenCV. I have verified my two bash scripts are working when I am relaying the webcam video feed between those two pipelines created, and I have verified that the <code>cv2.VideoCapture</code> receives the frames. I am no expert here, and my GStreamer knowledge is almost non-existent, so there might be several misunderstandings in my minimum example. It would be greatly appreciated if some of you could point out what I am missing here.</p> <p>I will also happily provide more information if something is unclear or missing.</p> <p><strong>EDIT:</strong> So it seems the intention of my minimum example was not clearly communicated.</p> <p>The three scripts provided as a minimum example serve to relay my webcam video feed from my laptop to the Jetson AGX Xavier who then relays the video-feed back to the laptop. The <code>servevideo.bash</code> creates a GStreamer pipeline on the laptop that uses v4l2 to grab frames from the camera and relay it on to a UDP socket. The <code>webcam_passthrough.py</code> runs on the Jetson where it &quot;connects&quot; to the UDP socket created by the pipeline running on the laptop. The Python script serves a passthrough which ideally will open a new UDP socket on another port and relay the frames back to the laptop. The <code>receivevideo.bash</code> creates yet another pipeline on the laptop for receiving the frames that were passed through the Python script at the Jetson. The second pipeline on the laptop is only utilised for visualisation purpose. Ideally, this minimum example shows the &quot;raw&quot; video feed from the camera connected to the laptop.</p> <p>The two bash scripts are working in isolation, both running locally on the laptop and running <code>receivevideo.bash</code> remotely on another computer.</p> <p>The <code>cv2.VideoCapture</code> configuration in the Python script also seems to work as I can visualise the frames (with <code>cv2.imshow</code>) received over the UDP socket provided by the <code>servevideo.bash</code> script. This is working locally and remotely as well. The part that is causing me some headache (I believe) is the configuration of <code>cv2.VideoWriter</code>; ideally, that should open a UDP socket which I can &quot;connect&quot; to via my <code>receivevideo.bash</code> script. I have tested this locally and remotely but to no avail.</p> <p>When I run <code>receivevideo.bash</code> to connect to the UDP socket provided by the Python script I get the following output:</p> <pre><code>Setting pipeline to PAUSED ... Pipeline is live and does not need PREROLL ... Setting pipeline to PLAYING ... New clock: GstSystemClock </code></pre> <p>This does not seem wrong to me, I have tried to run the different scripts with GST_DEBUG=3 which gave some warnings, but as the pipeline configurations are basically the same in the bash scripts and for the cv2 <code>VideoCapture</code> and <code>VideoWriter</code> I do not add much value to those warnings. As an example I have included one such warning below:</p> <pre><code>0:00:06.595120595 8962 0x25b8cf0 WARN rtpjpegpay gstrtpjpegpay.c:596:gst_rtp_jpeg_pay_read_sof:&lt;rtpjpegpay0&gt; warning: Invalid component </code></pre> <p>This warning is printed continuously running the Python script with <code>GST_DEBUG=3</code>. Running the <code>receivevideo.bash</code> with the same debug level gave:</p> <pre><code>Setting pipeline to PAUSED ... Pipeline is live and does not need PREROLL ... 0:00:00.013911480 9078 0x55be0899de80 FIXME videodecoder gstvideodecoder.c:933:gst_video_decoder_drain_out:&lt;jpegdec0&gt; Sub-class should implement drain() Setting pipeline to PLAYING ... New clock: GstSystemClock </code></pre> <p>I hope my intention is clearer now, and as I already pointed out I believe something is wrong with my <code>cv2.VideoWriter</code> in the Python script, but I am no expert and GStreamer is far from something that I use every day. Thus, I may have misunderstood something.</p> <p><strong>EDIT 2:</strong> So now I have tried to split the two pipelines into two separate processes as suggested by @abysslover. I still see the same result, and I still have no clue why that is. My current implementation of the Python script is listed below.</p> <p>webcam_passthrough.py:</p> <pre><code>#!/usr/bin/python3.6 import signal, cv2 from multiprocessing import Process, Pipe is_running = True def signal_handler(sig, frame): global is_running print(&quot;Program was interrupted - terminating ...&quot;) is_running = False def produce(pipe): global is_running video_in = cv2.VideoCapture(&quot;udpsrc port=12345 ! application/x-rtp-stream,encoding-name=JPEG ! rtpstreamdepay ! rtpjpegdepay ! jpegdec ! videoconvert ! appsink&quot;, cv2.CAP_GSTREAMER) while is_running: ret, frame = video_in.read() if not ret: break print(&quot;Receiving frame ...&quot;) pipe.send(frame) video_in.release() if __name__ == &quot;__main__&quot;: consumer_pipe, producer_pipe = Pipe() signal.signal(signal.SIGINT, signal_handler) producer = Process(target=produce, args=(producer_pipe,)) video_out = cv2.VideoWriter(&quot;appsrc ! videoconvert ! jpegenc ! rtpjpegpay ! rtpstreampay ! udpsink host=[destination-ip] port=12344&quot;, cv2.CAP_GSTREAMER, 0, 24, (800, 600), True) producer.start() while is_running: frame = consumer_pipe.recv() video_out.write(frame) print(&quot;Sending frame ...&quot;) video_out.release() producer.join() </code></pre> <p>The pipe that I have created between the two processes is providing a new frame as expected. When I try to listen to UDP port 12344 with <code>netcat</code>, I do not receive anything that is the same thing as before. I also have a hard time understanding how differentiating the pipelines are changing much as I would expect them to already run in different contexts. Still, I could be wrong concerning this assumption.</p>
<p>you were very close to the solution. The problem lies in the warning you yourself noticed <code>warning: Invalid component</code>. The problem is that rtp jpeg payloader gets stuck due to not supporting video format it is getting. Check <a href="http://gstreamer-devel.966125.n4.nabble.com/ximagesrc-to-jpegenc-td4669619.html" rel="nofollow noreferrer">this</a></p> <p>However I was blind and missed what you wrote and went full debug mode into the problem.</p> <p>So lets just keep the debug how-to for others or for similar problems:</p> <p>1, First debugging step - check with wireshark if the receiving machine is getting udp packets on port 12344. Nope it does not.</p> <p>2, Would this work without opencv stuff? Lets check with replacing opencv logic with some random processing - say rotation of video. Also eliminate appsrc/appsink to simplify.</p> <p>Then I used this:</p> <p><code>GST_DEBUG=3 gst-launch-1.0 udpsrc port=12345 ! application/x-rtp-stream,encoding-name=JPEG ! rtpstreamdepay ! rtpjpegdepay ! jpegdec ! videoconvert ! rotate angle=0.45 ! videoconvert ! jpegenc ! rtpjpegpay ! rtpstreampay ! queue ! udpsink host=[my ip] port=12344</code></p> <p>Hm now I get weird warnings like:</p> <pre><code>0:00:00.174424533 90722 0x55cb38841060 WARN rtpjpegpay gstrtpjpegpay.c:596:gst_rtp_jpeg_pay_read_sof:&lt;rtpjpegpay0&gt; warning: Invalid component WARNING: from element /GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0: Invalid component </code></pre> <p>3, Quick search yielded above mentioned GStreamer forum page.</p> <p>4, When I added <code>video/x-raw,format=I420</code> after videoconvert it started working and my second machine started getting the udp packets.</p> <p>5, So the solution to your problem is just limit the jpegenc to specific video format that the subsequent rtp payloader can handle:</p> <pre><code>#!/usr/bin/python3 import signal, cv2 from multiprocessing import Process, Pipe is_running = True def signal_handler(sig, frame): global is_running print(&quot;Program was interrupted - terminating ...&quot;) is_running = False def produce(pipe): global is_running video_in = cv2.VideoCapture(&quot;udpsrc port=12345 ! application/x-rtp-stream,encoding-name=JPEG ! rtpstreamdepay ! rtpjpegdepay ! jpegdec ! videoconvert ! appsink&quot;, cv2.CAP_GSTREAMER) while is_running: ret, frame = video_in.read() if not ret: break print(&quot;Receiving frame ...&quot;) pipe.send(frame) video_in.release() if __name__ == &quot;__main__&quot;: consumer_pipe, producer_pipe = Pipe() signal.signal(signal.SIGINT, signal_handler) producer = Process(target=produce, args=(producer_pipe,)) # the only edit is here, added video/x-raw capsfilter: &lt;------- video_out = cv2.VideoWriter(&quot;appsrc ! videoconvert ! video/x-raw,format=I420 ! jpegenc ! rtpjpegpay ! rtpstreampay ! udpsink host=[receiver ip] port=12344&quot;, cv2.CAP_GSTREAMER, 0, 24, (800, 600), True) producer.start() while is_running: frame = consumer_pipe.recv() rr = video_out.write(frame) print(&quot;Sending frame ...&quot;) print(rr) video_out.release() producer.join() </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Translation C99 code to Z3, subtle details<p>I am encountering some subtle details that I don't understand quite well. I am developing a tool to remove dead code, assuming the following example:</p> <pre><code>int main(){ if(1==0){ neverexecutes(); } } </code></pre> <p>I translate that to an AST (<a href="https://github.com/eliben/pycparser" rel="nofollow noreferrer">pycparser</a>), and when I encounter the if condition <code>1==0</code> I translate it to Z3 using the following method:</p> <pre><code>def evaluate_ast(self, node: c_ast.Node): &quot;&quot;&quot;Translates a c_ast.Node to a z3 predicate.&quot;&quot;&quot; typ = type(node) if typ == c_ast.BinaryOp: leftnode = self.evaluate_ast(node.left) rightnode = self.evaluate_ast(node.right) if node.op == '&amp;&amp;': return And(leftnode, rightnode) elif node.op == '||': return Or(leftnode, rightnode) elif node.op == '==': return leftnode == rightnode elif node.op == '&lt;': return leftnode &lt; rightnode elif node.op == '&lt;=': return leftnode &lt;= rightnode elif node.op == '&gt;': return leftnode &gt; rightnode elif node.op == '&gt;=': return leftnode &gt;= rightnode elif node.op == '!=': return leftnode != rightnode elif node.op == '/': return leftnode / rightnode elif node.op == '+': return leftnode + rightnode elif typ == c_ast.Assignment and node.op == '=': leftnode = self.evaluate_ast(node.lvalue) rightnode = self.evaluate_ast(node.rvalue) return leftnode == rightnode (...) </code></pre> <p>The <code>1==0</code> is translated to <code>k!0</code> and the solver answers <code>sat</code>, which is incorrect.</p> <p>If I change the treatment of C99 equality like this:</p> <pre><code>elif node.op == '==': return And(leftnode == rightnode) </code></pre> <p>it works, I assume I have the same problem with all binary operators. What am I missing here? A system with only <code>False</code> shouldn't be <code>unsat</code> ? I think the <code>k!0</code> is just a translation to some false value in Z3.</p> <p>I think this also graphics a little better my question:</p> <pre><code>&gt;&gt;&gt; from z3 import * &gt;&gt;&gt; s = Solver() &gt;&gt;&gt; s.add(False) &gt;&gt;&gt; s.check() unsat &gt;&gt;&gt; s.reset() &gt;&gt;&gt; s.add(1==0) &gt;&gt;&gt; s.check() unsat &gt;&gt;&gt; s.reset() &gt;&gt;&gt; s.add(Bool(1==0)) &gt;&gt;&gt; s.check() sat </code></pre> <p>What's the difference between <code>False</code>, <code>1==0</code> and <code>Bool(1==0)</code>?</p>
<p>The problem here is that <code>Bool</code> takes a name and makes a symbolic value out of it. You need to use <code>BoolVal</code> instead. In these cases the <code>sexpr</code> method is your friend for debugging purposes:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from z3 import * &gt;&gt;&gt; s = Solver() &gt;&gt;&gt; s.add(1==0) &gt;&gt;&gt; print(s.sexpr()) (assert false) </code></pre> <p>The above is OK, because the <code>add</code> method is smart to treat values correctly. You could've wrapped it around <code>BoolVal</code> for the same effect:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from z3 import * &gt;&gt;&gt; s = Solver() &gt;&gt;&gt; s.add(BoolVal(1==0)) &gt;&gt;&gt; print(s.sexpr()) (assert false) </code></pre> <p>But see what happens if you wrap it around <code>Bool</code>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from z3 import * &gt;&gt;&gt; s = Solver() &gt;&gt;&gt; s.add(Bool(1==0)) &gt;&gt;&gt; print(s.sexpr()) (declare-fun k!0 () Bool) (assert k!0) </code></pre> <p>And that is the essence of your problem. (Looks like z3 is coming up with an internal name <code>k!0</code> since <code>1==0</code> isn't a valid SMTLib name here. Which adds to the confusion.)</p> <p>Note that z3py has similar functions for <code>Int</code>/<code>IntVal</code>, <code>BitVec</code>/<code>BitVecVal</code>, <code>Real</code>/<code>RealVal</code> etc. that you have to be careful with similarly.</p> <p>This is one of the weakest points of z3py unfortunately: Due to Python's untyped nature, different functions try to interpret all sorts of inputs you can provide and they are sometimes inconsistent and it can be very hard to detect and debug such issues. If you suspect something is off printing <code>s.sexpr()</code> is your best friend. (A similar recent bug was reported <a href="https://stackoverflow.com/questions/62621990/checking-sat-using-check-with-assumptions-rises-attributeerror-bool-object/62625436?noredirect=1#comment110779871_62625436">here</a> and subsequently fixed, for instance.)</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Remove An Unique Item From Shopping-Cart In Django<p>I am trying to delete an item from the <code>cart</code> and I have some issues to do it. Here is the function:</p> <pre><code>def cart_contents(request): """ Ensures that the cart contents are available when rendering every page """ cart = request.session.get('cart', {}) cart_items = [] total = 0 destination_count = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) #remove = request.session.pop('cart', {id}) &lt;&lt;&lt;&lt;&lt;&lt; price = destination.price total += quantity * destination.price destination_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'destination': destination, 'price':price, 'remove':remove}) #cart_item will loop into the cart. return {'cart_items': cart_items, 'total': total, 'destination_count': destination_count} </code></pre> <p>Template.html</p> <pre><code>{% for item in cart_items %} {{ item.remove }} {% endfor %} </code></pre> <p>I've added a remove variable <code>remove = request.session.pop('cart', {id})</code> but if I use it in the code it will first not allow me to add more than one item and when I click the trash-can-button to remove the item it deletes all the <code>cart</code> in the session. The following image has two items in the card based by its id and the quantity as <code>{'id', quantity} = {'2': 1, '3': 2}</code>.</p> <p><a href="https://i.stack.imgur.com/LzNdD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LzNdD.png" alt="shopping cart"></a></p>
<p>I've found the answer. I made <code>cart</code> and <code>quantity</code> correlate each other. So, if you have three items in the cart you can delete/decrement until it reach 0 in the cart and if so, the cart will redirect to the destinations url.</p> <pre><code>def adjust_cart(request, id): """ Adjust the quantity of the specified product to the specified amount url for this function should be &lt;str:id&gt; not &lt;int:id&gt; - otherwise you need to add str() method for each dict representation. """ cart = request.session.get('cart', {}) quantity = cart[id] - 1 #decreases the cart quantity until deletes from cart if quantity &gt; 0: cart[id] = quantity else: cart.pop(id) request.session['cart'] = cart if not cart: #if all products be deleted from cart return to destination page return redirect(reverse('destination')) return redirect(reverse('view_cart')) </code></pre> <p>cart.html</p> <pre><code>{% for item in cart_items %} &lt;/tr&gt; ... &lt;td class="border-0 align-middle"&gt;&lt;a href="{% url 'adjust_cart' item.id%}" class="text-dark"&gt;&lt;i class="fa fa-trash"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>url.py</p> <pre><code>from django.urls import path from . import views urlpatterns = [ ... ... path('adjust/&lt;str:id&gt;/', views.adjust_cart, name="adjust_cart"), ] </code></pre> <p>Remembering that <code>cart_items</code> is a list with appended dictionary. Please if any acronym is wrong you can correct me. </p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to make query parameter list (multiple values) required at least one value in fastapi python framework<p>I'am using fastapi framework and i want to send multiple values using Query like this .</p> <pre class="lang-py prettyprint-override"><code>lst_name: Optional[List[str]] = Query(None). </code></pre> <p>so my question is how to make it required at least N values.</p>
<p>Simple, do not use <code>None</code> and <code>Optional</code>.</p> <pre class="lang-py prettyprint-override"><code>lst_name: List[str] = Query(...) </code></pre> <p>With <strong>Ellipsis</strong>: &quot;<code>...</code>&quot;, you can make a parameter required.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Extracting useful info from pandas column containing dict<pre><code>Category Data Age A1 30 {'Age1_Set': 25.6, 'WIndex': 343.3, 'Age2_Set': 22.6} A2 20 {'Age1_Set': 35.2, 'WIndex': 343.3, 'Age2_Set': 42.1} A3 20 {'Age1_Set': 26.5, 'WIndex': 343.3, 'Age2_Set': 11.1} </code></pre> <p>My pandas df is like above. Age should be the min of 'Age1_Set' and 'Age2_Set'. I am able to deal with this if Age was not a dict and rather three columns.</p> <p>My output is:</p> <pre><code>Category Data Age A1 30 22.6 A2 20 35.2 A3 20 11.1 </code></pre> <p>How can this be done?</p> <p>EDIT: I have another entry in original df</p> <pre><code>Category Data Age A4 20 </code></pre> <p>Age is null basically. How to deal with such case.</p>
<p>You can try:</p> <pre><code>df = pd.DataFrame({&quot;Category&quot;: [&quot;A1&quot;, &quot;A2&quot;, &quot;A3&quot;], &quot;Data&quot;: [30, 20, 20], &quot;Age&quot;: [{'Age1_Set': 25.6, 'WIndex': 343.3, 'Age2_Set': 22.6}, {'Age1_Set': 35.2, 'WIndex': 343.3, 'Age2_Set': 42.1}, {'Age1_Set': 26.5, 'WIndex': 343.3, 'Age2_Set': 11.1}]}) df[&quot;Min_Age&quot;] = [min(x[&quot;Age1_Set&quot;], x[&quot;Age2_Set&quot;]) for x in df.Age] print(df) </code></pre> <p>Result:</p> <pre><code> Category Data Age Min_Age 0 A1 30 {'Age1_Set': 25.6, 'WIndex': 343.3, 'Age2_Set'... 22.6 1 A2 20 {'Age1_Set': 35.2, 'WIndex': 343.3, 'Age2_Set'... 35.2 2 A3 20 {'Age1_Set': 26.5, 'WIndex': 343.3, 'Age2_Set'... 11.1 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: If then do: comparison two column in Python to create new column<p>I want to create new column and assign value using the logic below:</p> <p>if IN&gt;OUT then give value 1</p> <p>else give value 0</p> <p>This code below works fine but I would like to have something more &quot;readable&quot; like in other language, say SAS.</p> <pre><code>df = pd.DataFrame({'id': [1,2,3,4,5,6,7,8,9], 'In': [111, 100, 31, 1100, 12, 33, 21, 32, 33], 'Out': [24, 52, 34, 95, 98, 54, 32, 20, 16]}) print(df) conditions = [ (df['In'] &gt;= df['Out']), df['In'] &lt; df['Out']] choices = [df['In'].shift(1), 0] df['check'] = np.select(conditions, choices, default=np.nan) print(df) </code></pre>
<p>Since you only have two conditions, just use <code>np.where</code>:</p> <pre><code>df['check'] = np.where(df['In'] &gt;= df['Out'], df['In'].shift(), 0) </code></pre> <hr /> <pre><code>&gt;&gt;&gt; df id In Out check 0 1 111 24 NaN 1 2 100 52 111.0 2 3 31 34 0.0 3 4 1100 95 31.0 4 5 12 98 0.0 5 6 33 54 0.0 6 7 21 32 0.0 7 8 32 20 21.0 8 9 33 16 32.0 &gt;&gt;&gt; </code></pre> <p>Or if you have more, write a function:</p> <pre><code>def func(x): if x['In'] &gt;= x['Out']: if x.name: return df.loc[x.name - 1 , 'In'] else: return np.nan elif x['In'] &lt; x['Out']: return 0 return np.nan df['check'] = df.apply(func, axis=1) print(df) </code></pre> <p>Output:</p> <pre><code> id In Out check 0 1 111 24 NaN 1 2 100 52 111.0 2 3 31 34 0.0 3 4 1100 95 31.0 4 5 12 98 0.0 5 6 33 54 0.0 6 7 21 32 0.0 7 8 32 20 21.0 8 9 33 16 32.0 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to connect Python Selenium with Electron JS App<p>I'm building a simple automation app that will use Electron JS for good GUI and then Python Selenium to automate the task.</p> <p>I've just started when I'm trying to run electron JS app it shows that there is no module named as selenium.</p> <h2>Here is my python (demo.py)</h2> <pre><code> import time import re from selenium import webdriver import webbrowser import sys from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('https://example.com') userid = browser.find_element_by_id('user') time.sleep(1) userpass = browser.find_element_by_id('password') time.sleep(1) userid.send_keys('aafasdf@gmail.com') time.sleep(1) userpass.send_keys('#jlasdjf#') time.sleep(1) userid.send_keys(Keys.RETURN) userid.clear() browser.refresh() time.sleep(5) print('Hello from Python!') sys.stdout.flush() And the goes my index.js file - function some(){ var ps = require(&quot;python-shell&quot;) var path = require(&quot;path&quot;) var options = { scriptPath : path.join(__dirname,'../seleniumBro/'), pythonPath : '/usr/local/bin/python3.8' } ps.PythonShell.run('../../seleniumBro/demo.py', options, function (err, results) { if (err) throw err; // swal(results[0]); console.log(results[0]) }); } </code></pre> <p><a href="https://i.stack.imgur.com/1l6SK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1l6SK.png" alt="enter image description here" /></a></p> <p>When I run the app I get this error in console.</p> <pre><code>index.js:12 Uncaught Error: ModuleNotFoundError: No module named 'selenium' at PythonShell.parseError (/Users/rahul/Desktop/justDev/electronBro/hello-world/node_modules/python-shell/index.js:258:21) at terminateIfNeeded (/Users/rahul/Desktop/justDev/electronBro/hello-world/node_modules/python-shell/index.js:141:32) at ChildProcess.&lt;anonymous&gt; (/Users/rahul/Desktop/justDev/electronBro/hello-world/node_modules/python-shell/index.js:133:13) at ChildProcess.emit (events.js:223:5) at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12) ----- Python Traceback ----- File &quot;/Users/rahul/Desktop/justDev/seleniumBro/demo.py&quot;, line 3, in &lt;module&gt; from selenium import webdriver </code></pre> <p>I'm on MAC OS. And also new to this. Please help.</p>
<p>As per my views. You should go with Node.js as said by pguardio that Selenium is available for node too.</p>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Scraping from specific website has stopped working<p>So a couple of weeks ago I wrote this program which sucessfuly scraped some info on some online store, but now it has stopped working without me changing the code?</p> <p>Could this be something that has been changed within the website itself or is there something wrong with my code?</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://www.continente.pt/stores/continente/pt-pt/public/Pages/ProductDetail.aspx?ProductId=7104665(eCsf_RetekProductCatalog_MegastoreContinenteOnline_Continente)' res = requests.get(url) html_page = res.content soup = BeautifulSoup(html_page, 'html.parser') priceInfo = soup.find('div', class_='pricePerUnit').text priceInfo = priceInfo.replace('\n', '').replace('\r', '').replace(' ', '') productName = soup.find('div', class_='productTitle').text.replace('\n', ' ') productInfo = (soup.find('div', class_='productSubtitle').text + ', ' + soup.find('div', class_='productSubsubtitle').text) print('Nome do produto: ' + productName) print('Detalhes: ' + productInfo) print('Custo: ' + priceInfo) </code></pre> <p>I know for a fact that what im searching for does exist and the url is still valid, so what could be the issue? I separated the priceInfo into 2 lines because the error exists in the first declaration, since it returns a NoneType which has no text attribute</p>
<p>Solution is bit multistep.</p> <ol> <li>Try calling the page you want to scrape in Firefox once</li> <li>Use browser_cookie3 lib to extract cookies</li> <li>ensure they are not expired</li> <li>Use the cookies in requests.get(url, cookies=browser_cookie3.firefox())</li> <li>Use the headers as below</li> </ol> <p>Hope it works!! Happy scraping</p> <p>Have tried on my own and it works!!</p> <pre><code> headers = { 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-User': '?1', 'Sec-Fetch-Dest': 'document', 'Accept-Language': 'en-US,en;q=0.9,de;q=0.8', } </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: Numpy not producing desired sample variance value<p>I have a list for which I like to calculate <strong>sample variance</strong>. When I use <code>numpy.var</code> I get a different result from the function I defined. </p> <p>Can someone please help me understand what I am missing? </p> <pre class="lang-py prettyprint-override"><code>my_ls = [227, 222, 218, 217, 225, 218, 216, 229, 228, 221] def calc_mean(ls): sum_tmp = 0 for i in ls: sum_tmp = sum_tmp + i return round(sum_tmp/len(ls), 2) def calc_var(ls): tmp_mean = calc_mean(ls) tmp_sum = 0 for i in ls: tmp_sum = tmp_sum + ((i - tmp_mean)**2) return round(tmp_sum/(len(ls)-1), 2) calc_var(my_ls) &gt;&gt;&gt; 23.66 np.var(my_ls) &gt;&gt;&gt; 21.29 </code></pre> <p>23.66 is my desired value. </p>
<p>The denominator in the case of <code>np.var(my_ls)</code> by default is the total sample size (N).</p> <p>You can use the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html" rel="nofollow noreferrer"><strong>Delta Degrees of Freedom (ddof)</strong></a> parameter in <code>numpy</code> to show you're calculating the <strong>sample variance</strong> by setting <code>ddof = 1</code> for the mean degree of freedom. I.e. your denominator now becomes (N-1)</p> <pre class="lang-py prettyprint-override"><code>np.var(my_ls,ddof=1) &gt;&gt;&gt; 23.66 </code></pre>
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions. Stackoverflow question: How to call an if statement during a while loop in python<p>So as a python project I am making a game. So in this game, you enter a coordinate, and the computer says is it the correct one or not. Now the problem is there is a while loop and only after the while loop is done the if statement is called. But I want the if statement to be called after every loop in the while loop.</p> <p>This is the code</p> <pre><code>r = 0 while r&lt;15: hit = str(input(&quot;A1 A2 A3 A4 A5\n\nB1 B2 B3 B4 B5\n\nC1 C2 C3 C4 C5\n\nD1 D2 D3 D4 D5\n\nE1 E2 E3 E4 E5\nThis is the board. Pick any co- ordinate you want to fire on: &quot;)) if hit==&quot;A2&quot; or &quot;a2&quot;: print(&quot;You hit on target A2!&quot;) elif hit==&quot;B3&quot; or &quot;b3&quot;: print(&quot;You hit on target B3!&quot;) elif hit==&quot;C1&quot; or &quot;c1&quot;: print(&quot;You hit on target C1!&quot;) elif hit==&quot;C2&quot; or &quot;c2&quot;: print(&quot;You hit on target C2!&quot;) elif hit==&quot;D5&quot; or &quot;d5&quot;: print(&quot;You hit on target D5!&quot;) elif hit==&quot;E1&quot; or &quot;e1&quot;: print(&quot;You hit on target E1!&quot;) elif hit==&quot;E3&quot; or &quot;e3&quot;: print(&quot;You hit on target E3!&quot;) else: print(&quot;You missed!&quot;) r+=1 r = 0 </code></pre> <p>Can you please help me?</p>
<p>You just need to fix the indentation</p> <pre><code>r = 0 while r&lt;15: hit = str(input(&quot;&quot;&quot;A1 A2 A3 A4 A5\n\nB1 B2 B3 B4 B5\n\nC1 C2 C3 C4 C5\n\nD1 D2 D3 D4 D5\n\nE1 E2 E3 E4 E5\nThis is the board. Pick any co- ordinate you want to fire on: &quot;&quot;&quot;)) if hit in (&quot;A2&quot;, &quot;a2&quot;): print(&quot;You hit on target A2!&quot;) elif hit in (&quot;B2&quot;, &quot;b2&quot;): print(&quot;You hit on target B3!&quot;) elif hit in (&quot;C1&quot;, &quot;c1&quot;): print(&quot;You hit on target C1!&quot;) elif hit in (&quot;C2&quot;, &quot;c2&quot;): print(&quot;You hit on target C2!&quot;) elif hit in (&quot;D5&quot;,&quot;d5&quot;): print(&quot;You hit on target D5!&quot;) elif hit in (&quot;E1&quot;, &quot;e1&quot;): print(&quot;You hit on target E1!&quot;) elif hit in (&quot;E3&quot;, &quot;e3&quot;): print(&quot;You hit on target E3!&quot;) else: print(&quot;You missed!&quot;) r+=1 </code></pre> <p>The code that will run inside the loop is executed by the indentation so if your first line inside the loop is not indebted then the following code will not execute as part of the loop. And to check the <code>hit</code> value is equal to one of two options it will be better <code>in</code></p>