Counting occurence of objects in array based on property javascript

I tried to count the occurrences of a property in an array of objects with array.reduce. I want to count the occurences of titre with the same theme.

reponses = [
 {
   "theme" : "theme1",
   "titre" : "NC",
   "question": "api/question/123"
 },
 {
   "theme" : "theme1",
   "titre" : "NR",
   "question": "api/question/124"
 },
 {
   "theme" : "theme2",
   "titre" : "NR",
   "question": "api/question/125"
 },
 {
   "theme" : "theme2",
   "titre" : "NR",
   "question": "api/question/126"
 },
 {
   "theme" : "theme2",
   "titre" : "NR",
   "question": "api/question/127"
 },
]

What I’ve tried :

let theme = reponses.reduce(function (r, a) {
   r[a.theme] = (r[a.theme] || 0) + 1;
   return r;
 }, {});

console.log(theme);

The result is :

{"theme1" : 2, "theme2" : 3}

but it’s not exactly what I want.

D3 graph width and height attributes don’t correspond to size in browser

I am trying to make my bar chart responsive using “resize” function. But for some reason size of my “g” element in svg on browser doesn’t correspond to size defined by it’s “width” and “height” attributes.
enter image description here

This leads me to believe that I did something wrong making “resize” function. If I had used for example “viewBox” on my svg element to get responsivness then again “height” and “width” attributes would not correspond:

enter image description here

Here is my code:

const aspect = 619 / 280

const svg = d3.select('.canvas')
    .append('svg')
    .style('display', 'block')
    .attr('width', 619)
    .attr('height', 280)

let x = d3.scaleBand().padding(0.1)
let y = d3.scaleLinear()


const margin = {top:50, bottom:50, left: 50, right: 50}

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

const xAxisGroup = graph.append('g')
const yAxisGroup = graph.append('g')


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

    x.domain(africaData.map(item => item.date));
    y.domain([0, d3.max(africaData, function (d) { return d.infected; })]);

    const size = d3.select('.canvas').node().getBoundingClientRect()

    resize(size.width, size.height)

})

function resize(width, height){
    svg.attr("width", width);
    svg.attr("height",  width / aspect);
    
    const graphWidth = width - margin.left - margin.right
    const graphHeight = height - margin.top - margin.bottom
    
    graph.attr('width', graphWidth)
        .attr('height', graphHeight)

    xAxisGroup.attr('transform', `translate(0, ${graphHeight})`) // MOVE X AXIS TO BOTTOM

    x.range([0,graphWidth])
    y.range([graphHeight,0])


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

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

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

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

    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")

        const rects = graph.selectAll('rect')
            .data(africaData)
            .join(
                function (enter) {
                   return  enter.append('g')
                       .attr('class', "rect-container")
                       .append('rect')
                       .attr('width', x.bandwidth)
                       .attr('height', d => graphHeight)
                       .attr('fill', 'none')
                       .attr('x', (d) => x(d.date))
                       .attr('y', d => 0)
                       .attr('pointer-events', 'all')
                       .on('mouseover', function(d, i) {
                           console.log("Mouse Over")
                       })
                       .on('mouseout', function(d, i) {
                           console.log("Mouse Out")
                       })
                       .select(function () {
                           return this.parentElement
                       })
                       .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', 'all')
                        .on('mouseover', function(d, i) {
                            console.log("Mouse Over")
                        })
                        .on('mouseout', function(d, i) {
                            console.log("Mouse Out")
                        })
                },
                function (update) {
                  return  update.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', 'all')
                        .on('mouseover', function(d, i) {
                            console.log("Mouse Over")
                        })
                        .on('mouseout', function(d, i) {
                            console.log("Mouse Out")
                        })
                },

                function (exit) {
                   return exit.remove()
                }
            )

}

const myObserver = new ResizeObserver(entries => {
    entries.forEach(entry => {
        resize(entry.contentRect.width,entry.contentRect.height )
        console.log("Resize")
    });
});


myObserver.observe(document.querySelector('.canvas'))

Javascript: How to subtotal values in list of { value, date } by time period?

I have a list of objects like this:

const rawData = [
    {
        "quantity": 44000,
        "date": "2017-10-24"
    },
    {
        "quantity": 44000,
        "date": "2017-10-24"
    },
    {
        "quantity": 44000,
        "date": "2017-10-27"
    },
    {
        "quantity": 44000,
        "date": "2017-10-27"
    },
    {
        "quantity": 44000,
        "date": "2017-11-16"
    }
]

I want to sum the quantities that belong in the same time period.
For instance, applying a monthly period, I would like to obtain a list like this:

dataTotalledByMonth:

[
    {
        "quantity": 176000,
        "period": "2017-10"
    },
    {
        "quantity": 44000,
        "period": "2017-11"
    }
]

I want to come up with a general solution that will allow me to switch to different periods (annually, weekly, quarterly, etc) and get the processed list dynamically.

can i have multiple class with ternary expression

I have popBox for add data and when I click the button a window opens in which I enter data while the background is little bit obscured with opacity.

<div :class="[!popBox ? 'opacity-100' : 'opacity-60']">

This code works perfectly, but I want also delete data and I wanna another popup boxes where it says “do you want delete data” with two buttons.

My question is how can i merge two below class binding ?

<div :class="[!popBox ? 'opacity-100' : 'opacity-60']">
<div :class="[!popDeleteBox ? 'opacity-100' : 'opacity-60']">

How to automatically recover the data that has just been created?

I explain my problem:
I have two functions, one to create a garden and another a plot. So it’s POST requests to my API but when I click submit, I have another function (which is a GET request) that retrieves the garden and the plots, this function works but I have to reload the page for them to appear: it’s not added automatically. How can I do this?

I tried putting in the array of useEffect (which repeats my function to retrieve data from the Garden and the plots) the variable garden and plot or setGarden and setPlot but it doesn’t work.

Here is the code of the GET Request :

const [garden, setGarden] = useState([]);
const [plot, setPlot] = useState([]);
const [loading, setLoading] = useState(false);

  const gardenData = async () => {
    setLoading(true);
    const user = await AsyncStorage.getItem('user');
    const parsedUserData = JSON.parse(user);
    try {
      const response = await axios.get(
        `http://127.0.0.1/api/garden?user=${parsedUserData.user.id}`,
        {
          headers: {
            Authorization: `Token ${parsedUserData.token}`,
          },
        },
      );
      if (response.status === 200) {
        setGarden(response.data);
        setLoading(false);
        try {
          const plotResponse = await axios.get(
            `http://127.0.0.1/api/plots?garden=${response.data[0].id}`,
            {
              headers: {
                Authorization: `Token ${parsedUserData.token}`,
              },
            },
          );
          if (plotResponse.status === 200) {
            setPlot(plotResponse.data);
          }
        } catch (e) {
          alert(e);
        }
      }
    } catch (e) {
      console.log('Erreur ' + e);
      setLoading(false);
    }
  };

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

Thanks for the help !

React Native – TypeError: n.createContext is not a function. (In ‘n.createContext(o.default)’, ‘n.createContext’ is undefined)

I’m trying to implement React Native into a existing Android application. I follow the steps in the official documentation and I have ended with the following error when I compile the app (Although I receive and error the build is successful).


On my phone:

The error


In Android Studio emulator:

enter image description here

Has someone faced the same issue?

Is the official React Native docs wrong?

value from php EOT causing javascript map error

trying to render mapSvg via value from php.

however having an issue when mapSvg trying to read value from php variable…

if I bring in php value into chosen_source, then and do this

jQuery('#map-'+chosen_source).mapSvg(

then this above line will trigger the mapsvg getComputedStyle error.

if I directly hardcode jQuery('#map-newyork').mapSvg(
then no error

if I declare var chosen_source = 'newyork';
then no error.

mapsvg.min.js:1 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
    at new MapSVG.ResizeSensor (mapsvg.min.js:1:746)
    at Object.setResponsive (mapsvg.min.js:3:2667)
    at Object.setSize (mapsvg.min.js:3:2119)
    at Object.<anonymous> (mapsvg.min.js:4:25190)
    at c (jquery-3.6.0.min.js:2:28327)
    at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072)
    at l (jquery-3.6.0.min.js:2:79901)

<?php

$state = "newyork";

$printout = <<<EOT

    var view_width = jQuery("#content").width();
    var chosen_source = `{$state}`;
    var w = 1000;
    var h = 500;
    var vB = [map_source.get(chosen_source).get('vb_L')];

jQuery('#map-'+chosen_source).mapSvg(
    {width: w,
    height: h,
    source: "/map/"+ map_source.get(chosen_source).get('source') 
});
EOT;

echo $printout;
?>

anyone have solution on this?

How to solve in Knex.js ON CONFLICT DO UPDATE command cannot affect row a second time

I had built a query in Knex.js to insert records to the DB

upsert(input) {
    if (isEmpty(input)) return Promise.resolve(0);

    return this.tx(tableName)
      .insert(input.map(prepareInput))
      .onConflict([columns.candidateId, columns.startAt])
      .merge()
      .returning()
      .then(({ rowCount }) => rowCount);
  }

But I’m getting this error

ON CONFLICT DO UPDATE command cannot affect row a second time

I need to insert data and merge it with the existing one and not sure how should I edit this query to avoid the error

React Navigation crashes when rendering

I’m getting an error while rendering navigation container.

I just installed the project with the step by step getting started guide.
but still I’m getting an error.

here is my Code:

App.js

import * as React from 'react';
import { StatusBar } from 'expo-status-bar';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';

export default function App() {
  return (
    <View>
      <NavigationContainer></NavigationContainer>
      <StatusBar />
    </View>
  );
}

Package.json

{
  "name": "instagram_clone",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-navigation/native": "^6.0.10",
    "expo": "~44.0.0",
    "expo-status-bar": "~1.2.0",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-web": "0.17.1",
    "react-native-screens": "~3.10.1",
    "react-native-safe-area-context": "3.3.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

The error i am getting:
abi44_0_0.com.facebook.react.common.JavascriptException: Failed to execute ‘importScripts’
on ‘WorkerGlobalScope’: The script at ‘http://192.168.1.23:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=false&minify=false’ failed to load

Failed to execute ‘importScripts’ on ‘WorkerGlobalScope’: The script at ‘http://192.168.1.23:19000/node_modules%5CAppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false’ failed to load

Am i installing something wrong?

Vue.js 3 v-if ternary function, how to pass object as a conditional

<div :class="cellProps.rowData.BrandColor ? 'bluText' : 'redText'">
    <p v-if="cellProps.rowData.BrandColor ? message='cellProps.rowData.BrandColor' : message='NO VALUE PRESENT' ">Brand Color#: {{ message }}</p>
</div>

I am bringing in data off a Data Table and with a v-if I am checking to see if cellProps.rowData.BrandColor has a value, if it does I want to use that value as the message, if not, use “NO VALUE PRESENT”.

The class works fine, but passing in the value as a message is not working correctly. I am getting the feeling that I am not passing it correctly to message. What would be the proper way to pass the value cellProps.rowData.BrandColor to message ?

div array won’t close when external close button div is clicked (Javascript)

i’m actually occuring a situation when making an accordion. I already add a close button (x text) inside my div to close the accordion, but it won’t close after i clicked on that.

document.addEventListener("DOMContentLoaded", (e) => {
    
    const accordion = document.querySelectorAll('#accordion-img');
   const button = document.querySelectorAll('#button-close');
    
/* add Class from the div itself being clicked */
  accordion.forEach((accs,idx) => {
        accs.addEventListener('click', () => {
            addActive(accs,idx);
        });
    });
  
    function addActive(el,index) {
        el.classList.add('active');
        accordion.forEach((accs,idx) => {
            if(idx !== index){
                accs.classList.remove("active");
            }
        });
  }
  
/* remove class from button */
  button.forEach(xer => {
        xer.addEventListener('click', () => {
            removeActive();
        });
    });
  
    function removeActive() {
    accordion.forEach(accs =>{
      accs.classList.add('active');
    })
  }
})
.toggle {
  display: none
}

#accordion-img #button-close {
  display: none;
}

#accordion-img.active {
  color: blue;
}

#accordion-img.active #button-close {
  color: rgba(0,0,0,1);
  display: block;
  cursor: pointer;
}
<div id= "accordion-img" class="a"> Source <div id="button-close"> x </div></div>

<div id= "accordion-img" class="a"> Share <div id="button-close"> x </div></div>

<div id= "accordion-img" class="a"> Report <div id="button-close"> x </div></div>

Please help me to fix that. Thank you so much.

comparing between 2 values in react js [duplicate]

I tried to compare between 2 values (one in state) but in seems that react compare only the first digit of the values.

class BasicTextFields extends Component {
constructor(props) {
  super(props)
  this.state = { errorText: '', value: props.value , value2: props.value, errorText2: ''};
  
}
onChange(event) {
  if (event.target.value >399000) {
    this.setState({ errorText: '' })
    this.setState({  value: event.target.value})
    
  } else {
    this.setState({ errorText: 'wrong' })
    this.setState({  value: event.target.value})
    
  }
}

onChange2(event) {
   let check= this.state.value;
  if (event.target.value < check) {
  
    this.setState({value2: event.target.value})
    this.setState({ errorText2: '' })
    
  } else {
    this.setState({ errorText2: 'Invalid format: ###-###-####' })
    this.setState({  value2: event.target.value})
     }
  }

render() {
  return (
    <Box
    
   <TextField 
      id="outlined-basic" label="Asset value"  variant="outlined" value={this.state.value}
       helperText={this.state.errorText}
       onChange={this.onChange.bind(this)}/>
       <h3>{this.state.value}</h3>
       
       <TextField 
      id="outlined-basic" label="loan value"  variant="outlined" value={this.state.value2}
       helperText={this.state.errorText2}
       onChange={this.onChange2.bind(this)}/>
      
</Box>

someone can help me how to compare between 2 of the values (value and value2) ?

How come my react hook isn’t acting as expected? Importing problem? Destructuring issue?

Im trying to pass a state value into a component. Why is it working in one component and not working in another component in the same folder?

I have the hooks in here. Im trying to access “currentGuess”. In this function I initialize the state of currentGuess to “”, then the next part, “handleInput()”, just sets the “currentGuess” to whatever you type in.

———————-/src/hooks/useWordle.js———————-

const useWordle = (solution) => {
  const [currentGuess, setCurrentGuess] = useState("");

  /* OTHER UNNECESSARY CODE TO QUESTION */

  const handleInput = ({ key }) => {
    if (key === "Enter") {
      if (turn > 5) {
        console.log("You used all your guesses!");
        return;
      }
      if (history.includes(currentGuess)) {
        console.log("You already tried that word!");
        return;
      }
      if (currentGuess.length !== 5) {
        console.log("Word must be 5 characters long!");
        return;
      }
      const formatted = formatGuessWord();
      console.log(formatted);
    }
    if (key === "Backspace") {
      setCurrentGuess((state) => {
        return state.slice(0, -1);
      });
    }

    if (/^[a-zA-z]$/.test(key))
      if (currentGuess.length < 5) {
        setCurrentGuess((state) => {
          return state + key;
        });
      }
  };
  return {
    currentGuess,
    handleInput,
  };
};

export default useWordle;

I can use it in here like this and it works no problem:

———————-src/components/Wordle.js———————-

import React, { useEffect } from "react";
import useWordle from "../hooks/wordleHooks.js";

function Wordle({ solution }) {
  const { currentGuess, handleInput } = useWordle(solution);
  console.log("currentGuess=", currentGuess);

  useEffect(() => {
    window.addEventListener("keyup", handleInput);

    return () => window.removeEventListener("keyup", handleInput);
  });

  return <div>Current guess: {currentGuess}</div>;
}

export default Wordle;

I thought this line was what allowed me to use “currentGuess”. I destructured it.

const { currentGuess, handleInput } = useWordle(solution);

However when I place that line in this code, which is in the same folder as the above working code, “currentGuess” comes out undefined or empty.

———————-/src/components/Key.js———————-

import React, { useContext } from "react";
import { AppContext } from "../App";
import useWordle from "../hooks/wordleHooks.js";

export default function Key({ keyVal, largeKey }) {
  const { onSelectLetter, onDeleteKeyPress, onEnterKeyPress } =
    useContext(AppContext);
  const { currentGuess } = useWordle();

  const handleTypingInput = () => {
    console.log("Key.js - Key() - handleTypingInput() - {currentGuess}= ", {
      currentGuess,
    }); // COMES OUT "Object { currentGuess: "" }"
  };

If you made it this far thank you very much. Im new to this and hoping someone who knows what they are doing can see some glaring error I can fix. You don’t even have to solve it for me but can you point me in the right direction? How do I get the “currentGuess” in the Key.js component?