How to get the value of year and month separately using input type=”month” in PHP

How to get the value of year and month separately using input type=”month”.
I have this input type =”month” and when I displayed it , I got the value of ex “2022-05” and I wanted to store the “2022” to $year variable and “05” to $month variable.

I tried this date(“Y”, $selected_date) but have an error of “TypeError: date(): Argument #2 ($timestamp) must be of type ?int, string given in”

<input type="month" name="selected_date">

Form button refusing to execute javascript divide function

I am trying to attempt the following exercise from SAMS Teach Yourself Learn JavaScript in 21 Days;

“Look at Listing 7.1 and adapt it so that instead of using prompt boxes, the numbers
are entered using an XHTML form.”

Listing 7.1 is as follows;

<html>
<head>
<title>Precision of numbers</title>
<script type="text/javascript" language="javascript">
<!--
function Calculate(){
var n = 10.0 / 3.0;
document.write("10.0 divided by 3.0 is " + n); 
}
-->
</script>
</head>
<body onload="Calculate()">
</body>
</html>

Here is my attempt, but I am just going to put the JS script and form snippet;

<script type="text/javascript" language="javascript">
<!--
function SetFocus(){
document.Precision.FirstInput.focus();
}
function Calculate(){
var num1 = parseInt(document.getElementById('FirstInput').value);
var num2 = parseInt(document.getElementById('SecondInput').value); 
if (isNaN(num1) || isNaN(num2){
alert("You made an invalid entry. Please start again.");
document.SimpleForm.reset();
SetFocus();
}
else{
var result document.getElementById('result').value = num1 / num2;
}
}
-->
</script>

And the html form

<form name="Precision">
<p>
<strong>Enter first number:</strong>
<input type="text" name="FirstInput" id="FirstInput" />
</p>
<p>
<strong>Enter second number:</strong>
<input type="text" name="SecondInput" id="SecondInput" />
</p>
<p>
<strong>The answer is:</strong>
<input type="text" name="result" id="result" />
</p>
<p>
<button onclick="Calculate()">Click here to calculate</button>
</p>
</form>

My problem is the button is not executing the function and I would like to know why.

Convert band scale into time scale in D3

I created a bar chart using “bandscale” on x axis. I load my data from csv, where one column contains dates like “Jan-21” which means January 2021. I recently read that D3 provides time scale which serves for purposes of displaying dates. But I cant get a hang of how to configure it to work in my example. My current chart looks like this:
enter image description here

Here is my code:

const width = 620
const height = 280

const svg = d3.select(".canvas")
    .append('svg')
    .attr('viewBox', `0 0 ${width} ${height}`)
    .attr('preserveAspectRatio','xMinYMin')



const margin = {top:20, bottom:50, left: 20, right: 50}
const graphWidth = width - margin.left - margin.right
const graphHeight = height - margin.bottom - margin.top

const graph = svg.append('g')
    .attr('width', graphWidth)
    .attr('height', graphHeight)
    .attr('transform', `translate(${margin.left},${margin.top})`)

const xAxisGroup = graph.append('g')
    .attr('transform', `translate(0, ${graphHeight})`)

const yAxisGroup = graph.append('g')

d3.csv('./SixContinentFirst.csv').then(data => {
    africaData = data.map(obj => {
        return {infected: +(obj.Africa || '0'), date: obj.Dates}
    })

    const y = d3.scaleLinear()
        .domain([0, d3.max(africaData, data => data.infected)])
        .range([graphHeight,0])

    const x = d3.scaleBand()
        .domain(africaData.map(item => item.date))
        .range([0,graphWidth])
        .paddingInner(0.1)
        .paddingOuter(0.1)


    const rects = graph.selectAll('rect')
        .data(africaData)
        .enter()
        .append("g")
        .attr("class", "rect-container")


    // foreground rect
    rects.append('rect')
        .attr('width', x.bandwidth)
        .attr('height', d => graphHeight - y(d.infected))
        .attr('fill', 'orange')
        .attr('id', (d, i) => `bar_${d.date}`)
        .attr('class', "foreground-rect")
        .attr('x', (d) => x(d.date))
        .attr('y', d => y(d.infected))
        .attr('rx', 8)
        .attr('ry', 8)
        .attr('pointer-events', 'none')


    graph.append('rect')
        .style('fill', 'none')
        .style("pointer-events", "all")
        .attr('width', graphWidth)
        .attr('height', graphHeight)
        .on('mousemove',function(e){

        })
        .on('mouseout', function () {
            d3.select('.info-card').remove()
        })

    const xAxis = d3.axisBottom(x)
        .tickFormat((d,i) => i % 6 === 0 ? d : '')


    let formatter = Intl.NumberFormat('en', { notation: 'compact' });

    const yAxis = d3.axisRight(y)
        .ticks(3)
        .tickFormat(d => formatter.format(+d))


    xAxisGroup.call(xAxis)

    yAxisGroup.call(yAxis)
        .attr('transform', `translate(${graphWidth}, 0)`)
        .call(g => g.select('.domain').remove())
        .call(g => g.selectAll('line').remove())
        .selectAll('text')
        .attr("font-size", "10")

    xAxisGroup
        .call(g => g.select('.domain').remove())
        .call(g => g.selectAll('line').remove())
        .selectAll('text')
        .attr("font-size", "10")

})

Why is my font size not adjusting with vanilla js?

I have this little code here and by the console logs I can see it is apparently changed but on the display it is not changing. What could be going wrong ?

JS vanilla below

const gameItem = document.querySelectorAll('.game-item');
const gameItemS = document.querySelector('.game-item');

document.addEventListener('DOMContentLoaded', () => {
    titleSize(gameItem);
});

const titleSize = (gameItem) => {
    [...gameItem].forEach((title) => {
        let textSize = window
            .getComputedStyle(title, null)
            .getPropertyValue('font-size');
        let gameTitle = title.innerText;
        // console.log(gameTitle, gameTitle.length, textSize);
        if (gameTitle.length > 7) {
            textSize = '5px';
            console.log(
                'The font on this was changed: ' + gameTitle,
                gameTitle.length,
                textSize
            );
        }
    });
};

html below

            <section class="games">
                <h1>Games</h1>
                <ol class="container">
                    <li class="game-item">Halo<img src="" /></li>
                    <li class="game-item">Pokemon<img src="" /></li>
                    <li class="game-item">
                        Animal Crossing<img src="" />
                    </li>
                    <li class="game-item">Genshin Impact<img src="" /></li>
                    <li class="game-item">Skyrim<img src="" /></li>
                </ol>
            </section>

Azure Durable Functions – Microsoft.WindowsAzure.Storage: Settings must be of the form “name=value”

I develop my Function App in JavaScript using Azure Portal. Everything was working correctly when I was creating only http triggered functions, but after trying to create a durable function, I receive multiple errors.

In the Overview of my Function App, I see Microsoft.WindowsAzure.Storage: Settings must be of the form "name=value".

When I go to Functions, I see a warning that reads Azure Functions runtime is unreachable.

When I try to Create a function, I now see only HTTP trigger and timer trigger options and a warning In order to see the entire list of available function templates, you must set up extension bundles for your app.

It seems as if something is wrong with the configuration of both storage and binding extensions. My storage related application settings are:

AzureWebJobsStorage = *{storage name}*
WEBSITE_CONTENTAZUREFILECONNECTIONSTRING = DefaultEndpointsProtocol=https;AccountName=*{storage name}*;AccountKey=*{account key}*;EndpointSuffix=core.windows.net
WEBSITE_CONTENTSHARE = *{function app name with random code as found in storage account's file shares}*

My host.json:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}

I tried developing the function app in VS Code but had issues even with HTTP trigger functions and had to install binding extensions explicitly.

JS: prevent reseting of form fields after adding new form

I have below code where I add new form after clicking button. If I put some values into the fields everything is reseted. I would like to prevent that.
I tried e.preventDefault() and return false but it’s not working as I would like to.
Additionally after clicking ‘add button’ I am taking data from json file.
Please see my code here. Any help will be appreciated.

// add new product to the list

const newLocal = document.querySelector('.add-product-button');
const addNewProduct = newLocal;
const listProduct = document.querySelector('.products-list');
const changeVisibility = document.getElementById('change-visibility');
let productCounter = 1;

addNewProduct.addEventListener('click', e => {
    e.preventDefault();
    productCounter++;
    generateTemplate();
    changeVisibility.style.display = 'block';
});

const generateTemplate = (e) => {
    const html = `
        <li>
            <div class="first-product-indicator">
                <div class="first-product-border-line"></div>
                <div class="product-number">${productCounter}</div>
            </div>
            
            <form action="" method="get" class="form-product">
                    <select name="product-type" id="product-type" class="" required>
                        <option value="" disabled selected hidden>Typ Produktu</option>
                        <option value="produkt" >PRODUKT GOTOWY</option>
                        <option value="materiały" >MATERIAŁY POMOCNICZE</option>
                        <option value="surowce" >SUROWCE</option>
                    </select>
                    <div class="product-container">
                        <select name="product" id="product" class="option-field product-list" required>
                            <option value="" disabled selected hidden>Produkt</option>
                        </select>
                        <i class="fas fa-plus-circle add-product"></i>
                    </div>
                    <div class="form-price">
                        <input type="number" id="quantity" name="quantity" placeholder="Ilość">
                        <input type="number" id="netto" name="netto" placeholder="Netto">
                        <input type="number" id="brutto" name="brutto" placeholder="Brutto">
                    </div>
                    <div class="form-total-price">
                        <input type="number" id="netto-total" name="netto-total" placeholder="Wartość netto">
                        <input type="number" id="brutto-total" name="brutto-total" placeholder="Wartość brutto">
                    </div>
                </form>
        </li>
    `;

    listProduct.innerHTML += html;

    // populate product select field with values from json file (finished_good.json)

    let newProductElement = document.querySelector('.products-list').lastElementChild;
    let dropdownProductAdd = newProductElement.querySelector('.product-list');
    dropdownProductAdd.length = 0;

    let defaultOptionProductAdd = document.createElement('option');
    defaultOptionProductAdd.text = 'Produkt';

    dropdownProductAdd.add(defaultOptionProductAdd);
    dropdownProductAdd.removeIndex = 0;

    const urlProductAdd = 'finished_good.json';

    const requestProductAdd = new XMLHttpRequest();
    requestProductAdd.open('GET', urlProductAdd, true);

    requestProductAdd.onload = function() {
    if (requestProductAdd.status === 200) {
        const dataProductAdd = JSON.parse(requestProductAdd.responseText);
        let optionProductAdd;
        for (let i = 0; i < dataProductAdd.length; i++) {
            optionProductAdd = document.createElement('option');
            optionProductAdd.text = dataProductAdd[i].name;
        dropdownProductAdd.add(optionProductAdd);
        }
    } else {
        // Reached the server, but it returned an error
    }   
    }

    requestProductAdd.onerror = function() {
    console.error('An error occurred fetching the JSON from ' + urlProductAdd);
    };

    requestProductAdd.send();

    e.preventDefault();

};

JS async function returning undefined although calling it inside an asynchronous function

I am using nodeJs Express and I have an async function which is used in another function.

here is my code:

/* get user info */
const getUserInfo = async (req) => {
    let userID = req.cookies.userId;
    if(!userID) return null;
    await connection.query('SELECT * FROM users WHERE id = ' + userID,
        function (err, rows, fields) {
            if (err) throw err
            // if user not found
            if (rows.length === 0) {
                return null;
            }
            // if user found
            else {
                return rows[0];
            }
        });
}
/* display dashboard page */
router.get("/", async function (req, res, next) {
    let userInfo = await getUserInfo(req);

    console.log(userInfo) // It's result is undefined


    if (userInfo) {
        res.render('dashboard/profile', {
            fullName: userInfo.fname + " " + userInfo.lname,
            email: userInfo.email,
            phone: userInfo.phone,
        });
    }
    else {
        res.render('authentication/register', {
            title: 'ثبت نام',
        });
    }

});

how to resolved this problem? I need userInfo retun me some data.

Iterating my mongo collections to send mutiple emails to multiple recipient

I’m working with an aggregation to find matches so whenever two people select the same location, time and date it generates a new collection that is pushed ($out) to a matches document. I’ve generated 2 matches for testing and the structure of the document looks like this.

console.log(email)

[
  { Data: [ [Object], [Object] ], Total: 2 },
  { Data: [ [Object], [Object] ], Total: 2 }
]

Now my intention is to send a email to each person in each match with the data of the other person, I used Nodemailer in the next way.

router.get('/email', async (req, res) => {
    const email = await Match.find()

    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user:'[email protected]', 
            pass: 'xxxx'  
        }
    });

    let mail_option = {
        from: 'Test',
        to: email[0]._doc.Data[0].Email,
        subject: 'This is a test',
        html: ` ${email[0]._doc.Data[1].Name} ${email[0]._doc.Data[1].Surname}. <br/><br/>
        ${email[0]._doc.Data[1].Email} `
    };

    let mail_option1 = {
        from: 'Test',
        to: email[0]._doc.Data[1].Email,
        subject: 'This is a test',
        html: `${email[0]._doc.Data[0].Nombre} ${email[0]._doc.Data[0].Apellido}.  <br/><br/>
        ${email[0]._doc.Data[0].Email}`
    };

    transporter.sendMail(mail_option,  (err, info) =>{
        if(err){
            console.log(err);
        }else{
            console.log('Works')
        }
    });

    transporter.sendMail(mail_option1,  (err, info) =>{
        if(err){
            console.log(err);
        }else{
            console.log('Also works')
        }
    });

    res.json('Sent');

});

I got it working sending emails nexr I’m trying to get it to send the emails to everyone in the matchs collections. I’m trying with the next example but it doesnt send the email, looks like it doesnt even enter the for as it doesnt give any console log and go straight to the res.json:

router.get("/email", async (req, res) => {
    const email = await Match.find();
    let data = email[0];
    for (data; data < email.length; data++) {
        let transporter = nodemailer.createTransport({
            service: "gmail",
            auth: {
                user: "[email protected]",
                pass: "xxxx",
            },
        });

        let mail_option = {
            from: "Test",
            to: data._doc.Data[0].Email,
            subject: "This is a test",
            html: ` ${data._doc.Data[1].Name} ${data._doc.Data[1].Surname}. <br/><br/>
            ${data._doc.Data[1].Email} `,
        };

        transporter.sendMail(mail_option, (err, info) => {
            if (err) {
                console.log(err);
            } else {
                console.log("Works");
            }
        });
        res.json("Sent");
    }
});

Any help would be deeply appreciate

How can I use Drawer Navigation in TabScrren in React native?

I have a MainPage component, and in the MainPage component, there are PostList, Post, and Explain components as Stack.Screen. and i made Home component

this is my code

    const home = () => {
      return (
        <View>
        <Text>home</Text>
    </View>
        )
    }

    const MainPage = () => {
      return (
        <Stack.Navigator>
          <Stack.Screen
            name="PostList"
            component={PostList}
            options={{headerShown: false}}
          />
          <Stack.Screen
            name="Post"
            component={Post}
            options={{headerShown: false}}
          />
          <Stack.Screen
            name="Explain"
            component={Explain}
            options={{
              headerShown: false,
            }}
          />
        </Stack.Navigator>
      );
    };

And MainPage is wrapped with Tab.screen.

    <Tab.Navigator>
    <Tab.Screen
      name="MainPage"
      component={MainPage}
      options={{
        headerShown: false,
        tabBarStyle: {display: 'none'},

        tabBarIcon: ({color}) => (
          <FontAwesome5 name="list" size={20} style={{color}} />
        ),
        tabBarActiveTintColor: 'blue',
      }}
    />
    </Tab.Navigator>

I want to navigate to Home component using drawer navigation in MainPage component inside Tab.Screen.

so i tried like this code

    <Drawer.Navigator initialRouteName="Home">
    <Tab.Navigator>
    <Tab.Screen
      name="MainPage"
      component={MainPage}
      options={{
        headerShown: false,
      }}
    />
    </Tab.Navigator>
    </Drawer.Navigator>

but it doesn’t work. How can i fix my code?

Is there a specific parameter to pass when updating api with PUT in Javascript?

I am trying to update an API, I have gone through many documents and watched many videos; However, I keep on getting 404 errors. I first stored the API data on an object through a get request, amend it, and then tried to update the API through the updated object by sending PUT request, but I am getting a 404 error. Below is the code.

let url = 'https://www.vinted.co.uk/api/v2/users/83227138/items?page=1&per_page=20&order=relevance&currency=GBP';
    let forUpdate
    //Return array of feeback objects
    const ch = await fetch(url)
    .then(res => {
        console.log(res.status);
        return res.json()
    })
    .then(data => { 
        forUpdate = data;
        console.log("forUpdate = ", forUpdate);
        console.log("forupdate item 1 = ", forUpdate.items[0].title)
        console.log(data)
        
        console.log("Length of items = ", data.items.length)

        for(let i = 0; i < data.items.length; i++){
            console.log("ID is: ", data.items[i].id);
            data.items[i].is_favourite = true;
        }
        console.log("after is_fav true = ", data);
        
        const { feedback } = data;
    })
    .catch(error => console.log('ERROR'))

    forUpdate.items[0].title = 'changed';

    let updateData = {
        method: 'PUT',
        headers: {
            'Accept':'application/json',
            'Content-Type':'application/json'  
        },
        body: JSON.stringify(
            forUpdate.items[0].title
        )
    }

    fetch(url, updateData)
    .then(response => console.log(response.status)); 

Office Add-in: get 404 when accessing an ApiController

I am learning to create a ppt add-in according to the official tutorial. I followed the steps in the Insert an Image section, but found the add-in did not work properly. When I clicked the “Insert Image” button, the add-in visited /api/Photo/ via ajax, but the state code was always 404.

This is the function called when I clicked the button:

function insertImage() {
    // Get image from from web service (as a Base64 encoded string).
    $.ajax({
        url: "/api/Photo/", success: function (result) {
            insertImageFromBase64String(result);
        }, error: function (xhr, status, error) { // always 404
            showNotification("Error", "Oops, something went wrong.");
        }
    });
}

And this is the ApiController:

namespace HelloWorldWeb.Controllers
{
    public class PhotoController : ApiController
    {
        public string Get()
        {
            string url = "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1";

            // Create the request.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            using (Stream responseStream = response.GetResponseStream())
            {
                // Process the result.
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                string result = reader.ReadToEnd();

                // Parse the xml response and to get the URL.
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(result);
                string photoURL = "http://bing.com" + doc.SelectSingleNode("/images/image/url").InnerText;

                // Fetch the photo and return it as a Base64 encoded string.
                return getPhotoFromURL(photoURL);
            }
        }

        private string getPhotoFromURL(string imageURL)
        {
            var webClient = new WebClient();
            byte[] imageBytes = webClient.DownloadData(imageURL);
            return Convert.ToBase64String(imageBytes);
        }
    }
}

I wonder how can I config the routers. It has not been discussed in the tutorial and I am confused whether it is configured automatically.

Thank you!