How to keen the “r” characters in a string without any carrige return [closed]

I have an array where each element represents some text in a given language.
One of the languages is Coptic. Some of the text incudes the “r” characters as part of the language charcters (which the CSS font interprets into some Coptic letter when the text is rendred in an html element):

example:

"`mmoc nN`èrhi de 'en pi`èabot `èmma"

The “r” in “èrhi” represents some Coptic character not a carrige return.

I tried replacing r by \r in my string. I also tried to replace it by \r. It didn’t work.

How to force javascript to deal with “r” as normal string and ignore the escape characther before the letter “r”?

Getting 400 Bad Request Error When Making POST Request to obtain JWT Token Using HttpService in NestJS

I’m developing a NestJS application where I need to obtain a JWT token by making a POST request. I’m utilizing the HttpService from the @nestjs/common library. However, I consistently encounter a 400 Bad Request error.

Here’s the code using HttpService to get JWT token:

import {
  HttpService,
  InternalServerErrorException,
} from "@nestjs/common";


export class JwtService {
 constructor(private httpService: HttpService, private cache: CacheService) {}
private getAuthToken(): Observable<OAuth> {
    const url = 'endpoint_url';
    const body = JSON.stringify({
      "client_id": 'XXXXXXXXXXXXXXX',
      "client_secret": 'XXXXXXXXXXXXX',
      "grant_type": "client_credentials",
    });

    const headers = { "Content-Type": "application/json" };
    return this.callAPI(url, body, headers);
  }

private callAPI(
    url: string,
    body,
    headers: { [key: string]: string }
  ): Observable<any> {
        return this.httpService.post(url, body, headers).pipe(
          map((result: AxiosResponse<any>) => result.data),
          tap((result: any) => {
            const { access_token } = result; // eslint-disable-line
            this.cache
              .set("authToken", access_token, {
                ttl: env.SECONDS_TO_EXPIRE,
              })
              .subscribe();
          }),
          catchError((err: any) => {
            return throwError(
              new InternalServerErrorException(err.message, "Auth Service")
            );
          })
        );
      })
  }
}
}

Here’s what I’ve already tried:

  1. Other APIs: I tested the same code with other APIs, and it worked flawlessly. The issue seems specific to the JWT token API.
  2. Postman Success: When I manually send the request using Postman (same URL, body, and headers), I successfully receive the token.
  3. Body Format: I attempted using a plain object for the request body instead of a JSON object, but the error persists.
  4. Fetch API: I also experimented with the fetch() API, and it returned the expected response (code snippet below).

Sample code using fetch api:

const req = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        client_id: XXXXXXXXXX,
        client_secret: XXXXXXXXXXX,
        grant_type: XXXXXXXXXXX,
      }),
    };
    fetch('jwt_token_endpoint', req)
      .then((response) => response.json())
      .then((data) => {
        this.logger.log(`Success retrieving jwt token`);
        console.log(data);
        this.jwtSubject.next(`${data.token}`);
      })
      .catch((error) => {
        this.logger.error(`Error retrieving jwt token: ${error}`);
      });

I am looking for an assistance to resolve the error and get the token successfully.

How to loop through data a certain number of times in Svelte

I’ve successfully connected my app to supabase – and it’s fetching data from a table I’ve recently setup.

I’ve got the law-firm names appearing in a card template, so there’s a seperate card for each h3 being pulled in.

I want to be able to loop through my database, and after fetching 4 sets of data (the law-firm name) I want to create a duplicate row underneath – fetch another 4 and continue this way (I’ll sort out the pagination at a later date).

Any help would be appreciated as this is the first time I’ve used Svelte – and I’ve gone through multiple SO posts, as well as the svelte-kit documentation.

<script>
    export let data;
</script>

<ul class="flexCards">
    {#each visibleLawFirms as LawF}
        <li class="cardShape">
            <h3>{LawF.lawfirmname}</h3>
        </li>
    {/each}
</ul>

Need an anchor tag to download a binary file inside a td table cell

I’m trying to achieve something like I’ve shown in the image.

When an user clicks on that anchor tag, a fileselector should appear and binary (.bin) file has to get downloaded in the location where user selects. (https://i.stack.imgur.com/OGhw1.png)

I’ve created ‘a’ tag, and set all the attributes like ‘download’, ‘filename’ etc.
But, I’m not able to download it. I’m implementing it in a webview of VSCode extension.

I don’t want to post the complete code as previously question got closed due to some confusion. So, please help me with the ways/code to achieve this from scratch. Thanks in advance.

Warning: Functions are not valid as a React child – How to properly call functions in a child component?

// Parent Component

const handleViewPackage = (itemId) => {
  const currentItem = packageLists.content.find((e) => e.id === itemId);
  dispatch(
    openUpdatePackageModal({ isOpen: true, packageData: currentItem })
  );
};
    const manageListsItems = packageLists.content && packageLists.content.length > 0
    ? packageLists.content.map((item) => ({
      id: item.id,
      name: item.divisionName,
      division: item.divisionName,
      status: item.packageStatus,
      session: item.durationTime + " " + item.durationType,
      cost: item.cost,
      imageUrl: getImageOnDivisionName(item.divisionName),
      action: () => handleViewPackage(item.id),
    }))
  : [];


// Child Component
 
    function ChildComponent({ item }) {

    const handleAction = () => {

    item.action(); 
    };

    return (

    <li onClick={handleAction}></li>

    );

}

While refreshing the page, I’m facing the warning: “Functions are not valid as a React child.” This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

Angular ngbmodal: prevent closing of form modal if there is error from backend validation

Many components will use this modal hence used a dynamic approach where on adding a food item, a modal with a form will open to let the user add his details. However, for the check on backend for duplicate items, i can only retrieve that after the api call has finished.

The thing is I dont want the modal to be close if there is error as user has to fill all his details again.

Here is my code. I have used third party libraries for modal and toast.

food.component.ts :

addFood(data: any){
    this.api.request('foodItem', 'POST', data).subscribe({
        next: (response: any) => {
            if (response.message == 'Added Successfully.') {
                this._toastService.showSuccess('Food added.');
            } else {
                this._toastService.showError(response.message);
            }
        },
        complete: () => this.getFood(),
        error: (error: any) => this._toastService.showError(error.message)
    });
}

food-component.html

 <app-custom-table [tableData]="tableData" [form]="formData" [columnArray]="columnArray" (onAdd)="addFood($event)" (onEdit)="editFood($event)"></app-custom- 
 table>

custom – table.component.html

<button type = "button" class="btn btn-link"(click) = "openModal()"[disabled] = "isRowSelected"><span>Add</span></button>
<button type="button" class="btn btn-link"(click) = "openModal(selectedRow)"[disabled] = "isRowNotSelected"></i><span>Edit</span></button>

custom – table.component.ts :

openModal(rowData: any = null) {
    const config: Partial<DynamicFormComponent> = {
        form: this.form,
        data: rowData
    };

    const options: NgbModalOptions = { size: 'sm', centered: true };

    this.ModalService.show((DynamicFormComponent), config, options).subscribe((result: any) => {
        if (result.Success == true && result.Data) {
            if (rowData) {
                const updatedRowData = { ...rowData, ...result.Data };
                // If rowData is provided, it's an edit operation
                this.onEdit.emit(updatedRowData);
            } else { //add
                this.onAdd.emit(result.Data);
            }
        }
    });
}

Chrome notifications onButtonClicked not working?

I am creating a chrome extension for a personal project and I am stuck on getting the chrome notification to work. I have created the chrome notification as shown below, and added listeners for both onClicked and onButtonClicked. I added console logs for each of the following:

  • listeners added
  • notification created
  • button clicked
  • notification clicked
    To my understanding, I should see logs for all items listed, but I do not see the button clicked being logged. Here are the codes for both the notification creation and the listener addition.
// Function to create a notification
function createNotification() {
  chrome.notifications.create(
    NOTIFICATION_ID,
    {
      type: "basic",
      title: "Notification",
      message: "Message",
      iconUrl: "icons/air-horn.png",
      buttons: [{ title: "OK" }],
    },
    function () {
      console.log("notification created");
    }
  );
}

// Function to add listener for button clicks
function addNotificationListener() {
  chrome.notifications.onButtonClicked.addListener(function(notificationId) {
    console.log("Button clicked", notificationId);
  });
  chrome.notifications.onClicked.addListener(function (notifica`your text`tionId) {
    console.log("Notification clicked:", notificationId);
  });
  console.log("added");
}

addNotificationListener();

To further clarify, I have verified that my manifest contains the notification permission, and this is running in my background script. I have also referred to the chrome.notifications api but nothing seems to work. Everything else outside the code chunk behaves as expected. The only reference to the code chunk above would be the trigger to create the notification. I also have a runtime message listener but I do not believe that that is the cause of this issue.

I have tried:

  1. adding the listeners to the notification creation.
  2. adding the listeners outside of the function (with just the 2 lines of the addListener() instead of creating a function for them)
  3. testing in incognito
  4. removing a button (initially i started with 2 buttons and now I’m only using one)

All of these resulted in the same outcome below, with only the button clicked message missing.
Dev mode console

What should be the result and why?

I’m confused as why one, two and three are printed even after encountering an error.

Here’s the code:

setTimeout(() => {
  console.log("one");
}, 1000);
setTimeout(() => {
  console.log("two");
}, 2000);
setTimeout(() => {
  console.log("three");
}, 3000);

console.log(neha);

I was expecting just an error without printing set timeout values as per my knowledge js engine runs console.log first and then set timeout after their particular timeframe. Correct me if I am wrong and I am new to Stackoverflow too. It’s my first question.

here is the output of my code

Laravel Password reset link not generated in forget_password_submit method

I’m encountering an issue with generating a password reset link in my Laravel application within the forget_password_submit method. Despite attempting to construct the link using Laravel’s URL::to() helper function, the link doesn’t seem to be generated correctly. here i used mailtrap for testing mail.

Here’s my forget_password_submit method:

public function forget_password_submit(Request $request)
{
    $request->validate([
        'email' => 'required|email'
    ]);

    $admin_data = Admin::where('email', $request->email)->first();
    if (!$admin_data) {
        return redirect()->back()->with('error', 'Email address not found!');
    }

    $token = hash('sha256', time());

    $admin_data->token = $token;
    $admin_data->update();

    $reset_link = URL::to('admin/reset-password/' . $token . '/' . $request->email);
    $subject = 'Reset Password';
    $message = 'Please click on the following link: <br>';
    $message .= '<a href="' . $reset_link . '">Click here</a>';

    Mail::to($request->email)->send(new Websitemail($subject, $message));

    return redirect()->route('admin_login')->with('success', 'Please check your email and follow the steps there');
}

Despite constructing the link using URL::to(), the link is not being generated as expected. I’ve ensured that the APP_URL variable in the .env file is correctly set, and my routes are properly defined.

GrapesJS builds on macOS but not on Windows 10+

I am hitting a wall on this one. I am building GrapesJS, a web page editor (https://github.com/GrapesJS/grapesjs). It builds fine on macOS but not on Windows 10+. Same version of node, latest release of VS Code, same updates and dependancies.

WARNING in ./src/common/index.ts 35:2-16
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/view/EditorView.ts 16:0-39 45:21-22 68:2-6
 @ ./src/editor/index.ts 60:0-43 866:30-40
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/common/index.ts 43:2-21
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/view/EditorView.ts 16:0-39 45:21-22 68:2-6
 @ ./src/editor/index.ts 60:0-43 866:30-40
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/common/index.ts 51:2-15
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/view/EditorView.ts 16:0-39 45:21-22 68:2-6
 @ ./src/editor/index.ts 60:0-43 866:30-40
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/dom_components/model/Component.ts 1597:18-45
export 'Model' (imported as 'Model') was not found in 'backbone' (module has no exports)
 @ ./src/dom_components/index.ts 97:0-74 262:23-32 267:26-35 588:30-39 588:41-56
 @ ./src/editor/model/Editor.ts 91:0-52 138:4-20
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/dom_components/model/Component.ts 1625:25-53
export 'Model' (imported as 'Model') was not found in 'backbone' (module has no exports)
 @ ./src/dom_components/index.ts 97:0-74 262:23-32 267:26-35 588:30-39 588:41-56
 @ ./src/editor/model/Editor.ts 91:0-52 138:4-20
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/editor/model/Editor.ts 113:0-10
export 'default' (imported as 'Backbone') was not found in 'backbone' (module has no exports)
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

WARNING in ./src/undo_manager/index.ts 76:23-34
export 'default' (imported as 'UndoManager') was not found in 'backbone-undo' (module has no exports)
 @ ./src/editor/model/Editor.ts 108:0-51 118:4-21
 @ ./src/editor/index.ts 59:0-41 79:22-33
 @ ./src/index.ts 13:0-30 61:25-31

All of the config files are the same between the instances. I can browse to the backbone node_module. I have tried various path configs. I have tried both imports * as Backbone from 'backbone' and imports { backbone } from 'backbone' to no avail. Along with various modifications to the webpack.config.js and tsconfig.json. All the usual stuff. Two days of head banging and no love yet.

How to Prevent User from Restarting a Game Until the Day Ends After Completion or Game Over in JavaScript?

I’m working on a game application where users need to complete certain tasks within a day. Once the game is completed or if it’s game over, I want to prevent the user from restarting the game until the day ends, even if they refresh the page. However, currently, even after completion or game over, users can refresh the page and start the game again.

  • I’m using local storage to store game state data and check if the game is completed or if it’s game over.
  • I have implemented logic to update the game state in local storage when the game is completed or if it’s game over.
  • When the user refreshes the page, the game allows them to play again, regardless of whether the game was completed or game over.
Implemented code
useEffect(() => {
    checkLocalStorage(store, setStore, data, setData, setGameOver, setGameCompleted);
  },[])
import { PLAYERS } from "../assets/players"; 

export async function checkLocalStorage(store, setStore, data, setData, setGameCompleted, setGameOver) {
    const fullDate = new Date();
    const date = fullDate.getDate();
    const lastPlayed = localStorage.getItem('lastPlayed');
    
    if(lastPlayed == date){
        console.log('Welcome back');
        const temp = JSON.parse(localStorage.getItem('stat'));
        if(temp) setData(temp);
        
        const gc = localStorage.getItem('gameCompleted');
        if(gc === 'true') setGameCompleted(true);

        const go = localStorage.getItem('gameOver'); 
        if(go === 'true') setGameOver(true);
    } else {
        localStorage.removeItem('store')
        localStorage.removeItem('gameCompleted');
        localStorage.removeItem('gameOver');
        localStorage.setItem('lastPlayed', date);
    }
    
    const newData = localStorage.getItem('store');
    if(!newData) return;
    const newStore = JSON.parse(newData);
    setStore(newStore);
}

export async function updateLife(store, setStore) {
    if(store.lives <= 0) return console.log('Game Over');
    const newStore = {...store};
    newStore.lives -= 1;
    await setStore(newStore);
    localStorage.setItem('store', JSON.stringify(newStore));
}


export function updateStorePlayer(i, check, key, store, setStore) {
    const newStore = {...store};
    newStore.players[i][key] = check[key];
    setStore(newStore);
    localStorage.setItem('store', JSON.stringify(store));
}

export async function checkStat(store, data, setData, setGameOver, setGameCompleted) {
    const newData = JSON.parse(localStorage.getItem('stat'));
    if(!newData) return;
    const newStat = {...newData};
    if(store.lives <= 0) {
        newStat.totalGames += 1;
        setGameOver(true);
        localStorage.setItem('gameOver', 'true');
        return;
    }
    if(store.players.every((player) => player.playerName !== '')) {
        newStat.totalWins += 1;
        newStat.totalGames += 1;
        setGameCompleted(true);
        localStorage.setItem('gameCompleted', 'true');
        return;
    }
    setData(newStat);
    localStorage.setItem('stat', JSON.stringify(newStat));
}

export function compare(val, hero, store, setStore, data, setData ,gameCompleted, gameOver, setGameOver, setGameCompleted) {
    const check = PLAYERS.find((player) => player.playerName.toLowerCase() === val.playerName.toLowerCase());
    if(!check) return;
    checkStat(store, data, setData, setGameOver, setGameCompleted);
    let flag = false;
    for(let i=0; i<4; i++){
        if(hero[i].team.toLowerCase() === check.team.toLowerCase()) {
            updateStorePlayer(i, check, 'team', store, setStore);
        }
        if(hero[i].age === check.age) {
            updateStorePlayer(i, check, 'age', store, setStore);
        }
        if(hero[i].nation.toLowerCase() === check.nation.toLowerCase()) {
            updateStorePlayer(i, check, 'nation', store, setStore);
        }
        if(hero[i].playerName.toLowerCase() === check.playerName.toLowerCase()) {
            flag = true;
            updateStorePlayer(i, check, 'playerName', store, setStore);
        }
    }

    if(flag) {
        // incrementLife(store, setStore);
        flag = false;
    } else {
        updateLife(store, setStore);
    }

    localStorage.setItem('store', JSON.stringify(store));
}

Mac Vue Error: command failed: npm install –loglevel error –legacy-peer-deps

I’m on Mac.
Everytime I vue create project, it shows error:
‘Error: command failed: npm install –loglevel error –legacy-peer-deps’
enter image description here
Error: command failed: npm install –loglevel error –legacy-peer-deps
at ChildProcess. (/usr/local/lib/node_modules/@vue/cli/lib/util/executeCommand.js:138:16)
at ChildProcess.emit (node:events:519:28)
at maybeClose (node:internal/child_process:1105:16)
at ChildProcess._handle.onexit (node:internal/child_process:305:5)
Is it about mac access? How to do with it? Thanks a lot!

Vue3 how to minimize, maximize and close modal or component to bottom of page (like windows)

Let say in vue page has child component or a modal where user can minimize to bottom, maximize and close but keep state of those components until user close. (behave like windows)

I try to find a solution on how i can implement this logic but i didn’t get a solution after googling for a while.
please if you have any working example i will appreciate thank you.

see this image example
enter image description here