Can Javascript be embedded inside a .NET Application? [closed]

This is NOT about web development! I am working on a desktop application which has to allow users to write custom scripts to automate specific tasks. This application is basically doing basic accounting and through Javascript the user should be able to write more complex formula. These should then be compiled and executed on the data provided by the application.
Again, this has nothing to do with web development. There’s no html, no CSS but just a scripting engine. And I want this engine to be part of my .NET application, which will store these scripts inside a database and compile them when they’re used. And there will be no DOM inside my project either.
My problem is that there are a gazillion pages about Javascript, yet none seem to discuss embedding Javascript inside a generic application. Python, on the other hand is possible, but my users are more familiar with Javascript.


Yes, I’ve heard of V8.NET but that project seems dead. There have been more similar projects that are all a bit old and outdated. And to make things worse, some of these projects, like the V8.NET engine, are LGPL and I cannot use any GPL code inside my project. Nor can I use interpreters. Other solutions I’ve seen seem to be at least 5 years old and written for .NET 4.x and older. Considering how much changed with the current .NET versions, those solutions are outdated.
So, is there a better option available?

Problem with custom data and TripsLayer in Deck.GL

I am trying to use a custom dataset for the trips layer. When I use the demo dataset, it works as expected. If I use my own, the map shows but no trips are animated, or even shown. I am thinking it is my input data; here is a snippet:

{"path": [[41.03251538262551, -88.75811070649046], [41.5572090829644, -88.59968467178443]], "timestamps": [20, 1900]}

All of the paths are using the same timestamps, as the speed at which they move needs to be constant. My thought is it is either my input data format, or the mere size, as there are about 40k paths. Below is my code.

const DEFAULT_THEME = {
  buildingColor: [74, 80, 87],
  trailColor0: [253, 128, 93],
  trailColor1: [23, 184, 190],
};

const INITIAL_VIEW_STATE = {
  longitude: -74,
  latitude: 40.72,
  zoom: 13,
  pitch: 45,
  bearing: 0
};

const MAP_STYLE = 'https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json';

export default function App({
  trips = FLOW,
  trailLength = 180,
  initialViewState = INITIAL_VIEW_STATE,
  mapStyle = MAP_STYLE,
  theme = DEFAULT_THEME,
  loopLength = 1800, // unit corresponds to the timestamp in source data
  animationSpeed = 1
}) {
  const [time, setTime] = useState(0);
  const [animation] = useState({});

  const animate = () => {
    setTime(t => (t + animationSpeed) % loopLength);
    animation.id = window.requestAnimationFrame(animate);
  };

  useEffect(() => {
    animation.id = window.requestAnimationFrame(animate);
    return () => window.cancelAnimationFrame(animation.id);
  }, [animation]);

  const layers = [
    new TripsLayer({
      id: 'trips',
      data: trips,
      getPath: d => d.path,
      getTimestamps: d => d.timestamps,
      getColor: theme.trailColor1,
      opacity: 0.3,
      widthMinPixels: 10,
      rounded: true,
      trailLength,
      currentTime: time,

      shadowEnabled: false
    }),
  ];

  return (
    <DeckGL
      layers={layers}
      effects={theme.effects}
      initialViewState={initialViewState}
      controller={true}
    >
      <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} />
    </DeckGL>
  );
}

export function renderToDOM(container) {
  render(<App />, container);
}

How to get the text value of a datepicker?

I am trying to get the text value of a datepicker so that I can store it in a MySQL database.

Here is a sample of my HTML code (index.php):

   <div class="col-xl-6">
       <input id="datepicker2" placeholder="Date">
   </div>

    <div class="col-xl-12">
        <a href="#form3" class="popup-with-form">
            <button type="submit" class="boxed-btn3" onclick="customFunction()">Next</button>
        </a>
    </div>

Here is the JavaScript code (within index.php):

    <script>

      function customFunction() {
       
          var DateOfBirth = document.getElementById("datepicker2").value;
           
          if (DateOfBirth != null && DateOfBirth !="") {
                $.post("insert.php", {DateOfBirth : DateOfBirth },function(response){
                    console.log(response);
                });
            }   
 
       }

   </script>

The issue I am having is that I am unable to get the text value of the datepicker. Does anyone know a solution to this?

Why using .bind() in an example of .reduce()

I was looking at this example of reduce() at https://putaindecode.io/articles/array-reduce-par-l-exemple/

var stats = [
  { site: "google.fr", browser: "Chrome", value: "50%" },
  { site: "google.fr", browser: "FireFox", value: "30%" },
  { site: "google.fr", browser: "Internet Explorer", value: "20%" },
  { site: "mozilla.fr", browser: "FireFox", value: "60%" },
  { site: "mozilla.fr", browser: "Internet Explorer", value: "20%" },
  { site: "microsoft.fr", browser: "Chrome", value: "10%" },
  { site: "microsoft.fr", browser: "FireFox", value: "20%" },
];

function compareSite(site, item) {
  return site === item.site;
}
function containSite(site, items) {
  return items.some(compareSite.bind(null, site));
}
function groupBySite(memo, item) {
  var site = memo.filter(containSite.bind(null, item.site));
  if (site.length > 0) {
    site[0].push(item);
  } else {
    memo.push([item]);
  }
  return memo;
}
// We use an empty array as accumulator 
var results = stats.reduce(groupBySite, []);

console.log(results);

and the result is:

[
    [
      { site: 'google.fr', browser: 'Chrome', value: '50%' },
      { site: 'google.fr', browser: 'FireFox', value: '30%' },
      { site: 'google.fr', browser: 'Internet Explorer', value: '20%' }
    ],
      { site: 'mozilla.fr', browser: 'FireFox', value: '60%' },
      { site: 'mozilla.fr', browser: 'Internet Explorer', value: '20%' }
    ],
    [
      { site: 'microsoft.fr', browser: 'Chrome', value: '10%' },
      { site: 'microsoft.fr', browser: 'FireFox', value: '20%' }
    ]
  ]

I don’t understand some things:

Why in containSite function “.bind(null, site)” is necessary?
Why in groupBySite function “.bind(null, item.site)” is used and not the previous “.bind(null, site)”?

Render chartjs and export image to data not in the DOM

I am using chart.js from a frontend react application. I need to create a plot with chart.js so that I can attach it to a powerpoint slide with pptxgen. This image does not have to be rendered visually, I just need to create it when the user requests to generate the ppt.

Chart needs a context, so I created a canvas element to act as such, then tried to render and export the base64 image that I would then proceed to feed into pptxgen:

  let ctx = document.createElement("canvas")
  ctx.setAttribute("width", "400")
  ctx.setAttribute("height", "400")
  let chart: Chart = new Chart(ctx, {
    type: "bar",
    data: {
      datasets: [{
      barPercentage: 0.5,
      barThickness: 6,
      maxBarThickness: 8,
      minBarLength: 2,
      data: [10, 20, 30, 40, 50, 60, 70]
      }]
    },
    options: {
      scales: {}
    }
  } )

  chart.render()
  console.log(chart.toBase64Image())

But all I obtain is “data:;” which looks to be an empty image.

Do you know how to make it render?

D3 passing refs to parent component in React

I created pie chart using D3 in React app using jsx. In my parent component I want to have an element “div” lets say that when “mouseover” event is triggered will do some manipulation on pie chart. But to do that I need to pass array of my pie charts refs (each ref will contain one path element in svg) to my parent component so I can manipulate them there. Problem is I don’t know how I can do that.

Here is code:

Parent Component:

const ContinentsInfo = () => {

    const data = useIO({sideEffectFunction: getContinentsData})
    const loaderOrLegend = isNil(data) ? <Loading /> :  data.map(x => <ContinentLegend key={x.continent} continent={x.continent} totalCases={x.cases}  />)
    
    return (
      <>
          <div className={styles['continental__legends']} >
                {loaderOrLegend}
          </div>
          <ThePieChart />
      </>
    )

}

export default ContinentsInfo;

Child component:

const ThePieChart = () => {

    let width = 600
    let height = 600
    let margin = 20

    let radius = Math.min(width, height) / 2 - margin;

    const colors = ['#ffd384','#94ebcd','#fbaccc','#1a78be','#fa7f72', '#5033ec']

    const data = [
        {continent: 'Africa', infected: 8790143},
        {continent: 'Europe', infected: 215424950},
        {continent: 'NAmerica', infected: 153251277},
        {continent: 'SAmerica', infected: 54913452},
        {continent: 'Asia', infected: 57882962},
        {continent: "Oceania", infected: 21702163}
    ];

    const pie = d3.pie().value(function(d) {
        return d.infected;
    })(data);

    const ordScale = d3.scaleOrdinal()
        .domain(data)
        .range(colors);


    const arc = d3.arc()
        .outerRadius(radius)
        .innerRadius(0);

    return (
        <div  className={styles.canvas__wrapper}>
            <div  className={styles.canvas}>
                <svg viewBox={`0 0 ${width} ${height}`}>
                    <g transform={`translate(${width / 2}, ${height / 2})`}>
                        {pie.map( x => {
                            return <path key={x.data.continent} d={arc(x)} fill={ordScale(x.data.continent)}/>
                        })}
                    </g>

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

export default ThePieChart;

Why is my function returning ‘undefined’? [closed]

I’ve tried to rearrange the declaration of templeDoorMessage, but it either hasn’t helped or returned an error.

function templeDoor(biForcePieces, plasmaWand, masterKey, regularKeys) {
    const totalBiForcePieces = 6;
    const correctAmountOfRegKeys = 10;
    let templeDoorMessage;
    if (!(biForcePieces = totalBiForcePieces)) {
        if (!plasmaWand) {
            templeDoorMessage = 'You need the Plasma Wand to enter!'
        } else if ((!masterKey) || (!(regularKeys = correctAmountOfRegKeys))) {
            templeDoorMessage = 'You don't have enough keys! You only need one Master Key to unlock the door however...';
        } else {
            templeDoorMessage = 'You may enter! Good luck...';
        }
        templeDoorMessage = 'You don't have all the Bi Force pieces!';
    }
    console.log(templeDoorMessage);
}

Lottery game – Not allowed to input the same number twice – JS

I am very new to javaScript and I am currently trying to code a Lottery Game. The User is allowed to input 6 numbers between 1 and 49 and then Generate 6 random numbers and it will then tell you how many Numbers you got correct.
Everything seems to be working great so far but i can not figure out how to Code that you

  1. Can not input the same number twice (This should result in an error code)
  2. The Randomizer isnt allowed to draw the same number twice

My Code looks like this so far:

Lotto 6aus49

<div class="position_middle">
        <input id="ball1" class="LottoZahlen" />
        <input id="ball2" class="LottoZahlen" />
        <input id="ball3" class="LottoZahlen" />
        <input id="ball4" class="LottoZahlen" />
        <input id="ball5" class="LottoZahlen" />
        <input id="ball6" class="LottoZahlen" />

        <button id="submitBtn" value="button" onclick=" Jetzt_Spielen();">Jetzt Spielen</button>
    <div id="output">
    </div>
<script>

    function validateBall(num)
    {
        let ballValue = document.getElementById("ball" + num).value;
        if (ballValue == "")
        {
            alert("Ball " + num + " braucht eine Zahl");
            return false;
        }
        

        if (isNaN(ballValue))
        {
            alert("Ball " + num + " ist keine Zahl");
            return false;
        }


        let numberValue = parseInt(ballValue);
        if (numberValue <= 0 || numberValue > 49)
        {
            alert("Die Zahl des Balls muss zwischen 1-49 liegen");
            return false;
        }

        return numberValue;
    }

    function containsDuplicates(ballValue) {
        return array.length !== new Set(ballValue).size;

}

    function output(str)
    {
        let output = document.getElementById("output");
        var tag = document.createElement("p");
        var text = document.createTextNode(str);
        tag.appendChild(text);

        output.appendChild(tag);
    }

    function Jetzt_Spielen() {
        let value1 = validateBall("1");
        if (value1 == false)
            return;

        let value2 = validateBall("2");
        if (value2 == false)
            return;

        let value3 = validateBall("3");
        if (value3 == false)
            return;

        let value4 = validateBall("4");
        if (value4 == false)
            return;

        let value5 = validateBall("5");
        if (value5 == false)
            return;

        let value6 = validateBall("6");
        if (value6 == false)
            return;

        let values = [value1, value2, value3, value4, value5, value6];

        let outputDiv = document.getElementById("output");
        outputDiv.innerHTML = "";
        
        let matched = 0;
        for (let i = 0; i < 6; i++)
        {
            let randomNumber = Math.round(1 + Math.random() * 48);
            output("Gezogene Zahl: " + randomNumber);
            for (let j = 0; j < 6; j++)
            {
                let myBallValue = values[j];
                if (randomNumber == myBallValue)
                {
                    matched++;
                    break;
                }
            }
        }

        output("Du hast " + matched + " richtige Zahl(en)")
    }
</script>

I dont really know how to continue with this. I either did something wrong already that I cant do it with this code or I just can not figure the code(s) out..

I’d really appreciate some help!!

Thank you in advance 🙂

Pass value from main function into internal function node js

everyone can somebody please guide me as to how I can pass the value from getWebsite to const results where there is website written.

or (let i = 2; i < 6; i++) {
        var getWebsite = await page.$eval('#pane > div > div > div > div > div:nth-child(7) > div:nth-child(' + i + ') > button > div > div > div.fontBodyMedium'[0], el => el.textContent);
        if (getWebsite == regexWebsite) {
            break;
        }
        else {
            continue;
        }
    }

    console.log(getWebsite);
    const results = await page.evaluate(() => {
        return ({
            scraper_job_id: new Date().getFullYear(),
            company: document.querySelectorAll('#pane > div > div > div > div > div > div > div > div > h1 > span:nth-child(1)')[0].textContent,
            address: document.querySelectorAll('#pane > div > div > div > div > div:nth-child(7) > div:nth-child(1) > button > div > div > div.fontBodyMedium')[0].textContent,
            website: getWebsite,
            created_at: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate() + ' ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds(),
            updated_at: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate() + ' ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds()
        })
    });

How to create a Telegram group using API?

I’m doing an integration with Telegram where I need to create a group and add some collaborators to it through an API integration, but I haven’t found a way to do that.
Googling I found that Bots are not allowed to create groups.

Does anyone know any way to do this?

I’ve tried this route, but without success.

https://api.telegram.org/bot0000000:AAAAAAAAAA/createChat

{
   "title": "[Event][06/05/22][Name]",
   "users": [
      0000000
   ]
}

important:
The purpose of this integration is not spam, but for internal use with employees of a company.

Blurred box with transparent center with css in react js

I have a design like this:

enter image description here

and I have a code like this:

<div data-testid="container" class="reactEasyCrop_Container img-crop-container">
     <img alt="" class="reactEasyCrop_Image reactEasyCrop_Contain img-crop-media" src="" 
     />
     <div data-testid="cropper" class="reactEasyCrop_CropArea 
     reactEasyCrop_CropAreaRound" style="width: 371.594px; height: 371.594px;">
     </div>
</div>

Now, how can I have this blur box that is transparent in the center with this code and CSS? Note that I can only use CSS and can’t change the HTML code