I want to modify this photoshop .js script to save as a different format

I need a modification to this script to change the save as format

my goal is to have a script that saves as an Icon and close the document afterwards,
photoshop doesn’t support saving as Icon by default but using this plugin it gives me the option to do so (image has to be 8bit and no larger than 256×256)
Save as icon

I found the script below and it does most of what I want, except that it saves as png, I want to change that so it saves as an Icon.ico

and if possible, I want the script to also minimize photoshop after it’s finished.

main();


function main(){


if(!documents.length) return;


try{


    var Path = decodeURI(activeDocument.path);


    }catch(e){return;}


if(!Folder(Path).exists){


    alert(Path + " Does not exist!");


    return;


    }


var Name = decodeURI(app.activeDocument.name).replace(/.[^.]+$/, '');


var saveFile = File(Path + "/" + Name + ".png");


sfwPNG24(saveFile);


//Uncomment the line below if you want to close the document.


//app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);


}


function sfwPNG24(saveFile){


var pngOpts = new PNGSaveOptions;


pngOpts.compression = 9;


pngOpts.interlaced = false;


activeDocument.saveAs(saveFile, pngOpts, true, Extension.LOWERCASE); 


}

I should mention that after choosing to save as an icon, the plugin pops up this “Choose icon format” box (I always use standard ICO) so this has to be addressed in the script

Standard ICO

any help is appreciated, Thank you in advance.

How to only play splash screen text when the user lands on the home page, then it doesn’t play if they go back

I have a splash screen on my website home page, and it works, but it continuously plays even after the user has went to the home page, and then they go back. Is their any way to make sure that the animation only happens when the home page loads at first, and the user sees it, but then it never happens again until the page is closed and reopened?

HTML:

<!--Page Intro-->
<div class="splash">
    <h1 class="splash-content">Substitute Text Here</h1>
    <h1 class="splash-content">Substitute Text Here</h1>
</div>

CSS:

/* Intro */
.splash {
    background: black;
    z-index: 2;
    text-align: center;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100vh;
    transition: 2s;
}

.splash-content {
    color: white;
    transform: translateY(11em);
}

.splash.display-none{
    opacity: 0;
    z-index: 0;
    transform: translateY(-100%);
}

JS:

const splash = document.querySelector('.splash');
document.addEventListener('DOMContentLoaded', (e) => {
    setTimeout(() => {
       splash.classList.add('display-none');
    }, 2000);
})

How do I compare large decimal numbers in TypeScript/JavaScript?

I want to write a function that looks like this:

function getValuesGreaterThan(num, values);

It’ll return an array of the values.

Normally this is straightforward, but the values are stored in an array of strings: [..., "1643764147.7500000000", "1643764147.7600000000", "1643764147.7700000000", ...]. I want to make sure the output of getValuesGreaterThan isn’t affected by precision issues or coercion quirks.

I’ve learned that JavaScript/TypeScript has a BigInt type, but I can’t find anything about a BigReal or a BigDecimal, etc. I’m not even sure if I need to use these; perhaps the localeCompare will work as expected on these strings?

let getValuesGreaterThan = function (num, values) {
  return values.filter((v) => v.localeCompare(num) >= 0)
}

console.log(getValuesGreaterThan("1643764147.7600000000", ["1643764147.7500000000", "1643764147.7600000000", "1643764147.7700000000"]))

It seems to work, but there’s no way for me to know if other inputs could break it.

How do I compare large decimal numbers in TypeScript/JavaScript? An answer in either language is fine, but my codebase is TS.

Intersection Observer Not Working In Razor Page

I was trying to use intersection observers (javascript) in my razor pages but they don’t seem to be working, I also couldn’t find anything online where this is an issue.

// Intersection observer
const callback = function (entries) {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('show');
            observer.unobserve(entry.target)
        }
    });
}
const observer = new IntersectionObserver(callback);
const targets = document.querySelectorAll('.hidden');
targets.forEach(target => {
    observer.observe(target);
})

I found a post with similar code (i just changed the classes’ name) and it is not working.

I watched some yt videos and their code did not work for me either with exact copy pasting basically.

Any Ideas?

I need to convert Bytes[] to PDF on click and display on the side

I have a TreeList that I use as a third party DevExpress but I don’t need anything related to DevExpress but what when I click there is an event that calls a function in JavaScript that I have PDF bytes in one in the column I would like to know if there is any way to take the bytes and convert it to PDF and show it to the side on the right on the screen, I don’t need to download the file or show it on another tab just show it on the right to show a preview of the doc.

I leave some images and my code that currently tells me that the string is too big to pass it through the browser, I wanted to know if someone has done something like this.

enter image description here
JavaScript Function

    function GetPdf(result) {

        alert(result);
        var x = result;
        $("#DisplayPDF").html(
            $('<iframe>', {
                src: 'data:application/pdf;base64,' + x,
                width: '600px',
                height: "800px"
            })
        );
    }

View

<div id="DisplayPDF" style="float: right; width: 45%;overflow-y:scroll;height:60vh; margin-top:10px"></div>

I added an alert of the parameter result and that is what I’m getting.
enter image description here

Why does “localStorage.getItem(‘score’) keep adding dashes to my score variables and losses are stuck at 1 in the console? [closed]

here is the code that I used

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button onclick="
      playGame('heads');
    ">heads</button>
    <button onclick="
      playGame('tails');
    ">tails</button>
    <script>
      const score = JSON.parse(localStorage.getItem('score')) || {
        wins: 0,
        losses: 0
      }
      
      function playGame(guess) {
        const randomNumber = Math.random();
        const result = randomNumber < 0.5 ? 'heads' : 'tails';

        console.log(guess === result ? 'You win!' : 'You lose');

        if (guess === result) {
          score.wins++
        } else {
          score.losses++;
        };
        console.log(score);

        localStorage.setItem('score', JSON.stringify(score));
      }
    </script>
  </body>
</html>

when I tried it it added one to ‘score.losses’ and never added anything to the other variable, instead it kept adding forword slashes before every variable in ‘score’

Understanding order of tasks in the micro queue used for promises

I am trying to get a better understanding of the Nodejs event loop and have got to the different types of queues that are used under the covers. My question is related to the micro queue used for promises.

From everything I have read, my current understanding is that the micro queue used for promises works on a FIFO basis (first in first out). However I have a small piece of example code that doesn’t make sense to me following that principle.

const promise1 = Promise.resolve();
const promise2 = Promise.resolve();

promise2.then(function p2() {
  console.log('in promise2.then()')
})
promise1.then(function p1() {
  console.log('in promise1.then()')
})
console.log('end test')

So from my current (quite possibly flawed understanding) of the order of events that will take place here is

  1. promise1 resolves instantly causing its handler (p1) to be added to the micro queue
  2. promise2 resolves instantly causing its handler (p2) to be added to the micro queue
  3. console.log('end test') gets added to the stack, instantly popped resulting in the log being printed
  4. Now that the stack is empty the p1 handler is picked off the queue (FIFO) and added to the stack resulting in in promise1.then() being printed
  5. The p2 handler is picked off the queue and added to the stack resulting in in promise2.then() being printed

This would result in an output of

end test
in promise1.then()
in promise2.then()

However what I am actually getting is

end test
in promise2.then()
in promise1.then()

I’ve even tried to run it through a visualiser like this https://www.jsv9000.app/?code=Y29uc3QgcHJvbWlzZTEgPSBQcm9taXNlLnJlc29sdmUoKTsKY29uc3QgcHJvbWlzZTIgPSBQcm9taXNlLnJlc29sdmUoKTsKCnByb21pc2UyLnRoZW4oZnVuY3Rpb24gcDIoKSB7CiAgY29uc29sZS5sb2coJ2luIHByb21pc2UyLnRoZW4oKScpCn0pCnByb21pc2UxLnRoZW4oZnVuY3Rpb24gcDEoKSB7CiAgY29uc29sZS5sb2coJ2luIHByb21pc2UxLnRoZW4oKScpCn0pCmNvbnNvbGUubG9nKCdlbmQgdGVzdCcp

My understanding seems to hold up while the handlers are being added to the micro queue but then everything falls apart once it starts picking things off.

My question is how is the p2 handler being picked off the micro queue and run before the p1 handler if the microqueue is a FIFO system?

SQLite-expo return nothing

When i try to connect and then get data from db i get nothing but i have records in database (SQLiteStudio records proof)
I try all guids from Ethernet: get path with filesystem, use other derectory or only db name but it don`t help.
This is my directory screenshot .

My code

ExercisePage.js

import React, { useEffect, useState } from "react";
import * as SQLite from "expo-sqlite";
import { StyleSheet, View, Text } from "react-native";

const db = SQLite.openDatabase("../SQLite/data.db");

export default function ExercisePage() {
  const [exercises, setExercises] = useState([]);

  useEffect(() => {
    db.transaction((tx) => {
      tx.executeSql(
        "SELECT exercise.name AS exerciseName, GROUP_CONCAT(tag.name) AS tagNames " +
          "FROM exercise " +
          "LEFT JOIN exercise_tag ON exercise.id = exercise_tag.exercise_id " +
          "LEFT JOIN tag ON exercise_tag.tag_id = tag.id " +
          "GROUP BY exercise.id",
        [],
        (_, { rows }) => {
          const exercisesData = rows._array.map((row) => {
            return {
              name: row.exerciseName,
              tags: row.tagNames ? row.tagNames.split(",") : [],
            };
          });
          setExercises(exercisesData);

          console.log(exercisesData);
        },
        (_, error) => {
          console.error("Error fetching exercises:", error);
        }
      );
    });

    return () => db.close();
  }, []);

  return (
    <View style={styles.MainBox}>
      {exercises.map((exercise, index) => (
        <React.Fragment key={index}>
          <Text>{exercise.name}</Text>
          {exercise.tags.map((tag, tagIndex) => (
            <Text key={tagIndex}>{tag}</Text>
          ))}
        </React.Fragment>
      ))}
    </View>
  );
}

metro.config.js

const { getDefaultConfig } = require('expo/metro-config');

const defaultConfig = getDefaultConfig(__dirname);

defaultConfig.resolver.assetExts.push('db','sqlite');

module.exports = defaultConfig;

module.exports = {
    resolver: {
      assetExts: ['db', 'sqlite', 'ttf', 'obj', 'png', 'jpg', 'otf', 'ttc'],
    },
  };
  

Thanks for help.

What is the mistake here? Help me

I have this code:

const query = {
        sql: 'SELECT idA, idB FROM friends WHERE currentStatus = 'accepted' AND (idA = ? OR idB = ?)',
        values: [20, 20]
    };

But when doing the query from the front-end the back-end console returns this:

[ERR] Error query getAllFriends. (Unknown column 'id' in 'where clause') | Require: (IP) to '/friends/getallforuser': [POST].

Can you tell me what I did wrong? Or where it takes ‘id’ because I don’t declare it, my table is like this:

idA: int
idB: int
currentStatus: varchar(45)
idnoti: int

I hope that it returns the data that I request to handle it with another function, but it returns the error, I already tried to do a thousand things and nothing works 🙁

404 error with Node.js app deployed to Vercel using fetch

I am creating a website using Node.js to fetch image data from the image URL and showing the result on the page. I plan to turn it into a web scraping tool on the web to scrape image data from webpages instead of just image URLs.

When I open the console on Microsoft Edge after inputting in the image URL then pressing the button the error “/api/fetch-image?url=https%3A%2F%2Fmy.alfred.edu%2Fzoom%2F_images%2Ffall-drone-shot-thumbnail.jpg:1 Failed to load resource: the server responded with a status of 404 ()” comes up. It worked perfectly fine using a localhost proxy server of 3000 but doesn’t work on Vercel. I also edited it so that the code doesn’t include the proxy 3000 for Vercel.

The image URL I am using is: https://my.alfred.edu/zoom/_images/fall-drone-shot-thumbnail.jpg

The vercel URL to my app is: https://billionaire-shopping-game-web.vercel.app/

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Image Fetcher</title>
  <link rel="shortcut icon" href="">
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <h1>Image Fetcher</h1>
  <form id="image-form">
    <label for="url">Enter the image URL:</label>
    <input type="text" id="url" name="url">
    <button type="submit">Fetch Image</button>
  </form>
  <div id="image-container"></div>
  <script src="main.js"></script>
</body>
</html>

package.json

{
  "name": "billionaire-shopping-game-web",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^1.4.0",
    "express": "^4.18.2"
  }
}

main.js

document.getElementById('image-form').addEventListener('submit', async (event) => {
  event.preventDefault();
  
  const urlInput = document.getElementById('url');
  const imageUrl = urlInput.value;
  
  try {
    const response = await fetch(`/api/fetch-image?url=${encodeURIComponent(imageUrl)}`);
    
    if (response.ok) {
      const blob = await response.blob();
      const imageSrc = URL.createObjectURL(blob);
      const imageContainer = document.getElementById('image-container');
      imageContainer.innerHTML = `<img src="${imageSrc}" alt="Fetched Image">`;
    } else {
      console.error(response.status);
      alert('Error fetching image');
    }
  } catch (error) {
    console.error(error);
    alert('Error fetching image');
  }
});

server.js

const express = require('express');
const axios = require('axios');

const app = express();

app.get('/api/fetch-image', async (req, res) => {
  const imageUrl = req.query.url;
  
  try {
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
    const imageData = Buffer.from(response.data, 'base64');
    res.contentType('image/jpeg');
    res.send(imageData);
  } catch (error) {
    console.error(error);
    res.status(500).send('Error fetching image');
  }
});

module.exports = app;

Issue removing first element of array with Javascript

I’m trying to find an element in an array, remove that element if found, and then add that element at the start of the array.

However when I log my array sortedAdv returns as only one element length for some reason

My code:

let advantages = [ 'liked', 'sendUnlimitedLikes', 'unlockSundays', 'getBoosted', 'filters', 'revealAllProfiles', 'wholeCountry', 'exlusiveBlogs' ];
        console.log('advantages',advantages.length);
        let index = advantages.findIndex(advantage => advantage == type);
        if(index > -1)
        {
            console.log('index',index);
            let sortedAdv = advantages.splice(index, 1);
            console.log('sortedAdv',sortedAdv.length);
            sortedAdv.unshift(type);
            console.log('sortedAdv',sortedAdv.length);
            this.setPurchaseAdvantages(sortedAdv);
            

        }

How to add alt text to images without an ID

I need to add alt text to various images which do not have IDs or anything else to identify the images from one another other there the image file names.

Is there a way to add alt text to each image based on what the image file name is?

Here’s an example of the code I started working on, but it obviously doesn’t work and I’m not even sure I am heading in the right direct. Any help would be much appreciated.

<script>
document.onload = function(){
  img.setAttribute('src', 'icons-vegan.png');
  img.setAttribute('alt', 'Vegan Icon');
  img.setAttribute('title', 'Vegan Icon'); 
}   
document.onload = function(){
  img.setAttribute('src', 'icons-gluten.png');
  img.setAttribute('alt', 'Gluten Icon');
  img.setAttribute('title', 'Gluten Icon'); 
}   
</script>

Uncaught TypeError: Cannot read properties of undefined (Webpack, bundling)

Error:

useMultistepForm.ts:34 Uncaught TypeError: Cannot read properties of undefined (reading 'TableFilterOperatorsEqualsNotEquals')
    at Module.TableFilterOperatorsEqualsNotEquals (useMultistepForm.ts:34:1)
    at ./src/main-routes/gtm-publishing-queues/lib/types.ts (types.ts:65:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/main-routes/gtm-publishing-queues/lib/constants.ts (GtmQueue.tsx:47:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/main-routes/gtm-publishing-queues/lib/index.ts (constants.ts:32:1)

Webpack Error:

/* harmony export */   "TableFilterOperatorsEqualsNotEquals": () => (/* reexport safe */ _constants__WEBPACK_IMPORTED_MODULE_5__.TableFilterOperatorsEqualsNotEquals),

useMultistepForm.ts

import { useState } from 'react';

export const useMultistepForm = (maxSteps: number) => {
  const [currentStep, setCurrentStep] = useState(0);

  const next = () => {
    setCurrentStep(i => {
      if (i >= maxSteps - 1) return i;
      return i + 1;
    });
  };

  const back = () => {
    setCurrentStep(i => {
      if (i <= 0) return i;
      return i - 1;
    });
  };

  const goto = (index: number) => {
    if (index < 0) throw new Error('Cannot goto step less than 0');
    else if (index >= maxSteps) throw new Error('Cannot goto step greater than max steps');
    else setCurrentStep(index);
  };

  return {
    currentStep,
    isFirstStep: currentStep === 0,
    isLastStep: currentStep === maxSteps - 1,
    goto,
    next,
    back
  };
};

When I try running npm start, I am getting an undefined error when webpack is bundling. It says my error is from a variable and points to my custom hook when the variable does not exist in that file. Any help is appreciated, thank you!

I tried modifying import statement with/without curly braces and tried exporting using default.

Find distance between 2D point and line segment start point

This feels like a simple problem but I am bad at algebra.

enter image description here

I’m trying to find the distance between a point and the start of a line segment at an angle parallel to the segment. I will use the distance to interpolate a value along the line.

I also need to know when the points are outside of the line.

A code example would be appreciated, this is my attempt so far using threejs Vector2D but it isn’t behaving as expected.

const lineStartOrig = lineStart.clone()

const lineLength = lineStart.distanceTo(lineEnd)

const dotDiff = point2D.sub(lineStart).dot(lineEnd) / lineEnd.dot(lineEnd)


const pointIntersect = dummyLineStart.add(lineEnd)
                                     .multiplyScalar(dotDiff)
                                     .clamp(lineStartOrig, lineEnd)

const value = pointIntersect.distanceTo(lineStartOrig) / lineLength