Code Bug Fix: Objects: Value always undefined

Original Source Link

I am working on some keybinding functionality and came across something that is quite confusing to me.

I am doing some regex validation against the user defined keybinding pattern and would then like to assign the pattern as key and value to definedKeys:

const definedPattern = ['a', 'b']
let definedKeys = {}

const bindKeys = () => {
  const charKey = (String(definedPattern[0]) + String(definedPattern[1])).match(/^[a-zA-Z]{2}$/)
    
  if (charKey) {
    definedKeys[charKey.input[0]] = definedKeys[charKey.input[1]]
  }
  
  console.log(definedKeys)
}

bindKeys()

  • Use definedKeys instead of definedCharKeys as it is not declared neither initailized

  • Assigning value directly to key instead of refrencing value from definedKeys because value is not still set and it will be always undefined.

  definedKeys = {};
  const encodeKey = (pKey) => {
      charKey = (String(pKey[0]) + String(pKey[1])).match(/^[a-zA-Z]{2}$/);
      if (charKey) {
          // charKey.input = 'ab'
          definedKeys[charKey.input[0]] = charKey.input[1];
      }
  }

  encodeKey('ab');
  console.log(definedKeys);

Isn’t it because you don’t put anything in definedKeys but instead you put it in definedCharKeys?

As per the code. You are not assigning anything in “definedKeys”. You are assigning a value in “definedCharKeys” that’s why you are getting undefined for the “definedKeys”.

Please post full code where are you calling the function so that developers can provide you solution.

Tagged : /

Code Bug Fix: Create a new array of documents of objects using map JavaScript

Original Source Link

I have an array of ids and I am trying to map through this array to create a new array of movie objects which is in my database.

my code looks like this…

const movieIds = foundDirector.movies;

const movies = movieIds.map(async (id) => {
    await Movie.findById(id);
  });

The code above doesn’t work. I am able to find a movie and see that data from within the map function but when I print movies to the console I get an array with empty objects.

I then decided to do this instead and it works.

const movieIds = foundDirector.movies;
let movies = [];

for (let i = 0; i < movieIds.length; i++) {
  const movie = await Movie.findById(movieIds[i]);
  movies.push(movie);
}

I’m not happy with the solution. I obviously am having issues understanding how promises work in JavaScript and using async/await has been easy enough for now but I don’t want to rely on it.

as an example I tried doing something like…

const movieIds = foundDirector.movies;
let movies = [];

for (let i = 0; i < movieIds.length; i++) {
  const movie = Movie.findById(movieIds[i]).then((data) => data);
  movies.push(movie);
}

const allMovies = Promise.all(movies).then((values) => values);

I noticed that after printing movies to the console I was getting an array of pending promises I tried using const allMovies = Promise.all(movies).then((values) => values); but allMovies still just is a pending promise.

Can anyone please explain what is going on here, and how can I achieve this with a map function rather than a for loop.

Well, you can achieve what you want with an approach like below.

const allMovies = await Promise.all(movieIds.map(Movie.findById))

It just maps ids to promises and awaits all of them.

const allMovies = Promise.all(movies).then((values) => values);
console.log(allMovies);

The above code will log awaiting promises because by the time that console.log nothing has happened yet. There is nothing that awaits those promises to have resulted. Then callback has no effect on allMovies variable. This answer has nice info about it.

Tagged : / /

Code Bug Fix: MacOS: Pass filepath into node via cli

Original Source Link

Say I have the following npm script:

"test": "node $FILE"

How would I pass an absolute path to it via cli?

Example:

FILE="pwd + filename" npm run test

which should result in:

node /Root/Subfolder/filename

I’m on MacOS using NodeJS 14.

For example, you have a script file e.g. ./scripts/test.js.

The script config would be like this:

"test": "node ${FILE}"

And, the command to run it would be:

$ FILE="$(pwd)/scripts/test.js" npm run test

Tagged : / / / /

Code Bug Fix: await message reaction in a message await reaction, error (message.react is not a function)

Original Source Link

Whyever it says : UnhandledPromiseRejectionWarning: TypeError: message.react is not a function maybe it has to do because this await reactiont thing is already in a await message reaction -> if ( reaction emoji = C) but idk what i would have to change

} else if (mainEmbedEmoji == "🇨") {
                // call the lord EmojiMessageMan1 to handle reactions
                async function emojiMessageMan1(message, validReactions) {

                    // validReactions = ["one", "two"]
                    for (const reaction1 of validReactions) await message.react(reaction1);

                    // filter
                    const filter1 = (reaction, user) => validReactions.includes(reaction.emoji.name) && (!user.bot)

                    // returns emoji the user reacted with
                    return message
                        .awaitReactions(filter1, {
                            max: 1,
                        })
                        .then(collected => collected.first() && collected.first().emoji.name);
                }

                const bigC = new MessageEmbed()
                    .setColor('0x0099ff')
                    .setTitle("Premium Minecraft Servers")
                    .setDescription(`*Link:* https://cloudx.host/cart.php?gid=1nnYou want to host a Minecraft Java Edition Server? No problem, with our High-End specifications will your Server be online 24/7 and you can enjoy Minecraft with your friends without having to worry about connection!nn**Options/Prices:**`)
                    .addField(`**RAM Options:**`, "*Please choose how much RAM your Server should have:*n:one:: 1 GB RAMn:two:: 2 GB RAMn:three:: 3 GB RAMn:four:: 4 GB RAMn:six:: 6 GB RAMn:eight:: 8 GB RAMn:keycap_ten:: 10 GB RAMnnPlease react to this message with :one:, :two:, :three:, :four:, :six:, :eight: or :keycap_ten:")


                // sends bigC and await for reactions

                let mainEmbedMsg1 = "";
                    await message.channel.send(bigC).then((message) => {
                        mainEmbedMsg1 = message
                    })
                let mainEmbedEmoji1 = await emojiMessageMan1(bigC, ['1⃣', '2⃣', '3⃣', '4⃣', '6⃣', '8⃣', '🔟'])

In emojiMessageMan1 function call you are passing as first parameter bigC which is a MessageEmbed.

But you actually wait for a Message in your reaction handler.

So you have to pass mainEmbedMsg1 instead of bigC :

let mainEmbedEmoji1 = await emojiMessageMan1(mainEmbedMsg1, ['1⃣', '2⃣', '3⃣', '4⃣', '6⃣', '8⃣', '🔟'])

Tagged : / / /

Code Bug Fix: node.js] how to catch GET in server.js?

Original Source Link

I want to run function in server, then use $.ajax in website.js
First, i want to test ajax and cathc GET in server.
I’ll try to test the function that displays “hellooooo” on the console by simply catching GET.
However, the code is not working properly.

this is code in server js


##  server.js  ##

const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const EventHubReader = require('./scripts/event-hub-reader.js');
const SendMessage = require('./public/js/C2D.js');

const iotHubConnectionString = process.env.IotHubConnectionString;
if (!iotHubConnectionString) {
    console.error(`Environment variable IotHubConnectionString must be specified.`);
    return;
}
console.log(`Using IoT Hub connection string [${iotHubConnectionString}]`);

const eventHubConsumerGroup = process.env.EventHubConsumerGroup;
console.log(eventHubConsumerGroup);
if (!eventHubConsumerGroup) {
    console.error(`Environment variable EventHubConsumerGroup must be specified.`);
    return;
}
console.log(`Using event hub consumer group [${eventHubConsumerGroup}]`);

// Redirect requests to the public subdirectory to the root
const app = express();
app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res /* , next */) => {
    res.redirect('/');
});

app.get('./send/', function(req,res) {
    console.log("HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.broadcast = (data) => {
    wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
            try {
                console.log(`Broadcasting data ${data}`);
                client.send(data);
            } catch (e) {
                console.error(e);
            }
        }
    });
};

server.listen(process.env.PORT || '3000', () => {
    console.log('Listening on %d.', server.address().port);
});

    const eventHubReader = new EventHubReader(iotHubConnectionString, eventHubConsumerGroup);

(async () => {
    await eventHubReader.startReadMessage((message, date, deviceId) => {
        try {
            const payload = {
                IotData: message,
                MessageDate: date || Date.now().toISOString(),
                DeviceId: deviceId,
            };

            wss.broadcast(JSON.stringify(payload));
        } catch (err) {
            console.error('Error broadcasting: [%s] from [%s].', err, message);
        }
    });
})().catch();

i can found GET log in my application console

console message 

2020-05-15 08:43:23 test GET /send/ 

but i can’t find result of this code

app.get('./send/', function(req,res) {
    console.log("HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
});

what is problem in my code, and how can i modify to run correctly?

I don’t think there is supposed to be a ‘.’ dot in ./send/. Maybe it should just be /send

Tagged : / /

Code Bug Fix: how to run both validation(emailid,contactno) in javascript

Original Source Link

I m performing valiadation(emailid validation,contactno validation)

both are run individually

when I comment code emailaddress validation then contactno validation work fine

when I comment code contactno validation then emailaddress validation work fine

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title></title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    function validatation() {

      //validation for emailaddress
      var emailText = document.getElementById('txtemailid').value;
      var patternemailid = /^[a-zA-Z0-9-_]+(.[a-zA-Z0-9-_]+)*@[a-z0-9]+(-[a-z0-9]+)*(.[a-z0-9]+(-[a-z0-9]+)*)*.[a-z]{2,4}$/;
      if (patternemailid.test(emailText)) {
        debugger
        return true;
      } else if ($("#txtemailid").val() == "") {
        alert("Provide a Email Address");
        $("#txtemailid").focus();
        return false;
      } else {
        alert('your Email Address is Bad: ' + emailText);
        debugger
        return false;
      }

      //validation for contactno
      var txtPhone = document.getElementById("txtcontactno").value;
      var phoneno = /^+?([0-9]{2}))?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
      var mobileno = /^((\+91-?)|0)?[0-9]{10}$/;
      if ((txtPhone.match(phoneno)) || (txtPhone.match(mobileno))) {
        alert("Valid");
      } else {
        alert("Not Valid")
      }
    }
    }
  </script>
</head>

<body>
  <form id="txtContactInformation" action="displayInfo.html" onsubmit="return validatation()">
    <h1>Contact Information</h1>

    <label for="txtemailid">EmailAddress:</label>
    <input id="txtemailid" name="txtemailid" type="text" /><br/>

    <label for="txtpass">Password:</label>
    <input id="txtpass" name="txtpass" type="password" /><br/>

    <label for="txtcontactno">Contact No:</label>
    <input id="txtcontactno" name="txtcontactno" type="number" /><br/>

    <input id="btnsubmit" type="submit" value="Submit" />

  </form>
</body>

</html>

I want to run both validation emailaddress and contactno validation?

well your function is not reaching the contact no validation , because you are exiting the funtion after your email validation it self,

you have 2 approcached ,

1. have different function for email and contact number

        function mailValidation() {

        //validation for emailaddress
        var emailText = document.getElementById('txtemailid').value;
        var patternemailid = /^[a-zA-Z0-9-_]+(.[a-zA-Z0-9-_]+)*@[a-z0-9]+(-[a-z0-9]+)*(.[a-z0-9]+(-[a-z0-9]+)*)*.[a-z]{2,4}$/;
        if (patternemailid.test(emailText)) {
            debugger
            return true;
        }
        else if ($("#txtemailid").val() == "") {
            alert("Provide a Email Address");
            $("#txtemailid").focus();
            return false;
        }
        else {
            alert('your Email Address is Bad: ' + emailText);
            debugger
            return false;
        }
    }

and

function contactNoValidation(){
  //validation for contactno
            var txtPhone = document.getElementById("txtcontactno").value;
            var phoneno = /^+?([0-9]{2}))?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
            var mobileno = /^((\+91-?)|0)?[0-9]{10}$/;
            if ((txtPhone.match(phoneno)) || (txtPhone.match(mobileno))) {
                alert("Valid");
            }
            else {
                alert("Not Valid")
            }
        }

2. just don’t return after email validation and continue further validation

    function validatation() {
        var emailStatus = false;
        var contactNoStatus = false;
        //validation for emailaddress
        var emailText = document.getElementById('txtemailid').value;
        var patternemailid = /^[a-zA-Z0-9-_]+(.[a-zA-Z0-9-_]+)*@[a-z0-9]+(-[a-z0-9]+)*(.[a-z0-9]+(-[a-z0-9]+)*)*.[a-z]{2,4}$/;
        if (patternemailid.test(emailText)) {
            debugger
            emailStatus=true;
        }
        else if ($("#txtemailid").val() == "") {
            alert("Provide a Email Address");
            $("#txtemailid").focus();
        }
        else {
            alert('your Email Address is Bad: ' + emailText);
            debugger
        }

        //validation for contactno
        var txtPhone = document.getElementById("txtcontactno").value;
        var phoneno = /^+?([0-9]{2}))?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
        var mobileno = /^((\+91-?)|0)?[0-9]{10}$/;
        if ((txtPhone.match(phoneno)) || (txtPhone.match(mobileno))) {
            alert("Valid");
        }
        else {
            alert("Not Valid")
        }
        return emailStatus;
    }

       }

a return statement will exit the function so if the compiler finds a return statement, in any case, it will exit the function. So if you want to continue executing the function and do the further validations, remove return statements/

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function validatation() {
	         
			var Error_description=[];               
            //validation for emailaddress
            var emailText = document.getElementById('txtemailid').value;
            var patternemailid = /^[a-zA-Z0-9-_]+(.[a-zA-Z0-9-_]+)*@[a-z0-9]+(-[a-z0-9]+)*(.[a-z0-9]+(-[a-z0-9]+)*)*.[a-z]{2,4}$/;
           
		   if (patternemailid.test(emailText)) {
                debugger
                return true;
            }
            else if ($("#txtemailid").val() == "") {
               Error_description.push("Provide a Email Address");           
            }
            else {
                Error_description.push("your Email Address is Bad:"+ emailText);			
            }

            //validation for contactno
            var txtPhone = document.getElementById("txtcontactno").value;
            var phoneno = /^+?([0-9]{2}))?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
            var mobileno = /^((\+91-?)|0)?[0-9]{10}$/;
            if ((!txtPhone.match(phoneno)) || (!txtPhone.match(mobileno))) {
                Error_description.push("Provide a Valid Phone No");
            }
         
				if(Error_description.length>0){
				alert(Error_description.toString());
				return false;
				}
				else{
				return true;
				}
		
		}
      
	  
	 
    </script>
</head>
<body>
    <form id="txtContactInformation" action="displayInfo.html" onsubmit="return validatation()">
        <h1>Contact Information</h1>

        <label for="txtemailid">EmailAddress:</label>
        <input id="txtemailid" name="txtemailid" type="text" /><br />

        <label for="txtpass">Password:</label>
        <input id="txtpass" name="txtpass" type="password" /><br />

        <label for="txtcontactno">Contact No:</label>
        <input id="txtcontactno" name="txtcontactno" type="number" /><br />

        <input id="btnsubmit" type="submit" value="Submit" />

    </form>
</body>
</html>
Tagged : /

Code Bug Fix: Simple HTML Audio Track with a Few Variables [closed]

Original Source Link

I have an API that controls music playback.
Audio is not played through the browser, but via a Discord bot.

Desired Result

High Budget Diagram

Variables:

  • current: the current position of the track (e.g. 2:30)
  • max: the max position/length of the track (e.g. 3:00)

Events:

  • move: calls moveTo(position)
  • end: calls reset()

Is there any libraries that can achieve something similar to this, or would I have to make a custom one to do something like this?

I will be using Angular 9 to do this.

Audio Demo: https://www.youtube.com/watch?v=VowfGyZGS_Y

Are you looking for the <audio> tag? You can add this to your html document and get a audio player (the browser’s built in one). Here is an example https://www.w3schools.com/html/html5_audio.asp. If you do not want to use the browser’s built in one you can use a library like plyr or audio.js

EDIT

You say you want a Discord bot. Well I do not think there is any API for what you are looking for. Can you describe more what you want this bot to do?

Tagged : / / /

Code Bug Fix: Random in CSS or JS

Original Source Link

need help, want to spin the image and after 3 sec it must stop with random dergree (from 360 to 10800). it starts spin when I click it from the last position.

when the image stops, it appears an area with RANDOM citation from my massive. it must be something like “spin the bottle”

please help, I’ve got some code, but don’t know how to finish it.

.wheel {
  animation: wheel 3s .5s;
  animation-fill-mode: both;
}

@keyframes wheel {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(10800deg);
  }
}
<head>
  <link rel="stylesheet" href="bottle.css">
  <script src="bottle.js"></script>
</head>
<img id="wheel" class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">

You can do this with css custom properties. The first thing to do is create a property for your transform:

:root{
  --rot: rotate(108000deg);
}

And then use that in place of your hard-coded value

@keyframes wheel {
  from { transform: rotate(0);}             
  to { transform: var(--rot); }
}

At this stage everything should carry on working as before.

Now you can manipulate that property with javascipt:

var min = 360;
var max = 108000;
var rnd = Math.random()* (max - min) + min;
console.log(rnd);

var wheel = document.querySelector(".wheel");
wheel.style.setProperty("--rot","rotate(" + rnd + "deg)");
:root{
  --rot: rotate(108000deg);
}

.wheel {				
  animation: wheel 3s .5s;	
  animation-fill-mode: both;	
}

@keyframes wheel {
  from { transform: rotate(0);}				
  to { transform: var(--rot); }
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">

If you want to repeat the animation on something like a click you need to doa bit of a workaround

var min = 360;
var max = 108000;

var wheel = document.querySelector("#wheel");
wheel.addEventListener("click", function(e) {
  e.preventDefault;
  
  // -> removing the class
  wheel.classList.remove("wheel");
  
  // -> triggering reflow /* The actual magic */
  // without this it wouldn't work. Try uncommenting the line and the transition won't be retriggered.
  // Oops! This won't work in strict mode. Thanks Felis Phasma!
  // element.offsetWidth = element.offsetWidth;
  // Do this instead:
  void wheel.offsetWidth;
  
  var rnd = Math.random()* (max - min) + min;
  console.log(rnd);
  wheel.style.setProperty("--rot","rotate(" + rnd + "deg)");
  // -> and re-adding the class
  wheel.classList.add("wheel");
}, false);
:root{
  --rot: rotate(108000deg);
}

.wheel {				
  animation: wheel 3s .5s;	
  animation-fill-mode: both;	
}

@keyframes wheel {			
  to { transform: var(--rot); }
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">

Here is a one liner approach to spin the element with random degree;

let rnd = Math.floor(Math.random() * (10800 - 360 + 1)) + 360;
document.querySelector(".wheel").style = `transform:rotate(${rnd}deg)`;
.wheel {				
  animation: wheel 3s .5s;	
  animation-fill-mode: both;
}

@keyframes wheel {
  to { transform: rotate(0deg);}				
}
<img class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">
Tagged : / /

Code Bug Fix: Bug in tab navigation script when forms have content

Original Source Link

I am trying to write a script that gives a CSS class specifically made for tab navigation to tag-navigation users.

After much help from friends I had something that seemed to work, but after further testing it seems that it crashes every time I have written something into a form, and tab back to that element that has something written in it. I belive this is because I am using .value but I am not sure what I could replace it with (or how). The error message states

TypeError: Cannot read property ‘add’ of undefined
and is fired for the line focusedElement.classList.add("tabbed")

My script resides in my gatsby layout.js page

...imports here 
config.autoAddCss = false

const useActiveElement = () => {
  const [active, setActive] = useState(document.activeElement)

  const handleKeyup = (e) => {
    if (e.keyCode === 9) setActive(document.activeElement)
  }

  useEffect(() => {
    document.addEventListener("keyup", handleKeyup)
    return () => {
      document.removeEventListener("keyup", handleKeyup)
    }
  }, [])

  return active
}

const Layout = ({
  children,
  crumbLabel,
  subStatus,
  parentPageLabel,
  parentPageLink,
}) => {
  const focusedElement = useActiveElement()

  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      sanitySiteSettings {
        title
      }
    }
  `)

  useEffect(() => {
    const prevTabbedElements = document.getElementsByClassName("tabbed")
    for (let i = 0; i < prevTabbedElements.length; i++) {
      prevTabbedElements[i].classList.remove("tabbed")
    }
    focusedElement.value && focusedElement.value.classList.add("tabbed")
    focusedElement.classList.add("tabbed")
  }, [focusedElement])

  return (
    <>
      <Header siteTitle={data.sanitySiteSettings.title} />
      <nav>
        {subStatus ? (
          <Parentcrumbs
            crumbLabel={crumbLabel}
            parentPageLabel={parentPageLabel}
            parentPageLink={parentPageLink}
          />
        ) : (
          <Breadcrumbs crumbLabel={crumbLabel} />
        )}
      </nav>
      <main>{children}</main>

      <Footer />
    </>
  )
}
Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

Tagged : / /

Code Bug Fix: Problem with regex expressions and Jquery on Input events

Original Source Link

having a problem using regular expression to allow only certain characters. The problem is when i try to insert a character into words to correct errors. When i try to insert the new char the cursor move to the end of the input box.

this is the code i use:

$('body').on('input','.info',function() {
        this.value = this.value.replace(/[^a-zA-Z0-9+&,*_- b r ]/g, '');

Any hints?

Thank you in advance

You need to save the character index (the selectionStart) so you can reposition to it after value change is complete, if a value change needs to be made:

$('body').on('input', '.info', function(e) {
  const index = this.selectionStart - 1;
  const replaced = this.value.replace(/[^a-zA-Z0-9+&,*_- b r ]/g, '');
  if (replaced !== this.value) {
    this.value = replaced;
    this.selectionStart = index;
    this.selectionEnd = index;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="info">
Tagged : / /