how to handle validate form to next page use vue router

a form after validate must go to next author page with vue-Router using this code but not validate

  <form @submit.prevent="handlesubmit">

            <div class="row">
              

                <div class="col-md-4 mb-3">
                    <label>Name</label>
                    <input type="search" class="form-control" placeholder="" v-model.lazy.trim="form.nameTitle">
                    <div class=" text-danger">
                        {{ form.titleNameErrorText }}
                    </div>
                </div>
               

            <div class="row mt-4">
                <div class="col-6 ">
                    <button class="btn btn-primary btn-style" type="submit" >Submit
                        </button>
                </div>

            </div>
        </form>

js code and vue router handle next page after validation


> import { reactive } from "vue";
import { useRoute, useRouter } from 'vue-router'

export default {
    setup() {
        const router = useRouter();
        const form = reactive({
            nameTitle: "",
            familyTitle: "",
            addressTitle: "",
            phoneNumber: "",
            titleNameErrorText: "",
            titleFamilyErrorText: "",
            titleAddressErrorText: "",
            titlePhoneErrorText: "",
            name: "FormAddress",

        });



        function validate() {


            if (form.nameTitle.length < 3) {
                form.titleNameErrorText = "نام حداقل باید دارای 3 حرف باشد   "
            }
            else {
                form.titleNameErrorText = ""
            }
            if (form.familyTitle.length < 3) {
                form.titleFamilyErrorText = "نام خانوادگی حداقل باید دارای 3 حرف باشد   "
            }

            else {
                form.titleFamilyErrorText = ""
            }
            if (form.addressTitle.length < 3) {
                form.titleAddressErrorText = "آدرس حداقل باید دارای 3 حرف باشد   "
            }

            else {
                form.titleAddressErrorText = ""
            }

            const phonepattern = /^09d{9}$/;
            if (!phonepattern.test(form.phoneNumber)) {
                form.titlePhoneErrorText = "شماره وارد شده صحیح نمی باشد"
            }
            else {
                form.titlePhoneErrorText = "";
            }


        }


        function handlesubmit() {

            if (validate()) {
                console.log("amir")
                router.push({ name: 'map' })
            }

        }

        return { form, validate, handlesubmit }



    },



}



submit go to map page and no validate this current page im handle validate page and success form element next page else stay this page
///////////////////

React problem with setting data into constant [duplicate]

I have piece of code to put image URL from server part into JSON payload. I’ll show you what it looks like in code and what output gives the browser:

const url = `${apiUrl}/api/image/${barcode}`;
console.log("variable url:", url);
setPhotoUrl(`${apiUrl}/api/image/${barcode}`);
console.log("photoUrl when i put full url string:", photoUrl);
setPhotoUrl(url);
console.log("photoUrl when i put url variable inside:", photoUrl);

Output from browser:
browser output

Why this url don’t want to set in photoUrl constant even if it’s working in url variable?

How to store the programmitc zoom for mouse zoom not to start at 0,0 scale 1 again

I have a d3 v4 script which draws a windrose / pie chart type graphic which is tweened into to the canvas from x:0, y:0 to the middle of the canvas.

When a User zooms that windorose catapults back to 0,0 and scale 1. How can I make sure the zooming isn’t catapulting the windrose back to 0 again.

Starts like this.

// Zoom Behavior V4.
var zoom = d3.zoom().scaleExtent([0.5, 8]).on( “zoom”, zoomed );

This is the zooming base:

 var svg = d3.select("#group_canvas").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate( 0, 0 )scale(1,1)");

This is the zooming target:

// Container für Zooming
var cont = svg.append("g");

Then the cont is zoomed programmatically and the human interaction zoom is activated on svg:

 function applyZoom() {
        // Zoome die Fläche
    
          // .transition().duration(2000)
          // .call(zoom.translateTo, width/2, height/2);
          cont
          .transition().duration(2000)
          .tween("attr:transform", function() {
            //interpolate from start to end state
            var i = d3.interpolateString("scale(1)translate(0,0)", "scale("+scaleZoom+")translate("+(width/2)/scaleZoom+","+(height/2)/scaleZoom+")");
            return function(t) { 
              cont.attr("transform", i(t)); 
            };
          });
          
          // Call Zoom Behavior.
          svg.call(zoom);
          
        }

And finally this is the zoomed() function declared in the first line for the zoom behavior:

// Funktion die alles Zoomt. 
function zoomed() {
    // Diese Funktkion transformiert und skaliert alles gleichzeitig, welches den Effekt eines Zooms nachahmt.
var transform = d3.event.transform;

cont.attr('transform', transform.toString());

}

Get element by class list doesn’t seem to work in a for loop [duplicate]

I tried to create a for loop which loops through all buttons in an array I made – and it’s supposed to work according to: (https://www.w3schools.com/js/js_loop_for.asp)

But it does not.

I have no idea what should I do, since I haven’t found anything about that on the web.
Thank you for your time.

Here is the code

const buttons = document.getElementsByClassName('zoom-btn');

for (i = 0; i < buttons.length; i++) {
    buttons[i].onmouseover = () => {
        buttons[i].style.backgroundColor = "red";
    }
};
#article-navbar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;

    position: fixed;

    width: clamp(286px, 504px, 506px);
    height: clamp(90px, 182px, 184px);

    top: 36vw;
    left: 4vw;

    background-color: cyan;
}

.zoom-btn {
    background-color: slategray;
    color: white;

    padding: 18px 10px;
    margin-top: 12px;
    margin-left: 10px;

    font-size: 16px;

    position: relative;
}

.reset-btn {
    background-color: blue;
}

.zoom-hover {
    background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="a.css">
</head>
<body>
    <div id="article-navbar">

        <a id="button-RE" ; class="zoom-btn reset-btn">Reset</a>
        <a id="button-A1" ; class="zoom-btn">Block 1</a>
        <a id="button-A2" ; class="zoom-btn btn-deactivated">Block 2</a>
        <a id="button-A3" ; class="zoom-btn btn-deactivated">Block 3</a>
    
        <a id="button-B1" ; class="zoom-btn btn-deactivated">Block 4</a>
        <a id="button-B2" ; class="zoom-btn btn-deactivated">Block 5</a>
    
      </div>

    <script src="a.js"></script>
</body>
</html>

Prevent browser from inserting characters resulting from dead-keys in safari (composition sessions)

I am building a WYSIWYG text editor that is built on Meta’s Lexical Editor.

For the use case it is necessary to prevent the browser default behaviour when typing one of the dead-key characters, e.g. `, ´, ^, … and to execute some own function instead.

Desired behavior:

The user presses the dead key, the browser does not insert the respective character and does not start a composition session.

So when consecutively typing ` and then w, the browser does not insert „`w“ into the content editable, but only w.

When consecutively typing „´“ and then „e“, the browser does not insert „é“ into the content editable, but only e.


Approaches I tried to far:

Approach 1:

Listening on keydown-events of the content-editable of the lexical editor and calling preventDefault(), stopPropergation() and stopImmediatePropagation() on the event
Listening on the composition start, composition update and composition end events and calling preventDefault(), stopPropergation() and stopImmediatePropagation() on the event

This approach works fine in Chrome under MacOS, but does not work in Safari.

In Safari, the character is still appearing in the content-editable and the input event for the character resulting from pressing the Dead Key is still dispatched. I found no way to prevent this to happen.

Approach 2:

All Steps from Approach 2
Immediately remove the character in the callback function of the event listener for the respective input even

When doing this, the character disappears at first, but the browser still holds the composition session. After typing the next character, the browser inserts the dead-key character together with the next character.


Thanks in advance – would be happy for any ideas, experience or insights. We’ve been hitting a wall here for a while.

Environment:
macOs Sonoma 14.3.1
Safari Version 17.3.1

JS Single Page Application – history.pushState and history.replaceState issues

I’m implementing a Single Page Application in vanilla JavaScript, and I’m stuck on history.pushState and history.replaceState issues.

This is my code:

HTML

<ul id="nav"></ul>

<div id="root"></div>

JS

const routes = {
    "home": "Home",
    "blog": "Blog",
    "contact": "Contact"
};

for (var r in routes) nav.innerHTML += `<li data-id="${r}">${routes[r]}</li>`;


const load = page => {
    page = page.replace("#", "");
    nav.querySelector(".active")?.removeAttribute("class");
    if (routes[page]) {
        nav.querySelector(`[data-id="${page}"]`).className = "active";
        fetch("pages/" + page + ".html")
            .then(res => res.text())
            .then(res => root.innerHTML = res);
        history.pushState(null, null, location.pathname + "#" + page); // ISSUE #1
        document.querySelector("title").innerText = routes[page];
    } else {
        history.replaceState(null, null, location.pathname + "#" + page); // ISSUE #2
        location.href = "errors/404.html";
    }
};


nav.onclick = e => {
    if (e.target.tagName !== "LI") return;
    load(e.target.dataset.id);
}


window.onpopstate = () => {
    load(location.hash);
}


load(location.hash || "home");

ISSUE #1 – history.pushState(null, null, location.pathname + “#” + page);

When I click on the browser’s back button, it goes go back to one page only.

For instance: in the Home page, I click on Contact then on Blog, then I click on browser’s back button: it takes me back to Contact page, but if I click again (and again) on that button, it doesn’t take me back to Home page, stopping on Contact page.

ISSUE #2 – history.replaceState(null, null, location.pathname + “#” + page);

If the user writes a wrong URL (e.g. https://www.—.com/spa/#blogg), I want to delete that url from the browser’s history, before redirecting to 404 error page. But my code doesn’t do it: that URL is still in the browser’s history.

How can I fix those issues?

Any suggestions would be appreciated.

Do `aria-` tags include children elements?

I show and hide some inputs in the same form depending on the status of a radio group. For accessibility, I add and remove aria-hidden=true to the parents of these inputs by writing a JavaScript code.

In short my code is like this

<fieldset>
  <input type="radio" name="hello" value="1" />
  <input type="radio" name="hello" value="2" checked />
  <input type="radio" name="hello" value="3" />
</fieldset>

<div class="hidden" aria-hidden="true" data-radio-hello="1">
  <textarea></textarea>
</div>

<div class="active" data-radio-hello="2">
  <input type="text" />
</div>

<div class="hidden" aria-hidden="true" data-radio-hello="3">
  <input type="checkbox" />
</div>

In the example above, the JavaScript code adds a class to the matching parents, adding aria-hidden=true to hide them as the states of the parent radio inputs change.

In this case, according to the example above,

<textarea></textarea>
<input type="checkbox" />

Would I be able to correctly mark these elements with aria- and hide those two elements from screen readers?

nuxt 3 + cloudfare D1 problems with env.d.ts file

I’m using nuxt 3 with cloudfare D1, but I have encountered some problems.

It seems that it cannot read env.d.ts file I have created.
I’m getting this error:

500 Cannot read properties of undefined (reading ‘env’)

I used this repo:
https://github.com/tlebeitsuk/nuxt-cloudflare-lucia

My configured env.d.ts file

import { CfProperties, Request, ExecutionContext, KVNamespace, D1Database } from '@cloudflare/workers-types';

declare module 'h3' {
    interface H3EventContext {
        cf: CfProperties,
        cloudflare: {
          request: Request,
          env: {
            MY_KV: KVNamespace,
            DB: D1Database,
          }
          context: ExecutionContext,
        };
    }
}

And here is middleware->auth.ts

import { verifyRequestOrigin } from "lucia"
import { initializeLucia } from "../utils/auth"
import type { User, Session } from "lucia"

let lucia: ReturnType<typeof initializeLucia>

export default defineEventHandler(async (event) => {
  // CSRF protection
  if (!isMethod(event, "GET")) {
    const originHeader = getHeader(event, "Origin") ?? null
    const hostHeader = getHeader(event, "Host") ?? null
    if (
      !originHeader ||
      !hostHeader ||
      !verifyRequestOrigin(originHeader, [hostHeader])
    ) {
      return sendNoContent(event, 403)
    }
  }



  const { DB } = event.context.cloudflare.env

  if (!lucia) {
    lucia = initializeLucia(DB)
  }

  event.context.lucia = lucia


  const sessionId = getCookie(event, lucia.sessionCookieName) ?? null
  if (!sessionId) {
    event.context.session = null
    event.context.user = null
    return
  }

  const { session, user } = await lucia.validateSession(sessionId)
  if (session && session.fresh) {
    appendResponseHeader(
      event,
      "Set-Cookie",
      lucia.createSessionCookie(session.id).serialize()
    )
  }
  if (!session) {
    appendResponseHeader(
      event,
      "Set-Cookie",
      lucia.createBlankSessionCookie().serialize()
    )
  }

  event.context.session = session
  event.context.user = user
})

declare module "h3" {
  interface H3EventContext {
    user: User | null
    session: Session | null
    lucia: ReturnType<typeof initializeLucia>
  }
}

Specifically this part const { DB } = event.context.cloudflare.env is responsible

Server side api can’t pass cookies in NextJS app router

In my nextjs app, I am trying to fetch data by using async await mechanism like this

export const getHomeData = async (tokenCalled4PublicApis: string) => {
    try {
        // const all = getCookie('XSRF-TOKEN', { cookies });
        // console.log('all cookies', all);
        const data = await fetch(
            `${process.env.NEXT_PUBLIC_BASE_URL}/${API_ENDPOINTS.HOME}`,
            {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${tokenCalled4PublicApis}`,
                    Accept: 'application/json',
                    // abc: all,
                    'Cache-Control':
                        'public, max-age=60, stale-while-revalidate=60'
                },
                credentials: 'include'
            }
        );
        const result = await data.json();
        return result;
    } catch (error) {
        console.error('Error fetching platform token:', error);
        throw error;
    }
};

Unfortunately not getting data, as in this way i won’t be able to pass cookies set by API. How to pass browser cookies in server-side fetch functions?

Redis Not Adding Session into Cookie, but session being added when viewing via redis-cli

I have setup a spring boot backend with a react frontend. I want to use sessions, and have chosen Redis to do this.
The issue is that my chrome dev tools shows that there are no cookies being added, but in my redis-cli it shows that there are cookies. The issue no arises cause I want to send information using axios with withCredentials: true, but nothing will show up since there are no cookies in Chrome.

I won’t include the import statements as they may clutter the page.

Main

@SpringBootApplication
@EnableRedisHttpSession
public class LetstalkstartApplication {

    public static void main(String[] args) {
        SpringApplication.run(LetstalkstartApplication.class, args);
    }

}

Security Filter Chain

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final UserDetailsServiceImpl userDetailsServiceImpl;

    private final CustomLogoutHandler logoutHandler;

    private final UserDetailsService userDetailsService;
    public SecurityConfig(UserDetailsServiceImpl userDetailsServiceImpl,

                          CustomLogoutHandler logoutHandler, UserDetailsService userDetailsService) {
        this.userDetailsServiceImpl = userDetailsServiceImpl;
        this.logoutHandler = logoutHandler;
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return
                http
                        .csrf(AbstractHttpConfigurer::disable)
                        .authorizeHttpRequests(
                                req -> req.requestMatchers("/login/**", "/register/**")
                                        .permitAll()
                                        .requestMatchers("/admin_only").hasAnyAuthority("ADMIN")
                                        .requestMatchers("/getinfo").authenticated()
                                        .anyRequest().authenticated()
                        ).userDetailsService(userDetailsServiceImpl)
                        .logout(l -> l.logoutUrl("/logout")
                                .addLogoutHandler(logoutHandler)
                                .logoutSuccessHandler(
                                        (request, response, authentication) -> SecurityContextHolder.clearContext()
                                ))
                        .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

}

Endpoints:


    @PostMapping("/register")
    public ResponseEntity<AuthenticationResponse> register(
            @RequestBody User request
    ) {
        return ResponseEntity.ok(authenticationService.register(request));
    }

    @PostMapping("/login")
    public ResponseEntity<AuthenticationResponse> login(
            HttpSession session,
            @RequestBody User request,
            HttpServletResponse httpResp
    ) {


        AuthenticationResponse response = authenticationService.authenticate(request);
        if (response != null && response.isSuccess()) { // Check if authentication was successful
            // Store user information in the session
            Cookie sessionCookie = new Cookie("SESSION_ID", session.getId());
            sessionCookie.setHttpOnly(true); // Make it HTTP-only
            sessionCookie.setSecure(false);   // Make it secure
            sessionCookie.setPath("/");      // Set the path for the cookie

            // Add the cookie to the response
            httpResp.addCookie(sessionCookie);
            UserDetails user = userDetailsService.loadUserByUsername(request.getUsername());
//            session.setUsername(user.getUsername());
        }

        return ResponseEntity.ok(response);
    }

    @GetMapping("/getinfo")
    public ResponseEntity<AuthenticationResponse> getUserInfo(HttpServletRequest request) {
        AuthenticationResponse authenticationResponse = new AuthenticationResponse();
        if (request != null) {
            authenticationResponse.setSuccess(true);
            authenticationResponse.setMessage("Success!");

            Cookie[] cookies = request.getCookies();

            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    System.out.println("Cookie Name: " + cookie.getName() + ", Cookie Value: " + cookie.getValue());
                }
            }

            HttpSession session = request.getSession(false);
            if (session != null) {
                System.out.println("Session ID: " + session.getId());
                System.out.println("Session Attributes: ");
                session.getAttributeNames().asIterator().forEachRemaining(name ->
                        System.out.println(name + ": " + session.getAttribute(name))
                );
            } else {
                System.out.println("No active session found");
            }

        } else {
            authenticationResponse.setSuccess(false);
            authenticationResponse.setMessage("Failed to retrieve user information");
        }

        return ResponseEntity.ok(authenticationResponse);
    }

I’ve been using the /getinfo endpoint to test if the cookies are actually working, it’s not meant to serve any greater function within the app.

Here’s my auth service:

public class AuthenticationService {

    private final UserRepository repository;
    private final PasswordEncoder passwordEncoder;

    private final AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    public AuthenticationService(UserRepository repository, PasswordEncoder passwordEncoder, JwtService jwtService, AuthenticationManager authenticationManager, TokenRepository tokenRepository, UserDetailsService userDetailsService) {
        this.repository = repository;
        this.passwordEncoder = passwordEncoder;

        this.authenticationManager = authenticationManager;

        this.userDetailsService = userDetailsService;
    }

    public AuthenticationResponse register(User request) {
        User user = new User();
        user.setFirstName(request.getFirstName());
        user.setLastName(request.getLastName());
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setRole(request.getRole());

        user = repository.save(user);

        AuthenticationResponse response = new AuthenticationResponse();

        response.setMessage("Registration Successful");
        response.setSuccess(true);

        return response;

    }

    public AuthenticationResponse authenticate(User request) {
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        request.getUsername(), request.getPassword()
                )
        );
        System.out.println(" in authentication ");

        UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());
        if (userDetails != null && passwordEncoder.matches(request.getPassword(), userDetails.getPassword())) {
            AuthenticationResponse authenticationResponse = new AuthenticationResponse();
            authenticationResponse.setSuccess(true);
            authenticationResponse.setMessage("Authentication successful");
            return authenticationResponse;
        }
        AuthenticationResponse authenticationResponse = new AuthenticationResponse();
        authenticationResponse.setSuccess(false);
        authenticationResponse.setMessage("Authentication failed");
        return authenticationResponse;
    }


}

I tried to log in as an example and redis showed after running redis-cli

127.0.0.1:6379> keys *
1) "spring:session:sessions:84c2f69f-f969-4427-b74b-e6e783c6053a"

However, in chrome the cookies page is empty completely. I followed a youtube tutorial and when they log in with the premade page given via spring boot it adds it to the cookies. I’m confused as to what the difference could be.

Login page for frontend in react:

class AuthService {
    login(username, password) {
        return axios.post(API_URL + "/login", 
        {
            username: username, 
            password: password
        },  
        {
            headers: {
                'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        },
       
    
    )
        .then(response => {
            console.log("response: ", response)
            if (response.status == 200) {
                console.log("Logged in")
            } else {
                console.log("Couldn't log in")
            }
            return response.data;
        });
    }

// get info call
  const getUserInfo = () => {
    axios.get(API_URL + "/getinfo", {
      withCredentials: true,
    });
  };

Thank you all

I tried following a youtube tutorial which led to the right result, but when I did the same stuff in my own page it didn’t work. I initially thought this may be an issue with my log in page, but if that’s the case why can I still see a session added via the redis-cli command. Just confused why it’s not showing up in chrome at all.

in discord js msg.attachments.first().name,all blank chars are replaced by an underbar, and if the underbar is present at the beginning, it disappears

Sorry my code is dirty
and also I’m not a native english speaker

~

As the title goes, all spaces in msg.attachments.first().name are replaced by underbars and disappear if there is an underbar in the first
when a user sends a file with “$fur2mp3” in the chat window, the file must be converted through an external script,
but before that, there is a problem in the process of finding the name of the file
if the name of the file user sends does not contain underbar(‘_’) or space (‘ ‘), everything works fine, but if it does not, it fails to find the file (there are no errors or crashes btw)

This is a list of the file names and their values that I tried

_kirb space.fur –> kirb_space.fur

_kirb sp_ace.fur –> kirb_sp_ace.fur

kirb space.fur –> kirb_space.fur


     commands.add('fur2mp3',() => {
    fs.exists('buffer_furrendering.txt',  function(exists){
        if(exists){
            msg.channel.send('Another file is being processed! Please wait!');      
        } else {

            if(msg.attachments.first()){//checks if an attachment is sent
            //arg = msg.attachments.first()
            msg.channel.send('Uploading...');

            download(msg.attachments.first().url, process.cwd());//Function

            msg.channel.send('Uploaded!');
    
    msg.channel.send(msg.attachments.first().name);

            fs.exists(msg.attachments.first().name,  function(exists){
            if(exists){
     
                msg.channel.send('Current Furnace Tracker Version : 0.6.5');
                msg.channel.send('Converting...');
                msg.channel.startTyping();
    exec('fur2wav.bat' + ' ' + msg.attachments.first().name, (error, stdout, stderr) =>{
                msg.channel.stopTyping();
    

                fs.readFile('buffer_fur2wavmsg.txt', 'utf8', (err, gwav) => {
                if (err) {

                    console.error(err);
                    return;
                }

            console.log(gwav);

            msg.channel.send(gwav);
            msg.channel.send({ files: ["furoutput.mp3"] });
     });
       });
        console.log("exixts! : ",exists);
        } else {
            msg.channel.stopTyping();
             msg.channel.send('The file does not exist!');
        }});
           } else { msg.channel.send('Send your file with this command!'); }
           
           
        };
    });
    });

I tried this, ‘msg.attachments.first().name.join(‘ ‘)’ but uhh I think i was wrong

No error, but the bot returns these

Uploading…
Uploaded!
kirb_sp_ace.fur
The file does not exist!

WEBGL_debug_render_info extension appears in getSupportedExtensions but doesn’t work

I have opened the following HTML on multiple browsers (Chrome, Opera, etc.) but in the console it always logs ‘WEBGL_debug_render_info extension doesn’t work’ despite gl.getSupportedExtensions() showing a list where WEBGL_debug_render_info is present. Am I doing something wrong?

<!DOCTYPE html>
<html>
<body>
<script>
    
    var canvas = document.createElement('canvas');
    var gl = canvas.getContext('webgl');
    
    if (!gl) {
        console.log('WebGL not supported');
    } else {
        
        var extensions = gl.getSupportedExtensions();
        console.log('Supported extensions:', extensions);
        
        
        
        var debugInfo = gl.getExtension("WEBGL_debug_render_info");
        if (debugInfo) {
            var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
            var renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
            console.log('Vendor: ' + vendor);
            console.log('Renderer: ' + renderer);
        } else {
            console.log('WEBGL_debug_render_info extension doesnt work');
        }
    }

  
</script>
</body>
</html>

Issue with get ranges using getRangeList

I am trying to get ranges by using getRangeList method but I am getting error Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Sheet.getRangeList

How can we do it?

function consolidateData() {
  // defined all variables
  var sheetNames = [];
  var dataSheet = [];
  var conso = [];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var applyTo = ss.getSheetByName('Sheet10');
  // get all sheets
  var allsheets = ss.getSheets();

  for (var s in allsheets) {
    var sheet = allsheets[s];
    sheetNames[s] = sheet.getName();
    dataSheet[s] = ss.getSheetByName(sheetNames[s]);
    // adding all sheet's data to a single variable
    conso = conso.concat(dataSheet[s].getRange("A2:B" + dataSheet[s].getLastRow()).getValues());
    // conso = conso.concat(dataSheet[s].getRangeList(["A2:B","D2:E"] + dataSheet[s].getLastRow()).getValues());

  }
  applyTo.getRange("A2:B" + (conso.length + 1)).setValues(conso);
  // applyTo.getRangeList(["A2:B","D2:E"] + (conso.length + 1)).setValues(conso);
}

Image is not showing in datatable asp.net c#

I am trying to fetch the image from database but it showing no image (alt message) in the place of image.

Here is my image columnname, datatype and DataStoreValue

ColumnName : DesignImage
DataType : Image
DataStoreValue : Binary data [after applying query i.e. select * from abc I get output of image : 0xFFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C1….]

Now, when I applying ajax and fetch image and show in datatable it does’nt show image. Here is my aspx code,

function format(d) {
    // `d` is the original data object for the row
    let greeting = '<dl>';  
    if (d.DesignImage !== null) {
        const imgTag = '<img src="data:image/png;base64," ' + d.DesignImage +' alt = "No Image" style = "width: 50px; height: 50px;" > ';
        greeting += '<dt><u>Image</u> : ' + imgTag + ' </dt>n ';
    }
    greeting += '</dl>';
    return greeting;            
}

$("#btnSubmit").click(function (e) {                
    $.ajax({
        type: "POST",
        url: "FillGridMethod.asmx/StockList",    
        dataType: "json",
        success: function (data) {                    
            var datatableVariable = $('#gv_Datatable').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'pdf', 'print', 'excel'
                ],                        
                "bDestroy": true,
                "paging": true,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                data: data,
                columns: [
                    {
                        className: 'dt-control',
                        orderable: false,
                        data: null,
                        defaultContent: ''
                    },
                    { 'data': 'Product' },                
            });                            
            // Add event listener for opening and closing details
            datatableVariable.on('click', 'td.dt-control', function (e) {
                let tr = e.target.closest('tr');
                let row = datatableVariable.row(tr);

                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                }
                else {
                    // Open this row
                    row.child(format(row.data())).show();
                }
            });                    
        }
    });
});

Here is my asmx code

[WebMethod(enableSession: true)]
public void StockList()
{
    var stock = new List<StockModel>();
    string constr = cn.ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        qryFillGrid = "select TagItem, CAST(STCK.DesignImage AS VARBINARY(MAX)) as DesignImage from tbl_StockRunning STCK " + System.Environment.NewLine;       
        var cmd = new SqlCommand(qryFillGrid, con);
        con.Open();
        var dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            var stockModel = new StockModel
            {
                Product = dr[0].ToString(),
                DesignImage = dr[1].ToString()
            };
            stock.Add(stockModel);
        }
    }
    var js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(stock));
}

Here is my model .cs file

public class StockModel
{
    public string Product { get; set; }
    public string DesignImage { get; set; }
}

Any guess…what’s issue?

how to continue array numbers in javascript whose data is displayed with a php loop

I have a phone number table in the database like this

id_wa id_proyek bagian no_wa
65 112 renev 087665775667
66 112 renev 087665445334
67 112 renev 087665445444

I show it like this

<label for="inlineinput" class="col-md-3 col-form-label">No WA</label>
<?php
    $no=0;
    $cek=mysqli_query($koneksi,"select no_wa from wa_renev where id_proyek='112'");
    while($data = mysqli_fetch_array($cek)){
    $no++
?>
<div class='col-md-9 p-0'>
<input name='no_wa[<?php echo"$no";?>]' value='' type='text' class='form-control input-full' id='inlineinput' placeholder='Masukkan No WA (ex:087712333488)'/>
</div>
<?php
}
?>

And below the code to add another cellphone number with dynamicly

<script language="JavaScript" type="text/JavaScript">
counter = 0;
function action()
{
counterNext = counter + 1;
document.getElementById("input"+counter).innerHTML = "<div class='col-md-9 p-0'><input name='no_wa["+counterNext+"]' value='' type='text' class='form-control input-full' id='inlineinput' placeholder='Masukkan No WA (ex:087712333488)'/></div><div id="input"+counterNext+""></div>";
counter++;
}
</script>

<div id="input0">
</div>
<a href="javascript:action();"><span class="badge badge-primary">Tambah WA</span></a><br/>

How to continue the array from my first code when the cellphone number is added again ?

results display