What is the shorthand syntax for callback functions generating a new interface instance?

Given the following TypeScript example to construct a new object with default values

interface MyInterface {
  foo: boolean;
};

const generateMyInterfaceWithDefaults: () => MyInterface = () => { foo: false };

The syntax seems to be invalid because the function needs to have a nested return statement like so

const generateMyInterfaceWithDefaults = () => { return { foo: false }; }; // returns function that returns a new interface of MyInterface

I’m wondering if my first approach can be fixed because primitve objects seem to work fine

const generateFalsy = () => false; // returns boolean

So do I have to use the return statement for non primitive types or is it possible to have something like ( … pseudo code … )

const generateMyInterfaceWithDefaults = () => MyInterface.of({ foo: false }); // fixes the first approach

Issue with axios call, When trying to fetch api with name as parameter in Vuejs?

HelloWorld.vue

<template>
  <div>
    <div v-for="name in names" :key="name.PipelineID">
      <div>status: {{ name.OverallStatus }}</div>
    </div>
    <div v-for="item in items" :key="item.SourceDatabaseName">
      {{ item.DBIcon }}
    </div>
  </div>
</template>

<script>
import { tabsandcontent } from "./tabsandcontent";
import { tabs } from "./tabs";
export default {
  name: "HelloWorld",
  components: {},
  data() {
    return {
      names: [],
      items: [],
    };
  },
  mounted() {
    tabsandcontent().then((r) => {
      this.names = r.data;
    });

    tabs().then((r) => {
      this.items = r.data;
    });
  },
};
</script>

tabsandcontent.js

import axios from "axios";

export const tabsandcontent = (name) =>
  axios.get(
    "http://35.162.202.237:3000/pip?s_name=" + name **(api call edited for safety purpose, exact api call in codesandbox)**
  );

code:-
https://codesandbox.io/s/angry-euler-xt2wqh?file=/src/components/tabsandcontent.js

in tabsandcontent.js file, i have api call where i need to pass the name as query params at the end of the api url.
Then only i can able to call the api and get the response.

I tried writting above code logic, But it gives me like undefined when i pass name as params at the url end.

How to call api, that which has name as the query params?

In developer tools inside network tab. i am getting as

http://35.162.202.237:3000/pip?s_name=**undefined**

SlashCommands not showing up

I just finished my bot and wanted to invite it to another server to test it out.

However, when I typed / no commands showed up.

When I invited the bot I enabled application.commands so I can use the slashcommands but it still did not work. My bot also has a global slashcommand handler so it should normally work right?

I don’t know if the handler code is needed but I’ll still add it here in case you do need it:

const { Perms } = require('../Validation/Permissions');
const { Client } = require('discord.js');

/**
 * @param {Client} client
 */

module.exports = async (client, PG, Ascii) => {
    const Table = new Ascii("Command Loaded");

    CommandsArray = [];

    (await PG(`${process.cwd()}/Commands/*/*.js`)).map(async (file) => {
        const command = require(file);

        if(!command.name)
        return Table.addRow(file.split("/")[7], "⛔ FAILED", "Missing a name.")

        if(command.type !== "USER" && !command.description)
        return Table.addRow(command.name, "⛔ FAILED", "Missing a description.")

        if(command.permission){
            if(Perms.includes(command.permission))
            command.defaultPermission = false;
            else
            return Table.addRow(command.name, "⛔ FAILED", "Permission is invalid.")
        }

        client.commands.set(command.name, command);
        CommandsArray.push(command);

        await Table.addRow(command.name, "✅ SUCCESSFUL");
    });

    

    console.log(Table.toString());

    // PERMISSIONS CHECK //

    client.on("ready", async () =>{
        client.guilds.cache.forEach((g) => {
            g.commands.set(CommandsArray).then(async (command) =>{
                const Roles = (commandName) => {
                    const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission;
                if(!cmdPerms) return null;
    
                return g.roles.cache.filter((r) => r.permissions.has(cmdPerms) && !r.managed).first(10);
                }
    
                const fullPermissions = command.reduce((accumulator, r) =>{ 
                    const roles = Roles(r.name);
                    if(!roles) return accumulator;
    
                    const permissions = roles.reduce((a, r) =>{
                        return [...a, {id: r.id, type: "ROLE", permission:true}]
                    }, []);
    
                    return [...accumulator, {id: r.id, permissions}]
                }, []);
    
                await g.commands.permissions.set({ fullPermissions });
    
            });
        })
        });
}

Problems making a button disabled/change color depending on the input. Any advice?

I’ve been tying to work on this code, but can’t find the mistakes (and I’m guessing there are many of them) I’m making.
So far I tried it using querySelector and getElementById and I’ve been rewriting the functions quite a few times, but no luck so far. Any advice?
Thanks in advance.

const btnNext = document.querySelector(".btn-next");
const logIn = document.querySelector(".btn-login");
const inputMail = document.querySelector(".input-mail");
const inputPassword = document.querySelector(".input-password");

function btnLogIn() {
    if (inputMail.value.length && inputPassword.value.length == 0) {
        btnNext.disabled == true;
    } else {
        btnNext.disabled == false;
    }
}
function changeColor() {
    if (document.getElementById("input-mail") !== "") {
        document.getElementById("btn-next").style.background = "gray";
    } else {
        document.getElementById("btn-next").style.background = "blue";  
    }
}
body{
    margin: auto;
    width:50%;
    padding: 0;
    background-color: #eeeeee;
}
form{
    display: flex;
    flex-direction: column;
}
.btn-next{
    margin-top: .5rem;
    background-color: #949aa6;
    color: white;
    border: none;
    border-radius: 2px;
    padding: 18px 119px 18px 119px; 
    font-size: .8rem;
    font-weight: 600;
}
input{
    width: 16.5rem;
    height: 2rem;
    box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
    }
<body>
     <form>
        <p>Email</p>
        <input type="email" placeholder="Email" class="input-mail" id="input-mail">
        <p>Password</p>
        <input type="password" placeholder="Password" class="input-password" id="input-password"><br>
    </form>    
        <button class="btn-next" id="btn-next">NEXT</button> 
</body>

ID match with differen fields using if condtion in JS?

I Have two objects booking and History. I have to check booking userId matches with History userId or History CustomerID

If booking userId matches with any of these two fields(History userId or History CustomerID) we should return “ID matched” in the console.

If booking userId does not match with any of these two fields(History userId or History CustomerID). we should return “ID not matched with booking”.

Below is my code .its working as expected but is this a better approach? or i can do this in some other way

Please suggest

var booking = {"userId":"1233","CustomerID":null,"username":"av"};
var History = {"userId":"123","CustomerID":null,"username":"av"};

var a = booking.userId != History.userId;
var b = booking.userId == History.CustomerID;
var c = booking.userId == History.userId;
var d = booking.userId != History.CustomerID;
console.log(a)
console.log(b)
console.log(c)
console.log(d)

if( a && !b || c && !d)
{
console.log("ID not mathced with booking ")
}else{
console.log("ID mathced")
}

Uncaught ReferenceError: removeFiled is not defined

I am getting Function Reference undefined error while i add new Dynamic Fields. Note that I have split my bladed files into different parts or sections. but the function is defined in the same file. So basically i have a different- different part of files to make code easier to read. but the problem is when i write a function in a different file and mention that function name in the different file where all files part being included in one file. after that, i am getting errors many times like this `foo is not defined. in other words, all part of the files is included in one file. let’s check my code.

it is a script file in blade: script.blade.php

 <script> 
   var count_custom_field =0;
   $(document).on('click', '.new-row-weekly', function () {
    count_custom_field++;
    $(' <div class="clearfix field_'+count_custom_field+'" >&nbsp;</div>  ' +
        ' <div class="row field_'+count_custom_field+'">  <div class="col-md-4">  ' +
        ' <label class="text-label"> Repeat Day </label> {{ Form::select("repet_days[]",
         $days,null,array("class" => "form-control")) }} </div>  '+
        '  <div class="col-md-4">  ' +
        '  <label class="text-label"> Repeat Return Halt Duration(Minutes) </label>{!! Form::text("repet_times[]", null,
        array("class" => "form-control  repet_times" , "placeholder"=>"Ex. 120" ) ) !!} 
    </div>'+
        '  <div class="btn btn-danger"  onClick="removeCustFiled(213123)"  style="margin: 30px 0 0 0; height: 40px; padding-bottom: 18px;" > <i class="fa fa-close"></i> </div> </div> '+
        '</div>' ).appendTo('#weekly').hide().fadeIn(280);
   }

    function removeCustFiled( ref ) { console.log(ref);
       /* $('.'+ref+'').remove();
        if( Number( count_custom_field ) > 0)
        {
            count_custom_field--;
        }*/
    }
  </script>

UI blade file.
enter image description here

enter image description here

Please tell me what is reason i am getting this error.

Creating custom React hook to store File(s) (push/ purge), doesn’t render component where it is used

I’ve a create-react-app project with custom hook like this:

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const useStagedUploads = () => {
    const [items, setItems] = useState<CustomFileWithPath[]>([]);
    const setUploadItems = (files: CustomFileWithPath[]) => setItems(files);

    return [items, setUploadItems] as const;
};

export default useStagedUploads;

I use it to push files to when browsed (using react-dropzone). Now in one of my other component, I use it like below *:

const [ items, setUploadItems ] = useStagedUploads();

    useEffect(() => {
        if (items) {
            onDrop(items);
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            items.map((i) =>
                // eslint-disable-next-line @typescript-eslint/no-unsafe-return
                setUploadItems(
                    items.filter(
                        (items: CustomFileWithPath) => items.path !== i.path
                    )
                )
            );
        }
    }, [items]);

Now when upload is made like so (react-dropzone):

const { getInputProps, open, acceptedFiles } = useDropzone({
        noClick: true,
        noKeyboard: true,
    });

    useEffect(() => {
        if (acceptedFiles) {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            acceptedFiles.map((el) => stageUpload(el));
        }
    }, [acceptedFiles]);

… The former component (*) doesn’t re-render (tried console, debugger, etc.) ie I don’t receive items its empty “[]” array. Also doesn’t react useEffect body.

Gave a try using simple primitive type it does re-render. Is it so that files couldn’t be stored in react custom hooks or prevents re-render/ any serialization problem?

Thanks.

Publish app in Google play store when migrating from expo to bare react native

I had developed an app using Expo and published it in Google Play Store. It was running fine till now. But now I have a requirement to add a payment gateway. As of now, only stripe is available in expo. I wanted to add Razorpay Payment Gateway in the app.

So, I tried to eject the app and worked on it. But there were certain issues while building apk file. Then I tried to create a bare react native app from scratch and eventually I completed the work.

Now I want to publish the app in google app store.

If I create new keystore credential and upload it in Play store, will it work or I will have to use same keystore credentials that i used using expo.

Execute code without importing anything from .ts file [duplicate]

I have a file named listener.ts which has the following code.

import eventEmitter from './event';

eventEmitter.on('error', () => true); // TODO: Include calling of Bugsnag on callback.

I want to execute code of listener.ts file on starting up in main.ts file, without importing anything.

How can i achieve such functionality in Typescript ?.

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>