Skip to main content

Posts

Showing posts from August, 2022

Async Await not waiting until the end

frankly new to js so forgiveme if it's quite silly one. Firebase functions with Node.js 14 if that matters. My function (parts of it): exports.blablabla = functions.region('jajajaj').database.instance('ccc').ref('ddd').onCreate( (change, context) => { ... /** FOR LOOP **/ for (let i = 0; i < numberOfChild; i++) { /** CALLING THE ASYNC FUNCTION **/ if ( i > valueLimit - bufferValue - 1) { (async function(){ const keyToBeRemoved = pinKeysSorted[i]; const temp = await myAsync(area, country, section, genderString, keyToBeRemoved, lockMaximumTimeInHours); })() } } /** SCANNED EVERYTHING , CLOSING OFF **/ /** ALIGN THE overFlowValues TO REFLECT THE REAL VALUES **/ const myPromise = admin.database(zxcf).ref("minop...

Regex assertions match differently with different spacing

I'm new to RegEx and trying to learn via MDN. I've made it to assertions and I've run into some confusion with the Lookahead assertion x(?=y) . The example the MDN gives is: /Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However - when I've tested this, it doesn't work in either case, until I add spaces around = and \ . Here are some tests I ran ( Repl link ) let regex = /Jack(?=Sprat|Frost)/; let nurseryRhyme1 = 'Jack Frost is real.' let nurseryRhyme2 = 'Jack, this Frost is real.' let nurseryRhyme3 = 'Jack Sprat is not real.' console.log(nurseryRhyme1.match(regex)) // null console.log(nurseryRhyme2.match(regex)) // null console.log(nurseryRhyme3.match(regex)) // null regex = /Jack(?= Sprat|Frost)/; nurseryRhyme1 = 'Jack Frost is real.' nurseryRhyme2 = 'Jack, this Frost is real.' nurseryRhyme3 = 'Jack Sprat is not real.' console.l...

Drop child element from list rendered inside portal to parent div with Droppable context

I have a Draggable section within which element opens popover (as React portal) containing list of items, I was trying to drag the child element from popover and drop outside popover over the Droppable section outside. How can it be achieved? What I tried: Wrapped the list items inside the popover within Draggable to make items draggable but it doesn't allow dropping outside the portal Via Active questions tagged javascript - Stack Overflow https://ift.tt/1DRY7Xq

Scrapy: setting authorization header for proxy in middleware

I am trying to send scrapy requests through a proxy that requires an authorization. I updated the process_request method from the default middleware ( middleware.py ). I tried several ways to achieve it but everytime I get the following error messsage : ERROR: Gave up retrying <GET https://api.ipify.org/> (failed 3 times): Could not open CONNECT tunnel with proxy proxy_ip:proxy_port [{'status': 407, 'reason': b'Proxy Authentication Required'}] Here is what I tried : def process_request(self, request, spider): request.meta['proxy'] = 'http://proxy_ip:proxy_port' proxy_user_pass = "username:password" encoded_user_pass = base64.encodestring(proxy_user_pass.encode()).decode() request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass return None I try other ways of encoding the header, such as : From : https://www.zyte.com/blog/scrapy-proxy/ request.headers['Proxy-Au...

What is difference between local and global Node package installation?

I ask this question because I have been installing nodemon with npm and I see the results of installing through the suggested command at first sight, at the right side of the screen: npm i nodemon It is different from the installation instructions you can read above, on the Installation section. There we see: global installation: npm install -g nodemon install nodemon as a local project dependency: npm install --save-dev nodemon The thing is, what is difference between npm i nodemon and npm install -g nodemon When I use the first command it tells me typical "nodemon is not recognized as internal or external command, operable program or batch file". To solve it I must install globally. Via Active questions tagged javascript - Stack Overflow https://ift.tt/1DRY7Xq

Converting React ES6 class to functional component - what to use for private methods?

I'm converting a React ES6 class-style component to a functional component. The one thing I'm slightly unsure of is how best to convert private class methods. As far as I can tell, I should convert them to functions within the functional component's function, as they need to be there to access the component's state. However, that presumably means that on each re-render, the function is going to get recreated: Before class Game extends React.Component { handleClick(i) { if (this.state.foo) { ... } } } After function Game { function handleClick(i) { if (foo) { ... } } } Is this a problem performance-wise, and if so, is there any way to improve it? Also, most guides I've read recommend assigning arrow functions to variables instead of just declaring functions, eg. function Game { const handleClick = (i) => { if (foo) { ... } } } Is this purely stylistic, or is there another reason to use assigned arrow functions over regular nested function...

Unit for fit_time and score_time in sklearn cross_validate

in the sklearn's documentation they state: fit_time The time for fitting the estimator on the train set for each cv split. score_time The time for scoring the estimator on the test set for each cv split. (Note time for scoring on the train set is not included even if return_train_score is set to True Ok, but does anyone actually know the units of these answers? My best guess is that they are in seconds by the execution time of my cross validations, but I am still unsure. source https://stackoverflow.com/questions/73548091/unit-for-fit-time-and-score-time-in-sklearn-cross-validate

Dictionary behaves like a global variable

A dictionary that I pass as an argument seems to behave like a global variable. This was a surprise to me but it seems that it makes sense in Python (see for instance this topic ). However, I'm very surprised that I get a different behavior for a different type of variable. Let assume that I have a script main.py that calls two functions from a module. import mymodule an_int = 42 a_dict = {'value':42} mymodule.print_and_reassign(a_dict, an_int) mymodule.print_again(a_dict, an_int) with my modules.py containing the following functions def print_and_reassign(a_dict, an_int): # Dictionary print(f"Dictionary value: {a_dict['value']}") a_dict['value']=970 # Integer print(f"Integer value: {an_int}") an_int=970 def print_again(a_dict, an_int): # Dictionary print(f"Dictionary value: {a_dict['value']}") # Integer print(f"Integer value: {an_int}") By running main.py, I ...

Instagram Python scrapping re.compile() and window\.__additionalDataLoaded

I'm trying to fix a bug where the re.compile of window.__additionalDataLoaded of a post from instagram returns "None"... It didn't happened before so I think the way instagram manages its data has changed... Any advice where I can find the new way to get the new regex origin? I'm looking for the owner username and the likes an Instagram post got... Thank you source https://stackoverflow.com/questions/73548067/instagram-python-scrapping-re-compile-and-window-additionaldataloaded

how to do something like streams inside a port (Python socket)

there is such a code: server: import socket from threading import Thread from time import sleep sock = socket.socket() sock.bind(('', 1337)) sock.listen(1) conn, addr = sock.accept() def func1(): while True: conn.send("1".encode("utf-8")) sleep(0.5) def func2(): while True: conn.send("2".encode("utf-8")) sleep(0.5) t1 = Thread(target=func1) t1.start() t2 = Thread(target=func2) t2.start() client: import socket from threading import Thread from time import sleep sock = socket.socket() sock.connect(('localhost', 1337)) def func1(): while True: data = sock.recv(1024).decode("utf-8") if data != "1": print("the package did not arrive properly") else: print("package arrived ok") def func2(): while True: data = sock.recv(1024).decode("utf-8") if data != "2": ...

Python Port Scanner Syntax Problems

result = s.connect_ex((target,port)) TypeError: str, bytes or bytearray expected, not function I've been trying to make a python port scanner but i cant fix this problem any ideas ? source https://stackoverflow.com/questions/73548038/python-port-scanner-syntax-problems

Trigger child component to re-render in parent component

I'm using react-native to make an app. when onReserve() is implemented, I want ModalView to be updated. But it's not updated, value of usermachine in Modalview is the same as the value before onReserve() is implemented. let first value of usermachine is [] and the value is changed to [{"id":"1"}] after onReserve() . but usermachine displayed on Modalview is still [] and let the value of usermachine is changed to [{"id":"2"}] after onReserve() is implemented once again,usermachine displayed on Modalview is [{"id":"1"}] . How to update the value of usermachine displayed on Modalview right after onReserve() ? ReserveScreen.js import React, {useEffect, useState, useRef} from 'react'; import { SafeAreaView, ScrollView, StyleSheet, View, Alert, Button, Text, Modal, KeyboardAvoidingView, } from 'react-native'; import ModalView from '../components/ModalView.js'; import Machine...

useState define an empty array with new Array method

I am getting data which is an array of objects from the store. In useState I want to set an array of data.length size all set to false initially. But when I set the value it returns an empty array [] for each of the state variable I set. I also tried updating the state in the useeffect but nothing works. I am unable to figure out what is the issue here. function Datatable() { let data = useSelector((state) => state.dish); const [clicked1, setClicked1] = useState(new Array(data.length).fill(false)); const [clicked2, setClicked2] = useState(new Array(data.length).fill(false)); const [clicked3, setClicked3] = useState(new Array(data.length).fill(false)); const dispatch = useDispatch(); function setAllStates() { setClicked1(new Array(data.length).fill(false)); setClicked2(new Array(data.length).fill(false)); setClicked3(new Array(data.length).fill(false)); } useEffect(() => { setAllStates(); }, []...

How to add random position of image in css by the x

I need to make a random position of image ".block" and make the auto reset of function when it flies down. Big thanks to everybody who will help. :) var player = document.getElementById("player"); var block = document.getElementById("block"); function goleft(argument) { player.classList.add("animatel"); setTimeout(function() { player.classList.remove("animatel"); }, 1); console.log("left"); } function goright(argument) { player.classList.add("animater"); console.log("right"); } body { background-color: lightblue; } .player { height: 50px; width: 50px; position: relative; top: 450px; } .block { height: 30px; width: 30px; position: relative; top: -50px; animation: block 1s infinite linear; } #game { width: 500px; height: 500px; border: 2px solid black; } @keyframes block { 0% { top: -50; } 100% { top: 420; } } @keyframes gor { 0% { ...

python dask dataframe write json file with array format

I am trying to read a large CSV file and then loading the data as JSON file. The following code is working fine but the data is writing as JSON object in each line on JSON file. import dask.dataframe as dd import pandas as pd cols=['Name','State'] df=dd.read_csv('F:\csvs\stack.csv', low_memory=False, usecols=cols, dtype={'Name':str,'State':str} ) df.to_json(r'F:\csvs\stack', orient ='records', compression = 'infer') Above code writing the data as JSON object in each line {"Name":"John","State":"TS"} {"Name":"Paha","State":"MK"} How to write the data as JSON array like below? [{"Name":"John","State":"TS"},{"Name":"Paha","State":"MK"}] By default files are creating file type as .part , How to create files with .json extension. source https://stackoverflow.c...

TypeError: unsupported operand type(s) for -: 'DatetimeArray' and 'relativedelta'

I'd like to do a manual train-test-split for a random forest or linear regression on a dataframe called whatever_df based on the Date column. I would use this column to select all rows that have dates earlier than 3 months before the most recent one in the column to make a new dataframe called train_df with those older dates, and a test_df with all the dates within the latest 3 months. In raw format the dataframe looks like: PC1 PC2 Date 0 -0.319258 -0.042817 2019-05-24 1 -0.246079 0.131233 2019-05-24 2 -0.037325 0.562841 2019-05-24 3 -0.080725 0.594007 2019-05-24 4 0.133341 0.322822 2019-05-24 ... ... ... ... 3607 -3.583419 3.766158 2022-06-26 3608 -3.305263 4.019327 2022-06-26 3609 -2.913036 4.854316 2022-06-26 3610 -2.755733 4.873996 2022-06-26 3611 -2.535929 4.582312 2022-06-26 So what I'd want for train_df would be all the rows w...

how to solve Cast to ObjectId failed for value

<form action="" method="post"> <input type="password" name="password" placeholder="Enter Your Password" required> <input type="hidden" name="user_id" value="<%=user_id%> "> <br><br> <input type="submit" value="Reset Password"> </form>" // routes user_route.post('/forget-password', userController.resetPassword); //controllers const resetPassword = async(req,res)=>{ try { const user_id = req.body.user_id; const password = req.body.password; const secure_password = await securePassword(password); const updatedData = await User.findByIdAndUpdate({ _id:user_id }, { $set:{ password:secure_password, token:""}}); res.redirect("/"); } catch (error) { console.log(error.message) } } Output Server is connected at port 3000 Connection Succesful Email ...

Functions to combine elements of differents arrays?

I have a problem here, with the arreys. So. I have 3 arreys: const names = [Robert, Mark, Lindsay, Anna, Erin, Andrew] const surnames = [Smith, Black, White, Lewis, Cooper, Hill] const ages = [21, 14, 19, 28, 65, 31] I must create 2 functions: On will give me a new arrey with the couples man-woman (like Robert-Anna / Erin-Mark etc.); And one must give a me a new arrey with the name, the surname and the age (like Robert Smith 21, Mark Black 14, etc.). So, what i thinked for the first function was to do this randomly: function getElementFromArray(arr) { const min = 0; const max = (arr.length); const randIndex = Math.floor(Math.random() * (max - min)); return arr[randIndex]; } const boyArray = Array("Robert", "Mark", "Andrew"); const boy = getElementFromArray(boyArray); const girlArray = Array("Erin", "Anna", "Lindsay"); const girl = getElementFromArray(girlArray); const getPair = [boy + girl]; But this...

Outputting values of select options in specific HTML structure on selection

I want to output the values that become visible when selecting an option in the dropdown into the table structure that is now visible as an example. Edit: The table is just as an example how I want the output to be after selecting an option, I don’t want the table to -always- be visible and insert selections into it. So my guess is that the table structure should be set up after .innerHTML or something and declare the values at the right places into the table? Any help will be greatly appreciated. function selectedAfternoon(element) { var text = element.options[element.selectedIndex].value; document.getElementById("output-selected-option-afternoon").innerHTML = "<div>" + text.split("|").join("</div><div>") + "</div>"; document.getElementById("output-selected-option-afternoon").querySelector("div:last-child").classList.add("price-selected-option") } .selected-option { di...

Clone conda environment with Tensorflow and other packages

I have created an environment using conda and set up tensorflow along with a few other packages. How do I clone this environment such that it is a direct replica of the environment itself? I plan to clone the environment (call it base) twice: Once for testing out packages and again for production. In total I would have the base environment, the test version, and production version. The goal being I can test out packages in "test" and if they work, add them to production. If they really do work as expected, add them to "base". With that being said, I am not savy with the command line and get tripped up easily with naming conventions. Any explicit answers would be very helpful. source https://stackoverflow.com/questions/73521538/clone-conda-environment-with-tensorflow-and-other-packages

Better way to destructure object nested from payload in JavaScript?

I have this function : const id = await this.$axios(config) .then(({ data : { user : { profile : { profileId } }}}) => profileId || 0 ) To make it simple const id = ({ a : { b : { c : { id } } } } ) => id || 0 The best way to null check this without crashing in runtime is const id = ({ a : { b : { c : { id } = {} } = {} } = {} } = {} ) => id || 0 which is as you can see, not as readable as this const id = (data) => a?.b?.c?.c?.id || 0 Is there another way to destructure even if the property might not exist or if the object is another type ? Via Active questions tagged javascript - Stack Overflow https://ift.tt/XehMLIb

Mixing 2 functions as 1

Im having a trouble here, I need to create a function for an empty list with 4 digits random numbers, which I did import random def numerosazar(n): random_numeros=[] for i in range(n): random_numeros.append(random.randint(1000,10000)) return random_numeros The problem is I need it to also give me an ammount of number of 2 digits which I did but not as function azar=numerosazar(random.randint(10,100)) print("Los numeros de la lista son: ",azar, "\n") So im having trouble mixing them together (sorry if my english is not good enough btw) source https://stackoverflow.com/questions/73521530/mixing-2-functions-as-1

while trying the pong game in python i used super class to create paddles and when i am tryin to input position for the paddles it is showing error [closed]

[enter image description here][1]```[enter image description here][2] class Paddle (Turtle): def int (self, position): super(). init () self.shape("square") self.shapesize(stretch_wid=5, stretch_len=1) self.color("white") self.penup() self.goto(position) r_paddle = Paddle ((350,0)) l_paddle = Paddle ((-350,0)) [1]: https://i.stack.imgur.com/UWjla.png [2]: https://i.stack.imgur.com/76gVK.png source https://stackoverflow.com/questions/73521413/while-trying-the-pong-game-in-python-i-used-super-class-to-create-paddles-and-wh

Inspect find class in stack

I need to get the class (not just the name, the real class ref) from an inspect stack return. Say i have this: class excls: def somemethod(): something = "is happening here" return something if i go back with inspect.stack() i want to get the class reference of the previous entry in the stack, in this case the excls reference. I looked into to the return of inspect.stack() but i didnt find anything useful there. If there is an alternative method that allows me to get the class reference of the previous stack it is also welcomened source https://stackoverflow.com/questions/73514079/inspect-find-class-in-stack

Autocomplete: how to have multiple values on data source

I'm not expert on js, so I'd like to use the code taken from here to implement Autocomplete input on my form. Unfortunately, the example proposed show only one values on source data (see 'var countries'). I need to have multiple values on each Country. For example [{ label: "Afghanistan", value: 100, id: 1, }, { label: "Albania", value: 101, id: 2, }, { label: "Algeria", value: 102, id: 3, }] And, if is possible, get all values (label, value, id) of selected country on php, when submit the form... This is the actual code: function autocomplete(inp, arr) { /*the autocomplete function takes two arguments, the text field element and an array of possible autocompleted values:*/ var currentFocus; /*execute a function when someone writes in the text field:*/ inp.addEventListener("input", function(e) { var a, b, i, val = this.value; /*close any ...

Arrange radio buttons horizontally using pack method in Tkinter

This is my first GUI attempt with python using tkinter and I cannot figure out what is the problem: here is my initial code: from tkinter import * root_app = Tk() root_app.title("Test App") #Question 1 - best car brand v1 = StringVar() v1.set(None) Label(root_app, text="What is your favorite car barnd?\n", font=('Helvatical bold',16), fg='#ff0').pack() r1 = Radiobutton(root_app, text='Mazda', value='Mazda', variable=v1).pack() r2 = Radiobutton(root_app, text='BMW', value='BMW', variable=v1).pack() r3 = Radiobutton(root_app, text='Ford', value='Ford', variable=v1).pack() #Question 2 - best sports brand v1 = StringVar() v1.set(None) Label(root_app, text="What is your favorite sports barnd?\n", font=('Helvatical bold',16), fg='#ff0').pack() r1 = Radiobutton(root_app, text='Nike', value='Nike', variable=v1).pack() r2 = Radiobutton(root_app, text='Adidas...

Pandas: Map DF with multiple columns to another

I am trying to figure out an efficient way to map df2 to df1 . What makes this a bit trickier, is the key can sometimes be a tuple of 2+ keys . df1 = {'Index':[1,2,3,4,5,6,7,8],'key':[a,a,b,(a,c),c,(a,b,c),b,a]} df2 = {'Index':[a,b,c],'Val1':[1,2,3],'Val2':[.1,.2,.3],'Val3':[10,20,30],'Val4':[1,2,3],'Val5':[2,4,6]} Basically, I am trying to map df2 (via the Index ) to the key in df1 . The end result would have columns = [key, Val1, Val2, Val3, Val4, Val5] , and in the result that the type(key) == tuple , I would like a tuple of the 2+ matched Vals. Any help is appreciated! Thanks! source https://stackoverflow.com/questions/73513856/pandas-map-df-with-multiple-columns-to-another

I keep getting 404 error when using express-async-handler

I'm trying to get this sign in screen to work and I'm using express-async-handler and I'm putting in the email and password using ARC and I get a 404 not found error and from the debugging I can do I doesn't seem to be getting into the function. I'm not sure what to do at this point. Please help thanks. Screenshot import express from "express"; import User from "../models/userModel.js"; import bcrypt from "bcryptjs"; import { generateToken } from "../utils.js"; import expressAsyncHandler from "express-async-handler"; const userRouter = express.Router(); userRouter.post( "/signin", expressAsyncHandler(async (req, res) => { const user = await User.findOne({ email: req.body.email }); if (user) { console.log("found"); if (bcrypt.compareSync(req.body.password, user.password)) { res.send({ _id: user._id, name: user.name, email: user.emai...

Why does my 2048 game cover my Cash Out modal? [closed]

I am making a 2048 game , but the problem is that when I click Cash Out , the 2048 tiles covers the modal, but instead, it should cover the whole thing, like the modal's background should cover the game so you can cash out. Since I have a ton of code of Javascript, CSS, and HTML, you can locate my code here , and I don't know why it does that. Me and my friend have tried finding the source of the issue everywhere, but we couldn't find anything. Can you guys help? Via Active questions tagged javascript - Stack Overflow https://ift.tt/jRP1owJ

Ensure that every column in a matrix has at least `e` non-zero elements

I would like to ensure that each column in a matrix has at least e non-zero elements, and for each column that does not randomoly replace zero-valued elements with the value y until the column contains e non-zero elements. Consider the following matrix where some columns have 0, 1 or 2 elements. After the operation, each column should have at least e elements of value y . before tensor([[0, 7, 0, 0], [0, 0, 0, 0], [0, 1, 0, 4]], dtype=torch.int32) after, e = 2 tensor([[y, 7, 0, y], [y, 0, y, 0], [0, 1, y, 4]], dtype=torch.int32) I have a very slow and naive loop-based solution that works: def scatter_elements(x, e, y): for i in range(x.shape[1]): col = x.data[:, i] num_connections = col.count_nonzero() to_add = torch.clip(e - num_connections, 0, None) indices = torch.where(col == 0)[0] perm = torch.randperm(indices.shape[0])[:to_add] col.data[indices[perm]] = y Is it possible to do this without loops? I've thought...

Calling function from a list using named arguments

Lets say I have a list of function calls and their respective arguments, something like the following def printStuff(val1, val2, val3, printGotHere=False, saveValsToFile=False): allVals = [val1, val2, val3] if printGotHere: print('Got Here!') for val in allVals: print(val) if saveValsToFile: with open('vals.text', 'w') as fp: for line in allVals: fp.write("%s\n" % str(line)) funcList = [] funcList.append({'func': printStuff, 'args': [1, 2, 3]}) funcList.append({'func': printStuff, 'args': [4, 5, 6]}) funcList.append({'func': printStuff, 'args': [7, 8, 9]}) for funcAndArgs in funcList: funcAndArgs['func'](*funcAndArgs['args']) That works fine, but lets say I want to specify one of the named arguments like "saveValsToFile", without putting any of the other optional variables. So a normal frunction...

Not able to Map over Fetch data

I am not able to map over the data which is stored in the redux array. This action creator fetches the data and calls the dispatch action. import { checkStatus, getTours, checkLoading } from "../../features/tourSlice"; export const getData = () => { return async (dispatch) => { try { dispatch(checkLoading(true)); const res = await fetch(`http://localhost:8080/backpack/api/r1/tours`); if (!res.ok) { throw new Error(`Error while connecting with server`); } const data = await res.json(); dispatch(checkLoading(false)); dispatch(getTours(data)); } catch (error) { dispatch( checkStatus({ title: `Error`, message: `Servers are down or Error while connecting please try again later`, }) ); } }; }; calling in app.js function App() { const dispatch = useDispatch(); useEffect(() => { dispatch(getData()); }, [dispatch]); while using this component give...

Slick carousel add separate captions from img alt tag

I have a slick carousel where I'm trying to create separate captions from the img alt tags. However its not working and I'm not getting any errors. I'd like to get the caption from the img alt tag of each and then wrap them in a separate div, which then changes as you go through the images within the carousel Markup below: jQuery(document).ready(() => { var helpers = { addZeros: function (n) { return (n < 10) ? '0' + n : '' + n; } }; $('.carousel-module').each(function (index, sliderWrap) { var $sliderParent = $(this).parent(); var $slider = $(sliderWrap).find('.carousel-gallery'); var $caption = $('.carousel-caption'); $slider.slick({ dots: false, arrows: false, speed: 900, autoplay: true, autoplaySpeed: 4000, fade: true, cssEase: 'linear' }); ...

How to set and get values from datepicker fields and a select box and store them in local storage in javascript?

I am working on form in which I want get same data as I picked for dates field and selected the user id when window is duplicated, not on form submission. I want to store the values of audit, transcribe date, cru id and user id in local storage and get them in the fields when the browser window is duplicated. <div class="col-sm-6 one"> <div class="form-group"> <label for="">Audit Date <span>*</span></label> <input type="text" class="form-control datetimepicker-input auditdatepicker" id="audit_date" name="audit_date" data-toggle="datetimepicker" data-target=".auditdatepicker" required> </div> </div> <div class="col-sm-6 one"...

Undetected if condition

I am trying to use an if condition in conjuction with a for loop. I was confident this would work, but i'm seeming to have difficulty. I am able to print the information from the api, but when I try to if condition with results, something isn't getting detected. Code: for example in examples: profile = requests.get(api, params=params) hunter = json.loads(profile.content) accept_All = hunter['data']['accept_all'] verif = hunter['data']['verification']['status'] first_name = hunter['data']['first_name'] last_name = hunter['data']['last_name'] domain = hunter['data']['domain'] email_address = hunter['data']['email'] print(hunter['data']['verification']['status']) print(hunter['data']['accept_all']) if accept_All == 'False' and verif == 'valid': validEmails.append([fi...

Why does my LSTM model predict wrong values although the loss is decreasing?

I am trying to build a machine learning model which predicts a single number from a series of numbers. I am using an LSTM model with Tensorflow. You can imagine my dataset to look something like this: Index x data y data 0 np.array(shape (10000,1) ) numpy.float32 1 np.array(shape (10000,1) ) numpy.float32 2 np.array(shape (10000,1) ) numpy.float32 ... ... ... 56 np.array(shape (10000,1) ) numpy.float32 Easily said I just want my model to predict a number (y data) from a sequence of numbers (x data). For example like this: array([3.59280851, 3.60459062, 3.60459062, ...]) => 2.8989773 array([3.54752101, 3.56740332, 3.56740332, ...]) => 3.0893357 ... x and y data From my x data I created a numpy array x_train which I want to use to train the network. Because I am using an LSTM network, x_train should be of shape (samples, time_steps, features) . I reshaped my x_train array to be shaped like this: (57, 10000, 1), because I have 57 samp...

can anybody please tell me why this stale element reference exception is arising again and again?

i am trying to fetch 500 cars data for each of the 11 cities whose urls are saved in url_city variable from car dekho.com, but each time, i m getting this exception error. please suggest me some better way to get rid of this. code block for function car_data(city): def car_data(city): reg_year=[] fuel=[] kms=[] eng_power=[] owner=[] automation=[] ins=[] variant=[] brand=[] mod_name=[] colour=[] rto=[] price=[] href_tags=[] url=[] while len(href_tags)<500: href_tags=set(href_tags) href_tags=driver.find_elements('xpath',"//div[@class='gsc_col-xs-7 carsName']/a") driver.execute_script("window.scrollBy(0,document.body.scrollHeight)") time.sleep(0.5) continue for q in href_tags : url.append(q.get_attribute('href')) print(len(url)) for r in url: driver.get(r) delay=30 try: b=driver.fin...