Fabricjs panel containing text boxes should allow for editing text

I have built a panel using fabricjs that contains a list.

enter image description here

Every item is a text, and each text can be edited. The user can move the entire panel on the canvas. See codepen.

The code allows you to edit items (by double-clicking on them in the example, but mousedown would suffice), but the textboxes do not behave as expected for a fabric.js textbox. The cursor only appears at the beginning or end of the textbox, I cannot position the cursor in the middle of the box.

I simply want the user to be able to edit the text on the textboxes by clicking on them, and at the same time, allow the user to move the panel, but seems I am overcomplicating things.

It seems to me I should not be calling “enterEditing” myself, just let the events reach the textbox, see code:

items.forEach((item) => {
  let text = createTextItem(item.text, currentTop, 10);
  text.on("mousedblclick", function (e) {
    this.enterEditing();
    canvas.add(text).setActiveObject(text);
  });
  texts.push(text);
  currentTop += text.height + 5;
});

Is there an alternative way of doing this?

My questions of my javascript quiz won’t show in the website [closed]

I have a project for school where I have to do a HTML quizz using Javascript. I watched a ytb video and copied the code but it wont work like it works in the video, I have checked the code and I didnt see errors can somebody help me ?
Here is the video : https://youtu.be/WiLTsxjCmWQ

let timeLeft = document.querySelector(".time-left");
let quizcontainer = document.getElementById("container");
let nextBtn = document.getElementById("next-button");
let countOfQuestion = document.querySelector(".number-of-question");
let displayContainer = document.getElementById("display-container");
let scoreContainer = document.querySelector(".score-container");
let restart = document.getElementById("restart");
let userscore = document.getElementById("user-score");
let startScreen = document.querySelector(".start-screen");
let startButton = document.getElementById("start-button");
let questionCount;
let scoreCount = 0;
let count = 11;
let countdown;


const quizArray = [{
    id: "0",
    question: "HTML stands for ________",
    options: [
      "HighText Machine Language",
      "HyperText and links Markup Language",
      "HyperText Markup Language",
      "Higher Than Snoop Dogg",
    ],
    correct: "HyperText Markup Language",
  },
  {
    id: "1",
    question: "Which of the folowing element is responsible for making the text bold in HTML",
    options: [
      "<pre>",
      "<a>",
      "<b>",
      "<br>",
    ],
    correct: "<b>",
  },
  {
    id: "2",
    question: "which of the following tag is used for iinserting the largest heading in HTML",
    options: [
      "<h3>",
      "<h1>",
      "<h5>",
      "<h6>",
    ],
    correct: "<h1>",
  },
  {
    id: "3",
    question: "Which of the following tag is used to insert a break-line in HTML",
    options: [
      "<br>",
      "<a>",
      "<pre>",
      "<b>",
    ],
    correct: "<br>",
  },
  {
    id: "4",
    question: "Which of the following attribute is used to provide a unique name to an element ?",
    options: [
      "class",
      "id",
      "type",
      "Higher Than Snoop Dogg",
    ],
    correct: "id",
  },
  {
    id: "5",
    question: "The main computer that stores the files that can be sent to computers that are networked together is:",
    options: [
      "Clip art",
      "Mother Board",
      "Peripheral",
      "File server",
    ],
    correct: "File server",
  },
  {
    id: "6",
    question: "How can you catch a computer virus ?",
    options: [
      "Sending e-mail messages",
      "Using a laptop during the winter",
      "Opening e-mail attatchments",
      "Smoking salsa with the D O double G",
    ],
    correct: "Opening e-mail attachtments",
  },
  {
    id: "7",
    question: "Google (www.google.com) is a :",
    options: [
      "Search Engine",
      "Number in Math",
      "HyperText Markup Language",
      "Directory of images",
    ],
    correct: "Search Engine",
  },
  {
    id: "8",
    question: "Which is not an Internet protocol",
    options: [
      "HTTP", "FTP", "STP", "IP",
    ],
    correct: "IP",
  },
  {
    id: "9",
    question: "Which of the following is not a valid domain name?",
    options: [
      "www.yahoo.com",
      "www.yahoo.co.uk",
      "www.com.yahoo",
      "www.yahoo.co.in",
    ],
    correct: "www.com.yahoo",
  },
];

restart.addEventListener("click", () => {
  initial();
  displayContainer.classList.remove("hide");
  scoreContainer.classList.add("hide");
});

nextBtn.addEventListener("click", (displayNext = () => {
  questionCount += 1;

  if (questionCount == quizArray.length) {
    displayContainer.classList.add("hide");
    scoreContainer.classList.remove("hide");
    userScore.innerHTML = "Your Score is " + scoreCount + "out of " + questionCount;
    scoreCount + " out of " + questionCount;
  } else {
    countOfQuestion.innerHTML = questionCount + 1 + "of " + quizzArray.length + " Question";

    quizDisplay(questionCount);
    count = 11;
    clearInterval(countdown);
    timerDisplay();
  }
}));

const timerDisplay = () => {
  countdown = setInterval(() => {
    count--;
    timeLeft.innerHTML = `${count}s`;
    if (count == 0) {
      clearInterval(countdown);
      displayNext();
    }
  }, 1000)
};

const quizDisplay = (questionCount) => {
  let quizCards = document.querySelectorAll(".container-mid");

  quizCards.forEach((card) => {
    card.classList.add("hide");
  });
  quizCards[questionCount].classList.remove("hide");
};

function quizCreater() {
  quizArray.sort(() => Math.random() - 0.5);

  for (let i of quizArray) {
    i.options.sort(() => Math.random() - 0.5);
    let div = document.createElement("div");
    div.classList.add("container-mid", "hide");

    countOfQuestion.innerHTML = 1 + " of " + quizArray.length + " Question";

    let question_DIV = document.createElement("p");
    question_DIV.classList.add("question");
    question_DIV.innerHTML = i.question;
    div.appendChild(question_DIV);

    div.innerHTML += ` 
        <button class="option-div" onclick="checker(this)">
        ${i.options[0]}</button>
        <button class="option-div" onclick="checker(this)">
        ${i.options[1]}</button>
        <button class="option-div" onclick="checker(this)">
        ${i.options[2]}</button>
        <button class="option-div" onclick="checker(this)">
        ${i.options[3]}</button>
        `;

    quizContainer.appendChild(div);
  }
}

function checker(userOption) {
  let userSolution = userOption.innerText;
  let question = document.getElementsByClassName("container-mid")[questionCount];
  let option = question.querySelectorAll(".option-div");

  if (userSolution === quizArray[questionCount].correct) {
    userOption.classList.add("correct");
    scoreCount++;
  } else {
    userOption.classList.add("incorrect");

    options.forEach((element) => {
      if (element.innerText = quizArray[questionCount].correct) {
        element.classList.add("correct");
      }
    })
  }

  clearInterval(countdown);
  options.forEach((element) => {
    element.disabled = true;
  });
}

function initial() {
  quizContainer.innerHTML = "";
  questionCount = 0;
  scoreCount = 0;
  scoreCount = 0;
  count = 11;
  clearInterval(countdown);
  timerDisplay();
  quizcreator();
  quizDisplay(questionCount);
}

startButton.addEventListener("click", () => {
  startScreen.classList.add("hide");
  displayContainer.classList.remove("hide");
  initial();
});

window.onload = () => {
  startScreen.classList.remove("hide");
  displayContainer.classList.add("hide");
};
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}

body {
  height: 100vh;
  background-color: #1d2630;
}

.start-screen,
.score-container {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

button {
  border: none;
  outline: none;
  cursor: pointer;
}

#start-button,
#restart {
  font-size: 1.33em;
  padding: 0.5em 1.8em;
  border-radius: 0.2em;
  box-shadow: 0 20px 30px rgba(0, 0, 0, 0.4);
}

#restart {
  margin-top: 0.9em;
}

#display-container {
  background-color: #fff;
  padding: 3.1em 1.8em;
  width: 80%;
  max-width: 37.5em;
  margin: 0 auto;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  border-radius: 0.6em;
}

.header {
  margin-bottom: 1.8em;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0.6em;
  border-bottom: 0.1em solid #c0bfd2;
}

.timer-div {
  background-color: #e1f5fe;
  width: 7.5em;
  border-radius: 1.8em;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.7em 1.8em;
}

.question {
  margin-bottom: 1.25em;
  font-weight: 600;
}

.option-div {
  font-size: 0.9em;
  width: 100%;
  padding: 1em;
  margin: 0.3em 0;
  text-align: left;
  outline: none;
  background: transparent;
  border: 1px solid #c0bfd2;
}

.option-div:disabled {
  color: #000;
  cursor: not-allowed;
}

#next-button {
  font-size: 1em;
  margin-top: 1.5em;
  background-color: #1d2630;
  color: #fff;
  padding: 0.7em 1.8em;
  border-radius: 0.3em;
  float: right;
  box-shadow: 0px 20px 40px rgba(0, 0, 0, 0.3);
}

.hide {
  display: none;
}

.incorrect {
  background-color: #ffdde0;
  color: #d32f2f;
  border-color: #d32f2f;
}

.correct {
  background-color: #ffdde0;
  color: #689f38;
  border-color: #689f68;
}

#user-score {
  font-size: 1.5em;
  color: #fff;
}
<div class="start-screen">
  <button id="start-button">Start</button>
</div>
<div id="display-container">
  <div class="header">
    <div class="number-of-count">
      <span class="number-of-question">
                   1 of 10 questions 
                </span>
    </div>
    <div class="timer-div">
      <img src="clock.png" alt="clock" width="20px">
      <span class="time-left">10s</span>
    </div>
  </div>
  <div id="container">

  </div>
  <button id="next-button">Next</button>
</div>
<div class="score-container hide">
  <div id="user-score">Demo Score</div>
  <button id="restart">Restart</button>
</div>

I put the questions and it should’ve showed on the screen but it didn’t

Parsing a funky JSON response by JavaScript

I am developing an voice to text application. I am using Vue 3 and axios for requests in frontend and Laravel as a backend. I’ve successfully made a recording and sent it to my backend endpoint where I make a request to the Watson Speech To Text API and then respond back with the results.
The problem is that as a response I get a funky JSON object, which I can not parse.
Frontend code:

const prepareRecording = (chunks) => {
        const mimeType = mediaRecorder.value.mimeType;
        const audioBlob = new Blob(chunks, { type: mimeType });

        const reader = new FileReader();
        reader.readAsDataURL(audioBlob);

        reader.onload = () => {
            const recording = reader.result;

            const data = { audio: recording, mimeType };
            
            fetchAndSetTranscription(data);

            mediaRecorder.value = null;
        };
};

const fetchAndSetTranscription = async (data) => {
   const response = await axios.request({
       baseURL: 'http://www.dev-voice-to-text.lv/api',
       url: '/voice-to-text',
       method: 'POST',
       data,
       headers: {
           'Content-Type': 'application/json',
           'Accept': 'application/json',
           'Access-Control-Allow-Origin': '*'
       },
});

  const results = JSON.parse(response.data).results;
};

When trying to parse the JSON returned I get this error: SyntaxError: “[object Object]” is not valid JSON.

The JSON returned:

{
    "data": "{n   "result_index": 0,n   "results": [n      {n         "final": true,n         "end_of_utterance": "silence",n         "alternatives": [n            {n               "transcript": "hello ",n               "confidence": 0.2n            },n            {n               "transcript": "yeah hello "n            },n            {n               "transcript": "so "n            }n         ]n      }n   ]n}"
}

My backend code:

        $config = Config::get('watson');

        $locale = 'en_GB';
        $languageModel = $config['language_models'][$locale];

        $data = json_decode(json_encode($request->all()));

        $recordingStr = str_replace("data:{$data->mimeType};base64,", "", $data->audio);
        $recording = base64_decode($recordingStr);

        $storagePath = storage_path('app/data/upload/voice-to-text');

        if (!file_exists($storagePath)) {
            mkdir($storagePath, 0777, true);
        }

        $fileExtension = explode("/", $data->mimeType)[1];
        $fileName = $storagePath . '/' . Uuid::uuid4()->toString() . ".{$fileExtension}";
        
        if (!file_put_contents($fileName, $recording)) {
            throw new RuntimeException('Failed to store file');
        }

        $path = $fileName;
        $file = file_get_contents($path);

        /** @var GuzzleClient $client */
        $client = new GuzzleClient([
            'base_uri' => $config['base_url']
        ]);

        try {
            $apiRequest = new GuzzleHttpPsr7Request("POST", $config['client_url'] . $config['method']);
            $apiRequestParams = [
                'auth' => ['apikey', $config['key']],
                'headers' => [
                    'Content-Type' => $data->mimeType
                ],
                'query' => [
                    'model' => $languageModel,
                    'background_audio_suppression' => $config['options']['background_audio_suppression'],
                    'split_transcript_at_phrase_end' => $config['options']['split_transcript_at_phrase_end'],
                    'smart_formatting' => $config['options']['smart_formatting'],
                    'max_alternatives' => $config['options']['max_alternatives']
                ],
                'body' => $file
            ];

            $response = $client->send($apiRequest, $apiRequestParams);
            $results = $response->getBody()->getContents();

            unlink($path);

            return response()->json([
                'data' => $results,
            ]);
        } catch (Exception $e) {
            throw $e;
        }

What could I do so that I can parse the JSON normally (get an correct JS object)?

Efficiently Embedding Long Text Input for OpenAI API in Node.js

I’m developing an API in Node.js that utilizes the OpenAI API to summarize long responses. However, I’m encountering issues with token size and cost optimization due to the length of the text input. I’ve heard about embedding the input text into a vector to mitigate these issues, but I’m struggling to find a suitable solution in JavaScript.

Could someone provide guidance or examples on how to efficiently embed long text inputs for the OpenAI API in Node.js? Any insights on best practices or libraries that can help with this task would be greatly appreciated.

Thank you!

I tried implementing using llama,
I am expecting like, How can I provide long response to ChatGpt open, AI, whithout exceeding token size

Longest commong Substring from multiple strings

    let lcs = (s, t) => {
        let dp = Array.from({ length: s.length + 1 }, () => Array.from({ length: t.length + 1      }, () => 0));
        let maxLen = 0, endIndexS = 0, endIndexT = 0;

        for (let i = 1; i <= s.length; i++) {
            for (let j = 1; j <= t.length; j++) {
                if (s[i - 1] === t[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if (dp[i][j] > maxLen) {
                        maxLen = dp[i][j];
                        endIndexS = i;
                        endIndexT = j;
                    }
                }
            }
        }

        if (maxLen === 0) return ''; // If no common subsequence found

        return s.substring(endIndexS - maxLen, endIndexS);
    };

    let args = process.argv.slice(2);
    if (args.length === 0) {
        console.log('');
    } else {
        let result = args[0];
        for (let i = 1; i < args.length; i++) {
            result = lcs(result, args[i]);
            if (result === '') break;
        }
        console.log(result);
    }

I have written the above code where i had to take input from terminal and print the longest substring..it’s working for some test cases ..But the test cases like this : ZZZABXXX XXXYYYAB ABYYYZZZ is not working as it’s suppose to output AB it’s returning empty string..

Clack Stack And 3 loaded guns [closed]

As soon as we have the final value of instructionLen, we allocate the instruction []byte and add the Opcode as its first byte – by casting it into one. Then comes the tricky part: we iterate over the defined OperandWidths, take the matching element from operands and put it in the instruction. We do that by using a switch statement with a different method for each operand, depending on how wide the operand is.

The Smallest Compiler Now that we have a toolbox called code, we can start working on the compiler. Since we want a system that works from end to end as soon as possible, and not a system that can only be turned on once it’s feature-complete, our goal in this section is to build the smallest possible compiler. It should only do one thing for now: produce two OpConstant instructions that later cause the VM to correctly load the integers 1 and 2 on to the stack. In order to achieve that, this minimal compiler has to do the following: traverse the AST we pass in, find the *ast.IntegerLiteral nodes, evaluate them by turning them into *object.Integer objects, add the objects to the constant pool, and finally emit OpConstant instructions that reference the constants in said pool.

package compiler import ( “monkey/ast” “monkey/code” “monkey/object” ) type Compiler struct { instructions code.Instructions constants []object.Object } func New() *Compiler { return &Compiler{ instructions: code.Instructions{}, constants: []object.Object{}, } } func (c *Compiler) Compile(node ast.Node) error { return nil } func (c *Compiler) Bytecode() *Bytecode { return &Bytecode{ Instructions: c.instructions, Constants: c.constants, } } type Bytecode struct { Instructions code.Instructions Constants []object.Object }

ut I bet the thing that caught your eye immediately is the definition we’ve been looking for earlier, in the code package: Bytecode! There it is and it doesn’t need a lot of explanation. It containsdijeljenje

    List<Data> lista = new Vector<>();

    int duzina = data.size();

    String zadnje = String.valueOf(data.get(duzina - 1).getKey());

    int broj = Integer.parseInt(zadnje.substring(1));

    

    for(int i = 0; i < broj; i++) {

        double a = (double)data.get(i).getValue();

        for(int j = i + broj; j < duzina; j+= broj) {

            a /= (double)data.get(j).getValue();

        }

        lista.add(new Data("n" + (i + 1), a));

    }

    return lista;

What’s happening here doesn’t take long to explain: we take Monkey code as input, we parse it, produce an AST, hand it to the compiler and then make assertions about the bytecode the compiler produced. We do that by constructing a compilerTestCase in which we define the input, which constants we expect in the constant pool and which instructions we expect the compiler to generate. Then we hand the tests slice with the compilerTestCases to runCompilerTests to run them. That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.MnozenjeHelper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book.

List lista = new Vector<>();

    int duzina = data.size();

    String zadnje = String.valueOf(data.get(duzina - 1).getKey());

    int broj = Integer.parseInt(zadnje.substring(1));

    char slovo = zadnje.charAt(0);

    int brojSlova = (int)slovo - 96;

    int limit = (broj * 3) * (brojSlova - 1);

    int brojac = 0;



    for(int i = limit; i < duzina; i++) {

        double c = (double)data.get(i).getValue();

        double rez = 1;

        for(int j = brojac; j < limit; j += (3 * broj)) {

            double a = (double)data.get(j).getValue();

            double b = (double)data.get(j + 1).getValue();

            double d = (double)data.get(j + 2).getValue();

            rez *= zagrada(a, b, d);

        }

        rez *= c;

        lista.add(new Data("n" + (i - (limit - 1)), rez));

        brojac += 3;

    }

    return lista;

That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.Helper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book. Now, let’s talk about the helpers used in runCompilerTests. The parse function contains some of the things we built in the first book: the lexer and the parser. We hand it a string and Oduzimanjeget back an AST: That’s the prelude. The main part of runCompilerTests revolves around the two fields of the Bytecode the compiler produced. First, we want to make sure tha

That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.Helper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book. Now, let’s talk about the helpers used in runCompilerTests.

List lista = new Vector<>();

    int duzina = data.size() - 1;

    String zadnje = String.valueOf(data.get(duzina).getKey());

    char slovo = zadnje.charAt(0);

    int brojSlova = (int)slovo - 96;

    

    for(int i = 0; i < duzina + 1; i += brojSlova) {

        double a = (double)data.get(i).getValue();

        for(int j = i + 1; j <  i + brojSlova; j++) {

            double b = (double)data.get(j).getValue();

            a -= b;

        }

        lista.add(new Data("n", a));

    }

    return lista;

As soon as we have the final value of instructionLen, we allocate the instruction []byte and add the Opcode as its first byte – by casting it into one. Then comes the tricky part: we iterate over the defined OperandWidths, take the matching element from operands and put it in the instruction. We do that by using a switch statement with a different method for each operand, depending on how wide the operand is.

The Smallest Compiler Now that we have a toolbox called code, we can start working on the compiler. Since we want a system that works from end to end as soon as possible, and not a system that can only be turned on once it’s feature-complete, our goal in this section is to build the smallest possible compiler. It should only do one thing for now: produce two OpConstant instructions that later cause the VM to correctly load the integers 1 and 2 on to the stack. In order to achieve that, this minimal compiler has to do the following: traverse the AST we pass in, find the *ast.IntegerLiteral nodes, evaluate them by turning them into *object.Integer objects, add the objects to the constant pool, and finally emit OpConstant instructions that reference the constants in said pool.

package compiler import ( “monkey/ast” “monkey/code” “monkey/object” ) type Compiler struct { instructions code.Instructions constants []object.Object } func New() *Compiler { return &Compiler{ instructions: code.IPotencije{}, constants: []object.Object{}, } } func (c *Compiler) Compile(node ast.Node) error { return nil } func (c *Compiler) Bytecode() *Bytecode { return &Bytecode{ Instructions: c.instructions, Constants: c.constants, } } type Bytecode struct { Instructions code.Instructions Constants []object.Object }

    List<Data> lista = new Vector<>();

    int duzina = data.size();

    String zadnje = String.valueOf(data.get(duzina - 1).getKey());

    char slovo = zadnje.charAt(0);

    int brojSlova = (int)slovo - 96;

    for(int i = 0; i < duzina; i += brojSlova) {

        double rez = 0;

        for(int j = i; j < i + brojSlova; j++) {

            double a = (double)data.get(j).getValue();

            double zbir = 0;

            for(int k = i; k < i + brojSlova; k++) {

                double b = (double)data.get(k).getValue();

                if(k != j) {

                    zbir += b;

                }

            }

            rez += Math.pow(a, zbir);

        }

        lista.add(new Data("n", rez));

    }

    return lista;

That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.Helper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book. Now, let’s talk about the helpers used in runCompilerTests. The parse function contains some of the things we built in the first book: the lexer and the parser. We hand it a string and Sabiranjeget back an AST: That’s the prelude. The main part of runCompilerTests revolves around the two fields of the Bytecode the compiler produced. First, we want to make sure tha

That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.Helper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book. Now, let’s talk about the helpers used in runCompilerTests.

List lista = new Vector<>();

    int duzina = data.size();

    for(int i = 0; i < 3; i++) {

        double a = (double)data.get(i).getValue();

        for(int j = i + 3; j < duzina; j += 3) {

            a += (double)data.get(j).getValue();

        }

        lista.add(new Data("n" + (i + 1), a));

    }

    return lista;

As soon as we have the final value of instructionLen, we allocate the instruction []byte and add the Opcode as its first byte – by casting it into one. Then comes the tricky part: we iterate over the defined OperandWidths, take the matching element from operands and put it in the instruction. We do that by using a switch statement with a different method for each operand, depending on how wide the operand is.

The Smallest Compiler Now that we have a toolbox called code, we can start working on the compiler. Since we want a system that works from end to end as soon as possible, and not a system that can only be turned on once it’s feature-complete, our goal in this section is to build the smallest possible compiler. It should only do one thing for now: produce two OpConstant instructions that later cause the VM to correctly load the integers 1 and 2 on to the stack. In order to achieve that, this minimal compiler has to do the following: traverse the AST we pass in, find the *ast.IntegerLiteral nodes, evaluate them by turning them into *object.Integer objects, add the objects to the constant pool, and finally emit OpConstant instructions that reference the constants in said pool.

package compiler import ( “monkey/ast” “monkey/code” “monkey/object” ) type Compiler struct { instructions code.Instructions constants []object.Object } func New() *Compiler { return &Compiler{ instructions: code.ISuma{}, constants: []object.Object{}, } } func (c *Compiler) Compile(node ast.Node) error { return nil } func (c *Compiler) Bytecode() *Bytecode { return &Bytecode{ Instructions: c.instructions, Constants: c.constants, } } type Bytecode struct { Instructions code.Instructions Constants []object.Object }

    List<Data> lista = new Vector<>();

    int duzina = data.size();

    String zadnje = String.valueOf(data.get(duzina - 1).getKey());

    int broj = Integer.parseInt(zadnje.substring(1));

    

    int limit = duzina - (broj * 3);

    int brojac = 0;

    for(int i = limit; i < duzina; i += 3) {

        double a = (double)data.get(i).getValue();

        double b = (double)data.get(i + 1).getValue();

        double c = (double)data.get(i + 2).getValue();

        a = Math.max(a, b);

        a = Math.max(a, c);

        double rez = 0;

        for(int j = brojac; j < limit; j+=3) {

            rez += (double)data.get(j).getValue();

        }

        rez *= a;

        lista.add(new Data("n", rez));

        brojac++;

    }

    

    

    return lista;

As soon as we have the final value of instructionLen, we allocate the instruction []byte and add the Opcode as its first byte – by casting it into one. Then comes the tricky part: we iterate over the defined OperandWidths, take the matching element from operands and put it in the instruction. We do that by using a switch statement with a different method for each operand, depending on how wide the operand is.

The Smallest Compiler Now that we have a toolbox called code, we can start working on the compiler. Since we want a system that works from end to end as soon as possible, and not a system that can only be turned on once it’s feature-complete, our goal in this section is to build the smallest possible compiler. It should only do one thing for now: produce two OpConstant instructions that later cause the VM to correctly load the integers 1 and 2 on to the stack. In order to achieve that, this minimal compiler has to do the following: traverse the AST we pass in, find the *ast.IntegerLiteral nodes, evaluate them by turning them into *object.Integer objects, add the objects to the constant pool, and finally emit OpConstant instructions that reference the constants in said pool.

package compiler import ( “monkey/ast” “monkey/code” “monkey/object” ) type Compiler struct { instructions code.Instructions constants []object.Object } func New() *Compiler { return &Compiler{ instructions: code.ITest{}, constants: []object.Object{}, } } func (c *Compiler) Compile(node ast.Node) error { return nil } func (c *Compiler) Bytecode() *Bytecode { return &Bytecode{ Instructions: c.instructions, Constants: c.constants, } } type Bytecode struct { Instructions code.Instructions Constants []object.Object }

@Test

void djeljenjeTest()

{

    

    Calculate calc = new Calculate(property.get("dijeljenje"));

    A4Strategy str = new A4Strategy();

    List<Data> calculated = calc.calculate(str.readFile(property.get("dijeljenje").path().toString()));



    List<Data> testData = property.get("dijeljenje").testData();

    for(int i=0; i<testData.size(); i++) {

        assertEquals((double)testData.get(i).getValue(), (double)calculated.get(i).getValue(), 0.000001);

    }

    

    

}

That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.Helper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book. Now, let’s talk about the helpers used in runCompilerTests. The parse function contains some of the things we built in the first book: the lexer and the parser. We hand it a string and Mainback an AST: That’s the prelude. The main part of runCompilerTests revolves around the two fields of the Bytecode the compiler produced. First, we want to make sure tha

That’s a slightly different approach to constructing tests compared to the first book. The reason for that is Go 1.9, which introduced the wonderful t.Helper method. t.Helper, which we call in runCompilerTests, allows us to remove duplicated logic in test functions by defining test helpers. Think of it as inlining runCompilerTests into TestIntegerArithmetic. That in turn allows to abstract away the common behaviour shared by every compiler test we’re going to write, which greatly reduces the noise in every test function and the page count of this book. Now, let’s talk about the helpers used in runCompilerTests.

public static void main(String[] args) {

    // TODO Auto-generated method stub

    Parser a3 = new Parser();

    List<Data> list = new Vector<Data>();

    Suma potencije = new Suma();

    list = potencije.calculate(a3.readFile("files/data_a7_suma.txt"));

    for (Data data : list) {

        System.out.println(data.getKey() + " " + data.getValue());

    }

}

As soon as we have the final value of instructionLen, we allocate the instruction []byte and add the Opcode as its first byte – by casting it into one. Then comes the tricky part: we iterate over the defined OperandWidths, take the matching element from operands and put it in the instruction. We do that by using a switch statement with a different method for each operand, depending on how wide the operand is.

The Smallest Compiler Now that we have a toolbox called code, we can start working on the compiler. Since we want a system that works from end to end as soon as possible, and not a system that can only be turned on once it’s feature-complete, our goal in this section is to build the smallest possible compiler. It should only do one thing for now: produce two OpConstant instructions that later cause the VM to correctly load the integers 1 and 2 on to the stack. In order to achieve that, this minimal compiler has to do the following: traverse the AST we pass in, find the *ast.IntegerLiteral nodes, evaluate them by turning them into *object.Integer objects, add the objects to the constant pool, and finally emit OpConstant instructions that reference the constants in said pool.

package compiler import ( “monkey/ast” “monkey/code” “monkey/object” ) type Compiler struct { instructions code.Instructions constants []object.Object } func New() *Compiler { return &Compiler{ instructions: code.Instructions{}, constants: []object.Object{}, } } func (c *Compiler) Compile(node ast.Node) error { return nil } func (c *Compiler) Bytecode() *Bytecode { return &Bytecode{ Instructions: c.instructions, Constants: c.constants, } } type Bytecode struct { Instructions code.Instructions Constants []object.Object }

So i tried thos
But then i tried that

JavaScript runs last function on script when key pressed (question regarding using key presses to show specific divs)

I’m doing a slideshow based on divs and arrow keys, code below:

document.addEventListener("keydown", function (e) {
  if ($("#div-1").css("display") == "block") {
    if (e.keyCode == 39) {
      var AF = document.getElementById("div-1");
      AF.style.display = "none";
      var AG = document.getElementById("div-2");
      AG.style.display = "block";
    }
  }
  if ($("#div-2").css("display") == "block") {
    if (e.keyCode == 37) {
      var AH = document.getElementById("div-2");
      AH.style.display = "none";
      var AI = document.getElementById("div-1");
      AI.style.display = "block";
    }
  }
});

if ($("#div-2").css("display") == "block") {
  document.addEventListener("keydown", function (e) {
    if (e.keyCode == 39) {
      var AJ = document.getElementById("div-2");
      AJ.style.display = "none";
      var AK = document.getElementById("div-3");
      AK.style.display = "block";
    }

    if ($("#div-3").css("display") == "block") {
      if (e.keyCode == 37) {
        var AL = document.getElementById("div-3");
        AL.style.display = "none";
        var AM = document.getElementById("div-2");
        AM.style.display = "block";
      }
    }
  });
}

but when I pressed the right arrow key, it just jumps to div-3 (expecting it to go to div-2 from div-1). Not sure about the left arrow key, but I tried and it goes to div-2. Is there any solution to this?

Uncaught TypeError: Cannot read properties of undefined (reading ‘network’) in devtools extension [duplicate]

enter image description here

Here is the manifest.json:

{
  "manifest_version": 3,
  "name": "Your Extension Name",
  "version": "1.0",
  "description": "Description of your extension",
  "background": {
    "service_worker": "background.js"
  },
  "devtools_page": "devtools.html"
}

I’m trying to follow https://betterprogramming.pub/chrome-extension-intercepting-and-reading-the-body-of-http-requests-dd9ebdf2348b to create a devtools panel in order to grab the response of a specific post request on a website. I’ve started with the instructions in the second part of the article, to create a basic devtools panel (which appears to work). I now want to add to it a background.js script to access the completed requests via “chrome.devtools.network.onRequestFinished” :

chrome.devtools.network.onRequestFinished.addListener(function(request) {
    var response = request.response;
    if (response && response.content && response.content.mimeType) {
    if (response.content.mimeType.includes("text")) {
        response.getContent(function(body, encoding) {
        console.log("Response body:", body);
        });
    } else {
        response.getContent(function(body, encoding) {
        var text = new TextDecoder(encoding).decode(body);
        console.log("Response body:", text);
        });
    }
    }
  });  

I’ve added it in the extension root directory (screenshot). When I try to load it unpacked at chrome://extensions I get the title error. What am I doing wrong?

enter image description here

React. js ” code: ‘MODULE_NOT_FOUND’, requireStack: [ ]” issue that prevent localhost to connect

I am a very beginner here learning React. I tried doing a react project with Vite. This is what I did:

1- Create a folder on Desktop, named it “react”.
2- Open the folder in VScode.
3- Open the terminal (ctrl + J).
4- Type npm create vite@latest reactjobs, where reactjobs is the projct’s name.
5- I chose React framework and plain JavaScript.
6- Typed: cd reactjobs then npm install waited a bit, then npm run dev.

And here is the issue… when everything seems to work right, the localhost refuses to connect in both edge and chrome browsers, giving this error displayed on my browser:
This site can’t be reached,
localhost refused to connect.
Try:
Checking the connection.
Checking the proxy and the firewall.
ERR_CONNECTION_REFUSED

and in the terminal:

VITE v5.2.8  ready in 641 ms

➜  Local:   http://localhost:3000/
➜  Network: use --host to expose
➜  press h + enter to show help
node:internal/process/promises:289
         triggerUncaughtException(err, true /* fromPromise */);
         ^

[Failed to load PostCSS config: Failed to load PostCSS config (searchPath: C:/Users/dell/Desktop/reactvite/reactjobs): [Error] Cannot find module 'autoprefixer'
Require stack:
- C:Usersdell.postcssrc.js
Error: Cannot find module 'autoprefixer'
Require stack:
- C:Usersdell.postcssrc.js
 at Module._resolveFilename (node:internal/modules/cjs/loader:1142:15)
 at Module._load (node:internal/modules/cjs/loader:983:27)
 at Module.require (node:internal/modules/cjs/loader:1230:19)
 at require (node:internal/modules/helpers:179:18)
 at Object.<anonymous> (C:Usersdell.postcssrc.js:6:5)
 at Module._compile (node:internal/modules/cjs/loader:1368:14)
 at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
 at Module.load (node:internal/modules/cjs/loader:1205:32)
 at Module._load (node:internal/modules/cjs/loader:1021:12)
 at cjsLoader (node:internal/modules/esm/translators:366:17)] {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\Users\dell\.postcssrc.js' ]
}

Node.js v21.7.3

I tried many “solutions” but none seemed to solve the issue.

I tried:

1- updating Node.js, from their website, I downloaded the newest version.

2- messing with the vite.config.js file, adding:

server: {
    port: 3000,
  },

inside of:

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
  },
}). 

3- tried to open XAMP to check if port 3000 was used before, but it wasn’t.

4- Tried turning off the Firewall completely, then restarting the pc.

5- Tried npm install --start postcssrc.js as I saw these “solutions” on Youtube and google, nothing at all helped fixing this issue.

6- Ofcourse, I tried running npm install again, also tried npm i as well.

I still can’t open my project on the browser, I literally didn’t start coding yet, and I can’t display the project on my bowser… The weird thing is when I do npm create-react-app the server works well, but only doesn’t with npm create vite@latest

Please guide me, and thanks a lot in advance.

i am not able to show the posts on my react app,i tryed googling,chatgpt,bard but still not got the output

so i am a newbie and is trying to make a blogging site using react while watching a tutorial but i am stuck to a point where the posts are not displaying on the screen

github repo link-> https://github.com/AkshatGarg2005/blogging-site

code->

`import React from “react”;
import {Link} from “react-router-dom”;

const posts=[
{
id:1,
title:”Lorem ipsum dolor sit amet consectetur adipisicing elit”,
desc:”Lorem ipsum dolor sit amet consectetur, adipisicing elit. Itaque eos, incidunt reiciendis dolorum cumque delectus natus iure commodi, asperiores iste tempore beatae modi sunt libero nobis adipisci dignissimos voluptatem. Atque.”,
img:”https://images.pexels.com/photos/7008010/pexels-photo-7008010.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2″,
},
{
id:2,
title:”Lorem ipsum dolor sit amet consectetur adipisicing elit”,
desc:”Lorem ipsum dolor sit amet consectetur, adipisicing elit. Itaque eos, incidunt reiciendis dolorum cumque delectus natus iure commodi, asperiores iste tempore beatae modi sunt libero nobis adipisci dignissimos voluptatem. Atque.”,
img:”https://images.pexels.com/photos/6489663/pexels-photo-6489663.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2″,
},
{
id:3,
title:”Lorem ipsum dolor sit amet consectetur adipisicing elit”,
desc:”Lorem ipsum dolor sit amet consectetur, adipisicing elit. Itaque eos, incidunt reiciendis dolorum cumque delectus natus iure commodi, asperiores iste tempore beatae modi sunt libero nobis adipisci dignissimos voluptatem. Atque.”,
img:”https://images.pexels.com/photos/4230630/pexels-photo-4230630.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2″,
},
{
id:4,
title:”Lorem ipsum dolor sit amet consectetur adipisicing elit”,
desc:”Lorem ipsum dolor sit amet consectetur, adipisicing elit. Itaque eos, incidunt reiciendis dolorum cumque delectus natus iure commodi, asperiores iste tempore beatae modi sunt libero nobis adipisci dignissimos voluptatem. Atque.”,
img:”https://images.pexels.com/photos/6157049/pexels-photo-6157049.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2″,
},
];

const Home = () => {
return (

{posts.map((post) => (

<Link className=”link” to={/post/${post.id}}>

{post.title}

{post.desc}

Read More

          </div>
        </div>
      ))
      }
    </div>

    
  </div>
);

};

export default Home;`

i tryed googling, chatgpt, bard but still no help
the output i am getting isOUTPUT I AM GETTING
the output which should come is [OUTPUT WHICH SHOULD COME]enter image description here

How can I troubleshoot my react multistep form back button that does not work correctly?

function next() {
 setStep((i) => {
   if (i >= FormHeaders.length - 1) return i;
   return i + 1;
 });
}
function back() {
 setStep((i) => {
   if (i <= 0) return i;
   return i - 1;
 });
}
function onSubmit(e: FormEvent) {
 e.preventDefault();
 if (step !== FormHeaders.length - 1) return next();
 alert("Submission completed");
}
const FormHeaders = [
 "Student Information",
 "Parent Information",
 "Upload Files",
];
const StepDisplay = () => {
 if (step === 0) {
   return <StudentInfo formData={formData} setFormData={setFormData} />;
 } else if (step === 1) {
   return <ParentInfo formData={formData} setFormData={setFormData} />;
 } else {
   return <FileUpload formData={formData} setFormData={setFormData} />;
 }
};
return (
 <div className="form">
   <h2 className="form-title">Online Application</h2>
   <div className="progressbar">
     <div
       style={{
         width: step === 0 ? "33.3%" : step === 1 ? "66.6%" : "100%",
       }}
     ></div>
   </div>
   <div className="form-container">
     <h1 className="form-header">{FormHeaders[step]}</h1>
     <div className="form-body">
       <form onSubmit={onSubmit} action="#">
       {StepDisplay()}
         <div className="form-footer">
           {step !== 0 &&
             <button className="form-btn btn" onClick={back}>
               <FaAngleLeft />
             </button>
           }
           <button className="form-btn btn" type="submit">
             {step === FormHeaders.length - 1 ? (
               <i>
                 <FaRegPaperPlane />
               </i>
             ) : (
               <i>
                 <FaAngleRight />
               </i>
             )}
           </button>
         </div>
       </form>
     </div>
   </div>
 </div>
);
export default MultistepForm;

I am building a multistep form with ReactJS and Vanilla JS and I ran into a problem with my Back button. The form has 3 pages and the back button works fine until I get to the last page, I cannot go back anymore (At page 2, I can still go back to page 1, but once I get to page 3, I cannot go back to page 2 as the back button stops working).
It does not display any error.
I have tried multiple ways to define the back function, but the problem is still the same.
It was working perfectly fine, until I added the onSubmit function (I am not very sure about it).

Unable to get information from api/database to display

I am working on a project on react js and the backend is set up to get data from an api and store it in the database based on input provided, which it does when tested on postman:

postman display1

postman display2

A list of computers and specific details about each computer is displayed.

I am now trying to get it to display on the web site, such that when the user inputs the information needed on the info.js page and clicks the submit button, it takes them to the suggest.js page and displays a couple of computers based on the user input alongside a couple of information about the computer but the suggest page shows up empty. I have spent a lot of time trying to get it to work but I can’t figure out what I am doing wrong. Please help.

I expect to have something like this (tested with manually input objects):

What I have now:

I’ll provide all necessary code below.

EZ-PCTESTback-endsrcsupabasecomputerdtocreate-computer.dto.ts

export class CreateComputerDto {
    id: string;
    name: string;
    company: string;
    os: string;
    processor: {
        company: string;
        type: string;
        model: string;
    };
    display: number;
    graphics_card: {
        company: string;
        type: string;
        model: string;
    };
    ram: number;
    dimensions: {
        dimensions: string;
        weight: number;
    };
    storage: {
        space: number;
        type: string;
    };
    image: string[];
    price: number;
    tag: string[];
}


EZ-PCTESTback-endsrcsupabasecomputercomputer.controller.ts

import { Controller, Get, Param, Post, Body, Put, Delete, Query } from '@nestjs/common';
import { ComputerService } from './computer.service';
import { CreateComputerDto } from './dto/create-computer.dto';


@Controller('computer')
export class ComputerController {
    constructor(private readonly computerService: ComputerService) { }

    // Implement controller endpoints here
    @Get('api')
    async getComputers(): Promise<any> {
        return this.computerService.fetchDatatoDatabase();
    }

    @Get()
    async getUsers(@Body('min_price') min_price: string,
        @Body('max_price') max_price: string,
        @Body('student_level') student_level: string,
        @Body('hobbie') hobbie: string): Promise<any[]> {
        return this.computerService.getComputer(parseInt(min_price), parseInt(max_price), student_level, hobbie);
    }

//     // Define a new route in your computer controller to handle the POST request
// @Post()
// async suggestComputers(@Body() requestData: any): Promise<any> {
//   const { min_price, max_price, student_level, hobbie } = requestData;
//   // Process the submitted information and fetch suggested computers from the database
//   const suggestedComputers = await this.computerService.getSuggestedComputers(min_price, max_price, student_level, hobbie);
//   return suggestedComputers;
// }

}

EZ-PCTESTback-endsrcsupabasecomputercomputer.module.ts

import { Module } from '@nestjs/common';
import { ComputerService } from './computer.service';
import { ComputerController } from './computer.controller';
import { SupabaseService } from '../supabase.service';


@Module({
    providers: [ComputerService, SupabaseService],
    controllers: [ComputerController],
})
export class ComputersModule { }

EZ-PCTESTback-endsrcsupabasecomputercomputer.service.ts

import { Injectable } from '@nestjs/common';
import { SupabaseService } from '../supabase.service';
import { SupabaseClient } from '@supabase/supabase-js';
import axios from 'axios';
import { CreateComputerDto } from './dto/create-computer.dto';

@Injectable()
export class ComputerService {
    private supabase: SupabaseClient;

    constructor(private readonly supabaseService: SupabaseService) {
        this.supabase = supabaseService.getSupabaseClient();
    }

    async fetchDatatoDatabase(): Promise<any> {
        const options = {
            method: 'GET',
            url: 'https://laptopdb1.p.rapidapi.com/laptop/search',
            params: { company: 'Asus' },
            headers: {
                'X-RapidAPI-Key': '2478155a8cmshcaf03d1de7a38f0p128265jsnfe5212b1355c',
                'X-RapidAPI-Host': 'laptopdb1.p.rapidapi.com'
            }
        };

        try {
            const response = await axios.request(options);
            for (const key in response.data.result.laptops) {
                //get data from API
                const result = response.data.result.laptops[key];
                const id: string = result._id.$oid;
                const name: string = result.name;
                const company: string = result.company;
                const os: string = result.os;
                const processor = {
                    company: result.cpu.company,
                    type: result.cpu.type,
                    model: result.cpu.model
                };

                const display: number = result.screen.inches;

                const graphics_card = {
                    company: result.graphics_card.company,
                    type: result.graphics_card.type,
                    model: result.graphics_card.model
                };

                const ram: number = result.ram.amount;

                const dimensions = {
                    dimensions: result.dimensions.dimensions,
                    weight: result.dimensions.weight
                };

                const storage = {
                    space: parseInt(result.drives[0].space),
                    type: result.drives[0].type
                };

                let image = result.images;
                const price: number = result.price;
                const tag: string[] = await this.classifyComputer(processor, ram, storage, display);

                // //change image from URL to store in database
                // const data1 = await axios.get(image, { responseType: 'arraybuffer' });
                // image = Buffer.from(data1.data);

                this.createComputer({
                    id, name, company, os, processor, display, graphics_card, ram, dimensions, storage, image, price, tag
                })
            }
            return response.data;
        } catch (error) {
            throw new Error(`Error searching laptops: ${error.message}`);
        }
    }

    createComputer = async (createComputerDto: CreateComputerDto): Promise<any> => {
        const { id, name, company, os, processor, display, graphics_card, ram, dimensions, storage, image, price, tag } = createComputerDto;
        const { data, error } = await this.supabase
            .from('computer')
            .insert([{ id, name, company, os, processor, display, graphics_card, ram, dimensions, storage, image, price, tag }]);
        if (error) {
            throw error;
        }
        return data;
    }

    classifyComputer = async (processor: { company: string, type: string, model: string },
        ram: number,
        storage: { space: number, type: string },
        display: number
    ): Promise<any> => {
        let tag: string[] = [];
        if (ram === 8 && storage.space === 512 && display === 14) {
            tag.push("elementary")
        }
        if ((processor.type === 'ryzen' || processor.model.startsWith('Core i3') &&
            (ram >= 8 && ram <= 16) &&
            (storage.space >= 512 && storage.space <= 1024) &&
            (display >= 14 && display <= 15)
        )) {
            tag.push("middle_school")
        }
        if ((processor.type === 'ryzen' || processor.model.startsWith('Core i5') &&
            (ram === 16) &&
            (storage.space >= 512 && storage.space <= 1024) &&
            (display >= 15 && display <= 16)
        )) {
            tag.push("high_school")
        }
        if ((processor.type === 'ryzen' || processor.model.startsWith('Core i7') || processor.model.startsWith('Core i9') &&
            (ram >= 16) &&
            (storage.space >= 512) &&
            (display >= 15 && display <= 16)
        )) {
            tag.push("college")
        }
        if ((processor.type === 'ryzen' || processor.model.startsWith('Core i7') || processor.model.startsWith('Core i9') &&
            (ram >= 16) &&
            (storage.space >= 512) &&
            (display >= 15 && display <= 17)
        )) {
            tag.push("gaming")
        }
        if ((processor.type === 'ryzen' || processor.model.startsWith('Core i7') || processor.model.startsWith('Core i9') &&
            (ram >= 16) &&
            (storage.space >= 512) &&
            (display >= 15 && display <= 17)
        )) {
            tag.push("video_editing")
        }
        return tag;
    }

    async getComputer(min_price: number, max_price: number, student_level: string, hobbie: string): Promise<any[]> {
        const { data, error } = await this.supabase
            .from('computer')
            .select('*')
            .gte('price', min_price) // Filter by minimum price
            .lte('price', max_price) // Filter by maximum price
            .contains('tag', [student_level, hobbie])
            .limit(10);
        if (error) {
            throw error;
        }
        console.log(data)
        return data;
    }
}

EZ-PCTESTfront-endsrccomponentsInputInfo.js

import React, { useState } from 'react';
import './Info.scss'
import { Link } from "react-router-dom";
import infovid from '../../assets/infovid.mp4';
import axios from 'axios';



const Info = () => {
  const [minValue, setMinValue] = useState(0);
  const [maxValue, setMaxValue] = useState(10000);
  const [studentLevel, setStudentLevel] = useState('');
  const [hobby, setHobby] = useState('');

  const handleMinChange = (event) => {
    const value = parseInt(event.target.value);
    // Ensure minValue doesn't exceed maxValue
    if (value <= maxValue) {
      setMinValue(value);
    } else {
      setMinValue(maxValue);
    }
  };
  
  const handleMaxChange = (event) => {
    let value = parseInt(event.target.value);
    
    // Ensure maxValue doesn't go below minValue or exceed 10000
    if (value < minValue) {
      value = minValue;
    } else if (value > 10000) {
      value = 10000;
    }
  
    setMaxValue(value);
  };
  
  
  const handleStudentLevelChange = (event) => {
    setStudentLevel(event.target.value);
  };

  const handleHobbyChange = (event) => {
    setHobby(event.target.value);
  };



  // const handleSubmit = async (event) => {
  //   event.preventDefault();
  //   try {
  //     // const response = await axios.post('http://localhost:3000/users/login', userData);
  //     // Send user input to the back-end
  //     await fetch('http://localhost:3000/computers', {
  //       method: 'POST',
  //       headers: {
  //         'Content-Type': 'application/json',
  //       },
  //       body: JSON.stringify({ min_price: minValue, max_price: maxValue, student_level: studentLevel, hobbie: hobby }),
  //     });
  //     // Redirect to the Suggest page after submitting the form
  //   } catch (error) {
  //     console.error('Error submitting form:', error);
  //     // Handle error if needed
  //   }

  // };

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      // Make the fetch request to submit the form data
      await fetch('/computer', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ min_price: minValue, max_price: maxValue, student_level: studentLevel, hobby: hobby }),
      });
  
      // Redirect to the Suggest page after submitting the form
      window.location.href = "/suggest";
    } catch (error) {
      console.error('Error submitting form:', error);
      // Handle the error if needed
    }
  };
  
  
 

  return (
    <>
     <div className="container2" style={{  position: 'relative', /* Ensure proper positioning */
    height: '100vh', /* Full viewport height */
    background: 'linear-gradient(45deg, rgba(29, 236, 197, 0.7), rgba(91, 14, 214, 0.7) 100%)', /* Gradient background */}}>
      <div className="container"  /*style={{ backgroundImage: `url(${ill})` }}*/>
        <form className = "form"onSubmit={handleSubmit}>
          <div id="input" className="input">
            <p className="kind">Kindly provide the information below:</p>
            <p className="head">Budget:</p>
            <div className="price-input">
              <div className="field">
                <span>Min</span>
                <input
                  type="number"
                  className="input-min"
                  value={minValue}
                  onChange={handleMinChange}
                />
              </div>
              <div className="separator">-</div>
              <div className="field">
                <span>Max</span>
                <input
                  type="number"
                  className="input-max"
                  value={maxValue}
                  onChange={handleMaxChange}
                />
              </div>
            </div>
            {/* Slider */}
            <div className="slider">
              <div
                className="progress"
                style={{
                  width: `${((maxValue - minValue) / 10000) * 100}%`, // Assuming 10000 is the total range
                  left: `${(minValue / 10000) * 100}%`,
                }}
              ></div>
            </div>
            <div className="range-input">
              <input
                type="range"
                className="range-min"
                min="0"
                max="10000"
                value={minValue}
                onChange={handleMinChange}
              />
              <input
                type="range"
                className="range-max"
                min="0"
                max="10000"
                value={maxValue}
                onChange={handleMaxChange}
              />
            </div>
            {/* Other input fields */}
            <div id = "test">
            <p className="head">Student Level:</p>
            <select className="select" size="1" name="level" value={studentLevel} onChange={handleStudentLevelChange}>
              <option className="drop" value="">Select Student Level</option>
              <option value="Elementary">Elementary</option>
              <option value="Middle School">Middle School</option>
              <option value="High School">High School</option>
              <option value="College">College</option>
            </select>
            </div>

            <div id ="test">
            <p className="head">Other Hobbies:</p>
            <select size="1" name="hobby" value={hobby} onChange={handleHobbyChange}>
              <option className="drop" value="">Select Hobby</option>
              <option value="Gaming">Gaming</option>
              <option value="Video Editing">Video Editing</option>
            </select>
            </div>
            <div id ="test">
            <button type="submit">Submit</button>
            </div>
          </div>
        </form>

        <div className="video-container">
          <video autoPlay muted loop>
            <source src={infovid} type="video/mp4" />
          </video>
        </div>

          


       </div> 
       </div>
    </>
  );
}

export default Info;

EZ-PCTESTfront-endsrccomponentsSuggestionsSuggest.js

import React, { useState, useEffect } from 'react';
import './suggest.scss';

const Suggest = () => {
  const [computers, setComputers] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('http://localhost:3000/computer'); // Change the URL to fetch directly from the desired endpoint
        if (response.ok) {
          const data = await response.json();
          console.log(data); // Log the data to inspect its structure
          setComputers(data);
        } else {
          console.error('Error fetching data:', response.statusText);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div className="Scontainer" style={{ position: 'relative', height: '100vh', background: 'linear-gradient(45deg, rgba(29, 236, 197, 0.7), rgba(91, 14, 214, 0.7) 100%)' }}>
      <p className="Sug">Here are some suggestions for you:</p>
      <div className="d-flex justify-content-center row">
        <div className="col-md-10">
          {computers.map(computer => (
            <div key={computer.id} className="row p-2 bg-white border rounded">
              <div className="col-md-3 mt-1"><img className="img-fluid img-responsive rounded product-image" src={computer.image} alt={`${computer.brand} ${computer.model}`} /></div>
              <div className="col-md-6 mt-1">
                <h5>{computer.name} {computer.model}</h5>
                <div className="d-flex flex-row">
                  <div className="mr-3"><strong>Operating System:</strong> {computer.os}</div>
                  <div className="mr-3"><strong>Processor:</strong> {computer.processor}</div>
                  <div className="mr-3"><strong>Memory:</strong> {computer.memory}</div>
                  <div className="mr-3"><strong>Storage:</strong> {computer.storage}</div>
                  <div><strong>Display:</strong> {computer.display}</div>
                </div>
              </div>
              <div className="align-items-center align-content-center col-md-3 border-left mt-1">
                <div className="d-flex flex-row align-items-center">
                  <h4 className="mr-1">${computer.price}</h4>
                </div>
                <div className="d-flex flex-column mt-4"><button className="btn btn-primary btn-sm" type="button">Save</button><button className="btn btn-outline-primary btn-sm mt-2" type="button">Compare</button></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Suggest;

PLEASE HELP ME.

How to target Edge Dark Mode on iOS (js/css)

Microsoft Edge’s “Dark Mode” seems to go rogue on iOS. On Chrome/Safari/Firefox (iOS) & Chrome/Safari/Firefox/Edge (OSX/Windows) everything works as expected.

Ideally, I’d like Edge to not use dark mode at all. Next best would be to target Edge’s Dark Mode on iOS specifically and add some CSS overwrites. Most interestingly, I’m having trouble with the latter as well as Edge on iOS somehow doesn’t seem to listen to “prefers-color-scheme: dark” either.

Firstly, I’ve added this meta tag:

<meta name="color-scheme" content="only light">

Before I used this:

<meta name="color-scheme" content="light">

Secondly, I’ve added the following CSS (as per Chromium spec: https://developer.chrome.com/blog/auto-dark-theme):

:root {
    color-scheme: only light;
}

This works perfectly for listed environments, only Edge iOS doesn’t work.

So, I tried to overwrite this by using the following to add a css target through JS.

$(document).ready(function(){
    if (
    window.matchMedia &&
    window.matchMedia('(prefers-color-scheme: dark)').matches &&
    /EdgiOS/.test(navigator.userAgent)
  ) {
        document.body.classList.add('ios-edge-dark');
    }
});

In combination with CSS like this:

.ios-edge-dark {
        .hero-type-2 {
            .feature-icon {
                filter: $main-filter-neg;
            }
        }
}

This is where the real “fun” starts: Edge iOS is properly targetted, but somehow the second condition (window.matchMedia(‘(prefers-color-scheme: dark)’).matches) is true in Light Mode as well.

So I added a redundant media query in the CSS:

@media (prefers-color-scheme: dark) {
    .ios-edge-dark {
        .hero-type-2 {
            .feature-icon {
                filter: $main-filter-neg;
            }
        }
    }
}

At this point I’m out of ideas (and experiencing flashbacks to IE).

I did find a recent post that hints at others experiencing the same issues, but no real solution is listed:
https://learn.microsoft.com/en-us/answers/questions/1644468/inconsistent-dark-mode-behavior-in-edge-on-ios

Hopefully you guys have a solution! At this point I’m eager to get this to work, even if it includes a dirty JS-based workaround like the one I already tried. Thank you in advance!

P.S.: I tried to outline the issue as detailed as possible, to hopefully help others in the future. If you’re experiencing the same issue, feel free to share you attempts for a fix. I’m happy to add those as well.

How can I get notified when someone posts a tweet using Javascript & Twitter API? [closed]

I’m creating a discord bot using discordjs and I want it to send the link of any tweet I post in a specific channel, for simplicity please help me create a script that prints in the console the link of any tweet I post once I post it.

I tried to find source codes to learn from and read documentation but I didn’t manage to get any useful information.

(In case you know how to do it in any other programming language please leave a comment)