Skip to main content

Posts

Showing posts from October, 2021

State Variables become null When UseEffect hook is used

I'm trying to make new requests whenever user reach the bottom with the following; useEffect(() => { const scrolling_function = () => { if((window.innerHeight + window.scrollY) >= document.body.offsetHeight-10){ window.removeEventListener('scroll',scrolling_function) getMoviesFromApi() } } window.addEventListener('scroll', scrolling_function); }, []) But the state objects that I defined, such as: const[selectedGenres, setSelectedGenres] = useState(new Set()) All becomes undefined in the inside of my useEffect hook, and thus my getMoviesFromApi() method does not work properly. My question is, is that expected behavior? If so, how could I overcome it? The getmoviesfromapi method: const getMoviesFromApi = async () => { setLoading(true) let init, end; if(initialYear>endYear) { init = endYear end = initialYear } else { init = initialYear end = endYear } let res =...

Replace HTML tag with string that contains tag attribute

consider this string: the quick&nbsp;<input type="button" disabled="" value="brown.fox" />&nbsp;jumps over the&nbsp;<input type="button" disabled="" value="lazy.dog" /> I would like to replace every occurrence of the <input type="button" tag with a string that contains the value attribute of the tag, specifically with this string ${} So the end result should be the quick&nbsp;${brown.fox}&nbsp;jumps over the&nbsp;${lazy.dog} Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Php string condition check for plugin

I have that function inside on a wp all import plugin for Wordpress to import products,that takes the first value and renames to the second value, a simple mapping function. I want simply insert an condition that checking that strings and if isn't on that strings then the new string will be $cat=uncategorized>$cat in other words if isnt on my dictionary for example $cat=cars then i want to replace to uncategorized>cars function cat_change($cat){ $cat = str_replace("XLARGE", "XL", $cat); $cat = str_replace("xl", "XL", $cat); $cat = str_replace("extralarge", "XL", $cat); $cat = str_replace("XXL", "2XL", $cat); $cat = str_replace("2XLARGE", "2XL", $cat); $cat = str_replace("2large", "2XL", $cat); $cat = str_replace("2xlarge", "2XL", $cat); $cat = str_replace("XXXL", "3XL...

Links between HTML pages not working correctly

I am making a project in the p5.JS web editor. So far it has a start screen but I want to create separate HTMLs for the login and account creation using the button boundaries as links to each other; I don't know how to do that, so for now I am just using regular links. I want to use a database to store these details (I want to use a MySQL database through phpMyAdmin by using XAMPP, but if there is a better way to do it with the p5.js WEB EDITOR please let me know!) I am testing the link between the index.html to the signup.html (Which has the sketch page.js to test) This link to the signup is where I want the users to create details for an account which will be put into the database. On click to the sign up the link appears to load the HTML correctly, but when redirecting back to the start screen (index.html) input boxes and links are mispositioned and the gif doesn't play. Is there anyway somebody could help me with this? I don't have too much experience with p5.js or HTM...

Tkinter Notebook tab header background ERROR

I'm trying to change the background colour of tab headers and it works perfectly when I run the app for the first time however when I click on other menu buttons and turn back to page where the tabs are it doesn't even show the tabs! I can only see an empty canvas! How can I fix the problem? Can anyone help me please? Thanks in advance for your help def ch_fr(): frame_ch = Frame(screen) frame_ch.place(relx=0, rely=0, relwidth=1, relheight=1) WIDTH, HEIGTH = 1540, 821 canvas2 = Canvas(frame_ch, width=WIDTH, height=HEIGTH, bd=0, highlightthickness=0) canvas2.place(relx=0, rely=0, relwidth=1, relheight=1) firstcolor = "#f36958" secondcolor = "#132d7d" style = ttk.Style() style.theme_create("th_chp", parent="alt", settings={ "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0]}}, "TNotebook.Tab": { ...

how can I resolve this key error in this section of program

I have a problem with this section of my code that it returns to the diffusion analysts of materials from pymatgen.analysis.diffusion.analyzer import ( DiffusionAnalyzer, fit_arrhenius, get_conversion_factor, ) import json from pymatgen.analysis.diffusion.aimd.van_hove import VanHoveAnalysis %matplotlib inline data = json.load(open(".../py.pro/mp-1138_LiF.json", "r")) new_obj = DiffusionAnalyzer.from_dict(data) vhfunc = VanHoveAnalysis(diffusion_analyzer=new_obj, avg_nsteps=5, ngrid=101, rmax=10.0, step_skip=5, sigma=0.1, species = ["Li", "F"]) vhfunc.get_3d_plot(mode="self") vhfunc.get_3d_plot(mode="distinct") and the key error says this KeyError Traceback (most recent call last) <ipython-input-4-17584fdb7b1f> in <module> 3 data = json.load(open("J:/py.pro/mp-1138_LiF.json", "r")) 4 ----> 5 new_obj = ...

python kernel crashes when plotting with matplotlib after conda update

I have create this simple env with conda : conda create -n test python=3.8.5 pandas scipy numpy matplotlib seaborn jupyterlab The following code in jupyter lab crashes the kernel : import matplotlib.pyplot as plt plt.subplot() I don't face the problem on linux. The problem is when I try on windows 10. There are no error on the jupyter lab console (where I started the server) and I have no idea where to investigate. source https://stackoverflow.com/questions/69786885/python-kernel-crashes-when-plotting-with-matplotlib-after-conda-update

insert n in list x --> append list x to list y --> delete n in list x

I'm trying to insert the number "1" to the list in every position with a for loop and eventually get all possible lists in python. For Example: l = ["2","3","6"] number = "1" output = [[ "1" ,"2","3","6"],["2", "1" ,"3","6"],["2","3", "1" ,"6"],["2","3","6", "1" ]] l = ["2","3","6"] list_of_nrs = [] for index in range(len(l)+1): l.insert(index, "1") list_of_nrs.append(l) del l[index] print(list_of_nrs) So I've tried it like the code above me, but the output I get is: [['2', '3', '6'], ['2', '3', '6'], ['2', '3', '6'], ['2', '3', '6']] It seems like there is a problem between the append and del function. source http...

i don't know why , when i'm install matplotlib it's can't [duplicate]

ERROR: Command errored out with exit status 1: 'C:\Program Files\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\USer\\AppData\\Local\\Temp\\pip-install-lfu2ezm2\\matplotlib_a6f263fb06cb49b0ba9dd9f1bc0eef1f\\setup.py'"'"'; __file__='"'"'C:\\Users\\USer\\AppData\\Local\\Temp\\pip-install-lfu2ezm2\\matplotlib_a6f263fb06cb49b0ba9dd9f1bc0eef1f\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install...

Web Page is getting crashed on value change of range Slider

I have Slider for range change in my react application. On value change of that slider, page is getting crashed. Following error is showing in chrome : The following page(s) have become unresponsive. You can wait for them to become responsive or kill them. Short code overview : React code handler for Slider (MUI) : const handleRangeChange = useCallback( (sensorConfiguration) => { setSensorConfigurations({ ...sensorConfigurations, ...sensorConfiguration, }); onChange({ target: { name: name, value: { ...sensorConfigurations, ...sensorConfiguration }, }, }); }, [sensorConfigurations, name, onChange] const handleTemperatureChange = useCallback( (value) => { handleRangeChange({ TEMPERATURE: value }); }, [handleRangeChange] ); return ( <SensorRange range={sensorConfigurations.TEMPERATURE} min={DEFAULT_SENSOR_RANGES.TEMPERATURE.min...

how to restart a loop requestAnimationFrame

I'm tring to make a game and i want to use window.requestAnimationFrame() to make roles move, the movement seems to be right at first. but there is problem that when i re-trigger move() immediately after triggering pause() , the movement will be faster and faster, i have code blow, move() 、 pause() and initListener() are functions about movement type state = "init" | "mount" | "moving" | "pause" | "end"; interface position { left: number; top: number; } interface elProps { id: string; text: string; avatar: string; } export default class Bullet { public el: HTMLElement; public targetEl: HTMLElement; public unit: string = "px"; private id:string; private state: state; private position: position; private animationId: number | undefined; constructor(props: elProps) { if (!props) return; this.el = document.createElement("div"); this.initEl(props); } initEl(props: elP...

While running test case I'm getting syntax error: Cannot use import statement outside a module

While running testcase in my react application I'm getting this issue "Syntax error : Cannot use import statement outside a module". I'm using reactjs . I have tried few solutions including adding "type": "module" in to package.json ,after build using this command npm run build , i am getting error like this Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How can i assign my JavaScript value to html:hidden property in JSP?

How can i assign my JavaScript 'x' value to html:hidden property. Below my JSP file code. <%@ taglib uri="/WEB-INF/tlds/struts-bean.tld" prefix="bean"%> <%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html"%> <script language="JavaScript" type="text/JavaScript"> var x=10; document.getElementById("bookid").value=x; </script> <html:hidden property="book" id="bookid"/> I tried using " document.getElementById("booking_channel_id").value=x; " But it is not working. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Why is the default running even though the num is set to 1?

let spans = document.querySelector(`#spans`); let hrs = document.querySelector(`#hrs`); let mins = document.querySelector(`#mins`); let secs = document.querySelector(`#secs`); let start = document.querySelector(`#start`); let stop = document.querySelector(`#stop`); spans.style.fontSize = "10em"; let preFix = 0; let num = 1; let secspreNum= 0; let minspreNum = 0; let hrspreNum = 0; let myFunc = ()=> { setInterval(()=>{ switch (num){ case num===1: mins.innerHTML = `0` + num; num ===0; secs.innerHTML =`0`+ num++; default: console.log(`default test`) } } , 1000); }; start.addEventListener(`click`,myFunc) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewpor...

development - production incompatibility, ubuntu, apache2, php, mysql

My website seems to work fine, except one feature (uploading a document and saving info on the document to a mysql table only works on my local (deveolping machine), I do not get helpful error message for debugging For both my development machine and production virtual server (EC2 on aws), Im using ubuntu 20.04 with identical set up ( apache2 (apache/2.4.41, php 7.4.3 and mysql 8.0.27), the php.ini files are the same on both servers (yes, error reporting ON for the production server for now while I get to bottom of this) Any ideas where the incompatibilty lies? source https://stackoverflow.com/questions/69789116/development-production-incompatibility-ubuntu-apache2-php-mysql

Trying to insert multiple checkbox values in separate rows in MySQL table in PHP not working [duplicate]

I have a simple form in PHP like below: <div class="col-md-4 ip"><label>Select Class</label><br> <?php $ret=mysqli_query($con,"select * from class"); $cnt=1; while ($row=mysqli_fetch_array($ret)) { ?> <div class="form-check"> <input name="classname[]" class="form-check-input" type="checkbox" value="<?php echo $row['class_name'];?>" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> <?php echo $row['class_name'];?> </label> </div> <?php }?> </div> Now I want the user selected checkboxes to get inserted in database in separate rows, so I did the following PHP code: $classname=$_POST['classname']; foreach ($classname as $pop ){ $ins_query="insert into study_material (`classname`) values ('$pop')";...

How Do I Connect My Laravel Project[views] file to Route Auto Created with Jetstream?

I am actually following up on a Laravel course that uses Blade component template and the tutor coded the Login/Register/Dashboard, etc individually. I couldn't keep up with the coding and I sorted for a quicker way of adding those features. That was how I discovered I can do those things with Jetstream. I installed Jetstream/Livewire and the above mentioned features were added automatically with a default view/welcome.blade.php connected to Route/web.php . Now here is my problem. Because I still want to follow through with the course by using Blade template method, I deleted the defaulted welcome.blade.php (as the tutor did too), created two folders with a file respectively: Layouts/app.blade.php and Posts/index.blade.php . On the Route/web.php , I changed the default welcome to post.index but it is not working. Here is the code on my Route: Route::get('/post', function () { return Inertia::render('post.index', [ 'canLogin' => Route::h...

How to make windowsAuthentication together with anonymous option?

How to make windowsAuthentication together with anonymous option? IIS set up for anonymous and windows authentication will always force me to have anonymous users. I have a solution for older symfony 2.8 where there are services like windowsAuthenticationListener, windowsAuthenticationEntryPoint, windowsAuthenticationProvicer, windowsAuthenticationToken and windowsAuthenticationFactory to add, but rewriting them to symfony 5.2 after a few hours has no solution. Does anyone have a working solution for symfony 5.2? Anonymous or windows only authentication are easy, but for the combination I need to do some subrequests for http 401 challenge and here I have no idea... This must be a frequent requirement, to have part of the site under SSO and another for anyone... source https://stackoverflow.com/questions/69789045/how-to-make-windowsauthentication-together-with-anonymous-option

Livewire Updated hook with multiple input

I have this data $date = '21-10-1996'; $id = '1'; $count = 0; And now I want to update the $count data when every $date data and $id data are updated in the livewire form. how to properly do that? I have done public function updateddate($selected_date){ return($selected_date); } public function updatedid($selected_id){ $count = select:where('id', $selected_id)->where('date', $this->updateddate($this->date)->count); } but the data will only be updated if I change the $id only. if I change the $date , I have to update the $id after that so that the $count data is updated. source https://stackoverflow.com/questions/69788831/livewire-updated-hook-with-multiple-input

write using import streamlink module OR by runnong subprocess or os.system command?

I see some streamlink api available, but see hardly any info like examples on how to use it. What I am essentially trying to do is capture a live video from a specific youtube channel. I ONLY CARE ABOUT THE AUDIO, AND NOT THE VIDEO. So, a part of my script will be after I capture the .ts video file using streamlink, to convert it to .mp3 using ffmpeg. Because I dont think streamlink can capture a live stream as mp3? What is the best way to convert the file to mp3? Would it be to run the ffmpeg command AFTER the video is captured so that the script will wait to run further until the convert is finished? What I think is probably better is to run the ffmpeg command as a separate thread or thread separate from streamlink. So that way, streamlink can continue capturing/downloading while ffmpeg can run parallel at the same time converting the past .ts file to mp3. It seems much easier to run streamlink through os.system or subprocess and just run streamlink as a command passing the argu...

D3 Org Chart with custom React components returning object Object

I'm creating an org chart using React and this library: https://github.com/bumbeishvili/org-chart . It uses D3 to create the org chart. I want to use custom React components to style each node in the org chart, but when I try to set the node content to a React component, it returns {object Object} instead of actually rendering the component. Please take a look at this Stackblitz for reproducing the error: https://stackblitz.com/edit/d3-org-chart-react-integration-hooks-oysugz?file=OrgChart.js Here I try to set the node content to <TestOrgCard/> but as you can see, it does not render. Does anyone have an idea how to render cards using custom React components? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to get just the name of a country from a geojson object in javascript? [duplicate]

I have a geojson object like the one defined at the bottom. I am trying to get just the name of each country and feed it into an array but can't figure out how to. I can only get access to the feature using worldData.features but when I try to do worldData.features.properties.name it gives me undefined error. Any help will be appreciated. Thanks. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Zoom Functionality Not Implemented, need alternative

So I've been working with a React & D3 package called "react-d3-graph". Noticing I couldn't handle zooming, I took a look at their library functions and noticed onZoomChange was never implemented. They had written private helper functions for zooming, but never declared the function itself. I was wondering if there is an alternative that would force zoom onto the Graph, and I was thinking there might be some way defaulting onto D3's zoom, but I'm not sure. These functions are declared in the svg/components/graph/Graph.jsx. Here is their render of acceptable functions: render() { const { nodes, links, defs } = renderGraph( this.state.nodes, { onClickNode: this.onClickNode, onDoubleClickNode: this.onDoubleClickNode, onRightClickNode: this.onRightClickNode, onMouseOverNode: this.onMouseOverNode, onMouseOut: this.onMouseOutNode, }, this.state.d3Links, this.state.links, { ...

TypeError: this.props.handleLogin is not a function

import React, { Component } from "react"; class Login extends Component { constructor() { super(); this.handleSubmitLogin = this.handleSubmitLogin.bind(this); this.state = { username: "", password: "", signupEmail: "", signupPassword: "", account: {}, } } handleChange = (e) => { this.setState({[e.target.name]: e.target.value}); } handleSubmitLogin = (e) => { e.preventDefault(); fetch('/rest/login', { method: 'POST', redirect: 'follow', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.state.username, password: this.state.password, }) }).then(response => { if (response.status ==...

Discord.js v13 Reaction Roles

I already have this code to post an embed and to add a reaction, I'm just wondering how I would go about adding a role to a user when they add the reaction? if (message.content.startsWith(`${prefix}rr`)) { let embed = new MessageEmbed() .setColor("#ffffff") .setTitle("📌 Our Servers Rules 📌") .setDescription("To keep our server safe we need a few basic rules for everyone to follow!") .setFooter("Please press ✅ to verify and unlock the rest of the server!") .addFields( { name: "1.", value: "Stay friendly and don't be toxic to other users, we strive to keep a safe and helpful environment for all!", }, { name: "2.", value: "Keep it PG-13, don't use racist, homophobic or generally offensive language/overly explicit language!", }, { ...

Using PHP to read real time serial data

I am using a Raspberry Pi to read real time RS232 data via a USB port using a Prolific 2303 adaptor. I want to parse this and display it in a web page. My first approach was to use a python script. This could read and parse the data but passing it to a PHP web page proved a problem. Either I could use GET to send it or save it to a file and read it with PHP. The latter is a non starter with an SD card, it's not going to last too long and the former might involve file storage anyway. I then tried a PHP approach; $device = "/dev/ttyUSB0"; $fp = fopen($device,"r") or die(); while(true){ $xml = fread($fp,"400"); print_r($xml); } fclose($fp); print_r(); produces: CC128-v0.110011909:27:3016.70000951000660008500024 CC128-v0.110011909:27:3616.70000951000670008600024 CC128-v0.110011909:27:4216.70000951000680008700027 CC128-v0.110011909:27:4816.70000951000680008600024 CC128-v0.110011909:27:5516.70000951000680008800024 This is 5 bursts of XML strippe...

how to plot a time after conversion

hello i want to convert one column to time and then plot it what i did is this df = pd.read_csv('vv.txt',sep=" ",names=list(["time", "size", "type"])) df.time = df.time.apply(lambda X: "{0:02.0f}:{1:02.0f}".format(*divmod(float(X) * 60, 60))) df["time"] = pd.to_datetime(df["time"], format='%H:%M' ).apply(pd.Timestamp) df["time"] = df["time"].map(lambda x: x.strftime("%H:%M")) plt.scatter(df['time'], df['size']) and it shows this as a result, no X-axis is showing right how can i solve this ? enter image description here source https://stackoverflow.com/questions/69781427/how-to-plot-a-time-after-conversion

Deleting the leaf node in a binary tree

I am implementing a BST and everything works, even the deletion with two children.The only bug is in the deletion of a leaf which seems such a trivial task. There seem to be still a reference to the leaf node but I can’t get on top of this issue.Putting node = None doesn’t remove the entire Node.I have also tried del node without any luck.If you could spot the problem it would be nice. import random class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None self.left_child = None self.right_child = None self.level = None class Tree: def __init__(self): self.root = None self.size = 0 self.height = 0 def _insertion(self, root, data): new_node = Node(data) if root.data < data: if root.right: return self._insertion(root.right, data) root.right = new_node root.right.parent =...

Rotate set of points

Is there a way to rotate 2d point shape (2d pose NumPy array) 90 degrees as in this image pose upside down its 18 point NumPy? poses_2d [[ 24 170] [ 27 183] [ 21 130] [ 38 170] [ 44 150] [ 38 149] [ 23 131] [ 26 102] [ 19 71] [ 13 169] [ 5 153] [ 15 146] [ 21 126] [ 27 92] [ 21 59] [ 28 183][ 29 181] [ 24 185] [ 21 184]] Thanks source https://stackoverflow.com/questions/69781395/rotate-set-of-points

How to replace a part of a File Path in Python

import os.path original = input(str("Filepath:")) filename = os.path.basename(original) print(filename) target = r'C:\Users\Admin\Desktop\transfer\filename' path = filename.replace('filename', filename) print(path) I have a problem with getting new target path... I need to copy original file and paste it to new directory, that is always the same and the name must stay the same as it was in previous directory, I was trying to do it by code on top but it doesn't work, only thing I need to know is how to replace name of the Path file at the end. (Example: r'C:\Users\Admin\Desktop\Directory2\***' and replace *** with filename of first file) source https://stackoverflow.com/questions/69781393/how-to-replace-a-part-of-a-file-path-in-python

Run python script at the start before starting flask app

I have a python script that needs to be running before even starting flask app. it keeps checking database and if there is an entry it will take data, process it and return results to database. Now I need to deploy it on server but I can't understand how it can be done. There is a similar question while trying provided solution as following @app.route('/') def run_script(): file = open(r'/path/to/your/file.py', 'r').read() return exec(file) it only runs that file and doesn't return index.html file. I have also tried to call run_script inside index function where is returns index.html file, but still it only runs script, rather than returning index.html . The main purpose to use this script is to save memory as it creates an instance of deep learning model and if I create this instance with every user call it consumes too much memory. script code can be found in this gist and quest_df = flask_qg.gen_qa(input_text) creates that model. Can ...

React native, how to blur image with affecting his shadow? [duplicate]

How to blur image with affecting his shadow like this image: In css, it gives me something like this: filter: blur(100px); And I don't want to get this: backdrop-filter: blur(100px); Before : After (what I want) : Thanks. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

vue-cookies update a specific value in cookie inside a mixin

I am trying to use vue-cookies package and setup an initial cookie like this which works: this.$cookies.set('toDo',{ id:1, completed:false}); in a mixin I am running some other conditions and I want to update the value of completed to true when calling that method in child components. but if I do: this.$cookies.set('toDo',{ completed:true}); then it overwrites and I lose the id value. How can I just change completed value to true and not overwrite the entire cookie value? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How I get the details in cells of table from id's using Javascript function

I have a dropdown list like this: <select id="itemsList" onchange="gettingList()"> <option>Please select the option</option> <option value="50">Soap</option> <option value="100">Sugar</option> <option value="290">Oil</option> </select> <br><br> I get the price of the product from the above list. after, clicking the button I unable to get the result. <input type="number" id="price" disabled=""> <br><br> <input type="number" id="quantity" onChange="calculate()"> <br><br> <input type="number" id="result"> <button type="button" onclick="addDetails()">Add</button> Code for the table <table id="myTable" border="1"> <tr> <th>Product Name</th> ...

Extract property from an array of objects and create another one base on this property via lodash?

I have the following array: [ { baseAsset: 'XRP', quoteAsset: 'ETH', quoteAssetPrecision: 6, baseAssetPrecision: 8, price: '0.00025170' }, { baseAsset: 'MOD', quoteAsset: 'BTC', quoteAssetPrecision: 8, baseAssetPrecision: 4, price: '0.00004280' }, { baseAsset: 'MOD', quoteAsset: 'ETH', quoteAssetPrecision: 8, baseAssetPrecision: 4, price: '0.00116700' }, { baseAsset: 'ENJ', quoteAsset: 'BTC', quoteAssetPrecision: 8, baseAssetPrecision: 8, price: '0.00004508' }, { baseAsset: 'ENJ', quoteAsset: 'ETH', quoteAssetPrecision: 6, baseAssetPrecision: 8, price: '0.00064370' }, { baseAsset: 'STORJ', quoteAsset: 'BTC', quoteAssetPrecision: 8, baseAssetPrecision: 8, price: '0.00002090' }, { baseAsset: 'S...

add class to element in viewport

I have five sections on my page, and I am trying to add class "active" to the section in the view port. I tried this code but it is not working properly. the code saves all elements with tag name "section" in a node list then created an array of this list, I looped over the array and added an event listener for each element, then I tested if the element is in the viewport is so I add the class else I remove the class. the problem is once the page is scrolled all the five sections will have the class "active" which means that multiple elements have the class "active" at the same time even though only one section is viewed in the port and when I keep on scrolling down the sections that are moved upward out of the viewport have their class "active" removed. how can i have one element with the class "active" image of code at a time? //values of viewport const viewWidth = document.documentElement.clientWidth; const viewHeight = d...

Visit a page using Javascript without leaving the current page

I have a Javascript file running on a page and I would like to log certain events as they occur. For example, I have a web store - and when people add an item to their cart, I want to log this event by visiting a page that I built: function log_event(id) { window.location.href = 'https://example.com/log/cart.php?id=' + id; return false; } The log/cart.php page doesn't really have anything to display, all it does is insert a record into a database containing the item that was added to the cart, and the date. The code that calls this function looks like: document.getElementById('add-to-cart').addEventListener('click', function() { // Add to the cart ... // Track the item that was added let id = document.getElementById('add-to-cart').getAttribute('data-id'); log_event(id); }); With my current code, the log/cart.php actually replaces the current page. I want the opening of log/cart.php to only happen in the background witho...

How i Can Create a Volume Div For the Iframe where i can Control the Iframe Volume without click on IFrame Volume icon?

I want to create a separate div down the iframe where I can control the volume of the iframe without clicking on the iframe volume icon Iframe Code is here <div class="entry-content post-body" id="post-body-5924716169213906958">&nbsp; <div class="separator" style="clear:both"><iframe frameborder="0" height="500" id="thatframe" allowfullscreen="true" scrolling="no" src="https://www.newucp.com/hembedplayer/webcricn02/3/800/500" width="100%"></iframe></div> </div> Picture of Iframe Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Prevent overlay click for elements with a higher z index

I have a simple overlay that I want to catch click events on. Problem is, I don't want any clicks that occur within the content of the overlay to trigger an event. For example, if you look at my code snippet below, clicking inside the .content div should not trigger the click event listener that I set on the overlay, but it does. Basically I want to just know when someone clicks the black background of the overlay. Is there anyway to do this with how I currently have my code? const overlay = document.querySelector('.overlay') overlay.onclick = function() { console.log('click on overlay!') } body { margin: 0; } .overlay { position: fixed; top: 0; left: 0; background-color: rgba(0,0,0,0.5); width: 100%; height: 100%; z-index: 10; } .content { width: 200px; height: 200px; position: absolute; z-index: 11; top: calc(50% - 100px); left: calc(50% - 100px); background: white; display: flex; align-items: center; justify-content:...

How to test a setTimeout function with jasmine?

i need to write a test for a function that has a setTimeout() call inside, but i can't find how i should do. This is the function setTimeout(() => { this.loading = false; $('.pre_loading').fadeTo(1500, 0); setTimeout(() => { $('.pre_loading').remove(); }, 400); }, 3500); } Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Javascript Limitations of Google Apps Scripts WebApps? [closed]

C'mon help me push the boundaries a little here... Google supports sticking your Javascript in an html file. This guy shows how to display images in a webapp done in a google script. That guy makes those images have s3x (I mean, give me a better description here!) Settings variables for the images residing in a Google Drive in the Code.gs and later trying to use them in the javascript file doesn't work. I get a blank screen. Is this a limitation of Google or a Javascript knowledge limitation on my part? This here is the code dot js where I map the two images. This shows the html we see This is where the magic happen... the css.... Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Executing AJAX based on times stored in two different arrays?

This is one of those situations that its a bit tricky to explain the issue but I will try my best to explain it so I can get some help here. basically I have a project that I need to allow the users to login/logout even if they have no internet connections. Every time they login/logout while offline, I store 2 arrays and push to it so I can log them in/out accordingly based on the time they logged in/out. The arrays look like this: var logins = [{"id":1,"dateAdded":"2021-10-29T18:27:35.754Z"}, {"id":2,"dateAdded":"2021-10-29T18:28:35.754Z"}, {"id":3,"dateAdded":"2021-10-30T18:28:35.754Z"}]; var logouts = [{"id":1,"dateAdded":"2021-10-29T18:27:50.754Z"}, {"id":2,"dateAdded":"2021-10-29T19:28:35.754Z"}]; To explain the arrays, the id is the id of the account that they logged in/out . the dateAdded is basically the time date that the...

MYSQL query code to check if statement and get row values

so I was trying to use if statement on MySQL. I have a table contains tp1 column and in this column I have two different string values L1_ON or L1_OFF, I want to get L1_ON if there is one on tp1 column but if there is no L1_ON just get L1_OFF. this is what wrote and i know it's not correct just for extra explanation. $query1 = sprintf('SELECT id,dateandtime,tp1 FROM plate WHERE AND IF(tp1 LIKE "L1_ON") else (tp1 LIKE "L1_OFF") ORDER BY id ASC LIMIT 1'); source https://stackoverflow.com/questions/69772844/mysql-query-code-to-check-if-statement-and-get-row-values

how to change file from required to not required in this code?

<?php $cityIdError = (isset($errors) && $errors->has('city_id')) ? ' is-invalid' : ''; ?> <div id="cityBox" class="row mb-3 required"> <label class="col-md-3 col-form-label" for="city_id"> <sup>*</sup></label> <div class="col-md-8"> <select id="cityId" name="city_id" class="form-control large-data-selecter"> <option value="0" > </option> </select> </div> </div> source https://stackoverflow.com/questions/69773044/how-to-change-file-from-required-to-not-required-in-this-code

How to mount wordpress upload folder to another drive in ubuntu

I'm already mounted upload folder with this command: sudo mount /dev/sdb1 /var/www/html/upload But wordpress media don't working and site images can't be load. I cannot upload any file to the server Is it possible to fix this problem? source https://stackoverflow.com/questions/69773028/how-to-mount-wordpress-upload-folder-to-another-drive-in-ubuntu

Having 2 different values in one dropdown

I have this dropdown in codeigniter Nama Barang . This is the code : <div class="form-group"> <label>Nama Barang</label> <div class="form-inline"> <select id="nama" class="form-control namabarangsearch col-sm-10" name="name" required onchange="getNamaTransaksi()"> <option value="">-- Nama Barang --</option> <?php foreach ($groups as $group) { echo '<option value="' . $group->stok. '" value="' . $group->name . '">' . $group->name . '. Stok : ' . $group->stok . '</option>'; } ?> </select> </div> <small class="form-text text-muted" id="sisa"></small> </div> Then the script : <script> function getNamaTransaksi() { ...

phpmyadmin 504 timeout when logging in

I am setting up my server with nginx, faced with this annoying issue. phpmyadmin is giving out 504 time out when logging in, even if I input wrong user credentials, it is showing 504 time out error. my error log: 2021/10/29 09:46:48 [error] 154019#154019: *6670 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 122.178.182.104, server: localhost, request: "POST /phpmyadmin/index.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock", host: "54.152.202.60" Also, increasing the timeout value does not solve this error. location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } please help, thanks! source https://stackoverflow.com/questions/69772883/phpmyadmin-504-timeout-when-lo...

JavaScript for Loop - Error Code "item not defined"

I am a bit stuck here because I can't figure out why this does not work. When i try to run the code then it says "ReferenceError: item is not defined" - but I thought that by writing "let item" I am defining it. Any idea what the problem is here ? i know the code looks a bit more complicated than necessary but i need to do it like that. class Graph { constructor() { this.nodes = new Set(); this.edges = new Set(); } add(m,n){ let e = new Edge (m,n) var allEdges = new Set(); for (let item of this.edges){ allEdges.add(item.startpoint.nodeName,item.endpoint.nodeName) }; if (allEdges.has(e.startpoint.nodeName,e.endpoint.nodeName)){ console.log("first OCL Constraint") } else if(allEdges.has(e.endpoint.nodeName,e.startpoint.nodeName){ console.log("second OCL Constraint")} else { this.edges.add(item.startpoint.nodeName,item.endpoint.nodeName)}; } }; class Edge { constructor(star...

Using a Google Form to Populate a Google Doc: Punctuation appears when fields are empty in form

I have a Google form I'm using to gather signatures by inputting names, titles, and affiliations to a Google doc and Google sheet. However, aside from the name, which is a required field, the title and affiliation fields are not required. Most of the time, the person filling out the form will have a title and affiliation, but I would like the result to appear without one comma if one of the fields is empty, or without both commas if both fields are empty. For example, if someone fills out the form as such-- Name: Bob; Title: <blank>; Affiliation: <blank>; then the result will be "Bob, ," in the Google Doc. Ideally it would just say "Bob" . Or, example 2: Name: Bob; Title: <blank>; Affiliation: University; then an ideal result would be "Bob, University" I know next to nothing about Google Apps Script and have slightly edited a template script to fit my needs. Any help is greatly appreciated! function appendSignatureRow(e){ ...

Google Picker API UI not displaying in Chrome, not functioning in Firefox

we have been using the Google Picker API for quite some time, and it just recently started appearing to Chrome users as a blank IFRAME, with the following errors shown in the console: [Report Only] Refused to frame 'https://docs.google.com/' because an ancestor violates the following Content Security Policy directive: frame-ancestors https://docs.google.com". 2399533774-picker_modularized_opc.js:1112 Uncaught Error: Incorrect origin value. Please set it to - (window.location.protocol + '//' + window.location.host) of the top-most page at new JJ (2399533774-picker_modularized_opc.js:1112) at 2399533774-picker_modularized_opc.js:1115 at HTMLDocument.<anonymous> (picker:61)``` rpc.js?c=1&container=onepick:127 Invalid rpc message origin. vs https://...our domain There haven't been any changes to our Google API console settings. In Firefox, the picker IFRAME does display, and even allows for the selection of files, but choosing a file and clic...

why [ newTodo.innerText= todoInput.value ] is not working? help me out wity my Todo List

this is my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Todo List</title> <link rel="stylesheet" href="todo.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script> </head> <body> <header> <h1>The TodoList for learning JavaScript</h1> </header> <FORM> <input type="text" class="todo-input" id="text" placeholder="Write it all here..." /> <button class="...

How to correctly use enter/update/exit pattern for flexbox I've created w/ d3.js?

I've created a flexbox w/ d3, and want to be able to search and sort it. I got search and sort working separately-- see here: https://jsfiddle.net/yx4o0gj8/1/ -- but not together. I got help on the sorting via the last question I posted on Stack Overflow , and it was noted that I wasn't using the enter/edit/update pattern for d3. That's why search and sort don't work together. I've tried moving to the enter/update/exit pattern, but I'm missing something. Now the data doesn't show up at all. I've looked at examples, but they are mostly showing charts where there is a .transition().duration() attribute added. I'm not sure what the equivalent 'update' portion would be here. data = [ { "name": "Dave", "dept": "Marketing", "region": "South", "items": 28 }, { ...

AngularJS 1.5 Session Per Tab/Window

I know there are lots of opinions on this, but I've had an app running for 20 years as a CGI app and have been able to allow different users to be active connecting to different schema on separate tabs/windows. Now I find that I'm in a bind... On a single LAMP instance, I may have 100 clients (schema), and 1000 users. They are used to being able to work either 2+ users within a client or 2+ users accessing different clients from different browser tabs. It isn't something I can just take away from users after 20+ years. So far, I'm using basic PHP auth and can see the files changing on the server the second I login via a new tab to the new user (same php file on the server as the previous login). The previous connection info is overwritten with the new info... Is there anything out there (like an angular module or a php module) that could make this possible without a ton of re-writing? TIA source https://stackoverflow.com/questions/69772792/angularjs-1-5-session-p...

UnauthorizedException when connecting to exchange accounts using oauth2 - garethp - php-ews

I use garethp php-ews to connect EWS using oauth2. I am receiving the access token but when passing it to the mail function (getMailItems,getMailbox,getFolder....etc) following fatal error with "UnauthorizedException" is showing. Tried many ways but still the same. Fatal error: Uncaught garethp\ews\API\Exception\UnauthorizedException in C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php:453 Stack trace: #0 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php(368): garethp\ews\API\ExchangeWebServices->handleNonSuccessfulResponses(NULL, 401) #1 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php(301): garethp\ews\API\ExchangeWebServices->processResponse(NULL) #2 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API.php(362): garethp\ews\API\ExchangeWebServices->__call('GetFolder', Array) #3 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API.php(378): garethp\ews\API->...