How to get id attribute in front template of Anki to change display of back template with Javascript depend on whether answer is correct or not

Recently, I’ve been creating Anki cards with Javascript on the card editor. Today, I have a question for you about how do I obtain the id attribute in front template.

First of all, please confirm the code below.

Front Template

<p>652 - 558</p>
<input type="text" id="answer">

Back Template

<div class="answer-display-area"><div>
<script>
const answer = getElementById("answer");
const displayArea = getElementByClassName("answer-display-area");

if(answer === "94"){
const pElement =  document.displayArea.appendChild(document.createElement("p"));
pElement.innerHTML = `<p>652−558</p><p style="background-color:#77fc03;">${answer}</p>`;
} else {
const pElement = document.displayArea.appendChild(document.createElement("p"));
pElement.innerHTML = `<p>652−558</p><p style="background-color:red;">${answer}</p>`;

const correctAnswer = "<p>Answer: 94</p>";
const explaination = "<p>Answer is 94.  Please refer to 5th page.Carry down 1 from the ten's place because of the one's place can't subtract 8 from 2.</p>";
displayArea.parentNode.insertBefore(correctAnswer, displayArea.);
displayArea.parentNode.insertBefore(explaination, displayArea);
}
</script>

Namely, I would like to obtain id attribute in <input type="text" id="answer">, And then, I’m planning to get value with getElementById("answer"); when turn on back template from front template.

I already tried to write the getElementById() funtion to get the id attribute.

Calculating a bearing from co-ordinates on a cylinder(?)

im currently calculating the bearing between longitudes and latitudes of countries on a globe projection using this:

Formula:

θ = atan2( sin Δλ ⋅ cos φ2 , cos φ1 ⋅ sin φ2 − sin φ1 ⋅ cos φ2 ⋅ cos Δλ )

where φ1,λ1 is the start point, φ2,λ2 the end point (Δλ is the difference in longitude)

JavaScript:
(all angles
in radians)

const y = Math.sin(λ2-λ1) * Math.cos(φ2);
const x = Math.cos(φ1)*Math.sin(φ2) -
          Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1);
const θ = Math.atan2(y, x);
const brng = (θ*180/Math.PI + 360) % 360; // in degrees

from https://www.movable-type.co.uk/scripts/latlong.html

However, i’m trying to figure out a way to remove the distortion that the globe can have on the bearing between two countries. I thought that a flat map would work best however i would also like the map to loop around so i’m thinking a cylinder might actually be the best. However, i have no clue on how to translate this into a formula nor could i find anything online.

What are the benefits of version control? [closed]

Version control systems, such as Git and SVN, offer several invaluable benefits in software development.

Firstly, they provide a systematic and organized approach to tracking changes made to the codebase over time. This facilitates collaboration among team members, allowing them to work on different aspects of a project concurrently.

Version control ensures the preservation of a project’s history, enabling developers to revert to previous states or track the evolution of specific features. It enhances the quality of code by enabling developers to identify and fix issues promptly.

Additionally, version control fosters a collaborative and streamlined development process, minimizing conflicts and providing a structured mechanism for merging code changes.

Overall, version control is an essential tool for improving collaboration, tracking project evolution, and maintaining code integrity in the dynamic landscape of software development.

what next.js releases that were compatible with node.js14.17.0

Received a react app but it failed to work problem being, old mac-book PC version that has no capability to use dependencies of latest next code.

tried installing current node hoping it would just work but it failed, looked for node version that works with my PC and got it though failed to retrieve information on next version compatible with node.js14.17.0

how do i fix jquery not working in chrome?

My jquery code is working in vscode but when i open in chrome or any other browser, the code wouldn’t work. I was initialy working but along the line i don’t know what happened that it stopped.
Now even this:

$("h1").css("color", "red");
wouldn’t work in chrome.
This is what console is showing:

index.js:1 Uncaught TypeError: $(...).css is not a function
    at index.js:1:9

I thought maybe my jquery link from the library was not correct but when i checked the fault wasn’t from there.

I’m getting an error in Django Templates, with the event.preventDefault();

I’m made a dajngo website where if the product have a field with is_active = False, it gonna remove it from the basket in the shop.

So wrote this script in html file:

            {% if table.is_active %}
                    <div data-index="{{ table.id }}" class="table table-item">
                    <a href="{% url 'table_details' table.id %}" class="table-link">
                        <img class="table-img ib" src="{{ table.image.url }}" alt="">
                        <p class="title ib">{{ table.name }}</p>
                    </a>
                </div>
            {% else %}
                    <div data-index="{{ table.id }}" class="table table-item"></div>
                <script>
                    console.log("hello world 1")
                  $(document).ready(function (event) {
                  console.log("hello world 2")
                    event.preventDefault();
                    var tablid = $(this).data('index');
                    console.log(tablid)
                    $.ajax({
                      type: 'POST',
                      url: '{% url "basket:basket_delete" %}',
                      data: {
                        tableid: $(this).data('index'),
                        csrfmiddlewaretoken: "{{csrf_token}}",
                        action: 'post'
                      },
                      success: function (json) {
                        $('.table-item[data-index="' + tablid + '"]').remove();
                        document.getElementById("subtotal").innerHTML = json.subtotal;
                        document.getElementById("basket-qty").innerHTML = json.qty
                      },
                      error: function (xhr, errmsg, err) {}
                    });
                  })
            </script>
        {% endif %}

and in the console.log it gives me a warning and error with the same text,

# Uncaught TypeError: event.preventDefault is not a function
# at HTMLDocument.<anonymous> (basket/:116:27)
# at e (jquery-3.5.1.min.js:2:30005)
# at t (jquery-3.5.1.min.js:2:30307)

So what I did I tried to remove the line with event.preventDefault(), but then the data-index of the div stoped being used in the tablid varibale, and when I coneole.log(tablid), it show, undefined.

How to change class on several divs using onclick

I have two divs:

    <div class="gif_left">
    <div class="gif_right">

Initially, the first one has opacity 1, and the second one has opacity 0.

I want onclick function on .gif_left and change its class on .click:

.click { opacity: 0; }

And I also want that at the same onclick function change class .gif_right on:

.click2 { opacity: 1; }

When I click again, everything returns as it was.

Now I have only been able to assign onclick function to .gif_left and change its class to .click (it also works when you click again by toggleClass):

$(document).ready(function() {
  $('.gif_left').click(function () {
    $(this).toggleClass('click');
  });
});

new Date( ) is storing previously assigned values?

For a little bit of context, i’m currently working on a project where i can enter the name of a city and then get time and weather details about this specific place. The rest of the code is working fine, but it appears that whenever i search for another city, the ‘city_time’ variable will still store the previous cities’ times, and instead of showing just one time, it will loop through all of the times (previous and current) in one second.

    function displayCityTime(time_zone){
        const options = {
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
            timeZone: time_zone,
        }

        const cityTimeElement = document.getElementById('city-time')
        

        function updateClock() {
            city_time = new Date().toLocaleTimeString('pt-BR' , options)

            cityTimeElement.textContent = city_time
        }
        

        updateClock();

        setInterval(updateClock, 1000)
    }

If i search for Mumbai, where it’s 8am, then for Tokyo, where it’s 12pm, it will keep flickering between 8 and 12, and if i do more searches, it will do the same for all of them. I’ve tried using clearInterval(), but it still did not work.

why setNickname() function in discord.js is not always work?

bro.
I set the function of change the member nickname in guild for my discord robot.
The code is as follows:

function setNickname(interaction, AccountName, discordId) {

         let   dotLen = (AccountName.split('.').length - 1);
         let nickname = AccountName
         if(dotLen == 2){
            nickname = nickname.replace('.aco', '');
         }
         interaction.guild.members.cache.get(discordId).setNickname(nickname);
   
 }

After successfully running this code, the problem arises:sometimes the nickname can be changed successfully but sometimes it cannot be changed successfully.

I ensure that the relevant permissions of the robot are sufficient.

Does anyone know the reason behind this and how to fix it, thanks a lot, bro!

In my index.js, I call the function by this line of code:

await botton.setNickname(interaction,bitAccount, discordId);

‘await’ was added later by me. Before that, it was even rarer for the setnickname function to execute successfully.

So I guess it may be an asynchronous problem.

Programmatically add WooCommerce Analytics advanced filter

I’m struggling to programmatically add an advanced orders filter to Woo Analytics. The filter will be based on the value of a specific postmeta. So the filter will either show orders with a specific value on a specific postmeta, or show all the rest orders (with any other value than that on the same postmeta).

So far I did the JS part:

wp && wp.hooks && wp.hooks.addFilter('woocommerce_admin_orders_report_advanced_filters', 'add-advanced-filter', function (advancedFilters) {
    advancedFilters.filters['marketplace_orders'] = {
        labels: {
            add: 'Order Types',
            remove: 'Remove Marketplace orders filter',
            rule: 'Select Marketplace orders filter',
            title: '{{title}}Show orders{{/title}} {{filter /}}',
            filter: 'Select type of orders to show'
        },
        input: {
            component: 'SelectControl',
            options: [
                {
                    value: 'all',
                    label: 'All',
                },
                {
                    value: 'marketplace',
                    label: 'Marketplace only',
                },
                {
                    value: 'not_marketplace',
                    label: 'All but Marketplace'
                },
            ],
            defaultOption: 'all'
        }
    };

    return advancedFilters;
});

The above code creates an interface result like this:

enter image description here

enter image description here

I can’t figure out how to go from there though. Obviously this is not enough, but I’m not sure what the next step is. Any guide I found (there are no more than 2-3 ones on the subject) are not very clear and are not even marked as solved… The closer I found is this (which is based on woocommerce-admin which is a dead project anyway).

Anyone had any luck with adding such a filter?

Realtime database. When I send a put request with date 0 (just the number 0), I get an error. Other numbers work

There is a Firebase realtime database, and the anime likes function has been implemented on the website. The problems come from removing a like, it is implemented like this: a get request is made, the response contains the current number of likes and a put request is sent, setting the response to the get request minus 1.

Also, the user’s information about this anime is removed from his data, but this is not so important.

async unlikeAnime(userID, likeID, animeID) {
    const likeCount = await firebase.get(`AnimeList/${animeID}/like.json`);
    firebase.put(`AnimeList/${animeID}/like.json`, parseInt(likeCount.data - 1));
    firebase.delete(`Users/${userID}/likedAnime/${likeID}.json`);
}

Everything works fine with any numbers except 0. If a new anime is added to the site (it is displayed in the database with 0 likes), and then the user likes it (sends 1 to the database), and then removes it (sends 0 to the database), then the database will give an error and will not remove the like.

enter image description here

enter image description here

I checked whether the same types of data were sent in all situations (yes, a number), checked whether the correct response was received from a get request when there was 1 like (yes, likeCount.date returns 1 and is sent 0). I even wrote ParseInt just in case, it doesn’t help.

The get request and delete request work 100% perfectly, the problem is only in the put and only if the data is equal to the number 0. It simply cannot set the number 0 in the database and returns an error.

I checked the quality of the request, it is being created correctly. The link is fully working and correct. And I’ll also attach a link to what the database looks like.
enter image description here

how to convert the entity map to json string in javascript

I found the map in javascript could not convert to json string like this:

let m= new Map<string,string>();
m.set("a","b");
console.log("json:" + JSON.stringify(m));

the result look like: m:{} .what should I do to convert the map to json, I also found the javascript model that contains map will return {}. If the entity like this:

export interface TexFileModel { 
    id: number; 
    m: Map<string,string>
}
 

how to make sure the TexFileModel convert to json with the map datatype?

Rendering the Comment Form in React

I want to ask or advice on how to render the comment form, I have separate component for the comment form, I tried it on the code below and as expected the form is not showing when the logged in user click the reply button on the comment.

enter image description here

When the user click the reply button it showed the form as what it looks like on the image below:

enter image description here

import React from 'react';
import MainLayout from '../../components/MainLayout';
import BreadCrumbs from '../../components/BreadCrumbs';
import SuggestedPost from './container/SuggestedPost';
import SidebarLeft from '../../components/SidebarLeft';
import SidebarRight from '../../components/SidebarRight';
import { Link } from 'react-router-dom';
import { images } from '../../constants';
import './articledetail.css';
import CommentsContainer from '../../components/comments/CommentsContainer';

const breadCrumbsData = [
  {
    name: 'Home',
    link: '/',
  },
  {
    name: 'Article',
    link: '/',
  },
  {
    name: 'Article Detail',
    link: '/blog/i',
  },
];

const postData = [
  {
    id: 1,
    title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    createdAt: '2022-01-01',
  },
  {
    id: 2,
    title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    createdAt: '2022-01-01',
  },
  {
    id: 3,
    title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    createdAt: '2022-01-01',
  },
  {
    id: 4,
    title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    createdAt: '2022-01-01',
  },
  {
    id: 5,
    title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    createdAt: '2022-01-01',
  },
];

const tagsData = ['Programming', 'Development', 'Testing'];

const ArticleDetailPage = () => {
  return (
    <MainLayout>
      <div className="article">
        <div className="article-sidebar-left">
          <SidebarLeft />
        </div>
        <section className="article-detail-page">
          <article className="article-detail">
            <BreadCrumbs data={breadCrumbsData} />
            {/* Generating the BreadCrumbs from the data */}
            <div className="article-img-box">
              <img
                src={images.latestPost}
                alt="Latest Post"
                className="article-img"
              />
            </div>

            <Link
              to="/blog?category=SelectedCategory"
              className="article-category">
              Category
            </Link>
            <h1 className="article-title">Lorem ipsum dolor sit amet</h1>
            <p className="article-post">
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam
              fuga voluptatum corporis nostrum molestias aspernatur! Ad quia
              totam reprehenderit accusantium. Deserunt cumque voluptates alias,
            
            </p>
            <CommentsContainer
              className="comments-container"
              logginedUserId="a"
            />
          </article>
          <SuggestedPost
            header="Latest Article"
            post={postData}
            tags={tagsData}
          />
        </section>
        <div className="article-sidebar-right sticky">
          <SidebarRight />
        </div>
      </div>
    </MainLayout>
  );
};

export default ArticleDetailPage;

In this code/component the logginedUserId="a" is applied when the user got ID of a.

This is the container of comment form which display the comment as well as the form.

import React, { useEffect, useState } from 'react';
import CommentForm from './CommentForm';
import { getCommentsData } from '../../data/comments';
import Comment from './Comment';

const CommentsContainer = ({ className, logginedUserId }) => {
  //creating a state with empty initial
  const [comments, setComments] = useState([]);

  //Getting the main comments/parents comments
  //filtering the comments who have no parent
  const mainComments = comments.filter((comment) => comment.parent === null);
  const [afftectedComment, setAffectedComment] = useState(null);
  console.log(comments);

  //   Creating a state to reply and edit a comment

  //fill the state with the data from getCommentsData(putt all data in it)
  useEffect(() => {
    (async () => {
      const commentData = await getCommentsData();
      setComments(commentData);
    })();
  }, []);

  //this is for the comment handler
  const addCommentHandler = (value, parent = null, replyOnUser = null) => {
    //creating a variable newComment that stores the new comment
    const newComment = {
      _id: '10',
      user: {
        _id: 'a',
        name: 'Mohammad Rezaii',
      },
      desc: value,
      post: '1',
      parent: parent,
      replyOnUser: replyOnUser,
      createdAt: '2022-12-31T17:22:05.092+0000',
    };

    //adding comments to comments data
    setComments((curState) => {
      return [newComment, ...curState];
    });
  };

  return (
    <div className={`${className}`}>
      <CommentForm
        btnLabel="Add Comment"
        //passing the formSubmitHandler function with addCommentHandler
        formSubmitHandler={(value) => addCommentHandler(value)}
      />

      <div className="comments-area">
        {/* rendering the main comments/parents comments fromt the mainComments */}
        {mainComments.map((comment) => (
          <Comment
            comment={comment}
            logginedUserId={logginedUserId}
            afftectedComment={afftectedComment}
            setAffectedComment={setAffectedComment}
            addComment={addCommentHandler}
          />
        ))}
      </div>
    </div>
  );
};

export default CommentsContainer;

This the logic where I added to render the comment form if the logged in user is wanted to reply a comment to previous comment.

import React from 'react';
import { images } from '../../constants';
import { MdEditSquare, MdQuickreply, MdRemoveCircle } from 'react-icons/md';
import CommentForm from './CommentForm';

// This is a component to display a single comment
const Comment = ({
  comment,
  logginedUserId,
  affectedComment,
  setAffectedComment,
  addComment,
  parentId = null,
}) => {
  // Creating a function to render the button to reply
  const isUserLoggined = Boolean(logginedUserId);

  //   Creating Edit and Delete Function in the comments
  const commentBelongToUser = logginedUserId === comment.user._id;
  const isReplying =
    affectedComment &&
    affectedComment.type === 'replying' &&
    affectedComment._id === comment._id;
  const repliedCommentId = parentId ? parentId : comment._id;
  const replyOnUserId = comment.user._id;

  return (
    <div className="comment-box">
      <img src={images.theProfile} alt="user" className="comment-image" />
      <div className="comment-text">
        <h5 className="comment-name">{comment.user.name}</h5>
        <span className="comment-date">
          {new Date(comment.createdAt).toLocaleDateString('en', {
            day: 'numeric',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
          })}
        </span>
        <p className="comment-desc">{comment.desc}</p>
        {/* This is for the button */}
        <div className="comment-action">
          {isUserLoggined && (
            <button
              className="comment-reply"
              onClick={() =>
                setAffectedComment({ type: 'replying', _id: comment._id })
              }>
              <MdQuickreply className="comment-action-icon" />
              <span>Reply</span>
            </button>
          )}
          {commentBelongToUser && (
            <>
              <button className="comment-edit">
                <MdEditSquare className="comment-action-icon" />
                <span>Edit</span>
              </button>
              <button className="comment-delete">
                <MdRemoveCircle className="comment-action-icon" />
                <span>Delete</span>
              </button>
            </>
          )}
        </div>
        {isReplying && (
          <CommentForm
            btnLabel="Reply"
            formSubmitHandler={(value) =>
              addComment(value, repliedCommentId, replyOnUserId)
            }
          />
        )}
      </div>
    </div>
  );
};

export default Comment;

Vercel can’t delpoy due to react icons module is not found but it is actually installed

I am trying to deploy a project to Vercel but it marks down an error on the building phase, saying react icons can’t be found even if it is installed to package.json and imported correctly to the component that uses that module.

Here is the public repository where is all my code since it planned to be public: https://github.com/Benevos/react-nextjs-tailwind-juice-slider

This is the faulty component:

'use client';

import React from 'react';
import Link from "next/link";

import Navbar from "@/components/Navbar";

import { FaCircleUser } from "react-icons/fa6"; \ <---- Here is where the error shows
import { FaShoppingBag } from "react-icons/fa";

import { Londrina_Solid } from 'next/font/google';

const londrinaSolid = Londrina_Solid({weight: '400' , subsets: ['latin']});

function Header({ backgroundColor, textColor }) {
  return (
    <header id="header" style={{backgroundColor: backgroundColor, color: textColor}}
              className={`flex justify-start items-center 
                          py-4 font-semibold
                          relative transition duration-[1600ms] z-0`}>

        <Link href={"/#"} className={`text-3xl flex-initial ml-10 
                                        max-md:ml-5 ${londrinaSolid.className}`}>
            Trademark
        </Link>

        <Navbar/>

        <div className="flex text-xl gap-4 
                        flex-initial ml-auto
                        mr-10 max-md:mr-5">

            <Link href={"/#"}>
            <FaCircleUser/>
            </Link>

            <Link href={"/#"}>
            <FaShoppingBag/>
            </Link>
        </div>  

    </header>
  )
}

export default Header

This is package.json:

{
  "name": "juice-slider-vercel-fix",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "14.0.4",
    "react": "^18",
    "react-dom": "^18",
    "react-icons": "^4.12.0",
    "sass": "^1.69.5"
  },
  "devDependencies": {
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.4",
    "postcss": "^8",
    "tailwindcss": "^3.3.0"
  }
}

Vercel logs:

enter image description here

I used the suggested command by react icons documentation to install the module (npm install react-icons --save).

Already tried to start a fresh project installing react icons at beggining and importing all the source code but still not working.

I also checked deploy my next.js project on vercel, Cannot find module ‘react-icons/Fa’ or its corresponding type declarations but seems not to be the problem.

Someone knows what could be the problem, please?

activeCell.getRow is not a function

Attempting to use Google Scripts + followed a vid, but debugger is giving me a “activeCell.getRow is not a function” error despite it working in the video I followed.

Video I followed: https://www.youtube.com/watch?v=Lk40x6lzDwA&ab_channel=PracticalSheets

I formatted my own spreadsheet exactly like his, still failing. Any help here would be greatly appreciated!

Here’s the code I’ve tried using so far:

function dropdown() {
  var activeCell=SpreadsheetApp.getActiveRange;
  var activeRow=activeCell.getRow()
  var activeCol=activeCell.getColumn()
  var activeValue=activeCell.getValue()
  var activeSheet=activeCell.getSheet()

  if(activeSheet.getName()=="Main Sheet" && activeRow>1 && activeCol==1){
    var worksheet=SpreadsheetApp.getActiveSpreadsheet();
    var spreadsheet=worksheet.getSheetByName("Data")
    var data=spreadsheet.getDataRange().getValues();
    var list=data.filter(row=>row[0]==activeValue).map(row=>row[1])
    var validation=SpreadsheetApp.newDataValidation().requireValueInList(list).setAllowInvalid(false).build()
    activeCell.offset(0,1).setDataValidation(validation)
}
}

function onEdit(){
  dropdown()
}