Multiple Apollo Queries in one component / screen

I have these two Apollo queries in one react component.

 const { data, loading, error } = useQuery(PlaylistQuery, {
    variables: { _id: playlistId },
    fetchPolicy: "cache-and-network",
  });

  const [loadSong, { called, loading, error, data }] = useLazyQuery(SongQuery, {
    variables: {
      _id: song._id,
    },
  });

This will obviously give me the Cannot redeclare block-scoped variable error message. What’s a smart way to get around this?

Canvas gradient is diagonal when it should be vertical

I have some javascript code to generate a gradient from 14 colors:

var example = document.getElementById('example');
var context = example.getContext('2d');

var grdBnds = [0, 0, 200, 30]
var grd = context.createLinearGradient(grdBnds[0], grdBnds[1], grdBnds[2], grdBnds[3]);
grd.addColorStop((1/14)*0, "rgb(0, 0, 0)");
grd.addColorStop((1/14)*1, "rgb(191, 191, 191)");
grd.addColorStop((1/14)*2, "rgb(115, 115, 115)");
grd.addColorStop((1/14)*3, "rgb(245, 182, 181)");
grd.addColorStop((1/14)*4, "rgb(147, 252, 253)");
grd.addColorStop((1/14)*5, "rgb(87, 120, 246)");
grd.addColorStop((1/14)*6, "rgb(177, 251, 162)");
grd.addColorStop((1/14)*7, "rgb(80, 176, 51)");
grd.addColorStop((1/14)*8, "rgb(230, 230, 75)");
grd.addColorStop((1/14)*9, "rgb(187, 109, 93)");
grd.addColorStop((1/14)*10, "rgb(235, 51, 35)");
grd.addColorStop((1/14)*11, "rgb(188, 39, 246)");
grd.addColorStop((1/14)*12, "rgb(117, 20, 124)");
grd.addColorStop((1/14)*13, "rgb(191, 191, 191)");

context.fillStyle = grd;
context.fillRect(grdBnds[0], grdBnds[1], grdBnds[2], grdBnds[3]);
<canvas id="example" width="1000" height="400"></canvas>

As you can see, the gradient lines are being generated at a diagonal angle to the right, when they should be going vertically.

Does anybody know why this is happening, and how I could fix it?

I know you can also make gradients with CSS, but for what I am doing I need to make the vertical gradients with canvas.

making a game that includes only one player and the rolling of a dice and scoring the values

In this game, the player scores points based on the face values of the dice, and also on some decisions the player has to make during the game.
The game consists of six rounds. During each round, the player will roll some or all of
their five dice three times. At the conclusion of each round, the player must choose how
their dice are to be scored by choosing which die value to score. Each matching die is
worth the number of points shown on its face. For instance, if the dice values are 5, 3,
2, 3, 4, and the player chooses to score the 3s, the player will earn six points (0 + 3 + 0 +
3 + 0 = 6).
What makes the game tricky is that the player must choose how to score one round’s
set of dice before starting the next round, and they can’t change this choice later. If the
player scored the 3s from Round 1, and Round 2’s dice are 3, 3, 3, 2, 3, the player can not
elect to score the 3s from this round.
However, the player may choose to help themselves out during a round by choosing to
“keep” a particular value after a roll. For instance, if the player has already scored the
3s in Round 1, and Round 2 starts with 3, 2, 5, 3, 5, then the player may choose to keep
the 5s and re-roll only the other dice, since the 3s won’t be any help. Please note that
the player may only choose a value to keep, and not a collection of dice with different
values.
At the end of the game, the sum of the six rounds’ scores is the player’s final score.
This game is generally played with two players and five actual dice; in this game, you
will simulate a one-player version.

Import JSON field in ES6 format

I just came across this line of code:

const config = require(__dirname + '/../config/config.json')[env];

It imports one specific field from a json file, depending on an environment variable (in this case it imports different keys for testing, development and production).

What would the equivalent be in a javascript ES6 module? I am currently using this method:

import config from "../config/config.json" assert { type: "json" };
const settings = config[NODE_ENV];

Which requires importing all the settings and declaring another variable. Is there any way to import just one field?

React Context State Update

I need help updating a user within various parts of my react app.
I have successfully been able to create a context and access it globally, but anytime I try to update the state, it either breaks or uses default state
I have issues updating the state, the code goes here

import { createContext } from "react"; 
const user = {
  Fullname: "Ade Johnson",
  username: "Jonny",
  phone: "+234 0987655",
  email: "[email protected]",
  mode: "light",
  isLoggedIn: false,
};

export const UserContext = createContext(user);

const providerValue = useMemo(() => ({ user, setUser }), [user, setUser]);

<UserContext.Provider value={providerValue}>
{Children}
</UserContext.Provider>

function Login() {
  const [username, setUsername] = useState("");
  const [pass, setPass] = useState("");

  const { user, setUser } = useContext(UserContext);

  function proceed(url) {
let newArr = [...user];
newArr[0].isLoggedIn = true;
newArr[0].Fullname = "Toluwalope";
newArr[0].username = "Toolz";
newArr[0].email = "[email protected]";
setUser(newArr);
console.log(user);
window.location.replace(url);
 }

At this point, When the dashboard is loaded, it uses the default state.

Multiple Highcharts JavaScript Update very slow. Any options to increase speed?

I have multiple Highcharts on the same page, and I update them all at the same time using a combobox which selects the individual to be shown at the charts.

All the Highcharts are quite simple, with 3-4 line or column series each, and a limited number of observations per chart (around 10-12).

For updating the charts I use a JS function, and I’ve tried two options:

First option:

chart1.update({
    series: [{data: mybankjson["data"]["spr_t_tva"]},
              {data: mybankjson["data"]["enf_t_tva"]},
              {data: mybankjson["data"]["hogares_t_tva"]}],
    title: {text: 'Tasas de variación interanual del crédito. SPR<br>('+ecode+'-'+anombre+')'}
});

Second option:

chart1.series[0].setData(mybankjson["data"]["spr_t_tva"])
chart1.series[1].setData(mybankjson["data"]["enf_t_tva"])
chart1.series[2].setData(mybankjson["data"]["hogares_t_tva"])
chart1.setTitle({text:'Tasas de variación interanual del crédito. SPR<br>('+ecode+'-'+anombre+')'})

There are around 40 charts to be updated using first or second option. Both are really slow (around .5 seconds EACH chart), so using the combobox to quickly view charts for different individuals is mainly impossible.

Any ideas? The size of the .json file (mybankjson) might be an issue?

Cannot create `ImageBackground` element because property `source` of unknown type [1] is incompatible with `ImageURISource` [2] in property

I’m getting this flow error:

Cannot create `ImageBackground` element because  property `source` of unknown type [1] is incompatible with  `ImageURISource` [2] in property

this.source works fine in the Parent component (flow-wise), but doesn’t work in the Child component.

// @flow
import { ImageBackground } from 'react-native'

type Props = {
  source: any
}

class Parent extends React.Component<Props> {
  render(): React.Node {
    return (
      <ImageBackground source={this.source} />
    )
  }

  get source() {
    if (someCondition === true) {
      return 'some-image-path'
    }
    return null
  }
}

class Child extends Parent {
  render(): React.Node {
    if (this.source !== null) {
      return (
        <ImageBackground source={this.source} />
      )
    }

    return null
  }
}

Any ideas how I could fix the error and make sure the Child component has “access” to this.source?

Btw, I’m working on a large codebase and don’t have time to convert everything to functional components/hooks/typescript (trust me I would if I had time!).

How to convert ImageData to File

I am trying to send a File to 3rd party server, we are using a service to capture the necesary images but it return the image as ImageData, we tried to conver the ImageData to Blob and then to File, but it did not work. Do you guys know what I am doing wrong here? Thank you.

frontImageFrame

Functions:

export const blobToFile = (blobObj, fileName) => {
  blobObj.name = fileName;
  blobObj.lastModified = new Date();
  return new File([blobObj], fileName, { type: blobObj.type })
}

export const imageDataToBlob = (imageData) => {
  let w = imageData.width;
  let h = imageData.height;
  let canvas = document.createElement("canvas");
  canvas.width = w;
  canvas.height = h;
  let ctx = canvas.getContext("2d");
  ctx.putImageData(imageData, 0, 0);

  return new Promise(resolve => canvas.toBlob(resolve));
};

Implementation:

let frame = data.frontCameraFrame.frame // the ImageData
let imgBlog = imageDataToBlob(frame); // ImageData to Blob
const image = blobToFile(imgBlog, "file.png"); // Blob to File
let idrndReq = idrndRequest(accessToken, image, contractId);

How to update the child component b-tabs value from parent component in vuejs

I am trying to update the child component value from the parent component, when I set the value in the prop, I do get the following error,

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value.

I tried the below solution found on the internet but by doing so my child component prop is not getting changed when I update the parent component

Parent component

<template>
  <child :index-val="indexVal"> </child>
</template>

<script>
export default {
  props: [indexVal],
  data() {
    return {
      indexVal: 0,
    }
  },
  methods: {
    updateVal() {
      // updating value from parent
      this.indexVal = 2
    },
  },
}
</script>

Child component

<template>
  <div>
    <!-- Tabs with card integration -->
    <b-card no-body>
      <b-tabs v-model="tabIndex" small card>
        <b-tab title="tab1">tab1</b-tab>
        <b-tab title="tab2">tab2</b-tab>
      </b-tabs>
    </b-card>
  </div>
</template>

<script>
export default {
  props: [indexVal],
  data() {
    return {
      tabIndex: this.indexVal,
    }
  },
}
</script>

How to print table in excel same order by using XLSX library in react js?

**Below is the object that I would like to print **
I am using XLSX
*I need output as it is *

const handleClick = () => {
var wb = XLSX.utils.book_new();
var ws = XLSX.utils.json_to_sheet(arrayofobjects);
XLSX.utils.book_append_sheet(wb, ws, 'Test');
XLSX.writeFile(wb, 'file.xlsx');

};

  let arrayofobjects =[
{
  "00": 4,
  "01": 6,
    "10": 12,
    "11": 7,
},
{
  "00": 7,
  "01": 7,
    "10": 4,
    "11": 5, 
}

]

But I am getting output in another order in excel

first I am getting 10,11 later I am getting 00,01

This is what I am expecting

enter image description here

Postman Pre-Request Script to Read Variables from CSV file and Append to JSON Body

I have a JSON body with template to pass to an API endpoint in Postman/Newman as follows:

{
  "total": [
    {
      "var1a": "ABCDE",
      "var1b": {
        "var2a": "http://url/site/{{yyyy}}/{{mmdd}}/{{yyyymmdd}}.zip",
        "var2b": {
           "var3a": "{{yyyymmdd}}",
           "var3b": "GKG"
        },
        "var2c": "ABCDE"
        "var2d": "{{p}}"
      }
    },
    {
      "var1a": "ABCDE",
      "var1b": {
        "var2a": "http://url/site/{{yyyy}}/{{mmdd}}/{{yyyymmdd}}.zip",
        "var2b": {
           "var3a": "{{yyyymmdd}}",
           "var3b": "GKG"
        },
        "var2c": "ABCDE"
        "var2d": "{{p}}"
      }
    }
}

Everything enclosed in double braces is a variable that needs to read from an external CSV file, which looks like:

p,yyyymmdd,yyyy,mmdd
1,19991231,1999,1231
2,20001230,2000,1230
  • Note that the CSV isn’t necessarily 2 entries long – I’d ideally like it to take in a dynamic number of entries that append after the last.
  • Ideally, I’d get rid of the last two columns in the CSV file (yyyy and mmdd) and have the code just do a slice as needed.

How do I even begin coding the pre-request script?

Even if reading from an external CSV is not possible, or even coding within the pre-request script to do this, what is a quick one-liner in Javascript or Python that can quickly give me the output I need so that I can just manually place it in the request body?

I even tried using the Postman runner to do a “fake” run so that I can quickly extract the different JSON bodies, but even with this, there is no clean way that it does the export…

Postfix or Reverse Polish Notation

After many tries didn’t found a solution, so posting here.

Want to create a reverse polish notation by given numbers and operators.

Example below:

Input
Numbers = 2, 3, 5, 8, 12

Operators= +, -, *, /

Output should be like
(2 3 * + 5 3 8 / – 12 +)

Looking for a workable solution in JavaScript

How to prevent accidental scrolling outside the iFrame? (Svelte)

I have an iframe in a webpage:

<iframe id="wordBookiFrame" src="/wordBook" style="position:absolute; width:100%; height:100%;"></iframe>

When viewing the webpage on a small screen (ie a smartphone), both the iframe and the main page itself becomes scrollable, which is to be expected, as seen here.

When scrolling to the very end of the iframe however, if you continue to scroll, the main page scroll takes over and the user will then scroll to the bottom of the main page too. I assume this is standard browser behaviour.

However the consequence of this behaviour is that when a user tries to then scroll up in the iframe, it gets stuck, as the scroll in the main page takes priority over the iframe. It seems to “take over” and take precedence over the iFrame itself and results in sticky scroll behaviour of the iFrame.

The solution I have attempted is as follows:

if(document.getElementById("iframe") == block) //as the iframe only displays in certain circumstances
{
   window.addEventListener('scroll',(event) => {
   window.scrollTo(0,0)
   return;
   });
}

The thinking behind this code is that by forcing the main page to scroll position 0,0, you can avoid this problem, but the code doesn’t seem to do anything helpful.

I hope to find some easy solutions to this annoying problem!

Trying to pass parameters through components

So I am creating an app using the movie DB API and I have this Actor component where I am passing the actor id to and when I try to use that Id to link to the person webpage for some reason I am passing an object instead. I am trying to pass the number, is there any way to do this?

    import React from 'react';
// Styles
import { Wrapper, Image } from './Actor.style'

import { Link } from 'react-router-dom';

const Actor = ({name, character, imageUrl, personId}) => {
    console.log(personId);
    return(
        <Wrapper>
            <Link to={`/person/${personId}`}>
                <Image src={imageUrl} alt='actor-thumb' />
            </Link>

            <h3>{name}</h3>
            <p>{character}</p>
        </Wrapper>
    )
}

export default Actor;

So I have these components output to the screen:
enter image description here

And when I click on one of them I get this error:
enter image description here