Importing a javascript class not working in Visual Studio Code (Mac)

I’m looking to import a class from one javascript file to another. It doesn’t seem to be working with defaults or by importing the class individually. Here is the code, all the files are in the same folder:

test.js

class Test{
    constructor(self, str){
        self.str = str;
    }
    getStr(){
        return self.str;
    }
}
export default Test;

main.js

import Test from './test.js';

const test = new Test('Something happening');

document.getElementById('debug').innerHTML = test.getStr();

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    
    <!-- Link to your external stylesheet -->
    <link rel="stylesheet" href="styles.css">

    <!-- Link to your external JavaScript file -->
    <script src="main.js" defer></script>
    <script type="module" src="test.js" defer></script>
</head>
<body>
    <p id="debug">Nothing Happening</p>
</body>
</html>

So far I’ve tried using a default export and exporting in the class name export class Test, import {Test} from './test.js'. Both had the same issue where the import didn’t happen and all code below didn’t run. No error messages, no answers in documentation (so far), no nothing. Hopefully there is something I’ve overlooked, thanks for any help

How do I properly handle removal of a Blazor rendered element by Javascript?

I know changing DOM by Javacript within a framework like Blazor is a bad idea but right now I cannot see any workaround. I have a list of custom components (Material Web <MdInputChip>) rendered by Blazor’s for that iterates through an array. The chip could be removed by user by clicking an X button. When user clicks X, the Web Component code remove itself from the DOM (I cannot change this behavior).

Here’s a reproducible code that simulates my situation:

<div @key="DateTime.UtcNow.ToString()">
    @for (int i = 0; i < values.Count; i++)
    {
        var z = i;
        var item = values[z];

        <p @key="@(DateTime.UtcNow.ToString() + z)" @onchange="(() => Remove(z))">
            @(item)
            <button onclick="this.parentElement.dispatchEvent(new Event('change')); this.parentElement.remove();">
                Remove
            </button>
        </p>
    }
</div>



@code {

    List<string> values = new() { "A", "B", "C" };

    void Remove(int index)
    {
        values.RemoveAt(index);
        Console.WriteLine(string.Join(",", values));
    }

}

enter image description here

Problem is, when I click Remove on B for example, C also got removed most of the time. Then I tried adding @key, first to the <p> elements but it would cause all kind of weird problems when the array is modified further, then to the container <div> (and I also tried removing @key from <p>). I thought it fix it at first but turned out the problem gets rarer but it happens sometimes.

In my case, re-rendering that whole area is fine and performance is not critical. What are my options? Is there anyway to tell Blazor to just dispose that whole area and render everything new?


Just want to update that for my specific case, luckily the event can be cancelled with preventDefault() so I can do this:

export function beforeStart() {
    document.addEventListener("remove", e => {
        if (e.target?.tagName === "MD-INPUT-CHIP") {
            e.preventDefault();
        }        
    });
}

Google Sheet if condition continue even if value not in range

function checkRowCol(row, col) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getActiveSheet();
  if (13 <= row <= 16 || 29 <= row <= 32 || 45 <= row <= 48 || 61 <= row <= 64 || 77 <= row <= 80 || 93 <= row <= 96 || 109 <= row <= 112 || 125 <= row <= 128) {
    
    if (col == 6 || col == 12 || col == 18){
      if (13 <= row <= 16 || 29 <= row <= 32 || 45 <= row <= 48 || 61 <= row <= 64 || 77 <= row <= 80 || 93 <= row <= 96 || 109 <= row <= 112 || 125 <= row <= 128) {
      ownedUpdate(row, col);
      }
    }
    // complete
    else if(col == 3 || col == 9 || col == 15) {
      if (13 <= row <= 16 || 29 <= row <= 32 || 45 <= row <= 48 || 61 <= row <= 64 || 77 <= row <= 80 || 93 <= row <= 96 || 109 <= row <= 112 || 125 <= row <= 128) {
        if (ws.getRange(row, col + 3).getValue() == false && ws.getRange(row, col ).getValue() == true) {
          ws.getRange(row, col).setValue(false);
          SpreadsheetApp.getActive().toast("You cannot complete without owning the item sir");
        }
        else {
            completedUpdate(row, col);
            if (ws.getRange(row, col).getValue() == true){
              ownedUpdate(row, col + 3);
            }
        }
      }
    }
  }
}

I have this code block, I’ve made that if col 6 row 17 is changed so nothing will happen but for some reason it still enters the if that prints (“You cannot complete without owning the item sir”) and I can’t seem to understand why.
I’ve try putting the ranges in “(13 <= row <= 16)….”
I’ve tried as you seen to make extra ifs with the condition.
but for some reason it still enters when Row 17 is selected… can’t understand why

Tried to enter value row = 17, col= 3 result was

if (ws.getRange(row, col + 3).getValue() == false && ws.getRange(row, col ).getValue() == true) {
          ws.getRange(row, col).setValue(false);
          SpreadsheetApp.getActive().toast("You cannot complete without owning the item sir");
        }

tried multiple ifs, tried even the negative ifs that should not end in this result and still… that’s what I get…
:help:

How to install private git repo with Yarn via access tokens without hardcoding in package.json?

I thought I could use .npmrc for v1 or .yarnrc.yml for v2/3/4 but in all cases Yarn doesn’t even try to authenticate to Github

nodeLinker: node-modules

npmScopes:
  packagescope:
    npmAlwaysAuth: true
    npmAuthToken: my_personal_access_token
    npmRegistryServer: "https://npm.pkg.github.com"

yarnPath: .yarn/releases/yarn-3.6.2.cjs

It errors with:

error Command failed.
Exit code: 128
Command: git
Arguments: ls-remote –tags –heads https://github.com/user/some-dependency.git
Directory: /home/me/Documents/projects/myapp
Output:
fatal: could not read Username for ‘https://github.com’: terminal prompts disabled

When I go to github.com I find that the access token has never been used, so apparently authentication is never even attempted.

How can I install the repo using access tokens without hardcoding them into the package.json? When I hardcoded them into package.json it worked fine, but that’s terrible security practice, may break git bisect and has other downsides.

I can’t simply use SSH because I need this to work with CI servers owned by third parties and I don’t want to hand over unlimited access to all of our repositories.

Global variable is undefined after updating it in async callback [duplicate]

I have a callback function that is passed into an async function. That callback function updates a global variable I have inside my React component.

The problem is, then I try to log the global variable to the console, it returns undefined.

I understand that it is an async function so that console log statement would execute before the callback is called, making the global variable’s value whatever it was declared to (undefined in my case).

How can I go about making the global variable updated by the callback function?

Navbar.jsx

var userInfo = undefined;
function callbackUserQuery(userObj) {
    console.log('User Object: ', userObj);
    userInfo = userObj;
  }
  getUserDocFromEmail('[email protected]', callbackUserQuery);
console.log(userInfo);

asyncFuncFile.js:

async function getUserDocFromEmail(userEmail, finishedFunc) {
  const usersRef = collection(db, 'users');

  const q = query(usersRef, where('Email', '==', userEmail));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    // doc.data() is never undefined for query doc snapshots
    // console.log(doc.id, ' => ', doc.data());
    finishedFunc(doc.data());
  });
}

Issue adding counter to filter function in jquery

I have this code that is working great to add some css to specific class on various td. The code basically sees what td had the class mentioned, and apply .css to the td if the text (number) in the td is greater than 1.

$(document).ready(function () {
  var multipleitems = 0;
  var s = 0;
  var x = document.getElementsByClassName("a-text-center table-border");
  for (var i = 0; i < x.length; i++) {
    $("td")
      .filter(function () {
        return $(this).text() > "1";
      })
      .css("border-top-color", "rgb(0 217 150 / 38%)")
      .css("border-top-width", "5px")
      .css("font-size", "20px");
    multipleitems = s + 1;
  }
});

The problem is, that the counter multipleitems is counting all td in the pages, instead of counting only the td that has text inside greater than 1, as hapening on the .css

Thanks in advance for any help…

How to get the list of users who reacted to a facebook post?

I’m trying to get the list of people who reacted to a Facebook post, to then choose a random username among those who reacted, but I can’t find a way to get this information, I don’t know if it’s that currently the Facebook Graph API doesn’t allow it or something, but I couldn’t get it, I appreciate your answers.

I tried making such requests, but it didn’t work either and I already have a Facebook app, with the necessary permissions so I don’t think this is the case.

https://graph.facebook.com/{object-id} ?fields=likes.summary(true) &access_token={access-token}

Trying to convert german format of variable into international, what am i doing wrong? [duplicate]

The script i use gets content from an HTML element, which is in German decimal format (1380,20), and sets this as variable.

I’m trying to convert this number into the standard international decimal format (1380.20), so that the script can use it for calculations. But it doesn’t work – i’m getting the result “NaN”.

Since i’m a javascript beginner, i’m probably doing it wrong. But i lack the knowledge to find the error. Researched for almost two hours about this particular method, but can’t puzzle it out. 🙁

var euroTotal = $('.euroTotal').toLocaleString('en-US');

Any helpful pointers what’s wrong with this?

ASP.NET Core MVC: set focus on input element on view load

I am trying to set focus using javascript on the first unfocused input element of MVC view in a load window event listener. But element is focused only after page reloading. Attached browser – MS Edge I tried reloading the page programmatically using window.location.reload, but it didn’t have the same effect. Using setTimeout also was not helpful. This only works when previewing the page in Edge from Visual Studio. How to set focus correctly?

Test sample repo: https://github.com/pnfstas/TestFocus

HomeController:

using Microsoft.AspNetCore.Mvc;

namespace TestFocus.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Start()
        {
            return View("Start");
        }
    }
}

Start.cshtml:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
        <form action="javascript:void(0);" method="post" style="width:500px;height:300px;display:flex;flex-direction:column;align-items:stretch;justify-content:space-between;">
            <fieldset style="flex:auto;display:flex;flex-direction:column;justify-content:space-evenly;">
                <legend>Authentication</legend>
                <label id="username-label" for="UserName">User name:</label>
                <input class="user-property-input" id="UserName" name="UserName" type="text" />
                <label id="email-label" for="Email">E-Mail:</label>
                <input class="user-property-input" id="Email" name="Email" type="email" />
                <label id="phone-label" for="PhoneNumber">Phone number:</label>
                <input class="user-property-input" id="PhoneNumber" name="PhoneNumber" type="tel" />
            </fieldset>
            <span id="test-focus-span" style="margin-top:15px;"></span>
        </form>
        <script id="start" src="~/src/start.js" asp-append-version="true"></script>
    </body>
</html>

start.js

window.addEventListener("load", function(event)
{
    /*
    if(!document.cookie.includes("reloaded=true"))
    {
        document.cookie = "reloaded=true";
        window.location.reload();
    }
    */
    const element = document.querySelectorAll("input:not(:focus)")?.[0];
    if(element instanceof HTMLInputElement)
    {
        element.focus({ focusVisible: true });
        const message = `${element.id} is ${document.querySelector(`input#${element.id}:focus`) instanceof HTMLInputElement ? "" : "not"} focused`;
        const span = document.querySelector("span#test-focus-span");
        if(span instanceof HTMLSpanElement)
        {
            span.innerText = message;
        }
        console.log(message);
    }
});

Filter table based on href attribute value in tag and show parent row when child row matches the search value

I am trying to search and filter the below table based on the href value. My code works for all the columns that are displayed in the table and shows the corresponding row but does not work when I search for the string in the href attribute.

For example, when I search for Google in the search bar, I need to show the row that contains the href value of https://www.google.com.

I have tried looking for a solution everywhere but couldn’t find it. Can anyone help me or point me to where I could find the answer to this?

Also, is there a way to assign parent row and child row to the table without using the id attribute so that when the search and filter returns a child row I want to show the corresponding parent row as well?

My code on jsfiddle – JsFiddle

HTML :

<body>
  <div>
    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for website..">
    <button type="submit">Search</button>
  </div>

  <table border="0" id="myTable">
    <thead hidden>
      <tr>
        <th>Name</th>
        <th>URL</th>
      </tr>
    </thead>

    <tbody>
      <tr class="header clickable-row" style="cursor:pointer" data-toggle="true">
        <td colspan="2">
          <label style="cursor:pointer">Parent Row 1</label>
        </td>
      </tr>
      <tr class="hide collapse" style="display:none">
        <td>
          <h4>Column1</h4>
        </td>
        <td>
          <a class="connectorlink" href="https://google.com" target="_blank">website</a>
        </td>
      </tr>
      <tr class="hide collapse" style="display:none">
        <td>
          <h4>Column1</h4>
        </td>
        <td>
          <a class="connectorlink" href="https://yahoo.com" target="_blank">website</a>
        </td>
      </tr>
    </tbody>
  </table>
</body>

JavaScript

$(document).ready(function() {
  $('tr.header').click(function() {
    $(this).find('span').text(function(_, value) {});
    $(this).nextUntil('tr.header').slideToggle(100, function() {});
  });
});

function myFunction() 
{
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  
  // Loop through all table rows, and hide those that don't match the search query
  for (i = 0; i < tr.length; i++) 
  {
   td = tr[i];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) 
      {
        tr[i].style.display = "";
      } 
      else 
      {
        tr[i].style.display = "none";
      }
    }
  }
}

CSS

table,
tr,
td,
th {
  border-collapse: collapse;
}

h4,
{
  margin: 0;
  padding: 0;
  font-family: Inter;
  font-style: normal;
  font-size: 20px;
  font-weight: 600;
  line-height: 28px;
}


label {
  padding: 10px 10px 10px 12px;
}

.tabledesign {
  width: 900px;
  border-collapse: separate;
  border-spacing: 0 15px;
  margin: 50px auto;
}

th {
  background: #e5e5e5;
  color: rgba(0, 0, 0, 0.84);
  font-weight: bold;
}

td,
th {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: left;
  font-size: 18px;
}

#myInput {
  display: flex;
  background: #FFFFFF;
  font-family: Inter;
  /* Add a search icon to input */
  background-position: 10px 12px;
  /* Position the search icon */
  background-repeat: no-repeat;
  /* Do not repeat the icon image */
  width: 795px;
  /* Full-width */
  height: 46px;
  font-size: 16px;
  /* Increase font-size */
  padding: 12px 20px 12px 40px;
  /* Add some padding */
  border: 1px solid #ddd;
  /* Add a grey border */
  margin-bottom: 12px;
  /* Add some space below the input */
}

* {
  box-sizing: border-box;
}

Adding Try catch blocking [closed]

I am tasked at work to add a try/catch block around function calls for a class RAPI. Can someone help me figure out how to do this? Here’s sample code

const promise = LDC.load(docId).then(async entry => {
   if (!entry) {
       throw new Error("Not found");
   }

   const id = await RAPI.id();
   return kpl.send(id);
});

I need to add a try catch block around the RAPI.id function call in case it throws an error. We don’t want the app to crash. The goal is to avoid crashes when we call these functions.

Drag and Drop Interface with Web interface

I am looking to find some software that will allow a client to drag an image, change font color and lock text so they are uneditable.

Need to pass a weblink to my client so they can build a social media post

still looking. any help is appreciated

Rail Ajax post to controller action and iterate over in view

i have a unique combination array that generated in JavaScript based on two input fields, i am passing that combination array to combination action with AJAX POST.

How do i iterate that combination array inside _from.html.erb, so i can build field for Variants?.

Javascpit AJAX

 function generateUniqueCombinations(options, values) {
  var combinations = [];

  function generateCombinationsRecursive(currentIndex, combination) {
      if (currentIndex === options.length) {
          combinations.push(combination);
          return;
      }

      var currentOption = options[currentIndex];
      var currentValues = values[currentIndex];

      for (var i = 0; i < currentValues.length; i++) {
          var newValue = currentValues[i];
          var newCombination = combination ? combination + ' / ' + getOptionValueById(currentOption, newValue) : getOptionValueById(currentOption, newValue);
          generateCombinationsRecursive(currentIndex + 1, newCombination);
      }
  }

  generateCombinationsRecursive(0, '');
  //hiddenval.val(JSON.stringify(combinations));
  

  $.ajax({
    url: '/products/combinations',
    method: 'POST',
    data: { combinations: combinations }, // Send the combinations as data.
    headers: {
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    },
    success: function(response) {
      // Handle the response from the server if needed
    },
    error: function(xhr, status, error) {
      // Handle errors if necessary
    }
  });



  
  return combinations;
  
  

}

only way i got it to work passing params to current session

def combinations
 
 @combinations = params[:combinations]
 # Store @combinations in the session
 session[:combinations] = @combinations
 redirect_to new_product_path

end

but, even page reload params[:combinations] stays inside the @combinations

anyone got a suggestions none other than session params or solutions to make it work ?
Thanks

JSReport Docker Container not writing to data folder

I have been trying to create a docker image of Jsreport that persists even after it is stopped. However, no matter what I try, templates and work done in the portal that the image is running does not save to the data directory.

I have tried running the image and mounting the data directory that it is stored in

docker run -p 5483:5483 -v /mydata:/DOCKERJSREPORT/data jsreport-container

I have tried adding the property “Storage Path” In the Store Object of the config file:

"store": {
      "provider": "fs",
      "storagePath": "/DOCKERJSREPORT/data"
    },

And I have tried adding JSREPORT as a USER in my docker file:

USER jsreport

It runs with these and even loads all the stored custom templates from the data directory, but does not save or persist new ones. I’m at a lost please help!

Here is my full DockerFile in case it’s needed:

FROM jsreport/jsreport:3.13.0

USER jsreport

COPY --chown=jsreport:jsreport jsreport.config.json /app
COPY --chown=jsreport:jsreport /data /app/data

RUN npm install handlebars-intl --save

this is what my hierarchy looks like:

hierarchy