Skip to main content

Posts

Showing posts from July, 2023

Why is this async/Promise method running synchronously?

I'm really a noob in JavaScript and I'm trying to write a small ElectronJS/NodeJS app. I think the purpose of the App is not relevant to the question, suffice it to say that the App will listen to TCP connections that will send ~100MB of XML content and then will do some further processing on the parsed XML. Since the XML content is "large" the parsing is taking some time to process, so I decided to put the parsing in an asynchronous function but the code is apparently running synchronously. I'm not sure if I'm doing something wrong or if it's just because of the single-thread (AFAIU) nature of JavaScript. var net = require('net'); const fs = require('fs'); const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser"); const parser = new XMLParser(); var file_counter = 0; var server = net.createServer(function(connection) { console.log('Client Connected'); var content = ""; connection.o...

Why am I not seeing a TypeScript error here?

I would expect the following code (inside an arbitrary Class) to show a TypeScript error in VSCode. But it doesn't. Why? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... */ } The tooltip doesn't even acknowledge that someArg should be boolean|undefined : I'm guessing this must be an eslint configuration error because the same thing in TypeScript playground acts as I would expect. But I'm not seeing any eslint configuration errors in the VSCode console. Any advice on troubleshooting VS Code eslint problems like this? Edit It's worth noting that I am seeing some expected TypeScript errors, in the same file. As far as I can tell this seems to only happen with vars I would expect to be cast as |undefined . Via Active questions tagged javascript - Stack Overflow https://ift.tt/yBvh1Lu

V-model binding always reset text input Vue

So I have an Text Input that filled based on string that stored in cookies. Something like a Remember me. when I do the value binding the cookies using :value I can't type the new value although there is no cookie being stored. here is the code <template> <GuestLayout class="bg-neutral"> <Head title="Log in" /> <div v-if="status" class="mb-4 font-medium text-sm text-white-600"> </div> <form @submit.prevent="submit"> <div> <InputLabel for="email" value="Email" /> <TextInput id="email" type="email" class="mt-1 block w-full text-neutral-focus focus:border-accent" v-model="form.email" :value="rememberedEmail" ...

ChartJS Chart how to config Scales

I am creating a website about Bitcoins and using some interactive Charts from ChartJS. Until now the scales in the Charts are changing with the data. But I think to compare the differencesbetween the years I would like them to not change and stay the same. So the scale sould be always from 0 - 110. I already tried to do this but it does't work: The trick with the max and min... scales:{ r: { ticks: { beginAtZero: true, min: 150, max: 150, stepSize: 10, If somebody could help me I would be really greatfull! Fiddle in the comment. Cheers! Via Active questions tagged javascript - Stack Overflow https://ift.tt/Z02RAK7

How to close popup box when clicked outside or when page is scrolled? [duplicate]

I am creating a page with image map that has a popup box. It works ok but I am not sure how to close the popup box when user clicks outside of the box or when the users scrolls the page. Currently the popup box remains on the page until the user closes the box by selecting 'X' button. Here is link to my jsfiddle - https://jsfiddle.net/dyxc2qe5/2/ Thanks. $(function() { $('.map').maphilight(); }); var myData = { "left-eye": { "top" : -20, "left" : -200, "title": "", "image":"", "description": "Lorem ipsum A dolor sin amet. ." }, "mouth": { "top" : 20, "left" : 200, "title": "", "description": "Lorem ipsum B dolor sin amet. Lorem ipsum B dolor sin amet.Lorem ipsum B dolor sin amet.Lorem ipsum B dolor sin amet.Lorem ipsum B do...

on hover card should scale out of swiper

I'm trying to build a swiper just like a Netflix, and trying to achieve the same hover effect. But when I'm hovering over the card, its not scaling out of swiper and stays inside the swiper container. Below is my code. <!DOCTYPE html> <html > <head> <meta charset="utf-8" /> <title>Swiper demo</title> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" /> <!-- Link Swiper's CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css" /> <!-- Demo styles --> <style> html, body { position: relative; height: 100%; } body { background: #1e1e27; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; font-size: 14px; color: #000; mar...

how fix error: MongoNotConnectedError: Client must be connected before running operations

HY all , I have a problem when I running this code:- the file productinit.js const product = require('../model/product'); const mongoose= require('mongoose'); const connectDB = async () => { await mongoose.connect('mongodb://127.0.0.1:27017/orders', {bufferTimeout: null}); console.log('Connected to MongoDB'); }; connectDB(); const products = [ new product({ imagePath:"/images/about/a1.png", productName: "iphone 8+ ", price: 200, information: { displaySize: 6.5, storageCapacity: 64, CameraResolution: 16, numberOfSIM: "Dual SIM" }}), new product({ imagePath:"/images/about/a2.png", productName: "iphone 8 ", price: 240, information: { displaySize: 5.5, storageCapacity: 64, CameraResolution: 16, numberOfSIM: "D...

Refresh kendo grid within a partial?

I have the following partial: @model List<PrintedCheckInvoice> <div> @Html.Kendo().Grid(Model).Name("PrintedCheckInvoiceList").DataSource(dataSource => dataSource .Ajax() .ServerOperation(true) .Model(model => { model.Id(o => o.actionItemID); }).Read(read => read.Action("PrintedCheckInvoiceList_Read", "Assoc").Data("getInvoicesFilter")) ).Columns(columns => { columns.Bound(o => o.ledgerID).Width(90); columns.Bound(o => o.actionItemID).Width(100); columns.Bound(o => o.invoiceNo).Width(130); columns.Bound(o => o.description).Width(180); columns.Bound(o => o.glDetail).Width(230); columns.Bound(o => o.checkNo).Width(90); columns.Bound(o => o.amount).Format("{0:c}").Width(100); }).Resizable(resize => resize.Columns(true)).Scroll...

Problem with accordion's toggle when combining it with navtabs (Bootstrap)

So, I'm creating this navigation thing using Bootstrap which will be present in the form of tabs in desktop and for mobile it will be an accordion. It's almost finished except there's this error I am not able to resolve. Problem: If I click on any of the tabs (say Link #3) in the desktop version and then I switch to mobile, the correct tab is opened (i.e. Link #3) BUT when I click on it to close the tab and hide the content even though the content gets hidden, the button and toggle remains in "open state". This problem can be seen in desktops or tablets (as they'll show the navtabs). To view the problem on desktop just decrease the viewport size after clicking the nav tab. I thought that if I could use "classList.contains()" to somehow keep track of when the content has "show" class and when it does not I'd be able to control it. But, I think it only keeps track of the class if I mentioned the class inline (it keeps on alerting true f...

useState does not set

First of all, yes, I talked with ChatGPT, it does not give a working answer. The main is that I want an image to be rendered. Why in my case the setter does not work? Probably the error lies on the surface, I am a newbie so please do not be strict. I am trying to set setMeme in two places, but it does not work. What's horroring for me is that I do not receive any error. I screened a few sites, but solutions mostly rely on "useEffect", and did not help this did not help: The useState set method is not reflecting a change immediately import React from "react"; import memesData from "../memesData.js"; import { useState, useEffect } from "react"; import front_img from "../../public/images/front_meme.png"; function importAll(r) { return r.keys().map(r); } const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/)); //alert(images); // Create a require.context for the images folder //const images...

React native not persisting user data from firebase

So i am buidling a mobile app using Expo react native and firebase, i am having a issue with current user not presisting data. following are a few code snippets: App.js: import { AuthContextProvider } from "./context/AuthContext"; import MainNavigator from "./screens/MainNavigator"; export default function App() { return ( <AuthContextProvider> <MainNavigator /> </AuthContextProvider> ); } AuthContext.js: import React from "react"; import { onAuthStateChanged, getAuth } from "firebase/auth"; import firebase_app from "../firebase/config"; const auth = getAuth(firebase_app); import { Text } from "react-native"; export const AuthContext = React.createContext({}); export const useAuthContext = () => React.useContext(AuthContext); export const AuthContextProvider = ({ children }) => { const [user, setUser] = React.useState(null); const [loading, setLoading] = React.useState(true...

How to create multiple paths of different colour using Google StaticMap in Google Apps Script?

I am trying to create a small app that will take x number of lists of locations (in the form of Geocodable Addresses) and displaying them on a StaticMap as x different paths. To change the style of the paths the documentation says to use setPathStyle(weight, color, fillColor) When doing this though I cannot find a way to make the fill colour fully transparent, or to have no fill colour at all. I build the map and retrieve the URL using this Google Apps Script code (The real app is connected to a Google Sheets document with changing addresses which is why I am using GAS): function mainFn() { addressList = [[['London, UK'],['Milton Keynes, UK'],['Cambridge, UK']], [['Reading, UK'],['Oxford, UK'],['Bristol, UK']], [['Gloucester, UK'],['Worcester, UK'],['Birmingham, UK']]]; //would normally be sourced from a Google Sheets document directions = getDirections(addressList); map...

Generating a Gaussian point spread function using Python

I wrote this function to generate a Gaussian point spread function using Python, I wonder if my approach is correct or needs modification. I wrote this function, but not sure if my approach is correct: def generate_PSF(size, sigma): """ Generates a Gaussian Point Spread Function (PSF). """ x, y = np.meshgrid(np.linspace(-size/2, size/2, size), np.linspace(-size/2, size/2, size)) d = np.sqrt(x*x + y*y) psf = np.exp(-d**2 / (2*sigma**2)) psf /= np.sum(psf) # Normalize the PSF return psf source https://stackoverflow.com/questions/76745253/generating-a-gaussian-point-spread-function-using-python

How to write a cafe program in Python [closed]

I have to write a simple cafe program as a task to first ask the user which one of the three types of pizza he wants and display the price next to it. After that, we ask them if they want something else, for example, sauce, soft drink, or water, and their price should be as well. Finally, display the total purchase price I tried different ways but to no avail. source https://stackoverflow.com/questions/76745368/how-to-write-a-cafe-program-in-python

Pagination in Server Component Next js

I have a project that I'm doing. I'm trying to do pagination using the NextJS 13 server component without using use client. We need to make the code work. Now this code only adds a parameter to the page url, but does not add entries to the screen. In theory, it should first show 1 article, then when the button is clicked, 1 more article, then another, and so on. Nothing is happening right now. //component fetch mdx files import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; interface Blog { meta: any; slug: string; } export function getAllPosts() { // 1) Set blogs directory const blogDir = "blog"; // 2) Find all files in the blog directory const files = fs.readdirSync(path.join(blogDir)); // 3) For each blog found const blogs: Blog[] = files.map((filename: string) => { // 4) Read the content of that blog const fileContent = fs.readFileSync(path.join(blogDir, filename), 'utf-8'...

Next-Auth getServerSession not retrieving user data in Nextjs 13.4 API Route

I need to access user session data in a Next-Auth/Nextjs 13.4 API Route. I have configured the JWT and Session callback; however, the user data I specified in the callback function does not translate to what getServerSession is pulling in an API route. However, the session data does correctly reflect in a Client page when using useSession() so I'm not sure what the issue is. [...nextauth]/route.js import { connectToDB } from "@/app/server/db"; import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import bcrypt from 'bcrypt'; // Authorize function async function authorize(credentials) { const { email, password } = credentials; const { db } = await connectToDB("Tenants"); const user = await db.collection("Users").findOne({ email }); if (user) { const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return ...

How to make audio element hide after pressing play

So I'm trying to make an audio element hide after you press "play" but sadly it will not work Here's the code var audio = document.querySelector('audio'); audio.addEventListener('play', function() { audio.style.display = 'none'; audio.removeAttribute('controls'); }); and here's the HTML code <audio controls autoplay loop> <source src="Music551.mp3" type="audio/mp3" /> </audio> also I added some CSS but it's just for it to be at the bottom right audio { position: absolute; bottom: 0; right: 0; } But it's still not working I've tried everything. Also the file is in .php but all the HTML and JavaScript and CSS still works fine so I don't know. Also the audio element works fine but when I click play, the element is not hiding for some reason. I was expecting the audio to hide after clicking play. Via Active questions tagged javascript - Stack Overflow https://i...

Unable to fetch document from firestore using .doc()

I have a collection whose document id got changed. Now when I fetch that document using this piece of code: const doc = database.collection(col).doc(col.documentId as string); I get this error: Error: 5 NOT_FOUND: But if I use the where clause and provide the same col.documentId, I am able to fetch that document. Please help here. Via Active questions tagged javascript - Stack Overflow https://ift.tt/zmyXjp5

"TypeError: Cannot read properties of undefined (reading 'onDestroy')" while using observable with NgFor and the Async Pipe

I'm trying to display a list of jobs, the code looks like loadJob() { let query = { pageNo: this.pageNo, title: this.searchParam.title, location: this.searchParam.location, industry:this.searchParam.industry } this.store.dispatch(InitJobComponent({query})); this.jobs$ = this.store.pipe( select(getJobState) ); this.jobs$.subscribe((jobs) => { if (jobs && jobs.data && jobs.data.length>0) { this.currentJob = jobs.data[0]; this.checkSaveStatus(this.currentJob); this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.currentJob.file); } }); } <div *ngIf="(jobs$ | async) as jobs" class="page-wrapper job-list"> <div class="no-results" *ngIf="jobs.totalCount == 0"> <h3>No results found.</h3> </div> <nz-layout *ngIf="jobs.totalCount > 0" class="content"> <nz-sider class="sid...

How can a View get information from another class?

I am writing a calculator program. class Main { constructor() { this.calculator = new Calculator // here I do my calculations this.view = new View(this.calculator) // <-- watch this this.keyboard = new Keyboard // here I have some event listeners and other fun stuff } } After user clicking on the button, I have to rerender the view. But for this I need to know the result of math operation. I can't call the calculator methods directly in View class, so I passed the calculator object as an argument. Is this normal practice? Please show me what other ways exist to exchange information between objects? Via Active questions tagged javascript - Stack Overflow https://ift.tt/IkPEmUo

Using PyGAD for feature selection

I'm trying to create a Python script for feature selection using PyGAD The code below shows my previous attempt, but I haven’t achieved the desired result. Can you please help me with the correct implementation? Im taking the primary example shown on the package's documentation page.The error Im receiving is: AttributeError: 'tuple' object has no attribute 'tb_frame' My attempt so far: import pygad import numpy from sklearn.model_selection import train_test_split, cross_val_score from src.learner_params import target_column, model_features from sklearn.datasets import load_breast_cancer from lightgbm import LGBMClassifier as lgbm bc = load_breast_cancer() bst = lgbm(random_state = 42) function_inputs = bc.feature_names X, y = bc.data,bc.target X = pd.DataFrame(X, columns=bc.feature_names) X_train, X_test, y_train, y_test = train_test_split(X, y, rando...

Images not showing in pygame [duplicate]

I have been coding this basic rpg in pygame, the images showed at one point but now they don't, I also couldn't get the controls working either # Imports import pygame, playerSprites # Initialize pygame.init() # Screen screenWidth = 800 screenHeight = 800 icon = pygame.image.load("assets/icon.png") screen = pygame.display.set_mode((screenWidth, screenWidth)) pygame.display.set_caption("Basic Pygame RPG") pygame.display.set_icon(icon) # Game stuff fpsCap = 60 # Images playerSpriteSheetImg = pygame.image.load('assets\player\playerSpriteSheet.png').convert_alpha() Background1Img = pygame.image.load('assets/Background1.png') # Backgrounds Background1 = pygame.transform.scale_by(Background1Img, 8) # Sprite sheets playerSpriteSheet = playerSprites.spriteSheet(playerSpriteSheetImg) # Create transparency BLACK = (0,0,0) # Create animation list animation_list = [] animation_steps = [3,2,2,3] action = 0 last_update = pygame.time.get_ticks() an...

Proper way to import JSLib into k6.io tests

I tried to follow guide of k6.io to import JS modules in the test: https://jslib.k6.io/ My js tests can't load: import { uuidv4 } from "https://ift.tt/jX3weka" //@ts-check import http from "k6/http"; import { check } from "k6"; import { Counter } from "k6/metrics"; import { jsonRequest } from "../data/createNode.js"; import { uuidv4 } from "https://jslib.k6.io/k6-utils/1.4.0/index.j" //counter for http codes var http200 = new Counter("HTTP_200_counter") var error400 = new Counter("HTTP_400_error_counter") var error500 = new Counter("HTTP_500_error_counter") Via Active questions tagged javascript - Stack Overflow https://ift.tt/hZ6BbJY

autocomplete not working for dynamic created input rows

i have form with dynamic created rows. I added autocomplete with my form which worked fine for single row. But when i created dynamic rows, it stopped working. i attached main file, js file , backend file and jquerry online links of website which handle autocomplete for single row ```<form method="POST"> <table class="table table-bordered"> <thead class="table-success" style="background-color: #3fbbc0;"> <tr> <th width="15%"><center>Service</th> <th width="10%"><center>Mach No</th> <th width="10%"><center>Consultant</th> <th width="5%"><center>Qty</th> <button type="button" class="btn btn-sm btn-success...

Dynamically Provision iot Device With Azure dps - Unexpected Failure. Python sdk

I am dynamically provision an iot device using the python azure-iot-device python package. I am using v2 and not 3.0.0b2. I can't even get that to compile. Here's my python code trying to provision a device: import asyncio import os from azure.iot.device.aio import ( ProvisioningDeviceClient, ) from dotenv import load_dotenv load_dotenv(dotenv_path=".env") CONNECTION_STRING = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") ID_SCOPE = os.getenv("PROVISIONING_IDSCOPE") REGISTRATION_ID = os.getenv("PROVISIONING_REGISTRATION_ID") SYMMETRIC_KEY = os.getenv("PROVISIONING_SYMMETRIC_KEY") PROVISIONING_HOST = os.getenv("PROVISIONING_HOST") # PROVISIONING_SHARED_ACCESS_KEY = os.getenv("PROVISIONING_SHARED_ACCESS_KEY") async def main(): print("Starting multi-feature sample") provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key( provisioning_host=PROVISIONING_HOS...

how to pass timestamp between python/sql

enter image description here %python df =spark.sql(" select count(*) from sample.table_c") count = df.first()[0] spark.conf.set("myapp.count",count) spark.conf.get("myapp.count") i am getting count & saving it as variable for further use in sql.. the above code is working for int,string ..but when i am using it for timestamp,date instead of int..i am getting error %python import datetime as dt c_time =dt.datetime.now() spark.conf.set("myapp.ages",c_time) the error is py4j.Py4JException: Method set([class java.lang.String, class java.sql.Timestamp]) does not exist any way to solve this,please help me i tried widgets concept...but not working source https://stackoverflow.com/questions/76695280/how-to-pass-timestamp-between-python-sql

I just need help fixing my code(Python using replit) so the login won’t keep having an index error and that the user can login or be told to try again

I used a sub program for the login this is the code I did: def login(login): access = False while access == False: print ("**Login Loading**\\n") username = input("Enter your username: \\n") password = input ("Enter your password: \\n") file = open("Valid_users.txt","r") valid_users = file.read() valid_users = username.replace('\\n', ' ').split(".") for line in open("Valid_users.txt", "r").readlines(): #usersfile = line.split() if username == valid_users\[0\] and password == valid_users\[1\]: print("Welcome!") else: print("Username or password incorrect. Try again") if access == True: print("logged in") return username return access return login login(login) The problem is when I try to search the valid users in the file it come with an index error I’m not very familiar with sub programs so I’m not sure what to do. This is my...

Spark bucketing and Hive bucketing generating same logical plan for a join query, why?

I have a dataset that I have loaded into a SparkDataFrame. On these datasets I do the following df_spark_bucketed = ( df .repartition(10, col) .write .mode("overwrite") .parquet(save_path) ) df_hive_bucketed = ( df .repartition(10, col) .write .bucketBy(10, col) .mode("overwrite") .saveAsTable(table_name) ) I then construct the following query def dummy_join(df, col): temp = df.filter(sf.col("B") == col) return ( temp .select("A") .join(temp, "A", "inner") ) and finally run plan_sb = dummy_join(df_spark_bucketed, "C").explain() plan_hb = dummy_join(df_hive_bucketed, "C").explain() and observe that the two logical plans are identical. They both look like shown in the below figure. I find this to be odd because I'd expect the second plan to be different, specifically that it should showcase that less (or maybe even no...

How to handle Typescript dependency in a monorepo?

I have a monorepo using npm workspaces, the structure is as follows: web -package.json api -package.json common -package.json package.json I have some utility functions and types in "common" package which I use in my web and api packages. Do I need to install typescript as a dev dependency in each package or installing it at the root folder is enough (my current setup) what are the cons/pros? One more question if I have some utility that is in the api package and want to use it in the web package do I need to move it to "common" package and import from there or I can directly import from the api package? Thanks Via Active questions tagged javascript - Stack Overflow https://ift.tt/1z4klGh

Unable to access web_accessible_resource when using extension_ids options in manifest.json

I have an MV3 extension where I have a file which I want to access via content script. I am unable to do that when I specify "extension_ids": ["myextId"] in manifest.json. However when I use "matches": ["<all_urls>"], I am able to access it. According to chrome docs Each element must include a "resources" element and either a "matches" or "extension_ids" element. I am getting the extension ID from extensions management page Am i getting ID from the wrong place ? Manifest.json "web_accessible_resources": [ { "resources": [ "/sample.html", ], "extension_ids": ["liecbddmkiiihnedobmlmillhodjkdmb"] } ] Error Denying load of <URL>. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension. my.com/:40 Denying load of chrome-extension://liecbddmkii...

Finding a specific span element with a class using Selenium

The html below is stored in a selenium WebDriver variable <td colspan="2" class="pi_mailing_address"><strong>Mailing Address</strong> <div> <span class="ng-binding">1236 NW 167 ST </span> <span ng-show="property.mailingAddress.address2" class="ng-binding ng-hide">STE #</span> <span ng-show="property.mailingAddress.address3" class="ng-binding ng-hide">789</span> <span ng-show="property.mailingAddress.city" ng-class="{'inline':property.mailingAddress.city}" class="ng-binding inline">OPA LOCKA,</span> <span class="inline ng-binding">FL</span> <span class="inline ng-binding">33055-4314</span> <span ng-hide="isCountryUSA(property.mailingAddress.country)" class...

Expand a certain div when loading from a web search

I have a webpage with a good amount of expandable divs. Since the text is hidden and a person coming in from a web search would have to open each div to check for the content, is there any way I can open the div when the page loads? For example, consider that I have a webpage named example.com, and in that webpage I have a div with id expandableDiv with a target attribute liked to it as example.com#expandableDiv. Now I search on google about the content in expandableDiv and my website shows up. When I click on it, the div would be hidden. I need the div to open up when the person is coming in from the google search. Hope this explains my issue. Via Active questions tagged javascript - Stack Overflow https://ift.tt/JuLYq7p

how to fix the "Cannot read properties of undefined (reading 'map') in React"

actually I m working with SPFX webpart using React, really don t understand what is the issue here, but when I debug it shows the blow screenshot. trying to get the SP list items in SPFX webpart using React, during the map it getting error. please assist me using the below piece of code. [ ] public render(): React.ReactElement<IGetSpListItemsProps> { return( <div className={"styles.welcome"}> <table > { this.state.listitems.map(function (listitem, listitemkey){ let fullurl: string = `${GetSpListItems.siteurl}/lists/SampleList/DispForm.aspx?ID=${listitem.ID}`; return( <tr> <td><a className={styles.label} href={fullurl}>{listitem.Title}</a></td> <td className={styles.label}> {listitem.ID}</td> </tr>)})} </table> Here is the video where I have gone through as per the same I have followed but when I try it shows undefined error text Via Active questions t...

Anvil Error: files table not found but the table is already created

I have this server side code in Anvil: import anvil.files from anvil.files import data_files # Server-side code import anvil.server import pandas as pd import io from anvil import tables @anvil.server.callable def clean_and_process_data(file_string, model, capacity, renewed, unlocked, app_tables): # Convert the string back to bytes file_data = file_string.encode("utf-8") # Create a BytesIO object from the file data file_object = io.BytesIO(file_data) # Read the uploaded CSV file into a DataFrame df = pd.read_csv(file_object) # Clean the DataFrame df[['Date', 'Time']] = df['Time'].str.split(',', n=1, expand=True) df = df.drop(columns=['Time', 'Sales Rank', 'List Price']) df = df[['Date', 'New Price']] df = df.dropna(subset=['New Price']) df['Date'] = pd.to_datetime(df['Date']) # Convert 'Date' column to DatetimeIndex ...

How to animate a line graph in python where each step of the animation draws an entirely new line based on data in dataframe and export as gif

I would like to animate a line graph in python based on data in my df. For each step in the animation, a line graph would be displayed using one row of the df. A fraction of a second later, a new line graph would be displayed using the next row of data in the df. This process would continue until each row of data had been separately displayed. After this process had been done for all rows, the graph would show the last line of data. I would also have code that converts the animation to a gif and then exports it. I'm lost as to how to do this and was hoping someone could point me in the right direction. Here is the code and df I have so far: # Import dependencies import pandas as pd from datetime import datetime # Create lists to be converted to df data = [['01/01/2016', 4.17, 4.42, 4.53, 4.71, 4.77, 4.72], ['02/05/2017', 4.59, 4.64, 4.70, 4.74, 4.80, 4.68], ['04/17/2018', 4.67, 4.82, 4.90, 5.02, 5.20, 5.06], ['03/03/...

Display the data if the user has permissions to read the data in React(Firebase)

I need to write a program that will display specific data if the user has permission to view those documents. Below is the code, the user has permissions, but I still can't see the data. Thank you for your help! I need to read data from the collection named my_collection, and to display it if user has permissions. Rules are: import { useEffect, useState } from 'react'; import { getFirestore, collection, query, where, getDocs } from 'firebase/firestore'; import { auth } from '../firebase'; const Home = () => { const [data, setData] = useState([]); const checkUserPermissions = async (userId) => { const db = getFirestore(); const userPermissionsQuery = query( collection(db, 'my_collection'), where('user.id', '==', userId) ); const userPermissionsSnapshot = await getDocs(userPermissionsQuery); if (!userPermissionsSnapshot.empty) { const nikolaPozoristeQuery = query(collection(db, ...

validate form inputs and enable button

What I need is to validate the form from the second section of the tab. If there is any empty field of the 4 that does not appear hidden or transparent, the button should be disabled. If they already have the 4 data, then the button is enabled. The problem is that I add the two elements and for a reason the button is enabled since the last input has no data. And if I add a 3rd serious element, 6 fields to fill in or modify, because the data entry operator can proceed to delete an amount and the button should still be disabled even though the other 5 are filled with data the inputs are shoppingCartItemQuantity_ and price_ . How to make it take the inputs below the save button Summary: Leave button visible when all inputs are filled with data Place focus on the input to fill the first one that is empty const id_prod = document.querySelector('#first-tab >#articulos>#productos_content>.tr >.id_n').textContent; console.log(id_prod) const tbody = document.qu...