if else condition inside for loop using angular

I am working on a task where I am looping an array inside a tag & using target=”_blank” attribute but one of the array element should not want this target=”_blank” attribute so what to do?

<ul *ngIf="item.menu">
            <li *ngFor="let subMenu of item.menu">
              <a href="{{subMenu.link}}" target="_blank">{{'landing.menu.' + subMenu.name | translate}}</a>
            </li>
          </ul>

Javascript – Regex match multiple instances [duplicate]

I am new to regex and I am trying to get multiple instances of sections that start and end with a % across a string.
For example, I have the following string:

This happened %Monday% following our forest %trip%. Tomorrow %we will% start packing our things and %return home%.

I am looking to get all the sections that start with % and end with % detected and I cannot seem to get my head around regex… 🙁
I did try a few ways but all it did it selected either everything inside the sentence between first % and last one or just the %.
Thank you.

How to programmatically push a docker image to a docker registry?

I’ve looked online for an answer, but all I could find were articles about dockerizing a node app and pushing it to docker hub or another registry. My question is different.

I programmatically generate some basic files in a folder. One of the root files is a Dockerfile, which I use to build a docker image with child-process. After I build this image, I’d like to push it to my docker registry (not docker hub).

What options am I left with here? Using child-process again after building the image?

Issue with metamask when sending money to the smart contract

I am new to solidity and smart contracts and I am bit confused with sending money from metamask to my smart contract. Everything seems to work fine in remix but when I use metamask I get a revert error message. I am using ganache as my local blockchain

My smart contract looks like this: –

    // SPDX-License-Identifier: GPL-3.0
    pragma solidity ^0.8.10;

   import "@openzeppelin/contracts/access/Ownable.sol";


    contract Bet is Ownable{

     
     uint public Money;  // set variable to display balance on contract
     bool Odd;  // variable to set true or false
     uint TotalDiceNumber = 12;  // dice numbers from 1 - 12
     uint result;  // variable to hold the dice roll
     mapping(address => uint)  allowance;  //allowance for non owners of the contract
     uint  BetValue;  //variable for original bet value
     uint  _amount; //variable to hold value of allowance 
     bool  Active; // is the game active
     
     

     
    constructor() {
    

    }

    

    function isOwner() internal view returns(bool) {
        return owner() == msg.sender;  //returns the address who deployed it
    }
    event BetMade(address player, uint Bet);  //placeholder to send data to front end
     function receiveMoney() public payable  {  // get money(bet) from metamask and put on smart
        emit BetMade(msg.sender, BetValue); // send player and value of bet
        //Money += BetValue;  //added after react
        Money += msg.value;
        BetValue = msg.value;
            if (owner() == msg.sender) {
                Active = false;  // owner doesnt active contract to protect funds
            } else {
                Active = true;  // player activates contract when bet is placed
                require(BetValue <= 20 ether, "Bets must be below 21 Ether"); //player can only 
          bet under 20 ether/ owner can put as much money as they want on
         }
      }
    event BalanceofContract(uint Balcontract);
       function getBalance()public returns(uint) { 
        uint Bal;
        Bal = address(this).balance;
        emit BalanceofContract(Bal);
        return Bal;
        
        
    }
    
    event PlayerSelectOddEven(address player, bool OddEven);
    function selectOddorEven(bool OddEven) public {
        emit PlayerSelectOddEven(msg.sender, OddEven);
        require(msg.sender != owner(), "You are the house and cannot bet");  // house cannot bet
        require(Active = true, "Game not in play. Please place a bet"); // game must be active
        Odd = OddEven;  // create field to enter true for odd or false for Even
        //default is false

    }

    
    function Random() internal view returns(uint) {
        return uint(keccak256(abi.encodePacked
        (block.difficulty, 
        block.timestamp, 
        TotalDiceNumber)));  // create a random number from blockchain.
        //in production would look at chainlink VR but looks like there is a cost so
        //went with a less secure option
    } 
    event RollDiceOutput(address player, uint DiceNumber);
    function Rolldice() public returns(uint){
        emit RollDiceOutput(msg.sender, result);
        uint Outcome;
        require(Active = true, "Game not in play. Please place a bet");  //game must be actvie
        Outcome = Random() % TotalDiceNumber;
        result = Outcome + 1;  // use + 1 to remove 0 out of random sequence
        return result;  // function to create number
        
        }
    function OutcomeDice() public view returns (uint) {
        uint Outcome1;
        Outcome1 = result;
        return Outcome1;
        // function to view number from above function
        }
        
    function numberOddorEven() public view returns (bool) {
        bool OddorEven;  // true for odd false for even
        uint _result;
        _result = result;
            if (_result == 1  ||  _result == 3  || _result == 5 || _result == 7 || _result == 9 || 
          _result == 11) {
                OddorEven = true; 
            } else {
                OddorEven = false;
            }
            return OddorEven;
        
            }
    event Winning(address Player, uint WinningsValue);
    function addAllowance() public   {
        emit Winning(msg.sender, _amount);  
        require(msg.sender != owner(), "You are the house and cannot bet");
        require(Active = true, "Game not in play. Please place a bet");
        address _who = msg.sender; // assign player to variable
        _amount = BetValue * 2; //assign allowance twice as much original bet
        allowance[_who] == _amount;  // set allowance in mapping against player
        
        }

    event Won(address Player, uint Winnings);               
    function WinMoney() public  {  
        emit Won(msg.sender, _amount);
        bool UserInputOdd = numberOddorEven();
        bool decisionOdd = Odd;
        address _who = msg.sender; // assign player to variable
        require(Active = true, "Game not in play. Please place a bet"); 
        require(_amount > 0, "Add the house's money by adding a allowance to collect winning");
            if (UserInputOdd == decisionOdd) {
                address payable to = payable(msg.sender);  //pay the player's address
                to.transfer(_amount); // transfer the winning
                _amount = 0; //zeroed the variable for multiplying the bet
                allowance[_who] = 0; // zeroed the allowance
                BetValue = 0; // zeroed the bet
                Odd = false; // resets the odd/even input
                Active = false;  //disable the game 

            } else {
                _amount = 0;  //zeroed the variable for multiplying the bet
                allowance[_who] = 0;  // zeroed the allowance
                BetValue = 0;  // zeroed the bet
                Odd = false;  // resets the odd/even input
                Active = false;  //disable the game 

                }
            
                                    
         }

        receive() external payable {
        receiveMoney();
      }
   }

On the front end I am trying to add funds to the smart contract: –

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useState } from "react"  //import library for line 9
import { ethers } from "ethers" // import library for ethers
import { abi_file } from "../constants/abi"; // import abi from different file

export default function Home() {
  const [isConnected, setIsConnected] = useState(false);  //to show a button is not connected
  const [signer, setSigner] = useState();

  async function connect() {  //create function to connect metameask
      
    if (typeof window.ethereum !== "undefined") { // check to see if metamask is installed
      try {
        await ethereum.request({ method: "eth_requestAccounts"});
        setIsConnected(true);  // set variable as true
        const connectedProvider = new ethers.providers.Web3Provider(window.ethereum);
        setSigner(connectedProvider.getSigner());
        } catch (e) {
          console.log(e);  // catch and log and errors in console(F12 in chrome)
        }
      } else {
      setIsConnected(false);
      }

}

async function Rolldice() {  //execute function

  if (typeof window.ethereum !== "undefined") { // check to see if metamask is installed

    const contractAddress = "0x89f6D41f87054127066d4639e3Ada3DeEefE5EB7";  // address of the contract
    const abi = abi_file;
    

    const contract = new ethers.Contract(contractAddress, abi, signer);  // calls the contract from the 3 variables
    
   
    try {
     // await contract.Rolldice();  //function will are calling on the sol contract
     const transactionResponse = await contract.Rolldice();
     const transactionReceipt = await transactionResponse.wait();
     var player = (transactionReceipt.events[0].args.player);
     var result = (transactionReceipt.events[0].args.DiceNumber.toString());
      //alert("Dice Number pressed");
      //var x = document.createElement("H3");
      //var t = document.createTextNode("Dice rolled from " + player);
     // x.appendChild(t);
     // document.body.appendChild(x);
      var z = document.createElement("H3");
      var w = document.createTextNode("Dice number is " + result);
      z.appendChild(w);
      document.body.appendChild(z);
           
      
    } catch (error) {
      console.log(error);
    }
  } else {
    document.getElementById("executeButton").innerHTML = 
    "Please install MetaMask";
  }
}

async function receiveMoney() {  //execute function

  if (typeof window.ethereum !== "undefined") { // check to see if metamask is installed

    const contractAddress = "0x89f6D41f87054127066d4639e3Ada3DeEefE5EB7";  // address of the contract
    const abi = abi_file;
    

    const contract = new ethers.Contract(contractAddress, abi, signer);  // calls the contract from the 3 variables
    
   
    try {
     // await contract.Rolldice();  //function will are calling on the sol contract
     const transactionResponse = await contract.receiveMoney();
     const transactionReceipt = await transactionResponse.wait();
      var Balance = (transactionReceipt.events[0].args.Bet.toString());
      //alert("Dice Number pressed");
      //var x = document.createElement("H3");
      //var t = document.createTextNode("Dice rolled from " + player);
     // x.appendChild(t);
     // document.body.appendChild(x);
      var z = document.createElement("H2");
      var w = document.createTextNode("The Balance of the contract is " + Balance);
      z.appendChild(w);
      document.body.appendChild(z);
           
      
    } catch (error) {
      console.log(error);
    }
  } else {
    document.getElementById("executeButton").innerHTML = 
    "Please install MetaMask";
  }
}



  return <div className={styles.container}>


  {isConnected ? 
  <>
  <h2>"Connected!" </h2>

  <p> Please send money to 0x89f6D41f87054127066d4639e3Ada3DeEefE5EB7 but no higher than 20 ethers</p>
  
  <button onClick= {() => receiveMoney()}>Bet Money</button>
  <br></br>
  <br></br>
  <button onClick= {() => Rolldice()}>Roll dice</button>
  <br></br>
  <br></br>
  
  </>
  : (<button onClick={() =>connect()}>Connect</button>) }

   
    </div>;


   }

Can anybody suggest where I am going wrong? Many thanks

Javascript unexpected identifier but works in console

When I create a script as such

    async function a(){
        return 'a';
    }
    console.log(undefined || await a());

The browser (Brave & Edge) gives the error Uncaught SyntaxError: missing ) after argument list

Funnily enough, copy and pasting the exact same code into the debug console runs without a complaint.

Any explanation?

JS remove class Name dynamically

I have a requirement to remove a class name dynamically via js.

The reason to do so is that I’m trying to remove the icon of sorting a specific column from a table.

When I inspect the element – I see I have ng-class with the same class name as the class attribute.

I don’t have any access to the angular file – since it’s a third-party app, but I can write some JS in it.

<th title="" ng-repeat="$column in $columns" ng-class="{
   'sortable': $column.sortable(this),
   'sort-asc': params.sorting()[$column.sortable(this)]=='asc',
   'sort-desc': params.sorting()[$column.sortable(this)]=='desc'
   }" class="col_poi_Id_356 sortable">
</th>

When I’m removing the “sortable” from the class manually from the developer console – It works great.

But when I’m trying to do: element.remove("sortable"); it removes the “sortable” both from the class and from the ng-class and its causes unwanted behavior.

I want to remove a class name only from the class attribute without touching the ng-class.

is that possible?

I don’t have much knowledge in JS, but I tried to find a solution on the google but didn’t find one.

any help, including links, will be much appreciated.

Thanks!

JS/React: Replace ids by values from constant

I’ll be glad for any hint!
I have an array:

"languages": [
    {
        "languageId": 1,
        "languageLevelId": 2
    },
    {
        "languageId": 9,
        "languageLevelId": 3
    },
    {
        "languageId": 0,
        "languageLevelId": 3
    }
]

And constants:

export const LANGUAGE = {
    UKRAINIAN: 0,
    ENGLISH: 1,
    CHINESE: 2,
    SPANISH: 3,
    ARABIC: 4,
    JAPANESE: 5,
    HINDUSTANI: 6,
    FRENCH: 7,
    GERMAN: 8,
    RUSSIAN: 9,
    PORTUGUESE: 10,
    ITALIAN: 11
};

export const LANGUAGE_LEVEL = {
    BEGINNER: 0,
    INTERMEDIATE: 1,
    ADVANCED: 2,
    NATIVE: 3
};

How can I get something, like:

"languages": [
    {
        "languageId": ENGLISH,
        "languageLevelId": ADVANCED
    },
    ...
]

And then map languages, or what should I do in order to get such a result and get:
And then map languages, or what should I do in order to get such a result and get:

<div>English</div>
<div>Advanced</div>

Get original implementation during jest mock

I’m trying to temporarily mock node-fetch in an ESM module while still retraining the original implementation so I can access a real endpoint’s value. However, this errors with “Must use import to load ES Module.” I recognize jest support for ESM is still pending – is there any way to have this behavior in a combination of current Node, ES6, and Jest?

worker.ts (dependency):

export default async () => {
    const response = await fetch("http://example2.org");
    return await response.json()
  }

main.test.ts:

import { jest } from "@jest/globals";


jest.mock("node-fetch", () => {
    return Promise.resolve({
        json: () => Promise.resolve({ myItem: "abc" }),
    })
})

import doWork from './worker.js';
import mockedFetch from 'node-fetch';

const originalFetch = jest.requireActual('node-fetch') as any;

test("Ensure mock", async () => {
    const result = await doWork();
    expect(result.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(1);

    const response = await originalFetch("http://www.example.org");
    expect(response.status).toBe(200);

    const result2 = await doWork();
    expect(result2.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(2);
});

AWS API Gateway IAM Authorization – Generating signature using crypto.js

I am working on an app for Jira Cloud platform using forge framework. I created an HTTP endpoint using AWS API Gateway. This endpoint triggers a lambda function that does some operation on DynamoDB. I employed IAM authorization for the endpoint. After failing trials to use aws4 library with forge, I used the following function that is taken from AWS documentation to create signing key. However, while sending the request using javascript, I always get “{message: Forbidden}”.:

export function getAWSHeaders(){
  const accessKey = ""
  const secretKey =  ""
  const regionName = "us-east-1"
  const serviceName = "execute-api"


  var date = new Date().toISOString().split('.')[0] + 'Z';
  date = date.split("-").join("").split(":").join("")
  var dateWithoutTime = date.split("T")[0]

  var myHeaders = {}
  myHeaders["X-Amz-Date"] = date;

  var crypto = require("crypto-js");

  var kDate = crypto.HmacSHA256(dateWithoutTime, "AWS4" + secretKey);
  var kRegion = crypto.HmacSHA256(regionName, kDate);
  var kService = crypto.HmacSHA256(serviceName, kRegion);
  var kSigning = crypto.HmacSHA256("aws4_request", kService);

  myHeaders["Authorization"] = "AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + dateWithoutTime + "/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + kSigning

  return myHeaders;
}

This is how I send the request:

resolver.define("test", async ({context}) => {
  var url = ""
  var myHeaders = getAWSHeaders()
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  const result = await fetch(url, requestOptions)

I cannot figure out what is wrong with my signing key generation. I checked several posts but could not find a sample request.
Thanks for the help in advance.

PS: I tested it using Postman, it works with the “AWS Signature” authorization in Postman.

Generate any number of characters random id:

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * 
 charactersLength));
   }
   return result;
}

console.log(makeid(5));

I tried to use this code but i need to generate random count of chars.

For example: “fe3jo1gl124g” or “xkqci4utda1lmbelpkm03rba”

React useEffect TypeError Method Date.prototype.toLocaleString called on incompatible receiver undefined

I know this has something to do with a problem with the function binding to the wrong “this” but I can’t figure out how to fix it. I had this issue in the useState call but fixed that by following the advice from this post, but the advice given for the .toLocaleString in the useEffect is not working. I don’t know how to resolve this. Here is my code

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function DateTime(props) {
  const [getTime, setTime] = useState(() => new Date().toLocaleString());

  useEffect(() => {
    setInterval(() => {
      setTime(new Date().toLocaleString);
    }, 1000);
  });
    return (<div className="App">{getTime}</div>);
}

Sequelize help (throw new Error(`Unrecognized datatype for attribute “${this.name}.${name}”`);)

Here is the GitHub repo for this project: https://github.com/SethZygner/full-stack-testing

I am trying to use Sequelize to use CRUD in MySQL.

    return sequelize.define("test", {
        PersonID: {
            type: Sequelize.INT
        },
        Name: {
            type: Sequelize.STRING
        }
    });
};

When I run this in the terminal with node server.js it gives me this error:
throw new Error(`Unrecognized datatype for attribute "${this.name}.${name}"`);

As well as the error Error: Unrecognized datatype for attribute "test.PersonID"

Again, I’m not sure exactly how this works given my little knowledge on using Sequelize. So the repo will be more help to get a better idea.

For reference, MySQL has a database called DB and a table within it called test

Sidebar pushes content right when minimized, sticks when maximized

I am very, very new to front-end (I’ve been doing it for a week)

I currently have some JS/React, and CSS code that makes a basic website. Everything works and I’ve fixed all the bugs but one:

When the screen is full-size, the sidebar is automatically open. I don’t really care if it is or isn’t (and my problem may be solved if it wasn’t), but it is. When I minimize, the sidebar collapses and opens as normal. The content of the main page and the navigation bar on the top push to the right using JQuery. However, if I leave the sidebar open and maximize the screen, the contents stay pushed to the right because the sidebar stays open on the larger screen.

I have no idea what you need to see to be able to help me, so I’ll post the sidebar JS and CSS and the App.js JQuery code.

App.js

  const [sidebarOpen, setsidebarOpen] = useState(false);
  const openSidebar = () => {
    setsidebarOpen(true);
    $('.main__container').toggleClass("open");
    $('.navbar').toggleClass("open");
    $('.navbar__left').toggleClass("open");
  };
  const closeSidebar = () => {
    setsidebarOpen(false);
    $('.main__container').toggleClass("open");
    $('.navbar').toggleClass("open");
    $('.navbar__left').toggleClass("open");
  };

I did try to do an if/else up there ^, something like if the sidebar is already open and you try to open again, then toggle twice, but that didn’t work.

sidebar.js

const Sidebar = ({sidebarOpen, closeSidebar}) => {
   
    return (
        <div className={sidebarOpen ? "sidebar_responsive" : ""} id="sidebar">
            <div className="sidebar__title">
                <div className="sidebar__img">
                    <img src={logo} alt="logo" />
                </div>
                <div className="sidebar__he">
                    <h1>name <br></br> stuff</h1>
                </div>
                <i
                onClick={() => closeSidebar()}
                className="fa fa-times"
                id="sidebarIcon"
                aria-hidden="true"
                ></i>
            </div>
    **menu items**

sidebar.css

#sidebar {
    background: #263f8e;
    grid-area: sidebar;
    overflow-y: auto;
    padding: 20px;
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
    height: 100vh;
  }
  
  
  .sidebar__menu > h2 {
    color: #69BF87;
    font-size: 16px;
    margin-top: 15px;
    margin-bottom: 5px;
    padding: 0 10px;
    font-weight: 700;
  }
  

  .sidebar_responsive {
    display: inline !important;
    z-index: 9999 !important;
    left: 0 !important;
    position: absolute;
    
  }
  
  @media only screen and (max-width: 978px) {
    #sidebar {
      display: none;
    }
  
    .sidebar__title > i {
      display: inline;
    }
  }

I only included what I thought might help ^^

I can’t upload an image using cloudinary

I’m using express-file upload and Cloudinary to upload a file, but not to work, here is my server file and upload file. postman is sending a 500 empty error message, postman reads all the files, but I can’t upload them on Cloudinary. I’ve tried everything I know

import express from 'express';
import cloudinary from 'cloudinary';
const router = express.Router();

cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.CLOUD_API_KEY,
    api_secret: process.env.CLOUD_API_SECRET
});

router.post('/upload', (req, res) => {
    try {
        console.log(req.files)
        if (!req.files || Object.keys(req.files).length === 0) return res.status(422).json('no files uploaded');

        const file = req.files.file;
        console.log(file);
        if (file.size > 1024 * 1024) {
            rmvTmp(file.tempFilePath);
            return res.status(400).json({ msg: 'size too large' });
        }

        if (file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
            rmvTmp(file.tempFilePath);
            return res.status(400).json({ msg: 'this file format is not supported' });
        }
        cloudinary.v2.uploader.upload(
            file.tempFilePath,
            { folder: "vireau" },
            async (err, result) => {
              if (err) throw err;
      
              rmvTmp(file.tempFilePath);
              res.json({ public_id: result.public_id, url: result.secure_url });
            }
          );
    } catch (error) {
        return res.status(500).json({ msg: error.message });
    }
});

const rmvTmp = (path) => {
    fs.unlink(path, (err) => {
      if (err) throw err;
    });
  };

export default router;

How do I prevent the anchor tag from overwriting my CSS style

I’m very new to all this. I’m trying to make my image into a link using the anchor tag but doing so seems to ignore the previous style I had for the image and I’m not sure why.
So my CSS looks like this:

/* Element */
*, *::after, *::before{
    box-sizing: border-box;
}

/* Variable */
:root{
     --handle-size: 3rem;
     --img-gap: .25rem;
}


.body{
   margin: 0;
}

.container{
   display: flex;
   justify-content: center;
   overflow: hidden;
}

.slider{
     --items-per-screen: 4;
     --slider-index: 0;
     display: flex;
     flex-grow: 1;
     margin: 0 var(--img-gap);
     transform: translateX(calc(var(--slider-index) * -100%));
     transition: transform 500ms ease-in-out;
}

.slider > img {
     flex: 0 0 calc(100% /  var(--items-per-screen));
     max-width: calc(100% / var(--items-per-screen));
     aspect-ratio: 16 / 9;
     padding: var(--img-gap);
     border-radius: 1rem;
 }

and my images are inside of a div which without the anchor displays correctly:

<div class = "slider">
    <img src="Icons/schitts.jpg" stlye="container" alt = "Schitts Creek">
    <img src="Icons/familyguy.jpg" alt = "Family Guy">
    <img src="Icons/gameofthrones.jpg" alt = "Game Of Thrones">
    <img src="Icons/sopranos.jpg" alt = "The Sopranos">
    <img src="Icons/southpark.jpg" alt = "South Park">
    <img src="Icons/prisonbreak.jpg" alt = "Prison Break">
    <img src="Icons/curbyourenthusiasm.jpg" alt = "Curb Your Enthusiasm">
    <img src="Icons/americandad.jpg" alt = "American Dad">
    <img src="Icons/sinister.jpg" alt = "Sinister">
    <img src="Icons/superbad.jpg" alt = "Superbad">
    <img src="Icons/hangover.jpg" alt = "The Hangover">
    <img src="Icons/midsommar.jpg" alt = "Midsommar">
</div>

When I add the anchor tag between an image, it ignores the previous styles I had while the other images without the anchor tag remain in the correct style.
How do I keep the layout of everything the same while allowing the image to contain a link?

Without Anchor tag

With Anchor tag around first image