What will be value of max-content?

Is there any way by which one can actually calculate how much will be max-content or min-content or fit-content and so on.

Something like

.btn:hover {
    width: calc(max-content);
}

I tried (max-content + 0px) but it didn’t worked either. Need a pure CSS solution. Use of JavaScript should be last priority!

How to trigger the right mouse click event through JS?

I want to trigger the right mouse click event through JS.

Here is my test code:

            var obj = document.getElementById("testItem");
            var evObj = document.createEvent("MouseEvents",);
            evObj.initEvent('click', true, false);
            Object.defineProperty(evObj, "button", {
                value: 2,
                writable: false
            });
            Object.defineProperty(evObj, "buttons", {
                value: 2,
                writable: false
            });
            obj.dispatchEvent(evObj);

I tried lots of methods, but they didn’t work.

Anyone know how to solve it?

Thank you in advance.

Modal popup for Django DeleteView

I’m trying to have a modal popup asking for confirmation before deleting the object using DeleteView. So far, I’ve tried solutions from this thread using the following code.

views.py

class SessionCancelView(
    SuccessMessageMixin, LoginRequiredMixin, UserPassesTestMixin, DeleteView
):
    model = Session
    success_url = "/profile"
    success_message = "Session was cancelled successfully"
    # FIXME: success message not showing - eh maybe not necessary tho

    def test_func(self):
        session = self.get_object()
        if self.request.user == session.student:
            return True
        return False

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)

profile.html

<!-- Modal -->
<div class="modal fade" id="sessionDeleteModal" tabindex="-1" role="dialog" aria-labelledby="sessionDeleteModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Cancel Session</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Are you sure you want to cancel this session?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button class="btn btn-outline-danger" type="submit">Yes, Cancel</button>
                <form method="POST" action="{% url 'session-cancel' session.id %}">
                    {% csrf_token %}<input type="submit" value="DELETE">
                </form>
            </div>
        </div>
    </div>
</div>

.
.
.

{% for session in user_sessions %}
    {% if session.is_upcoming %}
    <div class="card bg-light mb-3" style="width: 18rem;">
        <div class="card-header">{{ session.date|date:"F d [l]" }}</div>
        <div class="card-body">
            <h5 class="card-title">{{ session.get_timeblock_display }}</h5>
            <h6 class="card-subtitle mb-2 text-muted">{{ session.weekday }}</h6>
            <p class="card-text">{{ session.helptype }}</p>
            <a class='btn btn-outline-secondary btn-small mt-1 mb-1' href="{% url 'session-edit' session.id %}">Edit</a>
            <a class='btn btn-outline-danger btn-small mt-1 mb-1'
                href="{% url 'session-cancel' session.id %}">Cancel</a>
            <button type="button" class="btn btn-outline-danger btn-small mt-1 mb-1" data-toggle="modal"
                data-target="#sessionDeleteModal">
                Modal Cancel
            </button>
        </div>
    </div>
    {% endif %}
    {% endfor %}

urls.py

from django.urls import path
from . import views
from .views import (
    SessionListView,
    SessionDetailView,
    SessionCreateView,
    SessionEditView,
    SessionCancelView,
)

urlpatterns = [
    path("", views.home, name="scheduler-home"),
    path("about/", views.about, name="scheduler-about"),
    path("sessions/", SessionListView.as_view(), name="scheduler-sessions"),
    path("sessions/<int:pk>/", SessionDetailView.as_view(), name="session-detail"),
    path("sessions/new/", SessionCreateView.as_view(), name="session-create"),
    path("sessions/<int:pk>/edit", SessionEditView.as_view(), name="session-edit"),
    path(
        "sessions/<int:pk>/cancel", SessionCancelView.as_view(), name="session-cancel"
    ),
    path("issues/", views.report_issues, name="scheduler-issues"),
]

However, I’m getting the following error when loading profile.html page:

Exception Type: NoReverseMatch at /profile/
Exception Value: Reverse for 'session-cancel' with arguments '('',)' not found. 1 pattern(s) tried: ['sessions/(?P<pk>[0-9]+)/cancel$']

I am assuming this is happening because modal has no way of having session.id passed in, hence causing a NoReverseMatch error. Would appreciate if anyone could help point out what I did wrong!

Source tag didn’t update the src attribute

I tried to use useState to update the video background, but it seems not working.

Here is my code:

  const [bgChange, setbgChange] = useState(backgroundDay);

  const handleBackground = () => {
    bgChange === backgroundDay
      ? setbgChange(backgroundNight)
      : setbgChange(backgroundDay);
    console.log(bgChange);
  };

  return (
    <div className="container">
      <div className="-z-50 absolute">
        <video className="videoTag" autoPlay loop muted>
          <source src={bgChange} type="video/mp4" />
        </video>
      </div>
      <button onClick={handleBackground}>Change BG</button>
    </div>
  );

Why is my CSS stylesheet not working using NodeJS and Express?

I am using EJS and Express for an application I am doing just for fun.
In my application, I am utilizing partials from a folder called views/partials. My css stylesheet is located in a directory called public. I have included app.use(express.static(path.join(__dirname, 'public'))); in my express routes directory. And it is working on all other pages besides this one, (edit.ejs):

<%- include('partials/head') %>


<div id="updatecustomer">
    <h1>Update Customer Profile</h1>

    <form method="post" action="/<%=customer.id%>?_method=PATCH">
        <label for="firstname">First Name</label>
        <input type="text" name="firstName" id="firstname" placeholder="<%= customer.firstName %>">
        <label for="lastname">Last Name</label>
        <input type="text" name="lastName" id="lastname" placeholder="<%= customer.lastName %>">
        <label for="phonenumber">Phone Number</label>
        <input type="text" name="contactNumber" id="phonenumber" placeholder="<%= customer.contactNumber %>">
        <label for="address">Address</label>
        <input type="text" name="address" id="address" placeholder="<%= customer.address %>">
        <label for="city">City</label>
        <input type="text" name="city" id="city" placeholder="<%= customer.city %>">
        <label for="state">State</label>
        <input type="text" name="state" id="state" placeholder="<%= customer.state %>">
        <label for="zipcode">Zipcode</label>
        <input type="text" name="zipcode" id="zipcode" placeholder="<%= customer.zipcode %>">
        <button type="submit">Update Customer</button>
    </form>
</div>

A snippet from index.js of my get/patch request, (I’m not using a database, simply an array of objects.):

app.get('/:id/edit', (req, res) => {
    const { id } = req.params;
    const customer = customers.find(c => c.id === id)
    res.render('edit', { customer })
})

app.patch('/:id', (req, res) => {
    const { id } = req.params;
    const foundCustomer = customers.find(c => c.id === id);

    const customerFirstname = req.body.firstName;
    foundCustomer.firstName = customerFirstname;

    const customerLastname = req.body.lastName;
    foundCustomer.lastName = customerLastname;

    const customerAddress = req.body.address;
    foundCustomer.address = customerAddress;

    const customerCity = req.body.city;
    foundCustomer.city = customerCity;

    const customerState = req.body.state;
    foundCustomer.state = customerState;

    const customerZip = req.body.zipcode;
    foundCustomer.zip = customerZip;

    const customerContactNum = req.body.contactNumber;
    foundCustomer.contactNumber= customerContactNum;

    res.redirect('/');
})
        

I have tried adding the styles manually to the page, clearing my browser data, and spent hours looking up a solution and remained stumped on this issue. Any ideas?

Why does the default react app file not run with eslint enabled?

I have globally installed eslint via cmd and its also installed as an extension in vs code. After that I used the following command in the vs code terminal to initialize it:

npx eslint --init 

I used the Airbnb style guide option while setting it up.
But even running the default file that comes when you create a react app multiple errors are shown like this screenshot of errors.
I have just started learning React, and don’t know what other details might be needed to solve this issue.
Below is the App.js file code.

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return ( <
    div className = "App" >
    <
    header className = "App-header" >
    <
    img src = {
      logo
    }
    className = "App-logo"
    alt = "logo" / >
    <
    p >
    Edit < code > src / App.js < /code> and save to reload. <
    /p> <
    a className = "App-link"
    href = "https://reactjs.org"
    target = "_blank"
    rel = "noopener noreferrer" >
    Learn React <
    /a> <
    /header> <
    /div>
  );
}

export default App;

Edit:
Imported React module and added

 "react/jsx-filename-extension": [1, { "extensions": [".js", ".JSX"] }]

in rules of .eslinrc.json but

Line 7:5:  JSX not allowed in files with extension '.js'  react/jsx-filename-extension 

this error is still there, despite deleting and reinitializing eslint for my app.

Moving Average Line in Highcharts Scattered Chart

I am trying to implement a Moving Average line in a Highachart’s Scattered chart. The x Axis is a Date and y axis is days but when I try to calculate the Moving average its is referring to date with year 1970.

Here is js fiddle link for my code:
enter link description here

I also have code without moving Average and the link is enter link description here

Here is the Highchart code with Moving average I am using :

Highcharts.chart('container', {
chart: {
    type: 'scatter',
    zoomType: 'xy'
},
title: {
    text: 'Height Versus Weight of 507 Individuals by Gender'
},
subtitle: {
    text: 'Source: Heinz  2003'
},
xAxis: {
  title: {
    enabled: true,
    text: 'PR Creation'
  },
  startOnTick: true,
  endOnTick: true,
  showLastLabel: true,
  type: 'datetime',
  dateTimeLabelFormats: {
  second: '%Y-%m-%d<br/>%H:%M:%S',
  minute: '%Y-%m-%d<br/>%H:%M',
  hour: '%Y-%m-%d<br/>%H:%M',
  day: '%Y<br/>%m-%d',
  week: '%Y<br/>%m-%d',
  month: '%Y-%m',
  year: '%Y'
}
},
 yAxis: {
title: {
  text: 'duration'
},
type: 'datetime', //y-axis will be in milliseconds
dateTimeLabelFormats: {
minute: '%H:%M'
                      }
 },
legend: {
    layout: 'vertical',
    align: 'left',
    verticalAlign: 'top',
    x: 100,
    y: 70,
    floating: true,
    backgroundColor: Highcharts.defaultOptions.chart.backgroundColor,
    borderWidth: 1
},
plotOptions: {
    scatter: {
        marker: {
            radius: 5,
            states: {
                hover: {
                    enabled: true,
                    lineColor: 'rgb(100,100,100)'
                }
            }
        },
        states: {
            hover: {
                marker: {
                    enabled: false
                }
            }
        },
        tooltip: {
            headerFormat: '<b>{series.name}</b><br>',
            pointFormat: '{point.x}'
        }
    }
},
 
series: [{
    name: 'PR',
    color: 'rgba(223, 83, 83, .5)',
     data: [{x:st4,y:3},{x:st5,y:7},{x:st6,y:8},{x:st7,y:9},{x:st8,y:9},{x:st9,y:7},{x:st10,y:7},{x:st11,y:3},{x:st12,y:2}]

},
{
   name: 'PR',
    color: 'green',
     data: [{x:st,y:5},{x:st3,y:7},{x:st11,y:1}]
}]
}
 ,function() {
            var Highcharts = this;
            var series = Highcharts.series[0];
            var data = [];
            var period = 2;
            var sumForAverage = 0;
            var i;
            for(i=0;i<series.data.length;i++) {
                sumForAverage += series.data[i].y;
                if(i<period) {
                    data.push(null);
                } else {
                    sumForAverage -= series.data[i-period].y;
                    data.push([series.data[i].x, sumForAverage/period]);
                }
            }
            Highcharts.addSeries({
                name: 'Moving Average',
                data: data
            });
        });

Please suggest if you have an idea on calculating the moving average . I am trying to implement something similar to the cycle time widget in Azure Devops

Having trouble with this drill: Find the most expensive item name [duplicate]

I’m supposed to find the most expensive item with a function and return the .itemName. I’m struggling to find what’s wrong the example of the array is :

let items = [
  {
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }
]
function mostExpensiveItemName(items){
  let highestPrice = 0;
  let expensiveItem ;
  
  
  for(let i = 0 ; i < items.length; i++){
   if (items[i].price > highestPrice) 
    
 highestPrice = items[i].price ; 
    expensiveItem = items[i].itemName;
  }
  
  return expensiveItem;
}

im making a circle follow the cursor which is working fine but how do i add a smoother effect and avoid the circle going out of the page

I have made a circle that follows the cursor using jquery which works fine but i want to give it a smoother effect, i have tried using timeout but that wont work which is kinda obvious so is there any other way to achieve this ?

Also whenever the cursor is close to the border of the webpage or crosses it the circle also goes outside the webpage creating a scrollbar can this be avoided by any way ?

My code –

var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;
  let mouseMovementStoppedTimer;
  const mouseMovementStopped = function() {
  $("#circlecc").css({ opacity: 0});
 }  

  $(document).mousemove(function(e){
    
    $("#circlecc").css({opacity: 1}) 
    mouseX = e.clientX - 12;
    mouseY = e.clientY - 12;
    setTimeout(() => {
    $("#circlecc").css({left: mouseX +'px', top: mouseY +'px'});
    }, 50)
    clearTimeout(mouseMovementStoppedTimer);
    mouseMovementStoppedTimer = setTimeout(mouseMovementStopped, 120);
  });

My Website

Objects are not valid as a React child [object Promise]

I’m new using reactjs. First case I want to get a json data from fetch url, but that json need async await to show all data. I managed to solve that problem, but now I want to append data from json to react return render. and then i get error like this Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.. This is my code

  async function URL(url, id){
    return fetch(url+"/"+id)
    .then((response) => response.json())
    .then((responseJson) => {
        const myArrayresponse = responseJson.image.split("/");
        return "https://myurl.com/"+myArrayresponse[2]+"/"+myArrayresponse[3];
    })
    .catch((error) => {
       return "images/icon.png";
    });
  }

const posts = datas[0].map((mydata, i) => URL(mydata.uri, mydata.id).then(img => {
      return `<a href={"https://myurl.com/"+CONFIG.ADDRESS+"?a="+mydata.id} target="_blank" className="mybtn"><div className="title">{mydata.name} ({mydata.symbol} - {mydata.id})</div><img src={img} /></a>`;
      })
    );
    
return (
<ResponsiveWrapper flex={1} style={{ padding: 24 }} test>
   <s.Container flex={1} jc={"center"} ai={"center"}>
       {posts}
   </s.Container>
</ResponsiveWrapper>
)

const post is [object Promise], how to append const post to react return render without [object Promise]?

In React, can you use useState variable_1 as default value for another useState variable_2?

  1. Can you use useState variable_1 as default value for another useState variable_2, especially when variable_1 is being set by useEffect?

  2. Even simpler, can you use useState variable_1 as default value for another useState variable_2 (without the useEffect dependency)?

To elaborate, here’s an example

const [firstName, setFirstName] = useState("DEFAULT_NAME");
const [fullName, setFullName] = useState(firstName); //is doing this permissible?

useEffect(() => {
  setFirstName("REAL_NAME")
}, []);

console.log(fullName); // what would be printed here?

What would the value of fullName be? Would it be set to "DEFAULT_NAME" (signaling that it was set BEFORE the useEffect was called) or be set to "REAL_NAME" (signaling that it was set AFTER the useEffect was called)?

Alternative to OnClick for select tag

I have a javascript function that changes a dropdown menu’s options based on some radio buttons that have been selected. I originally had the radio buttons set to “Onclick” to run the function but as it is based on 2 different sets of radio buttons this does not work. I changed the OnClick to happen when the user selects the drop down however now you cannot select an actual option as it just resets the dropdown when a selection is made. Is there and alternative I can use?

Genotype <select name="dropdown" id="dropdown" onClick = "DROPDOWN(father);"></select>

Where am I going wrong in this PRNG generator algorithm in JavaScript?

So I started off with this as a base How to get this PRNG to generate numbers within the range? Now I modified it like so (sorry for the messy code):

// https://primes.utm.edu/curios/index.php?start=5&stop=5

const fs = require('fs')
const startParts = `mi
ma
mo
ne
nu
di
da
do
be
bu
ti
te
ta
to
tu
ki
ke
ka
ko
ku
si
sa
so
ze
zu
fi
fa
fo
ve
vu
xe
xu`.split(/n+/)
const endParts = `le
ru
mu
ne
du
be
te
tu
ke
ku
su
ze
fu
ve
xe
xu`.split(/n+/)
const parts = startParts.concat(endParts)
const pattern = new RegExp(parts.map(x => `${x}${x}${x}`).join('|'))

const fetch = (x, o) => {
  if (x >= o) {
    return x
  } else {
    const v = (x * x) % o
    return (x <= (o / 2n)) ? v : o - v
  }
}

const SIZES = {
  64: {
    fetch: 41223334444555556666667777777888888889999999997n,
    xor: 2030507011013017019023n,
    j: 272261127249452727280272961627319532734291n,
  },
  32: {
    fetch: 3132343537383103113163n,
    modulo: BigInt(Math.pow(32, 15)),
    xor: 541613713n, // possibly half the size or less, and prime.
    j: 975319753197531975319n // almost as big as the other.
  },
  // total: 68,719,476,736
  // total: (32 * 16) * (32 * 16) * (32 * 16) * 32 = 4,294,967,296
  14: {
    fetch: 3778888999n,
    modulo: BigInt(Math.pow(32 * 16, 3) * 32),
    xor: 54121n,
    j: 1012639687n,
    max: 14
  },
  12: {
    // 134,217,728
    fetch: 134095867n,
    modulo: BigInt(Math.pow(32 * 16, 3)),
    xor: 7333n,
    j: 118818811n,
    max: 12
  }
}

const SIZE = SIZES[12]

const fetchLarge = (x) => fetch(x, SIZE.fetch)

// the last number can be anything.
// MODIFIED THIS
const buildLarge = (x, o) => fetchLarge((fetchLarge(x) + o) % SIZE.modulo ^ SIZE.xor)
// )
function createArray(n, fn) {
  if (!n) return [0]
  let arr = []
  let i = 0
  while (n) {
    let mod = fn(i++)
    arr.push(Number(n % mod))
    n /= mod
  }
  return arr
}

let i = 1n
let matched = {}
let matchedI = 1
const write = () => {
  let maxSize = SIZE.max
  const x = buildLarge(i++, SIZE.j)
  let chunks = createArray(x, i => i % 2 === 0 ? 32n : 16n).map((x, i) => {
    if (i % 2 === 0) {
      return startParts[x]
    } else {
      return endParts[x]
    }
  }).join('')
  if (chunks.length < (maxSize - 2)) {
    chunks = `mimi${chunks}`
  } else if (chunks.length < (maxSize)) {
    chunks = `mi${chunks}`
  }
  if (chunks.match(pattern)) return write()
  if (matched[chunks]) throw new Error(chunks + ' ' + Object.keys(matched).length + ' ' + matched[chunks])
  matched[chunks] = matchedI++
  const chunked = chunk(chunks.split(''), 4).map(x => x.join('')).join(':')
  return chunked
}

const map = fs.readFileSync('tmp/taxon.txt', 'utf-8')
  .trim()
  .split(/n+/)
  .map(x => x.split(/t+/)[3])
  .reduce((m, x) => {
    let p = x.trim().split(/s+/).join(' ')
    if (p.match(/d/)) return m
    m[p.toLowerCase()] = true
    return m
  }, {})

const list = chunk(Object.keys(map).map(key => `${write()},${key}`).sort(), 5000)

list.forEach((l, i) => {
  fs.writeFileSync(`tmp/taxon/${i + 1}.csv`, l.join('n'))
})
fs.writeFileSync('tmp/code.csv', String(i))

function chunk (arr, len) {

  var chunks = [],
      i = 0,
      n = arr.length;

  while (i < n) {
    chunks.push(arr.slice(i, i += len));
  }

  return chunks;
}

The taxon.txt looks like this (I greatly truncated the taxon file).

It is throwing this duplicate error:

$ node tmp/taxon2
/Users/me/tmp/taxon2.js:135
  if (matched[chunks]) throw new Error(chunks + ' ' + Object.keys(matched).length + ' ' + matched[chunks])
                      ^

Error: mikukenekeku 56542 7490
    at write (/Users/me/tmp/taxon2.js:135:30)
    at /Users/me/tmp/taxon2.js:152:51
    at Array.map (<anonymous>)
    at Object.<anonymous> (/Users/me/tmp/taxon2.js:152:37)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:816:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

Why is it running into duplicates?

If I comment out these lines, it passes however:

  if (chunks.length < (maxSize - 2)) {
    chunks = `mimi${chunks}`
  } else if (chunks.length < (maxSize)) {
    chunks = `mi${chunks}`
  }

But, there is an error in that case too: the text of some of the lines/strings is not long enough. I basically tried padding it with the zero element, but for some reason it’s erroring now, any ideas?

Inside the write function I fetch the next pseudo-random number from the fancy mathematical sequencer at const x = buildLarge(i++, SIZE.j). Then I do createArray(x, i => i % 2 === 0 ? 32n : 16n) which either divides by 32 on even index or 16 on odd index, so the value can be fetched from the startParts or endParts arrays respectively.

I tried doing .reverse() after createArray, but that doesn’t seem to help.

I think it just has something to do with the padding but not sure yet.

Fetching data from JSON file returning nothing

I am building a solar system app and I want to have all of my planet’s info in a JSON file for easy access. The JSON file is in the following format

Planet-info.json, in the public folder of my React app

  "planets": [
        {
            "Name": "Mercury",
            "Description": "The smallest planet in our solar system and closest to the Sun—is only slightly larger than Earth's Moon. Mercury is the fastest planet, zipping around the Sun every 88 Earth days.",
            "Moons": 0,
            "Habititable": "false"
        },
        {
            "Name": "Venus",
            "Description": "is hot",
            "Moons": 0,
            "Habititable": "false"
        }
    ]

And I am fetching the data with the useEffect hook

 const [planetData, setPlanetData] = useState();
  useEffect(() => {
    const fetchData = () => {
      fetch("/planet-info.json").then((result) => {
        setPlanetData(result);
      });
    };
    fetchData();
    console.log(`planet data is ${planetData}`);
  }, []);

However when this code runs and the console.log statement runs it returns the line
planet data is
It does not say undefined, or even [Object object] it is simply blank and I am unable to troubleshoot from there.