Downloaded PDF shows blank pages when pulling from SQL db

I’m pulling PDF files from a SQL table, and then wanting to show the PDF in a new window rather than download to the user’s computer. I get the data successfully, but when I try to view the PDF I get blank pages. The right number of pages shows but content is blank. Can’t understand what’s happening. Here is my code:

        var ms = new Date();
        var params = "action=DownloadFile2&ms=" + ms.getTime() + "&file_id=" + file_id;
        var url = urlPath + params;
        $.ajax({
            type: "POST",
            method: "POST",
            responseType: "blob",
            url: url,
            
            success: function (data) {
                var file = new Blob([data], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(file);
                window.open(fileURL, '', "height=1000, width=2000");
            }

Code behind: If IsDBNull(dt) = True Then Exit Sub

    Dim filename As String
    filename = Trim(dt.Rows(0)("Name").ToString())

    Dim filetype As String
    filetype = Trim(dt.Rows(0)("File_Type").ToString())

    Dim encodedBytes As Byte() = Convert.FromBase64String(Convert.ToBase64String(CType(dt.Rows(0)("Data"), Byte())))

    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.AddHeader("Pragma", "public")
    HttpContext.Current.Response.AddHeader("Cache-Control", "max-age=0")
    HttpContext.Current.Response.AddHeader("Content-disposition", "attachment;filename=" & filename)
    HttpContext.Current.Response.ContentType = "application/pdf"
    HttpContext.Current.Response.SuppressContent = False
    Response.Headers.Add("Content-Length", encodedBytes.Length.ToString())

    Dim outputStream As Stream = HttpContext.Current.Response.OutputStream

    outputStream.Write(encodedBytes, 0, encodedBytes.Length)
    outputStream.Flush()
    outputStream.Close()

I tried to open the PDF in a new window, I just get blank pages. One document showed page 1 and rest blank.

How to properly infer the Constructor of an object through JSDoc?

I want to make this function that receives a parameter and return its class if object, the parameter itself if function or the legacy object constructor if anything else.

In JavaScript the example below covers the functionality for most cases. But the JSDoc doesn’t follow…

export const ParseType = ( Subject ) =>
{
   if ( ( typeof Subject == 'function' ) && ( typeof Subject.prototype == 'object' ) )
   {
      return Subject;
   }
   
   return Object(Subject).constructor;
}

function MyCustomType ()
{
   
}
// JSDoc signature: () => void

const MyCustomInstance = new MyCustomType;
// JSDoc signature: any
// Expecting JSDoc signature: MyCustomType

const MyRetrievedCustomType = ParseType(MyCustomInstance);
// JSDoc signature: any
// Expecting JSDoc signature: typeof MyCustomType

To fix this issue, I can do something like this:


/**
 * @template [Type = InstanceType < typeof Object >]
 * @param { Type } [Subject = Type]
 */
export const ParseType = ( Subject ) =>
{
   let Inferred;
   
   if ( ( typeof Subject == 'function' ) && ( typeof Subject.prototype == 'object' ) )
   {
      Inferred =
      (
         /**
          * @type { Type extends Function & { prototype: {} } ? Type : never }
          */
         ( Subject )
      );
   }
   
   else
   {
      const Instance =
      (
         /**
          * @type { Subject & {} }
          */
         ( Object(Subject) )
      );
      
      Inferred =
      (
         /**
          * @type { Type extends Function & { prototype: {} }
          *          ? never
          *          : Instance extends { constructor: infer Constructor }
          *             ? Constructor
          *             : never
          *       }
          */
         ( Instance.constructor )
      );
   }
   
   return Inferred;
}

/**
 * @constructor
 */
function MyCustomType ()
{
   
}
// JSDoc signature: typeof MyCustomType

const MyCustomInstance = new MyCustomType;
// JSDoc signature: MyCustomType

const MyRetrievedCustomType = ParseType(MyCustomInstance);
// JSDoc signature: Function
// Expected JSDoc signature: typeof MyCustomType
// JavaScript actual value: [Function MyCustomType]

const MyRegrievedStringType = ParseType('MyString');
// JSDoc signature: Function
// Expected JSDoc signature: StringConstructor
// JavaScript actual value: [Function String]

I can’t extract the constructor from Instance correctly because JSDoc infers the constructor at ObjectConstructor.constructor which is Function. Oddly enough, when I’m extracting the constructor from Instance, in the casting JSDoc type tag I can test Instance against any class and evaluate as the “hard coded” class…

/**
 * @type { Instance extends MyCustomType ? typeof MyCustomType : never }
 */

Or even chaining like this…

/**
 * @type { Instance extends String ? typeof String : Instance extends BigInt ? typeof BigInt : never : never }
 */

But I can’t just keep increasing this chain and hard coding all the classes that could possibly be used in any project that will use this function…

Google Sign-In in React Native WebView opens new tab in Chrome and does not return to app

I’m using a WebView in my React Native app to load a website with Google Sign-In functionality. However, when I click the “Sign in with Google” button, it opens a new tab in Chrome. After selecting an email for login, the page just keeps showing a loading screen and does not return to the app or proceed with the sign-in.

code :

 <WebView
  allowFileAccess
  allowFileAccessFromFileURLs
  sharedCookiesEnabled
  thirdPartyCookiesEnabled
  nestedScrollEnabled
  userAgent="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
  source={{ uri: 'here i provide my url' }} 
  style={{ flex: 1 }}
/>

Problem:
Google Sign-In opens a new Chrome tab instead of staying within the WebView.
After selecting the email for Google login, the process gets stuck on a loading screen and doesn’t proceed further or return to the app.

What I’ve tried:
Enabled third-party cookies (thirdPartyCookiesEnabled).
Set a custom user agent.
Ensured sharedCookiesEnabled is enabled.

Any suggestions on how to fix this issue?

How to find distance between top of element and top of viewable webpage

I have an element that has position sticky and has the top property set to 30px. I want it so that when the element becomes stuck (so to say) It has a class of stuck added to it. I’m aware it can be done with intersectionObserver however I would like to know a way that I could do it in vanilla HTML, CSS or JS.

The way I have thought of so far is to add the class once the elements distance from the top of the viewable webpage is 30px. When researching, I have come across code like this:

var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top

Although this does do something, it doesn’t do want I want. What it does is it finds the top of the element to the top of the window height.

(Now at the time of writing this I am not sure if the window height is what it is called but I mean the bit of the webpage that you would get to if you scrolled up until you couldn’t any more. Sometimes it is out of sight).

Using this code, the value I get is always constant as the element is not moving up or down the page, it is only the viewport is moving down the page as you scroll down.

Instead, the value that the function (or whatever) returns should change depending on where you have scrolled to. Before the ‘stuck’ position activates, the distance from the top should vary depending on where you scroll. But once you have hit its ‘stuck’ threshold the distance from the top should stay the same.

I don’t mind the solution as long as it uses HTML, CSS or JS but nothing else.

Bar Icon onTouchEnd problem with animation on mobile device

I created a bar that looks like macOS bar, but when I’m using my phone, I clicked and the animation look like this, like it hasn’t done its hover animation:

clicked

It should look like this when I click (this is on the computer screen with mouse)

pc

I tried to figure out how, and I looked at the onTouch event, but it didn’t fix me; it also affects my tooltip, which can’t be closed when I’m using a mobile device.

This is my snip code BarIcon.js:

const BarIcon = ({ icon, name, url, clickHandler, changeColor, theme }) => {
  const [bounce, setBounce] = useState(false);
  const [hover, setHover] = useState(false);

  const changeHandler = () => {
    setBounce(true);
    setTimeout(() => {
      setBounce(false);
    }, 500);
  };

  const location = useRouter();
  const path = location.pathname;
  const displayNav = path === url;

  const handleClick = () => {
    setHover(false);
    setTimeout(() => {
      changeHandler();
      if (clickHandler) {
        clickHandler();
      }
    }, 50);
  };

  return (
    <div className="Icon--container" alt={name} style={{ position: "relative" }}>
      <div className={bounce ? "Icon--bounce icon2" : "icon2"}>
        <Tag
          pos="fixed"
          top={{ xs: "-37px", md: "-40px" }}
          w="auto"
          d={hover ? "block" : "none"}
          bg={changeColor ? "#fefefe" : "#161616"}
          border="0.5px solid"
          borderColor={changeColor ? "#dbdbdb" : "#3e3e3e"}
          textColor={changeColor ? "#858585" : "#7e7e7e"}
          transition="0.3s"
          zIndex="9999"
        >
          {name}
        </Tag>
        <span
          id="icon"
          className={"Icon Icon" + theme}
          onClick={handleClick}
          onTouchEnd={handleClick} // Đảm bảo xử lý nhấp chuột trên thiết bị di động
          onMouseEnter={() => setHover(true)}
          onMouseLeave={() => setHover(false)}
        >
          <Icon
            name={bounce ? "Loading" : icon}
            color={changeColor ? "#858585" : "#7e7e7e"}
            size="22px"
          />
        </span>
      </div>
      <Icon
        d={displayNav ? null : "none"}
        name="Dot"
        m="auto"
        color={changeColor ? "#dbdbdb" : "#3e3e3e"}
        size="10px"
      />
    </div>
  );
};

And this is my CSS for handling the hover event of the button:

.Icon:hover{
    transform: scale(1.4) translateY(-15px) ;
    margin: 20px 15px 0px 15px;
}
.Icon:not(:hover){
    transform: scale(1) ;
}

How can I read and save the content of a slot in Vue.js at runtime?

I’m currently working on a project with Vue.js and have a problem with using slots.

I have two components: PageView.vue and SlotComponentView.vue In SlotComponentView.vue, there is a slot named Content that is used in PageView.vue. For example, I add an input field to this slot, which is correctly inserted into the component at runtime.

Now, I want to read and save the content of this slot (specifically the value of the input field) from SlotComponentView.vue at runtime. The goal is to implement something like a “savable filter”. The filter has a slot where I can place any input (such as text fields), and in SlotComponentView.vue, I want to use a button to read and save those inputs.

Does anyone have an idea how I can access the content of a slot at runtime in order to process the data in the parent component?

Thanks in advance!

Access Slot Element Value

Cannot Find Asset error AWS Lambda Stack even when the directory to the asset looks fine

Image of directory I was trying to deploy a lambda stack that contains a lambda function. The code that the function will run lies in a services folder under the source folder. I run into a cannot find asset error even when the directory to my file seems to be correct in the lambda function. Does anyone know what I am missing?

import { Stack, StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";
import {
  Code,
  Function as LambdaFunction,
  Runtime,
} from "aws-cdk-lib/aws-lambda";
import { join } from "path";

export class LambdaStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new LambdaFunction(this, "getBooksLambda", {
      runtime: Runtime.NODEJS_18_X,
      handler: "getBooks.main",
      code: Code.fromAsset(join(__dirname, "..", "..", "services", "getBooks")),
    });
  }
}

exports.main = async function(event, context) {
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: "Hello from Lambda"
        })
    }
}

Error: Cannot find asset at C:UsersUserDocumentsBookeroobookeroo-cdksrcservicesgetBooks
at new AssetStaging (C:UsersUserDocumentsBookeroobookeroo-cdknode_modulesaws-cdk-libcorelibasset-staging.js:1:2119)
at new Asset (C:UsersUserDocumentsBookeroobookeroo-cdknode_modulesaws-cdk-libaws-s3-assetslibasset.js:1:1141)
at AssetCode.bind (C:UsersUserDocumentsBookeroobookeroo-cdknode_modulesaws-cdk-libaws-lambdalibcode.js:5:3487)
at new Function (C:UsersUserDocumentsBookeroobookeroo-cdknode_modulesaws-cdk-libaws-lambdalibfunction.js:1:10003)
at new LambdaStack (C:UsersUserDocumentsBookeroobookeroo-cdksrcinfrastacksLambdaStack.ts:13:32)
at Object. (C:UsersUserDocumentsBookeroobookeroo-cdksrcinfraLauncher.ts:12:1)
at Module._compile (node:internal/modules/cjs/loader:1241:14)
at Module.m._compile (C:UsersUserDocumentsBookeroobookeroo-cdknode_modulests-nodesrcindex.ts:1618:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
at Object.require.extensions. [as .ts] (C:UsersUserDocumentsBookeroobookeroo-cdknode_modulests-nodesrcindex.ts:1621:12)

I just tried running it expecting the cdk synth to not throw an error. I also tried moving around the getBooks file and also adding .js to the end of the directory. None of them worked

Overflow-x cuts off objects moving in Y axis

I wanted to animate the lifts, so that it can move up when a button is pressed. I will do that automation later as I’m stuck now.
But when I use overflow-x: hidden;, it hides the lift moving up/down. I am not removing overflow-x because I don’t want the lifts to get compressed.

const submitButton = document.querySelector('.submit');
const backButton = document.querySelector('.back');
const inputSection = document.getElementById('input-section');
const simulationSection = document.getElementById('simulation');
let floorNos = document.getElementById('floors');
let liftNos = document.getElementById('lifts');


function clearContent() {
    while (simulationSection.firstChild) {
        simulationSection.removeChild(simulationSection.firstChild);
    }
}

submitButton.addEventListener('click', () => {
    let errorMessage = '';
    let n = parseInt(floorNos.value);
    let m = parseInt(liftNos.value);

    if (isNaN(n) || n < 1) {
        errorMessage += 'Invalid Floor Input.n';
    }
    if (isNaN(m) || m < 1) {
        errorMessage += 'Invalid Lift Input.n';
    }

    if (errorMessage) {
        alert(errorMessage);
    } else {
        const newSimLiftsContainer = document.createElement('div');
        newSimLiftsContainer.id = 'sim-lifts';


        for (let i = 0; i < n; i++) {
            const floorDiv = document.createElement('div');
            floorDiv.classList.add('sim-floors');

            const buttonContainer = document.createElement('div');
            buttonContainer.classList.add('button-container');

            const upButton = document.createElement('button');
            upButton.classList.add('up');
            upButton.textContent = 'Up';
            const downButton = document.createElement('button');
            downButton.classList.add('down');
            downButton.textContent = 'Down';

            if (i === n - 1) upButton.style.display = 'none';
            if (i === 0) downButton.style.display = 'none';

            buttonContainer.appendChild(upButton);
            buttonContainer.appendChild(downButton);

            const floorContainer = document.createElement('div');
            floorContainer.classList.add('floor-container');

            const line = document.createElement('div');
            line.classList.add('line');

            const floorNo = document.createElement('div');
            floorNo.classList.add('floor-no');
            floorNo.textContent = `Floor ${i + 1}`; 

            floorContainer.appendChild(line);
            floorContainer.appendChild(floorNo);

            floorDiv.appendChild(buttonContainer);
            floorDiv.appendChild(floorContainer);

            simulationSection.appendChild(floorDiv);


            if (i === 0) {
                for (let j = 0; j < m; j++) {
                    const lift = document.createElement('div');
                    lift.classList.add('lift');

                    const liftDoorLeft = document.createElement('div');
                    liftDoorLeft.classList.add('lift-door-left');

                    const liftDoorRight = document.createElement('div');
                    liftDoorRight.classList.add('lift-door-right');

                    lift.appendChild(liftDoorLeft);
                    lift.appendChild(liftDoorRight);

                    newSimLiftsContainer.appendChild(lift);
                }

                floorDiv.appendChild(newSimLiftsContainer);
            }
        }
        newSimLiftsContainer.scrollLeft = newSimLiftsContainer.scrollWidth;
        inputSection.style.display = 'none';
        simulationSection.style.display = 'flex';
        backButton.style.display = 'block';

        newSimLiftsContainer.addEventListener('wheel', (e) => {
        e.preventDefault();
        newSimLiftsContainer.scrollLeft += e.deltaY;

        });
    }
});

backButton.addEventListener('click', () => {
    clearContent();
    simulationSection.style.display = 'none';
    inputSection.style.display = 'flex';
    backButton.style.display = 'none';
});
/*For Input*/
#simulation {
  display:none;
}
.back{
  display:none;
}
#input-section,
#simulation {
  width: 100%;
  height: 100%;
}

#input-section {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.input {
  margin: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font: bold larger Arial, Helvetica, sans-serif;
  padding-top: 200px;
}

#floors {
  margin-bottom: 100px;
}

.button{
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.submit{
  cursor:pointer;
  height:60px;
  width:120px;
  background-color:rgb(251, 251, 251);
  border-radius: 10px;
  border: 1px solid black;
}

.submit:hover{
  background-color:rgb(177, 177, 177);
}

.submit:active{
  background-color:rgb(126, 128, 128);
}

#floors,#lifts{
  width:190px;
  border-radius:5px;
  border: 1px solid black;
}

/*For Simulation*/

#simulation {
  font: bold larger Arial, Helvetica, sans-serif;
  display: flex;
  flex-direction: column-reverse;
  gap: 50px;
}

.sim-floors {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
  height: 150px;
}

.sim-floors:last-child {
  margin-top: 100px;
}

.button-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-top: 40px;
  width: 80px;
  z-index: 1;
}


.floor-container {
  display: flex;
  align-items: center;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}

.line {
  flex-grow: 1;
  border-top: 4px solid black;
  margin: 0 10px;
}

.floor-no {
  text-align: right;
  font-size: 18px;
  margin-top: 3px;
}

.up, .down {
  font-weight: 800;
  border-radius: 10px;
  border: none;
  padding: 10px 20px;
  margin-bottom: 3px;
  cursor: pointer;
  display: flex;
}

.up {
  background: #00b300;
  color: black;
}

.up:hover {
  background: #00b3009a;
}

.up:active{
  background: #00b300e0;
}

.down {
  background: #ffcc00;
  color: black;
}

.down:hover{
  background: #ffcc00a4;
}

.down:active{
  background: #ffcc00d2;
}

#sim-lifts {
  position: relative;
  display: flex;
  white-space: nowrap;
  max-width: 90.3%; 
  margin-left: 90px;
  padding-top: 60px;
  scrollbar-width: none;

}

#sim-lifts::-webkit-scrollbar {
  display: none;
}

.lift {
  z-index: 100;
  animation: moveUp 10s infinite;
  min-width: 60px;
  flex-shrink: 0;
  height: 75px;
  background: rgb(0, 153, 255);
  position: relative;
  margin: 0 5px;
  overflow-x: hidden;
}

.back{
  font-family: Arial, Helvetica, sans-serif;
  font-weight: 600;
  position:absolute;
  top:10px;
  right:10px;
  float:right;
  background:rgba(60, 0, 255, 0.522);
  padding: 7px;
  border-radius: 10px;
  border:none;
  padding-top:10px;
  padding-bottom:10px;
  cursor:pointer;
}

.back:hover{
  background: rgba(60, 0, 255, 0.381);
}

.back:active{
  background: rgba(60, 0, 255, 0.474);
}

.lift-door-left,
.lift-door-right {
  width: 50%;
  height: 100%;
  position: absolute;
}
.lift-door-left {
  background: silver;
  border-right: 1.5px solid black;
  left:0;
  animation: ldoor 5s;
}
.lift-door-right {
  background: silver;
  border-left: 1.5px solid black;
  right:0;
  animation: rdoor 5s;
}

@keyframes ldoor{
  0%{left:0;}
  50%{left:-50%;}
  100%{left:0;}
}

@keyframes rdoor{
  0%{right:0;}
  50%{right:-50%;}
  100%{right:0;}
}

@keyframes moveUp{
  0%{transform: translateY(0px);}
  50%{transform: translateY(-200px);}
  100%{transform: translateY(0px);}
}
<div id="input-section">  
  <div class="input">
    <div>
      Enter the no. of Floors: <br><br>
    </div>
    <input id="floors" style="font-size:16pt;" type="number" placeholder="Enter the no. of floors"/>
    <div>
      Enter the no. of Lifts: <br><br>
    </div>
    <input id="lifts" style="font-size:16pt;" type="number" placeholder="Enter the no. of lifts"/>
  </div>
  <div class="button">
  <button class="submit" style="font-size:16pt;">Submit</button>
  </div>
</div>

<div>
  <button class="back" style="font-size:16pt;">GO BACK</button>
</div>

<div id="simulation"></div>

custom Javascript tracking code, to accept code tracking events initial page has fired

I have an existing javascript code, which tracks page views and fires correctly on page load. however, i want to now add the ability to allow event tracking, eg onclick, scrollto etc.

The issue is after the page is loaded and the trackPageView has fired i am no longer able to push any more events i get _viq.push is not a function as it converts to an object. I have tried for over 12 hours, googled many articles, but to of no avail.

Here is the script that i embed on the page:

   var _viq = window._viq = window._viq || [];
  _viq.push(['trackPageView']);
  (function() {
    var u="https://visitor-inisghts.local:1443/";
    _viq.push(['setAccount', 'dev']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.src=u+'tracking.js'; s.parentNode.insertBefore(g,s);
  })();

Below is the code for the tracking script:

'use strict'


/*! js-cookie v3.0.1 | MIT */
!function (e, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : (e = e || self, function () { var n = e.Cookies, o = e.Cookies = t(); o.noConflict = function () { return e.Cookies = n, o } }()) }(this, (function () { "use strict"; function e(e) { for (var t = 1; t < arguments.length; t++) { var n = arguments[t]; for (var o in n) e[o] = n[o] } return e } return function t(n, o) { function r(t, r, i) { if ("undefined" != typeof document) { "number" == typeof (i = e({}, o, i)).expires && (i.expires = new Date(Date.now() + 864e5 * i.expires)), i.expires && (i.expires = i.expires.toUTCString()), t = encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape); var c = ""; for (var u in i) i[u] && (c += "; " + u, !0 !== i[u] && (c += "=" + i[u].split(";")[0])); return document.cookie = t + "=" + n.write(r, t) + c } } return Object.create({ set: r, get: function (e) { if ("undefined" != typeof document && (!arguments.length || e)) { for (var t = document.cookie ? document.cookie.split("; ") : [], o = {}, r = 0; r < t.length; r++) { var i = t[r].split("="), c = i.slice(1).join("="); try { var u = decodeURIComponent(i[0]); if (o[u] = n.read(c, u), e === u) break } catch (e) { } } return e ? o[e] : o } }, remove: function (t, n) { r(t, "", e({}, n, { expires: - 1 })) }, withAttributes: function (n) { return t(this.converter, e({}, this.attributes, n)) }, withConverter: function (n) { return t(e({}, this.converter, n), this.attributes) } }, { attributes: { value: Object.freeze(o) }, converter: { value: Object.freeze(n) } }) }({ read: function (e) { return '"' === e[0] && (e = e.slice(1, - 1)), e.replace(/(%[dA-F]{2})+/gi, decodeURIComponent) }, write: function (e) { return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent) } }, { path: "/" }) }));
/*!
 * generateUUID function
 * http://stackoverflow.com/a/8809472
 */
function generateUUID() { var x = (new Date).getTime(), e = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (e) { var r = (x + 16 * Math.random()) % 16 | 0; return x = Math.floor(x / 16), ("x" == e ? r : 3 & r | 8).toString(16) }); return e }

/*!
 * Visitor insight tracking library
 */
(function (context) {



        var API_LOC = "https://api.visitor-insights.local:1443/",
                VI_QUEUE = "_viq",
                VI_SESSION_LENGTH = 60 * 60 * 24 * 365; // in seconds

        var vInsight = vInsight || {};
        vInsight = function (queue) {
                this.queue = new vInsight.Queue(queue);
        }

        vInsight.Queue = function (queue) {
                this.executeAll(queue);
        }

        vInsight.Queue.prototype = {
                executeAll: function (queue) {


                        for (var i in queue) {
                                var method = this[queue[i][0]];


                                method.apply(this, queue[i].slice(1));
                        }
                },
                setAccount: function (accountId) {
                        this._accountId = accountId;

                },



                trackPageView: function () {

                        const urlSearchParams = new URLSearchParams(context.location.href);
                        const params = Object.fromEntries(urlSearchParams.entries());
                        var sessionId = Cookies.get('session_id');
                        if (!sessionId) {
                                sessionId = generateUUID();
                        }


                        var data = {
                                tenant: this._accountId,
                                userAgent: navigator.userAgent ? navigator.userAgent : null,
                                date: new Date().getTime(),
                                session_id: sessionId,

                                current_page: context.location.href,
                                referer: context.document.referrer,


                        };
                        //var apiLocation = API_LOC.replace('{accountId}', this._accountId);
                        var apiLocation = API_LOC;
                        var response = fetch(apiLocation, {
                                method: 'POST',
                                body: JSON.stringify(data),
                                headers: {
                                        'Accept': 'application/json',
                                        'Content-Type': 'application/json',
                                        'X-Tenant': this._accountId
                                },
                        })
                                .then((response) => response.json())
                                .then((data) => {

                                        Cookies.set('last_viewed_page_id', data.current_viewed_page_id, { expires: VI_SESSION_LENGTH })
                                        Cookies.set('last_viewed_page_at', data.current_viewed_page_at, { expires: VI_SESSION_LENGTH })


                                });

                },

                trackEvent: function () {
                        alert('Enable click tracking');
                },
                scrollToEvent: function () {
                        alert('scroll to event');
                },
        }

        context[VI_QUEUE] = new vInsight(context[VI_QUEUE]);
})(window);

What i want to be able to do is on a button click:

<button onclick="_viq.push(['trackEvent',{download:'has been clicked'}])">click</button>

and then capture that on the tracking script so its picked up by the trackEvent function.

“Validating Phone Numbers with Country Code in Python and HTML Form Handling” [closed]

I’m working on a web project where users need to enter their Zain Cash phone number, including the country code, in an HTML form. I’m facing an issue with validating this input.

Here’s what I need help with:

HTML Form Design: How can I design an HTML form to accept and validate a phone number with a country code? I want to make sure the phone number follows a specific format (e.g., starting with the country code followed by the phone number).

Validation Logic: How can I implement validation logic to ensure that the phone number and country code are in the correct format? If the phone number is valid, it should proceed to the next step; otherwise, it should show an error message.

Backend Handling (Optional): If relevant, I’d also appreciate guidance on how to handle this data in Python for further processing or validation on the server side.

What did you try?

I tried using Twilio for validating phone numbers, but I ran into issues. Specifically, I attempted to use Twilio’s Python library to validate the phone number format and ensure it includes the correct country code. However, I’m having trouble implementing this correctly in my HTML form and validating the input data.

What were you expecting?

I expected to have a functioning HTML form that can accurately validate phone numbers and country codes according to the desired format. If the input is correct, it should allow users to proceed to the next step. If the input is invalid, it should show a relevant error message. Additionally, I wanted the Python backend (using Twilio or another method) to handle this validation effectively and provide clear feedback.

A way to “tell” DevTools to prefer a specific frame when opened?

I have an application that’s a bit like CodePen, JSBin, etc. where there’s a ~fullscreen sandboxed iframe which contains the actual (user-written) content of the page.

The top-level frame is not “relevant” to users/developers on the platform, but the top-level frame is of course is what’s “focussed” in DevTools by default whenever DevTools is opened via Ctrl+Shift+I/J.

This can be confusing to newbie users, because they expect to be able to e.g. type a global variable and hit enter. They don’t realize that they have to first open the console tab, then find the dropdown, then find the correct frame in that dropdown (or, as a hacky shortcut, they can use the element selector and click an element inside the iframe). This isn’t an issue if “Inspect Element” is used to open DevTools, but users don’t know that by default.

I’m wondering whether there’s any way to “tell” DevTools to focus on the iframe instead of the top-level frame.

I’m definitely open to accepting somewhat “hacky” solutions here. For example, I’ve noticed that Cloudflare Turnstile (Captcha) programmatically/dynamically triggers a debugger statement if DevTools is open, which causes the containing frame/worker (of that debugger statement) to gain “focus” within DevTools. It somehow clears itself moments later (maybe via terminating/deleting the worker/frame from the outside?). This is actually a bit annoying, but probably less annoying to a newbie coder than not knowing why DevTools “isn’t working” due to having the wrong frame focus.

That said, ideally there would be a slightly less disruptive way than this to get a frame to “grab focus” within DevTools.

Note: My current solution here is to tell users to right-click and “Inspect Element” as a way to open DevTools. I’m looking for a better solution than this.

Change html table color based on the value of a cell

I am fetching data from an API and displaying it in a html table.
Now I want to change the color of the rows based on the value of a column.
For example if status is Accepted then green row and if status is not accepted then red color row.

<div class="container"></div>
    <table class="table">
       <thead>
          <tr>
            <th>Name</th>
            <th>Address<br>Status</th>
            <th>Status<br>Status</th>
          </tr>
      </thead>
   <tbody id="data">
   </tbody>
</table>
</div>
<Script>fetch("some url").then(
   res => {
     res.json().then(
       data => {
         console.log(data.data);
         if (data.data.length > 0) {
   
           var temp = "";
           data.data.forEach((itemData) => {
             temp += "<tr>";
             temp += "<td>" + itemData.Name + "</td>";
             temp += "<td>" + itemData.Address + "</td>";
             temp += "<td>" + itemData.Status + "</td></tr>";
           });
           document.getElementById('data').innerHTML = temp
   
   
         }
       }
     )
   }
   )
</script>

Limit type of return type of a function?

I am studying typescript with gpteachus and I got this code that i can’t wrap my head around it:

type MyFuncType = (a:number) => void

function MyFunc(a:MyFuncType) {
    return a(2)
}

MyFunc((a) => { return 'a'})

I expect typescript to prevent my from returning a string in the function! but it allows me to return a string. the expectation is to return void/empty/noting. not a string

Why typescript won’t warn me for a wrong type return?

Thanks!

I read typescript docs, I look up code examples online and via other people codebase but couldn’t find an answer

Working on navigation or refreshing it wont work ever again

Home htmlf
Basically i am trying to bring effect if i click on home after opening home it bring css effect on that text which was clicked in navigation
Here is my code please tell me what should i do
i also linked html inside html using javascript Navigation html
Nav css
Java

i took help of chat gpt it works for one time but after refreshing or clicking other links in nav it stop working

detect when horizontally animating element reaches center of viewport

Given an animating (transforming) row of images, detect when each one reaches the center so we can make some changes (e.g., adding styling like filter: grayscale)

row of images with one that is not black and white (as it reached middle of screen)

I’ve enlisted IntersectionObserver and gotten close. In fact my solution works great in Firefox but only works in Chrome if the mouse is moving and doesn’t work at all in Safari. Even if I tweak the options parameter behavior seems sporadic unless in Firefox.

Codepen

const options = {
  root: document.body,
  rootMargin: '0% -50% 0% -50%',
  threshold: 0,
}

const observer = new IntersectionObserver((entries) => { 
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.style.filter = 'grayscale(0%)'
    } else {
      entry.target.style.filter = 'grayscale(100%)'
    }
  })
}, options)

const items = document.querySelectorAll('.img-container img');
items.forEach(img => observer.observe(img))