How to use conditional ternary operator for mulitple cases javascript?

Hi i am trying to use ternary operator for multiple cases.

below is the code snippet,

const status_color_to_icon_name = {
    white: 'info',
    orange: 'major',
}

const default_icon_name = 'icon1';

<Icon name={status_color_to_icon_name[item.color] ?? default_icon_name} color= 
    {item.color} />

the above works fine. it looks for item name based on item.color if no name found in status_color_to_icon_name based on item.color it returns default_icon_name

now i have other condition if item.color is ‘red’ then i want to use custom_icon

i have tried below,

const custom_icon ='icon2';


const status_color_to_icon_name = {
    white: 'info',
    orange: 'major',
}

const default_icon_name = 'icon1';

<Icon name={item.color === 'red' ? custom_icon_name : 
    status_color_to_icon_name[item.color] ?? default_icon_name} color= 
    {item.color} />

but the above doesnt seem correct. could someone help me with this. thanks.

Why doesn’t Playwright reporter wait for async functions to complete?

I am using custom playwright reporter (but I think this issue is not only tied to reporter) and there in async OnTestEnd(test, result) I am trying to run exec command. With debugger turned on I see that as soon as program reaches this exec function it skips it and it ends.

async onTestEnd(test, result){
    const cmd = "some complex command"
    return new Promise((resolve, reject) => {
      exec(cmd, { timeout: 10000 }, (error, stdout, stderr) => {  // 10-seconds timeout
        if (error) {`enter code here`
          reject(error);
          return;
        }
        
        if (stderr) {
          reject(stderr);
          return;
        }
        resolve(stdout);
      });
    });
}

Above is one of many attempts to correctly run this function. But it skips all the time.

Access dynamic variable created in js (backstage.io) from a React component level file [closed]

Team A is using backstage.io an inside ../services/app/packages/backend/src/modules/auth.js they are creating microsoft token, modify this token adding some values and issuing as backstage (they are not able to provide me publick key to validate signature, don’t ask.), hence i need to catch and pass variable with microsoft token (before they modify this, yes i can change auth.js file) to my React component so during fetch (which is going through backstage proxy plugin) i could pass my microsoft token catched from auth.js as Authorization.
I have tried process.env , module.export etc. all of them are giving me undefined value from React component level and that is understandable because React env values are build on start of app.

Is there any possibility i could do this or only using token issued by them is possible

Error: runtimeTemplate.supportsAsyncFunction is not a function

I have a host and remote application developed with Angular 15.

Below is the webpack config of host:

const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
const path = require('path');

module.exports = {
  entry: './src/main',
  output: {
    publicPath: 'http://localhost:4200/',
    scriptType: 'text/javascript',
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  module: {
  },
  optimization: {
    runtimeChunk: false,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'host',
      remotes: {
        helloworld: 'helloworld@http://localhost:3000/remoteEntry.js',
      },
    }),
  ],
};

Below is webpack config of MFE:

const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
const path = require('path');

module.exports = {
  output: {
    publicPath: 'http://localhost:3000/',
    scriptType: 'text/javascript',
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /.js$/,
        type: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /.ts$/,
        loader: 'ts-loader',
        options: {
          configFile: 'tsconfig.app.json',
        },
      },
    ],
  },
  optimization: {
    runtimeChunk: false,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'helloworld',
      exposes: {
        './HelloWorldModule': './src/app/hello.module.ts',
      },
    }),
  ],
};

I am loading the MFE module in host using following code:

  {
    path: 'flights-search',
    loadChildren: () => // @ts-ignore
    // eslint-disable-next-line no-console
    import('helloworld/HelloWorldModule').then(m => m.Module).catch(error => console.log('Error=>', error))
  },

On running npm start in host, I get following error:
external “helloworld@http://localhost:3000/remoteEntry.js” – Error: runtimeTemplate.supportsAsyncFunction is not a function

Below are the packages I am using:

“webpack-bundle-analyzer”: “4.5.0”,
“webpack-cli”: “4.9.2”,
“webpack”: “^5.94.0”,
“webpack-dev-server”: “^4.11.1”,
“@angular-builders/custom-webpack”: “^15.0.0”

My mapplic v7 code cannot open on iPad or iPhone [closed]

This is using mapplic.js version 7. I think the problem is in the code below. I hope my map can be opened on an iPhone or iPad

self.addMarker = function(location) {
  // hidden marker
  if (location.pin.indexOf('hidden') != -1) 
    return false;
    
  var parent = $('.mapplic-layer[data-floor=' + location.level + '] .mapplic-map-image', self.el);
  var marker = $('<a></a>').addClass('mapplic-pin').addClass(location.pin.replace('hidden', '')).attr('aria-label', location.title + ' marker').css({
    'top': (location.y * 100) + '%',
    'left': (location.x * 100) + '%'
  }).appendTo(parent);
  
  marker.on('click touchend', function(e) {
    if (e.cancelable) e.preventDefault();
    if (!self.dragging) self.showLocation(location.id, 600);
  });
  
  if (location.label) {
    if (location.label.match(/(http(s)?://.)?(www.)?[-a-zA-Z0-9@:%._+~#=]{2,256}.[a-z]{2,6}b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g)) marker.css('background-image', 'url(' + location.label + ')');
    else $('<span><span>' + location.label + '</span></span>').appendTo(marker);
  }
  
  if (location.reveal) 
    marker.attr('data-reveal', location.reveal).css('visibility', 'hidden');
    
  if (location.category) {
    location.category = location.category.toString();
    marker.attr('data-category', location.category);
  }
  
  marker.attr('data-location', location.id);
  
  if (self.o.zoom && self.o.mousewheel) 
    marker.on('mousewheel DOMMouseScroll', self.mouseWheel);
    
  if (location.styled)
    marker.addClass(location.styled);
    
  if (location.color && location.pin.indexOf('pin-text') > -1) 
    marker.css('color', location.color);
  else if (location.color) 
    marker.css({
      'background-color': location.color,
      'border-color': location.color
    });
    
  location.el = marker;
  return marker;
}

I get the following error when i try to execute the command npm run build on my game project in visual studio code:

I am following a course to create a TS/JS-based game through webpack and Phaser. My GameScene Code is

import { Map } from "../components/map";

import TilesGroup from "../components/tiles/tilesGroup";
import Player from "../components/player/player";

export default class MainScene extends Phaser.Scene{
  player: Player
  tileGroup: TilesGroup
  cursors: Phaser.Input.Keyboard.CursorKeys
  level: number
  constructor(){
    super({
      key: "MainScene"
    })
    
  }
  init(props: {level? : number}){
    const {level = 0} = props
    this.level= Map.calcCurrentLevel(level)

  }

  create(){
    const map= new Map(this.level)
    this.cameras.main.setBackgroundColor('#ade6ff')
    this.cameras.main.fadeIn()

    this.cameras.main.setBounds(map.size.x, map.size.y, map.size.width, map.size.height)
    this.physics.world.setBounds(map.size.x, map.size.y, map.size.width, map.size.height)
    this.input.addPointer(1)
    this.cursors = this.input.keyboard.createCursorKeys()


    this.tileGroup= new TilesGroup(this,map.info.filter((el: TilesConfig) => el.type==="tile"))
    this.player= new Player(this,map.info.filter((el: TilesConfig) => el.type==="player")[0], map.size, this.level) 
  
    this.cameras.main.startFollow(this.player)
    this.physics.add.collider (this.tileGroup, this.player)
  }

update(time: number, delta: number): void{
  this.player.update(this.cursors)
}

}

I get the following webpack error when i try to run the command npm run build:



[webpack-cli] Failed to load 'C:UsersvivekLearningdemoplatformer+gameplatformer gamewebpackwebpack.dev.js' config
[webpack-cli] Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.  
 - options[0] has an unknown property 'to'. These properties are valid:
   object { patterns, options? }
 - options[1] has an unknown property 'to'. These properties are valid:
   object { patterns, options? }
 - options[2] has an unknown property 'to'. These properties are valid:
   object { patterns, options? }

I was expecting the webpack to be ready and run my game through the command npm start

I wanted to scroll to a particular slide which is not in view port using slickgoto functionality but I don’t want to enable infinite scroll as true

I am initializing a slick with the below properties

$(slickTabContainer)
        .not('.slick-initialized')
        .slick({
          dots: false,
          arrows: true,
          slidesToShow: 5,
          slidesToScroll: 1,
          infinite: false,
          variableWidth: true,
          responsive: [
            {
              breakpoint: 1280,
              settings: {
                slidesToShow: 4,
              },
            },
            {
              breakpoint: 1024,
              settings: {
                slidesToShow: 3,
              },
            },
          ],
        });

And on a particular event I need to load the slide which is not in view port without making inifinite property as true. How to achieve this.

My slickGoto functionality is as below

const checkTabSection = location.href.split("#")[1];
    if (checkTabSection) {
      dataTabDivs.forEach(div => {
        div.classList.remove('active');
        const tabIdList = div.getAttribute('data-tab').split(",");
        tabIdList.forEach(tabId => {
          const tabData = document.getElementById(tabId);
          if (tabData) {
            tabData.classList.add('tab-pane');
          }
          div.classList.add()
          if (tabId == checkTabSection) {
            if (tabData) {
              tabData.classList.add('active');
            }
            div.classList.add('active');
            if ($(slickTabContainer).hasClass('slick-initialized')) {
              $(slickTabContainer).slick('slickGoTo', Number(div.getAttribute('data-slick-index')));
            }
            $('html,body').animate(
              {
                scrollTop: $(div).offset().top - 100,
              },
              1000,
            );
          }
        })
      })
    }

.NET HTML grid using a model is lost when navigating to the second page in the paging structure.”

<script type='text/javascript'>
        function SeAction () {
                var ekbilgidetay = document.getElementById("#EkbilgiDetayListesi").value;
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("SinifEslestirme", "Home")',
                    data: '{ tempDataValue:"' + ekbilgidetay + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",

                });
            }
    </script>
 [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
  public ActionResult SinifEslestirme(string DetayNo)
  {
  var liste = Classes.SinifEslestirme.SinifEkBilgiDetayGetirmeListesi(DetayNo, HttpContext.Session["YETKI"].ToString());
  if (liste != null && liste.Count > 0)
  {  
      return View("SinifEslestirme", liste);
  }
}

        <h3>Sınıf Eşleştirme</h3>
        @if (Model != null)
        {
            <h3>@TempData["MalEkbilgiNo"].ToString() - @TempData["MalEkbilgiAdi"].ToString()   |   @TempData["MalEkbilgiDetayNo"].ToString() - @TempData["MalEkbilgiDetayAdi"].ToString()</h3>
            @ViewBag.mesaj
            @Html.ActionLink("<<Önceki Sayfa", "EkBilgi", "Home", new { @class = "btn btn-primary" })
            <br />
            <br />
            @Html.Grid(Model).Columns(columns =>
         {
           columns.Add(c => c.Mal_grup_no).Titled("Grup");
           columns.Add(c => c.Mal_grup_adi).Titled("Grup Adı").Filterable(true);
           columns.Add(c => c.Mal_altgrup_no).Titled("Alt Grup");
           columns.Add(c => c.Mal_altgrup_adi).Titled("Alt Grup Adı").Filterable(true);
           columns.Add(c => c.Mal_sinif_no).Titled("Sınıf");
           columns.Add(c => c.Mal_sinif_adi).Titled("Sınıf Adı").Filterable(true);
              columns.Add().Titled("Çalışır").Encoded(false).Sanitized(false).SetWidth(20).RenderValueAs(c =>
         {
        var isChecked = c.Calisir == 1 ? "checked" : "";
        var checkboxHtml = $@"
            <input type='checkbox' onclick=""updateSelectedValues(this, '{c.Mal_grup_no}{c.Mal_altgrup_no}{c.Mal_sinif_no}{c.Mal_ekbilgi_detay_no}')""
            {isChecked}>";
        return Html.Raw(checkboxHtml);

        });
}).WithPaging(20).Sortable(true)

        }

I am sending ekbilgidetay number to the SinifEslestirme ActionResult.
I am receiving a list and displaying it as a grid on the SinifEslestirme page

but grid using a model is lost when navigating to the second page in the paging structure.

How can I load the data into the grid once and enable pagination for navigating through it?

How can i do this ?

YouTube API upload no response (nodejs)

I am using the googleapis npm package, as described in the official documentation. However, in both cases (using the insert function with callback AND using the insert function as an asynchronous function) I am having issues.

When using the callback function, the code is executed asynchronously and the upload function starts after I try to log the response. When using the insert function as an asynchronous function, the upload completes, but there is no response logged. In fact, nothing is logged at all! Somehow we never reach the logger.log for Upload Response

I need the response to be able to read potential errors and other information. Below is the asynchronous use of the insert function in my upload function, as it is in my code. OAuth has been tested using the people API and is working fine. I have ended up with 2 videos in my YouTube dashboard that are stuck on infinitely processing, so something is working?

async function upload(
  oauth2Client,
  videoInfo,
  thumbInfo,
  publishAt,
  title,
  description,
  notifySubscribers
) {
  let result = {};
  // this await is needed because the insert function can optionally return a promise
  // which is what we want, ignore the underline in your IDE
  try {
    const res = await youtube.videos.insert(
      {
        auth: oauth2Client,
        part: "id,snippet,status",
        notifySubscribers,
        requestBody: {
          snippet: {
            title,
            description,
          },
          status: {
            privacyStatus: "private",
            publishAt,
          },
        },
        media: {
          body: fs.createReadStream(videoInfo.path),
          mimeType: videoInfo.mime,
        },
      },
      {
        onUploadProgress: (evt) => {
          const progress = Math.round((evt.bytesRead / info.length) * 100);
          // readline.clearLine(process.stdout, 0);
          // readline.cursorTo(process.stdout, 0, null);
          // process.stdout.write(`${progress}% complete`);
          logger.log(
            "debug",
            `Uploading file ${basename(filePath)} ${progress}%`
          );
        },
      }
    );
    logger.log("sensitive", "== Upload Response ==", res.data);
    result["data"] = res.data;
  } catch (error) {
    logger.log("error", "The API is not doing API things", error);
    result["error"] = "Possibly rate limited";
  }
  return result;
}

How to make GTM run before redirect?

Do anyone know how to prevent website wait a time to trigger all script in GTM tags?

My website have an event that will redirect to new URL when I click a button
I want to catch this event in GTM tag and add some script code to track behavior. I have setup a tag for this, it’s fired correctly but sometime no event capture; I was checked and put my code to console tab and it also worked.

I want wait a sec to run my code. But don’t know how to, I have tried use eventlistener(‘id-button’) but this make conflict with default event.

I’m just add tracking in GTM and don’t have access to based website code. The website also push missing datalayer. Sample below:

dataLayer.push({
  event: "gtm.click",
  gtm.element: "HTMLButtonElement: html > body > div.container > div.productPage1 > div.product_t" +
               "op > div.pure-g > div.pure-u-1.pure-u-md-1-2 > div.product__content > div.pure-g " +
               "> div.pure-u-1.pure-u-md-3-4 > div.action > button.and_checkout.btn_order.btn_add" +
               "_to_cart.buy-now.preorder",
  gtm.elementClasses: "and_checkout btn_order btn_add_to_cart buy-now preorder",
  gtm.elementId: "",
  gtm.elementTarget: "",
  gtm.triggers: "10,11,12,13,14,15,16,17,18,19,20",
  gtm.elementUrl: "",
  gtm.uniqueEventId: 22
})

Have someone tried this before? Pls help me a solution and I only can adjust in GTM tag.

DataTable not updating after adding new row in JavaScript application

I’m working on a JavaScript web application that uses DataTables to display a list of instructors. I’m having an issue where the DataTable doesn’t update immediately after adding a new instructor to the underlying data array.

The Problem

When I add a new instructor through a form submission, the underlying data array updates correctly, but the DataTable doesn’t reflect these changes until I manually refresh the page.

Code

I’ve reproduced this issue in both Vue.js and vanilla JavaScript. Here are CodePen links demonstrating the problem:

What I’ve Tried

  1. I’ve attempted to destroy and reinitialize the DataTable after adding new data:
updateDataTable() {
    if (this.dataTable) {
        this.dataTable.destroy();
    }
    this.$nextTick(() => {
        this.dataTable = $('#instructor-table').DataTable();
    });
}
  1. I’ve also tried using setTimeout to delay the reinitialization:
updateDataTable() {
    if (this.dataTable) {
        this.dataTable.destroy();
    }
    setTimeout(() => {
        this.dataTable = $('#instructor-table').DataTable();
    }, 0);
}
  1. I’ve made sure that the underlying data array (instructors) is updated correctly before calling updateDataTable().

Expected Behavior

I expect the DataTable to reflect the new data immediately after adding a new instructor, without requiring a page refresh.

Important Notes

  1. My main goal is to fix this issue in the Vue implementation but I noticed it happened on pure javascript .
  2. I don’t want solutions that pass the instructors array directly to DataTables. The data should remain managed by Vue v-for.

Question

How can I update the DataTable in my application to reflect new data without requiring a page refresh? Is there a more efficient way to add new rows to a DataTable dynamically while keeping the data management within Vue?

Any help or guidance would be greatly appreciated. Thank you!

NextJS – SyntaxError: Unexpected token < in JSON at position 0

I have NextJS project deployed in Vercel. The last deployment happened last week and everything was working fine.
Strangely, today I got SyntaxError: Unexpected token < in JSON at position 0 out of nowhere for pages with dynamic routing. I know this has something to do with JSON.stringify(), but problem is – it didn’t happen once I redeployed without any changes.

I’m confused why this happened and how can I mitigate it in future.

I’m using NEXT JS 13.4.6

Javascript Regular Expression Not Failing When I Think It Should

My code:

let g_Check = /^[a-z]+[a-z -.]{0,25}$/i;
let bl = g_Check.test("abc*"de"); // returns true, when I think it should return false because of the '*' and '"'

I want the test to only work (return true) for:

a) 25 length or less strings

b) must start with upper or lower case letter

c) the rest must only contain letters (upper or lower), spaces, minus signs and dots/periods

I would also like the expression to contain any number 0,1,2…,9.

I think that would be:

let g_Check = /^[a-z]+[a-z -.][0-9]{0,25}$/i;

But I have no way of checking this as my original expression does not work anyway.

JavaScript code to change href if contains a link

I want to create a script that changes the href of a button only if it contains a link or a period, since URLs normally contain periods (if it contains a link, I want to replace it with another one, for example google.com). However, the script I have changes all hrefs regardless of their content.

<script>
        window.onload = function() {
        var anchors = document.getElementsByClassName("elementor-button");
        for (var i = 0; i < anchors.length; i++) {
        anchors[i].href = "https://google.com"
        }
        }
</script>

How to import variables from one function to another in javascript?

I wanted to make simple multiplication from 2 variables that I collected before by prompt() and I performed every check to see if anything is wrong but everything in logs seems fine. But as soon as I want to make this multiplication it throws out NaN.

I tried logging every input i got and everything was fine.

let kurs1 = 0;
let stawka1 = 0;
//function stawka() {
//    const stawka1 = parseFloat(prompt("Podaj stawkę."));
//    document.getElementById("p1").innerHTML = "Stawka wynosi: " + stawka1 + "zł.";
//}
function druzyny() {
  let druz = prompt("Podaj drużynę pierwszą.");
  let druz2 = prompt("Podaj drużynę drugą.");
  document.getElementById("druzyna1").innerHTML = "Drużyna pierwsza: " + druz;
  document.getElementById("druzyna2").innerHTML = "Drużyna druga: " + druz2;
}

function stawka() {
  const stawka1 = parseInt(prompt("Podaj stawkę."));
  if (isNaN(stawka1)) {
    console.log("Błąd: Stawka to nie liczba.");
    return;
  }
  console.log("Stawka:", stawka1);
  document.getElementById("p1").innerHTML = "Stawka wynosi: " + stawka1 + "zł.";
}

function kurs() {
  const kurs1 = parseInt(prompt("Podaj kurs."));
  console.log("Kurs:", kurs1);
  document.getElementById("kurs").innerHTML = "Kurs wynosi: " + kurs1 + "x";
}

function mozlwygr(stawka1, kurs1) {
  const wygrana = stawka1 * kurs1;
  console.log(wygrana)
}

function mozlwygr(stawka1, kurs1) {
  if (isNaN(stawka1) || isNaN(kurs1)) {
    console.log("Błąd: Stawka lub kurs to nie liczba.");
    return;
  }
  let wygrana = stawka1 * kurs1;
  document.getElementById("mozliwawygrana1").innerHTML = "Możliwa wygrana: " + wygrana + "zł.";
}
<button id="butt-wyjdz" type="button" class="btn btn-info" onclick="stawka()">Ustaw stawkę</button>
<button id="butt-kurs" type="button" class="btn btn-info" onclick="kurs()">Ustaw kurs</button>
<button id="butt-kurs" type="button" class="btn btn-success" onclick="mozlwygr()">Oblicz możliwą wygraną</button>
<button type="button" class="btn btn-secondary" id="liveAlertBtn" onclick="losuj(), mozlwygr()">Przewiduj</button>
<button id="butt-druz" type="button" class="btn btn-info" onclick="druzyny()">Drużyny</button>
<script src="gamb1.js"></script>
<script src="scriptsite.js"></script>