Unable to get the result set from a database transaction [duplicate]

    async function loadImages() {
      debugger;
      let images = await temporaryDataModel.getDataCollections();
      console.log(`logged + ${images}`);         
      return images;
    }

    export async function getDataCollections() {
      let resultSet = await new Promise( resolve => () => {
        const db = commonDBUtils.useDatabase();
        let payload = [];
        let len = 0;
        debugger;
        db.transaction(async (txn) => {
          txn.executeSql("SELECT * FROM TEMPORARY_TBL",
            [],
            (txn, results) => {
              len = results.rows.length;
              for(let i = 0; i < len; i++){
                payload.push(results.rows.item(i));
              } 
            }
          )
        })

    return resolve(payload);
  })
  return resultSet;
}

When i call loadImages, it does not log the images array. Infact it just logs “logged images”. Also when I do a debug, the debugger never reaches to the getDataCollections function as well. Am I doing anything wrong here?

I need a ctrl+click feature that performs 2 functions [duplicate]

I am still trying to learn javascript and don’t quite have the syntax down yet. My client wants a ctrl+click feature on a button. If the button is just clicked, I want it to execute the existing code to go to Paypal, if the button is clicked with the ctrl key pressed, I want it to go to a different page altogether. I pulled this snippet from w3school and I got it to work for the button, but obviously alerts are not what I need.

  <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" onmousedown="isKeyPressed(event)">
    <input type="hidden" name="cmd" value="_s-xclick">
    <input type="hidden" name="hosted_button_id" value="L7XXXXXXXXXYU">
    <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
    <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
  </form>

<script>
function isKeyPressed(event) {
  if (event.ctrlKey) {
    alert("The CTRL key was pressed!"); <- I want to go to different .html page
  } else {
    alert("The CTRL key was NOT pressed!"); <- I want to execute the Paypal instructions
  }
}
</script>

I cannot seem to find the correct syntax to make this happen. I presume I need a === NULL somewhere to trigger Paypal and something else to go to the external HTML page. I’m at a loss.

How to solve the smtpjs error with gmail smtp host

I am working with smptjs to send email using javascript. The code was working fine until today morning.

I am getting the error “Only elasticemail is supported as an SMTP host. To open an account please visit https://elasticemail.com/account#/create-account?r=20b444a2-b3af-4eb8-bae7-911f6097521c”

I tried to search for this error and unsuccessful, any help in this matter would be appreciated.

This is my js code to send the email

const name = form.elements["name"].value;
const from = form.elements["email"].value;
const companyName = form.elements["company-name"].value;
const businessType = form.elements["business-type"].value;
const isOperatingBusiness = form.elements["business"].value;

const emailBody = `<h3>Please find the details below</h3>
<hr />
<span><strong>Name:</strong> ${name}</span><br />
<span><strong>Email Address:</strong>  ${from}</span><br />
<span><strong>Contact No:</strong>  ${phone}</span><br />
<span><strong>Company Name:</strong> ${companyName}</span><br />
<span><strong>Operating Business:</strong>  ${isOperatingBusiness}</span><br />
<span><strong>Business Type:</strong>  ${businessType}</span><br /><br />
<span>Thank you,</span><br />
<span>appiGo Team</span>`;

const emailObject = {
      Host: HOST,
      Username: USERNAME,
      Password: PASSWORD,
      To: DEV_MAIL,
      From: FROM,
      Subject: `${subject} ${name}`,
      Body: emailBody,
};

Email.send(emailObject).then((message) => {
      if (message == "OK") return onSuccess();
});

Thank you in advanced!

Not receiving push notifications on desktop browsers

I was using push notifications on my site just fine until recently, they stopped working. I’m using kreait/firebase-php to send the notifications and there are no errors there.

My service worker has this code to handle them

self.addEventListener('push', function(event) {
  //handle background push notifications
  console.log(event);
  const notif = event.data.json();
  console.log(notif);
  const options = {
    body: notif.notification.body,
    icon: notif.notification.icon,
    tag: notif.fcmMessageId,
    data: notif.notification.click_action
  };
  event.waitUntil(self.registration.showNotification(notif.notification.title, options));
});

When I send a test message from Chrome devtools > Applications > Service Worker, the first console.log appears, then there is this error:
Uncaught SyntaxError: Unexpected token T in JSON at position 0. I’m not getting notifications on firefox either but I am receiving them on Chrome Android. I’m sending them to all 3 of these devices simultaneously.

D365 CRM – Account Saved, Workflow modified a field, and that field’s JavaScript onchange was triggered

Since when do server-side edits to fields (e.g. Plugin or Workflow) come back after Save and trigger the on-change of those fields on the form?

Is there any documentation of this? Anyway to stop it?

Example:

  • Assume a CRM field “Name” has a JS onchange to alert the user “you changed my name!”
  • Assume a synchronous Workflow triggered by another field field “Calculate Name” checkbox, will set Name to something server-side
  • User checks “Calculate Name” and saves
  • Result: “Name” field is updated on the screen as expected, by the synchronous Workflow’s edited value
  • UNEXPECTED Result: the JS onchange of “Name” is triggered and user sees “you changed my name!”

This is a simplified/odd example… but it raises an issue that now JS that was only meant to respond to User action is actually now also responding to server-side action… but only when the Update is initiated by a User on a Form. It’s very unexpected, inconsistent.

Warning: A component is changing an uncontrolled input to be controlled, even though the default value is “”

enter image description here

When I change the the dropdown field by the name of Dropdown, It throws a component is changing from controlled to uncontrolled, On reference this happens usually when the default value of a component is undefined, but when I logged the default value that was stored in the dB (before trying to change it), its stored as "":

enter image description here

I am unable to solve this issue, and without solving this issue, the value of the Dropdown field isn’t getting saved.

How to search objects react.js javascript?

Thanks for your time reading.

I need to sort countries by Language or Continent, the user selects the option he wants in the buttons.

countries is an array of objects of each country that contain:

  • languages is an array of objects, because each country can have more than one language
  • continent is an object with the continent name
    Complete example(countries array content): https://github.com/gonzaloramosf/countries

If the user select for example continents and types in the input “es” all the results related whit content Asia listed together in a group and do not repeat the continent title in each one, same i need with languages.
This is my code:

const CountrySearch = ({countries}) => {
    const [searchTerm, setSearchTerm] = useState("");
    console.log(countries)
    return (
        <div className="search">
            <h1>Country Search</h1>
            <span> Some random text </span>
            <div className="searchResults">
                <input type="text" placeholder="Search country..." onChange={event => {
                    setSearchTerm(event.target.value)
                }}/>
                <div className="groupBy">
                    <h2> Group by: </h2>
                    <div>
                        <button> Continent </button>
                        <button> Language </button>
                    </div>
                </div>

                <div>
                    {countries.filter((val) => {
                        if (searchTerm === "") {
                            return ""
                        } else if (val.name.toLowerCase().includes(searchTerm.toLowerCase())){
                            return val
                        }
                    }).map((val, key) => {
                        return (
                            <div key={key}>
                                <h2> {val.continent.name} </h2> 
                                <div className="countryInfo">
                                    <div>
                                        <span>{val.emoji}</span>
                                        <h3> {val.name} </h3>
                                    </div>
                                    <p> Capital: {val.capital} </p>
                                    <p> Currency: {val.currency} </p>
                                </div>
                            </div>
                        )
                    })
                    }
                </div>
            </div>
        </div>
    )
}
export default CountrySearch;

This is console.log(countries): enter image description here

Test execution with Jest and Context

I want to perform a test of a button that executes a function called deleteEmployee() but the problem that occurs to me is that when I execute the test it gives me the following error.

Error

  ● Employees Component › should execute deleteEmployee (it has interacion with context) when click button

    TypeError: Cannot destructure property 'employees' of '((cov_2ati4da0re(...).s[3]++) , (0 , _react.useContext)(...))' as it is undefined.

       6 |     const navigate = useNavigate();
       7 |     const params = useParams();
    >  8 |     const {employees, setEmployees} = useContext(EmployeesContext);
         |            ^
       9 |
      10 |     const deleteEmployee = (id) => {
      11 |         setEmployees(employees.filter(({dni}) => dni !== id))

Function

const deleteEmployee = (id) => {
        setEmployees(employees.filter(({dni}) => dni !== id))
}

Test

  it("should execute delete employee function when click button", () => {
    const wrapper = mount(
      <EmployeesContext.Provider>
        <Employees />
      </EmployeesContext.Provider>
    );
    const button = wrapper.find("button").first();
    button.simulate("click");
    expect(button.props().onClick).toBeDefined();
  });

In my context I only have defined a basic code and an initial definition with some default values.

Context declaration

import React, { useState } from 'react';
import { Header } from './components/Header';
import { EmployeesContext } from './context/EmployeesContext';
import { AppRouter } from './router/AppRouter';
import { BrowserRouter as Router} from 'react-router-dom'

function App() {
  const [employees, setEmployees] = useState([
    {
      name: "Jaime Armando Straus",
      address: "Los Angeles, CA",
      dni: "MBJ34368V12P5",
      birth: "19/03/1998",
      phone: "5628903455",
      email: "[email protected]",
      position: "Front-end Developer"
    },
    {
      name: "Jose Armando Straus",
      address: "Washington, DC",
      dni: "NFIN3543543NKBN",
      birth: "19/03/1980",
      phone: "5628903455",
      email: "[email protected]",
      position: "Back-end Developer"
    }
  ]);

  return (
    <EmployeesContext.Provider value={{employees, setEmployees}}>
      <Router>
        <div className="app">
          <Header />
          <AppRouter />
        </div>
      </Router>
    </EmployeesContext.Provider>
  );
}

export default App;

Context Code

import { createContext } from "react";

export const EmployeesContext = createContext(null);

A problem occurred configuring project ‘:react-native-vector-icons’. when starting the project

I have React Native project and when I try to run using npx react-native run-android I found some errors that said like this
A problem occurred configuring project ':react-native-vector-icons'.

Error RN Vector Icons

Currently, I’m using React Native 0.55.4 and React Native Vector Icons 4.3.0

I try to re-install using npm uninstall and npm install again but turns out it’s not solving the error. How can I solve this error? at first, I can run my project successfully but suddenly out of nowhere I cannot run it again because of this error.

Display A Random Quote and Author from Array List in a New activity On Button Click

I’m trying to create a mood checker application. Where when the user clicks on a mood, it would display a quote in a new activity. My application runs but the quote is not displayed. I think there might be a problem with my try catch method, but I don’t really know how to resolve this.

public class MainActivity extends AppCompatActivity {
public ImageButton awesome, good, neutral,sad, awful;
public int index;
public ArrayList<Quote> awesome_List;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // DECLARE MOOD BUTTONS//
    awesome=(ImageButton) findViewById(R.id.btn_awesome);
    good=(ImageButton) findViewById(R.id.btn_good);
    neutral=(ImageButton) findViewById(R.id.btn_neutral);
    sad=(ImageButton)findViewById(R.id.btn_sad);
    awful=(ImageButton)findViewById(R.id.btn_awful);

    //Create Array List for each mood quote and author


    //AWESOME MOOD//
    String[] awesomeQuoteArray = {
            "“Happy people don\'t have the best of everything, they make the best of everything",
            "“Most people are about as happy as they make up their minds to be”.",
            "“A happy person is happy, not because everything is right in their life but because their attitude towards everything in life is right”.",
            "“Make someone happy. Make just one someone happy and you will be happy too”",
            "“The beauty of life does not depend on how happy you are, but how happy others are because of you”."
    };

    String[] awesomeAuthorArray={
            "Marcel Proust",
            "Eckhart Tolle",
            "Adi Shankara",
            "Marcus Tullius Cicero",
            "Marcus Aurellius"
    };
    awesome_List=new ArrayList<>();
    addAwesomeToQuoteList(awesomeQuoteArray,awesomeAuthorArray);

    // generate awesome random quotes
    final int awesomeQuoteLength = awesome_List.size();
    index=getRandomQuote(awesomeQuoteLength-1);
    addAwesomeToQuoteList(awesomeQuoteArray,awesomeAuthorArray);

    awesome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            sendAwesomeData(); 

    }
    });
   }
   
public void sendAwesomeData(){
    String AwesomeText="";
    try {
        System.out.println(AwesomeText.charAt(awesome_List.size()));

        String hello ="hello";

        AwesomeText= awesome_List.get(index).toString();


    }catch (StringIndexOutOfBoundsException e){
        System.out.println("String index out of bounds. String length:" + AwesomeText.length());
    }
    String AwesomeOutputText = AwesomeText;
    Intent awesomeIntent= new Intent(MainActivity.this, awesome_mood_quotes.class);

    awesomeIntent.putExtra(awesome_mood_quotes.QUOTE,AwesomeOutputText );
    startActivity(awesomeIntent);
}


public int getRandomQuote(int length){
    return(int) (Math.random()*length)+1;
}

}


Second Activity Code

public class awesome_mood_quotes extends AppCompatActivity {
public static final String QUOTE= "QUOTE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_awesome_mood_quotes);

    TextView awesomeQuote=(TextView) findViewById(R.id.awesome_quote_text);

    Intent intent= getIntent();
    String AwesomeText=intent.getStringExtra(QUOTE);
    awesomeQuote.setText(AwesomeText);



}

}

when i add `”type”:”module”,`in `package.json`, remix config error

when i add "type":"module",in package.json, error occur…

error:

[1] Building Remix app in production mode...
[1] Error: Error loading Remix config in /Users/hyeseonhan/Desktop/admin-remix/remix.config.js
[1]     at Object.readConfig (/Users/hyeseonhan/Desktop/admin-remix/node_modules/@remix-run/dev/config.js:67:11)
[1]     at Object.build (/Users/hyeseonhan/Desktop/admin-remix/node_modules/@remix-run/dev/cli/commands.js:151:31)
[1]     at Object.run (/Users/hyeseonhan/Desktop/admin-remix/node_modules/@remix-run/dev/cli/run.js:351:22)
[1]     at Object.<anonymous> (/Users/hyeseonhan/Desktop/admin-remix/node_modules/@remix-run/dev/cli.js:16:11)
[1]     at Module._compile (node:internal/modules/cjs/loader:1103:14)
[1]     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
[1]     at Module.load (node:internal/modules/cjs/loader:981:32)
[1]     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
[1]     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
[1]     at node:internal/main/run_main_module:17:47
[1] remix build && run-p dev:* exited with code 1

package.json:

{
  "name": "remix-template-express-ts",
  "private": true,
  "description": "",
  "license": "",
  "sideEffects": false,
  "type":"module",
  "scripts": {
    "build": "yarn build:css && remix build",
    "build:css": "tailwindcss -m -i ./styles/app.css -o app/styles/app.css",
    "dev": "concurrently "yarn dev:css" "remix build && run-p dev:*"",
    "dev:css": "tailwindcss -w -i ./styles/app.css -o app/styles/app.css",
    "dev:node": "cross-env NODE_ENV=development nodemon ./build/index.js --watch ./build/index.js  --exec babel-node",
    "dev:remix": "remix watch",
    "postinstall": "remix setup node",
    "start": "cross-env NODE_ENV=production node ./build/index.js"
  },
  "dependencies": {
    "@babel/plugin-syntax-import-meta": "^7.10.4",
    "@babel/plugin-transform-runtime": "^7.17.10",
    "@ckeditor/ckeditor5-build-classic": "^34.0.0",
    "@fullcalendar/core": "^5.11.0",
    "@fullcalendar/interaction": "^5.11.0",
    "@googlemaps/js-api-loader": "^1.14.2",
    "@headlessui/react": "^1.5.0",
    "@heroicons/react": "^1.0.6",
    "@left4code/tw-starter": "^3.1.33",
    "@remix-run/express": "^1.3.3",
    "@remix-run/react": "^1.3.3",
    "@tailwindcss/forms": "^0.5.0",
    "@types/qs": "^6.9.7",
    "axios": "^0.26.1",
    "chart.js": "^3.7.1",
    "classnames": "^2.3.1",
    "compression": "^1.7.4",
    "cross-env": "^7.0.3",
    "dayjs": "^1.11.2",
    "dropzone": "^6.0.0-beta.2",
    "express": "^4.17.1",
    "heroicons": "^1.0.6",
    "highlight.js": "^11.5.1",
    "js-beautify": "^1.14.3",
    "jwt-decode": "^3.1.2",
    "lodash": "^4.17.21",
    "lucide-react": "^0.44.0",
    "morgan": "^1.10.0",
    "qs": "^6.10.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-hook-form": "^7.29.0",
    "react-query": "^3.34.19",
    "react-table": "^7.7.0",
    "react-transition-group": "^4.4.2",
    "remix": "^1.4.3",
    "tiny-slider": "^2.9.4",
    "tippy.js": "^6.3.7",
    "toastify-js": "^1.11.2",
    "tom-select": "^2.0.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/core": "^7.17.10",
    "@babel/node": "^7.17.10",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.17.10",
    "@remix-run/dev": "^1.3.3",
    "@remix-run/eslint-config": "^1.3.3",
    "@types/react": "^17.0.24",
    "@types/react-dom": "^17.0.9",
    "@types/react-table": "^7.7.10",
    "autoprefixer": "^10.4.4",
    "babel-loader": "^8.2.5",
    "concurrently": "^7.0.0",
    "eslint": "^8.11.0",
    "nodemon": "^2.0.15",
    "npm-run-all": "^4.1.5",
    "postcss": "^8.4.12",
    "tailwindcss": "^3.0.23",
    "typescript": "^4.5.5"
  },
  "engines": {
    "node": ">=14"
  }
}

remix.config.js

/**
 * @type {import('@remix-run/dev').AppConfig}
 */
module.exports = {
  server: "./server.js",
  ignoredRouteFiles: [".*"],
  devServerBroadcastDelay: 1000,
  // appDirectory: "app",
  // assetsBuildDirectory: "public/build",
  // serverBuildPath: "build/index.js",
  // publicPath: "/build/",
};

Does Spread Syntax create a shallow copy or deep copy?

I am extremely confused for days now regarding the true definition of a shallow copy and a deep copy.

When I read the mdn docs (https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) on shallow copy, it all made sense. The first paragraph clearly explains what a shallow copy is. The docs says

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made. As a result, when you change either the source or the copy, you may also cause the other object to change too — and so, you may end up unintentionally causing changes to the source or copy that you don’t expect.

I totally got that part. From my understanding, the below code example is the example of a shallow copy. Since changing either the source or the copy causes the other object to change too.

let a = {
    food: "pasta",
    restaurantName: "myPastPlace"
}

let b = a

b.food = "Hamburger"

console.log(b.food) //hamburger
console.log(a.food) //hamburger

So, the confusing part was that when I use the spread syntax to make a copy. Is this deep copy or shallow copy? Because for the first level deep, to me, the spread syntax(operator) is making a deep copy. However, the Mdn doc says the spread syntax creates a shallow copy rather than a deep copy.

In JavaScript, all standard built-in object-copy operations (spread syntax, Array.prototype.concat(), Array.prototype.slice(), Array.from(), Object.assign(), and Object.create()) create shallow copies rather than deep copies.

let a = {
    food: "pasta",
    restaurantName: "myPastPlace"
}

let b = {...a}
console.log(b)

b.food = "hamburger"

console.log(b.food) //hamburger
console.log(a.food) //pasta

How i can create a Regular Expression to return (0/00/00, 00:00, myName, message) from ‘0/00/00, 00:00 – myName: my message’?

I’m creating a app to transform whatsapp backup .txt into a .json and .csv files.

My app it’s working but i am refactoring now.

This code snippet currently solves my problem using js:

function stringToObject(string) {
    let commaSepareted = string.split(',')
    let date = commaSepareted[0]
    if(commaSepareted.length >= 2){

        let hyphenSepareted = commaSepareted.filter((_, index) => index >= 1).join().split('-')
        let time = hyphenSepareted[0].trimEnd().trimStart()

        let twoPointsSepareted = hyphenSepareted.filter((_, index) => index >= 1).join().split(':')
        let username = twoPointsSepareted[0].trimEnd().trimStart()
        let message = twoPointsSepareted.filter((_, index) => index >= 1).join()

        return {
            date,
            time,
            username,
            message
        }
    }
    return null
}

I want to refactor to resolve the same problem but using REGEX, so i basically need a function the receive a string in this format: “0/00/00, 00:00 – myName: message” and return a object like this:

{
    "date": "0/00/00",
    "time" : "00:00",
    "username": "myName",
    "message": "message"
}

React render object value where key is variable

I’m trying to render an object where each key is different.
I have to display each key as a checkbox and if it is checked, I want to display the associated values if any in the values array.

My object structure is as follows:

    myObj: {
           "key1": ["val1", "val2"],
           "key2": [],
           ...
           }

I’m going through the list of keys to render the checkboxes and within, I’m using the code below for rendering the values.
I have the value of the current key accessible in a property myKey.value. But if I try to use formValues.myObj.myKey.value to access the values, it complains that property myKey does not exist on type myObj.

{formValues.myObj.[`${currentKey}`].length > 0 && 
    <CustomArrayHelper
    values={formValues.myObj.currentKey}
    arrayName="test"
    onRender={(avIndex: number) => (
        <div className="my-container std-TextField">
            <FormikTextField
                name={`test.${avIndex}`}
                label={`Test`}
            />
        </div>
    )}
/>}

I need some way to dynamically specify the current key to get the values for each key. The above code returns an error.

I also have the list of possible keys available separately:

export const MyKeys = [
    {
        value: 'key1',
        label: 'key1'
    },
    ...
]