Can you convert the javascript code block I will give you into C# code? [closed]

        var Y = "hxt!236";

        function v(s) {
            let t = ee(Y);
            return decodeURI(te(t(s)));
        }

        var ee = s => {
            let t = e => e.split("").map(n => n.charCodeAt(0)),
                r = e => t(s).reduce((n, o) => n ^ o, e);
            return e => e.match(/.{1,2}/g).map(n => parseInt(n, 16)).map(r).map(n => String.fromCharCode(n)).join("");
        };

        function te(s) {
            for (var t = s.toString(), r = "", e = 0; e < t.length; e += 2)
                r += String.fromCharCode(parseInt(t.substr(e, 2), 16));
            return r;
        }

        var result = v("46104640414341424143414B414B");

This will be the result of KB10199.

Can you convert the javascript code block below into C# code to give the value I want?

Problem when assigning code to selection in Lexical: marc property disappears for nested nodes

Context:
I am using Lexical Editor to create a custom implementation for assigning a code to a selection. The goal is to wrap selected nodes (which may include TranslateCommentNode and TranslateTextNode) into a new TranslateCommentNode, while preserving all properties of the original nodes, especially a custom property called marc.

The problem arises when nesting a TranslateCommentNode within another: the nested node’s marc property disappears or resets.

The problem arises when nesting a TranslateCommentNode within another: the nested node’s marc property disappears or resets.

Steps to Reproduce:
Select multiple nodes in the editor, including one or more TranslateCommentNode instances with the marc property set.
Run the assignCodeToSelection function.
Inspect the marc property of the nested TranslateCommentNode.

const assignCodeToSelection = (code) => {
  editor.update(() => {
    const selection = $getSelection();

    if (!selection || !$isRangeSelection(selection)) {
      console.warn("There is no valid range selection in the editor.");
      return;
    }

    // Get selected nodes
    let filteredSelection = selection.getNodes();

    // Skip the last `TextNode` if the second-to-last is a `TranslateParagraphNode`
    filteredSelection = filterLastInvalidNode(filteredSelection);

    // Filter to include only `TranslateTextNode` or `TranslateCommentNode`
    filteredSelection = filteredSelection.filter((node) => {
      if ($isTranslateCommentNode(node)) {
        if (node.getComment() === "This is not a comment, it’s a Verbatim") {
          return true; // Include the entire node
        }
      }
      return !$isTranslateCommentNode(node.getParent()); // Exclude child nodes of another `TranslateCommentNode`
    });

    if (filteredSelection.length === 0) {
      console.warn("No valid text or comment nodes found in the selection.");
      return;
    }

    const groups = groupByParagraphs(filteredSelection);

    if (groups.length === 0) {
      console.warn("No valid groups found to process.");
      return;
    }

    const groupId = `group-${Date.now()}-${Math.random()}`;
    const user = getUser();
    const colorToUse = code.color;

    let lastCommentNode = null;

    groups.forEach((group) => {
      const selectedNodes = group.filter(
        (node) => $isTranslateTextNode(node) || $isTranslateCommentNode(node)
      );

      if (selectedNodes.length === 0) {
        console.warn("No valid nodes found in the group.");
        return;
      }

      const copiedNodes = selectedNodes
        .map((node) => {
          return cloneNode(node); // Clone text or comment nodes
        })
        .filter(Boolean);

      const commentNode = createCommentNode(
        copiedNodes,
        user,
        code,
        colorToUse,
        groupId
      );

      const firstNode = selectedNodes[0];
      const lastNode = selectedNodes[selectedNodes.length - 1];
      const parentParagraph = firstNode.getParent();

      if (
        parentParagraph &&
        parentParagraph.getType() === "translate-paragraph"
      ) {
        if (parentParagraph.getChildren().includes(lastNode)) {
          lastNode.insertAfter(commentNode);
        } else {
          parentParagraph.append(commentNode); // Fallback
        }

        // Nest nodes inside the new TranslateCommentNode
        selectedNodes.forEach((node) => {
          if ($isTranslateCommentNode(node)) {
            const originalMark = node.getMarca(); // Save the original mark

            console.log(
              "Nesting existing TranslateCommentNode:",
              node.getKey(),
              "With code:",
              originalMark
            );

            commentNode.append(node); // Nest the node

            // Reapply the mark to ensure it persists
            if (originalMark !== null && originalMark !== undefined) {
              node.setMarca(originalMark);
              console.log(
                "Mark reapplied after nesting:",
                node.getKey(),
                "Mark:",
                node.getMarca()
              );
            }
          } else {
            commentNode.append(node);

            console.log(
              "Non-TranslateCommentNode nested:",
              node.getKey(),
              "Type:",
              node.getType()
            );
          }
        });

        // Remove original nodes after nesting
        selectedNodes.forEach((node) => {
          node.remove();
        });

        // Log to verify child nodes of commentNode
        const children = commentNode.getChildren(); // Get current children
        console.log(
          `Children of commentNode (${commentNode.getKey()}):`,
          children.map((child) => ({
            key: child.getKey(),
            type: child.getType(),
            mark: $isTranslateCommentNode(child)
              ? child.getLatest().getMarca() // Latest version of the node
              : null,
          }))
        );

        console.log(
          `Comment node ${commentNode.getKey()} created and original nodes processed successfully.`
        );
      } else {
        console.warn(
          "The selected node does not belong to a valid TranslateParagraphNode."
        );
      }
    });

    if (lastCommentNode) {
      lastCommentNode.select();
    }

    console.log("TranslateCommentNodes inserted successfully.");
  });
};

After running the function, the marc property of nested TranslateCommentNode instances is null or undefined.

Before Assigning Code:

[
  {
    "key": "node1",
    "type": "TranslateCommentNode",
    "marc": "code1"
  },
  {
    "key": "node2",
    "type": "TranslateTextNode"
  }
]

After Assigning Code:

[
  {
    "key": "node1",
    "type": "TranslateCommentNode",
    "marc": null
  }
]

Questions:
Why does the marc property disappear when appending a TranslateCommentNode into a new parent node?
Should I manually copy or reset the marc property? If so, what is the best practice for handling this in Lexical?
Is there a known issue with how Lexical handles custom properties during node nesting, or am I missing a critical step?

TRANSLATECOMMENTNODE

import "./TranslateCommentNode.css";

import { ElementNode, $applyNodeReplacement } from "lexical";

import { useLexicalComposerContext } from "lexical";
import { FontIcon } from "@fluentui/react/lib/Icon";
import { HighContrastSelectorWhite } from "@fluentui/react";

import { SHOW_COMMENT_DIALOG_COMMAND } from "../EditorPlugins/CommentDialogPlugin.jsx";

export class TranslateCommentNode extends ElementNode {
  #__id;
  #__comment;
  #__responses;
  #__isAnonymized;
  #__user;
  #__isPublic;
  #__color;
  #__mainComment;
  #__hideColor;
  #__mark;
  #__highlighted;
  #__group;

  constructor(
    key,
    {
      id,
      comment,
      responses,
      isAnonymized,
      user,
      isPublic,
      color,
      hideColor,
      mark,
      mainComment,
      group,
    }
  ) {
    super(key);
    this.#__id = id;
    this.#__comment = comment;
    this.#__responses = responses;
    this.#__isAnonymized = isAnonymized;
    this.#__user = user;
    this.#__isPublic = isPublic;
    this.#__color = color;
    this.#__hideColor = hideColor;
    this.#__mark = mark;
    this.#__mainComment = mainComment; // Corrected property name
    this.#__highlighted = false;
    this.#__group = group;
  }

  static getType() {
    return "translate-comment";
  }

  static clone(node) {
    const properties = {
      id: node.#__id,
      comment: node.#__comment,
      responses: node.#__responses,
      isAnonymized: node.#__isAnonymized,
      user: node.#__user,
      isPublic: node.#__isPublic,
      color: node.#__color,
      mainComment: node.#__mainComment,
      hideColor: node.#__hideColor,
      mark: node.#__mark,
      group: node.#__group,
    };
    return new TranslateCommentNode(node.__key, properties);
  }

  static importJSON(serializedNode) {
    // Ensure `serializedNode` contains all required properties

    const {
      id,
      comment,
      responses,
      isAnonymized,
      user,
      isPublic,
      color,
      hideColor,
      mark,
      mainComment,
      group,
    } = serializedNode;

    return $createTranslateCommentNode(
      comment,
      responses,
      id,
      mainComment,
      user,
      isPublic,
      color,
      hideColor,
      mark,
      isAnonymized,
      group
    );
  }

  exportJSON() {
    return {
      ...super.exportJSON(),
      type: "translate-comment",
      id: this.#__id,
      comment: this.#__comment,
      responses: this.#__responses,
      isAnonymized: this.#__isAnonymized,
      user: this.#__user,
      isPublic: this.#__isPublic,
      color: this.#__color,
      mainComment: this.#__mainComment,
      hideColor: this.#__hideColor,
      mark: this.#__mark,
      group: this.#__group,
    };
  }

  addHighlight() {
    const writableNode = this.getWritable();
    writableNode.#__highlighted = true;
    console.log(`Node ${writableNode.__key} highlighted`); // Log for confirmation
  }

  removeHighlight() {
    const writableNode = this.getWritable();
    writableNode.#__highlighted = false;
  }

  createDOM(config, editor) {
    const rootSpan = document.createElement("span");
    rootSpan.contentEditable = true;

    // Apply background color if `hideColor` is false and a color is assigned
    if (!this.#__hideColor && this.#__color) {
      rootSpan.style.backgroundColor = this.#__color;
      rootSpan.style.color = "black";
    }

    // Apply highlight style if `#highlighted` is true
    if (this.#__highlighted) {
      rootSpan.classList.add("highlighted-comment");
    }

    return rootSpan;
  }

  updateDOM(prevNode, dom, config) {
    // Add or remove the highlight class based on the node's state
    if (this.#__highlighted) {
      dom.classList.add("highlighted-comment");
    } else {
      dom.classList.remove("highlighted-comment");
    }

    // Update the node's background color if not hidden
    if (!this.#__hideColor && this.#__color) {
      dom.style.backgroundColor = this.#__color;
    } else {
      dom.style.backgroundColor = "";
    }

    return false; // Do not replace the DOM node
  }

  // Getter and Setter methods
  getId() {
    return this.getLatest().#__id;
  }

  getUser() {
    return this.getLatest().#__user;
  }

  isPublic() {
    return this.getLatest().#__isPublic;
  }

  setIsPublic(isPublic) {
    return (this.getWritable().#__isPublic = isPublic);
  }

  getColor() {
    return this.getLatest().#__color;
  }

  setColor(color) {
    return (this.getWritable().#__color = color);
  }

  setMark(mark) {
    return (this.getWritable().#__mark = mark);
  }

  getComment() {
    return this.getLatest().#__comment;
  }

  getMark() {
    return this.getLatest().#__mark;
  }

  getResponses() {
    return this.getLatest().#__responses;
  }

  getGroup() {
    return this.getLatest().#__group;
  }

  setId(id) {
    return (this.getWritable().#__id = id);
  }

  setUser(user) {
    return (this.getWritable().#__user = user);
  }

  setComment(comment) {
    return (this.getWritable().#__comment = comment);
  }

  setResponses(response) {
    return (this.getWritable().#__responses = response);
  }

  setHideColor(hideColor) {
    return (this.getWritable().#__hideColor = hideColor);
  }

  anonymize(isAnonymized) {
    this.getWritable().#__isAnonymized = isAnonymized;
  }

  getIsAnonymized() {
    return this.#__isAnonymized;
  }

  setMainComment(mainComment) {
    this.getWritable().#__mainComment = mainComment;
  }

  getMainComment() {
    return this.#__mainComment;
  }

  setGroup(group) {
    this.getWritable().__.__group = group;
  }
}

// Utility function to check if a node is a `TranslateCommentNode`
export function $isTranslateCommentNode(node) {
  return node instanceof TranslateCommentNode;
}

export function $createTranslateCommentNode(
  comment,
  responses,
  id,
  mainComment = null,
  user,
  isPublic,
  color,
  hideColor,
  mark,
  isAnonymized = false,
  group = null
) {
  const properties = {
    id: id,
    comment: comment,
    responses: responses,
    isAnonymized: isAnonymized,
    user: user,
    isPublic: isPublic,
    color: color,
    hideColor: hideColor,
    mark: mark,
    mainComment: mainComment,
    group: group,
  };
  console.log("TranslateCommentNode creation parameters:", properties);

  return new TranslateCommentNode(undefined, properties);
}

TRANSLATETEXTNODE (TSX)

import "./TranslateTextNode.css";

import type {
  EditorConfig,
  LexicalEditor,
  LexicalNode,
  NodeKey,
  SerializedTextNode,
  Spread,
} from "lexical";

import { $applyNodeReplacement, TextNode } from "lexical";

import { SET_VIDEO_POSITION_COMMAND } from "../EditorPlugins/VideoJSPlugin";
import { SHOW_PREVIEW_COMMAND } from "../EditorPlugins/TranslateTextPlugin.jsx";

export type SerializedTranslateTextNode = Spread<
  {
    type: "translate-text";
    start: number | null;
    end: number | null;
    isRead: boolean;
    isAnonymized: boolean;
    parent: string | null;
    search: boolean;
  },
  SerializedTextNode
>;

export class TranslateTextNode extends TextNode {
  #__start: number | null;
  #__end: number | null;
  #__isRead: boolean;
  #__isAnonymized: boolean;
  #__search: boolean;
  #__selected: boolean;
  #__highlighted: boolean; // New property for highlighting

  static getType(): string {
    return "translate-text";
  }

  getIsAnonymized(): boolean {
    return this.#__isAnonymized;
  }

  static clone(node: TranslateTextNode): TranslateTextNode {
    return new TranslateTextNode(
      node.__text,
      node.#__start,
      node.#__end,
      node.#__isRead,
      node.#__isAnonymized,
      node.__key
    );
  }

  constructor(
    text: string,
    start: number | null,
    end: number | null,
    isRead: boolean,
    isAnonymized: boolean,
    key?: NodeKey
  ) {
    super(text, key);
    this.#__start = start;
    this.#__end = end;
    this.#__isRead = isRead;
    this.#__isAnonymized = isAnonymized;
    this.#__search = false;
    this.#__selected = false;
    this.#__highlighted = false; // Initially not highlighted
  }

  // Method to enable/disable highlighting
  setHighlighted(isHighlighted) {
    const writableNode = this.getWritable();
    writableNode.#__highlighted = isHighlighted;
  }

  getStart() {
    return this.getLatest().#__start;
  }

  getEnd() {
    return this.getLatest().#__end;
  }

  getStartEnd() {
    const latest = this.getLatest();
    return {
      start: latest.#__start,
      end: latest.#__end,
    };
  }

  isRead() {
    return this.getLatest().#__isRead;
  }

  setRead(read) {
    return (this.getWritable().#__isRead = read);
  }

  anonymize(isAnonymized) {
    this.getWritable().#__isAnonymized = isAnonymized;
  }

  getReadElements() {
    const self = this.getLatest();
    return {
      start: self.#__start,
      end: self.#__end,
      isRead: self.#__isRead,
    };
  }

  setSearch(search) {
    this.getWritable().#__search = search;
  }

  getSearch() {
    return this.getLatest().#__search;
  }

  setSelected(selected) {
    this.getWritable().#__selected = selected;
  }

  getSelected() {
    return this.getLatest().#__selected;
  }

  createDOM(config: EditorConfig, editor: LexicalEditor): HTMLElement {
    const dom = document.createElement("span");
    if (this.#__isAnonymized) {
      return dom;
    }
    dom.ondblclick = (event) => {
      event.preventDefault();
      event.stopPropagation();
      editor.dispatchCommand(SET_VIDEO_POSITION_COMMAND, this.#__start);
    };
    dom.className = this.#__isRead ? "textread" : "";
    dom.ondragenter = (event) => {
      event.preventDefault();
      event.stopPropagation();
      editor.dispatchCommand(SHOW_PREVIEW_COMMAND, this);
    };
    dom.style.background = this.#__search ? "#d9b855" : "";
    if (this.#__selected) {
      dom.style.background = "#fd7e14";
    }
    const inner = super.createDOM(config);
    dom.appendChild(inner);
    return dom;
  }

  updateDOM(
    prevNode: TextNode,
    dom: HTMLElement,
    config: EditorConfig
  ): boolean {
    const inner = dom.firstChild;
    console.log(`updateDOM for TranslateTextNode with key: ${this.getKey()}`);
    console.log(
      `State of selected: ${this.#__selected}, search: ${this.#__search}`
    );

    if (!inner || this.#__isAnonymized) {
      return true;
    }

    // Update background if `search` or `selected` change
    if (
      prevNode.#__search !== this.#__search ||
      prevNode.#__selected !== this.#__selected
    ) {
      dom.style.background = this.#__search
        ? "#d9b855"
        : this.#__selected
        ? "#ffecb3"
        : "";
      console.log(
        `Updating background in the DOM for node ${this.getKey()} to ${
          dom.style.background
        }`
      );
    }

    if (prevNode.#__isRead !== this.#__isRead) {
      dom.className = this.#__isRead ? "textread" : "";
    }

    return super.updateDOM(prevNode, inner as HTMLElement, config);
  }

  static importJSON(
    serializedNode: SerializedTranslateTextNode
  ): TranslateTextNode {
    const node = $createTranslateTextNode(
      serializedNode.text,
      serializedNode.start,
      serializedNode.end,
      serializedNode.isAnonymized
    );
    node.setFormat(serializedNode.format);
    node.setDetail(serializedNode.detail);
    node.setMode(serializedNode.mode);
    node.setStyle(serializedNode.style);
    return node;
  }

  exportJSON(): SerializedTranslateTextNode {
    return {
      ...super.exportJSON(),
      type: "translate-text",
      start: this.#__start,
      end: this.#__end,
      isRead: this.#__isRead,
      isAnonymized: this.#__isAnonymized,
      parent: this.__parent,
    };
  }
}

export function $isTranslateTextNode(
  node: LexicalNode | null | undefined
): node is TranslateTextNode {
  return node instanceof TranslateTextNode;
}

export function $createTranslateTextNode(
  text: string,
  start: number | null,
  end: number | null,
  isAnonymized: boolean
): TranslateTextNode {
  const node = new TranslateTextNode(text, start, end, false, isAnonymized);
  return $applyNodeReplacement(node);
}

How to start from specific number in dropdown

I am using react-native-element-dropdown to build a dropdown in my app can someone tell me how to start the dropdown froma specific number say like 18 instead of 1. All numbers should be there but on Click it should automatically open from 18

<Dropdown
            style={[styles.input, errors.age && styles.errorInput]}
            data={Array.from({length: 110}, (_, i) => ({
              label: `${i + 1}`,
              value: `${i + 1}`,
            }))}
            value={age}
            labelField="label"
            valueField="value"
            onChange={item => {
              console.log('Selected age:', item.value);
              setAge(item.value);
            }}
            placeholder="Select Age"
            placeholderStyle={{color: '#6B7280'}}
            iconColor="#6B7288"
            selectedTextStyle={{color: 'black', fontSize: width * 0.04}}
            renderSelectedItem={() => (
              <Text style={{color: 'black', fontSize: width * 0.04}}>
                {age}
              </Text>
            )}
            renderItem={item => (
              <View style={styles.dropdownItem}>
                <Text
                  style={[
                    styles.dropdownItemText,
                    age === item.value ? {color: 'black'} : {color: 'grey'},
                  ]}>
                  {item.label}
                </Text>
              </View>
            )}
          />

Whatsapp send message link without new tab or new window

I want my users can trigger whatsapp messages from my web based application.
For example

<a href="https://wa.me/+905555555?text=your%20car%20is%20ready" target="_blank">Send Car Ready Message</a>

this opens https://api.whatsapp.com/send/?phone... link in new tab and whatsapp application appears. Then user clicks send icon.

When user wants to return browser, https://api.whatsapp.com/send/?phone... page is active tab. User has to close this active tab for returning my app. I want to close api.whastsapp tab automatically.

I tried the function below:

<a href="#" onclick="openWhatsApp()">Send Message</a>

<script>
function openWhatsApp() {
    const whatsappURL = "https://wa.me/+100000000?text=yourcarisready";
    const newWindow = window.open(whatsappURL, "_blank", "width=800,height=600,scrollbars=no");
    
    // close window after 3 seconds
    setTimeout(() => {
        if (newWindow) {
            newWindow.close();
        }
    }, 3000); 
}
</script>

but it did not work.
How can I bypass api.whatsapp page for triggering whatsapp messages?

POST request called to .aspx file returns empty JSON

I’m trying to send a POST request from a .js function to an .aspx file with a JSON body. At the moment I only want it to deserialize the JSON into an Input object and serialize it back into JSON before returning the ‘obj’ element.
My issue is that when I’m trying to print my response in the .js function, it is empty.

The body I’m sending:
{"obj":"ASM10007-1A","objType":"part"}

The response I’m expecting:
{"obj":"ASM10007-1A"}

Actual output:
enter image description here

I have no idea what to do here, so please help.

.js file

async function JS_PostRequest(obj, objType) {
    var url = T_wroot + 'tweak/HS2-tweak/parts/excelcreator.exe.aspx';

    console.log("URL: " + url);

    const data = {
        obj: obj,
        objType: objType,
    };

    console.log("POST request body: " + JSON.stringify(data));
    
    const options = {   method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(data) };
    
    await fetch(url, options)
    .then(function(res) {
        if (res.ok) {
            console.log("response:" + JSON.stringify(res));
            return res;
        }
        if (!res.ok) {
            throw new Error(`HTTP error, status = ${res.status}`);
        }
    })
    .catch((err) => {
        console.error(`Fetch error: ${err}`);
    });
}

.aspx file

<%
    string obj = Request.QueryString["o"];
    string objType = Request.QueryString["t"];
    
    try
    {
        var strJSON = String.Empty;
     
        //Request.InputStream.Position = 0;
        using (var inputStream = new StreamReader(Request.InputStream))
        {
            strJSON = inputStream.ReadToEnd();
        }
     
        var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Input>(strJSON);
        
        string message;
        if (data != null)  // Check if 'data' is not null
        {
            if (data.obj != null)  // Check if 'obj' inside 'data' is not null
            {
                message = data.obj;  // Assign the value of 'data.obj' to 'message'
            }
            else
            {
                message = "No message received";  // Assign default value if 'obj' is null
            }
        }
        else
        {
            message = "No message received";  // Assign default value if 'data' is null
        }
        
        var responseObj = new {
            response = message
        };
        string jsonResponse = Newtonsoft.Json.JsonConvert.SerializeObject(responseObj);
        
        Response.ContentType = "application/json";
        Response.Write(jsonResponse);
        Response.End();
    }
    catch (Exception e)
    {
     
        Response.Write("ASPX error: " + e.Message);
     
    }
%>

<script runat="server>
    public class Input 
    {
        public string obj { get; set; }
        public string objType { get; set; }
    }
</script>

How to make permission of Bluetooth and Location on a mobile application by React Native?

I currently work on my academic project where I build mobile application using framework React Native. It need to get the device permission of Bluetooth and location for well performance.

I building application for Android devices, I run my code prototype on Expo Go.

Can I get the permission request in Expo Go for test is it work? If permission allowed while asking the device will actually ON the Bluetooth and location?

If not, what’s the best way to proceed this?

I need solution on this for clarification from those who know.

trigger not working when CF7 .submit() was called programatically

I made a site [https://www.gokartbudapest.hu/hu/ajandekutalvany/ajandekutalvany_voucher/]* where my clients can book appointments — but I didnt want to use CF7 directly as it looks dodgy and I wanted to make it more fancy.
*it is yet under construction, not yet the final looks.

So I collect all the data from the clients than put everything programatically (javascript) into a hidden (yet its visible) CF7 from and than javascript calls the CF7 submission routine and the necessary info is sent to me via an email.

My problem is that when CF7’s form .submit() is executed the other triggers are not working; neither the nor the so it makes me now clueless how to control activities after submission though I want to redirect to an other subpage, clear the fields … etc.

Seems like DOM events are bypassed once javascript calls the wpcf7submit programatically because when you hit the CF7’s own SUBMIT button manually (yet visible on my site as for testing the whole form is not hidden) all triggers ( and ) works perfectly.

Do you have any ideas how I could
: get the triggers though working, or
: how to make a workaround to gain control when the submission went through.

This is the CF7 block:

<body>   
<div id="CF7 panel">[contact-form-7 id="a3064bc" title="Book-4" html_id="bookarace"]</div>
</body>   

These are the triggers which are working fine when you press the CF7’s form own SUBMIT button, but they remain silent when .submit() is called programatically (doesnt matter if you use the document or the Element place itself):

var Elem = document.getElementById('bookarace')  
// Elem.style.display = 'none'

document.addEventListener('wpcf7submit', function() {
    alert ('here-submit')
//  window.location.href = "https://www.gokartbudapest.hu"
    }, false )
    
Elem.addEventListener('wpcf7mailsent', function() {
    alert ('here-mailsent')
//  window.location.href = "https://www.gokartbudapest.hu"
    }, false )

So I guess the secret must be laying in the DOM event and the programatical call.
Thanks,
Adam

How to make html2canvas and jspdf reponsive for all the screens?

I have created a camera app where I send the pictures to a div and ultimately printing that div.

const handlePrint = async () => {
const grid = document.getElementById("image-grid");

const canvas = await html2canvas(grid);

const imgData = canvas.toDataURL("image/png");

const pdf = new jsPDF({
        orientation: "portrait",
        unit: "pt",
        format: "a4",
      });



 pdf.addImage(imgData, "PNG", 0, 0, 610, 760); //phone chrome


// Add text below the images
const text = "Special One"; // Change this to your desired text
const secondtext = "Second One";
pdf.setFont("Helvetica", "normal");
pdf.setFontSize(18); // Set font size
pdf.text(text, 100, 780);
pdf.text(secondtext, 380, 780);


pdf.save();

};

it works fine with laptop and big screens but for my tab and mobile screens, when I am printing, the image size is smaller with alot of gap from the top and right borders. I tried using scale property of html2canvas but that doesn’t help.
If I increase the coordinates of addImage by

pdf.addImage(imgData, “PNG”, 0, 0, 640, 780);

The borders doesn’t go but some parts of the image moves out pdf.

Why using classic prototype syntax to declare Symbol.hasInstance method cant make the instanceof operator work correctly?

There are two code snippets to show the problem I got.

demo1.js:

// using ES6+ class syntax

class MyObject {
  constructor() {
    this.myProp1 = 'myProp1';
  }

  get [Symbol.toStringTag]() {
    console.log('[Custom Symbol.toStringTag]]');
    return 'CustomTag';
  }

  static [Symbol.hasInstance](instance) {
    console.log('[Custom Symbol.hasInstance]');
    return false;
  }
}

const myObj = new MyObject();

console.log(Object.prototype.toString.call(myObj));  // works correctly, implicitly called custom getter Symbol.toStringTag
// first log print [Custom Symbol.toStringTag]], then log print [object CustomTag], since custom getter Symbol.toStringTag return 'CustomTag'

console.log(myObj instanceof MyObject);  // works correctly, implicitly called custom static method Symbol.hasInstance
// first log print [Custom Symbol.hasInstance], then log print false, since custom static method Symbol.hasInstance return false

demo2.js:

// using classic prototype syntax

function MyObject() {
  this.myProp1 = 'myProp1';
}

Object.defineProperty(MyObject.prototype, Symbol.toStringTag, {
  configurable: true,
  enumerable: true,
  get() {
    console.log('[Custom Symbol.toStringTag]]');
    return 'CustomTag';
  }
})

// is this a correct way to define a static method to MyObject by using classic prototype syntax?
MyObject[Symbol.hasInstance] = function (instance) {
  console.log('[Custom Symbol.hasInstance]');
  return false;
}

const myObj = new MyObject();

console.log(Object.prototype.toString.call(myObj));  // works correctly, implicitly called custom getter Symbol.toStringTag
// first log print [Custom Symbol.toStringTag]], then log print [object CustomTag], since custom getter Symbol.toStringTag return 'CustomTag'

console.log(myObj instanceof MyObject);  // does not works correctly, does not implicitly called custom static method Symbol.hasInstance
// just log print true

My Question:

  1. in demo1.js, everything works fine as expected.
  2. in demo2.js, does MyObject[Symbol.hasInstance] = function (instance) { ... } is a correct way to define a static method by using classic prototype syntax?
  3. in demo2.js, if MyObject[Symbol.hasInstance] = function (instance) { ... } is correct way to define a static method, why the js operator instanceof does not implicitly call custom static method Symbol.hasInstance?

btw, about the well-know Symbol Symbol.hasInstance, pls refer to MDN web page

$bindable and propagation don’t seem work

I’m building a nested tree of objects. This is the structure:

    ID: string;
    indexes: number[];
    title: string;
    validated: boolean;
    column: DescriptionElement[];
    children: Paragraph[];

I want to create a new div for every child inside children. I have 2 components:

  • SvelteDocument
  • SvelteParagraph

Inside SvelteDocuments I have a state which is an array of Paragraph. I’m passing the array like this

<div>
  {#each paragraphs as paragraph, index (index)}
    <SvelteParagraph bind:paragraph={paragraphs[index]} disabled={false} />
  {/each}
</div>

Inside SvelteParagraph we get the props of paragraph:

let { paragraph = $bindable() } = $props();

Inside SvelteParagraph whe show the paragraph children like above and we also have a function to add a chil to the current paragraph which is just a push on the prop () => paragraph.children.push(…)

The problem is that we can see the state updated through an $effect inside the console log but we cannot see any changes in the UI unless we reload from the terminal.

We tried using props, bindable and state combined in different ways, but always the same problem: the state changes but no changes in the UI.

How to put icons inside the ng-select [duplicate]

I have a icon component. Then I have a dropDown component which I have build using ng-select.
Then there is Home page where I want to dropdown to show up.
The dropdown is dynamic, I have created an object in home.component.ts. And the list of dropDown renders from there.

What I want is form drop-down is to have an icon with all of the options in the list.
I have used google icons (svg). Also I’m adding a image of drop-down.

<div class="drop-down-container">
    <div *ngTemplateOutlet="dropDownIcons"></div>
    <ng-select [items]="items"
    [bindLabel]="bindLabel"
    [bindValue]="bindValue"
    [placeholder]="placeholder"
    >
    <ng-template #truck>
        @if(items.icon == 'truck'){
            <app-svg-icons 
            icons="truck"
            icons="setting"
            color="red"
            />
        } @else {
            <app-svg-icons 
            icons="trialer"
            icons="setting"
            color="red"
            />
        }
    </ng-template>

</ng-select>
</div>

<ng-template #dropDownIcons>
    <app-svg-icons 
    icons="truck"
    icons="setting"
    color="red"
    />
    <h1>{{items.icons}}</h1>
    </ng-template>

I have tried to look up the on the internet and what I got to know is that it can be done using ng-template, but I couldn’t figure out how.

Why won’t console.log work until the loop finishes? [closed]

I’m working on a program(in codepen.io) where the computer generates a random number between 1 and 100. The player has to try and guess the number in as few attempts as possible. When the user enters a number they are told if the guess is too high or too low until the number is guessed correctly. At the end, the player is told how many guesses they made.

This is the code I used:

var num = Math.floor(Math.random() * 100);
var ans = false;
var count = 0 ;

while (ans == false) { 
  var guess = parseInt(prompt("guess a number(between 1-100)"));
  count += 1;

  if (guess == num) {
    console.log("Correct! " +count+ " guesses made."); 
    ans = true;
  } else if (guess > num) { 
    console.log("Guess is higher than number"); 
  } else {
    console.log("Guess is lower than number")
  } 
}

However, the program only asks the user for input, and doesn’t output whether the number is higher/lower than the answer, which makes it impossible to play the game. I’m presuming that based on some other programs I have made, the text is only logged at the end, when the loop’s condition if fulfilled, or in this case, the correct number is guessed, which means the hint part of the game is essentially non-functional

I’ve tried a few things, but I honestly have no idea what the problem is. I’ve read some articles that say that’s just how while loops work. However, I’m not sure if they’re accurate. Can someone please find a solution to this problem where a while loop is still part of the program?

Edit: sorry, I read of the comments and noticed I didn’t properly put the code into a code box, I’m rather new to stack overflow, so pardon my dumb mistakes.

request is in pending state, router handler not being called. how to fix

server.js

const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/api/users');
const profileRoutes = require('./routes/api/profile');
const fileRoutes = require('./routes/api/file');
// const fileAuthenticationRoutes = require('./routes/api/fileAuthentication');
const graphDataRoutes = require('./routes/api/graphData');
const cardDataRoutes = require('./routes/api/cardData');
const fieldDataRoutes = require('./routes/api/fieldData');
const columnNamesRoutes = require('./routes/api/columnNames');
const problemWellsRoutes = require('./routes/api/problemWells');
const wellGraphRoute = require('./routes/api/wellGraphs');

const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');
const fileUpload = require('express-fileupload');

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
// Health check endpoint
app.use('/healthcheck', (req, res) => {
  res.status(200).send('ok');
});
const DB_URI = process.env.MONGODB_URI;
console.log(DB_URI);
app.use(bodyParser.json());

mongoose
  .connect(DB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB Connected'))
  .catch((err) => console.log(err));

app.use(fileUpload());
console.log('close to userroute');
app.use('/', userRoutes);
app.use('/', profileRoutes);
app.use('/', fileRoutes);
app.use('/', graphDataRoutes);
app.use('/', cardDataRoutes);
app.use('/', columnNamesRoutes);
app.use('/', fieldDataRoutes);
app.use('/', problemWellsRoutes);
app.use('/', wellGraphRoute);
// app.use('/', fileAuthenticationRoutes);

app.listen(port, () => {
  console.log(`Server is listening at http://localhost:${port}`);
});

request file
//login user

const login = async (userData: any) => {
  console.log('in login service');
  console.log(userData);
  try {
    console.log('in try');
    const response = await axios.post(config.apiBaseUrl + '/login', userData, {
      headers: {
        'Content-Type': 'application/json',
      },
      withCredentials: true,
    });
    console.log('before response');
    console.log(response);
    if (response.status == 200 && response.data) {
      console.log('storing user to local host');
      localStorage.setItem('user', JSON.stringify(response.data));
    }

    return response.data;
  } catch (error: any) {
    console.log('in error login');
    console.error('Error', error.response);
    throw error.response;
  }
};

router.post('/login', (req, res) => {
  //check if password match
  // retlogurn jwt token
  //bcrpt compare password
  console.log('inn router');
})

router handler not being called. post request is still in pending state. not sure what is going on. I need to make sure the route handler is called but I don’t know how to ensure that.
router handler not being called. post request is still in pending state. not sure what is going on. I need to make sure the route handler is called but I don’t know how to ensure that.

Is it possible to update markerclusters when markers changes position without clearing markers?

So I have map with vehicle positions that updates its markers every minute using marker.setPosition({lat: newPoint.lat, lng: newPoint.lng}) from a list of markers added on initial load.

These are clustered with @googlemaps/markerclusterer and after I’ve moved the markers I do this to update the clusters

    this.markerCluster.clearMarkers();
    this.markerCluster.addMarkers(this.markers);

However this causes all clusters and markers to blink. Which I’ve been told is annoying and I was wondering if there was anything I could do to update it without this blinking?

Gif showing 3 markers, where after a little while they blink

The marker has a renderer that returns this marker if there’s anything I can do there

new Marker({
  label: { 
    text: `${cluster.count}`, 
    color: isSelected || hasSelectedMarker ? "white" : "black", 
    fontWeight: "bold", 
    className: "group-marker",
    fontSize: "17px"
  },
  opacity: isOpaque ? 1 : MARKER_DESELECTED_OPACITY,
  icon,
  position: cluster.position,
  zIndex: Number(google.maps.Marker.MAX_ZINDEX) + cluster.count,
});

How to write JSDoc if name of property is string, like ‘aria-label’

I want to write JSDoc for some React component:

/**
 * Some Component
 * @param {Object} props - props of the component
 * @param {boolean} [props.active=false] - active
 * @param {string} props.text - text
 * ...
 * @returns {React.ReactElement} Some Component
 */

How can I correctly add property named 'aria-label' in JSDoc?

I can’t find the necessary solution in the Net.