Fluent UI style not working in passed commands with buttons to CommandBar

i am using Fluent UI in my project. I dont know how to change hoover style in CommandBar.

I initializing my buttons with this simple code in javascript:

// inside `buttons` array
key: 'newfolder',
text: 'New Folder',
iconProps: { 
    iconName: 'NewFolder',
        styles: {
           root: { 
              color: 'orange' 
           }, 
           rootHovered: { 
              color: 'red' 
           }
    } 
},
onClick: ...

Then i am passing this buttons to CommandBar:

<CommandBar
    items={buttons}
        styles={{
            root: {
                paddingLeft: '5px'
            },
    }}
/>

and i can override default color to asked one.
enter image description here

My question is, how to set mouse hover color over button in CommandBar component? enter image description here

As you can see, it is still blue even if i passed red as rootHovered color

Boolean flickering from true to false

I’m trying to switch the position of an element between fixed and absolute based on how close the element is to the other. So I have a button which is fixed from the top to the bottom till it’s bottom value + 25px is less or equal to footers y value so that it stops to the top. My problem is that the button stops in the right place so the switch from fixed to absolute goes well but while the relative position of the button to the footer are negative the boolean which toggles the classes of the button flickers between true and false so that it goes from absolute to fixed back and forth very quickly.

This is my code that is tracking the position & switching the boolean:

Is there a logic issue or what? I cannot figure this out:(

var button = document.querySelector('.bottomCtaFixed')
            var footer = document.querySelector('.footer')
            window.addEventListener('scroll', (e) => {

                var buttonRect = button.getBoundingClientRect()
                var buttonBottom = buttonRect.bottom + 25

                var footerRect = footer.getBoundingClientRect()
                var footerTop = footerRect.y

                var relativePos = footerTop - buttonBottom
                console.log('button', buttonRect)
                console.log('footer', footerRect)
                console.log('buttonBottom', buttonBottom)
                console.log('relativePos', relativePos)

                if(relativePos <= 0) {
                    this.isStill = true
                    if(footerTop >= buttonBottom) {
                        this.isStill = false
                    } else {
                        this.isStill = true
                    }
                } else {
                    this.isStill = false
                }
                console.log(this.isStill)
            })

And here’s the classes:

.bottomCtaFixed {
        position: fixed;
        bottom: 25px;
        left: 25px;
        margin-top: 25px;
        width: calc(100% - 50px);
        z-index: 101;
        @media screen and (max-width: 290px) {
            display: none
        }
        @media screen and (min-width: $bp-xs) {
            display: none
        }
    }
    .bottomCtaStill {
        position: absolute; 
        top: calc(-9vh - 25px);
        left: 25px;
        width: calc(100% - 50px);
        z-index: 101;
        @media screen and (max-width: 290px) {
            display: none
        }
        @media screen and (min-width: $bp-xs) {
            display: none
        }
    }

Understand the following exercise of js loops and strings in array

I’m trying to make sense of the following javascript exercise but can’t seem to make sense of it, all I know for now is that I can access each string with “acrostic[i]” where the i would be the number in the array but don’t know where to go from there.

const acrostic = [
  "Give me your patience, sister, while I frame",
  "Exact in capitals your golden name;",,
  "Or sue the fair Apollo and he will",
  "Rouse from his heavy slumber and instill",
  "Great love in me for thee and Poesy.",
  "Imagine not that greatest mastery",
  "And kingdom over all the Realms of verse,",
  "Nears more to heaven in aught, than when we nurse",
  "And surety give to love and Brotherhood.",
  " ",
  "Anthropophagi in Othello's mood;",
  "Ulysses storm'd and his enchanted belt",
  "Glow with the Muse, but they are never felt",
  "Unbosom'd so and so eternal made,",
  "Such tender incense in their laurel shade",
  "To all the regent sisters of the Nine",
  "As this poor offering to you, sister mine.",
  " ",
  "Kind sister! aye, this third name says you are;",
  "Enchanted has it been the Lord knows where;",
  "And may it taste to you like good old wine,",
  "Take you to real happiness and give",
  "Sons, daughters and a home like honied hive."
];

/* Declare a variable that will return the final string */
let georgianaAugustaKeats = "acrostic[i][0]";

for (let i = 0; i < acrostic.length; i += 1) {
  /* add each first character of each string to the array
   to the georgianaAugustaKeats variable*/
 
}
console.log(georgianaAugustaKeats);

How to create 500 error with the help of PHP

How to create error with PHP like 500 (Internal server error), 502 (bad gateway) and 521 (Web server is down)

I am not asking how to prevent or custom error page. I want to create issues/error to my server.

What code with PHP or Javascript i can do to bring my website/webserver down.?

Note : I am not attempting hacking to someone. I want to down my own web server temporary for testing and personal work.

Issue related to Js/React arrays

I’m creating an array indexes in which i’m appending values(this will later be used in a map function).

let indexes = [];
export default function SortTiles() {

    let num = info.num_tiles;
    for (let i = 10; i < num+10; i++) {
        indexes = [...indexes, i];
    }
    console.log(indexes);
    console.log("UWU")

    return(
        <div id={"sort-tiles"}>
            {/*{indexes.map(makeTiles)}*/}
        </div>
    )
}

But when i’m trying to console.log my array this is the output i’m getting:
The output image
The output is being printed twice and the numbers in the array is also duplicated.

An error while changing text with javascript

I’m using google recaptcha with my django project. But it is not English. So I want to change its writing with javascript.

html

{% extends 'base.html' %}
{% block content %}
<div class="form-body">
    <div class="row">
        <div class="form-holder">
            <div class="form-content">
                <div class="form-items">
                    <h1>Registration</h1>
                    <br><br>
                    <form class="requires-validation" method="POST" novalidate>

                      {% csrf_token %}
                      {{form.as_p}}
                        <div class="form-button">
                            <button id="submit" type="submit" class="btn btn-primary">Register</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
  document.querySelector('recaptcha-anchor-label').innerHTML = "I'm not a robot";

</script>

{% endblock %}

After I did that it won’t apply the html in browser. Below the error message:

Cannot set properties of null (setting ‘innerHTML’)

Axios POSTing data records to Dynamo, but unable to Axios GET request to find – Javascript/Typescript

I have the following code for POSTing a record via axios to my DB, and then I would like to search for said record by its ID match as well as list all the latest records.

I have confirmed, via checking Dynamo, that the record gets added to the DB but cannot get it to appear when I look for it via the GET /search.

It makes me wonder if I’m somehow making a mistake.

I know that my database has 6000+ records of this same type, so I could just be getting unlucky (as I have not yet included pagination in my queries)… but I’ve tested this about 50 times with 0 retrieval success via the query vs running the same POST and GET via Postman and having about a 50% success rate.

test('post result then search for presence', async () => {
    const trafficAnalyticMessage = buildTrafficAnalyticMessage();

    const result = await axios.post(messagesUrl, trafficAnalyticMessage, {
      headers: {
        'x-api-key': 'redacted',
      },
    });

    const message = result.data as dataMessageApi.Message;
    logger.log(`Message ${util.inspect(message)}`);
    // logger.log(`Result ${util.inspect(result)}`);

    const results = await axios.get(searchUrl, {
      headers: {
        'x-api-key': 'redacted',
      },
      params: {
        type: 'analytic',
        subtype: 'traffic_volumes',
        startTime: 1,
      },
    });

    logger.log(
      'Attempting to search for message with id: ' + JSON.stringify(message.id),
    );

    const messages = results.data as dataMessageApi.Message[];
    const found = messages.find((m) => m.id === message.id);

    logger.log('Message returned from search: ' + JSON.stringify(found));
    // expect(found).toBeDefined();

    let date: string;
    // log length, first and last msg id
    logger.log(`Length of search response:  ${messages.length}`);
    // 1
    logger.log('First ID:  ' + JSON.stringify(messages[0].id));
    date = new Date(messages[0].timestamp!).toUTCString();
    logger.log(`First timestamp: ${date}`);
    // 2
    logger.log('Second ID:  ' + JSON.stringify(messages[1].id));
    date = new Date(messages[1].timestamp!).toUTCString();
    logger.log(`Second timestamp: ${date}`);
    // 3
    logger.log('Third ID:  ' + JSON.stringify(messages[2].id));
    date = new Date(messages[2].timestamp!).toUTCString();
    logger.log(`Third timestamp: ${date}`);
    // 4
    logger.log('Fourth ID:  ' + JSON.stringify(messages[3].id));
    date = new Date(messages[3].timestamp!).toUTCString();
    logger.log(`Fourth timestamp: ${date}`);
    // Fifth from last
    logger.log(
      'Fifth from last ID:  ' +
        JSON.stringify(messages[messages.length - 5].id),
    );
    date = new Date(messages[messages.length - 5].timestamp!).toUTCString();
    logger.log(`Fifth to last timestamp: ${date}`);
    logger.log(
      'Fourth from last ID:  ' +
        JSON.stringify(messages[messages.length - 4].id),
    );
    date = new Date(messages[messages.length - 4].timestamp!).toUTCString();
    logger.log(`Fourth from last timestamp: ${date}`);
    logger.log(
      'Third from last ID:  ' +
        JSON.stringify(messages[messages.length - 3].id),
    );
    date = new Date(messages[messages.length - 3].timestamp!).toUTCString();
    logger.log(`Third from last timestamp: ${date}`);
    logger.log(
      'Second to last ID:  ' + JSON.stringify(messages[messages.length - 2].id),
    );
    date = new Date(messages[messages.length - 2].timestamp!).toUTCString();
    logger.log(`Second to last timestamp: ${date}`);
    logger.log('Last ID:  ' + JSON.stringify(messages[messages.length - 1].id));
    date = new Date(messages[messages.length - 1].timestamp!).toUTCString();
    logger.log(`Last timestamp: ${date}`);

    expect(result).toBeDefined();
    expect(result.status).toBe(201);
  });

This is the output I am getting:

enter image description here

Any help would be greatly appreciated.

**Also, please can you advise me how to add the GET as a .then result of the POST? Or a promise or some kind of 2-part resolution? I have had great trouble figuring out how that works. I’m new to this kind of work.

Thanks so much!!**

what happend re-define setInterval to variable in useEffect hook?

I want to know what happened if I define setInterval function repeatedly to same variable in react hook useEffect.

I checked variable have new setInterval id value every defining.
But I wonder is there instance remained in memory about previous setInterval timer, even if new setInterval defined at same variable??

 useEffect(() => {
    const timer = setInterval(
      () => {
        if (count < elementLength - 1) {
          boolean.current = false;
          setCount(prev => prev + 1);
        } else {
          boolean.current = true;
          setCount(0);
        }
      },
      boolean.current ? 50 : 2500
    );

    return () => {
      clearInterval(timer);
    };
  }, [count]);

The best way to refresh paginated data on the client side?

I have a REST API that implements server-side pagination returning the following data:

{
  items: [
    {
      id: 1,
      name: 1
    },
    {
      id: 2,
      name: 2
    }
  ],
  nextToken: <some-hash-key> // cursor-based
}

How should the client application refresh the list if the resource gets updated (client isn’t aware of the update, so this is a pull model)? I have some ideas:

  1. fetch all resources at a regular interval (like every 10 seconds)
  2. maintain a session ID that rotates every N minutes. When a new session is created, fetch all resources

Both approaches are fundamentally the same idea. The first approach is more costly but allows more real-time updates. The second approach is based on session ID which I think is more idiomatic, but no real-time updates. Is there any other approach?

useState has previous value instead of the current

I’m new to react and I’m trying to understand how it’s working.

I have 2 select inputs and on change event I want to filter the other’s select values based on the first one.

After calling setOptions with the filtered values, they are always one step behind – so I have the previous value each time.

I understand that useState is async and I tried with and useEffect (() => {}, [options])
and I still have the previous values in options.

 const [options, setOptions] = useState<any>()
 const filterOptions = (ids: string[]) => {
        const filteredOptions = list.filter(item=> {
            return list.includes(item.id)
        })
        setOptions(filteredOptions)
    }

Listen/detect the Location URL change in React application

I have a requirement to listen/detect the Location URL change in React application.

I have tried using below code but it changes the location and then gets called.

const location = useLocation();

useEffect(() => {
debugger;
console.log(‘Location changed’);
}, [location]);

Is there a way to listen a URL change before actually changing the location?

Also, Is it possible to find “fromLocation” and “ToLocation”?

I am using “react-router-dom”: “^5.2.0”.

Please help.

Thanks & Regards,
Jyoti

3D Array output in GPU.JS

Hello I’m really new with using GPU.js and I am having trouble understanding createKernel and its output. I want to have a 3D array that stores the outputs from my current function. For example, below, is a gpu matrix multiplication that multiplies matrix a and b, and the result of this function is a 2D array. There are more than one matrix that I want to multiply to a and I want to store all their output in one 3D array.

  const gpu = new GPU();
  const multiplyMatrix = gpu.createKernel(function(a, b) {
    let sum = 0;
    for (let i = 0; i < 10; i++) {
      sum += a[this.thread.y][i] * b[i][this.thread.x];
    }
    return sum;
  }).setOutput([10, 10])

Can anyone please help me. I tried using for loop but it’s so slow and I read because it is expensive to keep using createKernel?

let big3Dmatrix = []
for(let i=0; i<matrices.length; i++){
    big3Dmatrix.push(multiplyMatrix(a,matrices[i]))
}

I would appreciate any help. Thank you!

vue.js ReferenceError (when using resize event)

I’m trying to get the height of the window on resize, but I keep getting the error ReferenceError: calcOfSliderHeight is not defined.

Could anyone let me know what’s going on? Here’s my code

let example = new Vue({
    el: '#example',
    data() {
        return {
            pageIndex: 2,
            posTop: 0,
            posTop2: 0,
        }
    },
    methods: {
        calcOfSliderHeight() {
            let _this = this;
            _this.posTop = (_this.pageIndex - 1) * window.innerHeight
        },
        calcOfSliderHeight2() {
            let _this = this;
            _this.posTop2 = (_this.pageIndex - 3) * window.innerHeight
        },
    },
    mounted: function() {
        let _this = this;

        window.addEventListener('resize', function() {
            calcOfSliderHeight()
            calcOfSliderHeight2()
        });

        _this.posTop = calcOfSliderHeight();
        _this.posTop2 = calcOfSliderHeight2();
    }
});

Multiple image change on click (similar to Cargo image gallery scrub)

I am trying to replicate Cargo’s image gallery scrub using my own HTML/CSS and/or Java. Example of what I want here on image click: https://sage-smith.com/. It is similar to this stack thread (which worked in my code): how to change image onclick javascript function?

However, this solution only offers to click between 2 images. I am trying to do it with multiple images (like an image gallery).

This is what I have so far:

HTML

 <a><img src="collage3.jpg" id="changer" onclick="changeImage(this)"/></a>

Javascript

  function changeImage(element) {
     element.src = element.bln ? "collage3.jpg" : "asset-2.png";
     element.bln = !element.bln;  /* assigns opposite boolean value always */
 }

How to get updated DOM element in javascript code

I am trying to better understand the relationship between how JavaScript updates DOM object.
Here is my html file index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <div id="container">old</div>
  </body>
  <script src="script.js"></script>
</html>

and here is my JavaScript file script.js,

const container = document.getElementById("container");
console.log(container, container.innerHTML);
container.innerHTML = "new";
console.log(container, container.innerHTML);

The console logs the same <div> tag but with different innerHTML which is quiet unexpected:

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

Therefore my 1st question is, what makes it possible for the console to print the same div elements but different innerHTML?


Secondly I made a small change to my script with setTimeout,

let timeout = 30;
setTimeout(() => {
  container.innerHTML = "new";
  console.log(container, container.innerHTML);
}, timeout);

Though container.innerHTML are always printed with different value, as expected, I found out that if the timeout value is above 35. The div tag is almost certainly printed differently with,

<div id="container">old</div> 'old'
<div id="container">new</div> 'new'

Then something I don’t understand happens. When timeout is set below 10, it is almost certain that div tag are printed as,

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

When timeout is set somewhere between 10 and 30ish, the result toggles, meaning sometimes

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

and sometimes

<div id="container">old</div> 'old'
<div id="container">new</div> 'new'

Therefore my second question is, what causes this difference?

Much Appreciated.