How to open a downloaded base64 file in desktop from outlook web add-in

Is there a way to open up a downloaded base64 file in desktop from outlook web add-in ??
I have a requirement where i am downloading the file from my web add-in. Now i want to open the downloaded pdf file in desktop in native application (Acrobat Desktop).
I know that it’s a security issue and web add-in works like any other web application running in sandboxed environment. But is there any way to achieve this ??

Output percentage in chart js label in a donut chart

Im using chart js in my portfolio dashboard to track my visitors. This specific chart is tracking visits per page. Im doing this with express and mongodb. Everything works except i cant see the actual percentage, only how many visitors..

async function renderPageVisitDonutChart() {
    const statsData = await fetchData();

    if (statsData.pageVisitCounts) {
        const pageNames = statsData.pageVisitCounts.map(item => item[0]);
        const visitCounts = statsData.pageVisitCounts.map(item => item[1]);

        const ctx = document.getElementById('myDonutChart');

        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: pageNames,
                datasets: [{
                    data: visitCounts,
                    borderColor: '#000000',
                    backgroundColor: ['#2bd890', '#d2f00e', '#33e7f3', '#fd650f'],
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            color: 'white',
                            font: { family: 'system-ui' }
                        }
                    },
                    title: {
                        display: true,
                        text: 'Page Visits',
                        color: 'white',
                        font: { family: 'system-ui' }
                    }
                },
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            var currentValue = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                            var total = data.datasets[tooltipItem.datasetIndex].data.reduce(function(previousValue, currentValue) {
                                return previousValue + currentValue;
                            }, 0);
                            var percentage = ((currentValue / total) * 100).toFixed(2);
                            return data.labels[tooltipItem.index] + ': ' + percentage + '%';
                        }
                    }
                },
                font: {
                    family: "'system-ui', '-apple-system', 'BlinkMacSystemFont'",
                    color: 'white'
                }
            }
        });
    }
}

Ive tried to add this to the tooltips but it didnt work.
Do i need the datalabel plugin for this?

tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            var currentValue = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                            var total = data.datasets[tooltipItem.datasetIndex].data.reduce(function(previousValue, currentValue) {
                                return previousValue + currentValue;
                            }, 0);
                            var percentage = ((currentValue / total) * 100).toFixed(2);
                            return data.labels[tooltipItem.index] + ': ' + percentage + '%';
                        }
                    }
                },

I would really like your help with this. Please come with suggestions or other post that i can read becuase i cant find anything in chart js docs.

setters are giving “typeError: not a function”

I am passing props from parent MoneyOut to child AddSupliers and from that child to another child SupplierNameCompont where it is used, these props are destructured. At first instance the form works and displays what I type in the console but when I type to enter another data, it throws the TypeError, what could be the challenge, would be glad to get any help. Here is my code..

const MoneyOut = () => {
    const [supplierName, setSupplierName] = useState('')
    const [supplierContact, setSupplierContact] = useState(0)

   console.log(supplierContact)
   console.log(supplierName)

  return (
    <>
    <Navbar/>
    <AddSupliers setSupplierName={setSupplierName} setSupplierContact={setSupplierContact}/>
    </>
)}
export default MoneyOut

//AddSupliers

const AddSupliers = ({setSupplierName, setSupplierContact}) => {
    const [visibleX, setVisibleX] = useState(false)
    const supplierDetailsOnclick =()=>{
          setVisibleX(!visibleX)
    }
  return (
    <div>
        { !visibleX &&
        <div className='addSupplierSection'>
            <h3>SUPPLIER (optional)</h3>
            <div className='addCustomerdiv'><button className='addSuppliersBtn' 
            onClick={()=>supplierDetailsOnclick()}>+ add Supplier</button></div>
        </div>
         }
    { visibleX && <SupplierNameCompont setSupplierName={setSupplierName} setSupplierContact={setSupplierContact}/>} 
    </div>
  )
}

export default AddSupliers

// SupplierNameCompont

const SupplierNameCompont = ({setSupplierName,setSupplierContact}) => {

    const [visible2, setVisible2] = useState(false)

    return (
    <>
       {!visible2 && 
       <div className='supplierNameSection'>
            <div>
                <h3>SUPPLIER NAME</h3>
            </div>

            <div>
                <form id='suppliersName'>
                    <input type='text' className='suppliersName'
                        placeholder='e.g. Mr John' onChange={(e)=>{setSupplierName(e.target.value)}}/>
                </form>
            </div>
            <div>
                <h3>SUPPLIER CONTACT</h3>
            </div>

            <div>
                <form id='suppliersContact'>
                    <input type='number' className='suppliersContact'
                        placeholder='e.g. 0810...' onChange={(e)=>{setSupplierContact(e.target.value)}}/>
                </form>
            </div>
            <hr className='borderline1'/>
            <div className='saveSuppliersBtnDiv'><button className='saveSuppliersBtn' onClick={()=>{setVisible2(!visible2)}}>+ Add</button></div>
        </div>}
        {visible2 && <AddSupliers/>}
    </>
    )
}

export default SupplierNameCompont

Context menu is not getting displayed due to enabling Lightning Web Security for LWC and Aura

I am building a driver diagram (visual representation of records) using aura component. To build this I’m importing third party D3 library, on the mouse right click in the node it should display custom context menu where we can add, edit or delete the node which works fine, but when we “enable Use Lightning Web Security for Lightning web components and Aura components“, the context menu is not displayed rather it shows the default browser right click menu, even though we prevent default browser behaviour, can you please suggest why is this happening when we enable Use Lightning Web Security for Lightning web components and Aura components ? and how we can resolve this ?

i tried using Third-Party Library Considerations for LWS, but still could not fix it.(https://developer.salesforce.com/docs/platform/lwc/guide/security-lwsec-js.html)

// calling function

.on(“contextmenu”, d3.contextMenu(menu))

this calls third party module d3-context-menu.js

i was expecting it to display custom context menu when we right click on node.

Vs Code Extentions: vscode.window.activeTextEditor always returns undefined

I’m trying to get the currently opened document in vscode extensions using the vscode.window.activeTextEditor property. I however get undefined each and every time.

 this._panel.webview.onDidReceiveMessage(
      async (msg: any) => {
        switch (msg.command) {
          case "startup":
            const _currDoc = vscode.window.activeTextEditor;
            console.log({ _currDoc });
            const doc = vscode.workspace.textDocuments[0];
            const data = doc?.getText();
            this._panel!.webview.postMessage({
              command: "data",
              data,
              fileName: path.basename(doc?.fileName),
              type: doc?.languageId,
            });
            break;
          case "opened":
            break;
          default:
            break;
        }
      },
      null,
      this._disposables
    );
  }

Does anyone have any idea why is this behaviour happending because in the extention.ts file i can be able to see the current opened document.

Password validation with Javascript

I can’t seem to find the reason why the code isn’t working. I tried to search for syntax errors but there’s none. Upon typing pwd into the textbox, it should reveal the text “hello” however, it does not change the css.

<html><head><style>.censor{filter: blur(10px);-webkit-filter: blur(10px);}</style></head>
<body>

<text class="censor">Hello</text>
<input type="password" placeholder="[Input password to reveal]" id="password" onkeyup="reveal()"/>

<script>
    function reveal(){ 
        var pass = document.getElementById("password").value; 
        if (pass == "pwd") {
            $(".censor").css("filter","blur(0)");
            $(".censor").css("-webkit-filter","blur(0)");
        }else{
            $(".censor").css("filter","blur(10px)");
            $(".censor").css("-webkit-filter","blur(10px)");
        }
    }
</script>

</body>
</html>

React-native-peerjs does not emit steam, why?

This is not a new question, and the previous questions did not get any solutions.

React-native-peerjs supposed to emit ‘stream’ upon answering call. But we are getting the call and answering it perfectly fine, but no stream gets emitted. What am I doing wrong?

We tried to set options like below when we are sending a call:

  var options = {
      'constraints': {
        'mandatory': {
          'OfferToReceiveAudio': true,
          'OfferToReceiveVideo': true
        },
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
      }
    }

But alas ! It still wont work. Here is the entire code :

/**
 *
 * @format
 * @flow strict-local
 */

import React, { useState, useEffect } from 'react';
import type { Node } from 'react';
import {
  SafeAreaView,
  ScrollView,
  Dimensions,
  useColorScheme,
  View,
  TextInput,
  TouchableOpacity,
  Text
} from 'react-native';

import { Colors } from 'react-native/Libraries/NewAppScreen';
import Peer from 'react-native-peerjs';
import { RTCView, mediaDevices } from 'react-native-webrtc';


const { width, height } = Dimensions.get('window');

const App: () => Node = () => {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    flex: 1,
  };
  const [remotePeerId, setRemotePeerId] = useState('');
  const [ongoin, setOngoin] = useState(undefined);
  const [localPeer] = useState(() => new Peer()); // using peer cloud
  const [localStream, setLocalStream] = useState();
  const [remoteStreams, setRemoteStreams] = useState();

  useEffect(() => {
    console.log('Local peer is opening ...');

    let isFront = true;
    mediaDevices.enumerateDevices().then(sourceInfos => {
      let videoSourceId;
      for (let i = 0; i < sourceInfos.length; i++) {
        const sourceInfo = sourceInfos[i];
        if (
          sourceInfo.kind == 'videoinput' &&
          sourceInfo.facing == (isFront ? 'front' : 'environment')
        ) {
          videoSourceId = sourceInfo.deviceId;
        }
      }
      mediaDevices
        .getUserMedia({
          audio: true,
          video: {
            mandatory: {
              minFrameRate: 30,
            },
            facingMode: isFront ? 'user' : 'environment',
            optional: videoSourceId ? [{ sourceId: videoSourceId }] : [],
          },
        })
        .then(stream => {
          setLocalStream(stream);
          localPeer.on('open', peerId => {
            console.log('Local peer is opened with Id = ' + peerId);

            localPeer.on('call', call => {
              console.log('Local peer receives incoming call');

              call.answer(stream); // answring call should emit 'stream', but won't
              

              call?.on('stream', remoteStream => {
                console.log('Local peer receives stream from remote peer');

                setRemoteStreams([remoteStream, remoteStream, remoteStream]);
              });
            });

         
          });
        })
        .catch(error => {
          console.log(error);
        });
    });

    return () => {
      if (localPeer) {
        localPeer.destroy();
        console.log('Local peer is destroyed');
      }
    };
  }, []);


  const handleCallPress = () => {
    console.log("CURRENT STREAM");

    var options = {
      'constraints': {
        'mandatory': {
          'OfferToReceiveAudio': true,
          'OfferToReceiveVideo': true
        },
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
      }
    }

    const outgoingCall = localPeer.call(remotePeerId, localStream, options);



      setOngoin(outgoingCall); 
  };

  useEffect(() => {
    if (!ongoin) return;
    console.log("Running steam");
    
    ongoin.on('stream', (remoteStream) => {
      console.log('Local peer receives stream from remote peer');
      setRemoteStreams([remoteStream, remoteStream, remoteStream]);
    });

  }, [ongoin]);


  return (
    <SafeAreaView style={backgroundStyle}>
      <View style={{ flex: 1 }}>
        <View
          style={{
            flex: 0.7,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          {localStream ? (
            <RTCView
              streamURL={localStream.toURL()}
              style={{
                width: width * 0.9 - 8,
                height: 200,
              }}
            />
          ) : null}
        </View>
        <ScrollView
          horizontal
          style={{ flex: 0.8 }}
          showsHorizontalScrollIndicator={false}>
          <>
            {remoteStreams ? (
              remoteStreams.length > 0 ? (
                <>
                  {remoteStreams.map((stream, index) => {
                    return (
                      <View
                        key={index}
                        style={{
                          width: width * 0.9,
                          marginRight: 8,
                          justifyContent: 'center',
                          alignItems: 'center',
                        }}>
                        <RTCView
                          streamURL={stream.toURL()}
                          style={{
                            width: width * 0.9 - 8,
                            height: 300,
                          }}
                        />
                      </View>
                    );
                  })}
                </>
              ) : null
            ) : null}
          </>
        </ScrollView>
        <View
          style={{
            flex: 0.5,
          }}></View>
      </View>


      <View style={{ flex: 0.5, alignItems: 'center', justifyContent: 'center' }}>
        <TextInput
          style={{
            height: 40,
            borderColor: 'gray',
            borderWidth: 1,
            padding: 8,
            marginBottom: 16,
            width: width * 0.8,
            borderRadius: 8,
          }}
          placeholder="Enter Remote Peer ID"
          onChangeText={(text) => setRemotePeerId(text)}
          value={remotePeerId}
        />
        <TouchableOpacity
          onPress={() => handleCallPress()}
          style={{
            backgroundColor: '#4CAF50',
            padding: 10,
            borderRadius: 8,
          }}>
          <Text style={{ color: 'white', fontWeight: 'bold' }}>Initiate Call</Text>
        </TouchableOpacity>
      </View>

    </SafeAreaView>
  );
};

export default App;

Why i am getting the Error: The Specified module could not be found by running npm run dev the command in terminal?

[here is the error I am getting when I run the command ‘npm run dev’ in my terminal](https://i.stack.imgur.com/vD2PA.I cannot find why this error is showing in my terminal while running #npm run dev even though I have updated the versions and tried everything I can, I am not getting the link of #vite-react interface, I have to make projects but this error is not resolving. I am using react.js.

state as an argument to access an object?

(i’m new to react btw)
So i’m trying to make a code that:

  1. Reads the value of two select boxes and an input
  2. Uses the value of the selects to read a Javascript object
  3. Multiplies the value of the input by the value from the object.

This is what I’ve got to so far:

const valores = {
  longitud: {
    metros: {
      val: 1,
    },
    centímetros: {
      val: 0.01,
    },
  fuerza: {
    newtons: {
      val: 1,
    },
    dina: {
      val: 0.0000001,
    },
  }
}
const [tipo, setTipo] = useState("longitud")
  const [uIn, setUIn] = useState("metros")
  const [val, setVal] = useState(0)
  const unidades = {
    longitud: [
      "metros",
      "centímetros",
    ],
    fuerza: ["newtons", "dinas"],
  }
  return (
    <div>
      <select
        id="tipoMedida"
        value={tipo}
        onChange={e => setTipo(e.target.value)}
      >
        <option value="longitud">Longitud</option>
        <option value="fuerza">Fuerza</option>
        
      </select>

      <input type="number" id="valor" value={val}
        onChange={e => setVal(e.target.value)}/>

      <select id="unidadOrigen" value={uIn}
        onChange={e => setUIn(e.target.value)}>
        {unidades[tipo].map(u => {
          return <option value={u}>{u}</option>
        })}
      </select>

This part works fine. However, I’m not sure how to do the next one. I want to show a text that shows the result, for which i did this
<div id="resultado">El resultado es {val*valores[tipo[uIn[val]]]}</div>but it shows nothing, and {val*valores[tipo[uIn.val]]} says uIn is undefined. Is something wrong with my code, and if not how could I achive that result?

Bad Request for mobile only on wordpress site

I have a custom wordpress plugin that works fine on my computer’s browser, but 400s out on mobile. I am at a loss.

Here is the php for handling the request.

<?php
add_action( 'wp_ajax_receive_api_call', 'recieveAPICall' );

function recieveAPICall() { 
    $dist = $_POST["distance"];
    if($dist > 50){
        $dist = 50; //distance should be limited for search
    }
    $zip = $_POST["zip"];
    $api_key_text = get_option('key_text');
    $api_url = 'http://some_url_i_am_using/endpoint?zip='.$zip.'&distance='.$dist;
    $response = wp_safe_remote_post($api_url, array(
        'headers' => array('X-API-Key' => $api_key_text)
    ));

    if (is_wp_error($response)) {
        echo "ERROR";
    } else {
        $json_string = json_encode($response['body'], JSON_PRETTY_PRINT);
        echo $json_string;
    }
    die;
}

?>

Here is the javascript function I am using to make a post to the php which is called by clicking a button.

        var zip = $("#ffl_zip").val();
        var dist = $("#ffl_distance").val();
        if(dist == undefined || dist == null){
            dist = 25;
        }
        if(dist >= 50){
            dist = 50;
            $("#ffl_distance").val(50);
        }
        if(zip == undefined || zip == null || zip == ""){
            alert("Please enter a zip code to search.");
            return;
        }
        var data = {"action":"receive_api_call", "zip":zip, "distance":dist, enctype: "multipart/form-data"};
        
        $.post(ajaxurl, data).done(function(response) {
            if(response.includes("INVALID API KEY")){
                //FFLs = {};
            }
            //console.log(response);
            var json = JSON.parse(response);
            json = JSON.parse(json);
            //console.log(json);
            FFLs.list = json;
            FFLs.dict = {};
            $.each(json, function(key,value) {
                FFLs.dict[value.ffl] = value;
            }); 
            $("#ffl_select").empty();
            for(var i = 0; i < FFLs.list.length; i++){
                var ffl = FFLs.list[i];
                $("#ffl_select").append($("<option></option>")
                    .attr("value", ffl.ffl)
                    .text(ffl.licensee + (ffl.dba==""?"":" ("+ffl.dba+")") + ": " + ffl.premiseAddress + ", " + ffl.premiseCity + ", " + ffl.premiseState + ", " + ffl.premiseZip));
                if($("#ffl_select option[value="823011076L16497"]").length > 0){
                    $("#ffl_select").val("823011076L16497").change();
                } else {
                    $("#ffl_select").change();
                }
            }
        }).fail(function(xhr, status, error) {
            alert(status + " " + error);
            alert(xhr.responseText);
        });

Like I said, this all works fine on the computer, but no luck on mobile. The alerts above spit out Bad Request, and 0 from the php. Any clues?

Find a point a minimum distance from all other points

I would like to “sprinkle” points on the screen (2d) so they seem relatively randomly placed and take up most of the space on the screen. The idea is that the points would not be within a certain distance, like 50 pixels, of each other so they are spaced well. The final code will be in Javascript — I just need the code / algorithm to make the array of points.

I am picking points somewhat randomly now and then checking against all other points but this is horribly inefficient. I have an idea of using some sort of delaunay grid but I am not sure how to make sure the points are not too close together.

two event listeners, to reload content, both rendered inside conditionals inside a function, yet one doesn’t work?

let me show you the code first.

<script>
let score = 0;
let op1 = '';
let op2 = '';
let op3 = '';
let opc =  '';
let nxt = '';

function reload(rp){
    if (rp === '') {
        document.getElementById('container').innerHTML =
            `<div id="startbuttoncontainer"><img id="startbutton" src='assets/startbutton.png' /></div>`;
    } 
    if (rp === 'score') {
        document.getElementById('container').innerHTML =
            `<span>Final Score<br/>${score}</span>`;
    } 
    if(rp === 'a'){
    op1 = 'Red';
    op2 = 'Apple';
    op3 = 'Tree';
    opc = '2';
    nxt = 'b';
    document.getElementById('container').innerHTML =
    `
        <div id="paperbg">
            <span id="score">Score: ${score}</span>
            <img id="obj"  src="assets/${rp}.png" />
        </div>

        <div id="opscontainer">
            <div id="op1" class="op">${op1}</div>
            <div id="op2" class="op">${op2}</div>
            <div id="op3" class="op">${op3}</div>
        </div>
        
    `;
    } 
    if(rp === 'b'){
    op1 = 'Blue';
    op2 = 'Bunny';
    op3 = 'Banana';
    opc = '3';
    nxt = 'c';
    document.getElementById('container').innerHTML =
    `
        <div id="paperbg">
            <span id="score">Score: ${score}</span>
            <img id="obj"  src="assets/${rp}.png" />
        </div>

        <div id="opscontainer">
            <div id="op1" class="op">${op1}</div>
            <div id="op2" class="op">${op2}</div>
            <div id="op3" class="op">${op3}</div>
        </div>
        
    `;
    }
}



function handlestartbuttonpress(p) {
   // document.getElementById('startbuttoncontainer').innerHTML =
  //  `<img id="startbuttonpressed" src='assets/startbuttondown.gif' />`;

    setTimeout(function() {
        reload(p);
    }, 1600);  
}

reload('');

document.getElementById('startbutton').addEventListener("click", function(){ handlestartbuttonpress('a'); });
document.getElementById('op2').addEventListener("click", function(){ handlestartbuttonpress('b'); });
</script>

i’ve simplified the code to handle the same function (handlestartbuttonpress) for simplicity annd debugging sake. when the “start button” is pressed, everything works as expected, a short delay before updating the page and redering the page with the content for “a”. but on the “a” page, the option 2 div element should reload to the “b” page. but i get nothing.

ive tried different ways of calling the function including onclick rather than event listeners, same result.