Photoshop – split / merge channels using Javascript

Photoshop has an option where you can separate each color channel in a diffrent document Channels->options->Split Channels, and reverse process, you can take the separate channels and create a new document (RGB, CMYK, etc) Channels->options->Merge Channels. I want automate this proccess using a script.

The first part Split Channels is done, using the following code:

// Separate each color channel in a different document (grayscale)
app.activeDocument.splitChannels();

But the reverse process to merge all separate channels in a new document, I can’t did it yet. I did search in the Javascript reference manual, but, I canĀ“t found an example or relevant information about it.

I appreciate your help and guidance.

What is the most optimal solution for this array of objects problem. Explain in detail below

we have a array of objects . if value of any object is greater than 3 . we need to multiply it with 10 .

example of array of objects :

arr = [{“a” : 3}, {“b” : 4}, {“c” : 1}, {“d” : 10}, {}, {“e” : 5, “f” : 1}]

in above example we have objects with only one key:value pair and also multiple key:value pair. in multiple key:value pair every value if greater than 3 must be multiply by 10 and we also have a empty object in that case it should be left alone

I have got the solution but its not most optimal one . I have tried my best but couldn’t get it . I was wondering to get an answer here . kindly help me

Why does my addrole command have errors? (discord.jsV12)

So basically my addrole command after the new version of discord.jsv13 no longer works and displays errors like role.id is not a function or role.id is not defined even though I believe there is no error, I’m pretty experienced with javascript but I tried different methods of fixing it but neither seem to do the trick, maybe because v12 is deprecated the discord API malfunctions idk?

The code

const lineReplyNoMention = require('discord-reply');
const color = process.env.Color;
module.exports = {
    name: 'addrole',
    cooldown: 5,
    aliases: ['addnewrole'],
    permissions: ["MANAGE_ROLES"],
    clientpermissions: ["MANAGE_ROLES", "SEND_MESSAGES", "EMBED_LINKS"],
    async execute(client, message, cmd, args, Discord) {
        const user = message.mentions.users.first();
        const usertarget = message.guilds.members.cache.get(user.id);
        if (!user) {
            const nopr = new Discord.MessageEmbed().setTimestamp().setColor(`${color}`).setAuthor(`${message.author.username}`, message.author.displayAvatarURL({ dynamic: true })).setDescription(`**`(prefix)addrole <@user> <@role>`**`)
            return message.lineReplyNoMention({ embed: nopr })
        }
        args.shift()
        const roleToGive = message.mentions.roles.first()
        if (!roleToGive) {
            const addroleError2 = new Discord.MessageEmbed().setTimestamp().setDescription(`**No Roles Provided!**`).setColor(`${color}`)
            return message.lineReplyNoMention({ embed: addroleError2 })
        }
        usertarget.roles.add(roleToGive.id)
        const embed = new Discord.MessageEmbed().setTimestamp().setColor(`${color}`).setAuthor(`${message.author.username}`, message.author.displayAvatarURL({ dynamic: true })).setDescription(`**Added: `${roleToGive}` To `${user.username}`**`)
        message.lineReplyNoMention({ embed: embed })
    }
}

Chrome Extension – Bookmark 2 returning as undefined

I’m creating a chrome extension that allows navigation to the users first four bookmarks using ctrl+shift+number; everything is going well, and functional for the 1st, 3rd and 4th bookmark, but the 2nd bookmark seemingly returns undefined every time.
I have a feeling this is due to the way that I’m navigating the bookmark tree that is get from the chrome api, but I’m unsure where or how I can fix this at all. Another thought is that this function has to be resolved asynchronously, but I’m unsure why that would be, or why it would work with the other bookmarks if that is the case.

This is my js file

const bookmarks = [];

chrome.tabs.onCreated.addListener(function(tab) { //refresh bookmarks on new tab opening
    var bookmarkTreeNodes = chrome.bookmarks.getTree(
    function(bookmarkTreeNodes){
        bookmarksArray(bookmarkTreeNodes)
    })
})

chrome.commands.onCommand.addListener(function(command){ 
    var bookmarkTreeNodes = chrome.bookmarks.getTree( //also check bookmarks on command execution
        function(bookmarkTreeNodes){
            bookmarksArray(bookmarkTreeNodes)
        })
    printArray(); //temp
    console.log('command:',command.charAt(8)); //tab number temp 
    tabSelected = command.charAt(8);
    chrome.tabs.update({
        url: ("" + bookmarks[tabSelected-1])
    })    
});

function printArray(){
    for(var i = 0; i<bookmarks.length; i++){
        console.log(bookmarks[i]);
    }
}
    
function bookmarksArray(bookmarkTree){
    for(var i=0; i<bookmarkTree.length; i++){
        bookmarks[i] = ("" + bookmarkTree[i].url); //url is insert to each spot as string 
        console.log("" + bookmarks[i])
        if(bookmarkTree[i].children){
            bookmarksArray(bookmarkTree[i].children)
        }
    }
}

Fire radio button change action after dynamically created on ajax

Hi stackoverflow community

I’m trying to work with an on change event of radio buttons created dynamically from ajax call. This buttons are created based on mysql result and every radio button should listen to an on change event.

Here is my ajax call:

$.ajax({
        ...
        success:function(ajax_result){
            ajax_result.forEach(fn_Populate); // could be replaced with for loop
            function fn_Populate(element){
                $("xdiv").append("<input type='radio' id='radio_"+element[0]+"' name='xradio'>");
                $("xdiv").append("<label for='radio_"+element[0]+"'>"+element[0]+"</label>");
            }
        }
});

This should create n radio buttons according to ajax result, example radio_1, radio_2, radio3, all with name xradio.

After radio button are created I need to identify when a button is clicked. Here is the code in jquery:

$("input[type=radio][name=xradio]").change(function(){
    alert("DO SOMETHING");
    // rest of code 
});

The problem is that change event is not fired if is outside the ajax call.

I need to fire it outside the ajax call because it will generate another dynamic buttons thru a new ajax call.

All help will be appreciated.

Thanks

react component JSX backgroundColor value not re-applied after refresh

enter image description here

so I have a <ColorPreview /> component that uses a theme value coming from the localStorage previously set by picking a color from a color picker component.

const ColorPreview = ({ colors }: any) => {
  const { theme, setTheme } = useThemeState();
  
  return (
    <>
      <div className='grid grid-cols-3 gap-4'>
        {Object.keys(theme).map((key: any, index) => {
          console.log('THEME', typeof theme[key as keyof ITheme]); //string
          return (
            <div
              key={key}
              className={clsx('overflow-hidden rounded-lg border-2', {
                ['h-62 col-span-2 row-span-2 w-52 ']: index === 0,
              })}
            >
              <div
                style={{
                  backgroundColor: `${theme[key as keyof ITheme]}`,
                }}
                className={clsx('h-28', {
                  ['!h-64']: index === 0,
                })}
              />

              <p
                className={clsx('justify-center p-2 text-base', {
                  ['!p-8']: index === 0,
                })}
              >
                {theme[key as keyof ITheme]}
              </p>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default React.memo(ColorPreview);

i’m setting the theme value using a ColorPicker component that maps a color palette into the theme object so we end up with a theme object with the new color codes as follows:

  theme: {
    primary: newHexValue //#002d89,
    secondary: newHexValue //#bfd4ff,
    tertiary: newHexValue //#80aaff,
  }

the problem is that the new theme value is correctly being set up in localStorage and its values and backgroundColor is correctly being displayed on each color pick from the color picker but after Refresh of the page, the backgroundColor is not being rendered empty even though the correct color code is still persisting in the ColorPreview component as shown below.

enter image description here
any help or guidance is highly appreciated…

ACI IPFS node connection issues

I have followed this tutorial for how to set up an IPFS node in an Azure container to set up two IPFS nodes, one in Europe and one in the US to do some benchmarking on how long it takes to retrieve a CID across the nodes. I have created a simple script for adding and retrieving data from these two nodes using ipfs-http-client.

// write.js
import * as IPFS from 'ipfs-http-client';

const main = async () => {
  const ipfs = IPFS.create({
    host: '<eu host>',
    port: '5001',
    protocol: 'http',
  });

  const { cid } = await ipfs.add(
    `Hello at ${new Date().toISOString()}`
  );

  console.log(cid);
};

main();
// read.js
import * as IPFS from 'ipfs-http-client';

const main = async () => {
  const ipfs = IPFS.create({
    host: '<us host>',
    port: '5001',
    protocol: 'http',
  });

  for await (const c of ipfs.cat(
    '<cid>'
  )) {
    console.log(new TextDecoder().decode(c));
  }
};

main();

If I read and write to the same node it works fine, however, the data stored in one node does not seem to be accessible from any other node anywhere, as if the nodes are not properly connected.

I have also tried using the same snippets of code to write data to the infura-ipfs gateway and retrieving it through the ipfs.io gateway which seems to work. This probably means I have just configured my nodes wrong, however I have no idea how to work around this issue. I have tried multiple solution to just get an IPFS node online but I have not succeeded in any way so far. Optimally, I need any two applications to be able to select any peer at random from a selected list and share the same data across nodes, preferably using pubsub.

How to properly set keydown event listener to send message?

I am writing a small chat app and I ran up into some difficulties. App is properly working but I want to set keydown event listener to track when user presses Enter so he can also send message this way (not just manually clicking the Send message button).

I am using Firebase and firestore as a DB to save messages. Here is the full code of Chat.jsx component:

import { useAuthState } from 'react-firebase-hooks/auth'
import { FirebaseContext } from '..'
import { useCollectionData } from 'react-firebase-hooks/firestore'
import firebase from 'firebase/compat/app'
import Loader from './loader/Loader'
import { generateRandomKey } from '../helpers/generateRandomKey'

const Chat = () => {
    const { auth, firestore } = useContext(FirebaseContext)

    const [user] = useAuthState(auth)
    const [value, setValue] = useState('')
    const [messages, loading] = useCollectionData(
        firestore.collection('messages').orderBy('createdAt')
    )

    const handleSendMessage = async () => {
        firestore.collection('messages').add({
            uid: user.uid,
            displayName: user.displayName,
            photoURL: user.photoURL,
            text: value,
            createdAt: firebase.firestore.FieldValue.serverTimestamp()
        })
        setValue('')
    } // useCallback?

    useEffect(() => {
        document.body.addEventListener('keydown', e => {
            if (e.key === 'Enter') {
                handleSendMessage()
            }
        })
        return () =>
            document.body.removeEventListener('keydown', e => {
                if (e.key === 'Enter') {
                    handleSendMessage()
                }
            })
    }, []) // what to put in deps?

    if (loading) return <Loader />

    return (
        <div className="content">
            <div>
                {messages.map(message => {
                    return (
                        <div key={generateRandomKey()}>
                            <div>
                                <img
                                    src={message.photoURL}
                                    alt="User avatar"
                                />
                                <p>{message.displayName}</p>
                            </div>
                            <p>{message.text}</p>
                        </div>
                    )
                })}
            </div>
            <div>
                <input
                    placeholder="Enter your message..."
                    value={value}
                    onChange={e => setValue(e.target.value)}
                ></input>
                <button onClick={handleSendMessage}>Send message</button>
            </div>
        </div>
    )
}

export default Chat

Speaking about problems – when I am trying to set event listener via useEffect with handleMessage dependency whenever I press Enter it sends two empty messages and then a couple of messages like this:

message: 'hello' -> '' - '' - 'h' - 'he' - 'hel' - 'hell' - 'hello'

useEffect(() => {
    document.body.addEventListener('keydown', e => {
        if (e.key === 'Enter') {
            handleSendMessage()
        }
    })
    return () =>
        document.body.removeEventListener('keydown', e => {
            if (e.key === 'Enter') {
                handleSendMessage()
            }
        })
}, [handleSendMessage]) 

Same happens if I wrap handleSendMessage with useCallback hook and put [user, value, firestore] in deps.

Question: How can I fix this and properly set keydown event listener to send messages via pressing Enter?

Javascript get image width and height from blob

So this is my code snippet (unnecessary code lines are removed):

let imgInput = document.getElementById('id_photo');
imgInput.addEventListener('change', function (e) {
    if (e.target.files) {
        for (let i = 0; i < e.target.files.length; i++) {

        let imageFile = e.target.files[i];
        var reader = new FileReader();

        reader.onload = function (e) {
            var img = document.getElementById(node.inputId+'-img');
            img.onload = function() {
                var shape = resizeImage(img) // resizing image for future canvas drawing, returns [width, height] (resized)
                
                var canvas = document.createElement("canvas")
                canvas.width = 1000
                canvas.height = 1000
                var ctx = canvas.getContext("2d")
                ctx.drawImage(img, 0, 0, shape[0], shape[1])
            }
            img.src = e.target.result;
        }
        reader.readAsDataURL(imageFile);

    }
}
});

I want to get the uploaded original image’s width and height so I can resize it. I can’t do it from imageFile as it returns undefined and can’t get it from the img variable as it originally depends on my css (in css the <img> tag is in a <div> tag which is not fullscreen, let’s say it is 400 pixels). So correspondingly, if I upload 5000×5000 image it will not be the original-sized (hope you got it). My problem is that because my css resizes that div and elements inside, I can’t get normal widht and height of my original image, so I can resize it then draw with canvas and then convert it to base64.

I try to add this code to img.onload:

var blobURL = URL.createObjectURL(imageFile)

Here I access my original image (which is imageFile), create blob for it and get that blob link. But I can’t access that blob link image’s width and height. Any suggestions?

Note: I think the problem is in img.onload itself. As in this line I pass that img:

ctx.drawImage(img, 0, 0, shape[0], shape[1])

and as a result I get this error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.
at HTMLImageElement.img.onload

React component creating extra div

I’m working on converting some page elements into React components and I’m encountering a strange and difficult issue. I create the components normally like so:

const ComponentName = () => {
  return (
    <div className='styling-classes'>
      <SubComponentName />
    </div>
  )
}

and the component renders, but the problem is that React is wrapping it in an extra div that is breaking styling like so:

<div id='div-containing-component>
  // React sticks this in here
  <div id="ComponentName-react-component-a0838426-9f52-48be-99fd-d36745dceb35">
    <more component markup />
  </div>
</div>

Now I’m sure that there are good reasons for the library doing this, but rest assured, this is something that I DO NOT WANT. I don’t care what the React teams reason is for this extra div, I’m working on a legacy app with enough CSS to fill an encyclopedia and this additional div is breaking styling in a way that simply isn’t fixable. If I’m not able to eliminate it on my own I’ll write a separate script to delete the extra div manually and relocate the enclosed markup but I’d prefer to not have to do all of that. Can anyone tell me how to get rid of this div that I didn’t ask for and need to go away?

Protected Routing not working. Page is not getting displayed

After implementing it my page is not getting displayed. I am beginner in this. So please guide and help me in fixing it.
I want my every page to display login page till user login it and id,password get stored in local storage.
Everything was working fine but when i implemented protected route the page became blank.

App.js

import React from 'react';
import './App.css';
import {
BrowserRouter as Router,
Routes,
Route
} from 'react-router-dom'
import Home from "./components/Home"

import RestaurantSearch from "./components/RestaurantSearch"
import RestaurantCreate from "./components/RestaurantCreate"
import RestaurantList from "./components/RestaurantList"
import RestaurantUpdate from "./components/RestaurantUpdate"
import Login from "./components/Login"
import Logout from "./components/Logout"
import Protected from "./components/Protected"

function App() {
  return (
    <div className="App">
  <Router>
    <Routes>
      <Route path="/list" element={<RestaurantList />} />
      <Route path="/create" element={<RestaurantCreate />} />
      <Route path="/search" element={<RestaurantSearch />} />
      <Route path="/update/:id" element={<RestaurantUpdate />} />
      <Route path="/login" element={<Login />} />
      <Route path="/logout" element={<Logout />} />
      <Protected exact path="/" element={<Home />} />

    </Routes>
  </Router>
</div >
);
}

export default App;

Protected.js

import React from 'react';
import { Navigate, Route } from 'react-router-dom'

const Protected = ({ component: Cmp, ...rest }) => (
<Route
    {...rest}
    render={(props) =>
        localStorage.getItem('login') ? (
            <Cmp {...props} />
        ) :
            <Navigate
                to={{ pathname: "/login", state: { from: props.location } }}

            />
    }
/>


)

export default Protected;

How to split a string with multiple regex?

How can we split a string with multiple regexes? For example, I have this string:

String multipleSentences = "Hi! How are you? I am fine."; // java
val multipleSentences = "Hi! How are you? I am fine." //kotlin
var multipleSentences = "Hi! How are you? I am fine."; // javascript

Now, what I want is that I want to split it sentence by sentence. Where a sentence can have multiple endings like this:

  1. .
  2. ?
  3. !
    , etc

And, the output comes:

["Hi!", "How are you?", "I am fine."]

So, how can I achieve this in or or .


The question could have been more specific if the question was like this:

How to split sentences ?

but this seemed better as this is in common.

returning the htmlcontent of a fetch response into a variable [duplicate]

I have a function that returns a response with ‘htmlcontent’. If I run the code in console I get the expected result but the second it is wrapped in a function it returns ‘undefined’

The code is as follows

function func() {
var fn;
fn = fetch(url).then(result => result.json()).then(data => fn = data['htmlcontent']);

return fn;
}

I was hoping someone that knows more js than me would be able to spot my issue. If I think run

var x = func()

I get undefined. The url is defined elsewhere in the code.

error Cannot read properties of undefined (reading ‘indexOf’)

I have an array named : board_3x3_squars
it has 9 rows with numbers 1 to 9 in each row

I want to create a new array with the values of the index of a random value (1 to 9) in each of the rows in array board_3x3_squars.
so for example if value 5 is in index 2 of row 0 in board_3x3_squars
I want the new array for value 5 to be like:
new array = [2]

the for loop is giving me the following error: “Cannot read properties of undefined (reading ‘indexOf’)”

and I don’t know how to solve it.
Code:

    for (let i = 0; i <= board_3x3_squars.length; i++) {
  let valIndex = [];
  let val = [];
  val = board_3x3_squars[i].indexOf(randmNum());
  valIndex.push(val);
}

This is the randNum funbction:

let numPick;
const chosenNumPick = [];

function randmNum() {
  let min = Math.ceil(1);
  let max = Math.floor(9);
  numPick = Math.floor(Math.random(1, 9) * (max - min + 1) + min);
  if (chosenNumPick.includes(numPick)) {
    randmNum();
  } else if (chosenNumPick.lenth < 9) {
    chosenNumPick.push(numPick);      }
  return numPick;
}

Chrome Extension: uncaught SyntaxError: Unexpected token ‘export’

When trying to export a value from “content.js” into my “popup-sign-in-script.js”, I get this error:

Uncaught SyntaxError: Unexpected token 'export'

My content.js:

[Some Code]
export const userubi = userubi;

My popup-sign-in-script.js:

import {userubi} from './content.js';
[Some code]

The HTML file of popup-sign-in-script.js (popup-sign-in.html):

<script type="module" src="./popup-sign-in-script.js"></script>
<script type="module" src="./content.js"></script>