Improvements for rotation matrix

I made a rotation matrix that seems to work fine, but I want to know if ther is any way I can improve it.

function rotate3(pos, xr, yr, zr) { //pos is an array: [x, y, z]
    
    let sinX = Math.sin(xr * rad); 
    let cosX = Math.cos(xr * rad);
    let sinY = Math.sin(yr * rad); // rad = pi / 180 to convert degrees to radians
    let cosY = Math.cos(yr * rad);
    let sinZ = Math.sin(zr * rad);
    let cosZ = Math.cos(zr * rad);
    
    let x = pos[0];
    let y = pos[1];
    let z = pos[2];
    
    // rotate around X
    let xm = [0, (z * sinX + y * cosX), (z * cosX - y * sinX)];
    // rotate around X
    let ym = [(xm[2] * sinY + x * cosY), xm[1], (xm[2] * cosY - x * sinY)];
    // rotate around Z
    let zm = [(ym[1] * sinZ + ym[0] * cosZ), (ym[1] * cosZ - ym[0] * sinZ), ym[2]];
    
    return zm; // returns [x, y, z]
    
}

Im posting this for any way I could improve this, but I was struggling to find a 3d rotation matrix that I could understand and figure out how to use, so I figured this could help someone.

BUG: “Error: 413 The data value transmitted exceeds the capacity limit.” when calling v1/images/edits

I’m trying to send an image from my Firebase Storage bucket to openai edit image API, but I’m getting the error above on the title.

exports.sendToOpenAI = functions.https.onRequest(async (req, res) => {
    corsMiddleware(req, res, async () => {
        if (req.method !== "POST") {
            return res.status(405).end();
        }

        try {
            const relativePath = req.body.path;
            const bucket = admin.storage().bucket();

            const file = bucket.file(relativePath);
            const fileBuffer = await file.download();

            const openAIResponse = await openai.images.edit({
                image: fileBuffer[0],
                prompt: "Put a suit on that person",
                size: "256x256",
            });

            return res
                .status(200)
                .json({ success: true, response: openAIResponse.data });
        } catch (error) {
            console.error("Error sending image to OpenAI:", error);
            return res.status(500).json({
                success: false,
                error: "Internal Server Error sending image to OpenAI",
            });
        }
    });
});

The “fileBuffer” has a length of 0.1MB and according to the API docs the image must have less than 4MB.

I tried to pass other small images too, but had no success.

I gave permissions on Firebase to anyone writes and reads the storage.

I don’t know why I’m getting this error. Has anyone had the same problem?

Time series with multiple range selectors

I need UI interface which will allow to select ranges of audio record and assign labels to them.

prodi.gy

Please, advice me JS libraries with such functionality.

I know that there is d3.js, but I want out of the box functionality without poking around too much.

Fetching related data via an API and rendering it in components via Next.js

I am dealing with Notion’s API to fetch a list of Places and their related City and then rendering this data via some components. I am fairly new to the JS world (2023 edition) so I’m having some trouble figuring out what’s the best way to organise this.

This is what I was thinking about:

  • /lib/api.js where I fetch data from Notion’s API via their SDK; since the returned data is in a fairly custom format, I map each property that I’m interested in and return a very simplified object. Fetching nested data (a City for every Place) also happens here. In summary, the functions in this file should return what Notion would if it offered a GraphQL API;
  • /pages/[placeId].js where I call the relevant functions in the file above in a getStaticProps and call relevant components from the page itself;
  • /components/text.js where I manipulate the data in a more composable way and render it

This all makes sense until I figure some Notion responses include render information:

{
  "type": "text",
  "text": {
    "content": "This is an ",
    "link": null
  },
  "annotations": {
    "bold": false,
    "italic": false,
    "strikethrough": false,
    "underline": false,
    "code": false,
    "color": "default"
  },
  "plain_text": "This is an ",
  "href": null
}

In this case, it would be strange parsing this and generating the respective HTML inside /lib/api.js. If, on the other hand, I simply return Notion’s response in /lib/api.js, I would have to parse properties and request nested information from components, which also doesn’t look too nice.

How would one tackle this in a clean, JS-worthy way? I can provide more details if it helps, I tried being as short as possible.

Maintaining order with Stylelint v15.11.0

My team’s React project has been configured as follows wrt stylelint :

"stylelint": "^13.12.0",
"stylelint-config-prettier": "^8.0.2",
"stylelint-config-recommended": "^4.0.0",
"stylelint-config-sass-guidelines": "^7.1.0"

In .stylelintrc.json are these key parts:

"extends": [
  "stylelint-config-recommended",
  "stylelint-config-sass-guidelines",
  "stylelint-config-prettier"
],
"rules": {
  "order/order": null,
  "order/properties-alphabetical-order": null,

A message appeared that suggested we should upgrade to v15.11.0. I did so. I then uninstalled stylelint-config-recommended and stylelint-config-prettier because they were deprecated with this newer version of stylelint.

But then those 2 rules shown above appeared with errors about them being “Unknown rules”.

We absolutely do want to maintain the order that Stylelint has enforced. I’m not sure what to do to fix this. Any ideas?

Robert

Replace text between two tags within html string – Javascript RegEx?

I have a string containing html that is outputted from Wix Studio. I am trying to manipulate and put back within the original tags. So far I have managed to strip the tags and manipulate the string (wrapping each letter in a ), but I can’t figure out how to put the manipulated string (inner) back within the original tags, desired outcome below. Won’t always be <h1>, could be <h2> through to <h6>, potentially a <p> – Unable to use jQuery!

// Get string from Wix using the Wix Editor Elements ($w) APIs)
var html = $w('Text').html;

var string = html.replace(/(<([^>]+)>)/ig, ''), 
    wrap = string.replace(/w/g, "<span>$&</span>");

html returns "<h1 class="wixui-rich-text__text">Add a Title</h1>" ✅ All good

string returns "Add a Title" ✅ All good

wrap returns "<span>A</span><span>d</span><span>d</span> <span>a</span> <span>T</span><span>i</span><span>t</span><span>l</span><span>e</span>" ✅ All good

Desired result:

The original html tag with the modified content within:

output to return "<h1 class="wixui-rich-text__text"><span>A</span><span>d</span><span>d</span> <span>a</span> <span>T</span><span>i</span><span>t</span><span>l</span><span>e</span></h1>"

A bit out of my depth, may be a better way to go about.

Many thanks!

For ref: https://www.wix.com/velo/reference/$w/text/html

How to download base64 pdf files from website on iOS

I’m struggling with this issue that I can download documents on chrome but not on iOS devices

Whenever I try, I get “Not allowed to navigate top frame to data URL” error.

Is there a way to do this with JS?

Extra question:

Is getting base64 encoded pdf to client and then downloading is a good solution or do you have any other suggestions? Please bear in mind that there are a lot of documents so adding every doc to assets is not possible.

I tried the code below and it worked on desktop devices but not on iOS.

        const a = document.createElement("a");
        a.href = "data:application/pdf;base64,BASE_64_PDF";
        a.download = "file.pdf";
        a.click();

Is It Possible to Use Any Child React Element inside RouterProvider?

I’ve successfully created several route configurations using React Router 6, and they are working as expected. Additionally, I’ve developed an AxiosInterceptor component to handle HTTP requests and responses. However, I’m encountering an issue when trying to use the AxiosInterceptor component within my application because it relies on the useNavigate hook, requiring it to be placed inside the BrowserRouter.

Here’s an example of my route configurations

AuthRoute.tsx

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

const AuthRoutes: RouteObject[] = [
    {
        path: '/',
        element: <Navigate to="/sign-in" />
    },
    {
        path: 'sign-in',
        async lazy() {
            const { SignIn } = await import('@/modules/auth');
            return { Component: SignIn };
        }
    },
    {
        path: 'forget-password',
        async lazy() {
            const { ForgetPassword } = await import('@/modules/auth');
            return { Component: ForgetPassword };
        }
    },
    {
        path: 'reset-password',
        async lazy() {
            const { ResetPassword } = await import('@/modules/auth');
            return { Component: ResetPassword };
        }
    }
];

export default AuthRoutes;

AppRoutes.tsx

const AppRoutes: RouteObject[] = [
    {
        path: '',
        element: <AuthLayout />,
        children: [...AuthRoutes]
    },
    {
        path: '',
        element: <AdminLayout />,
        children: [
            {
                path: 'dashboard',
                children: DashboardRoutes
            }
        ]
    }
];

export default AppRoutes;

App.tsx

function App() {
    return (
        <>
            <AuthContextProvider>
                {/* <AxiosInterceptor> */}
                <RouterProvider router={createBrowserRouter(AppRoutes)} />

                {/* </AxiosInterceptor> */}
            </AuthContextProvider>
        </>
    );
}

export default App;

I want to filter LoadData data by an ID (IdFase)

I have a Datatable Ajax, but I want to filter the data by an ID, currently I am trying a .Where(a => a.IdFase == id) but it is not working, my LoadData is being loaded in my controller Index.

    public IActionResult LoadData(int id)
    {
        // Filtra las acciones por el id proporcionado
        var acciones = _context.Acciones
            .Where(a => a.IdFase == id)
            .Include(a => a.IdAspectoNavigation)
            .Include(a => a.IdFaseNavigation)
            .Include(a => a.IdUsuarioNavigation)
            
            .ToList();

        var jsonData = acciones.Select(accione => new
        {
            idAccion = accione.IdAccion,
            nombreAccion = accione.NombreAccion,
            idAspectoNavigation = accione.IdAspectoNavigation?.NombreAspecto,
            idFaseNavigation = accione.IdFaseNavigation?.NombreFase,
            idUsuarioNavigation = accione.IdUsuarioNavigation?.IdUsuario,
            fechaInicio = accione.FechaInicio.ToString("yyyy-MM-dd"),
            fechaVencimiento = accione.FechaVencimiento.ToString("yyyy-MM-dd")
        });

        return Json(new { data = jsonData });
    }

}



<script type="text/javascript">
    var js = jQuery.noConflict(true);
    
    js(document).ready(function () {
        js('#accionesTable').DataTable({
            "ajax": {
                "url": '/Acciones/LoadData', // Agrega el id a la URL
                "type": "GET",
                "dataType": "json"
            },
            "columns": [
                {
                    "data": null,
                    "render": function (data, type, row) {
                        var editButton = '<a href="/Acciones/Edit/' + row.idAccion + '" class="btn btn-primary">Editar</a>';
                        var detailsButton = '<a href="/Acciones/Details/' + row.idAccion + '" class="btn btn-info">Detalles</a>';
                        var deleteButton = '<a href="/Acciones/Delete/' + row.idAccion + '" class="btn btn-danger">Eliminar</a>';
                        return editButton + " | " + detailsButton + " | " + deleteButton;
                    }
                },
                { "data": "nombreAccion" },
                { "data": "idAspectoNavigation" },
                { "data": "idFaseNavigation" },
                { "data": "idUsuarioNavigation" },
                { "data": "fechaInicio" },
                { "data": "fechaVencimiento" }
            ]
        });
    });
</script>

I want the data to be filtered. For example, to show the data that is only from the IdFase depending on the id of the url.

Hot solve the error: Uncaught Error: Expected an order id to be passed on paypal createOrder

I am using paypal sdk to integrate payment with paypal to my application, the createOrder request should be handled by a spring boot application, but now when the user clicks on paypal button the popup to insert the user email does not show up, instead I get the error:

Uncaught Error: Expected an order id to be passed
at https://www.sandbox.paypal.com/smart/buttons?

Here is the javascript code:

createOrder(data, actions, cartInfo) {
        console.log('CREATE ORDER DATA: ', data);
        console.log('CREATE ORDER ACTIONS: ', actions);
        console.log('CREATE ORDER CARTINFO: ', cartInfo);
        const totalAmount = cartInfo.total;

        // Order is created on the server and the order id is returned
        return fetch("http://127.0.0.1:8102/paypal/create-order", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            // use the "body" param to optionally pass additional order information
            // like product skus and quantities
            body: JSON.stringify({
                intent: "SALE",
                purchase_units: [
                    {
                        items: cartInfo.items,
                        amount: {
                            currency_code: 'CAD',
                            value: {totalAmount},
                        },
                    },
                ],
            }),
        })
        .then((response) => response.json()).catch(error => {
            console.log('ERROR: ', error);
        })
        .then((order) => order.id);
    }

anf the JAVA code:

 @PostMapping(value = "/create-order",  produces = MediaType.APPLICATION_JSON_VALUE)
    public String createOrder(HttpServletRequest request, @RequestBody String order) {
        STRING orderId = "1";

    return orderId;
}

I do not know what to do in the createOrder java method to return a satisfying response to the font end.
Any help or documentation would be appreciated.

jQuery is not defined, even thought it clearly is

Here is the error message from the browser console:

Uncaught ReferenceError: jQuery is not defined
at code.js:6:1

I just have a simple function utilizing jQuery, which I have put into the document.ready block, to ensure jQuery will load first.

jQuery(document).ready(function () {
    function showView(viewName){
        $('.view').hide();
        $('#' + viewName).show();
    }
    console.log('test');
});

Here, console promts that ‘jQuery is not defined’ , even thought it is.

I have seen a similar issue question, but I have checked if:

  1. Other plugins may overwrite the $ tag, they don’t.
  2. jQuery is loaded in the Head tag of the page BEFORE my own script.
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script src="js/code.js"></script>
</head>

I have also noticed that this was once working. Only as I have been adding more stuff to the code.js script, stuff has gone wrong.
Firstly, the $ tag went “undefined” thus I have placed all of these into the document.ready block.
Secondly, the $ tag in the document.ready block went “undefined”.
And lastly, the jQuery class before document.ready went “undefined” as a whole, and now refuses to work.

Here is a Minimal Reproducible Example, hosted on glitch.

https://harmonious-dot-clam.glitch.me/

I dont know if this is helpful, but this is a part of an electron project.

I have no idea what went wrong here, as it initially worked fine. As I said, I checked all the answers that helped others, but none worked. Please try and help, as this is delaying my project and I need help with this.

How to access artboard element in a Photoshop script?

I need to replace text elements in a photoshop template via a script. When it’s a regular file, everything works fine. But if it’s a project where artboards are used, I have no way to select the active layer I want to change. The layer names are fixed and I just want to refer to them by name, but no matter how much I search I can’t find a way.

This is how I access the layers in a normal file:

#target photoshop;

var fileRef = new File("I:/ps15.psd");

if (fileRef.exists) {

    app.open(fileRef); //open file

    activeDocument.activeLayer = activeDocument.artLayers.getByName("layer_1"); //find the layer with the name I want

    activeDocument.activeLayer.textItem.contents = "Hi!"; //text replacement

    app.activeDocument.close(SaveOptions.SAVECHANGES); //close file

} else { alert("File not found"); }

I’ve found functions that determine if a layer is an artboard, but I’ve never been able to figure out how to select the active layer in them.

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop when call the seState

When the try to store is the tableListWinner array into the getWinnerSubTab state using the setGetWinnerSubTab method then i got the error of infinite loop when call the seState. How can i solve this issue. please provide me the solution. i want to store this array into the getWinnerSubTab state here.

Code

import { Box, Grid, makeStyles } from "@material-ui/core";
import React, { useState, useCallback, useEffect } from "react";
import LeaderboardMenu from "./leaderboardMenu";
import LeaderboardSubMenus from "./leaderboardSubMenus";
import LeaderboardWinnersStage from "./leaderboardWinnersStage";
import LeaderboardWinnersTable from "./leaderboardWinnersTable";
import { EVENTS } from "../common/utils/constant";
import { useDispatch, useSelector } from "react-redux";
import {
  selectLeaderboardDetails,
  selectLeaderboardRanks,
} from "./slices/leaderboardSlice";

const useStyles = makeStyles((theme: any) => ({
  rootContainer: {
    width: "100%",
    backgroundColor: "",
    
  },
  screnContainer: {
    ...theme.common.screenContainer,
    padding: "2rem 1rem 1rem 1rem",
    [theme.breakpoints.down("sm")]: {
      backgroundColor: "#0E0E0E",
      padding: "0rem 0rem 0rem",
    },
  },
}));

function Leaderboard() {
  const classes = useStyles();
  const dispatch = useDispatch();
 
  const leaderboardDetails = useSelector(selectLeaderboardDetails);
  const [getWinnerSubTab, setGetWinnerSubTab] = useState([]);
  const [activeView, setActiveView] = useState("table_with_stage"); // table_with_stage || table
  const [activeTab, setActiveTab] = useState(0);
  const [activeSubTab, setActiveSubTab] = useState(0);

  console.log("leaderboardDetails-----------", leaderboardDetails);

  useEffect(() => {
    dispatch({ type: EVENTS.GET_LEADERBOARD, payload: {} });
  }, []);

  useEffect(() => {
    console.log(leaderboardDetails, 5655444444);
    let tabs = getTabList();
    console.log(tabs, 214155785623354);
    if (tabs.length) {
      setActiveTab(tabs[0]?.id);
    }
  }, [leaderboardDetails]);

  useEffect(() => {
    console.log(activeTab, 562144452, "[DIAGNOSE_ACTIVE_TAB_ID] activeTab useEffect",activeTab);
    let tabs = getSubTabList();
    console.log("DIAGNOSE_ACTIVE_TAB_ID tabs", tabs);
    console.log(tabs, 214155785623354);
    if (tabs.length) {
      console.log("DIAGNOSE_ACTIVE_TAB_ID tabslength", "YES");
      setActiveSubTab(tabs[0]?.id);
    }
  }, [activeTab]);

  useEffect(() => {
    console.log("[activeSubTab]", activeSubTab);
    if (activeSubTab) {
      dispatch({
        type: EVENTS.GET_LEADERBOARD_RANK,
        payload: { leader_board_id: activeSubTab },
      });
      // dispatch({
      //   type: EVENTS.GET_LEADERBOARD_WINNER,
      //   payload: { leader_board_id: activeSubTab },
      // });
    }
  }, [activeSubTab]);

  const renderView = useCallback(() => {
    if (activeView === "table_with_stage") {
      return (
        <Grid
          container
          style={{ border: "0.5px solid rgb(214 208 208", borderRadius: "4px" ,marginTop:'2%'}}
        >
          <Grid
            item
            md={6}
            sm={12}
            style={{
              // padding: "2rem",
              border: "0.5px solid rgb(214 208 208",
            }}
          >
            <LeaderboardWinnersStage />
          </Grid>

          <Grid item md={6} sm={12}>
            <LeaderboardWinnersTable />
            {/* <p style={{color:'red'}}>LeaderboardWinnersTable</p> */}
          </Grid>
        </Grid>
      );
    }
    return (
      <Box>
        <LeaderboardWinnersTable />
        <p style={{ color: "blue" }}>LeaderboardWinnersTable</p>
      </Box>
    );
  }, [activeView]);

  const getTabList = () => {
    const leaderboardList = leaderboardDetails?.leaderboards;
    let tabList = [];
    let tableListWinner = [];
    if (leaderboardList?.length) {
      leaderboardList.map((item) => {
        console.log('item-WINNER_DATA',item)
        if (
          !tabList.includes(item?.leaderboard_type) &&
          item?.leaderboard_type !== ""
        ) {
         
          tabList.push(item?.leaderboard_type);
          tableListWinner.push({
            id: item.leaderboard_type,
            appId: item.leaderboard_type,
            label: item.leaderboard_type,
            l_id:item.leaderboard_id
          })
        }
      });
    }
    setGetWinnerSubTab(tableListWinner);
    console.log("DIGNOSE_TABS: tableListWinner", tableListWinner);
   

    let tabListMenus = tabList.map((item) => {
      let icon = "";
      let selectedIcon = "";
      if (item === "Hourly") {
        icon = "hour.svg";
        selectedIcon = "selectedhour.svg";
      } else if (item === "Daily") {
        icon = "daily.svg";
        selectedIcon = "selecteddaily.svg";
      } else if (item === "Weekly") {
        icon = "daily.svg";
        selectedIcon = "selecteddaily.svg";
      } else if (item === "Monthly") {
        icon = "monthly.svg";
        selectedIcon = "selectedmonthly.svg";
      }

      return {
        id: item,
        appId: item,
        label: item,
        icon: icon,
        selectedIcon: selectedIcon,
      };
    });
   
    console.log("tabListMenus-1-1-1-1-1-1", tabListMenus);
    // Add the new object to the tabListMenus
    if (tabListMenus.length > 0) {
      tabListMenus.push({
        id: "Winner",
        appId: "Winner",
        label: "Winner",
        icon: "winner.svg",
        selectedIcon: "selectedwinner.svg",
      });
    }
    console.log("tabListMenus2-2-2-2-2", tabListMenus);
    return tabListMenus;
  };

  const getSubTabList = () => {
    const leaderboardList = leaderboardDetails?.leaderboards;
    console.log(
      "getSubTabList-leaderboardList:",
      JSON.stringify(leaderboardList)
    );
    let tabList = [];
    let tabListMenus: any = [];
    if (leaderboardList?.length) {
      leaderboardList.map((item: any) => {
        if (
          !tabList.includes(item?.leaderboard_title) &&
          item?.leaderboard_title !== "" &&
          item?.leaderboard_type === activeTab
        ) {
          console.log("item?.leaderboard_title tabList", !tabList);
          console.log("item?.leaderboard_title IN IF", item?.leaderboard_title);
          console.log("item?.leaderboard_title IN IF activeTab", activeTab);
          tabList.push(item.leaderboard_title);
          tabListMenus.push({
            id: item.leaderboard_id,
            appId: item.leaderboard_title,
            label: item.leaderboard_title,
          });
        } 
      });
    }
    console.log(tabList, tabListMenus, 268542511);
    // if (tabList.length) setActiveSubTab(tabList[0]);

    // tabList.map((item: any) => {
    //   tabListMenus.push({
    //     id: item,
    //     appId: item,
    //     label: item,
    //   });
    // });
    return tabListMenus;
  };
  console.log("...getSubTabList()", [...getTabList()]);
  return (
    <div className={classes.rootContainer}>
      
      <div className={classes.screnContainer}>
        <LeaderboardMenu
          menus={[...getTabList()]}
          menu={activeTab}
          handleMenuChange={(active) => {
            console.log("DIAGNOSE_ACTIVE_TAB_ID handleMenuChange:", active);
            setActiveTab(active);
          }}
        >
          <LeaderboardSubMenus
            menus={[...getSubTabList()]}
            menu={activeSubTab}
            handleMenuChange={(active) => {
              console.log(active, 69666663355);
              setActiveSubTab(active);
            }}
          >
            {renderView()}
          </LeaderboardSubMenus>
        </LeaderboardMenu>
      </div>
    </div>
  );
}

export default Leaderboard;