How to parse dates and times from users in many formats? [closed]

I’d like to be able to parse a date/time given by the user into a Date (or luxon DateTime object). I don’t know the user’s format beforehand. They’ll likely be copy-pasting it from another source so I’d prefer not to force a particular format.

Perl has Date::Parse exactly for this and it works brilliantly.

What is the JavaScript equivalent?

The timestamp could come e.g. in any of these formats, or others:

  • Fri Sep 20, 2024 04:07PM
  • 2024-09-22 04:07:00-0700
  • 2024-09-20 04:07:00
  • 2024-09-20 04:07
  • 9/20 4:07
  • 20/9 4:07
  • 4:07
  • Sep 20, 4:07
  • Sep 20

When there is ambiguity, I’d like the last instance, so e.g. 4:07 refers to the last time it was 4:07. And for e.g. “2/3” which could be Mar 2 or Feb 3, just pick one of them.

  • luxon seems to be king of the hill at the moment. Its DateTime.fromFormat does it perfectly. It can take a zone as one of its options, and if the given format and string doesn’t contain time zone information, the zone parameter controls which time zone fromFormat will interpret the time stamp in. But with DateTime.fromFormat I’m locked into having to specify a fixed format known beforehand.

    But I apparently can’t get luxon to try its best without a format string. Is there such a thing as moment-guess for luxon or other ways to get luxon to do this?

  • new Date(str)

    Date.new() on Chrome does a pretty good job of guessing the Date from any string you throw at it, but Apr 1 gets interpreted as Sun Apr 01 2001 00:00:00 GMT+0200 (Central European Summer Time) which has two problems: 2001 is not the most recent and there is no way to tell new Date() which time zone to use. It always uses the local time zone. Also, apparently implementations are inconsistent

  • moment.js is deprecated

  • Temporal isn’t here yet.

  • date-fns’s parse needs a format string

  • js-joda’s DateTimeFormatter.ofPattern needs a format string

  • dayjs either needs a format string or assumes ISO 8601 format.

Unable to get the value from BehaviorSubject in angular on interceptor refer the below

**
common.service.ts
**

Login service has been created.

export class CommonService {

  public tokenSubject: BehaviorSubject<UserToken>;
  public token: Observable<UserToken>;
  constructor(private httpclient: HttpClient,
              private router: Router
  ) { 
    this.tokenSubject = new BehaviorSubject<UserToken>(JSON.parse(localStorage.getItem('access_token') as string));
    this.token = this.tokenSubject.asObservable();
  }

  private commonApi = `${Appsettings._ApiEndpoint}`;

  login(data: any): Observable<any> {
    return this.httpclient.post<UserToken>(`${this.commonApi}api/user/user-login`, {loginData: data})
    .pipe(
      map(token => {
        const userToken: UserToken = token;

        localStorage.setItem('access_token' , JSON.stringify(userToken));
        this.tokenSubject.next(userToken);

        return userToken;
      })
    );
  }
}

 public get tokenValue(): UserToken {   
    return this.tokenSubject.value;
  }

**
user.ts
**

export class UserToken {
    token: string;
}

**
login.component.ts
**

Login service being called, passed with requested data.

constructor(private commonservice: CommonService,
              private router: Router
  ) { }


 login(formData:NgForm, isValid: any) {
    if(isValid) {
      this.commonservice.login(formData.value)
      .subscribe((data: any) => {
        console.log('login data : ' , data);
        this.router.navigateByUrl('/dashboard');
      }, error => {
        console.log('error : ' , error);
        alert(error.error.message);
      })
    }
    
  }

We are getting null in tokenObj and isLoggedIn console.log() Can you please help to correct what are the wrong here. And also please help to better and deep understanding how to get the value from BehaviorSubject RxJs in angular. Kindly refer the given snapshot, How will we get the data from BehaviorSubject.

**
request.interceptor.ts
**

We are unabel to get the token value on interceptor.

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    this.spinner.show();
    
    const tokenObj = this.commonService.tokenValue;
    console.log('tokenObj : ' , tokenObj);
    const isLoggedIn = tokenObj && tokenObj.token;  
    console.log('isLoggedIn : ' , isLoggedIn);
    if(isLoggedIn) {   
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${tokenObj.token}`
        }
      })
    }
    return next.handle(request).pipe(
      tap(
        event => {
          if(event instanceof HttpResponse) {
            console.log('success in calling API : ', event);
            this.spinner.hide();
          }
        },
        error => {
          console.log('error in calling API : ', error);
          this.spinner.hide();
        }
      )
    );
  }

enter image description here

How to send an ArrayBuffer as binary in a multipart/form-data request using JavaScript?

I’m trying to send a file (such as a PNG image) as binary data using a multipart/form-data request in JavaScript. I want to ensure that the file’s binary data is sent correctly without converting it to characters (which corrupts the binary data).

Currently, I have a File object that I convert to an ArrayBuffer:

const fileContent = await fileData.file.arrayBuffer();

I want to append this binary data to the request body in a multipart/form-data format. However, I’m not sure how to correctly iterate over the ArrayBuffer and append the binary data as-is.

Here’s a simplified version of what I’m doing:

// Now, I want to append the binary content to the body
const uint8Array = new Uint8Array(fileContent);

for (let i = 0; i < uint8Array.length; i++) {
  body += String.fromCharCode(uint8Array[i]); // This corrupts binary data
}

// Then I send `body` in a POST request


This works for text files, but it corrupts the png, pdf…

I tried everything. I know there are other ways of sending a request, but i had other problems when trying it like that. So i am basically stuck with this one.

Using cookies storage on Next.js app with Amplify Auth

I am currently creating a website with Next.js where I am using Amplify to authenticate my users. But the problem is that Amplify stores user’s session including tokens on browser’s localStorage which I think is not secure.

Is it more secure to use cookiesStorage instead and how can I configure Amplify to store user’s session in cookiesStorage

Abort Controller does not cancel All the pending requests

In my project all the requests goes through a single fetch function. In that I am storing all the abort controller inside and global set. When the user swictches to another page I will call the global set and abort all fetch requests that are waiting for response. If a response is received for a req I remove its controller from the set.

But the problem is not all requests are cancelled. When I try only a fraction of requests are getting cancelled.

Fetch Req-

 const controller = new AbortController();
            const request = { urlString, controller };
            requests.activeRequests.add(request);
            const signal = controller.signal;

            fetch(urlString, {
                headers: headers,
                method: method,
                signal: signal,
                body: payload ? JSON.stringify(payload) : undefined,
                credentials: 'include' 
            }).then(async (response) => {
                if (response.status === 200 || response.status === 204) {
                    requests.activeRequests.delete(request);

and this code is executed when user switches to other page

requests.activeRequests.forEach((req)=>{
                req.controller.abort();
                requests.activeRequests.delete(req)
            })

Can someone help me understand why only some requests are cancelled, What am i doing wrong?

How to retain scrollbar position even after reloading using javascript

After clicking on any lower check box in the grid the vertical scrollbar position changed to top level in the grid. How to keep the vertical scrollbar in same position after reloading the grid.?

after clicking on any checkbox the grid will be empty and it’s reload again .

this.grid.empty();

I have tried for keeping scroll position on same position using localstorage & session storage get setItem, but it didn’t work.

spacemacs configuration for react (MERN)

How do I set spacemacs for programming in react js (MERN)? I enabled all possible layereas, but I get a constant error: “LSP : : Error on the language server side: Request initialize failed with message: Can’t find typescript.js or tsserverlibrary.js in “” (Internal Error)”. I have installed typescript and in bash it finds the path to typescript. I use Linux Mint Cinnamon.

I tried to write the path manually to the typescript install location in .spacemacs, but it still doesn’t work. It doesn’t autocomplete my js or jsx files, but it works in the .spacemacs file. I would be very grateful with a concrete example of a .spacemacs setup file.

Getting `Unsupported request – method type: post` when trying to create an ad account with the Facebook API,use python

“media_agency”: “{my_fb_app_id}”,
“partner”: “NONE”,
“funding_id”: “{my_funding_id}”
}
According to the docs, a POST endpoint is available and valid.I’ve checked if the payment method behind the funding ID is active and valid and it is. It’s assigned to other ad accounts as well and I’m spending money with it.

Fetch request does not return results

I send a request to the site and it takes forever, I get no response or error.

async getCookies() {
return await fetch(`https://portal.elpts.ru/portal/`, {
  method: "GET",
  headers: {
    "User-Agent": this.userAgent,
  },
  follow: "manual",
  agent: this.agent,
}).then(res => {
  console.log('res: ', res)
  return res.headers.get("set-cookie")})
  .catch(err => {
    console.log('err: ', err)
    return err
  });

userAgent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

I add intermediate certificate of this site using ssl-root-cas

import sslRootCas from 'ssl-root-cas';
sslRootCas.addFile('/path/to/GlobalSign_GCC.crt')
sslRootCas.inject();

Without this certificate I get an error

Error during task execution: FetchError: request to https://portal.elpts.ru/portal/index failed, reason: unable to verify the first certificate

errno: ‘UNABLE_TO_VERIFY_LEAF_SIGNATURE’

Site certificates via browser viewer tool

Adding the root certificate and the _.elpts certificate does not affect the requests in any way, only the presence of the GlobalSign GCC R3 DV TLS CA 2020 intermediate certificate determines whether there will be an error. When adding these additional certificates, the request still lasts forever, without returning either a result or an error

React application not getting status of Jenkins Pipeline

I am creating an application in which there is a Jenkins Pipeline responsible for cloning repository and running megalinter on it and then when the process is completed the megalinter.log file is cleaned and issues are shown in Issues.jsx page. Till the pipeline build process is going on there is a animation under which the pipeline status is shown but following errors are seen

-Even when the pipeline is triggered successfully then too just after few seconds these errors are seen in the console log.
-There are no articafts being fetched even when the build is completed
-The stages of animation is showing failed in few seconds but pipeline is triggred in jenins so I don’t know what’s causing these erros.
Erros(All these errors are just after few seconds)

network tab

I don’t know from where that 147 is coming I am not even using that url

I tried these things in code
Jenkins Pipeline

pipeline {
    agent any

    environment {
        NODEJS_HOME = tool name: 'NodeJS', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation'
        PATH = "${env.NODEJS_HOME}/bin:${env.PATH}"
    }

    parameters {
        string(name: 'REPO_URL', defaultValue: '', description: 'URL of the Git repository to analyze')
    }

    stages {
        stage('Clone Repository') {
            steps {
                script {
                    try {
                        git url: "${params.REPO_URL}", branch: 'main'
                    } catch (Exception e) {
                        echo "Main branch not found, trying master branch"
                        git url: "${params.REPO_URL}", branch: 'master'
                    }
                }
            }
        }
        stage('Run MegaLinter') {
            steps {
                script {
                    try {
                        bat "npx mega-linter-runner --flavor cupcake --release v6"
                    } catch (Exception e) {
                        echo "MegaLinter found issues, but continuing pipeline"
                    }
                }
            }
        }
    }

    post {
        always {
            archiveArtifacts artifacts: 'megalinter-reports/**', allowEmptyArchive: true
            cleanWs()
        }
    }
}

Issues.jsx page code

const Issues = () => {
  const { repoName } = useParams();
  const [buildStage, setBuildStage] = useState('Initializing');
  const [issues, setIssues] = useState([]);
  const [filteredIssues, setFilteredIssues] = useState([]);
  const [filters, setFilters] = useState({
    severity: "",
    language: "",
    linter: ""
  });

  useEffect(() => {
    let isMounted = true;
    let intervalId;
  
    const runPipeline = async () => {
      try {
        setBuildStage('Triggering Pipeline');
        await triggerPipeline({ name: repoName });
        
        if (!isMounted) return;
        setBuildStage('Waiting for Build');
        
        let lastBuildNumber = null;
  
        const pollBuildStatus = async () => {
          try {
            const { isBuilding, result, number } = await checkBuildStatus();
            
            if (number !== lastBuildNumber) {
              lastBuildNumber = number;
              console.log(`New build started: #${number}`);
            }
  
            if (!isBuilding && result) {
              clearInterval(intervalId);
              if (result === 'SUCCESS') {
                if (isMounted) {
                  setBuildStage('Fetching Results');
                  const results = await getBuildResults(number);
                  await processMegaLinterResults(results.megaLinterLog);
                  setBuildStage('Complete');
                }
              } else {
                if (isMounted) setBuildStage(`Failed: ${result}`);
              }
            }
          } catch (error) {
            console.error('Error in pollBuildStatus:', error);
            if (isMounted) setBuildStage('Failed: Error checking status');
          }
        };
  
        intervalId = setInterval(pollBuildStatus, 5000); // Check every 5 seconds
      } catch (error) {
        console.error('Error in pipeline process:', error);
        if (isMounted) setBuildStage('Failed: Error triggering pipeline');
      }
    };
  
    runPipeline();
  
    return () => {
      isMounted = false;
      if (intervalId) clearInterval(intervalId);
    };
  }, [repoName]);

  const processMegaLinterResults = (logContent) => {
    try {
      const processedIssues = [];
      const lines = logContent.split('n');
      
      let currentLinter = '';
      let currentFile = '';
  
      for (const line of lines) {
        if (line.startsWith('Linter:')) {
          currentLinter = line.split(':')[1].trim();
        } else if (line.startsWith('File:')) {
          currentFile = line.split(':')[1].trim();
        } else if (line.includes('|')) {
          const [lineNumber, column, level, message] = line.split('|').map(item => item.trim());
          processedIssues.push({
            message,
            linter: currentLinter,
            file: currentFile,
            severity: level,
            line: lineNumber,
            column
          });
        }
      }
  
      setIssues(processedIssues);
      setFilteredIssues(processedIssues);
    } catch (error) {
      console.error('Error processing MegaLinter results:', error);
    }
  };


  useEffect(() => {
    const filtered = issues.filter(issue => 
      (!filters.severity || issue.severity === filters.severity) &&
      (!filters.language || issue.language === filters.language) &&
      (!filters.linter || issue.linter === filters.linter)
    );
    setFilteredIssues(filtered);
  }, [issues, filters]);

  const handleFilterChange = (filterType, value) => {
    setFilters(prev => ({ ...prev, [filterType]: value }));
  };

  return (
    <div className='flex'>
      <Sidebar>
        <SideBarItem link="/user/dashboard" icon={<Home size={20} />} text="Home" alert />
        <SideBarItem link={`/user/dashboard/repos/${repoName}`} icon={<BarChart4 size={20} />} text="Details" alert />
        <SideBarItem link={`/user/dashboard/repos/${repoName}/issues`} icon={<Bug size={20} />} text="Issues" />
        <SideBarItem link={`/user/dashboard/repos/${repoName}/commits`} icon={<GitCommitVertical size={20} />} text="Commits" />
        <SideBarItem link={`/user/dashboard/repos/${repoName}/pull-requests`} icon={<GitPullRequestIcon size={20} />} text="Pull Requests" />
        <SideBarItem link="/user/dashboard/help" icon={<HandHelping size={20} />} text="Help" />
      </Sidebar>
      <div className="p-4 flex-grow">
        <h1 className="text-2xl font-bold mb-4">Issues of {repoName}</h1>
        {buildStage !== 'Complete' ? (
          <div className="flex flex-col items-center justify-center h-64">
            <div className="loader"></div>
            <p className="mt-4">Status: {buildStage}</p>
          </div>
        ) : (
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-grow bg-black shadow-md rounded-lg p-6">
              <h2 className="text-xl font-semibold mb-4">Mega Linter Results</h2>
              <div className="overflow-x-auto">
                <table className="min-w-full bg-black">
                  <thead className="bg-gray-100">
                    <tr>
                      <th className="py-2 px-4 border-b text-left">S.No</th>
                      <th className="py-2 px-4 border-b text-left">Issues</th>
                      <th className="py-2 px-4 border-b text-left">Linter</th>
                      <th className="py-2 px-4 border-b text-left">File</th>
                      <th className="py-2 px-4 border-b text-left">Severity</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredIssues.map((issue, index) => (
                      <tr key={index} className={index % 2 === 0 ? 'bg-gray-50' : 'bg-black'}>
                        <td className="py-2 px-4 border-b">{index + 1}</td>
                        <td className="py-2 px-4 border-b">{issue.message}</td>
                        <td className="py-2 px-4 border-b">{issue.linter}</td>
                        <td className="py-2 px-4 border-b">{issue.file}</td>
                        <td className="py-2 px-4 border-b">{issue.severity}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
            
            <div className="w-full md:w-64 bg-black shadow-md rounded-lg p-6">
              <h2 className="text-xl font-semibold mb-4">Filters</h2>
              <div className="space-y-4">
                <div>
                  <label htmlFor="severity" className="block text-sm font-medium text-gray-700">Severity</label>
                  <select
                    id="severity"
                    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
                    onChange={(e) => handleFilterChange('severity', e.target.value)}
                  >
                    <option value="">Select severity</option>
                    {['Low', 'Medium', 'High'].map((option) => (
                      <option key={option} value={option}>{option}</option>
                    ))}
                  </select>
                </div>
                
                <div>
                  <label htmlFor="language" className="block text-sm font-medium text-gray-700">Language</label>
                  <select
                    id="language"
                    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
                    onChange={(e) => handleFilterChange('language', e.target.value)}
                  >
                    <option value="">Select language</option>
                    {[...new Set(issues.map(issue => issue.language))].map((option) => (
                      <option key={option} value={option}>{option}</option>
                    ))}
                  </select>
                </div>
                
                <div>
                  <label htmlFor="linter" className="block text-sm font-medium text-gray-700">Linter</label>
                  <select
                    id="linter"
                    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
                    onChange={(e) => handleFilterChange('linter', e.target.value)}
                  >
                    <option value="">Select linter</option>
                    {[...new Set(issues.map(issue => issue.linter))].map((option) => (
                      <option key={option} value={option}>{option}</option>
                    ))}
                  </select>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Issues;

Controller functions

export const triggerPipeline = async (repo) => {
  try {
    if (!repo || !repo.name) {
      throw new Error('Invalid repository information');
    }

    const { data: { user }, error } = await supabase.auth.getUser();
    if (error) {
      throw new Error('Failed to fetch user data');
    }

    const githubUsername = user.user_metadata.user_name;
    if (!githubUsername) {
      throw new Error('GitHub username not found in user metadata');
    }

    const response = await fetch('http://localhost:8080/job/generate-issues/buildWithParameters', {
      method: 'POST',
      headers: {
        'Authorization': 'Basic ' + btoa('username:password'),
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: `REPO_URL=https://github.com/${githubUsername}/${repo.name}.git`,
    });

    console.log('Response status:', response.status);
    console.log('Response headers:', JSON.stringify(Object.fromEntries(response.headers)));

    if (response.status === 201 || response.status === 303) {
      console.log('Jenkins pipeline triggered successfully');
      return { message: 'Pipeline triggered successfully' };
    } else {
      throw new Error(`Failed to trigger Jenkins pipeline: ${response.status}`);
    }
  } catch (error) {
    console.error('Error triggering Jenkins pipeline:', error);
    throw error;
  }
};

export const checkBuildStatus = async () => {
  const buildUrl = 'http://localhost:8080/job/generate-issues/lastBuild/api/json';
  const authHeader = 'Basic ' + btoa('username:password');

  try {
    const response = await fetch(buildUrl, {
      headers: {
        'Authorization': authHeader
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch build status: ${response.status}`);
    }

    const buildData = await response.json();
    console.log('Build data:', buildData);

    return { 
      isBuilding: buildData.building,
      result: buildData.result,
      number: buildData.number
    };
  } catch (error) {
    console.error('Error checking build status:', error);
    return { isBuilding: false, result: 'ERROR', number: null };
  }
};

export const getBuildResults = async (buildNumber) => {
  const logUrl = `http://localhost:8080/job/generate-issues/${buildNumber}/artifact/megalinter-reports/megalinter.log`;
  const authHeader = 'Basic ' + btoa('username:password');

  try {
    const response = await fetch(logUrl, {
      headers: {
        'Authorization': authHeader
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch MegaLinter log: ${response.status}`);
    }

    const megaLinterLog = await response.text();
    return { megaLinterLog };
  } catch (error) {
    console.error('Error fetching MegaLinter log:', error);
    throw error;
  }
};

Context api values reading NaN when used for calculation in a function but returns as a number when logged to the console individually

I’m trying to get the percent of a number using numbers gotten from an api endpoint which I saved globally using context api but each time I pass the number to the function doing the calculation it returns NaN but when I log the inputs used for the calculation on the console it shows the actual numbers.

import React, { createContext, useState, useContext } from "react";
import { FormatNum } from "../utils/FormatNum";
import { useFetchUsersData } from "../hooks/useFetchUsersData";

const UserContext = createContext();

export const UserProvider = ({ children }) => {
  const onError = (error) => {
    console.log("Error:", error);
  };

  const enabled = true;
  const endpoint = "growthData";
  const { data } = useFetchUsersData({ endpoint, enabled, onError });

  const totalUser = data?.data.reduce((accumulator, currentItem) => {
    return accumulator + currentItem.users;
  }, 0);

  const totalActiveUsers = data?.data.reduce((accumulator, currentItem) => {
    return accumulator + currentItem.activeUsers;
  }, 0);

  const [totalUsers, setNumberOfUsers] = useState(Number(totalUser));
  const [activeUsers, setActiveUsers] = useState(Number(totalActiveUsers));
  const [percentActiveUsers, setPercentActiveUsers] = useState(0);

  const calculatePercent = (total) => {
    console.log("value:", total);
    if (total && total > 0) {
      return (activeUsers / totalUsers) * 100;
    }
    return 0; // Return 0 if totalUsers is not valid or zero to avoid NaN
  };

  const updateNumberOfUsers = (newNumber) => {
    setNumberOfUsers(FormatNum(newNumber));
  };

  const updateActiveUsers = (newNumber) => {
    setActiveUsers(FormatNum(newNumber));
  };

  const updatePercentActiveUsers = (newNumber) => {
    setPercentActiveUsers(FormatNum(newNumber));
  };

  return (
    <UserContext.Provider
      value={{
        totalUsers,
        updateNumberOfUsers,
        activeUsers,
        updateActiveUsers,
        percentActiveUsers,
        updatePercentActiveUsers,
        calculatePercent,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

// Custom hook to use the UserContext
export const useUserContext = () => {
  return useContext(UserContext);
};

This is were I’m passing in my data from because every other thing I tried didn’t work

import React from "react";
import { HiOutlineUsers } from "react-icons/hi2";
import { useUserContext } from "../../context/usersData";
import ActiveUsersPieChart from "../Charts/ActiveUsersPieChart";

const ActiveUsersPieCard = () => {
  const {
    activeUsers,
    totalUsers,
    percentActiveUsers,
    updatePercentActiveUsers,
    calculatePercent,
  } = useUserContext();

  console.log(totalUsers);
  const percent = calculatePercent(totalUsers);
  updatePercentActiveUsers(Number(percent));
  console.log(percent);
  console.log(activeUsers);
  console.log(totalUsers);

  return (
    <div className="md:w-full md:h-[430px] flex flex-col bg-blue-800 shadow-md rounded-lg p-5">
      <section className="md:ml-4">
        <div className="flex gap-2 items-center">
          <HiOutlineUsers size={20} />
          <h3 className="text-xl">Percentage of users active</h3>
        </div>
        <p className="text-2xl font-semibold mt-2 mb-5">{percentActiveUsers}</p>
      </section>

      <ActiveUsersPieChart />
    </div>
  );
};

export default ActiveUsersPieCard;

Error changing styles in Monaco Editor React with deltaDecorations

I’m having trouble changing the characters in the Monaco Editor that don’t match a specific variable (text1). My goal is to apply a bg-red-600 style only to the incorrect characters, but if there’s an error, all subsequent characters are highlighted with bg-red-600, even if they are correct.

I asked ChatGPT for help, but the solution it provided overwrote all the text in the editor and caused performance issues. Any advice on how to fix this efficiently?

This is my code:

import Editor from '@monaco-editor/react';
import { getTheme } from '../models/StylesEditor';
import { useEditorContext } from '../context/EditorContext';

export const CodeEditor = () => {
    const text1 = `const num1 = 25;
const num2 = 5;
const result = num1 / num2;
console.log(result)`;
    const textLines = text1.split('n')

    const { config, themeEditor } = useEditorContext();
    const eventKey = useRef(null);
    const monacoObj = useRef(null);
    const [value, setValue] = useState('');

    const onValueChange = (newValue, event) => {
        eventKey.current = event;
        setValue(newValue);
    };

    const handleEditorDidMount = (editor, monaco) => {
        monaco.editor.defineTheme('my-theme', getTheme(themeEditor));
        monaco.editor.setTheme('my-theme');
        monacoObj.current = { editor, monaco };
    };

    useEffect(() => {
        if (!monacoObj.current) return;
        const { editor, monaco } = monacoObj.current;
        const e = eventKey.current?.changes[0]
        const eR = e.range;
        const verification = textLines[eR.startLineNumber - 1][eR.startColumn - 1] !== e.text && e.text !== ""
        const classDeco = verification ? 'bg-red-600' : 'bg-transparent'
        const newDecoration = {
            range: new monaco.Range(eR.startLineNumber, eR.startColumn, eR.startLineNumber, eR.startColumn + 1),
            options: { inlineClassName: `${classDeco}` }
        }
        editor.deltaDecorations([], [newDecoration])
    }, [value]);

    return (
        <div className="h-full w-full flex items-center justify-center">
            <Editor
                {...config}
                onMount={handleEditorDidMount}
                value={value}
                onChange={onValueChange}
            />
        </div>
    );
};

Flutter slide animation when widget change data

I create a animation on jetpack compose. How can I create it in Flutter?

Jetpack compose code:

@Composable
fun Greeting( modifier: Modifier = Modifier) {
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        val isVisible = remember { mutableStateOf(true) }

        Button(
            onClick = {
                isVisible.value = !isVisible.value
            }
        ) {
            Text(text = "Button")
        }

        AnimatedContent(
            targetState = isVisible.value,
            modifier = modifier
                .fillMaxWidth()
                .weight(1f),
            content = {
                if (it) {
                    Box(modifier = Modifier.background(Color.Red))
                } else {
                    Box(modifier = Modifier.background(Color.Green))
                }
            },
            transitionSpec = {
                slideInHorizontally(
                    initialOffsetX = { if (isVisible.value) -it else it },
                ) togetherWith slideOutHorizontally(
                    targetOffsetX = { if (isVisible.value) it else -it },
                )
            },
            label = "Animation"
        )
    }
}

I tried animated switcher but not worked like I expected.

Translate emit intercept in plugin from vuejs 2 to 3

I’m slowly marching a resonable sized project from vuejs 2 to 3, keeping with the Options API for now. The previous developer created a plugin that intercepted all emits so they could be logged every time an emit was called in a component. I’m uncertain how to translate this to vuejs 3 aside that the first parameter is now an app instance versus Vue. Here is the relevant plugin block:

function plugin (Vue, options = {}) {
  ...
  const emit = Vue.prototype.$emit
  Vue.prototype.$emit = function (...args) {
    const from = this.$vnode ? this.$vnode.tag : 'Event without vnode'
    if (args.length > 1) {
      log.event(`Event "${args[0]}" from ${from}: `, ...args.slice(1))
    } else {
      log.event(`Event "${args[0]}" from ${from}`)
    }
    emit.apply(this, args)
  }
...

My best guess is with defineEmit, but not quite seeing it.