alternative way of providing index to querySelectorAll by :even and :odd

I am trying to get even (div)elements and give them different class Names compared to odd (div) elements in which they will have different class names also, I want to write inside querySelectorAll() function to get even (.project) class and to get odd (.project) class without providing index like [0], [1],…etc. is there a way to do something like that?
here is there code for explanation.

here is the original code:

document.querySelectorAll('.project')[0].classList.add('EvenProject');
document.querySelectorAll('.project')[1].classList.add('OddProject');
document.querySelectorAll('.project')[2].classList.add('EvenProject');

here is what I want to implement:

document.querySelectorAll('.project:even').classList.add('EvenProject');
document.querySelectorAll('.project:odd').classList.add('OddProject');

I also tried this code, by querySelector(), but It doesn’t work.

 document.querySelector('.project:even').classList.add('EvenProject');

thanks for you help.

how can i retry a fetch request when an 408 or say an 503 error is receved in reactjs

i am fetching data from a sever and sometime the request take so long and the sever responds with a 408 status
so my code looks like this

export class ResponseError extends Error {
  public response: Response;

  constructor(response: Response) {
    super(response.statusText);
    this.response = response;
  }
function parseJSON(response: Response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  return response.json();
}
function checkStatus(response: Response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new ResponseError(response);
  error.response = response;
  throw error;
}
export async function request(
  url: string,
  options?: RequestInit,
): Promise<{} | { err: ResponseError }> {
  const fetchResponse = await fetch(url, options);
  const response = checkStatus(fetchResponse);
  return parseJSON(response);
}

how can i retry the request if the response status code 408 is received

Passing JS variable value to PHP variable to update database

If you want to see the part where I tried AJAX, go look down below. It completely messed up the page and I’m stuck on how to do this. I’ve got some code here:

$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id='$id'";
$INFO=mysqli_query($conn, $sql);
if (mysqli_num_rows($INFO) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($INFO)) {
        echo "riskcoin: " . $row["riskcoin"].  "<br>";
        $riskcoins = $row["riskcoin"];
    }
} else {
   echo "0 results";
}
?>

var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();


// Bets Object
function Bets() {
   this.pot = <?php echo "$riskcoins"; ?>;
   this.bet = 0;
   $('#bet').text(0);
   $('#pot').text('$' + this.pot);
 }

// Bets methods
Bets.prototype.updateAmounts = function () {
   $('#bet').text('$' + this.bet);
   $('#pot').text('$' + this.pot);
};
Bets.prototype.doubleDown = function() {
   this.pot -= this.bet;
   this.bet += this.bet;
};
Bets.prototype.potAmount = function() {
    return this.pot;
};
Bets.prototype.betAmount = function(){
    return this.bet;
};
Bets.prototype.disableDeal = function () {
    $('#button-deal').addClass('disabled');
};
Bets.prototype.addBet = function(amount) {
    if (this.pot >= amount) {
        this.pot = this.pot - amount;
        this.bet = this.bet + amount;
        this.updateAmounts();
        $('#button-deal').removeClass('disabled');
    } else {
        notEnoughChips();
    }
};

First part is php second part js. I have an int value in my database called riskcoin. this.pot contains that riskcoin value (//Bets object) and shows itin another php file in a paragraph with id="pot".

When an image is clicked another function ads an amount to the bet depending on the picture (for example 5).

Now my question: after the line this.updateAmounts(); it executes

// Bets methods
Bets.prototype.updateAmounts = function () {
   $('#bet').text('$' + this.bet);
   $('#pot').text('$' + this.pot);

Now my question would be if I could update the riskcoin value in my database with an update query after this function with the current this.pot value? It should show live updates without page refreshes. I’ve read about AJAX so I tried something like this:

Bets.prototype.updateAmounts = function () {
    $('#bet').text('$' + this.bet);
    $('#pot').text('$' + this.pot);
    window.history.pushState('page2', 'Title', '?coins=' + this.pot);
    $(document).ready(function(){
    var url = window.location.href;
    var params = url.split('?coins=');
    var id = (params[1]);
        $("#button-deal").click(function(){ $.ajax({
        type:"POST",
        url:"blackjackgame.php",
        data:{id:id},
        success:function(result){
        $("#pot").html(result);
        }
        });
        });
    });
};

But it for some reason when I click on the deal button (#button-deal) it shows up my login page in the middle of the page under all the other stuff, console gives me: GET http://riskybusiness.nglyceum.eu/games/login.css net::ERR_ABORTED 404 (Not Found)jquery-3.1.1.js:5921

jQuery only using whole numbers

I currently have a form that draws a circle based on user input and outputs the diameter in the console as well. However, when I input a number with a decimal, it just converts it to a whole number. For example if I input 5.68, it takes my input as 5. How do I make it so that It recognized decimal numbers?

https://jsfiddle.net/Kaevonz/wsgfhjLc/215/

$(function() {
  $('.circle').hide();
  $('#outer_diameter').on('change', function() {
    var $outer_diameter = parseInt($("#outer_diameter").val());
    var $converted = ($outer_diameter * 10);
    console.log($outer_diameter, $converted);
    /*const $circalc = (2 * Math.PI * ($outer_diameter / 2)).toPrecision(6);*/
    $('.circle').css({
      height: (2 * $converted),
      width: (2 * $converted),
      top: "calc(50% - " + ($converted) + "px)",
      left: "calc(50% - " + ($converted) + "px)"
    });
    $('.circle').fadeIn(300);
    $('#error').hide();
  })

  $('.circle2').hide();
  $('#inner_diameter').on('change', function() {
    var $inner_diameter = parseInt($("#inner_diameter").val());
    var $converted_2 = ($inner_diameter * 10);
    console.log($inner_diameter, $converted_2);
    $('.circle2').css({
      height: (2 * $converted_2),
      width: (2 * $converted_2),
      top: "calc(50% - " + ($converted_2) + "px)",
      left: "calc(50% - " + ($converted_2) + "px)"
    });
    $('.circle2').fadeIn(300);
  })
});


Monorepo – Multiple .vscode settings

Project structure

I have the following project structure:

/
| - .vscode/
| - - - - settings.json
|
| - packages/
| - - - - app/
| - - - - - - index.js
| - - - - - - package.json
| - - - - website/
| - - - - - - .vscode/
| - - - - - - - - settings.json
| - - - - - - index.html
| - - - - - - styles.scss
| - - - - - - package.json
|
| - package.json
|

As you can notice, I have two vs-code setting files… one at the root and another one inside the website workspace.

Root vs-code settings

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
  },
  "editor.formatOnSave": false,
  "editor.tabSize": 2,
  "editor.rulers": [
    80,
    120
  ],
  "eslint.codeAction.showDocumentation": {
    "enable": true
  },
  "eslint.validate": [
    "javascript"
  ],
  "eslint.workingDirectories": [
    {
      "mode": "auto"
    }
  ],
  "javascript.updateImportsOnFileMove.enabled": "always",
}

Website workspace vs-code settings

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },
  "css.validate": false,
  "less.validate": false,
  "scss.validate": false,
  "stylelint.configFile": ".stylelintrc",
  "stylelint.snippet": [
    "css",
    "scss"
  ],
  "stylelint.validate": [
    "css",
    "scss"
  ],
  "stylelint.packageManager": "yarn"
}

Questions

I know that /.vscode/settings.json is merged with my vs-code default settings. But…

  1. Is /packages/website/.vscode/settings.json merged with /.vscode/settings.json

  2. As you can see, there is some code repetition in both configs:

  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
  },

and

  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },

If I remove "source.fixAll.eslint": true, from the /packages/website/.vscode/settings.json, will editor.codeActionsOnSave.source.fixAll.eslint be extended from /.vscode/settings.json?

How to test function defined on window object in Jest and typescript

So I’m trying to test a call to a function defined on the global window object. I have looked at multiple examples but am still not able to run a simple test case. My limited knowledge of TypeScript doesn’t help as well 🙂

Api.ts

import "./global.d";
const verifier = window.Verifier;

export class Api {
  constructor(private readonly id: string) {}
  public fetchData() {
    return new Promise<object>((resolve, reject) => {
      verifier.request({
        request: {
          id: this.id
        },
        onSuccess: (data: object) => {
          resolve(data);
        },
        onFailure: () => {
          reject("Error!");
        }
      });
    });
  }
}

Api.test.ts

import { Api } from "./Api";

let windowSpy: any;

describe("Test Apis", () => {
  beforeEach(() => {
    windowSpy = jest.spyOn(window, "window", "get");
  });

  afterEach(() => {
    windowSpy.mockRestore();
  });
  it("should call the function", () => {
    const mockedReplace = jest.fn();
    windowSpy.mockImplementation(() => ({
      Verifier: {
        request: mockedReplace
      }
    }));
    const api = new Api("123");
    api.fetchData();
    expect(mockedReplace).toHaveBeenCalled();
  });
});

global.d.ts

import { Verifier } from "./verifier";

declare global {
  interface Window {
    Verifier: Verifier;
  }
}

verifier.d.ts

type RequestPayload = {
  request: {
    id: string;
  };
  onSuccess: (data: object) => void;
  onFailure: () => void;
};
type verifyCode = number;

export interface Verifier {
  request: (requestPayload: RequestPayload) => verifyCode;
}

I have also created a codesandbox example for easy reference
https://codesandbox.io/s/cranky-mccarthy-2jj622?file=/src/verifier.d.ts

Any help is appreciated!

connecting localhost fastapi to react app

I am trying to develop a react app that connects to a python fastapi server. I am developing the frontend and the backend both on my local computer. When I try to use the fetch API to get data from my python server, I get a bunch of errors stating CORS permissions denied and Uncaught (in promise) TypeError: Failed to fetch. I have added “proxy”: “HTTP://localhost:3000” to my package.json file and am still receiving the same error. How do I resolve this?
My backend is on port 80 and my frontend is on port 3000.
If there is any more information I could provide to make this post more clear please let me know.
I am relatively new to dealing with APIS and JS

error messages

This is my backend script

import math
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware


myApp = FastAPI()
userInput = 0

origins = [
    "http://localhost:3000",
    "localhost:3000"
]


app.add_middleware(
    CORSMiddleware,
    allow_origins = origins,
    allow_credentials = True,
    allow_methods = ["*"],
    allow_headers = ["*"]
)


@myApp.get("/")
def default():
    return "enter a number after a slash in the URL"


@myApp.get("/is-prime")
def is_prime():
    prime = True
    sqrt = int(math.sqrt(userInput))
    for i in range(2, sqrt + 1):
        if userInput % i == 0:
            prime = False
            break

    return {"prime": prime} 

This is my frontend script

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

class App extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            input: 0,
            prime: true,
            testList: []
        }

    }
    componentDidMount() {
        console.log("content is being loaded")
        fetch("http://localhost:80")
            .then(res => res.json())
            .then(json => {
                this.setState({
                    prime: json["prime"],
                })
                console.log("content is loaded")
                console.log("testList is " + String(this.state.testList))
            });
        
    }
    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <h2>Welcome to the prime finder App.</h2>
                    <p>Enter a Number below</p>
                    <form>
                        <input type="number"></input>
                        <button> Is it prime? </button>
                    </form>
                    <p>{this.state.prime ? "Yes its prime!" : "No its not prime"}</p>
                </header>
            </div>
        );
    }

}

export default App;

Use webpack to inject custom bootstrap using a Link tag

I want to customize bootstrap to my needs, and I’m trying to use webpack to inject my CSS as a link tag.

I’ve installed:

  • webpack
  • mini-css-extract-plugin
  • sass
  • node-sass
  • sass-loader
  • css-loader

And this is what I have tried so far:

// I want to take the content of custom-bootstrap, and inject it as a link tag.
{
  include: resolve('src/scss/custom-bootstrap.scss'),
  use: [
    MiniCssExtractPlugin.loader, // 3. Injects the styles into a link tag.
    //"style-loader", // 3. Injects styles into the DOM.
    "css-loader", // 2. Turns css into js.
    "sass-loader", // 1. Turns sass into css.
  ]
}

The contents of custom-bootstrap.scss looks like this:

@import "~bootstrap/scss/bootstrap";

I also have another webpack rule (/.(sc|c)ss$/i) very similar to the one above with is to handle every other style in the app. It looks like this:

{
  test: /.(sc|c)ss$/i,
  exclude: resolve('src/scss/custom-bootstrap.scss'),
  use: [
    // MiniCssExtractPlugin.loader, // 3. Injects the styles into a link tag.
    "style-loader", // 3. Injects styles into the DOM.
    "css-loader", // 2. Turns css into js.
    "sass-loader", // 1. Turns sass into css.
  ]
}

When I run webpack I get the following error:

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: expected "{".
  â•·
2 │       import API from "!../../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js";.

Anyone knows how to solve this? I also tried to use a a path to the node_modules instead of using the ~ syntax in the scss file, but without luck. Any help will be appreciated. 🙂

Calculation not being performe properly in JavaScript

I have the following code that is converting characters entered in an input field into other characters (namely, entering an e or and E and converting it to a 3, likewise for a t or T into a 7).
I am also calculating the percentage of the characters that were converted, but my calculation is not being performed properly and was wondering if someone can help with this.
For example, if someone enters in a string like 373, it will not convert the characters (as expected), but the number of converted characters will be 3 when they should be 0 instead.

function ReplaceChars() {

  var json         = JSON.parse(localStorage.getItem("registration"));
  var characters   = json['charsEntered'];
  var total        = "";
  var convertedPct = 0;

  const result = characters
      .replaceAll(/e|E/g,"3")
      .replaceAll(/t|T/g,"7")

  total = characters.length;

  let x = Number((result.match(/3|7/g)||[]).length);
  let y = Number(total);

  convertedPct      = (x/y)*100
  roundedPercentage = convertedPct.toFixed(2);

  $("#charsConverted").val(result);
  $("#convertedChars").val(x);
  $("#totalChars").val(y);
  $("#pctChars").val(roundedPercentage + "%");
}

Older date in Spreadsheets Google Script

I am trying to get information of newly created files in a G drive folder. Everytime I run my program the output should refer only to new files in the folder. The D column will contain the creation dates. So I read the last value of the D column, let’s call it DX; DX would have the creation date of the newest file (because I sorted them in the last line of the program). Then I compare DX to the creation dates of all the files in my folder. Only the files.creationDate > DX are the ones I need. I’ve managed to come up with:

//get value of D2
  var control_cell = SpreadsheetApp.getActiveSheet().getRange('D2');
//get last non blank value in the D column and assign it to variable lastTimeCreated
  var values = SpreadsheetApp.getActiveSheet().getRange('D:D').getValues().flat().filter(String);
  var [lastTimeCreated] = values.slice(-1)
//If D2 is empty assign an old date to lastTimeCreated
  if (control_cell.isBlank()){
    lastTimeCreated = '1/10/2020 12:00:00'
  }

  while(contents.hasNext()){
    varFile = contents.next();
    varTime = varFile.getDateCreated().toLocaleString();

    if(new Date(varTime).getTime() >= new Date(lastTimeCreated).getTime() && varOwner.includes(actualSheetName)){
      dataRows[i] = [varTime];
      i++;
    }
    else{
      continue
    }
  }
  const sortedRows = dataRows.sort((a, b) => new Date(a[3]) - new Date(b[3]));

The problem is the last if with the new Date(varTime).getTime() >= new Date(lastTimeCreated).getTime() statement. I think lastTimeCreated can’t be interpreted as a Date and as a result they can’t be compared. I know varTime is not the problem because the last line of this program works perfectly. Maybe the problem is the format date of both dates (?). I’ve also tried with Date.parse() for both variables but it hasn’t worked. Any help is widely appreciated.
Edit
The date format is this: 1/10/2020 12:00:00

Dropdown menu how hide elements on click and display only one?

I have a quastion how to manipulate state in my dropdown menu? I mean that now when i click one element (for example “Mezczyzna” – ItemsMenu – MenuItem) my item shows up and when i click another item (for example “Kobieta”-ItemsMenu – MenuItem (Kobieta is title)) this item also shows up and “Mezczyzna” is still open but i want to hide “Mezczyzna”.
I dont know how to setState for element with specific index for example. Now i have parent file – Navigationn which renders (map) ItemsMenu with state. How can i setState[2]element to false?
Thanks for the help 🙂

const Navigationn = ({displayHandlerMenu}) =>{
return (
<>
  <SidebarWrap>
    {menuItems.map((item, index) => (
      <ItemsMenu key={index} item={item} displayHandlerMenu={displayHandlerMenu} />
    ))}
  </SidebarWrap>
</>);};
export default Navigationn;



const ItemsMenu = ({ item, displayHandlerMenu, index }) =>{
const [submenu, setSubmenu] = useState(false);
const showSubmenu = () => {
setSubmenu(!submenu);};
return (
<>
  <MenuItemLink to={item.path} onClick={showSubmenu} key={index}>
    <MenuItem>{item.title}</MenuItem>
  </MenuItemLink>
  {item.submenu &&
    submenu &&
    item.submenu.map((subItem, index) => (
      <>
        <ItemsSubMenu
          key={index}
          item={subItem}
          displayHandlerMenu={displayHandlerMenu}
        />
      </>
    ))}
</>
);};
export default ItemsMenu;

Switching img src to one that has already been fetched

I have a list of images as buttons and when clicked a modal appears that has the image on the left with text on the right. But when I switch the src of the image in the modal the browser refetches the image from the database. Is there a way to switch the image without refetching since it has already been downloaded?

$(button).on("click", function () {
  // GET ALL THE INFO NEEDED FOR THE CARD
  const imgURL    = this.querySelector("img").src;
  const name      = this.querySelector(".__name").innerHTML;
  const position  = this.querySelector(".__position").innerHTML;
  const questions = this.querySelectorAll('[data-js="question"]');
  const answers   = this.querySelectorAll('[data-js="answer"]');

  // POPULATE THE CARD
  employeeCard.querySelector(".__name").innerHTML     = name;
  employeeCard.querySelector(".__position").innerHTML = position;
  employeeCard.querySelector(".__img").src            = imgURL;

  // CONSTRUCT ANSWERS AND QUESTIONS

  // SHOW THE CARD AFTER 200 MS
  setTimeout(() => {
      $(employeeCard).toggleClass("active");
  }, 200);
});

for the fact that the browser refetches the image on change. Thanks for answers in advance.

problem getting id and deleting document Vuejs Firestore

I am creating site for my store and learning Vue js at the same time. I’m having a problem with getting product id from firestore and being able to delete product. When i create a new product in console id doesn’t come out either, got this message (Document written with ID: undefined)
I’m using Vue js 3 and Firebase 9

I have this on main.j

const dataBase = collection(db, "products");

and this on products.js

<script>
import { dataBase } from '../main';
import { addDoc, onSnapshot, doc, deleteDoc } from "firebase/firestore";

export default {
  name: "Products",
  props: {
    msg: String
  },
  data() {
    return {
      products: [],
      product: {
        name: '',
        detail: '',
        price: '',
        brand: '',
        category: ''
      }
    }
  },
  methods: {
    saveData() {
      try {
        const docRef = addDoc(dataBase, this.product);
        console.log("Document written with ID: ", docRef.id);
        this.reset();
      } catch (e) {
        console.error("Error adding document: ", e);
      }
    },
    reset() {
      Object.assign(this.$data, this.$options.data.apply(this));
    },
    deleteProduct(doc) {
      deleteDoc(doc(dataBase, doc.id));
    }
  },
  created() {
    onSnapshot(dataBase, (snapshot) => {
      snapshot.docs.forEach((doc) => {
        this.products.push({ ...doc.data(), id: doc.id })
      })
    });
  }
};
</script>

Thanks!

Rails – MVC – How to change HTML tag with to code Ruby after fetching API?

I’m trying to use data from a fetch and store it in a ruby variable. I’m going to use that variable in a ruby if/else statement after but I need to be able to access it first. When I use .innerHTML, it doesn’t get declared as a variable but it is displayed on the page as a text. I tried with .innerText but its the same result and with .value it just disappears and value is nothing.

<p id="answer"><%=@answer%></p>
<div id="word"></div>
<script>
  const answer = document.getElementById('answer').innerHTML;
  console.log(answer);
  fetch(`api/${answer}`)
    .then(response => response.json())
    .then((data) => {
      console.log(data)
      console.log(data.found)
      document.getElementById('word').innerHTML = `<%@word=${data.found}%>`
    })
</script>
<%=@word%>