Solving a system of linear equations using javascript

I need to write a code to do a polynomial interpolation for any number of user determined points to create a curve that goes through all points on p5js. I think I’ve figured out how to go about creating the matrices using a for loop with 2D arrays to fill with data points with respect to a parameter, t. However, to easily solve the arrays to get the polynomial coefficients, I’m not sure how to go about trying to solving for it, as I’m not sure how to put math.js into the p5js editor on browser. I’m not even sure that would be helpful since as far as I’m aware, math.js’ matrix functions only work for n x n, whereas the ones I’m trying to solve would be A = n x 4 matrix. If there’s any code that could be used to solve this problem, I would love to see it, because at this point, I am very lost.

“Could not exchange access token for unknown reasons” ; In-meeting App Meeting Extension

Myself and a team member have followed the ‘Try this sample’ and ‘Use the app in Teams’ instructions for the In-Meeting sample application:
https://github.com/OfficeDev/TeamsFx-Samples/tree/v2/in-meeting-app

We’ve both followed the same steps on different computers and on different OS’s (Mac and PC), and we are getting the same issue:

enter image description here

“An error has occurred. This application may no longer respond until reloaded”.

The instructions have us open Powershell and run commands in two locations. (‘Try this sample’ Step 5)

  1. ‘tabs’ folder, asked to run npm install and npm start
  2. ‘bot’ folder, asked to run npm install and npm run start:local

No errors occur when these commands are run initially, but when we open the app up in Teams and click on the button to bring out the side panel, errors show up in both terminals where we ran the commands.

In terminal 1, the tabs folder, we get a ‘proxy error’:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:UsersLukeTeamsAppsin-meeting-apptabs> npm install
up to date, audited 1685 packages in 2s

101 packages are looking for funding
  run `npm fund` for details

142 vulnerabilities (125 moderate, 16 high, 1 critical)

To address issues that do not require attention, run:
Compiled successfully!

You can now view microsoft-teams-ext in the browser.

  Local:            https://localhost:3000
  On Your Network:  https://192.168.0.3:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

Proxy error: Could not proxy request /getGraphAccessToken?ssoToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1yNS1BVWliZkJpaTdOZDFqQmViYXhib1hXMCJ9.eyJhdWQi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WGIPHrS28TajvFa1Acu64YJGNAGys-r6uU7U5MrpcEszufRVExx8tDEysNWc55_Wr88Ur5mBIzDgDqiUbEf_RP2ZzlulRlPZC2ZVwI54VZqAWM2LfbCpD5bL9OhT7H9qAml5N8fOXY_WNHlYUWROgtD_iinQ from reflectrdomain.eu.rok.io to http://localhost:5000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

In terminal 2, the bot folder, we get a type error:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:UsersLukeTeamsAppsin-meeting-appbot> npm install

up to date, audited 188 packages in 1s

12 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
PS C:UsersLukeTeamsAppsin-meeting-appbot> npm run start:local

> [email protected] start:local
> cross-env NODE_ENV=development.local node ./index.js

API server is listening on port 5000
C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesbotbuilderlibbotFrameworkAdapter.js:192
            const connectorClient = this.createConnectorClientInternal(reference.serviceUrl, credentials);
                                                                                 ^

TypeError: Cannot read properties of undefined (reading 'serviceUrl')
    at BotFrameworkAdapter.<anonymous> (C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesbotbuilderlibbotFrameworkAdapter.js:192:82)
    at Generator.next (<anonymous>)
    at C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesbotbuilderlibbotFrameworkAdapter.js:15:71
    at new Promise (<anonymous>)
    at __awaiter (C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesbotbuilderlibbotFrameworkAdapter.js:11:12)
    at BotFrameworkAdapter.continueConversation (C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesbotbuilderlibbotFrameworkAdapter.js:165:16)
    at C:UsersLukeTeamsAppsin-meeting-appbotindex.js:144:13
    at Layer.handle [as handle_request] (C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesexpresslibrouterlayer.js:95:5)
    at next (C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesexpresslibrouterroute.js:137:13)
    at Route.dispatch (C:UsersLukeTeamsAppsin-meeting-appbotnode_modulesexpresslibrouterroute.js:112:3)

My team member who is on Mac, instead of getting the error I get above, just gets the message “Could not exchange access token for unknown reasons.”, but his client displays the same behaviour.

These errors repeat each time we open and close the side panel.

What can we do to fix the issue, and get it to show as it’s supposed to?

enter image description here

Steps to reproduce:
Follow steps at https://github.com/OfficeDev/TeamsFx-Samples/tree/v2/in-meeting-app

“An error has occurred. This application may no longer respond until reloaded.”

jQuery .each() is ignoring elements

I’m making a commission website for fun.
I have made a jQuery function which parses for divs with #portfolio ids and then creates a custom bootstrap carousel to populate them.

The issue is the .each function is ignoring my second #portfolio div

My website is actually running right now and you can check out the issue here: https://pinkflamess.com/

here’s the html snippet:

<h3>Pixel Sprite</h3>
    <div id = "portfolio" count = 8 gifs="https://i.imgur.com/S5jceRT.gif,https://i.imgur.com/hsz8u5H.gif,
    https://i.imgur.com/Tv3MJJo.gif,https://i.imgur.com/6jNkVn4.gif,https://i.imgur.com/ifahlQx.gif,
    https://i.imgur.com/I5JrulB.gif,https://i.imgur.com/Q3DAk0f.gif,https://i.imgur.com/aPAa3Hf.gif">
    </div>
    <p><em>An animation in a pixelated style. 80 by 80 pixels, 4 frames, any fps </em><br/>
      Price: $10 to $15
    </p>
  <h3>Simple Chibi</h3>
    <div id = "portfolio" count = 8 gifs="https://i.imgur.com/OeE0lK4.gif,https://i.imgur.com/6VVvchn.gif,
    https://i.imgur.com/tr8lxoL.gif,https://i.imgur.com/SMH69wR.gif,https://i.imgur.com/mSkbr6J.gif,
    https://imgur.com/MILhBUn.gif,https://imgur.com/oLUxK6N.gif,https://imgur.com/dreYSnx.gif">
    </div>

here’s the jQuery snippet:

$(document).ready(function(){
  //BOOTSTRAP CAROUSELS
  $('#portfolio').each(function() {
    var gifs = $(this).attr('gifs').split(",");
    var count = $(this).attr('count');
    console.log($(this).attr("gifs")); 
    var strToAppend = '<div id="portfolioControls" class="carousel slide data-interval="10000" data-ride="carousel"><div class="carousel-inner">';
    //Mobile carousel (one image per slide))
    if($(window).width() < 480){
      strToAppend = strToAppend + '<div class="carousel-item active"><img class="d-block w-100" src="' + gifs[0] + '"></div>';
      for(var i = 1; i < count; i++){
          strToAppend = strToAppend + '<div class="carousel-item"><img class="d-block w-100" src="' + gifs[i] + '"></div>';
        }
    }
    //Tablet carousel (two images per slide))
    else if($(window).width() < 768){
      strToAppend = strToAppend + '<div class="carousel-item active"><img class="d-block w-50" src="' + gifs[0] + '"><img class="d-block w-50" src="' + gifs[1] + '"></div>';
      for(var i = 2; i < count; i = i + 2){ //must be divisble by 2
        strToAppend = strToAppend + '<div class="carousel-item"><img class="d-block w-50" src="' + gifs[i] + '"><img class="d-block w-50" src="' + gifs[i+1] + '"></div>';
      }
    }
    //Desktop carousel (three images per slide))
    else{
      strToAppend = strToAppend + '<div class="carousel-item active"><img class="d-block w-25" src="' + gifs[0] + '"><img class="d-block w-25" src="' + gifs[1] + '"><img class="d-block w-25" src="' + gifs[2] + '"><img class="d-block w-25" src="' + gifs[3] + '"></div>';
      for(var i = 4; i < count; i = i + 4){ //must be divisble by 4
        strToAppend = strToAppend + '<div class="carousel-item"><img class="d-block w-25" src="' + gifs[i] + '"><img class="d-block w-25" src="' + gifs[i+1] + '"><img class="d-block w-25" src="' + gifs[i+2] + '"><img class="d-block w-25" src="' + gifs[i+3] + '"></div>';
      }
    }
    strToAppend = strToAppend + '</div><a class="carousel-control-prev" href="#portfolioControls" role="button" data-slide="prev"><span class="carousel-control-prev-icon" aria-hidden="true"></span>' +
      '<span class="sr-only">Previous</span></a><a class="carousel-control-next" href="#portfolioControls" role="button" data-slide="next">' +
      '<span class="carousel-control-next-icon" aria-hidden="true"></span><span class="sr-only">Next</span></a></div>'
    //Adds arrows to every carousel type
    $(this).append(strToAppend);
  });
  });

The console.log only prints out the gifs=”” of the first div, and not the second. (it also only prints once)

Thanks for reading, hope you have a good day/night!

Why are canvas stroke styles overriden by new strokes?

I would like to draw 2 lines. The first line should be red, and the second one should be green. I assumed this would be accomplished by the following code.

<html>
  <canvas id='c'></canvas>
  <script>
    let canvas = document.getElementById('c');
    let ctx = canvas.getContext('2d');

    ctx.strokeStyle = 'red';
    ctx.moveTo(10, 10);
    ctx.lineTo(200, 200);
    ctx.stroke();

    ctx.strokeStyle = 'green';
    ctx.moveTo(20, 200);
    ctx.lineTo(200, 100);
    ctx.stroke();
  </script>
</html>

After the first ctx.stroke() we get the expected result.

A red diagonal line

However, the second ctx.stroke() does something odd to the first stroke.

Two green diagonal lines

I expect the second line to be green, and the first line to remain red, yet they both are drawn with different shades of green.

Why is this happening, and what can I do to avoid this?

The code is availible at this codepen.

function not working when i click button?

when i click my button, a timer is supposed to display a countdown timer. But the button does not work.

let timerCounter = document.getElementById("timer-counter");
let timer;
let timerCount;



function startTimer (){
timer = setInterval(function(){
    timerCount--;
    timerElement.textContent = "Time; " + timerCount;
    if (timerCount === 0){
        clearInterval(timer);
    }
});

}
startButton.addEventListener(“click”, startTimer);

How to trigger re-render in Parent Component from Child Component

Using props I was able to effectively pass state upwards from my child component to its parent, but a change in the state does not cause a re-render of the page.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const AddToList = (item) => {
    setText([...text, item]);
  };
  const removeFromList = (item) => {
    const index = text.indexOf(item);
    text.splice(index, 1);
  };
  const [text, setText] = React.useState(["default"]);
  return (
    <div className="App">
      <div>
        <button
          onClick={() => {
            AddToList("hello");
          }}
        >
          Add
        </button>
      </div>
      {text.map((item) => {
        return <ChildComponent text={item} removeText={removeFromList} />;
      })}
    </div>
  );
}

const ChildComponent = ({ text, removeText }) => {
  return (
    <div>
      <p>{text}</p>
      <button
        onClick={() => {
          removeText(text);
        }}
      >
        Remove
      </button>
    </div>
  );
};

In the snippet, each time AddToList is called, a new child component is created and the page is re-rendered reflecting that. However, when i call removeFromList on the child component, nothing happens. The page stays the same, even though I thought this would reduce the number of childComponents present on the page. This is the problem I’m facing.

Passing data from a child component to a parent component (React)

I have a child component that has some states which change in value when you check or un-check some boxes; I want to be able to pass those state values to the parent component. I’ve tried a few things on the internet but nothing seem to work.

I’ve tried to (Parent Component File):

const ParentComponent = () => {

     const [ data, setData ] = useState();

     const childToParent = (childData) => {
          setData(childData);
     };

     return(
          <Child childToParent={childToParent} />
     );
}

and on the Child Component:

const ChildComponent = ({ childToParent }) => {

     const [ childData, setChildData ] = useState(false);

     const handleChange = () => {
          setChildData(!childData);
          childToParent(childData);
     };

     return(
          <div>
               <Checkbox value={childData} callback{() => handleChange()} />
          </div>
     );
}

Basically the problem is I dont get how to move data from a child component to a parent component.

How to freeze scrolling on a certain frame in Javascript or React.js

I have a website when I scroll to a certain position I want to freeze the scrolling functionality but be able to raise the other object when I am scrolling.

I did not find any useful articles on the internet, maybe someone knows how I can do it.

To sum up,

I have multiple sections on my website, when I scroll to section 3, I want to disable scrolling but be able to raise the block which is located in this section 3 – I want to create a parallax effect where we continue scrolling functionality once one block is raised up.

I want to freeze scrolling but be able to listen to the mouse scroll event.

I don’t need code, just tell me how I can do it. Thanks

How nike detect Puppeteer?

When I want to connect with a browser launched from puppeteer, POST requests from Nike is permanently blocked.
Yet I used puppeteer-extra-plugin-stealth.
I don’t understand how nike manages to detect Puppeteer.

My code :

const puppeteer = require('puppeteer-extra');
const pluginStealth = require("puppeteer-extra-plugin-stealth");

puppeteer.use(pluginStealth())

puppeteer.launch({
    headless: false
}).then(async browser => {
    const page = await browser.newPage()
    await page.goto('https://www.nike.com')
})

When i want to log in :
output

Struggling with this js Codewars challenge

I am learning js and struggling with a problem I encountered on Codewars.

I need to calculate how many numbers containing only binary digits exist between 1 and a random number n. For example, if n is 20, there are 3 such numbers: 1, 10, 11;

I have written a solution that works on codepen but Codewars is telling me it is too inefficient to be accepted. I can’t think of anything else I can do to optimize it. Thank you in advance for your help!

function incompleteVirus(n) {
  let countInMemory = 0;
  let isBinary = true;

  // Loop through all numbers below and including n
  for (let i = 1; i <= n; i++) { 

    let strCurrNum = String(i); 

    // Iterate through all digits in the current number
    for (const digit of strCurrNum) {
  
      let numDigit = Number(digit);
 
      // Check if each digit is binary; if not, exit loop
      if (numDigit > 1) {
        isBinary = false;
        break;
      } else {
        isBinary = true;
      }
    }

    // Update memory count
    if (isBinary) {
      countInMemory += 1;
    }
  } 
  return countInMemory
}

Markers not showing on Google Map

My custom markers aren’t coming up on a google map on my WordPress site. I’ve reviewed the code for bugs and I’ve seen the following error in the console: (index):573 Uncaught ReferenceError: myMarkers is not defined at initialize however I have another site with nearly the same exact code that is working fine and so I can’t figure out why myMarkers is not defined. I’ve tried rearranging the code to no avail. Has anyone seen this before? Thanks!

Map is at the bottom of the page here: https://excelsportspt.com/

Here is the code:

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBtKFXFKTieXTdke5jGk_KxZE6FYEADYxg"></script>
    <script type="text/javascript">// <![CDATA[
        jQuery(document).ready(function() {
            <?php if (have_rows('location_map', 'options')): ?>
                //set up markers
                myMarkers = {"markers": [
                    <?php while (have_rows('location_map', 'options')): the_row();
                        $loclatitude = get_sub_field('address_latitude', 'options');
                        $loclongitude = get_sub_field('address_longitude', 'options');
                        $locname = get_sub_field('address_name', 'options');
                        $locadd = get_sub_field('address', 'options');
                        $locmap = get_sub_field('loc_map_url');
                    ?>
                        {
                            'latitude': '<?= $loclatitude; ?>',
                            'longitude': '<?= $loclongitude; ?>',
                            'icon': '<?= esc_url(get_template_directory_uri()); ?>/images/map-pin.png',
                            'balloon_text': '<a target="_blank" href="<?= $locmap; ?>"><?= $locname; ?></a>'
                        },
                    <?php endwhile; ?>
                ]}
            <?php endif; ?>
            map = '';
            function initialize() {
                var myOptions = {
                    center: new google.maps.LatLng(38.7234409, -90.6383197),
                    zoom: 10,
                };
                map = new google.maps.Map(document.getElementById('map1'), myOptions);
                setMarkers(map,myMarkers.markers);
            }
           
            function setMarkers(map,markers) {
                var marker, i;
                for (i = 0; i < markers.length; i++) {
                    var lat = markers[i].latitude;
                    var long = markers[i].longitude;
                    var content =  markers[i].balloon_text;
                    var icon =  markers[i].icon;
                    latlngset = new google.maps.LatLng(lat, long);
                    var marker = new google.maps.Marker({
                        map: map,
                        title: content,
                        position: latlngset,
                        icon: icon
                    });
                    var infowindow = new google.maps.InfoWindow()
                    google.maps.event.addListener(marker, 'click', (function  (marker,content,infowindow) {
                        return function() {
                            infowindow.setContent(content);
                            infowindow.open(map,marker);
                        };
                    })(marker,content,infowindow));
                }
            }
           
            google.maps.event.addDomListener(window, 'load', initialize);
            jQuery(document).on('click', '.map-open', function(event) {
                event.preventDefault();
                map.setCenter(
                    new google.maps.LatLng(jQuery(this).data('lat'),  jQuery(this).data('long'))
                );
            });
        });
    </script>
       
    <div class="location-map" id="map1"></div>

Apollo Client GraphQL Unit Testing return Error: TypeError: (0 , _reactHooks.useQuery) is not a function

I was trying to write unit test with react component from Apollo Client Unit Testing, but I got an error when mocking call to the GraphQL endpoint to some hook functions.

My unit test implement:

import React from 'react';
import MockedProvider from '@apollo/react-testing';
import renderer from 'react-test-renderer';
import { GET_CHARACTER_DETAILS } from '../../containerHooks/useCharacterDetails';
import { UseCharacterDetails } from '../../containerHooks/useCharacterDetails';

const mocks = [
  {
    request: {
      query: GET_CHARACTER_DETAILS,
      variables: {
        id: 1,
      },
    },
    result: {
      data: {
        character: {
          id: '1',
          name: 'Rick Sanchez',
          status: 'Alive',
          gender: 'Male',
        },
      },
    },
  },
];

it('renders without error', () => {
  renderer.create(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UseCharacterDetails id='1' />
    </MockedProvider>
  );
});

Here is my Test Component

import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';

export const GET_CHARACTER_DETAILS = gql`
  query CharacterDetails($id: ID!) {
    character(id: $id) {
      id
      name
      status
      species
      type
      gender
      origin {
        name
      }
      location {
        name
      }
      image
      episode {
        name
      }
      created
    }
  }
`;

export const UseCharacterDetails = ({ id }) => {
  const { loading, error, data } = useQuery(GET_CHARACTER_DETAILS, {
    variables: { id },
  });

  return {
    data,
    error,
    loading,
  };
};

When I run a test, it throws an error

TypeError: (0 , _reactHooks.useQuery) is not a function

Is there a way to communicate client to client in a static website

I want to make a game with room system, like kahoot or stop. Using a static website (github pages):

My plain is to have two links,

link 1 – sitename/host.github.io

link 2 – sitename.github.io

the host device will connect to the 1 link and the players to the 2. The clients (devices at the 2 link) should be able to send data to each other, for example, if client1 selects a button, client2 will be informed.

Ps. this site is for my math teacher, and not always all the devices will be connected to the same wifi, like if he is in a online class. or the school wifi is bad and they have to use mobile data(4g, 3g, etc.) so I dont think it is a good idea to use LAN.

JavaScript post request to PHP file – No content available because this request was redirected

Failed to load response data: No content available because this request was redirected

I have no idea what this response message means whatsoever. Maybe stack can help?

This is the most specific I can get. The context is that I made a website and made a javascript post request to the .php file then checked network and it responded with the error above

I do not have an example code because it is not necessary the .php file is blank.

My php file:

<?php ?>

Resize CSS Grid Layout

So I am attaching a sandbox to help with this question.
https://codesandbox.io/s/xenodochial-benz-2333fv?file=/src/ResizeColumns.tsx:185-196

I have 2 control Divs.
one for Rows,
one for Columns, and
a Central grid area.

I would like for the black bars in the control divs on the side and bottom to allow for adjusting the CSS grid.

  • Not sure how to allow for the black bars to move.
  • Grid layout on control divs should update with bar movement.
  • Central grid layout needs to update with bar movement.

Any help would be greatly appreciated even if its just more learning/research material.