How to use the new firebase firestore or queries in google cloud functions

I’m trying to use the new firebase firestore or queries in my (js) cloud functions, but couldn’t find where to import the “or” statement in the docs.

Currently I am importing Filter as so: const { Filter } = require("firebase-admin").firestore;I am also importing admin by const admin = require("firebase-admin"); . However, when I run

const snapshot = await admin.firestore().collection("bookings")
          .where('restaurantId', '==', restaurantId)
          .where('locationId', '==', locationId)
          .where(Filter.or(
            Filter.where('endDateTime', '>', startDateTime).where('startDateTime', "<=", startDateTime),
            Filter.where('startDateTime', '>=', startDateTime).where('endDateTime', "<", endDateTime),
            Filter.where('startDateTime', '<', endDateTime).where('endDateTime', ">=", endDateTime),
            Filter.where('startDateTime', '<=', startDateTime).where('endDateTime', ">=", endDateTime)
          )).get();

,I get the error “TypeError: Cannot read properties of undefined (reading ‘or’)”

Where do I actually import or from? I am probably being stupid, apologies.

How to process the suggestions done by datalist on user input?

I have an input box for, say, firstname/lastname using datalist, the list being built from a data base. If the final input from the user is in the list, I can trigger a request in the database with the input, but if the final input is not, the form for must ask for other data (email, …) by showing new input boxes. The problem is to detect (I use javascript) when there are no more suggestions by datalist (meaning the user is willing to give a name that is NOT in the list), and then the form will open the new input boxes. I can’t do this by just analysing if the characters typed by the user are or are not in the list (the analysis is triggered by input event), but rather by searching the suggestion list.

an error occured using nuxt3 + element plus

tried to learn nuxt3 and element plus is dependencis I used to, but using all together

some had a dependency problems

this is error message

in the index.vue file using element ui components then got an error

ERROR  Error while requiring module @element-plus/nuxt: TypeError: _dayjs.default.extend is not a function                                                                                                   

 ERROR  Cannot start nuxt:  _dayjs.default.extend is not a function                                                                                                                                           4:44:34 PM
  at node_modules/element-plus/es/components/time-picker/src/time-picker.mjs:10:16
  at jiti (node_modules/jiti/dist/jiti.js:1:245784)
  at node_modules/element-plus/es/components/time-picker/index.mjs:1:2184
  at jiti (node_modules/jiti/dist/jiti.js:1:245784)
  at node_modules/element-plus/es/components/calendar/src/date-table.mjs:2:1

here is package.json file

{
  "name": "mazer-nuxt",
  "version": "2.0.2",
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev --dotenv .env.development",
    "start": "nuxt start --dotenv .env.production",
    "generate": "nuxt generate",
    "preview": "nuxt preview",
    "postinstall": "nuxt prepare"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/color-mode": "^3.2.0",
    "@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.7",
    "apexcharts": "^3.36.3",
    "axios": "^1.3.4",
    "bootstrap": "^5.2.3",
    "bootstrap-icons": "^1.10.2",
    "element-plus": "^2.3.4",
    "feather-icons": "^4.29.0",
    "vue3-apexcharts": "^1.4.1"
  },
  "devDependencies": {
    "@nuxt/types": "^2.16.3",
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/eslint-config": "^12.0.0",
    "@nuxtjs/eslint-config-typescript": "^12.0.0",
    "@nuxtjs/google-fonts": "^3.0.0-1",
    "@pinia/nuxt": "^0.4.6",
    "@types/bootstrap": "^5.2.6",
    "@types/node": "^18.15.11",
    "autoprefixer": "^10.4.14",
    "element-plus": "^2.3.5",
    "eslint": "^8.37.0",
    "nuxt": "^3.5.3",
    "perfect-scrollbar": "^1.5.5",
    "pinia": "^2.0.27",
    "postcss": "^8.4.23",
    "prettier": "^2.8.7",
    "sass": "^1.56.1",
    "sass-loader": "^13.2.0",
    "tailwindcss": "^3.3.2",
    "typescript": "^5.0.3",
    "vue-tsc": "^1.2.0",
    "@element-plus/icons-vue": "^2.1.0",
    "@element-plus/nuxt": "^1.0.5"
  }
}

tried different version of dependencies but got stuck for weeks

Why doesn’t javascript engine throw error when assinging a value to a primittive in a function call?

Consider the following example:

function primitiveAssigner(x) {
  console.log(x, typeof(x));
  x = 123;
  console.log(x, typeof(x));
}

primitiveAssigner(3); // 3 = 123 ??
let y = "MyString";
primitiveAssigner(y); // "MyString" = 123 ??

The only explanation I think makes sense is that if a primitive is passed as an argument to a function, then the JS engine doesn’t just pass a copy of the primitive; it rather creates a local variable x first, and then assignes the passed argument as a value to that x.

This question originally came up to me when I was trying to emulate useState hook behavior in simple javascript:

function theUseState(value) {  
  //const state = () => value; //correct impelementation   
  const setState = (newVal) => {
    value = newVal; //what if value is a primitive? e.g. theUseState(123), 123 = newValue ??
  };
  return [value, setState];
}

const [count2, setCount2] = theUseState(0);

Please do not consider this question as a question for react useState, I am working on it myself and don’t want to spoil it.

Netlify forms could not identify form in my JS file

I am unable to get the user response in my netlify server where i have enabled form detection and added data-netlify=true as mentioned in the docs in my form element.

I have tried to implement netlify forms in my project.I have followed the documentation and added data-netlify true in my form element.I have deployed the site on my custom domain https://mindokay.com/ and
the form is hosted on this particular link https://mindokay.com/talkToUs .Here is my JS file of the form container,
here is the js code

      <form
        name="form"
        onSubmit={handleSubmit}
        method="POST"
        action="/talkToUs"
        data-netlify="true"
      >
        
          Name:
          <input
            type="text"
            id="customerName"
            name="customerName"
            value={formData.customerName}
            onChange={handleInputChange}
            required
          />
        
        `your text`
          Phone Number:
          <input
            type="tel"
            id="phoneNumber"
            name="phoneNumber"
            value={formData.phoneNumber}
            onChange={handleInputChange}
            required
          />
        
        
          Company Name:
          <input
            type="text"
            id="companyName"
            name="companyName"
            value={formData.companyName}
            onChange={handleInputChange}
            required
          />
        
        
          Email:
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
          />
          
            Company Size:
            <select
              type="dropdown"
              id="companySize"
              value={companySize || ""}
              onChange={(e) => setCompanySize(e.target.value)}
              style={{ width: "105%" }}
            >
              
                Select a company size
              
              
                {" "}
                below 25{" "}
              
              
                25-100
              
              
                100-250
              
              
                250-1000
              
              1000" className="option">
                above 1000
              
            
          
          
            I already have a mental health plan of another company <br />
          
          
            
              <input
                type="checkbox"
                checked={showDate}
                onChange={handleToggle}
              />
              
            
            {showDate && (
              
                
                  Expires on :
                
                <input
                  type="date"
                  id="planEndDate"
                  name="planEndDate"
                  value={planExpiryDate ? formatDate(planExpiryDate) : ""}
                  onChange={(e) =>
                    setExpiryDate(
                      e.target.value ? new Date(e.target.value) : null
                    )
                  }
                  placeholder={showDate ? "Expires on" : ""}
                />
              `your text`
            )}
          
        
        
        

        <button type="submit">Submit</button>
      </form>

and the handleSubmit funtion as well.

const handleSubmit = (event) => {
event.preventDefault();
setShowBanner(true);
const myForm = event.target;
const formData = new FormData(myForm);

   fetch("/talkToUs", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams(formData).toString(),
   `your text`})
  .then((response) => {
    if (response.ok) {
      // Handle successful form submission
      alert("Thank you for your submission");
      // Reset form data and state
      setFormData({
        name: "",
        phoneNumber: "",
        companyName: "",
        email: "",
      });
    } else {
      // Handle form submission error
      throw new Error("Form submission failed.");
    }
  })
  .catch((error) => alert(error));

};

i have attached the screenshot of the response.Basically i am looking to get the response of my form in netlify server where i have deployed the site.

How to become a great programmer? [closed]

I’m beginner and I’m currently learning webdevelopment particularly BackEnd development, I want to become efficient when it comes in learning programming and not wasting time to it.
any tips?

and

How can I read someone else’s code to become a great programmer?

I’m expecting of giving of tips of other programmers because I want get some knowledge

ReactJS component file name must start with uppercase letter

I am playing around with the ReactJS and i have noticed that name of file which export components always upper case. For example file that contain Book component ( i’m working with book list) name Book.js. Naming the file export components by starting with uppercase letter is convention of Reactjs Community or this is the rule of reactjs library

Can i name the file that export Book component is book.js or b.js ? and this is may cause any implicit errors or not match with the rule of reactjs

useIdleTimer loader error with react 17 and node 18

  "engines": {
    "node": ">= 18.16.0",
    "npm": ">= 9.5.1"
  },
  "react": "^17.0.2",
  "react-idle-timer": "^5.7.2",
import { useIdleTimer } from "react-idle-timer";

Error msg:

./node_modules/react-idle-timer/dist/index.esm.js 240:8
Module parse failed: Unexpected token (240:8)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| var Q = {},
|   Ae = class {
>     name;
|     closed = !1;
|     mc = new MessageChannel();

Seemed to have tried everything. no solution.

Why does the hyperlink dissappear when setting a background color to a word in a page?

can someone help me figure out what’s wrong with the code below? Basically, I’m showing a hyuperlink in a page and if I add the highlightword function which works, the hyperlink disappears and what is left are the words. I would appreciate if someone could recommend or suggest a solution. Thank you very much in advance.

function project_awesome() {

for (let m = 0 ; m < images.length ; m++) {

    const checkA = document.documentElement.textContent.indexOf(images[m].A) > -1
    const checkB = document.documentElement.textContent.indexOf(images[m].B) > -1
    

    if (checkA == true && checkB) {

        let link = document.createElement("a");
        var linkText = document.createTextNode(images[m].name);
        
        link.appendChild(linkText);
        link.title = images[m].name;
        link.href = images[m].image_src;
        link.target = '_blank';
        link.appendChild(document.createElement("br"));
        link.appendChild(document.createElement("br"));
        document.getElementById('formatted-ticket-content').prepend(link);
        
        //Will send a notification that the hyperlink was clicked

        let eventListenerFunction = (e) => {log('A link was clicked'); }
        document.querySelectorAll('#formatted-ticket-content').forEach(linkText => {
        link.addEventListener("click", eventListenerFunction);
});

        // Find the words Test Word and set background color on page load 

        const htmlEncode = value => {
        const span = document.createElement("span");
        span.innerText = value;
        return span.innerHTML;
 };

        const highlightWord = wordToFind => {
        const element = document.getElementById('formatted-ticket-content');
        const originalLines = element.textContent.split("n");
        const newLines = originalLines.map(line => {

    if (!line.includes(wordToFind)) {
        return htmlEncode(line);
}

        const parts = line.split(", ").map(htmlEncode);
        parts[0] = `<span style="background-color:green;color:white;">${parts[0]}</span>`;
        return parts.join(", ");
   });

        element.innerHTML = newLines.join("n");
 };

        highlightWord('"Test Word"');

        break


    }
}

}

Unable to generate clientAccessUri for WebPubSubClient in typescript with @azure/web-pubsub and @azure/web-pubsub-client

I’m trying to use the Azure Web Pun Sub Service in my vuejs application which does the publish & subscribe both to a specific group (which is supposed to create dynamically and add users to this).
Looking into the examples provide for @azure/web-pubsub and @azure/web-pubsub-client npm package it seems to be very easy but the moment I start with the code, I got first struggled with building the project because uncaught exceptions for ‘crypto’, ‘stream’, ‘Buffer’, and ‘chile_process’ is not defined but I was able to fix this by installing npm packages crypto-browserify, stream-browserify and buffer and also added fallback settings in my webpack.config.js.

fallback: { // not present by default
                "crypto": require.resolve("crypto-browserify"),
                "stream": require.resolve("stream-browserify"),
                "buffer": require.resolve("buffer"),
                //"util": false,
                "child_process": false,
            }

The above fixes, help me to build the project successfully but I was unable to get the Azure pub-sub service client access URL to create the instance of WebPubSubClient. here is my code:

const key = new AzureKeyCredential(WPS_APIKEY);
                const serviceClient = new WebPubSubServiceClient(WPS_ENDPOINT, key, hubName);
                const fetchClientAccessUrl = async (_: GetClientAccessUrlOptions) => {
                    return (
                        await serviceClient.getClientAccessToken({
                            roles: [`webpubsub.joinLeaveGroup.${groupName}`, `webpubsub.sendToGroup.${groupName}`],
                        })
                    ).url;
                };
                let client = new WebPubSubClient({
                    getClientAccessUrl: fetchClientAccessUrl,
                } as WebPubSubClientCredential);
client.on("connected", (e) => {
                    console.log(`Connection ${e.connectionId} is connected.`);
                });

                client.on("disconnected", (e) => {
                    console.log(`Connection disconnected: ${e.message}`);
                });
                await client.start();
                await client.joinGroup(groupName);
                await client.sendToGroup(groupName, {
                    conversationId: this.$data.conversation.conversationId,
                    conversationContext: this.$data.conversation.conversationContext,
                    message: {
                        messageId: 100,
                        message: `Hello, You are welcome to the group: ${groupName}`,
                        timestamp: "08-06 06:20 PM",
                        sender: this.user.userName
                    }
                }, "json");

The above code fails when the client.start() executes and it tries to fetchClientAccessUrl with the above code func, with an error: “Right-hand side of ‘instanceof’ is not an object” inside jsonwebtoken/sign.js file at line no. 108 where the code is:

 if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {
    try {
      secretOrPrivateKey = createPrivateKey(secretOrPrivateKey)
    } catch (_) {
      try {
        secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === 'string' ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey)
      } catch (_) {
        return failure(new Error('secretOrPrivateKey is not valid key material'));
      }
    }
  }

Note: I have not installed the NPM package ‘jsonwebtoekn’ instead it came from ‘@azure/identity’.

Also, I get the same error while I’m trying to create a group and add users with the below code:

const key = new AzureKeyCredential(WPS_APIKEY);
const chatHub = new WebPubSubServiceClient(WPS_ENDPOINT, key, hubName);
let groupExists = await checkGroupExists(groupName);
        if (!groupExists) {
            let group = await chatHub.group(groupName);
            users.forEach(async usr => {
                await group.addUser(usr);
            });
        }

I tried a lot but had no luck. Can anyone please help me to understand if I’m doing something wrong here?

Here is the list of npm dependencies that my project has along with node (v20.2.0) and npm (v9.6.3).

"dependencies": {
        "@azure/identity": "^3.2.2",
        "@azure/web-pubsub": "^1.1.1",
        "@azure/web-pubsub-client": "^1.0.0-beta.3",
        "axios": "0.21.4",
        "core-js": "3.25.3",
        "crypto-browserify": "^3.12.0",
        "msal": "^1.4.18",
        "stream-browserify": "^3.0.0",
        "util": "^0.12.5",
        "uuid": "^9.0.0",
        "vue": "2.6.14",
        "vue-i18n": "8.27.2",
        "vue-router": "3.5.2",
        "vuex": "3.6.2"
    },
    "devDependencies": {
        "@babel/core": "7.15.5",
        "@babel/eslint-parser": "7.15.7",
        "@babel/preset-env": "7.15.6",
        "@types/jest": "27.4.0",
        "@types/node": "17.0.16",
        "@types/uuid": "^9.0.1",
        "@typescript-eslint/eslint-plugin": "5.11.0",
        "@typescript-eslint/parser": "5.11.0",
        "@vue/eslint-config-typescript": "9.1.0",
        "@vue/test-utils": "1.2.2",
        "@vue/vue2-jest": "27.0.0-alpha.2",
        "babel-loader": "8.2.2",
        "clean-webpack-plugin": "4.0.0",
        "concurrently": "7.4.0",
        "cors": "2.8.5",
        "css-loader": "6.2.0",
        "dotenv-webpack": "7.0.3",
        "eslint": "7.32.0",
        "eslint-plugin-vue": "8.0.1",
        "eslint-webpack-plugin": "3.2.0",
        "html-webpack-plugin": "5.3.2",
        "jest": "27.3.1",
        "jest-fetch-mock": "3.0.3",
        "jest-sonar-reporter": "2.0.0",
        "mini-css-extract-plugin": "2.5.3",
        "nodemon": "2.0.20",
        "postcss-loader": "6.1.1",
        "process": "0.11.10",
        "sass": "1.41.1",
        "sass-loader": "12.1.0",
        "serve": "12.0.1",
        "stylelint": "13.13.1",
        "stylelint-config-sass-guidelines": "8.0.0",
        "terser-webpack-plugin": "5.2.4",
        "ts-jest": "27.1.3",
        "ts-loader": "9.2.6",
        "typescript": "5.1.3",
        "vue-loader": "15.9.8",
        "vue-remove-attributes": "1.0.3",
        "vue-template-compiler": "2.6.14",
        "webpack": "5.74.0",
        "webpack-bundle-analyzer": "4.6.1",
        "webpack-cli": "4.10.0",
        "webpack-dev-server": "4.11.1"
    },

Not able to change title when using ‘use client’ in next.js 13

I have /demo route in my Next 13 App, and it is using app router. But I am unable to change title of page( The current title I an getting is localhost:3000/demo). I have following code.

/demo/page.js

'use client'

 ....

export const metadata = {
  title: 'Demo - ModalJS',
};

export default Demo(){
 return ...
}

The 'use client' is creating problem, because when I remove it Title changes, but problem is that I cannot remove it because this component uses OnClick which gives error without ”use client`’

Embed JavaScript code within the of the WooCommerce Thank You page and get order details

I am collaborating with an Affiliate Marketing company and need to send the order information to their system when an order is placed.
Despite my efforts to search for articles using keywords such as “Woocommerce Thank You page order details javascript,” I have been unsuccessful in retrieving the order information.

Here is the code provided by the other party:

<script type="text/javascript">
 var oeyaPostParam = {
 code : '',
 cookie_name : '',
 mcode : '', 
 oid : 'order id', 
 amount : 'order total',
 bid : '',
 gno : 'product id', 
 gname : 'product name',
 unit : ' ', 
 odate : 'order establishment time ', 
};
 (function() {
 var oeyasc = document.createElement('script'); oeyasc.type = 'text/javascript'; oeyasc.async = true;
 oeyasc.src = ' https://www.conn.tw/track/oeya_jss2s_v1.0.js';
 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(oeyasc, s);
 })();
</script>

The blank space means that there is no need to fill in or only a fixed value needs to be filled in.

I used Code Snippets and adding the following code:

Code PHP, setting to ‘Run snippet everywhere’

<?php

global $wp;

if ( isset($wp->query_vars['thankyou']) ) {
    $order_id = absint($wp->query_vars['thankyou']); // The order ID
    $order    = wc_get_order( $order_id ); // The WC_Order object
}

And Code HTML, insert it into Thank You page with elementor shortcode widget.

<!-- begin content -->

<script type="text/javascript">
 var oeyaPostParam = {
 code : '',
 cookie_name : '',
 mcode : '', 
 oid : '<?php echo $order->get_order_number(); ?>', 
 amount : '<?php echo $order->get_total(); ?>',
 bid : '',
 gno : '<?php echo $item->get_product_id(); ?>', 
 gname : '<?php echo $item->get_name(); ?>',
 unit : ' ', 
 odate : '<?php echo $order->get_date_created(); ?>', 
};
 (function() {
 var oeyasc = document.createElement('script'); oeyasc.type = 'text/javascript'; oeyasc.async = true;
 oeyasc.src = ' https://www.conn.tw/track/oeya_jss2s_v1.0.js';
 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(oeyasc, s);
 })();
</script>

But it didn’t work.
You may observe that the values are not being received on the Thank You page of the test order.

https://www.zmoji.com.tw/checkout/thankyou/1098/?key=wc_order_JyTChsw3eAXvn

What adjustments should I make to correctly transmit the order information to JavaScript?

Thank you all.

in this image have two side left and right. the image should stay in the middle of this tags and when I resize of website it should move too with line

in this image have two side left and right. the image should stay in the middle of this tags and when I resize of website it should move too with lineenter image description here

in this image have two side left and right. the image should stay in the middle of this tags and when I resize of website it should move too with line

Button can only run “alert()” and not any other code

My button <button id="btnDelete" class="delete-button" onclick="DeleteItems()">-</button> in ejs and it can only run alert() codes and not the rest like console.log(). I have added app.use(express.static("public")); in my nodejs. this is my route for the js file in the header <script src="scriptbutton.js"></script>

This is what i want my button to do:

function DeleteItems(){
   const pagetitle = document.getElementById("ListTitle").innerHTML;
   let arr = [];
   let checkboxes = document.querySelectorAll("input[type='checkbox']:checked");
   if(checkboxes.length == 0){
        alert("Please check at least one checkbox to delete");
        return;
   }
   for(let i = 0; i < checkboxes.length; i++){
        arr.push(checkboxes[i].value);
   }
   let body = JSON.stringify({checked : arr});
   fetch("/remove",
        {method: "post",
        redirect:"follow",
        body: body,
        headers: {
            'Content-Type' : 'application/json' 
        }})
        .then(response => {
            if(response.redirected){
                window.location.href = "/typeoflist/" + pagetitle;
            }
        })
        .catch(function(err){
            console.info(err);
        });
}   

I have tried testing the button to see if it worked with console.log and alert and it only displayed the alert command and not the console.log. it also does not route it into my post request (“/remove”) in app.js.

How to run Vue.js app with json-server backend simultaneously on cyclic?

I’m trying to deploy my Vue.js application on Cyclic, and I’m facing issues with running the frontend and backend scripts concurrently. The frontend is built with Vue.js, and I’m using json-server as a fake REST API for the backend. The problem is that I need to run both the frontend (dev script) and the backend (json-server) simultaneously for the application to work correctly.

Here’s my current package.json file:

{
  "name": "vue-project",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "backend": "json-server --watch db.json --port 5000"
  },
  "dependencies": {
    "json-server": "^0.17.3",
    "serve": "^14.2.0",
    "vue": "^3.3.2",
    "vue-router": "^4.0.13"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.2.3",
    "@vitejs/plugin-vue-jsx": "^3.0.1",
    "vite": "^4.3.5"
  }
}

I’m using the dev script to run the Vue.js frontend, and the backend script to run the json-server backend. Locally, I can run these two scripts concurrently using the concurrently package with the command npm run dev and npm run backend. However, when deploying the application on Cyclic, I’m unsure how to achieve the same behavior.

Additionally, I’m not sure how to run the backend on Cyclic since it’s using the port number 5000. How can I deploy my Vue.js application on Cyclic, run both the frontend and backend scripts simultaneously, and ensure that the backend is accessible on port 5000? Any suggestions or insights would be greatly appreciated. Thank you!