Timezone JS function

I am wanting to get this function to work to display the timezone in the footer of my webpage. As of now, when the webpage is loaded, the timezone does not appear in the footer of the webpage as intended.

This is what I have for JS script:

// This function displays the timezone.

function timezoneName() {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timezone);
document.getElementById("timezone").innerHTML = timezone;
}
timezoneName();

This is what I have for .html footer:

<footer>
<p id="timezone"></p>
</footer>

how to remove a classList when I select another element?

When I click on an ‘imposter’ I want it to become grey with some text as you can see in my CSS with the selector .imposter.voted. But when I click another imposter I want that one to appear grey and the previous one to appear like usual again.

When I try this.classList.remove("voted") it does not work and it just makes all the imposters I select grey. The class does not get removed. I don’t see where I went wrong.

imposters = document.querySelectorAll(".imposter");

for (let i = 0; i < imposters.length; i++) {
  imposters[i].addEventListener("click", function() {
    this.classList.add("voted");
  });
}
.imposter.voted {
  background-color: gray;
  position: relative;
  opacity: 0.7;
}

.imposter.voted::after {
  content: "I voted";
  position: absolute;
  top: 5px;
  right: 5px;
  display: inline-block;
  font-family: "Comic Sans Ms";
  color: red;
}

.imposters__voting {
  text-align: right;
}
<main class="dashboard">
  <h1>Who Is The Imposter?</h1>
  <div class="imposters">
    <div class="imposter">Baba</div>
    <div class="imposter">Baraki</div>
    <div class="imposter">Garfield</div>
    <div class="imposter">Erik</div>
    <div class="imposter">GreenBlood4</div>
    <div class="imposter">Easter</div>
  </div>
</main>

PNPM docker non-root user Permission Denied

I just found about pnpm today and it helped solve my issue with npm timing out on my installation which is amazing.
I’ve a problem with pnpm tho in the docker image.

Previously with just npm I had unprivileged user like so

FROM node:14.17.3-slim

# build args
ARG NPM_AUTH_TOKEN
ARG HOME=/home/app
ARG NPMRC_PATH=$HOME/.npmrc

# setup unprivileged user
RUN useradd -Umrd $HOME app
WORKDIR $HOME
USER app

# copy configuration
COPY --chown=app:app "bin" "bin"
COPY --chown=app:app "package.json" "package-lock.json" "webpack.config.js" ".babelrc" ./

RUN ./bin/write_npmrc && 
    npm ci --production=false

ENV NODE_ENV=development
VOLUME ["$HOME/config", "$HOME/log", "$HOME/src"]
CMD ["npm", "start"]
EXPOSE 9000

But if I switch to the pnpn I’m no longer able to proceed with building the image due to Permission Denied and I need to use root user.

FROM node:14.17.3-slim

# build args
ARG NPM_AUTH_TOKEN
ARG HOME=/home/app
ARG NPMRC_PATH=$HOME/.npmrc

RUN apt-get update && apt-get install -y curl 
 && rm -rf /var/lib/apt/lists/*
RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm

WORKDIR $HOME

# copy configuration
COPY "bin" "bin"
COPY "package.json" "pnpm-lock.yaml" "webpack.config.js" ".babelrc" ./

RUN ./bin/write_npmrc && 
    pnpm install --frozen-lockfile

ENV NODE_ENV=development
VOLUME ["$HOME/config", "$HOME/log", "$HOME/src"]
CMD ["pnpm", "start"]
EXPOSE 9000

Is there a way so I can keep

# setup unprivileged user
    RUN useradd -Umrd $HOME app
    WORKDIR $HOME
    USER app

With pnpm instead?

Use fetch or axios to display html content of another page running the scripts

I want to use fetch or axios to download a html content of a page, this works fine but the javascript code inside the page does not run

here is what i’ve tried

document.getElementById('test').innerHTML=
await (await fetch('url')).text()

what i want is similar to this answer, but i want to get the page with the javascript inside processed instead of running a script.

Can I run a JS script from another using `fetch`?


My goal is to create a boostrapEmail template that i can send parameters and make it dynamic, using localstorage

https://bootstrapemail.com/docs/introduction

Im trying to split n to make a breakline in ReactJS

I received this string: Ticket #: 9 (ORIGINAL)nDate/Time: 12/10/2020 03:33 PM from an API, I want to breakline using n and I use useState to print it:

const [Ticket, setTicket] = useState('');

const getData = async (ID, Serial) => {
    try{
      const res = await FetchRewards(ID, Serial)
      console.log('%c Ticket has been found Successfully. Status: 200 ', 
     'background: #28a745; color: #fff')

        setTicket(res.data.ticket.ticket);
        console.log(res)
    }
    catch (err){
      console.error("404: Ticket not found")
    }
  }

but my problem is trying to make split on Ticket to make breaklines using n, this is my split function to do that:

const text = `Ticket #: 9 (ORIGINAL)nDate/Time: 12/10/2020 03:33 PM`;

let ticketWrap = text.split("n").map(i =>{
    return `<p>${i}</p>`; // this is JSX in my real code
});

console.log(ticketWrap)

When I add a text with n,ticketWrap returns the breakline, but using Ticket it returns: Ticket #: 9 (ORIGINAL)nDate/Time: 12/10/2020 03:33 PM

Send a Single Email to Project Owner w/All Related Project Subtasks & w/All Project Notes

I am trying to write a Javascript/appscript for an Appsheet app. I cant figure this out, if someone could please help.

I have Three Sheets:
Project
Subtasks
Notes

I would like to be able to send the Project owner an email, that includes the project name all of the tasks assigned to that project (relationship via PK/FK ID,Project Name) and all of the notes assigned to that project (same relationship as Notes PK/FK ID,Project Name)

  • I have provided a sample of all the tables, their columns, and an ideal sample output

idealOutput

Module parse failed: Unexpected token – react-refresh-webpack-plugin/loader

I built a react component package locally, with Rollup.

Tech stack of package is: React, typescript, styled-components and so on…

  1. That package lives inside of the one project.

  2. Now I am trying to use that package inside of another project locally.

  3. Now I am trying to test that package

    • yarn link
    • open second project executed yarn link “package-name”
    • Imprted component (package)
    • yarn start

Result:

Failed to compile.

../enrollment-client/src/components/GeneralSectionForm/GeneralSectionForm.tsx 31:7
Module parse failed: Unexpected token (31:7)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| import { TOAST_ERRORS } from '../../utils/constants';
| 
> export type QuestionElementRef = {
|   id: string | undefined;
|   element: HTMLDivElement | null;

got the error regarding that the current webpack configuration inside of the project is not enough to compile this package – something like that.

That is something that I am currently investigating, and trying to figure out why? πŸ™‚

Any help will be super appreciated

Prevent tooltip from showing using onTrigger

Situation: I have a div with a Tippy attached to it, and inside the DIV there are highlighted spans with their own tooltips. They all use ‘click’ as triggers.

Ideal behavior: When I click on a highlight, only the highlight Tippy should show.

Current behavior: Both tooltips show at the same time.

I can catch the click with onTrigger, using “event.target”. However, “return false” or “instance.hide()” do not prevent it from showing. Is there a way I can do that with onTrigger?

tippy(divEl, {
content: 'Tooltip!',
   allowHTML: true,
  onTrigger(instance, event) {
    if (event.target.className == 'highlight') 

{console.log('It should hide the tooltip!');
instance.hide();
return false;
}
  },
    arrow: true,
    interactive: true,
    trigger: 'click',
    theme: 'light-border',
    zIndex: 9999
      });
}

I got it working with the following trick, but it wouldn’t work if I had other DIVs inside the main DIV:

tippy(divEl, { ...,

onShow(instance) {
    if (item.lastChild.nodeName == "DIV") {return false}
  },
});

How to select diferent modals with one function?

i tried the lightbox from W3 school and it works nicely, but if I have more modals on one page the script open all of them together.

Is it possible to set within one script some condition which modal should be opened? Or/and is this the correct way of thinking how to code it?

I omitted from code lower the styling and tons of other content to make it shorter but i didn’t do any changes in the original script from W3 except of adding new line of “myModal1” to functions open/closeModal which is the problem i try to solve.

Thank you very much in advance for your answers. πŸ™‚

<div id="epo20-23">
    <div class="row">
        <div class="whole-gallery">
            <h2 style="text-align:center;" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">gallery
            </h2>
        </div>
    </div>
    <div id="myModal" class="modal">
        <span class="close cursor" onclick="closeModal()">&times;</span>
        <div class="modal-content">
            <div class="mySlides">
                <div class="numbertext">1 / 2</div>
                <img src="image1.jpg" style="width:100%">
            </div>
            <div class="mySlides">
                <div class="numbertext">2 / 2</div>
                <img src="image2.jpg" style="width:100%">
            </div>
            <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
            <a class="next" onclick="plusSlides(1)">&#10095;</a>
            <div class="caption-container">
                <p id="caption"></p>
            </div>
            <div class="column-container">
                <div class="column">
                    <img class="demo cursor" src="image1.jpg" style="width:100%" onclick="currentSlide(1)">
                </div>
                <div class="column">
                    <img class="demo cursor" src="image2.jpg" style="width:100%" onclick="currentSlide(2)">
                </div>
            </div>
        </div>
    </div>
</div>
<div id="epo24-38">
    <div class="row">
        <div class="whole-gallery">
            <h2 style="text-align:center;" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">gallery
            </h2>
        </div>
    </div>
    <div id="myModal1" class="modal">
        <span class="close cursor" onclick="closeModal()">&times;</span>
        <div class="modal-content">
            <div class="mySlides">
                <div class="numbertext">1 / 2</div>
                <img src="image3.jpg" style="width:100%">
            </div>
            <div class="mySlides">
                <div class="numbertext">2 / 2</div>
                <img src="image4.jpg" style="width:100%">
            </div>
            <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
            <a class="next" onclick="plusSlides(1)">&#10095;</a>
            <div class="caption-container">
                <p id="caption"></p>
            </div>
            <div class="column-container">
                <div class="column">
                    <img class="demo cursor" src="image3.jpg" style="width:100%" onclick="currentSlide(1)"
                        alt="img3">
                </div>
                <div class="column">
                    <img class="demo cursor" src="image4.jpg" style="width:100%" onclick="currentSlide(2)"
                        alt="img4">
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function openModal() {
        document.getElementById("myModal").style.display = "block";
        document.getElementById("myModal1").style.display = "block";
    }

    function closeModal() {
        document.getElementById("myModal").style.display = "none";
        document.getElementById("myModal1").style.display = "none";
    }

    var slideIndex = 1;
    showSlides(slideIndex);

    function plusSlides(n) {
        showSlides(slideIndex += n);
    }

    function currentSlide(n) {
        showSlides(slideIndex = n);
    }

    function showSlides(n) {
        var i;
        var slides = document.getElementsByClassName("mySlides");
        var dots = document.getElementsByClassName("demo");
        var captionText = document.getElementById("caption");
        if (n > slides.length) { slideIndex = 1 }
        if (n < 1) { slideIndex = slides.length }
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        for (i = 0; i < dots.length; i++) {
            dots[i].className = dots[i].className.replace(" active", "");
        }
        slides[slideIndex - 1].style.display = "block";
        dots[slideIndex - 1].className += " active";
        captionText.innerHTML = dots[slideIndex - 1].alt;
    }
</script>

How to get the details on backend nodejs with the GET request in angular

I am unable to fetch the query parameters of frontend GET request, on the backend side.
I tried using url and query. I need to fetch the query on the nodejs side.
Kindly suggest a suitable method that would help me get the details on GET request using axios.

code –

component.ts – angular file

googleSearch(googleText){


let params = new HttpParams();
    params = params.append('q', googleText.trueLocation);
       

return new Promise((resolve, reject) => {
this.httpClient.get("http://localhost:3003/seekSearchApi" , ({params:params}))
      .pipe(map(Response => Response))
    
      .pipe(catchError(this.errorHandler))
      .subscribe((res: Response) => {

        this.writeItOutput = res;
        
        resolve(this.writeItOutput);

      });

    })
    
  

}
errorHandler(error: HttpErrorResponse) {
  return throwError(error.message || 'server Error');
}
}

server.js- express file

app.use('/seekSearchApi', require('./server/nodejs-serverapi'));

applicationserver.js – nodejs file

function seekSearchApi(req,res) { 

var query = require('url').parse(req.url,true).query;

console.log("req.query.q", query.q);  //no response

console.log("Inside seekSearchApi");

  axios({
    method: 'get',
    url: 'https://serpapi.com/search.json?',
    data: {
      api_key: "xxxx",
      q:query.q
      hl: "en",
      gl: "us",
      google_domain: "google.com"
    }
  }).then((response) => {
    res.send(stringify(response))
   
  }, (error) => {
    console.log(error);
  });

Testing React/Jest component with Window.onload

I’m testing a functional component that uses Window.onload to stay on a certain page. Example of the code

function SignUpForm(props) {

  const history = useHistory();
  const {setOnPage } = props;
  window.onload = setOnPage("/registrarse")

My test is:

import React from 'react'
import Enzyme from "enzyme";
import { screen, render } from '@testing-library/react'

import SignInScreen from './SignInScreen'
import Adapter from "enzyme-adapter-react-16"

const { shallow } = Enzyme; 

Enzyme.configure({ adapter: new Adapter() })

describe('Test for login in form', () => {
    test("renders correctly", () => {
        shallow(<SignInScreen/>);
      });
});

The error is in the line of Window.onload, I have not been able to find any solution that can help me.

setOnPage is not a function

Material table data prop and redux

So Hi i am trying to render columns and rows in material table which are loaded from redux.

Let my try to explain

const data = useKPIReport(_ => _.data) // from redux

<TableContainer>
        <MaterialTable
          tableRef={tableRef}
          columns={options.columns}
          options={}
           data={
            async (query) => {
              const {
                page,
                pageSize
              } = query
              try {
                const fetchReport = async () => {
                  try {
                    const result = await postReport({
                      startDate: startDateEpoch / 1000,
                      endDate: endDateEpoch / 1000,
                      page: page + 1,
                      pageSize,
                      accountId
                    })
           
                    const { rows, totalRowsCount } = data // this is important data from redux
                    return {
                      columns: formattedCols,
                      totalCount: totalRowsCount,
                      rows
                    }
                  } catch (e) {
                    console.error(e)
                    return handleError()
                  }
                }
                const result = await fetchReport()
          
                return ({
                  data: result.rows,
                  page,
                  totalCount: result.totalCount,
                })
              } catch (e) {
                console.error(e)
                dispatch(snackbarMessagesAction({
                  severity: 'error',
                  messages: [t('Failed to fetch report')]
                }))
                return ({
                  data: [],
                  page: 0,
                  totalCount: 0
                })
              }
            }}

So overall postReport() method it doesn’t return any results, it sends data to redux, and look like redux is updated later so it’s not possible return results in time.

Any idea how to tackle this in data prop, i have tried something with useEffect:

 React.useEffect(() => {
    tableRef.current && tableRef.current.onQueryChange()
  }, [data])

but feeling this is not possible, i need some general idea usually API endpoint (“postReport()”) returns results but that is not option for me since i am storing results into redis, and later redux is updated via server side event.

Regex to ignore digits before and after a number but accept the number in standalone? [duplicate]

Can someone help me with a regular expression? How can I write one in JS that will accept:

β€œ42”
β€œ42 is my favorite number”
β€œI have 42 cats”
β€œI really like 42”

But reject
β€œ12342”
β€œ423”
β€œ14211”
β€œ167889994442113233”
Etc.

I tried D*42D* but no dice.. it’s been keeping me up! Any tips? It’s been a few years since I covered regexs

How I center my HTML iframe in Android webivew?

I have an iframe in my Android webview that I am loading like this:

     String folderPath = "file:android_asset/";
     String fileName = "index.html";
     String file = folderPath + fileName;
     webView.loadUrl(file);

The iframe is loaded via HTML and CSS files located in my android/assests folder. The HTML and CSS look like this. HTML:

<!DOCTYPE html>
<html lang="en">
<body>
<link rel="stylesheet" type="text/css" href="default.css"  />
    <div class="abs-frame-container">
    <iframe 
      id="my_frame"
      src="my web page link"
      scrolling="no"
      allowtransparency="true" 
      style="border:none;overflow:hidden">
    </iframe>
    </div>
</body>
</html>

and my CSS

#my_frame {
  position: absolute;
  top: 0%;
  bottom: 0%;
  right: 0%;
  width: 117%;
  height: 100%;
}

#abs-frame-container{
    top: 10%;
    bottom: 0%;
    position: relative;
}

The webpage in iframe shows fine in the webview. I want to center (vertical alignment) my iframe in the webview so that it aligns automatically based on the webview dimensions (height). Would appreciate a lot if someone could help me how this can be achieved?