How to add catch error to my axios API code

THE CODE BELOW DISPLAYS POST FROM REDDIT, how can i make it display error if http is incorrect? if the data is not gotten.

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import axios from 'axios'

class Reddit extends React.Component {
  state = {
    posts: [],
  }
  componentDidMount() {
    axios
      .get(`https://www.reddit.com/r/${this.props.subreddit}.json`)
      .then((res) => {
        const posts = res.data.data.children.map((obj) => obj.data)
        this.setState({ posts })
      })
  }
  render() {
    const { posts } = this.state
    return (
      <div>
        <h1>{`/r/${this.props.subreddit}`}</h1>
        <ul>
          {posts.map((post) => (
            <li key={post.id}>{post.title}</li>
          ))}
        </ul>
      </div>
    )
  }`
}

ReactDOM.render(<Reddit subreddit='reactjs' />, document.querySelector('#root'));

THE CODE BELOW DISPLAYS POST FROM REDDIT, how can i make it display error if http is incorrect? if the data is not gotten.

Jest TypeError: jest.setSystemTime is not a function

I’m writing a test with jest but keep getting the error TypeError: jest.setSystemTime is not a function

I was following the methods from previous post How do I set a mock date in Jest? but this error persists.

I call the function from my beforeAll like so:

beforeAll(() => {
  jest.useFakeTimers('modern')
  jest.setSystemTime(new Date('2022-3-16'))
})

Any thoughts on what could be causing this error?

My package.json is using "ts-jest": "^26.3.0" and "@types/jest": "^26.0.13"

GetSelection from metamask

I want the numbers inside the selected text to be put in -var selected-. It works very well on webpages, but i want it to work in other plugins like metamask. Google transaction also use getselection and it works inside metamask, but mine does not work in metamask, all help will be appreciated.

var selected = window.getSelection().toString().replace(/[^d.]/g, ”);

Group an array of sales by sellers, get the total from each Seller, order by total sales

I have an array like this :

[
    {
        "orderId": 1,
        "orderDate": "2021-04-28T08:20:58Z",
        "status": "Confirmed",
        "sellerName": "Chris Gilmour",
        "revenue": 2316.49
    },
    {
        "orderId": 2,
        "orderDate": "2020-12-19T12:30:18Z",
        "status": "Confirmed",
        "sellerName": "Alanna Sumner",
        "revenue": 2928.88
    },
    {
        "orderId": 4,
        "orderDate": "2020-12-24T08:00:09Z",
        "status": "Confirmed",
        "sellerName": "Beth North",
        "revenue": 1550.19
    },
    {
        "orderId": 5,
        "orderDate": "2021-06-06T04:40:48Z",
        "status": "Confirmed",
        "sellerName": "Laura Ponce",
        "revenue": 35.5
    },
    {
        "orderId": 8,
        "orderDate": "2021-08-27T05:13:40Z",
        "status": "Canceled",
        "sellerName": "Blade Newman",
        "revenue": 2957.29
    },
    {
        "orderId": 9,
        "orderDate": "2020-12-26T08:07:57Z",
        "status": "Confirmed",
        "sellerName": "Alanna Sumner",
        "revenue": 2164.75
    },
    {
        "orderId": 10,
        "orderDate": "2021-04-23T18:44:19Z",
        "status": "Confirmed",
        "sellerName": "Blade Newman",
        "revenue": 2287.55
    }
]

I want the new Array to be :

[ 
    {
        "sellerName": "Blade Newman",
        "totalRevenue": 5244.84
    },
    {
        "sellerName": "Alanna Sumner",
        "totalRevenue": 5093.63
    },
    { 
        "sellerName": "Chris Gilmour",
        "totalRevenue" : 2316.49
    },
    {
        "sellerName": "Beth North",
        "totalRevenue": 1550.19
    }

]

So I want the array to be grouped by sellerName, the amount sold summed up and ordered By sellers with the most total sales.

I tried to solve this by using forEachs and reduces but I failed, if anyone can help me that would be great.

Thanks in advance.

I have no idea what this is asking me to do [closed]

CODE: https://calu.desire2learn.com/d2l/le/content/3179339/topics/files/download/32504273/DirectFileTopicDownload
MEMBER TEXT FILE: https://attachments.office.net/owa/MIL3311%40calu.edu/service.svc/s/GetFileAttachment?id=AAMkADNiNTg2YWVmLTI4YzktNDlmMS05YzhmLWEwYmExMTZhODE1NgBGAAAAAABgh7qvnxkdRqd04op9O%2BLNBwAYAsq%2BOHoXSK9ZbN9mtV8DAAAAAAEMAAAYAsq%2BOHoXSK9ZbN9mtV8DAAE%2BiTr%2FAAABEgAQABYOM0KJ1k1PmbfDwcC7634%3D&token=eyJhbGciOiJSUzI1NiIsImtpZCI6IkZBRDY1NDI2MkM2QUYyOTYxQUExRThDQUI3OEZGMUIyNzBFNzA3RTkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiItdFpVSml4cThwWWFvZWpLdDRfeHNuRG5CLWsifQ.eyJvcmlnaW4iOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbSIsInVjIjoiZWNmY2RiZWU2Yzg5NDBlOGJmNGRkNGI0ZjFiMjZhYjUiLCJzaWduaW5fc3RhdGUiOiJbXCJrbXNpXCJdIiwidmVyIjoiRXhjaGFuZ2UuQ2FsbGJhY2suVjEiLCJhcHBjdHhzZW5kZXIiOiJPd2FEb3dubG9hZEA2MjcyNzI1OC02OTE2LTQ4YmUtOGY5OS0yMDYzNTk3N2JhZGQiLCJpc3NyaW5nIjoiV1ciLCJhcHBjdHgiOiJ7XCJtc2V4Y2hwcm90XCI6XCJvd2FcIixcInB1aWRcIjpcIjExNTM4MDExMTgyNDE0NzIyMTVcIixcInNjb3BlXCI6XCJPd2FEb3dubG9hZFwiLFwib2lkXCI6XCI3ZjQ1MzA1OC00MjE1LTQ4NmItYWMxMi0yOTc3NDE3MDM3ZDlcIixcInByaW1hcnlzaWRcIjpcIlMtMS01LTIxLTYxMjQ2MjMxNC0zNjc4Mjc5NDgyLTM1MTU4ODk3NDgtMjUyNTg3MThcIn0iLCJuYmYiOjE2NDk3MTMxNzAsImV4cCI6MTY0OTcxMzc3MCwiaXNzIjoiMDAwMDAwMDItMDAwMC0wZmYxLWNlMDAtMDAwMDAwMDAwMDAwQDYyNzI3MjU4LTY5MTYtNDhiZS04Zjk5LTIwNjM1OTc3YmFkZCIsImF1ZCI6IjAwMDAwMDAyLTAwMDAtMGZmMS1jZTAwLTAwMDAwMDAwMDAwMC9hdHRhY2htZW50cy5vZmZpY2UubmV0QDYyNzI3MjU4LTY5MTYtNDhiZS04Zjk5LTIwNjM1OTc3YmFkZCIsImhhcHAiOiJvd2EifQ.JHmzyRfmaQf7DPEr6zlJgtncjOJCygXOCCzoOtBCjVuPHE2z3a_oWQBT6m_ZnATy6gJgg5X1hzEOp0bvifEzNx-l2R2uw4bR581FUxCHoOakhfhLQ8OP6pDyP8eqeCrdYVAS_8K04Y5ZzsqX1qJP3q8MCBBo8A5XGwWL8vAIflA9vhwWepD-bU83YPWQTDNNYMip5CZN2dlK634rvg8qsXyu0lrkLsizvs3M1gJ8E9sdUjHcsm0cwl2vIFdtAW59YsQaZNIawWflWycRm1sIT7mV0vYsna32n2A6mX0cVKYBOzpr3fbSXP_KUPO40kTJOmY1YKgV93ePwXIWGEsQFw&X-OWA-CANARY=mj9aZOxLaE-bOpXiLB7NZgD3VsUDHNoY9wBp4dyXUhtmzN_uBP1kbiUfxnCkyljOWGSfxi_Vs3A.&owa=outlook.office.com&scriptVer=20220401003.04&isDownload=true&animation=true
REGISTER TEXT FILE:
https://attachments.office.net/owa/MIL3311%40calu.edu/service.svc/s/GetFileAttachment?id=AAMkADNiNTg2YWVmLTI4YzktNDlmMS05YzhmLWEwYmExMTZhODE1NgBGAAAAAABgh7qvnxkdRqd04op9O%2BLNBwAYAsq%2BOHoXSK9ZbN9mtV8DAAAAAAEMAAAYAsq%2BOHoXSK9ZbN9mtV8DAAE%2BiTr%2FAAABEgAQABYOM0KJ1k1PmbfDwcC7634%3D&token=eyJhbGciOiJSUzI1NiIsImtpZCI6IkZBRDY1NDI2MkM2QUYyOTYxQUExRThDQUI3OEZGMUIyNzBFNzA3RTkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiItdFpVSml4cThwWWFvZWpLdDRfeHNuRG5CLWsifQ.eyJvcmlnaW4iOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbSIsInVjIjoiZWNmY2RiZWU2Yzg5NDBlOGJmNGRkNGI0ZjFiMjZhYjUiLCJzaWduaW5fc3RhdGUiOiJbXCJrbXNpXCJdIiwidmVyIjoiRXhjaGFuZ2UuQ2FsbGJhY2suVjEiLCJhcHBjdHhzZW5kZXIiOiJPd2FEb3dubG9hZEA2MjcyNzI1OC02OTE2LTQ4YmUtOGY5OS0yMDYzNTk3N2JhZGQiLCJpc3NyaW5nIjoiV1ciLCJhcHBjdHgiOiJ7XCJtc2V4Y2hwcm90XCI6XCJvd2FcIixcInB1aWRcIjpcIjExNTM4MDExMTgyNDE0NzIyMTVcIixcInNjb3BlXCI6XCJPd2FEb3dubG9hZFwiLFwib2lkXCI6XCI3ZjQ1MzA1OC00MjE1LTQ4NmItYWMxMi0yOTc3NDE3MDM3ZDlcIixcInByaW1hcnlzaWRcIjpcIlMtMS01LTIxLTYxMjQ2MjMxNC0zNjc4Mjc5NDgyLTM1MTU4ODk3NDgtMjUyNTg3MThcIn0iLCJuYmYiOjE2NDk3MTMxNzAsImV4cCI6MTY0OTcxMzc3MCwiaXNzIjoiMDAwMDAwMDItMDAwMC0wZmYxLWNlMDAtMDAwMDAwMDAwMDAwQDYyNzI3MjU4LTY5MTYtNDhiZS04Zjk5LTIwNjM1OTc3YmFkZCIsImF1ZCI6IjAwMDAwMDAyLTAwMDAtMGZmMS1jZTAwLTAwMDAwMDAwMDAwMC9hdHRhY2htZW50cy5vZmZpY2UubmV0QDYyNzI3MjU4LTY5MTYtNDhiZS04Zjk5LTIwNjM1OTc3YmFkZCIsImhhcHAiOiJvd2EifQ.JHmzyRfmaQf7DPEr6zlJgtncjOJCygXOCCzoOtBCjVuPHE2z3a_oWQBT6m_ZnATy6gJgg5X1hzEOp0bvifEzNx-l2R2uw4bR581FUxCHoOakhfhLQ8OP6pDyP8eqeCrdYVAS_8K04Y5ZzsqX1qJP3q8MCBBo8A5XGwWL8vAIflA9vhwWepD-bU83YPWQTDNNYMip5CZN2dlK634rvg8qsXyu0lrkLsizvs3M1gJ8E9sdUjHcsm0cwl2vIFdtAW59YsQaZNIawWflWycRm1sIT7mV0vYsna32n2A6mX0cVKYBOzpr3fbSXP_KUPO40kTJOmY1YKgV93ePwXIWGEsQFw&X-OWA-CANARY=mj9aZOxLaE-bOpXiLB7NZgD3VsUDHNoY9wBp4dyXUhtmzN_uBP1kbiUfxnCkyljOWGSfxi_Vs3A.&owa=outlook.office.com&scriptVer=20220401003.04&isDownload=true&animation=true

–

Download the files “ymca.java” and “member.txt” for this email
Open eclipse and create project, package and class called “ymca”
copy the code “ymca.java” (over top of the code that was generated in the step above).
Minimize the eclipse screen and drag the file “member.txt” into the main folder of the project. In this case, it will be the folder “ymca” that is directly under the eclipse workspace.

  1. Add two new sets of parallel arrays to the program, these arrays will store the information that will be read in from the register.txt file. That file contains the member’s code and the name of the class they will be registered for. The two parallel arrays will be names of your choice, but each will be defined as being 100 big.
     Need to define:
     Register Member code to be an Integer array defined as 100 big
     Register Class name to be a String array defined as 100 big
     Also need to define a new variable that will keep track of how many registration items that have been read in from the data file. This new variable will work with the registration file the
    same way the variable mcount works with the member file.

  2. Add code to the read_registration method. In this method, read in all data from the
    register.txt file into the new parallel arrays defined in #1 above. This code is just like the code in the
    method read_member where you are reading in the member information.
    Have to change the call to the read_register statement passing the arrays and the count you defined in step #1 above.
     Drag the additional data file register.txt to the same folder where the file member.txt is.
    Remember that the location of the data files is the main folder of your java project (just under the
    eclipse workspace folder) (contents of the register.txt file can be viewed at the end of this
    assignment)

  3. Add code to the Modify member method. In this method, you will increment the member count
    (mcount) and prompt the user for new member data to be read into the member parallel arrays. You will have to change the call to the modify_member method, passing the arrays and the member count

  4. Add code to the Modify Registration method In this method, you will increment the registration count
    (defined in step #1 above) and prompt the user for new registration data to be read into the registration parallel arrays. Will have to change the call to the modify_registration method, passing the arrays and the registration count
     The possible class names are:
     Yoga
     Karate
     AerobicsI
     AerobicsII
     SwimmingI
     SwimmingII

  5. Add code to the exit_program method. In this method:
     Add the code to write the member data back to the data file member.txt.
     Add the code to write the registration data back to the data file register.txt.
     Will have to change the call to the exit_program method, passing the arrays and counts

  6. Add code to the Report Method
     Will have to change the call to the report method, passing the arrays and the counts

 Change the menu text to the wording below

  1. All Member Information

  2. All Registration Information

  3. All Members of a Specific type

  4. All Members between a specific age range

  5. All Members of a specific gender

  6. Specific Member’s Registration

  7. Report 7

  8. Report 8

  9. Report 9

  10. Report 10

  11. Exit Report Menu
     Each report is defined as follows:

  12. All Member Information – Displays all information on all members

  13. All Registration information -Display all information for all registrations

  14. All Members of a Specific type- Prompt for the type and then display all information for
    members of that type

  15. All Members between a specific age range – Prompt for the beginning and ending age, then
    display all member information for the members within the date range

  16. All Members of a specific gender – Prompt for the gender and then display all members of that
    gender.

  17. Specific Member’s Registration – List of all classes a specific member is signed up for (prompt
    for the member code) You must display all of the member’s information and then search the
    registration arrays and when there is a match on the member’s code, print the list of all classes he
    is registered for

  18. Report 7 print message “Report 7 to be defined later”

  19. Report 8 print message “Report 8 to be defined later”

  20. Report 9 print message “Report 9 to be defined later”

  21. Report 10 print message “Report 10 to be defined later”

  22. Screen shot of Report #1, 2, 3, 4, 5 ,6 running seperatly
    2 (add Member information) Screen shot of adding a new member
    3 Screen shot of Report #1 running again
    4 (add new registration information) Screen shot of adding a new registration

  23. Screen shot of Report #2 running

  24. Close the program…start it again. Screen shot of Report #1 running7

  25. Screen shot of Report #2 running

Vectors of latitude and longitude in geolocation app in shiny

I am building and app, that includes geolocation captures using the geoloc package

This is an example app:

library(shiny)
library(leaflet)
library(geoloc)

ui <- fluidPage(
  h2("Where Am I?"),
  tags$p("Click the button to get your location"),
  geoloc::button_geoloc("myBtn", "Get my Location"),
  tags$br(),
  textOutput("coords"),
  textOutput("col"),
  leafletOutput("lf")
)

server <- function(input, output) {
  output$coords <- renderText(paste(input$myBtn_lat, input$myBtn_lon, sep = ", "))
  
  Lats <- reactiveValues(Lat = NULL)
  
  observeEvent(input$myBtn_lat, {
    Lats$Lat <- append(Lats$Lat, input$myBtn_lat)
  })
  
  
  output$col <- renderText({
    Lats$Lat
  })
  
  output$lf <- renderLeaflet({
    req(input$myBtn_lon)
    req(input$myBtn_lat)
    leaflet() %>%
      addTiles() %>%
      setView(as.numeric(input$myBtn_lon), as.numeric(input$myBtn_lat), zoom = 17) %>%
      addMarkers(as.numeric(input$myBtn_lon), as.numeric(input$myBtn_lat), label = "You're here!")
  })
}

shinyApp(ui, server)

I have two questions for this:

How to get a vector of latitudes and longitudes with the button

I need this because usually, we like to take 4 or 5 times the location and then use the median.

This has been addressed in this question, however, there are some kinks I can’t figure out since the button is a custom one, and the inputs are not input$myBtn, but input$myBtn_lat and input$myBtn_lon, I find it hard to compute. This is what I am trying to do with the observe events

How to transform this into shiny modules

This will go to a larger shiny app, so I would love to generate modules for this, but again, the facto that the input in ui is “myBtn”, but then in the server I have 2 inputs (MyBtn_lon and MyBtn_lat), make it very hard to figure out

Any help is welcome

How to pass a decimal point number in to local state with type on number in typescript?

I want to be able to pass a number with decimal point to a TextField using typescript, the current issue is, I need to convert the (e.target.value) to a number since I cannot set selected like this directly, and if I use a decimal point it ignores it, I need to know a way to convert (e.target.value) with a decimal point to a number a be able to pass it to the selected (state)

const [selected , setSelectd]= useState<number>(0);
  
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  console.log(e.target.value);
  const convertedValue = Number(e.target.value);
  setSelectd(convertedValue);
};
 
return (
  <TextField
    value={selected.amount}
    onChange={handleChange}
   /> 
);

Subclassing without the class keyword

How does the following look in terms of constructing a subclass from objects without using the class keyword as a sort of academic exercise?

// Product > Book
function Product(type, price) {
    if (!new.target) return new Product(...arguments);
    console.log('--- Product.constructor() ---');
    Object.assign(this, {type, price});
}
Product.prototype.getPrice = function getPrice() {
    console.log('--- Product.getPrice() ---');
    return this.price;
}
Product.prototype.display = function displayProduct() {
    console.log('--- Product.display() ---');
    return `${this.type} (${this.price})`;
}

// subclass the Product
function Book(type, price, title, author, pages) {
    if (!new.target) return new Book(...arguments);
    console.log('--- Book.constructor() ---');
    Object.assign(this, new Product(type, price), {title, author, pages});
    this.parent = Product;
}
Book.prototype.getNumPages = function() {
    console.log('--- Book.getNumPages() ---');
    return this.pages;
}
Book.prototype.display = function displayBook() {
    console.log('--- Book.display() ---');
    return `${this.parent.prototype.display.call(this)}`
         + ` -- ${this.title} by ${this.author} (${this.pages} pgs)`;
}
// these are the two lines that make it work -- 
Book.prototype = {...Product.prototype, ...Book.prototype}; // otherwise, we wouldn't inherit the Product superclass
Book.constructor = Book; // and we have to make sure that after we've inherited the prototype we re-set the proper constructor

console.log(Product.prototype);
console.log(Book.prototype);

let book = Book("Book", 4.99, "Angels & Demons", "Dan Brown", 305);
console.log(book.getNumPages());
console.log(book.getPrice());
console.log(book.display());

Does it seems like anything is missing in the above or can be improved? One question I was a bit perplexed on — why doesn’t the this get updated automatically when calling the parent constructor, which requires doing this (passing the return value of the Product constructor rather that it just updating this as a sort of side-effect:

Object.assign(this, new Product(type, price), {title, author, pages});

¿Es posible enviar un object o class desde un envio MultiFile de react?

paso 1 : en este caso seria el parametro que habilitarias en el controlador

paso 2: convertir el object o array en json para posteriormente sobreescribirle el binario

al final de todo puedes con probar el estado del envio

fileTosave(contiene el objeto o array que deseas enviar )
var fileTosave2 = new Blob([JSON.stringify(product)], {
  type: 'application/json'
});
formData.append('obj',fileTosave2);

files2.files2 (contiene la imagen en formato multiFile)
formData.append('image1',files2.files2);
files3Create (contiene una lista de  imagenes  en formato multiFile)
for(var i = 0 ; i< files3Create.length ; i++ ){
  console.log(files3Create[i]);
   formData.append('files', files3Create[i].files3);
}

axios({  method: "POST",
url: "http://localhost:8080/cliente/GuardarCliente",
data: formData,
headers: { "Content-Type": "multipart/form-data" },})
  }

Bull queue nestjs not processing the job at correct time

I am trying to create a time in milliseconds to pass it to delay using bull queue. I can correctly get time for the processing of the job, but somehow the job is not being called at a specific time. Some time it take more than 30 or 45 seconds to process the job from it’s actual start of time.

for example if delay time is for 2 minutes. it execute in 2 minutes and 45 seconds. I am unable to find the reason. I want it to run only at 2 minutes. Below is my code

const startTime = moment().tz(timeZone).set('second', 0).valueOf();
const endTime = moment(time)
      .subtract(timeToSubtract, 'minutes')
      .tz(timeZone)
      .set('second', 0)
      .valueOf();
const scheduleTime = endTime - startTime

this.queue.add(
     'test-queue',
      {
        mesage,
      },
      {
        delay: scheduleTime,
        removeOnComplete: true,
      }
    );

Pusher Cannot read properties of undefined (reading ‘push’)

I want to update the list of users with pusher.
When I submit the console shows this error:
enter image description here

I also get Uncaught refering to pusher.js
The pusher.js cointains code for pusher and it is placed in the footer:

   let teamChannel = pusher.subscribe('team-list');
   teamChannel.bind('updated-team', function(data) {
     app.team.push(JSON.stringify(data)); 
   });
    

My event:

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;

class NewParticipant implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $team;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($team)
    {
        $this->team = $team;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return IlluminateBroadcastingChannel|arrays
     */
    public function broadcastOn()
    {
        return new Channel('team-list');
    }

    public function broadcastAs() 
    {
        return 'updated-team';
    }
}

js from my Vue component:

<script>

    export default {
        data() {
            return {
                team: [],
            }
        }, 
        created() {
            this.fetchPlayer();
            this.listenForChanges();
        },
        methods: {
            fetchPlayer() {
                console.log('test');
            },
            listenForChanges() {
                window.Echo.channel('team-list')
                    .listen('updated-team', (e) => {
                        console.log("echo is working");
                        console.log("e is " + e);
                        })
            }
        },  
        computed: {
            teamList() {
                return this.team;
            }
        }
    }
    </script>

My controller has this function:

protected function addPlayer($event, Request $request) {   

    $profile = auth()->user()->profile;
    $profile->participate()->syncWithoutDetaching([$event->id], false);
    $team = $event->participants()->get();    
    event(new NewParticipant($team));

    return redirect()->route('event.show', [ 'event' => $event ]);
}

Why the pusher & echo won’t listen to app.team.push?

Call a function on Input Completion

I have a name input on 1.html.
I need to call a function where the input will be stored after completion, and when the person clicks ~next~ to go to the next page (2.html), whatever was stored appears there.
Example:

~1.html~

What’s your name?
~input~ John ~input~

~2.html~

Hi, John! How can i help you?

I know i can use local Storage to do it, but i’m not sure on how to proceed.
Here’s what i have:

1.html

<p>"Whats Your Name?"</p>
<input id="your-name-input" type="text">

<script> 

function setName() {
  var name = document.getElementById("your-name-input").value;
  localStorage.setItem("name", name);
}

</script>

And then, on 2.html i have:

<p id="user-name"></p>

<script>

function getName() {
    var name = localStorage.getItem("name");
    document.getElementById("user-name").innerHTML = "Hey, " + name + "!" + <br></br> + "Are you ready?"
}

</script>

What am i doing wrong here? How do i call those functions correctly?

How to properly save fibonacci series in javascript using matrices

I am trying to solve the Fibonacci algorithm using matrices. My target time complexity is an o(logn) instead of an o(n). The return output of the program is not the number for the series but the sixth significant digits. Its why I am returning the remainder of the solution divided by a million.

I have written the code and it runs well but I noticed that for extremely large inputs, I get a NAN(not a number) instead of an output


const fib = (n) => {
  let fibMatrix = [[1,1], [1,0]]
  
  if(n == 0){
    return 0;
  }
  
  raiseToPower(fibMatrix, n - 1);
 
  return Math.floor(fibMatrix[0][0] % 1000000)
}

const raiseToPower = (matrix, n) => {
  
  if(n == 0 || n == 1){
    return;
  }
  
  let newMatrix = [[1,1], [1,0]]
  
  raiseToPower(matrix, Math.floor(n / 2))
  
  
  multiplyMatrices(matrix, matrix)
  
  
  
  if(n % 2 !== 0){
    multiplyMatrices(matrix, newMatrix)
  }
  
}

const multiplyMatrices = (matrix, newMatrix) => {
    let x =  matrix[0][0]*newMatrix[0][0] + matrix[0][1]*newMatrix[1][0];
    let y =  matrix[0][0]*newMatrix[0][1] + matrix[0][1]*newMatrix[1][1];
    let z =  matrix[1][0]*newMatrix[0][0] + matrix[1][1]*newMatrix[1][0];
    let w =  matrix[1][0]*newMatrix[0][1] + matrix[1][1]*newMatrix[1][1];
    
    
     
    matrix[0][0] = x;
    matrix[0][1] = y;
    matrix[1][0] = z;
    matrix[1][1] = w;
}

console.log(fib(2000))

Thats my code above. Is there anything I could change to actually make this much more performant?

Find the longest Elements in a 2d array

I’m currently working with a 2d Array which is 6 rows long.

Now I need to filter the longest rows to work with them. But I dont know how to filter the shortest the element.

For example:

0: (3) ['karo11', 'karo6', 'kreuz13']
1: (2) ['pik6', 'pik13']
2: ['karo13']
3: (2) ['herz11', 'kreuz6']
4: ['herz6']
5: (2) ['kreuz11', 'pik11']

This is my array. Now I need to filter out row 2 and 4. But how should I do this?

Note. The Array is not static so the length of the rows are variable and change everytime I run the code

rotate variable to fit credit score gauge javascript

I am new to javascript, so I am trying to rotate the variables of bad, poor, good and excellent to fit the border on the credit score gauge. I have searched the web, but I am stuck in how to angle/rotate these variables. Here is the link to the codepen.

var chartVars = "KoolOnLoadCallFunction=chartReadyHandler";

KoolChart.create("chart1", "chartHolder", chartVars, "100%", "100%");

function chartReadyHandler(id) {
document.getElementById(id).setLayout(layoutStr);
document.getElementById(id).setData(chartData);
}
var trackValues = [0,20,40,60,80,100];

var trackLabels = ["BAD", "POOR", "FAIR", "GOOD", "EXCELLENT"];

var layoutStr = 
'<KoolChart frameColor="#EEEEEE"  borderStyle="none">'
+'<Options>'
+'<Caption text="CREDIT SCORE" />'
+'</Options>'
+'<NumberFormatter id="numFmt" precision="0"/>'
+'<HalfCircularGauge frameType="flat" trackLabelStyleName="trackText" minimumAngle="180" 
maximumAngle="360" minimum="0" maximum="100" interval="20" minorInterval="20" 
formatter="{numFmt}" tickGap="0" padding="-120" showValueLabel="false" 
tickLabelStyleName="tickText" valueLabelStyleName="valueText" 
dataTipJsFunction="dataTipFunction" editMode="true" liveDragging="true" 
showDataTip="true" needleThickness="30" pointThickness="2" needleLengthRatio="0.65" 
needlePointStyle="steeple" needleBackLengthRatio="0" showTickLabels="false" 
tickLabelPosition="inside" showTrackColor="true" trackColors=" 
[#FF4500,#FF8000,#EEEE00,#00CD00,#008000]" trackAlphas="[1,1,1,1,1]" trackValues="[' + 
trackValues.toString() + ']" trackInnerRadius="0.35" trackOuterRadius="1" 
bounceAnimating="true" majorTickType="line" tickRadius="98" needleCoverRadius="15" 
trackLabels="[' + trackLabels.toString() + ']" trackLabelsXOffset=" 
[-1.3,-0.8,-0.2,0.5,0.8]" trackLabelsYOffset="[0.2,-0.8,-1.35,-0.8,0.2]" 
needleTrackColorEnable="true">'
+'<stroke>'
+'<Stroke color="#CCCCCC" weight="1" alpha="0.5"/>'
+'</stroke>'
+'<frameStroke>'
+'<Stroke color="#ffffff" weight="40" alpha="0"/>'
+'</frameStroke>'
+'<tickStroke>'
+'<Stroke color="#ffffff" weight="2"/>'
+'</tickStroke>'
+'<frameFill>'
+'<SolidColor color="#B3B3B3"/>'
+'</frameFill>'
+'<needleFill>'
+'<SolidColor color="#555555"/>'
+'</needleFill>'
+'<needleStroke>'
+'<SolidColor color="#555555"/>'
+'</needleStroke>'
+'<needleCoverStroke>'
+'<Stroke color="#555555" weight="12"/>'
+'</needleCoverStroke>'
+'</HalfCircularGauge>'
+'<Style>'
+'.tickText{fontSize:15;color:0xFF6600;}'
+'.trackText{fontSize:25;color:#171717;fontWeight:bold;}'
+'</Style>'
+'</KoolChart>';

var chartData = [70];

function dataTipFunction(str) {
return "<font color='#FF2200'>Value: " + Math.round(str) + "</font>";
}

https://codepen.io/anuygen/pen/zYppyWR