Convert selected layers into smart objects via script in photoshop

I have created the following Photoshop script designed to convert selected layers into smart objects:

// Function to convert selected layers to smart objects
function convertToSmartObject() {
    var doc = app.activeDocument;
    var selectedLayers = getSelectedLayers(doc);

    // Iterate through selected layers
    for (var i = 0; i < selectedLayers.length; i++) {
        var layer = selectedLayers[i];
        // Convert the layer to a smart object
        convertLayerToSmartObject(doc, layer);
    }
}

// Function to get selected layers
function getSelectedLayers(doc) {
    var selectedLayers = [];
    var layers = doc.layers;
    for (var i = 0; i < layers.length; i++) {
        var layer = layers[i];
        if (layer.selected) {
            selectedLayers.push(layer);
        }
    }
    return selectedLayers;
}

// Function to convert a layer to a smart object
function convertLayerToSmartObject(doc, layer) {
    doc.activeLayer = layer;
    createSmartObject();
}

// Function to create a smart object
function createSmartObject() {
    var idnewPlacedLayer = stringIDToTypeID('newPlacedLayer');
    executeAction(idnewPlacedLayer, undefined, DialogModes.NO);
}

// Call the function to convert selected layers to smart objects
convertToSmartObject();

Why isn’t this script functioning properly? What might be the issue with my script?

Get remote MKV file metadata using nodejs

I need to extract the softsubs embeded into an mkv file hosted on a remote server using nodejs.

All of the solutions I’ve found online so far are using local files, and others are either poorly documented or throwing unknown errors that I can’t find online; That doesn’t work for me. I need to extract subtitles from the remote file (like http://some-url.com/videos/video.mkv) without downloading the entire file to use it in my web-based application.

How to save downloaded by parser file into js buffer?

I have a parser written on puppeteer, where i download a file, so how to use this downloaded file in js code?

(async () => {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: false,
args: ['--start-maximized']
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto('');
await page.type('#username', '');
await page.type('#password', '');
await page.click('#loginbtn');
await page.click('.aalink.stretched-link');
setTimeout(async () => {
await browser.close();
3000);
})();

Please help me

Vue3 Suspense Parent > Child Animation

I would like to leverage Vue3 Suspense to initiate a loading state at the parent level that triggers animations in the children. When the request resolves at the parent level, I would like to remove the animation from the children.

App Header:

router-view(v-slot="{ Component, route }")
  template(v-if="Component")
    transition(:name="route.meta.transition" appear)
      KeepAlive
        Suspense
          component(:is="Component")
          template(#fallback='')
            div.loading-div LOADING !! 

Parent Template:

<template lang="pug">
section.discover-row
  div.discover-row-carousel
    DiscoverItem(
      v-for="(item, index) in DiscoverItemStore.automobiles"
      :key="item._id" 
      :item="item"
      :index="index"
    )
</template>

<script setup>
...
import { useDiscoverItemStore } from "@/stores/DiscoverItemStore"
const DiscoverItemStore = useDiscoverItemStore()
DiscoverItemStore.fetchItems()
</script>

Child Template:

Suspense
  template(#default='')
    div.item SHOW SOME STUFF
  template(#fallback='')
    div.loading-div CHILD LOADING !!

Request (from pinia store):

    async fetchItems() {
      this.automobiles = []
      this.items = []
      this.loading = true
      try {
        
        this.items = await fetch(discoverUrl)
          .then((response) => response.json()) 
        
        this.automobiles = [...this.items.Cars, ...this.items.Suvs, ...this.items.Trucks, ...this.items.Vans]
        this.loading = false
     ...

————————————————————

How can I trigger the loading state at the parent level then show CHILD LOADING !! on each child instance until the request to fetchItems() at the parent level is resolved?

Here’s a codesandbox that approximates the problem (see “home” tab).

How to display legend box in tooltip text for amCharts 5 in Rails application?

I’m working on a Rails application where I’m using amCharts 5 to create charts. I have a requirement to display the legend name along with its corresponding color in the tooltip text for each series in the chart. I’ve tried several approaches, including customizing the tooltip function, but I’m encountering difficulties in achieving the desired result.

enter image description here

` series.columns.template.set("tooltipHTML", am5.Tooltip.new(root, {
        tooltipHTML: function(dataItem) {
            var seriesName = dataItem.series.name;
            var color = dataItem.series.fill.hex;
            var valueX = dataItem.categoryX;
            var valueY = dataItem.valueY;
            var seriesColorBox = '<span style="display:inline-block; width:12px; height:12px; background-color:' + color + '; margin-right: 5px;"></span>';
            return valueX + ', Number of appointments<br>' +
                'Total: ' + valueY + '<br>' +
                seriesColorBox +
                '<span style="color: black;">' + seriesName + ': ' + valueY + '</span><br>';
        }
    }));`

Despite trying this approach and others, I’m not achieving the desired outcome. The tooltip text is not displaying the legend name and color correctly.

Any insights or suggestions on how to resolve this issue and correctly display the legend colors in the tooltip text would be greatly appreciated!

regex working not as expected javascript, displays wrong values [closed]

i have string "This auction will run from Friday 28 July - Monday 7 August. It will close from 7pm (GMT) on Monday 7 August 2023. Read here for information on how our auctions end."

and im trying to get dates from this string

const str = "This auction will run from Friday 28 July - Monday 7 August. It will close from 7pm (GMT) on Monday 7 August 2023. Read here for information on how our auctions end.";
const regex = /(d{1,2} w+(?: d{4})?)/g;
const dates = str.match(regex);
console.dir(dates);

this is regex that i wrote and in regex checker site((d{1,2} w+(?: d{4})?)) it matches for 28 july, 7 august and 7 august 2023, but in javascript it only matches for 7 august and 7 august 2023, whats wrong?

KeyboardAvoidingView makes a messy the flexbox

I have the following code:

  return (
<KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled>
  <View style={style.flex1}>
    <View style={style.imageContainer}>
      <Image
        style={style.image}
        source={require("../../assets/pictures/LoginBackground.png")}
        resizeMode="cover"
      />
      <View style={style.blackOpacity} />
    </View>
    <View style={style.contentContainer}>
      <View style={style.flex1}>
        <Text style={style.welcomeHeader}>{Strings.Welcome}</Text>
      </View>
      <View style={style.fieldsContainer}>
        <LoginInput
          placeholder={Strings.MailPlaceholder}
          keyboardType={"email-address"}
          onChangeText={setEmail}
          styles={style.itemContainer}
        />
        <LoginInput
          placeholder={Strings.PasswordPlaceholder}
          secureTextEntry={true}
          onChangeText={setPassword}
          styles={style.itemContainer}
        />

        <TouchableOpacity
          disabled={isLoginFormEmpty()}
          style={
            isLoginFormEmpty()
              ? [style.loginBtn, style.itemContainer, style.disabled]
              : [style.loginBtn, style.itemContainer]
          }
          onPress={() => submitLogin()}
        >
          <Text style={style.loginBtnText}>{Strings.LoginBtn}</Text>
        </TouchableOpacity>
      </View>
    </View>
  </View>
</KeyboardAvoidingView>

With the following style:

const style = StyleSheet.create({
  flex1: {
    flex: 1,
  },
  imageContainer: {
    flex: 1,
  },
  image: {
    width: "100%",
    height: "100%",
  },
  blackOpacity: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: "black",
    opacity: 0.6,
  },
  contentContainer: {
    flex: 2,
    backgroundColor: Colors.opacityBlack,
    alignItems: "center",
  },
  welcomeHeader: {
    fontFamily: getFontFamily("Heebo", "600"),
    textAlign: "right",
    fontSize: scaleFontSize(40),
    marginTop: verticalScale(10),
    color: Colors.white,
  },
  fieldsContainer: {
    flex: 5,
    alignItems: "center",
    flexDirection: "column",
    justifyContent: "space-between",
  },
  loginBtn: {
    justifyContent: "center",
    backgroundColor: Colors.submitPurple,
    marginBottom: verticalScale(120),
  },
  disabled: {
    opacity: 0.5,
  },
  loginBtnText: {
    fontFamily: getFontFamily("Heebo", "500"),
    fontSize: scaleFontSize(20),
    textAlign: "center",
    color: Colors.black,
  },
  itemContainer: {
    width: horizontalScale(250),
    height: verticalScale(40),
    borderRadius: horizontalScale(20),
  },
});

When the keyboard is closed, everything looks ok:
without keyboard

But when I open the keyboard, it makes all the inputs closer and doesn’t keep the spaces between each element:

enter image description here

How do I keep the space between the elements even when the keyboard is open?

I tried to change the behavior to position or put the KeyboardAvoidingView inside the main View but it doesn’t work.

Typescript: returnType based on value ‘single’ prop

I’m going to try to explain this as best as I can with a simplified version of my function:

I have this function where I fetch data from a third-party API. Based on the ‘single’ prop the returned value will either be an a single table object or an array of table objects.

I put a generic value on table prop and single prop. But it seems like this doesn’t work with how the function is set up at the moment. My goal is to explain that when single is true, it will just return an object of a table and when single is false it will be an array of table objects. What should be changed?

function useData<T extends TableNames, S extends boolean>({
  query: { table, select = [], filters = [], single = false, limit },
}: UseDataProps<T, S>): UseDataReturn<T, S> {
  const { data } = getData();

  return {
    data: data[table],
  };
}

interface UseDataProps<T, S> {
  query: {
    table: T;
    select?: string[];
    filters?:string[];
    single?: S;
    limit?: number;
  };
}

interface UseDataReturn<T, S> {
  data: S extends true ? Table<T> : Table<T>[];
}

On the single prop I currently get an error like this:

Type ‘boolean’ is not assignable to type ‘S’.
‘boolean’ is assignable to the constraint of type ‘S’, but ‘S’ could be instantiated with a different subtype of constraint ‘boolean’.

Js variable to php using a

I’m trying to send string of 13 ascii characters from js to php session using ajax, but up on receving string is not the same as i send it, using json.stringyfy and jsondecode does nothing.


    console.log(plik_T[click])
    jQuery.ajax({
        type: "POST",
        url: './Setyb.php',
        dataType: 'text',
        data: {send: plik_T[click]},
        success: function (obj) {
           console.log(obj)
        }
        
    });
<?php
    var_dump($_POST['send']);
?>

console output

i tried using json.stringify or changing meta UTF-8 to older versions non of this resolved my problem. Then i tried checking type of variables witch both were string, so that lead my to nothing. what i’m trying to accomplish is to set my Session variable up on user click and use it in next php page

The rules of Conway’s Game of Life aren’t working in my Javascript version. What am I doing wrong?

I’m working on some code for a javascript implemenation of Conway’s Game of Life Cellular Automata for a personal project, and I’ve reached the point of encoding the rules. I am applying the rules to each cell, then storing the new version in a copy of the grid. Then, when I’m finished calculating each cell’s next state, I set the first grid’s state to the second’s one, empty the second grid, and start over. Here’s the code I used for the rules:

if (Cell(i, j) == 1) {
    if (Nsum(i, j) == 2 || Nsum(i, j) == 3) ncells[j][i] = 1;
    else ncells[j][i] = 0;
}
else {
    if (Nsum(i, j) == 3) ncells[j][i] = 1;
    else ncells[j][i] = 0;
}

Nsum is the function that calculates the neighborhood sum of the current cell. I say ncells[j][i] instead of ncells[i][j] because in a 2d array you adress the row first.

I didn’t try much, but I can’t imagine a solution. Help!

Rotate an object around another object in javascript

I’m having problem with a project of mine, I want to rotate an planet on it’s orbit around the sun to a certain degree that comes from an equation. I’m looking for a way to rotate a planet withount a need of doing 360 classes in CSS just to change them everytime. That degree is calculated from latitude and the angle of the planet’s inclination, here’s my code so far

function gorowanie(){
    var wysokosc=document.getElementById("licz1").value;
    var nachylenie=document.getElementById("licz2").value;
    var polkola=document.getElementById("lista").value;
    var wynik=0;
    if(polkola=="1"){wynik=90-Number(wysokosc)+Number(nachylenie);}
    else if(polkola=="2"){wynik=90+Number(wysokosc)+Number(nachylenie);}
    else{wynik=90;}
    document.getElementById("linia").style.transform="rotate("+(Number(wynik)-90)+"deg)";
    document.getElementById("wynik").innerHTML=wynik+"°";
}

If it helps I’ll throw a photo of the project here
(https://i.stack.imgur.com/puLKU.png)

I was looking for something that can help me with that but sadly I just can’t find anything that could help me, I was trying to use translate somehow but I just can’t seem to get a good outcome.
I would be thankfull if someone gave me an idea how to do it.

How to make promises execute in order?

let promise = ''

function A() {
  return new Promise((resolve) => {
    resolve(promise)
  })
}

function callbackA(res) {
  console.log("callbackA:", res)
  
  return new Promise(resolve => {
    promise = 'A'
    resolve()
  })
}

function B() {
  return new Promise((resolve) => {
    resolve(promise)
  })
}

function callbackB(res) {
  console.log("callbackB:", res)
}

function C() {
  promise = 'C'
  return promise
}

function callbackC(res) {
  console.log("callbackC:", res)
}

function promiseThen(maybePromise, callback) {
}

promiseThen(A, callbackA)
promiseThen(B, callbackB)
promiseThen(C, callbackC)

The function promiseThen accepts two parameters: maybePromise, which may be a promise or a regular function, and callback, which receives their results to operate on them.

I want the promise to be executed first, completing all of its then functions, and then proceed to the next promise. So the result of the above code should be:

callbackC: C
callbackA: C
callbackB: A

Just like restoring the execution order of promises to that of regular functions.

Update Sidebar Height to Cover the Document Height (with React Pro Sidebar)

I’m using Next.js with React Pro Sidebar, but this seems to be a problem related to JS, HTML, and CSS. Anyways, I’ve tried a lot of “solutions” on a lot of questions here on SO, but none of them worked, and I’m surprised this isn’t covered inside of React Pro Sidebar itself.

Anytime I route to a page with bigger height, I get something like this:

Cut through Sidebar

That’s because I haven’t been able to update the height of the sidebar to the height of the whole document. The height of the document is another problem, because I haven’t been able to find a way of tracking it through events, e.g. resize. The full height of the document seems to be tracked by document.body.scrollHeight.

I’ve tried to create a useEffect for document.body.scrollHeight, but it doesn’t seem to be enough (in Next.js, you might need to create a dynamic component with no SSR, like this):

const [viewHeight, setViewHeight] = useState<string | number>("100vh")

useEffect(() => {
  setViewHeight(document.body.scrollHeight)
}, [document.body.scrollHeight])

...

<ProSidebar style={{ height: viewHeight }}>

...

I’ve also tried to create a ResizeObserver but it didn’t work either:

useEffect(() => {
  const observer = new ResizeObserver(() => {
    setViewHeight(document.body.scrollHeight)
  })
  observer.observe(document.body)
}, [])

And, specifically for React Pro Sidebar, I’ve also tried this solution from an issue created by one of its contributors:

<Sidebar
  defaultCollapsed={isCollapsed}
  rootStyles={{
    [`.${sidebarClasses.container}`]: {
      backgroundColor: "#ffffff",
      height: "100vh !important",
    },
    [`.${sidebarClasses.root}`]: {},
  }}
>

Does anyone know of a specific, or, better yet, general solution to updating the sidebar height in JS (or React)?

Display Ring on Divi slider module

As Divi doesn’t allow modules to be displayed using Divi slider, i tried to come with a workaround.
My only issue is that my ring drawing animation doesn’t work in the first time the slide is loaded and only fire once and not every time the slide is changed.

Here’s the code I came up with:


    $( document ).ready(function() {
            var defaultSlide = document.querySelector('.et_pb_slide_0');
            var defaultCanvas = defaultSlide.querySelector('#ringCanvas'); //pass it as a class
            var dafaultCtx = defaultCanvas.getContext('2d');
            var defaultCanvasCleared = false;
        
            //init values
            var counter = 1;
            var endCount = defaultCanvas.getAttribute("number");
            var goal = defaultCanvas.getAttribute("goal"); // Your goal count
            var interval = 20; // milliseconds
            var ringColor = defaultCanvas.getAttribute("bar_color"); // Default ring color
            var textColor = defaultCanvas.getAttribute("number_color"); // Default text color
            drawRing(dafaultCtx); // Start drawing the ring in the initial container

            var targetNodes = document.querySelectorAll('.et_pb_slide');
            var classNameToCatch = 'et-pb-active-slide';
            var config = { attributes: true, attributeFilter: ['class'], attributeOldValue : true };
            var callback = function(mutationsList, observer) {
                var targetWithClassAdded;
                var targetWithClassRemoved;

                mutationsList.forEach(function(mutation) {
                    if (mutation.type === 'attributes' && mutation.attributeName === 'class'){
                        var currentClassList = mutation.target.classList;
                        var oldValue = mutation.oldValue || '';
                        var classAdded = currentClassList.contains(classNameToCatch);
                        var classRemoved = !currentClassList.contains(classNameToCatch) && oldValue.includes(classNameToCatch);

                        if(classAdded){
                            targetWithClassAdded = mutation.target;
                        }
                        if(classRemoved){
                            targetWithClassRemoved = mutation.target;
                        }
                        
                        targetWithClassAdded != null && workOnClassAdd(targetWithClassAdded);
                        targetWithClassRemoved != null && workOnClassRemoval(targetWithClassRemoved);
                    }
                });
                    
            };

            // Create an observer instance linked to the callback function
            var observer = new MutationObserver(callback);

            // Start observing each target node for configured mutations
            targetNodes.forEach(function(targetNode) {
                observer.observe(targetNode, config);
            });

            function workOnClassAdd(target) {
                var currentCanvas = target.querySelector("#ringCanvas")
                // Check if default canvas has been cleared before
                if(!defaultCanvasCleared) {
                    clearCanvas(defaultCanvas);
                    defaultCanvasCleared = true;
                }
                
                displayRing(currentCanvas)
            }

            function workOnClassRemoval(target) {
                var currentCanvas= target.querySelector("#ringCanvas")
                //currentCanvasId = document.getElementById(target.id).children[0].id;
                clearCanvas(currentCanvas);
            }

            function displayRing(canvas) {
                var ctx = canvas.getContext('2d');
                endCount = canvas.getAttribute("number");
                goal = canvas.getAttribute("goal");
                ringColor = canvas.getAttribute("bar_color");
                textColor = canvas.getAttribute("number_color");
                counter = 1; // Reset counter
                drawRing(ctx);
            }

            function clearCanvas(canvas) {
                var ctx = canvas.getContext('2d');
                counter = 1; // Reset counter
                ctx.clearRect(0, 0, canvas.width, canvas.height);
            }

            function drawRing(ctx) {
                var x = ctx.canvas.width / 2;
                var y = ctx.canvas.height / 2;
                var radius = 70;

                ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

                // Calculate percentage
                var percentage = (counter / goal) * 100;

                // Draw ring
                ctx.beginPath();
                ctx.arc(x, y, radius, -Math.PI / 2, (2 * Math.PI * (percentage / 100)) - (Math.PI / 2));
                ctx.strokeStyle = ringColor;
                ctx.lineWidth = 20;
                ctx.lineCap = "round";
                ctx.stroke();

                // Draw counter
                ctx.font = '20px Montserrat';
                ctx.textAlign = 'center';
                ctx.fillStyle = textColor;
                ctx.fillText(counter + '€', x, y + 7); // Add the € symbol after the counter text

                // Update counter
                counter++;

                // Check if reached the end count
                if (counter <= endCount) {
                    // Continue counting
                    setTimeout(function() {
                        drawRing(ctx);
                    }, interval);
                }
            }

        });

Want i’m trying to achieve is to have the ring animation on page load and every time the slide is changed.
For additional info : Divi handles slide changing with a class “et-pb-active-slide”.

If anyones has some tip I’m grateful.