Forward console to channel discord.js

I am trying to forward my bot’s console to a channel in Discord. I assume I would use process.stdout to get the console output, and client.channels.cache.get(id).send() to send the message, but how do I combine the two and send that to a channel?

Any help is appreciated, cheers!

Getting a bytecode error when packaging javascript

Hey so I am trying to package my node javascript application with pkg on my mac, but I keep getting met with a codesign utility error?

**Error! Cannot generate bytecode

pkg fails to run “codesign” utility. Due to the mandatory signing
requirement of macOS, executables must be signed. Please ensure the
utility is installed and properly configured.**

Also only trying to get this as a runnable file, not put it on the mac store or anything.

Disabling a tablerow in react

When a user clicks a line on a tablerow on my website, it displays another page with a different table row. Here’s my code where I display the second mentioned table row:

        return (
            <>
            <TableRow key={this.props.rowData.dependency_id} onClick={() => this.setOpen(!this.state.isOpen)}>
                <TableCell>{this.props.rowData.name}</TableCell>
                <TableCell>{this.props.rowData.component}</TableCell>
                <TableCell>{this.props.rowData.version}</TableCell>
                <TableCell>{this.stringify_licenses(this.props.rowData.licenses)}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numLowVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numMediumVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numHighVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.numCriticalVulnerabilities}</TableCell>
                <TableCell style={{paddingRight: '2px'}}>{this.props.rowData.totalNumVulnerabilities}</TableCell>
                <TableCell>
                    {this.state.isOpen ? <FaAngleUp/> : <FaAngleDown/>}
                </TableCell>
            </TableRow>

I want to disable this table row if the line on the first table row has a certain tablecell value. How can I do this?

Why is <= returning false not true? [closed]

Hey so i have a little problem, which one is blowing my mind. maybe someone will enlighten me with this, because im done.

Here is code

function cashOut() {
  if (cashAmount.value<=cash && cashAmount.value % 50 === 0) {
        outCash.innerHTML = "Withdraw: " + cashAmount.value + "USD";
        withdrawCash = cashAmount.value;
    } else {outCash.innerHTML = "Failed to withdraw funds, the amount withdrawn must be divisible by 50 and not less than  " + cash;
    }
}

and problem is that cashAmount.value<=cash returns false not true as it should. Because your cashAmount which is amount of cash you want to withdraw, cant be bigger then your balance. I guess its stupid question but i lost my mind on this.

cash is simple variable, but cashAmount is taking value from input if that matters.

I have an error in my school javascript project

I have multiple errors in my code. When I run the code, it gives an error saying that there is an unexpected identifier. Here is the full error, “SyntaxError: Unexpected identifier at /script.js:46:16”. However, when I check through lines 46 through 16, I cant find any unclosed functions or methods. When I comment the if statement on line 46, it just gives an error on the other if statement. can someone help me.

Heres the code

function print(str){
    console.log(str)

}

function farhToKelvin(far){
    const cel = Math.floor(far / (9/5) - 32)
    const kel = cel + 273
    return kel

}

function farhToCelsius(far){
    const cel = Math.floor(far / (9/5) - 32)
    return cel

}

function convertToFarh(type, val){
    
    type.toLowerCase()
    val.toLowerCase()

    if (type == "kelvin"){
        return Math.floor(far / (9/5) - 32 - 273) 

    }
    else if(type == "celsius"){
        return Math.floor(far / (9/5) - 32)

    }

}


while (farh != "exit"){
    var farh = prompt("enter a farhanhite tempature: ")

    var type = prompt("convert it to celsius, or kelvin")

    type.toLowerCase()

    if (type == "celsius"){
        const c = farhToCelsius(farh)
        var val = convertToFarh(c)
        if (val > 50 or val == 50){
            print("it is cold, you should wear a coat")

        }
        if (val > 50 or val == 50){
            print("it is hot, you should wear a tank top")

        }

    }
    else if(type == "kelvin"){
        const k = farhToKelvin(farh)

        var val = convertToFarh(k)
        if (val > 50 or val == 50){
            print("it is cold, you should wear a coat")

        }
        if (val > 50 or val == 50){
            print("it is hot, you should wear a tank top")

        }

    }

}

Trying to upload a ScreenCapture Video (JavaScript) onto a server (Java)

i wanted to write a javascript function that records the screen of the user and saves it onto a server.

It seems to work so far and records the user-selected screen (i printed most variables into the console for testing purpose but here deleted it for clarity, the ids etc are filled), but there is a problem when i am trying to upload it.

Since i am new to JavaScript programming, i seem to be stuck now, i tried to change mimeTypes/types in ajax since i am not sure if they are used right, did not help.

I run the JavaScript frontend on a local XAMPP and the Java backend on a local WildFly.

Would be so glad if anyone got helping ideas.

The code i wrote is integrated into a existing project, i will post the snippets i wrote.

1)

 // Create Recorder

var recorder;
var stream;
var chunks = [];
var blob = new Blob;
var start_recording_timestamp ;


this.startIntegratedScreenCapture = async function () {

    start_recording_timestamp = new Date(new Date().getTime() + 3600000).toISOString(); //add 1 hour because of Berlin-Timezone

   try {
        stream = await navigator.mediaDevices.getDisplayMedia({
            video: {mediaSource: "screen"},
            mimeType: 'video/webm;codecs=h264'
        });

    recorder = new MediaRecorder(stream);

    recorder.ondataavailable = e => chunks.push(e.data);
    recorder.onstop = e => {
        let that = this;
        blob = new Blob(chunks, { type: chunks[0].type });
      
        window.repositoryService.saveVideoForModel(window.modelId, start_recording_timestamp, blob);
        that.videoSaveCallbacks.forEach(callback => callback(blob));
    };

    recorder.start();

    }
    catch(e){console.log(e)}
};
     //stop Recording



 this.stopIntegratedScreenCapture = function () {
    if (recorder) {
  recorder.stop();
  stream.getVideoTracks()[0].stop();
    }

};
  // Integrated Screen Capture



this.saveVideoForModel = function (modelID, timestamp, video_content) {

    var reader = new  FileReader();

    reader.addEventListener('loadend', (event) => {
        var videoAsJSON = event.srcElement.result;
        var videoURI = this.videoURI;

        var data = new FormData();
      data.append("data", new Blob([videoAsJSON], {type: "application/octet-stream"}));
        data.append("modelID", modelID);
        data.append("startRecTimestamp", timestamp);


        this.uploadVideo("POST", videoURI, data, function (response) {
            try {
                response = JSON.parse(response);
            } catch (event) {
            }
            if (response === null || response === "") {
                window.showMessage("Error saving the video", "error", "Error");
                return;
            }
            window.showMessage("Video of model " + modelID + " successfully saved", "success", "Success");
        },function (error){console.log(error)});

    });

    reader.readAsArrayBuffer(video_content);
};
  1. //start upload
    
    
    
    
     this.uploadVideo = function (method, url, data, success, error) {
      var errorHandler = (error != null) ? error : this.defaultErrorHandler;
      var token = this.getToken();
      url = method === "DELETE" ? url + "?" + $.param(data) : url;
    
    
      $.ajax({
          url: url,
          type: method,
          data: data,
          enctype: 'multipart/form-data',
          cache: false,
          async: true,
          processData: false,
          contentType: false,
          beforeSend: function (xhr) {
              if (token != null) {
                  xhr.setRequestHeader("Authentication", "Bearer" + token);
              }
          },
          success: success,
          error: errorHandler
      }
      ).done(function(data){console.log(data)});
    

    };

The serverside code looks like this, it uses Spring framework:

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/integrated/saveVideo", method = 
     RequestMethod.POST)
     public ResponseEntity<VideoDto> saveVideo(@RequestParam("data") 
      MultipartFile file,
                                          @RequestParam("modelID") 
      String modelID,
                                          
     @RequestParam("startRecTimestamp") String startRecTimestamp) {
    HttpStatus status = HttpStatus.OK;
    startRecTimestamp = startRecTimestamp.replaceAll(":", "_");
    String fileName = env.getProperty("screenrecording.directory") + 
    modelID + "_Model_" + startRecTimestamp;
    try (FileOutputStream fosVideo = new FileOutputStream(fileName, 
   true)){
        byte[] bytes = file.getBytes();
        fosVideo.write(bytes);
    } catch (IOException ioe) {
        status = HttpStatus.CONFLICT;
        ioe.printStackTrace();
    }
    return new ResponseEntity<>(new VideoDto(), status);
}   

When i use developer mode in firefox, i see that the program seems to fail at the axaj query (the beforeSend in the ajax gets triggered, tried it with console.log to see if token has id)

The FunctionReponse gets not triggered using uploadVideo function in saveVideoForModel since uploadVideo function ends in error.

       Status
       409
         Conflict
       VersionHTTP/1.1
   Referrer Policystrict-origin-when-cross-origin

XHRPOST../saveVideo
[HTTP/1.1 409 Conflict 610ms]

POST
…/saveVideo
Status
409
Conflict
VersionHTTP/1.1
Übertragen533 B (81 B Größe)
Referrer Policystrict-origin-when-cross-origin

HTTP/1.1 409 Conflict

Expires: 0

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

X-XSS-Protection: 1; mode=block

Pragma: no-cache

X-Frame-Options: DENY

Date: Mon, 29 Nov 2021 23:31:07 GMT

Connection: keep-alive

Access-Control-Allow-Origin: *

Vary: Origin

Vary: Access-Control-Request-Method

Vary: Access-Control-Request-Headers

X-Content-Type-Options: nosniff

Transfer-Encoding: chunked

Content-Type: application/json; charset=UTF-8








   XHRPOST.../saveVideo
   [HTTP/1.1 409 Conflict 610ms]

    
   POST
    .../saveVideo
  Status
   409
  Conflict
   VersionHTTP/1.1
  Übertragen533 B (81 B Größe)
   Referrer Policystrict-origin-when-cross-origin
        
    HTTP/1.1 409 Conflict

    Expires: 0

    Cache-Control: no-cache, no-store, max-age=0, must-revalidate

    X-XSS-Protection: 1; mode=block

    Pragma: no-cache

    X-Frame-Options: DENY

    Date: Mon, 29 Nov 2021 23:31:07 GMT

    Connection: keep-alive

    Access-Control-Allow-Origin: *

    Vary: Origin

    Vary: Access-Control-Request-Method

    Vary: Access-Control-Request-Headers

    X-Content-Type-Options: nosniff

    Transfer-Encoding: chunked

    Content-Type: application/json; charset=UTF-8
        
    POST ...saveVideo HTTP/1.1

    Host: localhost:8080

    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0

    Accept: */*

    Accept-Language: de,en-US;q=0.7,en;q=0.3

    Accept-Encoding: gzip, deflate

    Authentication: BearereyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwcm9iYW5kIiwiZXhwIjoxNjM4Mjc1ODU0fQ.dy-e-gJtD3R-UlPD9FVnJ5YQmjko7tEqS-l9ocprk9vRpCXUKjelL78mafe9zTKJlDo_c8pElbiQWKdGIbfapw

    Content-Type: multipart/form-data; boundary=---------------------------188953772220050190214011980307

    Content-Length: 1090343

    Origin: http://localhost

    Connection: keep-alive

    Referer: http://localhost/

    Sec-Fetch-Dest: empty

    Sec-Fetch-Mode: cors

    Sec-Fetch-Site: cross-site

JSON is not properly turning an object into a string

I am making a game and am working on the accounts. When i have JSON stringify the object and save it to a file, it sometimes (occasionally and at random) writes:

{"[email protected]":{"email":"[email protected]","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >}< "[email protected]":{"email":"[email protected]","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}

when i am expecting:

{"[email protected]":{"email":"[email protected]","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >,< "[email protected]":{"email":"[email protected]","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}

My Code:

fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {});

What is going on?

How Node JS Map Of Values Adds Up to K

Given a list of numbers const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];and a number k say const k = 17;, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k = 17, we should return True, since 10 + 7 =17.

Wrote below code using key,values in Map,but seems not able to get the solution,can anyone suggest what code change is needed below ,want to solve especially using Maps

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
const k = 17;
let addInput = new Map(arr.flatMap((x) => Object.entries(x)));

addInput.forEach((v) => {
  for (var i = 0; i < addInput.size; i++) {
    if (v != addInput[i]) {
      if (addInput[i] + v == k) {
        console.log(`${v} + ${addInput[i]} = ${k} (true)`);
      }
    }
  }
});

Sort by date with isotope-layout in Next js

I can’t find any documentation on how to do a date sort with isotope-layout in my Next JS project. Here is how far I have got.
The date obviosuly sorts but it will sort alphabetically. I need to know how to write this in
date: function ($elem) { return Date.parse($elem.find('.date').text()); }

const KeyOutcomes = (props) => {
  const isotope = useRef()
  const [sortKey, setSortKey] = useState('date')

  // initialize an Isotope object with configs
  useEffect(() => {
    isotope.current = new Isotope('.news', {
      itemSelector: '.newsInner',
      layoutMode: 'fitRows',
      getSortData: {
        header: '.header',
        date: '.date',
      },
    })
    // cleanup
    return () => isotope.current.destroy()
  }, [])

  // handling sort key change
  useEffect(() => {
    isotope.current.arrange({ sortBy: `${sortKey}` })
  }, [sortKey])

  const handleSortKeyChange = (key) => () => setSortKey(key)
  return (
    <div className="container">
      <div className="row">
        <div className="col-12">
          <div className="sortAndFilter">
            <ul className="sortFilter">
              <li>Sort By:</li>
              <li
                onClick={handleSortKeyChange('header')}
              >
                Header
              </li>
              <li
                onClick={handleSortKeyChange('date')}
              >
                Date
              </li>
            </ul>
          </div>
          <div className="news">
            <div className="newsInner vege">
              <div className="newsText two">
                <h3 className="header">V News Header</h3>
                <p className="date">02/05/2020</p>
              </div>
            </div>
            <div className="newsInner one">
              <div className="newsText">
                <h3 className="header">D News Header</h3>
                <p className="date">26/05/2020</p>
              </div>
            </div>
            <div className="newsInner one">
              <div className="newsText">
                <h3 className="header">G News Header</h3>
                <p className="date">10/12/2021</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

React state not updating after API request

I am making a very simple store front react app that talks to a simple backend API that I made. I am trying to make a cart system that makes a POST request using the Axios library each time the page is loaded. The API will send back a cart object and it will have a unique ID. I want to store this ID in a state so that I can pass it to other pages to track the current card.

Here is the code for the function that handles making a POST request with Axios and storing that data in the currentCartID state:

const makeAPIPOSTRequestForCart = () => {
        setAPIRequestIsLoading(true);
        Axios.post('http://localhost:5512/carts/create').then((response) => {
            setCurrentCardID(response.data._id); // <-- THIS IS THE SET METHOD FOR THE STATE
            console.log('====================================');
            console.log('STATUS: ' + response.status);
            console.log('ID: ' + response.data._id);
            console.log('STATE OBJ: ' + currentCartID); // <--- PRINTS OUT NOTHING OR UNDEFINED
            console.log('====================================');
            setAPIRequestIsLoading(false);
        });
    };

This function is called each time the page is loaded with the useEffect hook like so:

useEffect(() => {
        makeAPIGETRequest();
        if (isCartMade === false) {
            makeAPIPOSTRequestForCart(); // <--- CALL TO POST FUNCTION RIGHT HERE
            setIsCartMade(true);
        }
    }, []);

The problem is each time I make this request the API is responding with a cart object and I can view the ID, however I cant seem to set the state to the current ID which is a string. Ive made sure that the type is correct however nothing is working. Whenever I try printing the state all I get is undefined or a blank line. It seems that the update state function is not working properly.

I am quite new to react so any help would be greatly appreciated! 🙂

Ethers contract on method “No mathing event” error

I just started learning ethers, here is my code:

(async () => {
  const connection = new ethers.providers.JsonRpcProvider(
    "https://mainnet.infura.io/v3/key"
  );

  const contract = new ethers.Contract(
    "0x7be8076f4ea4a4ad08075c2508e481d6c946d12b",
    abi,
    connection
  );

  contract.on("atomicMatch_", (to, amount, from) => {
    console.log(to, amount, from);
  });
})();

so the contract is opensea main contract – link
I would like to listen to sales transactions/events. As I see in the contract name of that event is probably Atomic Match_ or atomicMatch_ in ABI.
For ABI I just copy pasted whole contract to https://remix.ethereum.org/ website and copied abi code. The problem is I am getting this error now:

Error: no matching event (argument="name", value="atomicMatch_", code=INVALID_ARGUMENT, version=abi/5.5.0)

What is wrong here? I tried both names of event but I get the same error over and over…

javascript tip calculator output not showing on html page

So I seem to have this issue a lot with my output not showing on the html, and even following along previous programs seems to give me no clue on why they never show. But I have a simple tip calculate program in javascript, I want the tip amount and tip per person to appear under the form on the html page, but whenever I hit the submit button nothing appears. I tried different event listeners (both visible in the code) one on the button and one in the javascript but it did nothing. I’m not sure if it’s due to the “” around the submit in html and the ” around submit in javascript, or even if I’m supposed to use ” around the ids in the html, I saw different code using either or so I was uncertain on which to really use so I went with “” around the ids in the html file.

HTML (filename pro3):

<!DOCTYPE html>
<html>
    <head>
        <title>Project 3</title>
    </head>

    <body>
        <script src = "pro3java.js"></script>

        <h1>TIP CALUCULATOR</h1>

        <form name = 'tipForm'>
            <p>Enter bill amount:</p>
            <input type="number"name="billAmt">

            <br>

            <p>Enter tip percentage:</p>
            <input type="number" name="tipPerc">

            <br>

            <p>Enter number of people:</p>
            <input type="number" name="people">

            <br>
            <br>
            
            <button type="submit" onclick="result()">Calculate</button>
            <br>
        </form>

        <div id = 'tipResult'></div>
        
    </body>
</html>

JAVASCRIPT (filename pro3java:

const form = document.forms.tipForm;

const output = document.getElementById('#tipResult');

form.addEventListener('submit', result);

//calc
let tip = parseInt(form.bill.value) * (parseInt(form.tipPerc.value) / 100);

let amount = (parseInt(form.bill.value) + parseInt(tip)) / form.people.value;

let total = amount.toFixed(2);

function result(e){
tipResult.textContent = `Your tip is $${tip}!`;
tipResult.textContent = `Everyone will pay $${total}!`;
} //result end

Cypress E2E Testing how can i make cypress use windows authentication where i do not have any specific login API request

Am stuck at an issue where am unable to make use of cy.ntlmSs and cy.ntlm to launch my work url. This application uses Windows Authentication which is collected by .net core pre-defined library and does use any login validation via API call with username and password.

How do overcome this scenario. I have tried almost all available ntlm options but none work. Please suggest.