How to show the list of items after clicking the button

Try to search “social” in the input field and hit enter, It is working fine. But I want the same functionality if you click the button.

I already tried creating a document.getElementById("cta-search-button").click(...); and calling it inside 'keyup' but no to avail.

$(function() {
  
  $('.stores-search-not-found').hide();
  $(".stores-input-search").on('keyup', function (e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
      e.preventDefault();
      var filter = $(this).val();
      var count = 0;
      if (count == 0) {
        $('.stores-search-not-found').hide()
      }
      // Loop through the comment list
      $('.stores-search-lists .card').each(function() {
        // If the list item does not contain the text phrase fade it out
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
          $(this).hide(); // MY CHANGE
          if (count == 0) {
            $('.stores-search-not-found').show()
          } else {
            $('.stores-search-not-found').hide()
          }
          // Show the list item if the phrase matches and increase the count by 1
        } else {
          $(this).show(); // MY CHANGE
          count++;
        }
      });  
    }
    
  });
  
});
.stores-search-lists {
  font-size: 1rem;
}
.stores-search-lists .card {
  background-color:gray;
  padding: 1rem;
  margin: 1rem;
  color: white;
}
.stores-search-not-found {
  padding: 3rem 1rem;
}



/* =========================
   GENERAL STYLES 
   NOT RELATED TO THE DEMO
============================ */

*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {  
  --clr-primary: #ee6352;
  --clr-secondary: #d16e8d;
  --clr-accent: #F7F7FF;
  --clr-gradient: linear-gradient(-90deg, var(--clr-primary), var(--clr-secondary));
  --ff-title: bungee, sans-serif;
  --ff-body: canada-type-gibson,sans-serif;
  --fw-body: 300;
  --fw-bold: 800;
  --fw-title: 400;
  --fw-number: 800;
}

body {
  min-height: 100vh;
  font-family: var(--ff-body);
  font-weight: var(--fw-body);
  font-size: 1.25rem;
  padding: 0;
  margin: 0;
}

a {
  color: inherit;
}

a:hover,
a:focus {
  color: var(--clr-accent);
}

:focus {
  outline: 5px solid var(--clr-accent);
  outline-offset: 3px;
}
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<div style="display: block;">
<!-- search input -->
  <input class="stores-input-search" type="text" id="stores-input-search" placeholder="Search for anything">
<button class="cta-search-button" id="cta-search-button">Button</button>

  <!-- list -->
  <div class="stores-search-lists">
      <div class="card">
        <h4>Social</h4>
        <p>Social Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat, ut. </p>
      </div>
      <div class="card">
        <h4>Security</h4>
        <p>Security Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto obcaecati eum reprehenderit qui deleniti pariatur suscipit labore. Veniam, magnam laboriosam. </p>
      </div>
      <div class="card">
        <h4>System</h4>
        <p> System Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea, repellat praesentium magnam quis repudiandae aliquam ipsum necessitatibus quas tempora in consectetur, quibusdam porro laudantium quisquam voluptas minima officia vitae natus. </p>
      </div>
  </div>


  <!-- feedback -->
  <div class="stores-search-not-found" aria-live="polite">No matching results. Try changing your search terms.</div>
  
  </div>

IntersectionObserver rootMargin is ignored on mobile device

I’m using the IntersectionObserver API to load additional content when the page scrolls close to 1000px from the bottom. It works fine on desktop, but on mobile screens, the content only loads when it reaches the end of the footer.

Here’s my current code:

const loader_element = document.querySelector(loader_element_selector);

const observer = new IntersectionObserver(
  async (entries) => { 
    if (entries[0].isIntersecting && !is_loading && has_more_content) { 
      await load_more_content(); 
    } 
  },
  { root: null, rootMargin: "0px 0px 1000px 0px", threshold: 0.1 }
);

observer.observe(loader_element);

On mobile, I want the content to load earlier, before it reaches the footer. How can I adjust my implementation to achieve this? Any suggestions or solutions would be greatly appreciated!

Error: Error: Node is either not visible or not an HTMLElement

I need help locating the freeriderhd.com HTML login element because in my code it says: Error: Error: Node is either not visible or not an HTMLElement

Basically I need help inspecting the page and finding the login button HTML Element. Please copy and paste the element along with an screenshot of in inspect would be greatly helpful thank you so much.

(I am trying to make an track-editor tool for the game)

When I type the command “node script.js”

CODE IS BELOW:

const puppeteer = require('puppeteer');

(async () => {
  let browser;
  let page;

  try {
    // Launch the browser
    browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox'], // Required for environments like Codespaces
    });

    // Open a new page
    page = await browser.newPage();

    // Navigate to the FreeriderHD website
    console.log('Navigating to FreeriderHD...');
    await page.goto('https://www.freeriderhd.com', { waitUntil: 'networkidle2' });

    // Wait for the login button to be visible
    console.log('Waiting for the login button...');
    await page.waitForSelector('#left-nav-login', { visible: true });

    // Wait for any loading overlays to disappear (if applicable)
    await page.waitForSelector('.loading-overlay', { hidden: true }).catch(() => {});

    // Scroll into view and focus on the button
    await page.evaluate(() => {
      const loginButton = document.querySelector('#left-nav-login');
      if (loginButton) {
        loginButton.scrollIntoView();
        loginButton.focus();
      }
    });

    // Wait for the button to be fully loaded and clickable
    await page.waitForFunction(() => {
      const loginButton = document.querySelector('#left-nav-login');
      return loginButton && loginButton.offsetParent !== null && !loginButton.disabled; // Check if the button is visible and not disabled
    });

    // Click the login button with a delay
    console.log('Clicking the login button...');
    await page.click('#left-nav-login', { delay: 100 });

    // Wait for the login form to load
    console.log('Waiting for the login form...');
    await page.waitForSelector('#login_password', { visible: true });

    // Enter the username and password
    console.log('Entering credentials...');
    await page.type('input[name="username"]', 'backstreets'); // Enter username
    await page.type('#login_password', 'Humor1341!'); // Enter password

    // Click the login submit button
    console.log('Submitting the login form...');
    await page.waitForSelector('.auth-btn[data-action="login_with_email"]', { visible: true });
    await page.click('.auth-btn[data-action="login_with_email"]');

    // Wait for navigation after login
    console.log('Waiting for login process...');
    await page.waitForNavigation({ waitUntil: 'networkidle2' });

    console.log('Login successful!');
  } catch (error) {
    console.error('Error:', error);

    // Take a screenshot for debugging
    if (page) {
      await page.screenshot({ path: 'error-debug.png' });
      console.log('Screenshot saved as error-debug.png');
    }

    // Close the browser in case of error
    if (browser) {
      await browser.close();
    }
  } finally {
    // Ensure the browser is closed in case of success or error
    if (browser) {
      await browser.close();
    }
  }
})();

Did not work just errrors.

What should I do if the ScrollView containing HStack Button in SwiftUI can’t detect scrolling? [duplicate]

Strangely enough, if you remove the HStack from the outer layer, you can detect the roll, otherwise you can’t

Or if you take the Button out and you just use Text you can detect it? Is this a bug? How to fix it?

please see the SCREENSHOTS

It is bad When no HStack

It is ok When no HStack


import SwiftUI
struct ScrollOffsetPreferenceKey: PreferenceKey {
    typealias Value = CGFloat
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}
struct test5Scroll: View {
    var body: some View {
        NavigationView {
            
            ScrollView {
                GeometryReader { proxy in
                    if let distanceFromTop = proxy.bounds(of: .named("MyScrollView"))?.minY {
                        Text(distanceFromTop, format: .number)
                            .font(.system(size: 40))
                            .padding(.top, 120)
                            .foregroundStyle(.pink)
                            .navigationTitle("Why Can't Detected?")
                            .preference(key: ScrollOffsetPreferenceKey.self, value: distanceFromTop)
                    } else {
                        Text("can't be detected")
                    }
                }
                ForEach(0 ..< 30) { index in
                    // Strangely enough, if you remove the HStack from the outer layer, you can detect the roll, otherwise you can't
                    // Or if you take the Button out and you just use Text you can detect it? Is this a bug? How to fix it?
                    
                    
                    //A. The code simply fails with HStack
                    HStack{
                        Button(action: {
                            
                        }, label: {
                            Text("item --- (index)")
                        })
                    }
                    .frame(width: 100, height: 40)
                    
                    //B. The code will work if HStack is removed
//                     Button(action: {
//                        
//                     }, label: {
//                        Text("item --- (index)")
//                     })
//                     .frame(width: 100, height: 40)
                }
            }
            .background(.black.opacity(0))
            .coordinateSpace(.named("MyScrollView"))
            .onPreferenceChange(ScrollOffsetPreferenceKey.self) { value in
                // Why can't it be detected when it rolls?
                print("Scroll offset ----- (value)")
            }
        }
        
    }
}

#Preview {
    test5Scroll()
}

Tell me how to do? Please, thank you

It is ok when no HStack, but I need HStack. Is it a bug of SwiftUI?

ESLint not working on new vue application

I was setting up a new vue3 + typscript project with all the required prettier and lint configuration. I’ve tried my configurations but none if it worked. Below you will see my script, response and config.

this is the lint script in my package.json

"lint": "eslint "./src/**/*.{js,ts,vue}"",
"lint:fix": "eslint "./src/**/*.{js,ts,vue}" --fix",

and when I run this I get this error:

eslint "src/**/*.{js,ts,vue}"


Oops! Something went wrong! :(

ESLint: 9.18.0

You are linting "src/**/*.{js,ts,vue}", but all of the files matching the glob pattern "src/**/*.{js,ts,vue}" are ignored.

If you don't want to lint these files, remove the pattern "src/**/*.{js,ts,vue}" from the list of arguments passed to ESLint.

If you do want to lint these files, explicitly list one or more of the files from this glob that you'd like to lint to see more details about why they are ignored.

  * If the file is ignored because of a matching ignore pattern, check global ignores in your config file.
    https://eslint.org/docs/latest/use/configure/ignore

  * If the file is ignored because no matching configuration was supplied, check file patterns in your config file.
    https://eslint.org/docs/latest/use/configure/configuration-files#specifying-files-with-arbitrary-extensions

  * If the file is ignored because it is located outside of the base path, change the location of your config file to be in a parent directory.

Below is my eslint.config.js:

import { defineConfig } from 'eslint-define-config';
import pluginJs from '@eslint/js';
import pluginVue from 'eslint-plugin-vue';
import tseslint from '@typescript-eslint/eslint-plugin';

export default defineConfig({
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 2021,
    sourceType: 'module',
  },
  plugins: ['vue', '@typescript-eslint', 'prettier'],
  rules: {
    'prettier/prettier': 'error',
    'no-console': 'warn',
    'no-unused-vars': 'off',
    '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
    '@typescript-eslint/explicit-module-boundary-types': 'warn',
    'eqeqeq': ['error', 'always'],
    'consistent-return': 'warn',
    'no-undef': 'error',
    'vue/require-default-prop': 'warn',
    'vue/no-v-html': 'warn',
  },
  ignorePatterns: ['node_modules/', 'dist/', 'build/', '**/*.min.js'],
  overrides: [
    {
      files: ['*.vue'],
      rules: {
        'max-len': 'off',
      },
    },
  ],
});

I tried adding

{ ignores: ['*.d.ts', '**/coverage', '**/dist'] },

and I am expecting the lint to work perfectly fine

I dont seem to understand routing [closed]

Hi guys Im having a problem with my api route in next js. Basically trying to get my document from MinIO (File Storage) then use langchain to turn into vectors and then transfer to pineconeDB

api/create-chats/route.ts

import { loadMinioIntoPinecone } from "@/lib/pinecone";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  try {
    // Check if the request is a form-data request
    const contentType = req.headers.get("content-type");
    if (!contentType || !contentType.includes("multipart/form-data")) {
      return NextResponse.json(
        { error: "Invalid content type. Expected multipart/form-data." },
        { status: 400 }
      );
    }

    // Parse request body
    const formData = await req.formData();
    const file = formData.get("file");
    const body = await req.json();
    const { file_key, file_name } = body;

    // Validate required fields
    if (!file || !file_key || !file_name) {
      console.error("Missing required fields in the request body:", {
        file,
        file_key,
        file_name,
      });
      return NextResponse.json(
        { error: "Missing required fields: file, file_key, and file_name" },
        { status: 400 }
      );
    }


    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      return NextResponse.json(
        { error: "File size exceeds the maximum limit of 5MB." },
        { status: 400 }
      );
    }

    // Handle file_key and file_name (e.g., store in a database, etc.)
    console.log("Processing file:", { file_key, file_name });

    // Load file data into Pinecone
    const pages = await loadMinioIntoPinecone(file_key , file);

    // Return a successful response
    return NextResponse.json(
      {
        message: `${pages} pages processed successfully for file: ${file_name}.`,
        file_key,
        file_name,
      },
      { status: 200 }
    );
  } catch (error) {
    console.error("Error in POST /api/create-chats:", error);
    return NextResponse.json(
      { error: "Internal server error. Please try again later." },
      { status: 500 }
    );
  }
}

FileUpload.tsx

"use client";

import React, { useState } from "react";
import { FileUpload } from "@/components/ui/file-upload";
import { uploadToMinIO } from "@/lib/minio"; // Import the upload function
import { useMutation } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";

export function FileUploadComponent() {
  const [errorMessage, setErrorMessage] = useState<string | null>(null); // State for error messages

  const { mutate, isPending } = useMutation({
    mutationFn: async ({ file_key, file_name }: { file_key: string; file_name: string }) => {
      const response = new Request(`/api/create-chats`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ file_key, file_name }),
      });
      if (!response) {
        throw new Error('Network response was not ok');
      }
      const responseData = await response.json();
      return responseData;
    },
    onError: (error: Error) => {
      setErrorMessage(error.message); // Set error message on mutation error
    },
  });

  const handleFileUpload = async (uploadedFiles: File[]) => {
    if (uploadedFiles.length === 0) {
      console.error("No files selected.");
      return;
    }

    try {
      setErrorMessage(null); // Reset error message
      const uploadPromises = uploadedFiles.map(async (file) => {
        const data = await uploadToMinIO(file);
        if (!data?.file_key || !data?.file_name) {
          throw new Error("An error occurred during file upload.");
        }
        return data;
      });

      const uploadedFilesData = await Promise.all(uploadPromises);
      uploadedFilesData.forEach((data) => {
        mutate(data, {
          onSuccess: (data) => {
            console.log("Upload successful:", data);
          },
        });
      });
    } catch (error) {
      console.error("Error uploading file to MinIO:", error);
      setErrorMessage("Error uploading files. Please try again."); // Set a user-friendly error message
    }
  };

  return (
    <div className="bg-transparent dark:bg-black rounded-lg p-4">
      {isPending ? (
        <div className="flex justify-center items-center h-32">
          <Loader2 className="w-10 h-10 text-blue-900 animate-spin" />
          <p className="text-neutral-700 dark:text-neutral-300">Uploading...</p>
        </div>
      ) : (
        <>
          {errorMessage && <p className="text-red-500">{errorMessage}</p>} {/* Display error message */}
          <FileUpload onChange={handleFileUpload} />
        </>
      )}
    </div>
  );
}

Truth be told im still a novice regarding back-end, but I tried using different dependencies like axios, and Next’s defualt routing dependencies but alas nothing worked.

Draw distorted image on canvas and don’t show wire mesh

I’d like to ask if there is a version without the wire mesh, I tried to use http://tulrich.com/geekstuff/canvas/perspective.html but I still can’t realize the control point and no wire mesh together. Thank you!

Reference Draw distorted image on html5’s canvas Author’s version

But I don’t want answers like this one, because I need the image to flip or the control points to be swapped without a wire mesh.

var triangle1 = new Triangle(
    new Point(p1x-1, p1y),
    new Point(p3x+2, p3y+1),
    new Point(p4x-1, p4y+1),
    new TextCoord(u1, v1),
    new TextCoord(u2, v2),
    new TextCoord(u1, v2)
);

var triangle2 = new Triangle(
    new Point(p1x-2, p1y),
    new Point(p2x+1, p2y),
    new Point(p3x+1, p3y+1),
    new TextCoord(u1, v1),
    new TextCoord(u2, v1),
    new TextCoord(u2, v2)
);

Here is my program code URL:

var controls = []
var canvas
var context
var image
var triangles = []
var dirtyTriangles = true

var rand = function(s, e) {
  return Math.random() * (e - s) + s
}

// dom ready
document.addEventListener("DOMContentLoaded", function() {
  image = new Image();
  image.onload = function() {
    setInterval(draw, 1000 / 60);
  };
  image.src = "https://cdn.pixabay.com/photo/2021/12/23/03/58/da-guojing-6888603_1280.jpg";

  canvas = document.createElement("canvas");
  canvas.width = 500;
  canvas.height = 500;
  document.body.appendChild(canvas);

  context = canvas.getContext("2d");

  controls = [];
  for (let i = 0; i < 4; ++i) {
    const control = document.createElement("div");
    control.classList.add("node");
    document.body.appendChild(control);
    controls.push(control);
  }

  controls[0].style.left = "25px";
  controls[0].style.top = "25px";

  controls[1].style.left = "250px";
  controls[1].style.top = "25px";

  controls[2].style.left = "250px";
  controls[2].style.top = "250px";

  controls[3].style.left = "25px";
  controls[3].style.top = "250px";

  document.body.addEventListener("mousedown", function(e) {
    if (e.target.classList.contains("node")) {
      const node = e.target;

      const mouseMoveHandler = function(e) {
        const x = e.pageX + "px";
        const y = e.pageY + "px";
        node.style.left = x;
        node.style.top = y;
        dirtyTriangles = true;
      };

      const mouseUpHandler = function() {
        document.body.removeEventListener("mousemove", mouseMoveHandler);
        document.body.removeEventListener("mouseup", mouseUpHandler);
      };

      document.body.addEventListener("mousemove", mouseMoveHandler);
      document.body.addEventListener("mouseup", mouseUpHandler);
    }
  });
});

var draw = function() {
  context.clearRect(0, 0, 500, 500)

  var render = function(wireframe, image, tri) {
    if (image) {
      drawTriangle(
        context,
        image,
        tri.p0.x,
        tri.p0.y,
        tri.p1.x,
        tri.p1.y,
        tri.p2.x,
        tri.p2.y,
        tri.t0.u,
        tri.t0.v,
        tri.t1.u,
        tri.t1.v,
        tri.t2.u,
        tri.t2.v,
      )
    }
  }

  if (dirtyTriangles) {
    dirtyTriangles = false
    calculateGeometry()
  }

  for (triangle of triangles) {
    render(false, image, triangle)
  }
}

var calculateGeometry = function() {
  // clear triangles out
  triangles = []
  // generate subdivision
  var subs = 7
  var divs = 7
  const p1 = new Point(
    parseInt(controls[0].style.left) + 6,
    parseInt(controls[0].style.top) + 6,
  )
  const p2 = new Point(
    parseInt(controls[1].style.left) + 6,
    parseInt(controls[1].style.top) + 6,
  )
  const p3 = new Point(
    parseInt(controls[2].style.left) + 6,
    parseInt(controls[2].style.top) + 6,
  )
  const p4 = new Point(
    parseInt(controls[3].style.left) + 6,
    parseInt(controls[3].style.top) + 6,
  )

  var dx1 = p4.x - p1.x
  var dy1 = p4.y - p1.y
  var dx2 = p3.x - p2.x
  var dy2 = p3.y - p2.y

  var imgW = image.naturalWidth
  var imgH = image.naturalHeight

  for (var sub = 0; sub < subs; ++sub) {
    var curRow = sub / subs
    var nextRow = (sub + 1) / subs

    var curRowX1 = p1.x + dx1 * curRow
    var curRowY1 = p1.y + dy1 * curRow

    var curRowX2 = p2.x + dx2 * curRow
    var curRowY2 = p2.y + dy2 * curRow

    var nextRowX1 = p1.x + dx1 * nextRow
    var nextRowY1 = p1.y + dy1 * nextRow

    var nextRowX2 = p2.x + dx2 * nextRow
    var nextRowY2 = p2.y + dy2 * nextRow
    for (var div = 0; div < divs; ++div) {
      var curCol = div / divs
      var nextCol = (div + 1) / divs
      var dCurX = curRowX2 - curRowX1
      var dCurY = curRowY2 - curRowY1
      var dNextX = nextRowX2 - nextRowX1
      var dNextY = nextRowY2 - nextRowY1
      var p1x = curRowX1 + dCurX * curCol
      var p1y = curRowY1 + dCurY * curCol

      var p2x = curRowX1 + (curRowX2 - curRowX1) * nextCol
      var p2y = curRowY1 + (curRowY2 - curRowY1) * nextCol

      var p3x = nextRowX1 + dNextX * nextCol
      var p3y = nextRowY1 + dNextY * nextCol

      var p4x = nextRowX1 + dNextX * curCol
      var p4y = nextRowY1 + dNextY * curCol
      var u1 = curCol * imgW
      var u2 = nextCol * imgW
      var v1 = curRow * imgH
      var v2 = nextRow * imgH

      var triangle1 = new Triangle(
        new Point(p1x, p1y),
        new Point(p3x, p3y),
        new Point(p4x, p4y),
        new TextCoord(u1, v1),
        new TextCoord(u2, v2),
        new TextCoord(u1, v2),
      )
      var triangle2 = new Triangle(
        new Point(p1x, p1y),
        new Point(p2x, p2y),
        new Point(p3x, p3y),
        new TextCoord(u1, v1),
        new TextCoord(u2, v1),
        new TextCoord(u2, v2),
      )

      triangles.push(triangle1)
      triangles.push(triangle2)
    }
  }
}
var drawTriangle = function(
  ctx,
  im,
  x0,
  y0,
  x1,
  y1,
  x2,
  y2,
  sx0,
  sy0,
  sx1,
  sy1,
  sx2,
  sy2,
) {
  ctx.save()
  ctx.beginPath()
  ctx.moveTo(x0, y0)
  ctx.lineTo(x1, y1)
  ctx.lineTo(x2, y2)
  ctx.closePath()
  //ctx.stroke();
  ctx.clip()
  // TODO: eliminate common subexpressions.
  var denom = sx0 * (sy2 - sy1) - sx1 * sy2 + sx2 * sy1 + (sx1 - sx2) * sy0
  if (denom == 0) {
    return
  }
  var m11 = -(sy0 * (x2 - x1) - sy1 * x2 + sy2 * x1 + (sy1 - sy2) * x0) / denom
  var m12 = (sy1 * y2 + sy0 * (y1 - y2) - sy2 * y1 + (sy2 - sy1) * y0) / denom
  var m21 = (sx0 * (x2 - x1) - sx1 * x2 + sx2 * x1 + (sx1 - sx2) * x0) / denom
  var m22 = -(sx1 * y2 + sx0 * (y1 - y2) - sx2 * y1 + (sx2 - sx1) * y0) / denom

  var dx =
    (sx0 * (sy2 * x1 - sy1 * x2) +
      sy0 * (sx1 * x2 - sx2 * x1) +
      (sx2 * sy1 - sx1 * sy2) * x0) /
    denom
  var dy =
    (sx0 * (sy2 * y1 - sy1 * y2) +
      sy0 * (sx1 * y2 - sx2 * y1) +
      (sx2 * sy1 - sx1 * sy2) * y0) /
    denom
  ctx.transform(m11, m12, m21, m22, dx, dy)

  // Draw the whole image.  Transform and clip will map it onto the
  // correct output triangle.
  //
  // TODO: figure out if drawImage goes faster if we specify the rectangle that
  // bounds the source coords.
  ctx.drawImage(im, 0, 0)
  ctx.restore()
}

// point class

var Point = function(x, y) {
  this.x = x ? x : 0
  this.y = y ? y : 0
}

var p = Point.prototype

p.length = function(point) {
  point = point ? point : new Point()
  var xs = 0,
    ys = 0
  xs = point.x - this.x
  xs = xs * xs

  ys = point.y - this.y
  ys = ys * ys
  return Math.sqrt(xs + ys)
}

var TextCoord = function(u, v) {
  this.u = u ? u : 0
  this.v = v ? v : 0
}

var Triangle = function(p0, p1, p2, t0, t1, t2) {
  this.p0 = p0
  this.p1 = p1
  this.p2 = p2

  this.t0 = t0
  this.t1 = t1
  this.t2 = t2
}
body {
  background-color: #111;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.node {
  border-radius: 12px;
  width: 24px;
  height: 24px;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  background-color: magenta;
}

canvas {
  background-color: white;
  width: 500px;
  height: 500px;
}

JSFiddle

enter image description here
I hope that even if the whole image is flipped over, there will be no wire mesh.

Cannot extract public key from ASN Object

So I am trying to parse a der format file to extract the public key. I have three algos, RSA, EDDSA and ECDSA. The below code works for RSA but not for EDDSA and ECDSA. I am getting the below error

Error: Cannot read public key. Unknown OID. at
push../node_modules/node-forge/lib/rsa.js.pki.publicKeyFromAsn1

Below is the function which I wrote which parses the der to extract the public key. I think this is generic but not sure why it is not working for ecdsa and eddsa.

  const uploadDer = (file: any): boolean => {
    const fileReader = new FileReader();

    fileReader.onload = () => {
      const arrayBuffer = fileReader.result as ArrayBuffer;

      try {
        const uint8Array = new Uint8Array(arrayBuffer);
        const byteBuffer = forge.util.createBuffer(uint8Array);
        const asnObject = forge.asn1.fromDer(byteBuffer);
        const publicKeyObject = forge.pki.publicKeyFromAsn1(asnObject);
        const fileContent = forge.pki.publicKeyToPem(publicKeyObject);
        console.log('fileContent--> ', fileContent);

        const pemSections = forge.pem.decode(fileContent);
        const lastPemSection = pemSections[pemSections.length - 1];
        const publicKey = forge.util.encode64(lastPemSection.body);
        props.change('publicKey', publicKey);
      } catch (error) {
        props.change('publicKey', '');

        return dispatch(
          showNotification({
            id: uuidv1(),
            title: 'statusTitle',
            message: 'uploadKeypairFailedMessage',
            type: NotificationTypes.error,
          })
        );
      }
    };

    fileReader.onerror = (error) => {
      console.error('onerror', error);
    };

    fileReader.readAsArrayBuffer(file);

    return false;
  };

How to display items without overlapping?

i’m trying to make reservation chart with using ChartJs in react.

const scheduleData = {
  data: [
    {
      name: "testNameA",
      title: "a teatment",
      start: new Date(2025, 0, 1, 9, 0, 0),
      end: new Date(2025, 0, 1, 10, 0, 0),
    },
    {
      name: "testNameB",
      title: "b teatment",
      start: new Date(2025, 0, 1, 9, 0, 0),
      end: new Date(2025, 0, 1, 10, 0, 0),
    },
    {
      name: "testNameC",
      title: "c teatment",
      start: new Date(2025, 0, 1, 10, 0, 0),
      end: new Date(2025, 0, 1, 11, 0, 0),
    },
    {
      name: "testNameD",
      title: "d teatment",
      start: new Date(2025, 0, 1, 11, 0, 0),
      end: new Date(2025, 0, 1, 12, 0, 0),
    },
    {
      name: "testNameE",
      title: "e teatment",
      start: new Date(2025, 0, 1, 14, 0, 0),
      end: new Date(2025, 0, 1, 15, 0, 0),
    },
    {
      name: "testNameF",
      title: "f teatment",
      start: new Date(2025, 0, 2, 9, 0, 0),
      end: new Date(2025, 0, 2, 10, 0, 0),
    },
    {
      name: "testNameG",
      title: "g teatment",
      start: new Date(2025, 0, 3, 9, 0, 0),
      end: new Date(2025, 0, 3, 10, 0, 0),
    },
  ],

  openTime: 9,
  closeTime: 19,
};
                    data: scheduleData.data.map((schedule) => {
                      return {
                        x:
                          dayNames[Number(moment(schedule.start).format("d"))] +
                          schedule.start.getDate(),
                        y: [
                          moment(schedule.start).hour(),
                          moment(schedule.end).hour(),
                        ],
                        title: schedule.title,
                        name: schedule.name,
                      };
                    }),

as you can see, x value is for start date, y value is for hour value of start,end

if i make a bar chart with this, this happens.enter image description here

testNameA, testNameB has the same start date value. so it seems ovelapped bar items.

What I want to implement is, if you have the same start date, make the items all visible in the same position without overlapping.

like this.
enter image description here

And if you don’t have multiple items with the same date value, I want to make it look like the previous image.

i tried using multiple datasets, but this is the result what i’m gettingenter image description here

how to display items without overlapping in ChartJs?

how to display items without overlapping in ChartJs

i’m trying to make reservation chart with using ChartJs in react.

const scheduleData = {
  data: [
    {
      name: "testNameA",
      title: "a teatment",
      start: new Date(2025, 0, 1, 9, 0, 0),
      end: new Date(2025, 0, 1, 10, 0, 0),
    },
    {
      name: "testNameB",
      title: "b teatment",
      start: new Date(2025, 0, 1, 9, 0, 0),
      end: new Date(2025, 0, 1, 10, 0, 0),
    },
    {
      name: "testNameC",
      title: "c teatment",
      start: new Date(2025, 0, 1, 10, 0, 0),
      end: new Date(2025, 0, 1, 11, 0, 0),
    },
    {
      name: "testNameD",
      title: "d teatment",
      start: new Date(2025, 0, 1, 11, 0, 0),
      end: new Date(2025, 0, 1, 12, 0, 0),
    },
    {
      name: "testNameE",
      title: "e teatment",
      start: new Date(2025, 0, 1, 14, 0, 0),
      end: new Date(2025, 0, 1, 15, 0, 0),
    },
    {
      name: "testNameF",
      title: "f teatment",
      start: new Date(2025, 0, 2, 9, 0, 0),
      end: new Date(2025, 0, 2, 10, 0, 0),
    },
    {
      name: "testNameG",
      title: "g teatment",
      start: new Date(2025, 0, 3, 9, 0, 0),
      end: new Date(2025, 0, 3, 10, 0, 0),
    },
  ],

  openTime: 9,
  closeTime: 19,
};
                    data: scheduleData.data.map((schedule) => {
                      return {
                        x:
                          dayNames[Number(moment(schedule.start).format("d"))] +
                          schedule.start.getDate(),
                        y: [
                          moment(schedule.start).hour(),
                          moment(schedule.end).hour(),
                        ],
                        title: schedule.title,
                        name: schedule.name,
                      };
                    }),

as you can see, x value is for start date, y value is for hour value of start,end

if i make a bar chart with this, this happens.enter image description here

testNameA, testNameB has the same start date value. so it seems ovelapped bar items.

What I want to implement is, if you have the same start date, make the items all visible in the same position without overlapping.

like this.
enter image description here

And if you don’t have multiple items with the same date value, I want to make it look like the previous image.

i tried using multiple datasets, but this is the result what i’m gettingenter image description here

how to display items without overlapping in ChartJs?

WebView Android not satisfying S.browser_fallback_url

I am trying to implement an app that uses webview, inside the html loaded on clicking a button the app a intent url of the form intent://<data>#Intent;scheme=<scheme-name>;action=android.intent.action.VIEW;S.browser_fallback_url=<url>;end is opened, If the intent can be handled by an app downloaded then it opens but if the app is not downloaded or the scheme is misspelt then I get net::ERR_UNKNOWN_URL_SCHEME it does not go to the fallback_url provided.

If I use the same intent url in the browser directly then the fallback url is respected

I have tried creating a webViewClient

       myWebView.setWebViewClient(new WebViewClient() {
           @Override
           public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
               if(URLUtil.isNetworkUrl(request.getUrl().toString())) {
                   return false;
               }

               Intent intent;
               try {
                   intent = Intent.parseUri(request.getUrl().toString(), Intent.URI_INTENT_SCHEME);
               }
               catch (URISyntaxException e){
                   return false;
               }

               try{
                   view.getContext().startActivity(intent);
               }
               catch (ActivityNotFoundException e){
                   String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                   if(fallbackUrl != null){
                       view.loadUrl(fallbackUrl);
                   }
               }

               return true;
           }
       });

which works but according to my understanding as given in https://developer.chrome.com/docs/android/intents S.browser_fallback_url should work without the use of a webClient and is already part of webview

What needs to be changed to make it work?

Thanks in advance

Tampermonkey does not run script

I am trying to figure out what I can do to run a simple script via TamperMonkey:

// ==UserScript==
// @name         Test
// @namespace    http://tampermonkey.net/
// @version      2025-01-15
// @description  test
// @author       ngnewbie
// @match        https://youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=mozilla.org
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    alert("foo");
})();

Nothing happens when I run this script. What am I doing wrong ?

These are my settings:
enter image description here

Next.js Paypal integration (@paypal/paypal-react-js) – The Paypal modal closes after sandbox account login

I am working on a small Ecommerce site, and have to integrate paypal into my nextjs application. I don’t have any server and am using a cms. I am using @paypal/react-paypal-js for it, and have pasted the below template code from the docs. Now the paypal button’s rendering, I can see the paypal modal too, I fill in the sample sandbox credentials for testing, it logs in and then suddenly I get this message in the popup: “Things don’t appear to be working at the moment”
However when I click use debit/credit card button below paypal button, that’s working.

paypal modal error img

const PayPalButton: React.FC<PayPalButtonProps> = ({ 
  amount, 
  onSuccess,
  currency = 'USD'
}) => {
  // Create order function
  const createOrder = (data: any, actions: any) => {
    return actions.order.create({
      purchase_units: [{
        amount: {
          value: amount, // Use the prop instead of hardcoded value
          currency_code: currency, // Use the currency prop
        },
      }],
    }).then((orderID:string)=> {
            console.log(orderID)  ; 
            return orderID ;
    })
  };

  const onApprove = (data: any, actions: any) => {
    return actions.order.capture().then((details: any) => {
      console.log("Transaction details:", details); // Log details of the successful capture
      onSuccess(details); // Call your success callback with the details
      alert('Transaction completed by ' + details.payer.name.given_name);
    }).catch((error: any) => {
      console.error("Error capturing payment:", error); // Log any error during capture
      alert("An error occurred while completing the transaction.");
    });
  };

  // Handle errors
  const onError = (err: any) => {
    console.error("PayPal error:", err);
    alert("An error occurred during the payment process.");
  };

  if (!process.env.NEXT_PUBLIC_CLIENT_ID) {
    console.error("PayPal Client ID is not configured");
    return null;
  }

  return (
    <PayPalScriptProvider 
      options={{
        clientId: process.env.NEXT_PUBLIC_CLIENT_ID,
        currency: "USD",
        intent: "capture",
      }}
    >
      <PayPalButtons
       fundingSource= {FUNDING.PAYPAL}
        style={{ layout: "vertical" }}
        createOrder={createOrder}
        onApprove={onApprove}
        onError={onError}
      />
    </PayPalScriptProvider>
  );
};

export default PayPalButton;

The camera doesn’t move with the avatar template and cursor in Networked A-frame scene

I am implementing a network scene with avatar in a react project using the Networked A-frame framework. The camera doesn’t move and is in the center of the scene, but the avatar and cursor move together. What could be the problem?

The hierarchy is realized as follows: The root container rig serves as the main positioning entity, within which is a player network entity containing camera and visual avatar elements. The camera entity includes controls for movement and inspection, and the fact that it is a child of the player. The visual representation (avatar template: box and text) exists at the same level as the camera, inside the player entity, which should allow them to move together as a unit, but they don’t.

Here is avatar temlate creation (template-setup.js):

export const createAvatarTemplate = () => {
  if (document.getElementById('avatar-template')) return;

  const templateHTML = `
    <template id="avatar-template">
      <a-entity class="avatar">
        <a-box 
          class="head clickable"
          color="#5985ff"
          depth="0.2"
          height="0.2"
          width="0.2"
          position="0 1.6 0"
          material="opacity: 0.8"
        ></a-box>
        <a-text
          class="player-name"
          position="0 1.9 0"
          align="center"
          side="double"
          width="1"
          color="#FFFFFF"
          scale="0.5 0.5 0.5"
        ></a-text>
      </a-entity>
    </template>
  `;

  const template = document.createElement('div');
  template.innerHTML = templateHTML;
  document.body.insertBefore(template.firstElementChild, document.body.firstChild);
}; 

createAvatarTemplate();  

Code of networked scene(NetworkedScene.jsx):

const Cursor = memo(() => (
  <a-cursor
    position="0 0 -1"
    geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03"
    material="color: white; shader: flat"
    cursor="rayOrigin: mouse"
    raycaster="objects: .clickable"
  ></a-cursor>
));

Cursor.displayName = 'Cursor';

const Camera = memo(() => (
  <a-entity
    id="camera"
    position="0 1.6 0"
    camera
    look-controls="pointerLockEnabled: false"
    wasd-controls="acceleration: 200; fly: true"
  >
    <Cursor />
  </a-entity>
));

Camera.displayName = 'Camera';

const Player = memo(() => (
  <a-entity
    id="player"
    position="0 0 0"
    networked="template: #avatar-template; attachTemplateToLocal: true"
  >
    <a-box
      class="head clickable"
      color="#5985ff"
      depth="0.2"
      height="0.2"
      width="0.2"
      position="0 1.6 0"
    />
    <a-text
      class="player-name"
      value="Player"
      position="0 1.9 0"
      align="center"
      side="double"
      width="1"
      color="#FFFFFF"
      scale="0.5 0.5 0.5"
    />
  </a-entity>
));

Player.displayName = 'Player';

const VRScene = memo(({ sceneRef, username, roomName }) => (
  <a-scene
    ref={sceneRef}
    embedded
    networked-scene={`
      room: ${roomName}; 
      adapter: socketio; 
      audio: false; 
      debug: true; 
      connectOnLoad: true; 
      serverURL: ws://localhost:8000
    `}
    renderer="antialias: true"
    background="color: #1a1a1a"
  >
    <a-entity 
      id="rig" 
      position="0 0 0"
      rotation-reader
    >
      <Camera />
      <a-entity
        id="player"
        networked="template: #avatar-template; attachTemplateToLocal: true"
      >
        <a-box
          class="head clickable"
          color="#5985ff"
          depth="0.2"
          height="0.2"
          width="0.2"
          position="0 1.6 0"
        />
        <a-text
          class="player-name"
          value={username}
          position="0 1.9 0"
          align="center"
          side="double"
          width="1"
          color="#FFFFFF"
          scale="0.5 0.5 0.5"
        />
      </a-entity>
    </a-entity>

    <a-plane position="0 0 0" rotation="-90 0 0" width="30" height="30" color="#7BC8A4"></a-plane>
    <a-sky color="#ECECEC"></a-sky>
    <a-entity light="type: ambient; color: #BBB"></a-entity>
    <a-entity light="type: directional; color: #FFF; intensity: 0.6" position="-0.5 1 1"></a-entity>
  </a-scene>
));


VRScene.displayName = 'VRScene';

And I need to define the avatar template that way, since there is a conflict between React and NAF.

As soon as I try to link them together, the avatar pattern disappears or one thing moves:

  1. Avatar and cursor, and the camera stands still.
  2. The camera and cursor, and the avatar disappears.

How to re-direct to a particular bootstrap tab

I found the following code in another post (which I can’t find now) but can’t get the code to work. As you can see from the attached image, I am getting close because the tab has a blue highlight whereas before I installed the code there was no highlight. A commenter to the post I can’t find said some mods to this code were necessary but did not give specifics or an example. I added my page’s url, or at least the portion before the hash. Another commenter said this would not active but didn’t offer a solution.

TIA for any help.

<script>
$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="2025_dko_home_need_to_renew_join.php#' + hash + '"]').tab('show active');

  $('.nav-tabs a').click(function (e) {
    $(this).tab('show');
    var scrollmem = $('body').scrollTop();
    window.location.hash = this.hash;
    $('html,body').scrollTop(scrollmem);
  });
});    
</script>

Here’s the tab’s HTML code:

<div class="container-fluid">
  <ul id="clothingnav1" class="nav nav-tabs" role="tablist">

    <li class="nav-item"> <a class="nav-link active" href="#home1" id="hometab1" role="tab" data-toggle="tab" aria-controls="home" aria-expanded="true">Online Entry</a> </li>

    <li class="nav-item"> <a class="nav-link" href="#paneTwo1" role="tab" id="hatstab1" data-toggle="tab" aria-controls="hats">Advance Entries</a> </li>

tab with blue border

I was expecting to be able to click on the tab’s url#tab_id and have the page open and goto the second tab.