Questions tagged [python]

Python, a versatile and dynamic programming language, offers a multitude of functionalities. Known for its easy comprehensibility and efficient syntax enforcement, Python has gained popularity among developers. However, it's important to acknowledge that Python 2 is no longer supported since January 1, 2020. If you have questions regarding specific versions of Python, kindly include the [python-2.7] or [python-3.x] tag. Additionally, when utilizing alternate Python variations such as Jython or PyPy, or incorporating libraries like Pandas or NumPy, please remember to include relevant tags.

Obtaining only string values when looping through JSON information

JSON: { "status": "success", "data": { "9": { "1695056": { "id": "1695056", [...] }, "csevents": { "2807": { "id": "280 ...

Python Web3 Ganache - Error traceback encountered when attempting to build a transaction

Currently enrolled in the freeCodeCamp course via YouTube and encountered an issue while running the program. I am attempting to incorporate a transaction into Ganache and noticed activity in the Ganache logs as well. This is my first time posting, so feel ...

What causes map and filter to be less 'interactive' in Python 3.x compared to Python 2.x?

Back in the days, I used to code interactively with Python 2.7 using IDLE. It was simple - when I used functions like map(... some fn ..., ... some collection ...) or filter(... some fn ..., ... some collection ...), I would get the result as a collection ...

The journey in Python encounters a bump in the road with OpenCV errors

I recently completed the installation of OpenCV 3 on my Raspberry Pi 2 model B following this tutorial . I came across a code snippet that is compatible with my version of OpenCV and Python (3): from picamera.array import PiRGBArray from picamera import ...

Using Python to locate an element based on a specific type value in the preceding element's xpath

I've been struggling to figure out a way to select an element if there is a preceding element that contains a specific name. For example, consider the following HTML: <div> <input type="text" name="name"> </div> <div> < ...

Utilizing regular expressions or BeautifulSoup to locate a specific word or numerical value following a designated keyword

My goal is to extract data from Bloomberg in a structured format to create concise lists. The data structure on Bloomberg's website looks like this: <script type="text/javascript"> var ClientApp = require('app/ClientApp'); var clientApp = new Cl ...

Why does pygame.mixer.Sound only produce a popping sound before abruptly stopping?

My attempt to play sound using Python through pygame is resulting in a strange issue. When I run the program, all I hear is a popping noise and then it abruptly quits. The audio track I am trying to play is at least 20 seconds long, but for some reason the ...

One way to shuffle outcomes from two querysets in a Django template

Hey there! I'm interested in finding out how we can display results from two different querysets in a Django template. This is what my views.py looks like: def index(request): answers = Answer.objects.filter(user=request.user) questions = Questio ...

Dateutil - Your Trusted Source for Relative Date Calculation

Recently, I've been facing a challenge while attempting to parse relative dates like "today at 4:00", "tomorrow at 10:00", "yesterday at 8:00", etc. in Python using dateutil.parse. However, I wish to provide a specific "today" date to serve as a reference ...

Unpacking Key-Value Pairs in Python

I am developing a software program where I have a dictionary that contains only one key and one value. My goal is to assign the key to a variable named 'key' and the value to a variable named 'value.' Here is the relevant code snippet: ...

Python code: Simulate clicking on the next page without a specified link to follow using JavaScript or AJAX

I'm seeking aid from a kind-hearted individual. I require assistance in navigating to the next page on this particular site: . Here's my code: from selenium import webdriver url = 'https://www.xtip.co.uk/en/today/index.html' browser = webdriver.Chrome(' ...

Ways to interact with a button that toggles between states

I am working with a button that has both an enabled and disabled state. Enabled State: <button type="button" class="btt-download-csv site-toolbar-menu-button icon-download no-icon-margins ng-isolate-scope" title="Download CSV" rc-download-csv="" curren ...

A guide on extracting data from a Script element in an HTML file and saving it to a CSV file using Python Selenium

Looking for help with optimizing a Python script that extracts data from the Script tag on an HTML web page. The current output saved in a CSV file is not meeting my requirements: (1) the format is incorrect, and (2) there is unnecessary content included. ...

Comparing time across different time zones using Python

I need to schedule daily emails for users at 7am in their respective time zones. For instance, User 1 is in the America/Los_Angeles time zone, while Customer 2 is in America/New_York and would receive the email at 7am their local time, but it would be 4am ...

I need information on where to locate guides and tutorials for Mutagen in Python

After posing the question: How can I access album artwork using Python? I found myself feeling 'stuck'. I have searched extensively for documentation online but haven't been able to find any. Many responses suggest looking through the int ...

Allow SSL certificate using Marionette with Python's Splinter library in Firefox WebDriver

While utilizing Python Splinter with Firefox 47 and the new Marionette webdriver, I encounter a certificate error when trying to access a specific website. I attempted to resolve this issue by accepting SSL certificates using the following code: browser = ...

Steps to create a Runtime array and assign it a name from a predefined list

There's a list called list_1 = ["File_A","File_B","File_C","File_D"] I'm looking to execute a loop and create four arrays: File_A = np.array(0) File_B = np.array(0) File_C = np.array(0) File_D = np.arr ...

What is the process for converting JSON output into a Python data frame?

I have a JSON file that I need to convert into a Python dataframe: print(resp2) { "totalCount": 1, "nextPageKey": null, "result": [ { "metricId": "builtin:tech.generic.cpu.usage", ...

Encountering difficulties retrieving and displaying the data stored in my Firebase node

When examining the Firebase structure, it appears as follows: characters -Lt9nfslaIKgoe7E3SHT -LtA93jCQn-2Kmf4gP-S -LtK-Bk156abpROmhxgI ... in these keys booleans are saved from 1 - 64, true or false 1: true, ...

I am curious if it is possible to incorporate a personalized application into the Python AppOpener library

One issue that I've come across is that the App Opener library automatically scans and finds apps on the PC during the first run. But what if there are some apps that it doesn't recognize? For instance, I want to open the Winexp app that I downlo ...

Unable to load Environment Variables in ScrapingHub Configuration

Recently, I encountered a puzzling situation while deploying spiders on ScrapingHub. The spider itself functions properly, but I am facing challenges in changing the output feed based on whether the spider is running locally or on ScrapingHub. My goal is t ...

Determining if a function is being executed from a Jupyter notebook or elsewhere

As I work on learning coding for data science, I find myself switching back and forth between Spyder and Jupyter notebooks. I am exploring ways to determine whether a function is being called from one or the other so that I can deactivate certain parts of ...

A streamlined approach to tackling extensive if-elif chains for better performance

Currently, I am referencing a value obtained from an HTML form which corresponds to price ranges. For instance: 0 represents any price, 1 denotes $0 to $100, and so on. I can't help but feel that there must be a more Pythonic or efficient approach to hand ...

Can you explain the significance of the error message "EOFError: stream has been closed"?

Whenever I run my code, at some point PyScripter opens up another script and shows an "EOFError: stream has been closed" message. This is the snippet of code causing the issue: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt impor ...

Retrieving bounding boxes and category tags from the MS-COCO dataset

In my current project, I am using the MS-COCO dataset to work with images. My goal is to extract bounding boxes and labels for images containing backpacks (category ID: 27) and laptops (category ID: 73). These annotations will be stored in separate text fi ...

Issue encountered on Cloud Run: The container encountered an error while trying to initiate. It failed to start and establish connection on the designated port specified by the PORT environment variable

As a newcomer to asking questions on SO, I appreciate your patience. Despite the abundance of existing answers, none seem to solve my issue. I've been developing a Django web app and now need to deploy it for mobile access. My attempts to run it on Google ...

Getting superclasses ready in Python

Currently, I am in the process of learning Python. While working on a project involving creating a class for a colored square, I faced an issue with inheritance. My code works perfectly fine with composition but throws an error when I attempt to implement ...

What causes a SyntaxError to be thrown when running "pip install" within a Python environment?

When attempting to install a package using pip, an issue arises. Upon running pip install in the Python shell, a SyntaxError occurs. The error appears to be related to improper syntax. What could be causing this error? Moreover, how can one successfully ...

Invalid Label Error Encountered with Python Requests URL

When trying to access Shopify's API, I am using a URL format like this - https://apikey:password@hostname/admin/resource.xml For example, http://7ea7a2ff231f9f7:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4fd..." tar ...

Reportlab is unable to locate the _imaging module when using the production server

I'm encountering an issue while attempting to deploy a Django app on the production server. The error message reads: ImportError: The _imaging C module is not installed Interestingly, the application works perfectly fine when running on the development ...

How can recursive data be displayed in a template?

I am working with a model in Django that has a ForeignKey pointing to itself, and I need to display all the data from the database using lists and sublists: Below is my model definition: class Place(models.Model) name = models.CharField(max_length=1 ...

Is there a way to fetch values from a dataframe one day later, which are located one row below the largest values in a row of another dataframe of identical shape?

I am working with two data frames that share the same date index and column names. My objective is to identify the n largest values in each row of one dataframe, then cross-reference those values in the other dataframe one day later. The context here is f ...

Encountered a NoReverseMatch error in Django 1.10.2 stating that the reverse for 'django.contrib.auth.views.login' with empty arguments and keyword arguments was not found

Looking for help with a Python & Django error I'm encountering. Any guidance is appreciated. https://i.stack.imgur.com/4Cw94.png from django.shortcuts import render # Create your views here. # log/views.py from django.shortcuts import render from dja ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

Manipulating pandas Dataframe output based on different entries within a single column

Below is a representation of my dataset, DF. DF_Old = ID NER tID POS token R 1 B-ORG 1 NNP univesity "OrgBased_In+university of washington seismology lab.*wash" 1 I-ORG 1 IN of "OrgBased_In+university of washington seismology lab.*w ...

Can the function variables be dynamically updated with each call?

I am currently tackling an Ordinary Differential Equation (ODE) system using the solve_ivp function and I aim to modify the local variables within the function each time it is called by the solver. Specifically, I wish to update the Lagrange multipliers ...

Gradually increase the time in a dataframe column by the initial value of the column

I am facing a situation where I need to increment the timestamp of a particular column in my dataframe. Within the dataframe, there is a column that contains a series of area IDs along with a "waterDuration" column. My goal is to progressively add this d ...

What could be causing the error in sending private messages with Discord.py?

After hours of searching through various overflow posts, forums, and documentation, I am still unable to solve the issue I'm facing. I need help with sending an embed as a private message to a specific user in my function. Everything works fine except for ...

What is the method for obtaining a compilation of TestReports once a py.test execution has concluded?

Is there a way to collect a list of all tests (such as in the format of a py.test TestReport) at the conclusion of running all tests? I am aware that pytest_runtest_makereport accomplishes something similar, but only for an individual test. I am intereste ...

String insertion into the table is not allowed in Python

I was working on a coding project to create a dynamic updating table. The program is currently only allowing me to insert integers and not strings. Whenever I try to input strings, it returns an "operational error". I attempted to modify the datatype of th ...

Python regular expressions: eliminate specific HTML elements and their inner content

If I have a section of text that includes the following: <p><span class=love><p>miracle</p>...</span></p><br>love</br> And I need to eliminate the part: <span class=love><p>miracle</p>.. ...

The total squared difference calculated for a collection of lists containing individual lists

Looking for a way to calculate the sum of squared differences between two lists? Here's what I have: list = [[20.20458675 17.14946271 2.78568516 5.8363439 14.00318441 11.96825089] [ 3.89675236 9.99523907 13.0328716 18.10551237 22.11318234 -0.30 ...

Interacting with a button element using Selenium automation

I've been working on automating the job application process on the Indeed website using Selenium. However, I've encountered an issue where I am unable to select the 'Continue' button to move to the next page. Despite trying XPath, CSS selectors, and Class ...

A deep dive into the nuances of DP: Unlocking the

Examining the codes below, I implemented two different approaches to solve the problem (simple recursive and DP). Why is the DP method slower? Do you have any suggestions? #!/usr/local/bin/python2.7 # encoding: utf-8 Problem Statement: An array contains ...

Create a Python function that takes a list as input, iterates through each element, converts it to

When working with a Python list that requires double quotes around the strings in order to pass it to an API as a list of double quote strings, I encountered an issue. The data needed by the API: data = { "styles" : styleList } It worked when I manu ...

Is it possible to scrape using Python Beautiful Soup only when the text matches?

I am currently learning how to use beautiful soup by watching videos and trying examples. However, I am facing a challenge where the examples have well-structured HTML layouts and do not search for specific words anywhere. What I want to achieve is to prin ...

Python is not triggering the custom object_hook function in JSON parsing

I have created a custom hook in Python that successfully works when the input string is a valid dictionary, but it fails to work with a valid list. For example, [1,2] is a valid JSON format. However, when I pass this to json.loads along with my custom hoo ...

Issues with sv_ttk and pyinstaller

Hey everyone, I'm having trouble getting this code in .py to work when compiling it to .exe with PyInstaller, even with the --onefile option. #imports > from tkinter import * from tkinter import ttk import sv_ttk as sv #< imports #definitions ...

Uploading Multiple Files with Selenium using Python

I have been working on a multiple image upload feature and here is the code I am using: import selenium import time import selenium.common.exceptions import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriv ...

Is there a way to optimize the performance of scipy.integrate.quad?

Take a look at this code snippet: def disFunc(x,n): y = np.power(x, n-1)*np.exp(-x) return y def disFunc2(t,n,beta): y = integrate.quad(disFunc, a = 0, b = beta*t, args = (n)) return y[0] def disFunc3(func): y = np.vec ...

Setting up NEO4J graph database on your current Amazon EC2 instance

Currently, I have an adjacency list prepared for constructing a graph with 50,000 nodes and 100 million edges. My plan is to store this data in a graph database, specifically NEO4J. I am looking for guidance on how to download and install NEO4J for free ...

Error message: "The specified file could not be found in the

I am looking to integrate adb functions within a Python environment. When connecting adb in the terminal, everything seems to be working fine as seen below. $ adb --version Android Debug Bridge version 1.0.41 Version 31.0.3-7562133 Installed as /opt/homebr ...

What is the best way to create a grid made up of rectangles, allowing each rectangle to be easily referenced by its position, represented by a tuple of row and column, for future use

Here is a sample code snippet: from tkinter import * import numpy as np rows = 10 columns = 10 width, height = rows*18, columns*18 window = Tk() window.geometry(str(width)+"x"+str(height)) window.resizable(width=False, height=False) window.confi ...

The program encountered a problem while trying to access the CPU power usage for a specific node instance in the main program

I'm currently working on a Python script for my system monitoring project, and I need to display the PowerUsage. However, when trying to retrieve this information, I encountered an error message that reads <bound method Node.getCpuPowerUsage of <__ma ...

Utilizing a Python Script to Modify Sudo Permissions in a Linux File

I am trying to add text to a file that requires sudo permissions. I have this Python script here: import subprocess ssid= "testing" psk= "testing1234" p1 = subprocess.Popen(["wpa_passphrase", ssid, psk], stdout=subprocess.PIPE) p2 = subprocess.Popen(["su ...

Guide to making Python's virtual machine output a stack trace

I'm currently faced with an issue on a server built using Python that freezes unexpectedly, causing the logging to also cease. I am curious if there is a command similar to Java's "kill -3" signal in Python that could print out the current stacktrace for ...

What is the best way to change the color of text within a tkinter text widget?

Is there a way to change the color of specific parts of a tkinter text widget? Here's a snippet of my code for a chat application where I need to distinguish between the sender and the message: T = Text(window, bg="black", fg="white", font=("bold", 1 ...

Error: Selenium encountered an AttributeError stating that the type object 'By' does not contain the attribute 'id'

Currently, I am attempting to populate a dropdown form using Selenium. I have been trying to select the dropdown element based on its ID but encountered an error message stating: AttributeError: type object 'By' has no attribute 'id'. This error is being ...

Tips for efficiently scraping multiple hrefs within a webtable using Selenium

I am currently faced with the challenge of web scraping a website using Python and Selenium. The information I need is spread across different pages linked in the 'Application number' column. How can I programmatically click on each link, navigat ...

Removing a requirement from pip-check

A project written in pipenv includes the Trend Micro deepsecurity dependency. Previously, this was accessible on pypi but has since been removed by Trend. Now, users are required to download the SDK and manually install it, which involves unzipping the pac ...

Try implementing the functionality of MATLAB using Python code, or look for a comparable alternative

I have a project where I need to translate Matlab code into Python, but not at a very low level. The issue I'm facing is that I have the following lines of Matlab code: p = sobolset(problem_size, 'Skip', 1e4, 'Leap', 1e3); p = scramble(p, 'MatousekAffineOw ...

Tips for maintaining the active tab in Jquery even after the page is reloaded, especially for tabs that are constantly changing

$(document).ready(function(){ $('.scroll_nav li a').click(function(){ $('li a').removeClass("active_scroll"); $(this).addClass('active_scroll'); $('ul li .btn-br_all_gun').click(function(){ $('li a').removeClass("active_s ...

Using Pydantic to define models with both fixed and additional fields based on a Dict[str, OtherModel], mirroring the TypeScript [key: string] approach

Referencing a similar question, the objective is to construct a TypeScript interface that resembles the following: interface ExpandedModel { fixed: number; [key: string]: OtherModel; } However, it is necessary to validate the OtherModel, so using the ...

Encountering a problem with serializing data.Json, unable to dump the data

import json data={"name":"John","age":30,"cars": [{ "name":"Ford", "models":["Fiesta", "Focus", "Mustang" ] },{ "name":"BMW", "models":[ "320", "X3", "X5"] },{ "name":"Fiat", "models":[ "500", "Panda" ] }]} with open('newjson','w') as file: json.dump ...

Constant price updates through an API loop

I am transferring data from a spreadsheet to a dataframe that includes product details, which I need to update prices in an e-commerce via a put request through an API. However, I am facing the challenge of creating a loop to properly iterate through the e ...

discovering the initial preceding sibling that matches, exclusive of any others

Is there a way to locate only the first preceding sibling that meets a specific criteria (e.g. class='a')? Currently, my search returns all matching nodes instead of just the first one. Here is an illustration of what I am referring to: tr class ...

Send a variety of arguments as a list to a function

I'm attempting to feed a series of arguments into a function I created. def pdftotext(params=[], layout='-layout'): cmd = ['pdftotext', params, '-layout'] return cmd This is how the function is invoked: text = pdftotext(params=['-f', '1', '-l', ...

Updating a complete segment in Python using Tkinter

I am facing an issue with my GUI where I have a segment that generates multiple labels using a for loop. There is also a button intended to delete all these labels and initiate the for loop again with new data. However, I am struggling to make the button ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Uniform color scheme throughout Matplotlib Groupby visualization

My goal is to create a unique visual representation called a scatter pie plot, which groups data by two specific columns: Column1 and Column 2. The color displayed in each section of the pie chart is determined by the values found in Column 3. You can see ...

Database with socket capability for efficient memory storage

Python, SQLite, and ASP.NET C# are on my mind. I need an in-memory database application that doesn't store data to disk. Basically, I have a Python server receiving gaming UDP data, translating it, and storing it in the memory database engine. Avoiding w ...

What is the process for extracting CHIME/FRB data files?

Illustration of a Rapid Radio Burst I'm encountering an issue with msgpack.py while attempting to read and decompress msgpack data. The files I'm working on uncompressing are located here: CHIME/FRB data files. For further assistance, you can refer to thi ...

The Python percentage calculator does not utilize the exit() function

I have been working on a percentage calculator that prompts the user to enter the number of subjects, their marks, and then calculates the percentage. The functionality is smooth, but I am facing an issue where it does not exit properly when the user enter ...

How to break out of a nested Python loop

I am currently using the following code in Python 2.7x: def captureAlbumLinks(): for page in index_pages: # index_pages is a list of URLs resp = connect_tor(page) soup = BeautifulSoup(resp.read(), from_encoding=resp.info().getparam(&ap ...

Using Pandas to refine data on a grouped and summarized dataset

I am working with a dataframe that is generated from an excel file. The dataframe consists of multiple columns and rows, each with a unique identifier. My goal is to visualize the data using a PyQT interface where users can select specific criteria (checkb ...