Get API response properly

I am using:

https://api-v3.mbta.com/docs/swagger/index.html#/Schedule/ApiWeb_ScheduleController_index

and I am trying to create something like dashboard where you can see arriving and departing trains.
As far as I can see, if I use API route like this:

https://api-v3.mbta.com/schedules?filter[stop]=place-north

I am getting everything except name of the direction(where the train is heading to?). How I can add the name? I tried several stuff like this:

https://api-v3.mbta.com/schedules?filter[stop]=place-north&include=route.data.id.attributes

But unfortunately not getting the proper result.
My dashboard be something like this:

https://commons.m.wikimedia.org/wiki/File:North_Station_departure_board,_December_2011.jpg

(intermediate value).setTitle(…).setDescription(…).setThumbnail(…).addFields(…).setImage(…).setTimeStamp is not a function, Discord.js

Hi’ I’ve been trying to code an embed for my bot to send but I keep getting the same error “(intermediate value).setTitle(…).setDescription(…).setThumbnail(…).addFields(…).setImage(…).setTimeStamp is not a function”

I’ve looked online for answers but all people who had the same problem had errors in their code in areas mine doesn’t, I’ve been looking for hours and I have no idea what’s wrong. this is my code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed, MessageAttachment} = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('information')
        .setDescription('Returns info based on input')
        .addSubcommand(subcommand =>
            subcommand
                .setName("user")
                .setDescription("Gets information of a user mentioned")
                .addUserOption(option => option.setName("target").setDescription("The user mentioned")))
        .addSubcommand(subcommand =>
            subcommand
                .setName('server')
                .setDescription("Gets information about the server")),
    async execute(interaction, client) {
        if (interaction.options.getSubcommand() === "user") {
            const user = interaction.options.getUser("target");
            if (user) {
                const file = new MessageAttachment("./src/images/mayancoin.png");
                const userEmbed = new MessageEmbed()
                    .setTitle(`${user.username} Information:`)
                    .setDescription("test")
                    .setThumbnail(client.user.displayAvatarURL())
                    .addFields(
                        { name: `Username:`, value: `Username is: ${user.username}`, inline: true},
                        { name: `u200B`, value: `u200B`, inline: true },
                        { name: `Tag:`, value: `Tag is: #${user.discriminator}`, inline: true }
                    )
                    .setImage("attachment://mayancoin.png")
                    .setTimeStamp()
                    .setColor("#009988")
                    .setFooter(client.user.tag, client.user.displayAvatarURL());

                await interaction.reply({ embeds: [userEmbed], files: [file] });
            } else {
                await interaction.reply(`Username: ${interaction.user.username}nYour ID: ${interaction.user.id}`);
            }
        } else if (interaction.options.getSubcommand() === "server") {
            await interaction.reply(`Server Name: ${interaction.guild.name}nTotal Members: ${interaction.guild.memberCount}`);
        } else {
            await interaction.reply("No sub command was used");
        }
    },
};

Any help is appreciated

Testcafe AWS Cognito Login – Input not recognized as visible

I’m building a website and as a part a AWS Cognito login is used. I now wanted to write e2e test in TestCafe, but I’m struggling to get the Cognito login form to work with TestCafe.

When no session is found, the page will redirect you to the proper AWS Cognito OAuth “login” page.

The following test code will fail

import { Selector } from 'testcafe';

const config = {...};

test('Logging in', async t => {
    await t
        .typeText(Selector('input#signInFormUsername'), config.credentials.username)
        .typeText('input#signInFormPassword', config.credentials.password)
        .click('input[type=submit]');
});

with the error

The element that matches the specified selector is not visible.

...

       21 |});
         22 |
         23 |//then create a test and place your code there
         24 |test('Logging in', async t => {
         25 |    await t
       > 26 |        .typeText(Selector('input#signInFormUsername'), config.credentials.username)
         27 |        .typeText('input#signInFormPassword', config.credentials.password)
         28 |        .click('input[type=submit]');
         29 |});
         30 |

And in deed, when I execute the test

test('Logging in', async t => {
    const usernameInputVisible = usernameInputSelector.visible;
    await t.expect(usernameInputVisible).ok();
});

it does fail.

The curious thing is a) I do actually see the element and b) it’s neither display: none nor visibility: hidden as descripted here under visible.

The element does exists according to TestCafe as the following does not fail:

test('Logging in', async t => {
    const usernameInputExists = usernameInputSelector.exists;
    await t.expect(usernameInputExists).ok();
});

What am I missing here? How do I get TestCafe to work with the AWS Cognito OAuth login page?

Setup:

$ sw_vers
ProductName:    macOS
ProductVersion: 12.2.1
BuildVersion:   21D62

$ node --version    
v16.14.0

$ testcafe --version
1.18.4

Uploading files with Ajax and PHP but does not write data to database

I want to upload file and write the uploaded file name and upload time into database. In the code below, the file is loaded, but it does not write the data to the database. Why do you think it might? Is there anyone who can help with the issue? Where exactly could I be making the mistake?

Form Block Code

<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1"><br>
  <input type="button" value="Gönder" onclick="uploadFile()">
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <h3 id="status"></h3>
  <p id="loaded_n_total"></p>
</form>

Ajax Code

function _(el) {
  return document.getElementById(el);
}

function uploadFile() {
  var file = _("file1").files[0];
  // alert(file.name+" | "+file.size+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file1", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);
  ajax.open("POST", "upload_file_for_booking.php");
  ajax.send(formdata);
}

function progressHandler(event) {
  _("loaded_n_total").innerHTML = " Uploaded " + event.loaded + " bytes to " + event.total;
  var percent = (event.loaded / event.total) * 100;
  _("progressBar").value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% Uploaded ... Please Wait";
}

function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0;
}

function errorHandler(event) {
  _("status").innerHTML = "Upload Failed";
}

function abortHandler(event) {
  _("status").innerHTML = "Upload Aborted";
}

PHP Code

<?php 
$localhost = "localhost"; #localhost
$dbusername = "my_user_name"; #username of phpmyadmin
$dbpassword = "my_password";  #password of phpmyadmin
$dbname = "my_db_name";  #database name

$conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname);

$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true


if (!$fileTmpLoc) { // if file not chosen
    echo "Hata : Please select file";
    exit();
}

if(move_uploaded_file($fileTmpLoc, "upload/$fileName")){
    $sql = "INSERT INTO `uploads` (`id`,`file_name`,`upload_time`) VALUES (NULL,'$fileName','2020-03-18 08:18')";
    echo "$fileName Upload Complete.";
} else {
    echo "Error";
}
?>

Modal is refresh on KeyPress

I know there are question asked before, but I have tried the solution but it’s not working. I have split the component differently but then also it refresh on every single keypress.

    const TenementRegistration = () => {

   const [show, setShow] = useState(false);
   const [name, setName] = useState("");
   const [editId, setEditId] = useState("");
    
    function Example() {

  

    const onSubmitHandler = async () => {
      
      const data = {
        name: name
    }
     await services.postService("User", data).then((res) => {
              onGetUserData();
            });
    }

    return(

          <Modal
          show={show}
          onHide={() => setShow(false)}
          size="lg"
          aria-labelledby="example-custom-modal-styling-title"
          scrollable="true"
          centered
          animation="true"
        >
          <Modal.Header closeButton>
            <Modal.Title id="example-custom-modal-styling-title">
              Add User
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div className="form-container">
              <form>
                <Row>
                  <div className="form-group col-12 col-md-6 center">
                    <label for="inputName" className="asy-FormLabel">
                      Name
                    </label>
                    <input
                      type="text"
                      className="form-control asy-InputValues"
                      id="policyName"
                      placeholder="Enter Property Id"
                      onChange={(e) => {
                        setName(e.target.value);
                      }}
                      value={Name}
                      required
                    />
                  </div>
</Row>
              </form>
</div>
</Modal.Body>
          <Modal.Footer>
            <button
              type="button"
              className="submit-button"
              onClick={() => 

    {
              
    
          onSubmitHandler();
                  }}
                >
                  Submit
            </button>
</Modal.Footer>
        </Modal>

    const [data, setData] = useState([]);

  useEffect(() => {
    onGetUserData();
  }, []);

  const onGetUserData = async () => {
    services.getService("User").then((res) => {
      setData(res.data);
    });
  };
const onEditData = async (id) => {
setShow(true);
 const newData = data.filter((obj) => obj.id === id)[0];
 setName(newData.name);
}
//Table where we show name and pass id to update button
}

I have also tried to Split the Modal and separate the form (not in this example) but it didn’t work any suggestions how to handle the modal problem

how to create a chart with a callback function for the x-axis if the values are numbers?

I try to create a line-chart with numbers for the x-axis (the ‘kw’ value), but it only works if the value is in string format. I use a callback function to add a string to the value in the legend. How can I create the chart with numbers from the data and add a string to it for the legend?
I hope you can see in my example what I mean.

With String:

var dString = [{
    kw: '1',
    wert: 120
  },
  {
    kw: '2',
    wert: 125
  },
  {
    kw: '3',
    wert: 110
  }
];

var dNumber = [{
    kw: 1,
    wert: 120
  },
  {
    kw: 2,
    wert: 125
  },
  {
    kw: 3,
    wert: 110
  }
];


dia(dString, 'dia');
dia(dNumber, 'dia2');


function dia(d, id) {
  var configDia = {
    data: {
      datasets: [{
        type: 'line',
        label: 'Ist',
        data: d,
        parsing: {
          xAxisKey: 'kw',
          yAxisKey: 'wert'
        }
      }]
    },
    options: {
      scales: {
        x: {
          ticks: {
            display: true,
            callback: function(value, index, ticks) {
              return `KW ${this.getLabelForValue(value)}`;
            }
          }
        },
        y: {
          ticks: {
            callback: function(value, index, ticks) {
              return value + '%';
            }
          }
        }
      }
    }
  };

  var ctx = document.getElementById(id);
  var myChart = new Chart(ctx, configDia);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<canvas id="dia"></canvas>
<canvas id="dia2"></canvas>

Form check prevent from submiting even when everything is ok

i have a problem with my form, i ran it through the form checker and even when everything is successful it still won’t submit. i tried to change it a lot of times and im not sure how to keep the code like that instead of one function that will return on form submit.

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
const genderSelected = document.getElementById('select');
//Show input error messages
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

//show success colour
function showSucces(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

//check email is valid
function checkEmail(input) {
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  if (re.test(input.value.trim())) {
    showSucces(input)
  } else {
    showError(input, 'Email is not invalid');
  }
}


//checkRequired fields
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`)
    } else {
      showSucces(input);
    }
  });
}


//check input Length
function checkLength(input, min, max) {
  if (input.value.length < min) {
    showError(input, `${getFieldName(input)} must be at least ${min} characters`);
  } else if (input.value.length > max) {
    showError(input, `${getFieldName(input)} must be les than ${max} characters`);
  } else {
    showSucces(input);
  }
}

//get FieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// check passwords match
function checkPasswordMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
  }
}

//check if selected a gender
function checkSelect(option) {
  if (select.value)
    showSucces(option);
  else
    showError(option, 'Please select a gender');
}



//Event Listeners
form.addEventListener('submit', function(e) {
  e.preventDefault();

  checkRequired([username, email, password, password2, genderSelected]);
  checkLength(username, 3, 15);
  checkLength(password, 6, 25);
  checkEmail(email);
  checkPasswordMatch(password, password2);
  checkSelect(genderSelected);
});
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
 :root {
  --succes-color: #2ecc71;
  --error-color: #e74c3c;
}

* {
  box-sizing: border-box;
}

.wrapper {
  width: 400px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 25px;
  margin: 8% auto 0;
  position: relative;
}

.container {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

h2 {
  text-align: center;
  margin: 0 0 20px;
}

.form {
  padding: 30px 40px;
}

.form-control {
  margin-bottom: 10px;
  padding-bottom: 20px;
  position: relative;
}

.form-control label {
  color: #777;
  display: block;
  margin-bottom: 5px;
}

.form-control input {
  border: 2px solid #f0f0f0;
  border-radius: 4px;
  display: block;
  width: 100%;
  padding: 10px;
  font-size: 14px;
}

.form-control input:focus {
  outline: 0;
  border-color: #777;
}

.form-control.success input {
  border-color: var(--succes-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  position: absolute;
  bottom: 0;
  left: 0;
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}

.form button {
  cursor: pointer;
  background-color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  color: #fff;
  display: block;
  padding: 10px;
  font-size: 16px;
  margin-top: 20px;
  width: 100%;
}

form {
  border: 0px solid black;
  display: inline-block;
  text-align: left;
}

body {
  margin: 50px 0px;
  padding: 0px;
  text-align: center;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
  background-color: lightblue;
}

.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  display: inline;
  resize: horizontal
}

label,
input[type="text,password,date"] {
  display: block;
  width: 150px;
  float: left;
  margin-bottom: 10px;
}

input[type="radio"] {
  display: block;
  width: 25px;
  float: left;
  margin-bottom: 10px;
}

label {
  text-align: right;
  width: 75px;
  padding-right: 20px;
}

br {
  clear: left;
}

h1 {
  color: black;
  text-align: center;
  font-size: xx-large;
}

.button {
  text-align: center;
  margin: auto;
  display: inline-block;
  padding: 5px 15px;
  font-size: 18px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: black;
  background-color: white;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: black;
  color: white;
}

.button:active {
  background-color: black;
  color: white;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

p {
  font-family: verdana;
  font-size: 20px;
}

#wrapper {
  width: 30%;
  margin: 50px auto;
  padding: 50px;
  background: #D7FBFF;
}

.textInput {
  border: none;
  height: 28px;
  margin: 2px;
  border: 1px solid #6B7363;
  font-size: 1.2em;
  padding: 5px;
  width: 95%;
}

.textInput:focus {
  outline: none;
}

.btn {
  width: 98.6%;
  border: none;
  margin-top: 5px;
  color: white;
  background-color: #3b5998;
  border-radius: 5px;
  padding: 12px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
  border-right: 1px solid #bbb;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

output {
  display: inline;
}

.customizedBox {
  border: 1px solid #111;
  width: 500px;
  height: 400px;
}

select {
  width: 280px;
  height: 40px;
  padding: 10px;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  border: none;
}
<div class="nav">
  <ul>
    <li><a href="HomePage.aspx">Home</a></li>
    <li><a href="MemesOverTheYears.aspx">Memes Over The Years</a></li>
    <li><a href="Profile.html">Profile</a></li>
    <li><a href="About.aspx">About</a></li>
  </ul>
</div>
<!-- partial:index.partial.html -->
<div class="wrapper">
  <div class="container">
    <form id="form" class="form">
      <h2>Register With Us</h2>
      <div class="form-control">
        <label for="username">Username</label>
        <input type="text" id="username" placeholder="Enter Username">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="email">Email</label>
        <input type="text" id="email" placeholder="Enter email">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter password">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="password2">Confirm Password</label>
        <input type="password" id="password2" placeholder="Enter password again">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="gender">Gender</label> <br/>
        <select id="select">
          <option value="">Choose an option</option>
          <option value="Male">Male</option>
          <option value="female">Female</option>
          <option value="other">Other</option>
        </select>
        <small>Error Message</small>
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
</div>
<br /><br /><br /><br />
<span>Allready have an account?<a href="LogIn.aspx">Log In</a></span>

Can’t use chrome.runtime.getPackageDirectoryEntry in service work with the manifest v3 Chrome Extension standard

In manifest v2, I’ve used chrome.runtime.getPackageDirectoryEntry in the background script to list all the files within a subfolder that came with the extension to realize a specific design feature.

Now that Google is forcing me to migrate my extension from manifest v2 standard to manifest v3, I tried to do the same feature using the chrome.runtime.getPackageDirectoryEntry method but chrome would simply report this error:

Uncaught TypeError: chrome.runtime.getPackageDirectoryEntry is not a function

Can anyone help with this please?
or provide an alternative method for me to list all the filenames in a specified subfolder that would be shipped within the extension?

Find x-axis location to make an element move

I’m trying to make an element move backward on the X axis when the user presses “a”. However, I don’t know how to make it move farther every time the users presses that key :(. I’m new to JS

document.addEventListener("keypress", function (e) {
  let moveBy = 20;
  if (e.key === "a") {
    moveBy++;
    element.style.webkitTransform = `translateX(-${moveBy}px)`;
  }
}

Thank you!

Property * does not exist on type typeof * – static parent method

React Native, TypeScript code JS(non-TS) ORM module:

Parent BaseModel:

export default class BaseModel {
  static createTable() {
    ...
  }
  ...

My model of Animal does NOT redefine the method, it’s just defined as:

export default class Animal extends BaseModel { ...

Now this code await Animal.createTable(); actually works, but VSCode TypeScript checker gives following error in code:

Property 'createTable' does not exist on type 'typeof Animal'.ts(2339)

Is this the editor/checker issue? Or should the JS/TS code be defined somehow better?

CSS, JS Mousedown Getting Stuck During Drag Event

I’m working on the Etch-a-Sketch project from The Odin Project and I’m trying to make it so that my grid element (‘div’ in this case) changes color when my cursor is over it and while my mouse is down.

The code I have now works, however, there’s an issue with the mousedown portion where it will get intermittently stuck down. It seems to occur during an accidental drag event. I’ll notice a hand drag icon appear on my cursor and then all the other grid elements I mouseover will change color regardless of the mousedown condition.

Is there a way to turn off just the ‘draggable’ portion of a ‘div’ or is there another workaround I should be considering?

const grid = document.querySelector('.grid');
grid.addEventListener('mouseover', colorGrid);

let mousedown = false;
grid.addEventListener('mousedown', function(){
    mousedown = true;
});

grid.addEventListener('mouseup', function(){
    mousedown = false;
});


function colorGrid(e){
    if(mousedown) e.target.style.backgroundColor = markerColor.value;

}

.grid {
    display: grid;
    grid-template: repeat(var(--columns-row), 1fr) / repeat(var(--columns-row), 1fr);
    border: solid black 1px;
    width: 100%;
}

.grid div {
    border: 1px dotted lightgrey;
    background-color: var(--bgColor);
 }

 .grid div:hover {
    background-color: var(--color);
 }

Trying to use var as img src in JSX

I’m working on a react project and I have a situation where I need the src attribute for an img tag to be a variable. The relevant parts of the code look something like this:

import React, { useState, useEffect } from 'react';

// topics is already defined and is a js object

const allTopics = topics.map(topic => {
        url = topic['image_url'];
        return (
            <Grid item key={ topic['topic_id'] } item xs={4}>
                <div class='img-wrapper'>
                    <img id='topicpreview' src={url} alt="loading" />
                    <h1>{topic['topic_name']}</h1>
                </div>
            </Grid>
        );
    });

return (
<div style={{ padding: '0', margin: '0', border: '1px solid black', width: '100%', height: '60%', overflow: 'hidden', display: 'inline-block' }} text-align='center'>
                <Grid container>
                    {allTopics}
                </Grid>
            </div>
    );

The image path exists and points to a valid file and I’ve console logged the url to make
sure it’s the same path. However, it doesn’t find the image and ends up printing the “Loading” alternate text instead. I’m not sure what’s going wrong, so any help would be appreciated!

javascript how to get the web page get Session variable

I’m trying to a Session variable in javascript.

I have tried a number of post suggestions without success unfortinately.

I see this example all over the place.

    var userName = '<%= Session["UserName"] %>'

However that is not working, at least for me. What I am trying to do is as below.

    var qrdataString = "<qr-code data=" + "XL" + ' <%= Session["style"] %>'  + "></qr-code>";
    document.getElementById("styleqr").innerHTML = qrdataString; 

Using Single quotes where they appear above just returns the string as

    <%=Session["xUID"]%>   in the alert that I use to show me the returned value

Using Double quotes give me either – unexpected token: string literal – or unexpected token identifier.

Thanks

Method Tracers for New Relic in Nodejs

As the new relic docs are not very rich in providing examples. I wondered how I can use Method Tracers in Node Js for New Relic ?.
I want to make a common method that can be used for this purpose.

For example

ApplyMethodTracer (className, MethodNameOfClass) this method should apply method tracer for the given method of the given class.