Skip to main content

Posts

Showing posts from May, 2021

React app with nodejs/express server and mysql database doesn't load data right away when first visiting the home page. Related to mysql connection

I have an app with the server hosted on heroku where 15 of the latest entries in the database should show up when going to the home page. I have a a conifg.js file where I establish a connection to the database. The code used to be const mysql = require('mysql'); const db = mysql.createConnection({ host: 'host', database: 'db', user: 'user', password: 'password', }); module.exports = db; This was loading the latest entries on the home page properly on first visit but my app was experiencing crashes due to I believe it trying to query without there being a connection? Not entirely sure. I changed this code to const mysql = require('mysql'); let connection=null; function handleDisconnect() { connection = mysql.createConnection({ host: "host", user: "user", password: "password", database: "db" }); // Recreate the connection, s...

Someone help me with this error: Cannot set property 'type' of undefined. In my schema discord.js

I need help solving this problem. If I put 2 , or greater than 2 in $guaranteedTier in my database, I get this error "cannot set property 'type' of undefined. But if it's 1 in $guaranteedTier , it works normally. The error is on line 112 : cardToAdd.type = 'character'; Could tell me what I did wrong, and what could I do, to solve this? My Schema: const { model, Schema } = require('mongoose'); const Probability = require('probability-node'); const _ = require('lodash'); const cardPackSchema = new Schema({ name: { type: String, unique: true }, description: String, cards: Number, //Número de cartas dentro desse pack type: String, //Se é um Personagem, Feitiço, Item, Todos tier: Number, probability: { //Probabilidade de pegar cartas de especifico tier 1: Number, 2: Number, 3: Number, 4: Number, 5: Number, }, price: Number, discoun...

Score Tracking with angular [closed]

I'm building a game that increases the score by 2 points every time you answer a question correctly, I have the whole game built and the options ready but I'm not sure how to start the score function. (I'm using angular). Here's what I have if ur wondering: http://localhost:4200 Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Modify one component with another (HOC maybe?)

I have seen that some libraries such as "framer-motion" from react work using this syntax, for example to insert an animated H1: <motion.h1> which would translate to an h1 but with animations defined in the props of the component. What I don't understand is how the "motion" component accesses that "h1" and then in the function it knows which component to render animated. I need to create a component for example <lazy.div> that interprets a div with certain modifications that I am going to define. What I need to know is how to use that syntax and not the typical <Lazy><h1>Content<h1> </Lazy> Would it also be possible to use this type of syntax to modify chain elements or add functions to those already modified components? For example <lazy.fullwidth.div> Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

component state disappears after page is refreshed

I have a custom hook import { useState } from "react"; import { useDispatch } from "react-redux"; import axios from "axios"; import getDevices from "../actions/devicesAtions"; import { isPositiveInteger, FORM_FIELDS } from "../helper"; export default function useDevice(value) { const dispatch = useDispatch(); const [device, setDevice] = useState(value); const [msg, setMsg] = useState(""); const saveDeviceChange = ({ target }) => { const { name, value } = target; setDevice({ ...device, [name]: value }); setMsg(""); }; const saveDeviceSubmit = async ( e, axiosMethod, selectedUrl, newDevice = device ) => { e.preventDefault(); const { system_name, type, hdd_capacity } = device; if (!system_name || !type || !hdd_capacity) { setMsg( `Please fill out ${!system_name ? FORM_FIELDS.SYS_NAME : ""} ${ !type ? FORM_...

Top navigation items in header constantly flickers when typing

The image in the header constantly flickers when I type. May I ask how do I stop this flickering at the top right hand corner or accessoryRight? I am using this TopNavigation component from UI Kitten UI library. I don't think this is normal, it shouldn't happen at all. I must be doing something wrongly. https://youtu.be/fQppQn-RzeE (How do I embed this? Editor, thank you in advance!) The flickering happens in the title and the right side of the Navigation Header. I made a separate component for the TopNavigation and then call it in respective screens. Things I have tried: Since the outcome of the Header relies on navigation props , I tried using useState and useEffect (with navProps as the dependency) to save the prop instead of reading directly from props , but to no avail Directly adding the jsx into the TopNavigation's accessoryLeft/Right and title options Any input is welcome, appreciate it! TopNavigation: const NavHeader = ({ navProps }) => { cons...

Javascript Sum return only one iteration

Codeware Challenge So here what happening I'm trying to make a function that return the number i enter in the function parameter * the number of loop iteration i expect // 1 * 5 = 5 // 2 * 5 = 10 // 3 * 5 = 15 // 4 * 5 = 20 // 5 * 5 = 25 // 6 * 5 = 30 // 7 * 5 = 35 // 8 * 5 = 40 // 9 * 5 = 45 // 10 * 5 = 50 but i only get // 1 * 5 = 5 i know that return stop the loop from iterating but i can't figure out how to make the loop continue function multiTable(number) { //loop from 1 to 10 for(let i = 1; i <= 10; i++){ //create a string with the calculation let sum = (`${i} * ${number} = ${number * i}\n`); //return the sum return sum //this is where the error happen it only return the first iteration (1 * 1 = 1) // i expect it to return 1 * 1 = 1, 1 * 2 = 2 all the way up to 10 } } multiTable(5); Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

In React Hook, how can I change specific value of useState array?

let [_value, setValue] = useState([1, 2, 3, 4, 5, 1, 2, 3, 4, 5 ]); In this code, if I want to change the _value[3] how can I change value using setValue? In my project, I have to change the _value[index] when the (rating) button is clicked. So I have to dynamically change the _value[index]. If you know the answer, please let me know. Thank you! Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Checking values ​in the firebase database - Discord.js

Well, I'm new to programming and I have a question. I'm using firebase database, and I want to get values ​​from two users. Here is my database, and I have these two user ids as an example. I want to check if the value "mstatus" of the first user is set to "CASADO" , if it is, the bot will send an error message. At first I tried to do a verification of only the first user, but it didn't work out very well, the bot sent the error message, but he also executed a command that was not supposed to be executed when the value had defined "CASADO" database.ref(`Servidores/${message.guild.id}/Users/${user.id}/Casamento`).once('value').then(async function(fg) { if (fg.val().mstatus === 'CASADO') { return message.reply('oi') } }); Then I made the code that was to be sent if the values ​​were all right database.ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Casamento`).once(...

Cannot read property includes of undefined [closed]

I have to filter an array, it doesn't work for my project. This is the code: edit : This is the whole code: http://collabedit.com/2prqs $("#searchBar").on("keyup", function(e){ const searchString = e.target.value; console.log(searchString) let filteredCoins = coinsArray.filter((coin) => { return coin.symbol.includes(searchString); }); console.log(filteredCoins) }) and this is the error I'm getting: Uncaught TypeError: Cannot read property 'includes' of undefined Does anyone know why? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Old JS script in SparkAR stoped working with multiple errors

I created this JS script a long time ago for a face filter effect. After the new SparkAR update I needed to refresh the project to make it available for the users, but my old script now shows me a lot of errors. The script is used to change textures assigned to some materials when I click on different 3D planes in the scene. I tried to create a new script to see if the syntax has changed, but the brand new script also has errors. I looked in the documentation, the syntax seems to be right. How can I fix them? Example from my script: Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Resize React Bootstrap Table column sizes with fixed minWidth

I have a Bootstrap table where the columns are toggled. Due to the number of columns, I need to use horizontal flow to make it all fit inside. However, the size of the header and the column itself gets too small to a point that it's unreadable. So I have to set up a minimum width for each column. So, the columns should be in the whole table length at all times, and adapt the size to fill it all. However, when I am using the fixed minWidth and there are not many columns, the columns do not resize to fit the whole table. In the image below, the red square should not be appearing, but filled with the columns. I have created a sandbox link with the table that does not resize correctly. https://codesandbox.io/s/eloquent-almeida-9lgp2?file=/src/index.js I have searched stack overflow to help me with the horizontal overflow, this is the CSS I have used to do so, by the way. I think this is the reason why the columns are not resizing as they should. #table-employee-compensation { ov...

Page with dynamic content shifting to the middle on loading only safari

I created a docusaurus based website which includes some custom react components that are loaded with dynamic import using loadable-components. When I navigate between the pages both Chrome and Firefox work as expected but on Safari, as the page is loaded it is shown starting at some where in the middle depending on how many react components I have on that page. I did a bit of research and some point to overscroll-behavior which is not currently implemented by Safari. I am not sure if that is what is causing the problem. What can be done to make sure the docs page loads only at the top even if there is dynamic content (no ssr) on the page? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Add star icon on candlestick Google Chart

I'm trying to add a star icon to candlestick chart with Google Charts api, but I'm having difficulty. If anyone can help me: I saw it working on this google page: https://developers.google.com/chart/interactive/docs/points https://i.stack.imgur.com/blkeK.png As much as I add css and define the column type, it doesn't work. Below is my code, but this is the test link in jsfiddle: https://jsfiddle.net/wd4egpo1/ <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['x', 'n1', 'n2', 'n3', 'n4', {label:'point', role:'style', type:'string'}], ...

Bundle JS and CSS into single file with Vite

I'm having a devil of a time figuring out how to build a single .js file from Vite in my Svelte project that includes all of the built javascript and CSS from my Svelte projects. By default, Vite bundles the app into one html file (this is ok), two .js files (why??), and one .css file (just want this bundled into the one js file). What is the magic set of plugins and config that will output a single HTML file with a single js file that renders my Svelte app and its CSS onto the page? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Highlight current page with included header file

I have a header file that I include with php on every page. Inside the navigation I use php to check if someone is logged in. Depending on the check the header looks different (different list items). Following these guidelines ( highlight the current page in menu in php ) I am aware that a good way to achieve my goal is to declare a basename[PHP_SELF]-variable and then add some code to those list items. But that is where I mess up. Since I already use php inside my html to check if the user is logged in or not I get lost in the single or double quotes I need to use to add the php code to my list items. <header> <nav class="nav collapsible"> <ul class="list nav__list collapsible__content"> <?php echo "<li class='nav__item'><a href='contact.html'>Contact</a></li>"; echo "<li class='nav__item'><a href='about.html'>About</a></li>"; ...

Codeigniter emails not reaching Outlook and landing in spam folder in Gmail

I've been working on this code to send emails to people who want to make appointments at a Law Firm. My problem is that my emails don't land anywhere in Outlook and land in the spam folder in Gmail. I found many suggestions to similar problems online : encrypting the message, using newline("\r\n"), use set_header(), etc. but none of them seem to work. I'm using ovhcloud hosting and CodeIgniter 3. Here's my controller function, please help : public function nouveau_rdv(){ $prenom = $_POST['prenom']; $nom = $_POST['nom']; $email = $_POST['email']; $var = $_POST['date']; $date = str_replace('/', '-', $var); $date = date('Y-m-d', strtotime($date)); $sexe = $_POST['sexe']; $motif = $_POST['motif']; $tel = $_POST['tel']; if(is_null($email)!=1 && is_null($nom)!=1 && is_null($prenom)!=1 && is_null($motif)!=1 && is_nul...

Curl The requested URL returned error 404

so the problem is Curl return 404 error for this link. Work on localhost but not on live server, any idea why this error occur , Thanks. $url = $this->input->get('https://govid.xyz:2053/embed-r3ym33t0bfc0.html'); $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'; $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_USERAGENT, $agent); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_NOBODY , false); curl_setopt($c, CURLOPT_FAILONERROR, true); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($c, CURLOPT_SSL_VERIFYHOST , false); $contents = curl_exec($c); if (curl_errno($c)) { $error_msg = curl_error($c); echo $error_msg; }else{ echo $contents; } curl_close($c); if (isset($error_msg)) { // TODO - Handle URL error accordingly } source https...

Consulta sql donde la suma de los valores sea mayor a un valor

espero que se encuentren muy bien. Tengo una tabla donde se registran los id (en número) de usuarios y valores (en número) que corresponden a dinero de una transacción. Cada registro es una transacción. Quiero hacer una consulta en las que la suma del dinero de las transacciones sea mayor o igual a 100.000 por usuario, pero que traiga los registros de forma individual. Alguna idea de como puedo hacer la consulta?? Muchas gracias source https://stackoverflow.com/questions/67781257/consulta-sql-donde-la-suma-de-los-valores-sea-mayor-a-un-valor

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest [duplicate]

I'm trying to make an xmlhtttprequest request and this error always comes up and I'm told that this type of error only happens when there is some html tag in the php code and I can't see where it is. Of course, if the problem is not the php file, please indicate where it is. Arquivo Js: function connection() { document.getElementById("characterSpinnerSection").innerHTML = ""; document.getElementById("comicsSpinnerSection").innerHTML = ""; var xhr = new XMLHttpRequest(); var name = document.getElementById("name").value; var params = "name=" + name; xhr.open("GET", "./connections/name-search.php?" + params , true); xhr.onloadstart = function() { document.getElementById("characterSpinnerSection").innerHTML = '<strong id="spinnerText" class="text-primary">Loading character...</strong>' + '<div class=...

HTML in PHP [duplicate]

I want to achieve the following... I retrieve data from my MySQL database In this database I retrieve if the position is token or not if the position is taken I echo "sold" if the position is not taken I want to use a button (form) from coinpayments in my PHP the code is like this now but I cant make it work... if ($row["taken"] == "no") { echo "<td>" . "<form action="https://www.coinpayments.net/index.php" method="post"> <input type="hidden" name="cmd" value="_pay_simple"> <input type="hidden" name="reset" value="1"> <input type="hidden" name="merchant" value="2b2a959cbc1f2d1c80eac843dd0bc14a"> <input type="hidden" name="item_name" value="PLOT 0001"> <input type="hidden" name="item_desc" value="Blockch...

Permissions problem with files in PHP and unlink not deleting all files

I know there has been numerous postings about issues with PHP unlink, and I have tried quite a number of them in the past few days. Nothing seems to work. and it's getting desperate here. I keep receiving 'Permission denied' on the attachments that I extracted and wrote to disk. I am developing using Windows 10, Localhost:8081 using PHP 5.6.40, Wampserver with Apache 2.4.41 That being said, I am logged into my computer as administrator (which I gather doesn't mean a hill of beans to Apache). Here's the flow: I read a email, extract any attachments (files), write them to a folder (which is inside of my project), rename the files (keeping the renamed file in same folder as original folder) to a new name and upload only the newly RENAMED files. And it works well EXCEPT - it will not unlink (delete) the original file. It will unlink the new file (original file renamed), but not the original file. When I extracted the attachments, I wrote them out and issued a chmod(Orig...

How to fix HTML in repeating function ACF

first of all I´m a beginner in coding, I wrote this function to show ACF repeater timleine And he returns the result to me, but a problem when I add html function wpb_nos_formules(){ $html = ''; if( have_rows('formule') ) : $html .='<section class="design-process-section" id="process-tab"> <div class="container"> <div class="row"> <div class="col-xs-12">'; while( have_rows('formule') ) : the_row(); $title = get_sub_field("title"); $html .='<ul class="nav nav-tabs process-model more-icon-preocess" role="tablist"> <li role="presentation" class="active"><a href="" aria-controls="discover" role="tab" data-toggle="tab"><i class="fa fa-search" aria-hidden="true"></i> <p>'....

Python sort_values (inplace=True) but not really?

So I am trying to write a loop in python as I have to compare rows to each other in a table. I have to sort the data, which I do by 'sort_values', the dataframe seems to sort, yet when I step through it with a 'for loop' it is still unsorted? So I'm clearly not understanding how pandas memory allocation works. I have tried sorting to another dataframe and I get the same problem import pandas as pd data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'], 'date1': ['2000-04-18', '2000-04-16', '2000-04-15', '2000-04-25', '2000-04-16', '2000-04-17'], 'stat1': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]} frame = pd.DataFrame(data) frame output original unsorted: state date1 stat1 0 Ohio 2000-04-18 1.5 1 Ohio 2000-04-16 1.7 2 Ohio 2000-04-15 3.6 3 Nevada 2000-04-25 2.4 4 Nevada 2000-04-16 2.9 5 Ne...

How can I wrap all BeautifulSoup existing find/select methods in order to add additional logic and parameters?

I have a repetitive sanity-check process I go through with most calls to a BeautifulSoup object where I: Make the function call ( .find , .find_all , .select_one , and .select mostly) Check to make sure the element(s) were found If not found, I raise a custom MissingHTMLTagError , stopping the process there. Attempt to retrieve attribute(s) from the element(s) (using .get or getattr ) If not found, I raise a custom MissingHTMLAttributeError Return either a: string, when it's a single attribute of a single element ( .find and .select_one ) list of strings, when it's a single attribute of multiple elements ( .find_all and .select ) dict, when it's two attributes (key/value pairs) for multiple elements ( .find_all and .select ) I've created the below solution that acts as a proxy (not-so-elegantly) to BeautifulSoup methods. But, I'm hoping there is an easier eay to accomplish this. Basically, I want to be able to patch all the BeautifulSoup metho...

Python program to add the squares of numbers in list which have been entered by while-loop

I'm writing a program which should produce an output of something like this: `Enter an integer (or Q to quit): 1 Enter an integer (or Q to quit): 2 Enter an integer (or Q to quit): 3 Enter an integer (or Q to quit): Q (1 x 1) + (2 x 2) + (3 x 3) = 14` So far, I've gotten the display of the equation right, but I can't seem to figure out how to actually get the total of the equation. Currently, the total displays 18 instead of the expected 14 . Here's my code so far: `int_list = [] # initiate list while True: user_input = input("Enter an integer (or Q to quit): ") # get user input if user_input == "Q": # break loop if user enters Q break integer = int(user_input) # convert user_input to an integer to add to list int_list.append(integer) # add the integers entered to the list for i in range(0, len(int_list)): template = ("({0} x {1})".format(int_list[i], int_list[i])) if i == len(int_list)-1: trailing = " = ...

Timestamp is no longer supported error when creating a new column

I would like to ask a question abou the error I am getting here. I am trying to create a new column that intiate a position if the price of tomorrow is predicted higher than today using the following code. it is giving me the error: TypeError: Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n , use n * obj.freq new= pd.DataFrame(index=x_valid.index) new['Shares'] = [1 if x_valid[i+1] > x_valid[i] else 0 for i in new.index] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-92-5e7800e6d5ce> in <module>() 2 new= pd.DataFrame(index=x_valid.index) 3 ----> 4 new['Shares'] = [1 if x_valid[i+1]>x_valid[i] else 0 for i in new.index] <ipython-input-92-5e7800e6d5ce> in <listcomp>(.0) 2 new= pd.DataFrame(index=x_valid.index) 3 --...

code=H10 desc="App crashed" Heroku Application error

I am trying to deploy an ML model using Flask on Heroku but the application keeps failing. I checked the logs and this is what I get to be the errors. 2021-05-30T23:40:59.657322+00:00 app[web.1]: File "/app/wsgi.py", line 1, in <module> 2021-05-30T23:40:59.657322+00:00 app[web.1]: from app.app import app 2021-05-30T23:40:59.657322+00:00 app[web.1]: ModuleNotFoundError: No module named 'app.app'; 'app' is not a package 2021-05-30T23:40:59.657552+00:00 app[web.1]: [2021-05-30 23:40:59 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-05-30T23:40:59.660745+00:00 app[web.1]: [2021-05-30 23:40:59 +0000] [8] [ERROR] Exception in worker process 2021-05-30T23:40:59.660746+00:00 app[web.1]: Traceback (most recent call last): 2021-05-30T23:40:59.660747+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-05-30T23:40:59.660748+00:00 app[web.1]: worker.init_process() 2021-05-30T23:40:59....

Is there any equivelant of setCurrentBlockState of QSyntaxHighlighter in QsciScintilla?

Because the highlighting I want to use is needed to get the previous status of store in a variable in the previous line, and I can use it in the QSyntaxHighlighter by store it in setCurrentBlockState. For example: from PyQt5.Qsci import QsciScintilla class QsciLexerCustom1(QsciLexerCustom): def styleText(self, start, end): editor = self.editor() SCI = editor.SendScintilla interline_status = 0 for line in source: #(tokenizing the line) for token in tokenized_line: if token == "string1": interline_status = 1 if token == "string2": interline_status = 2 However, the interline_status will be reset to 0 while processing to the next line. I have found the variable QsciScintilla.SCI_GETSTYLEAT which is similar to what I want like below: pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index - 1) interline_state = SCI(QsciScintilla.SCI_GETSTYLEAT, pos) H...

Heroku flask application error No web processes running

I'm a newbie, trying to get a flask chatterbox application Github to work on heroku. I can get it running just fine, locally, but it deploys and nothing happens, I just get application error. This is the log I get with heroku logs --tail. I think it's something to do with this Procfile I have no clue about. 2021-05-30T23:56:46.955267+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=murmuring-refuge-89355.herokuapp.com request_id=d9837176-ecfd-4739-bb7d-9efe086feb58 fwd="177.208.24.201" dyno= connect= service= status=503 bytes= protocol=https source https://stackoverflow.com/questions/67766686/heroku-flask-application-error-no-web-processes-running

How to read many files and export the numbers of rows in one table using pandas? [closed]

Does anyone know how to initiate the loop to read all the files below and count the row in each table and export the number in one table? I use jupyter notebook to run the python (3.8) and use pandas to manipulate the data. I want to count how many tweets per day during certain period. I used twint to retrive the information and want to analyze the data. df01 = pd.read_csv("00_bitcoin_raw_2020-03.csv") df02 = pd.read_csv("00_bitcoin_raw_2020-04.csv") df03 = pd.read_csv("00_bitcoin_raw_2020-05.csv") df04 = pd.read_csv("00_bitcoin_raw_2020-06.csv") df05 = pd.read_csv("00_bitcoin_raw_2020-07.csv") df06 = pd.read_csv("00_bitcoin_raw_2020-08.csv") df07 = pd.read_csv("00_bitcoin_raw_2020-09.csv") df08 = pd.read_csv("00_bitcoin_raw_2020-10.csv") df09 = pd.read_csv("00_bitcoin_raw_2020-11.csv") df10 = pd.read_csv("00_bitcoin_raw_2020-12.csv") total_data_2020 = [len(df01),len(df02),len(df03),le...

Need help using Selenium Chromedriver and Python

I would like to print each merchant name next to "his" price of the page like this: Climaconvenienza 1.031,79 € Hwonline 1.031,80 € Shopdigit 1.073,90 € The code I made is this: browser.get('https://www.trovaprezzi.it/televisori-lcd-plasma/prezzi-scheda-prodotto/lg_oled_cx3?sort=prezzo_totale') wait = WebDriverWait(browser, 10) wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".merchant_name_and_logo img"))) wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".merchant_name_and_logo img"))) names = browser.find_elements_by_css_selector(".merchant_name_and_logo img") for span in names: print(span.get_attribute("alt")) all_divs = browser.find_elements_by_xpath("//div[@class='item_total_price']") for div in all_divs: print(div.text) But, by running my code, I get this: Climaconvenienza Hwonline Shopdigit 1.031,79 € 1.031,80 € 1.073,90 € source https:...

Drawing modular multiplication circle using turtle

I want to draw a modular multiplication circle using turtle library as showed in this link: https://yashaslokesh.github.io/mod-mult-circle.html My questions are: If the line already drawn, the turtle must not be passed by it again. So how to track the lines and how to do it? If the multiplicator is decimal, how to make the problem work? Since I have seen an animation like this: https://www.youtube.com/watch?v=qhbuKbxJsk8 from 12min17s Here is my code: import turtle import math pen = turtle.Turtle() pen.speed(0) #num = nb of points on the circle def Points(num, radius): points = [] for i in range(num): x = radius*math.cos(i*2*math.pi/num) y = radius*math.sin(i*2*math.pi/num) #coord = coordonnees des points coord = (x,y) points.append(coord) return points pointsList = Points(200, 250) #points = list of the coordinates of points on the circle def drawPoints(turtle, points): turtle.up() for i in range(len(points)): ...

How do I use exec() to parce an import statement to find if a module exists within a program

How do I use this format of code to find if a module exists within a python program? I know there are similar questions like this, but i need to specifically use exec() to parse an import statement. def file_exists(name): try: exec() return True #if the file does exist except: return False #tests file_exists(module1) #should return true because there is a module named module1 file_exists(module2) #should return false because there is not a module named module2. source https://stackoverflow.com/questions/67766657/how-do-i-use-exec-to-parce-an-import-statement-to-find-if-a-module-exists-with

How to call a function from another function without constructor in React native?

I need to call from my function " RegisterTaster " to my function " endRegisterAlert " but actually im not using constructor because i use the class like a const in react native. How can i call the function ? const Validator=(props)=>{ async function RegisterTaster(){ //do something... endRegisterAlert(); } function endRegisterAlert(){ //do something } return( <Button onPress={async ()=> await RegisterTaster() }> <Text >Register</Text> </Button ); } export default Validator; Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Need to pass string without removing the special characters in string in node.js [closed]

How do i pass string without removing the special characters in string in node.js ? I tried using string.raw but it removes special characters like ^ or / etc. I want to pass the string as is. I am using node js and puppeteer to pass username n password into the login pages of web apps. So the password would contain special characters. Hence i want to sent it as is. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to ignore accented letters in javascript? [duplicate]

I have a javascript code as shown below in which Line A prints the following output at console. const megaList = sortedMegaList.reduce((r, e) => { let group = e.title[0]; // Line B console.log(group); // Line A }, {}); o/p at console: B C D E É G H I L What I want achieve is I don't want to show accented letters in the o/p above. This is what I have tried in the code below. At Line B , I have made the following change: const megaList = sortedMegaList.reduce((r, e) => { let group = e.title[0].normalize('NFD').replace(/[\u0300-\u036f]/g, ""); // Line B console.log(group); // Line A }, {}); After changes at Line B , its ignoring all accented letters and Line A doesn't print any accented letters in the o/p. I am wondering if its the right way to ignore accented characters. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Custom property on File instance not cloned when passing to web worker

According to MDN, File objects can be passed to Web Workers and they are properly cloned using the structured cloning algorithm. So far, so good. And this works in all browsers I've tested: // myFile comes from a form. // webWorker is the WebWorker object. webWorker(myFile); // myFile appears as-is on the other side, // only losing non-enumerable properties // and functions, per the spec. But this doesn't work: // myFile comes from a form. // webWorker is the WebWorker object. myFile.customIdProperty = 'some string value'; webWorker(myFile); // myFile appears on the other side, // WITHOUT the 'customIdProperty' property. Curiously enough, this WORKS: // myFile is a custom object now. // webWorker is the WebWorker object. myFile = {}; myFile.customIdProperty = 'some string value'; webWorker(myFile); // myFile appears on the other side, // WITH the 'customIdPropert...

print selected information from select box by HTML

//I want to print selected information from selection of select box. But I don't know why the function 'print_info' doesn't work in my code. I think there's a problem in print_info's div tag because I can't see color icon next to the 'background-color'. Please let me know where should I fix. <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body style="text-align: center; background-color:#9191e988"> <div style="position: absolute; left: 60px; border:white; background-color:white; padding:10px;"> <p><font size="2">Select route</font></p> <form> <select name="number" id="NUM" onchange="changenumSelect(this.value)"> <option value=""disabled>select num</option> <...

Invalid Json response with API CURL PHP

I am trying to call an API using CURL , and the supplier is only allowed x-www-form-urlencoded's content-type, but it responds XML with JSON within it. However, in PHP's curl response, it will remove all xml tag. This is the respond I got : { "Description":"MERCEDES BENZ C 300 AMG LINE MY17 W205 FACELIFT 9 SP AUTOMATIC 9G TRONIC", "RegistrationYear":"2020", "CarMake":{ "CurrentTextValue":"MERCEDES BENZ" }, "CarModel":{ "CurrentTextValue":"C" }, "MakeDescription":{ "CurrentTextValue":"MERCEDES BENZ" }, "ModelDescription":{ "CurrentTextValue":"C" }, "Seats":"5", "Body":"SEDAN", } The registered car is a MERCEDES BENZ C 300 AMG The problem is at last "sentence" where it is not a valid json string, is there any way to remove unwanted "sentence" after the last }...

String comparison in PHP doesn't make sense … [duplicate]

I have this really basic PHP code I can't figure out. In the example below, why do I get 'MATCH' when $i = 0, and not for the remaining rows …? It seems to be possible to workaround by using === instead of ==, but I can't understand why. <?php $text = 'foo bar'; for ($i = 0; $i <= 5; $i++) { echo '<p>' . $i . ': '; if ($i == $text) { echo 'MATCH!'; } else { echo 'NOPE'; } } ?> source https://stackoverflow.com/questions/67731189/string-comparison-in-php-doesnt-make-sense

Stop Mediawiki tinymce editor to convert html code

I'm just started to working with mediawiki file. I installed Bootstrap extension there and added jquery also. Everything was fine but In tinymce editor when i use html tag like , after submit it's just vanished that tag & left only plain text. I searched similar issue since 2 days on internet but can't find solution that work for me. I've tried html entities, cleanup, valid_elements and many more things. Is there any solution ? any suggestions will be appreciated. Ask me if you want to see something. source https://stackoverflow.com/questions/67761425/stop-mediawiki-tinymce-editor-to-convert-html-code

Requested entity was not found error when calling spreadsheets_values with Google Sheets API (PHP)

I am using the Google Sheets API (PHP) with a service account. When running spreadsheet_values->get($spreadsheetId, $sheet_name, ['majorDimension' => 'ROWS']) I get a 404 error "Requested entity was not found". The spreadsheet ID is correct and the sheet in the drive has given the service account permissions. The weird thing is that this works on localhost, but has broken when moving to a web host (000webhostapp). Note that WordPress is being used with PHP version 7.2. The version of the Sheets API being used is v2.7. source https://stackoverflow.com/questions/67766436/requested-entity-was-not-found-error-when-calling-spreadsheets-values-with-googl

JS use video frame as canvas background

I'm attempting to use a the first frame of a video as the background of a canvas, as you probably guessed from the title of the question. I can set a background, I can get a frame from a video, but I can't make the frame be the background. It looks like I need a url for the frame to set as the background in the CSS style. For that, I need a blob on which I can call createObjURL() (although I'm discovering now that that method may be deprecated/ing). Here's some code: <!DOCTYPE html> <html lang="en"> <canvas id="back" style="background-image: url('path/to/.png')";></canvas> <input type="file" accept="video/*" /> <script> document.querySelector('input').addEventListener('change', extractFrame, false); var canvas = document.getElementById('back'); var context = canvas.getContext('2d'); var imageObj = new Image(); var image; ima...

How to insert unique object to Mongo Db or update it

I have a task to insert array of objects to mongo db collection. If the collection already has the record with same key parameters - update the values (if not - insert). My object look like this: { keyParameter: 'value', keyForUpdate1: 'someValue1', keyForUpdate2: 'someValue2', keyForUpdateN: 'someValueN', } I try to do following code: dataStore.collectionName.bulkWrite( myArray.map((item) => ({ updateOne: { filter: { keyParameter: item.keyParameter, }, update: { $set: { keyForUpdate1: item.keyForUpdate1, keyForUpdate2: item.keyForUpdate2, keyForUpdateN: item.keyForUpdateN }, $setOnInsert: { keyParameter: item.keyParameter, }, }, upsert: true } })) Now it doesn't work. First time it record array two times. After insert, but not update. What I do...

js canvas ctx clip not working with forEach

In the beginning, there is for loop to generate colors and push them to an array. after that I want to print 50 circles with colors but when I use the ctx clip it did not print only one of them when I don't use ctx clip its print 50 of them var arr= [] for (var i = 1; i < 50; i++) { var color = "#"+ Array.from({length: 6},()=> Math.floor(Math.random()*16).toString(16)).join(""); arr.push({ color:color, name:i }) } var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); canvas.width = 35 * 10; canvas.height = (arr.length /10) *35; var x = 0,y = 10; arr.filter(role => !isNaN(role.name)).sort((b1, b2) => b1.name - b2.name).forEach(role => { x += 30; if (x > 40 * 8) { x = 30; y += 30; } ctx.arc(x+12.5, y+12.5, 12, 0, Math.PI* 2 , false); c...

How do I access the onTextLayout event within a React Native Text component?

I have a React Native Text component that contains a user profile's information and has a max NumberOfLines at 2. I also have a TouchableOppacity button that says "Read More.." on it that clears the max NumberOfLines of the component. I don't want the "Read More" button to show if there the NumberOfLine is already 2 or less. In the documentation it says that the onTextLayout event would return an array with a TextLayout objects for each line but when I try to access it I never have anything returned. I've tried to access the onLayout event and I can get info from that event but it doesn't have the info that I need. Has anyone had this problem? <Text numberOfLines={2} onTextLayout={onInfoLayout}> test text test text test text test text test text test text test text test text </Text> } const onInfoLayout = React.useCallback((e:any) =>{ console.log("this is how long the text is", e); }, []); The c...

antd input auto resizing on focus

i'm using ant form, form.item, input etc... I made a page but the inputs are resized automatically when they are clicked. how can I prevent it to be happen explicitly? and I'm also struggling with applying css file to those antd components. here's some code <Form labelCol= wrapperCol= layout="vertical" scrollToFirstError={true} onFinish={handleSubmit}> <Form.Item required={true} label="input placeholder" > <Input name="name" value={state.name} onChange={handleChange} placeholder="example)... "/> </Form.Item> ... Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How can I get permutations of many different arrays with different number of values in them?

I read this medium article and I understand how to get permutations of values in one array. However I need to get the permutations of dynamically entered arrays. I want to make an app where I have multiple fields where I can enter multiple arrays with many values in them and I want to get all permutations after storing them. How can I get permutations of many different arrays with different number of values in them following the principles in this code? function permute(nums) { let result = []; if (nums.length === 0) return []; if (nums.length === 1) return [nums]; for (let i = 0; i < nums.length; i++) { const currentNum = nums[i]; const remainingNums = nums.slice(0, i).concat(nums.slice(i + 1)); const remainingNumsPermuted = permute(remainingNums); for (let j = 0; j < remainingNumsPermuted.length; j++) { const permutedArray = [currentNum].concat(re...

How to attach onClick Listener dynamically in a span tag and store it in MongoDB

I am trying to attach an onClick even in a span tag as like as below and would like to store it in MongoDb . but my event is not saving it is automatically removed and when I am fetching data from DB it is not available. How Can I fix it ? here is my code below let span = document.createElement("span"); myEvent=span; myEvent.setAttribute('onClick', 'removeElement'); here is what is storing in the db, <span onclick="removeElement" data-highlightid="1622237808204" style="background-color: rgb(114, 76, 249); cursor: pointer;">passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a pa</span> Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Jest error -- Cannot read property 'get' of undefined

I have the configuration of a service inside a component in React and I am having problems with jest and testing-library, the app is working but the test is blocking. import { appSetupConfig } from '.../myapp' import theConfig from '.../config' useEffect(() => { const allowAppInstance = appSetupConfig(); allowAppInstance.get(theConfig).then((value) => { if (value.something) { Do Something; } ...the rest of code }, []); This theConfig is an external file containing an object. This is the error: TypeError: Cannot read property 'get' of undefined 37 | const allowAppInstance = appSetupConfig(); 38 | > 39 | allowAppInstance.get(theConfig).then((value) => { Is there any way to mock this get in jest's setup.js? I don’t necessarily need to test this item yet, but I can’t proceed without it. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Extra entries in array

I have an odd issue where when adding results / events to a user empty entries are added to the array, what is strange is that when I a few at a time it appears to be ok, if I go back and add more this is when the entries appear. See below. Here is the code for adding the events. function addEvents(pos) { document.querySelector('#doupdate').addEventListener('click', function(e){console.log(athletes[pos]) e.preventDefault(); athletes[pos].comps.events.push(evtupdate.value); athletes[pos].comps.evresult.push(resultupdate.value); athletes[pos].comps.venue.push(venuup.value) athletes[pos].comps.edate.push(dateupdate.value); updateform.reset(); }); initially I used this code below for listing the events, and I thought that it was the for loop, causing the issue, I used that to display each set of results on a new line. for (let { firstName, lastName, eanum, comps:{events,evresult,venue,edate} } of athletes) { if (firstName=...

How do I make a number variable from a html number input?

I am looking to add the values of two input elements (in this case sliders, but in future development one will probably become a number input) and add them together. This value I would like displayed on the console (again, in a later stage this will be a full-on part of the site using .innerHTML). The code below treats the two values as text strings and just puts them next to each other (50+50=5050). I've tried using .parseInt instead of .value but that did not help. My HTML code: <input id="FirstSliderElement" type="range" min="0" max="100"> <input id="SecondSliderElement" type="range" min="0" max="100"> <button onclick="thisIsMyFunction()">Show in Console</button> My JS code: var sliderOne = document.getElementById("FirstSliderElement"); var sliderTwo = document.getElementById("SecondSliderElement"); function thisIsMyF...

How do I approach solving this problem: Cannot access 'calculationEntry' before initialization?

I'm developing a large CRA single page app. It has been running fine for months, with the normal bugs that are normally fixable. A couple of weeks ago it failed by just hanging in the splash page with a spinning circle. No code was hit so no breakpoints worked. I did a lot of experimentation with the importing and exporting of all the files, thinking that was the root cause. Finally I thought to do a build and run that. That did get past the splash screen and generate an exception. The first was fixed, but now I get this Cannot access 'calculationEntry' before initialization error. I'm using VSCode and the launch.json configuration is: "name": "Chrome React", "type": "chrome", "request": "launch", "sourceMaps": true, "url": "http://localhost:3000", "webRoot": "${workspaceRoot}/src", "userDataDir": "${workspaceRoot}/.chrome", ...