Making subscriptions sync

I’m working on a project for my company and deeply respecting the NDA that I have signed I provide the following code snippet without any sensitive information, consider this code:

toggleLoadingAnimation()
Subscription1()
Subscription2()
…
Subscription10()

toggleLoadingAnimation()
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>

The problem is that all the Subscription methods are async, they all look like that:

this.randomFieldSubscription = this.randomService.randomEntityList.value$.subscribe(entityList => {this.entityList = entityList})

When the .subscribe gets executed we also send a request to the server inside the randomService.

How do I make the second toggleLoadingAnimation() get executed only when all the previous Subscriptions are done and all responses from the server are recieved?

Break newline in react native with react i18next

I am using react-i18next i18next in a react-native project. I am having trouble adding a new line in the translated text.

// locales_en.json
"FOO": "I am text n that should have a new line

That n is not doing anything. How would I add a line break in the translation files?

How to save/download a pdf file from browser’s pdf preview

I am using this sample PDF.

https://www.cheat-sheets.org/saved-copy/http-response-codes-1.pdf

My goal is to download this as a pdf file.

Here is my code so far

const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  // await page.emulateMedia({ media: 'print' }); // Doesn't work also.
  await page.emulateMedia({ media: 'screen' });

  await page.goto('https://www.cheat-sheets.org/saved-copy/http-response-codes-1.pdf');

  console.log('Page Visited');

  await page.waitForTimeout(3000); // To wait for the pdf to be full loaded.

  console.log('Timeout Done');

  await page.pdf({ path: `document.pdf` });

  console.log('Document Saved');

  await browser.close();
})();

It does save the document but the content is broken.

Example this is what the document looks like on a browser controlled by playwright.

enter image description here

But this is what was saved locally

enter image description here

Not sure what is going on here.
I tried the screenshot approach and it does behave the same way.
I tried the triggering of ctrl+s but learned that this is not possible due to security reasons. I am a bit lost.

Any help is appreciated.

But my overall goal is to download a pdf file from the pdf preview of the browser.

response payload missing last character

authRouter.post("/checkEmail", async (req, res) => {
  try {
    const { email } = req.body;
    if (!email) {
      return res
        .status(400)
        .json({ error: "Email address is missing in the request body." });
    }
    const query = "SELECT auth.is_email_exist($1);";
    const result = await pool.query(query, [email]);
    const isEmailExist = result.rows[0].is_email_exist;
    res.json(isEmailExist);
    console.log(isEmailExist);
  } catch (err) {
    console.error("Error checking email:", err);
    res.status(500).json({ error: err.message });
  }
});

This post request always gives the correct response but the request gets blocked as the response last character always gets ommitted and it is only happening with this request

I have set the content header encoding to UTF8

missing {

enter image description here

How do I send push notifications in my Expo managed React Native project? (Firebase backend)

Let’s say I have user1 and user2. If user1 likes user2’s post, I want user2 to get a notification. For reference, in Firestore I have collections users and posts. I’ve done a lot of research on Expo Notifications but I’m not sure how to handle this use case. What are my options? Is it necessary to create a node server? If so, how would I go about doing this?

At the moment, I’m focusing on releasing for iOS.

I am able to obtain a user’s push token, but I don’t know how to send notifications to individual users based on examples like the one provided.

I saw this in the expo-server-sdk-node docs, but I’m not sure how or where to implement it because I don’t have much experience with servers.

import { Expo } from 'expo-server-sdk';

// Create a new Expo SDK client
// optionally providing an access token if you have enabled push security
let expo = new Expo({
  accessToken: process.env.EXPO_ACCESS_TOKEN,
  useFcmV1: false // this can be set to true in order to use the FCM v1 API
});

// Create the messages that you want to send to clients
let messages = [];
for (let pushToken of somePushTokens) {
  // Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]

  // Check that all your push tokens appear to be valid Expo push tokens
  if (!Expo.isExpoPushToken(pushToken)) {
    console.error(`Push token ${pushToken} is not a valid Expo push token`);
    continue;
  }

  // Construct a message (see https://docs.expo.io/push-notifications/sending-notifications/)
  messages.push({
    to: pushToken,
    sound: 'default',
    body: 'This is a test notification',
    data: { withSome: 'data' },
  })
}

// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
(async () => {
  // Send the chunks to the Expo push notification service. There are
  // different strategies you could use. A simple one is to send one chunk at a
  // time, which nicely spreads the load out over time:
  for (let chunk of chunks) {
    try {
      let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
      console.log(ticketChunk);
      tickets.push(...ticketChunk);
      // NOTE: If a ticket contains an error code in ticket.details.error, you
      // must handle it appropriately. The error codes are listed in the Expo
      // documentation:
      // https://docs.expo.io/push-notifications/sending-notifications/#individual-errors
    } catch (error) {
      console.error(error);
    }
  }
})();

...

// Later, after the Expo push notification service has delivered the
// notifications to Apple or Google (usually quickly, but allow the service
// up to 30 minutes when under load), a "receipt" for each notification is
// created. The receipts will be available for at least a day; stale receipts
// are deleted.
//
// The ID of each receipt is sent back in the response "ticket" for each
// notification. In summary, sending a notification produces a ticket, which
// contains a receipt ID you later use to get the receipt.
//
// The receipts may contain error codes to which you must respond. In
// particular, Apple or Google may block apps that continue to send
// notifications to devices that have blocked notifications or have uninstalled
// your app. Expo does not control this policy and sends back the feedback from
// Apple and Google so you can handle it appropriately.
let receiptIds = [];
for (let ticket of tickets) {
  // NOTE: Not all tickets have IDs; for example, tickets for notifications
  // that could not be enqueued will have error information and no receipt ID.
  if (ticket.id) {
    receiptIds.push(ticket.id);
  }
}

let receiptIdChunks = expo.chunkPushNotificationReceiptIds(receiptIds);
(async () => {
  // Like sending notifications, there are different strategies you could use
  // to retrieve batches of receipts from the Expo service.
  for (let chunk of receiptIdChunks) {
    try {
      let receipts = await expo.getPushNotificationReceiptsAsync(chunk);
      console.log(receipts);

      // The receipts specify whether Apple or Google successfully received the
      // notification and information about an error, if one occurred.
      for (let receiptId in receipts) {
        let { status, message, details } = receipts[receiptId];
        if (status === 'ok') {
          continue;
        } else if (status === 'error') {
          console.error(
            `There was an error sending a notification: ${message}`
          );
          if (details && details.error) {
            // The error codes are listed in the Expo documentation:
            // https://docs.expo.io/push-notifications/sending-notifications/#individual-errors
            // You must handle the errors appropriately.
            console.error(`The error code is ${details.error}`);
          }
        }
      }
    } catch (error) {
      console.error(error);
    }
  }
})();

Taking Screenshot of Dynamically Rendered Element with Puppeteer

The user will provide a URL, and then they will click a button. Using Puppeteer, specific data will be scraped from the user-provided webpage. After that, the page will be rendered. The goal is to take a screenshot of an element from the rendered page. How can this be achieved?

Here’s the code (server.js):

"use strict";
const express = require("express");
const app = express();
const puppeteer = require("puppeteer");
const fs = require("fs");
const path = require("path");
const https = require("https");

app.use(express.static("public"));
app.use(express.static("src"));

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("index");
});

app.post("/result", async (req, res) => {
  const reveiwLink = req.body.review_link;

  try {
    const browser = await puppeteer.launch({
      headless: false,
      defaultViewport: false,
      userDataDir: "./tmp",
    });

    const page = await browser.newPage();
    await page.goto(`${reveiwLink}`, {
      waitUntil: "load",
    });

    // specifying the selectors and scraping of data works here

    res.render("result", {
      data: {
        movieName,
        reviewerName,
        review,
        movieYear,
        rating,
        watchedDate,
        likes,
        hasSpoiler,
      },
    });

    await page.goto(`http://localhost:3000/result`, {
      waitUntil: "load",
    });

    const element = await page.$("#htmlContent");
    await element.screenshot({ path: "theCard.png" });
    await browser.close();
  } catch (err) {
    console.error(err);
    res
      .status(500)
      .json({ error: "An error occurred while fetching the review" });
  }
});

app.listen(3000);

As you can see, after rendering the “result,” an attempt was made to take a screenshot of the rendered “result” by navigating to http://localhost:3000/result in the Puppeteer browser. However, this did not display the rendered “result,” and an error occurred: “Cannot GET /result.” As a result, the screenshot could not be taken.

What should be done to resolve this issue? Please provide suggestions. Thank you.

I’m using Puppeteer to take the screenshot because I’ve tried using html2canvas, dom-to-image, apiFlash to take the screenshot and I am not satisfied with the quality of the image. That’s why I’m using Puppeteer to take the screenshot.

The Python code for calculating the RSI of a coin is being converted to JavaScript, but the values are different. What could be the reason?

This is python code

PYTHON

import pandas as pd

def get_rsi(ohlcv, period, st):
    ohlcv["close"] = ohlcv["close"]
    delta = ohlcv["close"].diff()
    up, down = delta.copy(), delta.copy()
    up[up < 0] = 0
    down[down > 0] = 0
    _gain = up.ewm(com=(period - 1), min_periods=period).mean()
    _loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
    RS = _gain / _loss
    return float(pd.Series(100 - (100 / (1 + RS)), name="RSI").iloc[st])

JAVASCRIPT

export function getRSI(ohlcv, period) {
  if (ohlcv.length < period + 1) {
    throw new Error("Data length must be greater than period");
  }

  let gains = [];
  let losses = [];

  for (let i = 1; i < ohlcv.length; i++) {
    let diff = ohlcv[i].close - ohlcv[i - 1].close;
    if (diff > 0) {
      gains.push(diff);
      losses.push(0);
    } else if (diff < 0) {
      gains.push(0);
      losses.push(Math.abs(diff));
    } else {
      gains.push(0);
      losses.push(0);
    }
  }

  let avgGain = gains.slice(0, period).reduce((acc, cur) => acc + cur, 0) / period;
  let avgLoss = losses.slice(0, period).reduce((acc, cur) => acc + cur, 0) / period;

  let RS = avgGain / avgLoss;
  let RSI = 100 - 100 / (1 + RS);
  return RSI;
}

do you know the reason..?

I tried to test it
But RSI results were different

there is no Pandas for Javascript.

The JavaScript code generated through ChatGPT isn’t effective. Could you please help me understand the reason behind it?

Why is $(this).text() not showing value in tag when using $(‘#table tbody tr’).filter function?

I am developing a functionality to filter table content based on text box input.

Here is my code.

HTML code:

<div style="overflow: auto;">
     <div style="margin: 20px; display: flex; justify-content: space-around;">
          <span>Product: <span id="btnawfproduct"></span></span>
          <div>Filter: <input id="filteraliasdesc" type="text"></div>
          <button id = "btnupdatealiasdesc" class="btn btn--dark">Update All</button>
     </div>
     <table id="editaliastable" style="table-layout: fixed; width: 100%;">
        <thead>
             <tr>
                  <th>Metric</th>
                  <th>Metric Alias</th>
                  <th>Metric Description</th>
             </tr>
        </thead>
     </table>
</div>

JS code:

$(document).on('keyup', '#filteraliasdesc', function(){
    var searchText = $(this).val().toLowerCase();
    $('#editaliastable tbody tr').filter(function(){
      var rowText = $(this).text().toLowerCase();
      console.log('rowText --> ', rowText) //This is not showing input type='text' value
      if(rowText.indexOf(searchText) === -1){
            $(this).hide();
        } else {
            $(this).show();
        }
    });
});

$(document).on("click", ".editaliasdesc", function () {
    const table = $('#editaliastable');
    $('#btnawfproduct').text(awf_metric_alias[0]['productname']);
    var metric_alias = awf_metric_alias[1]['metric_alias'];
    var table_rows = ''
    for(var i = 0; i < metric_alias.length; i++)
        table_rows += `<tr>
                        <td><input type='checkbox' class ="chkupdatealias" style='transform: scale(1.5);'>${metric_alias[i].metric}</td>
                        <td><input type='text' style='width: 100%;' value = '${metric_alias[i].metric_alias}'></td>
                        <td><textarea style='width: 100%;'>${metric_alias[i].description}</textarea></td>
                     </tr>`;
    table.append('<tbody>' + table_rows + '</tbody>');
});

Problem:

The keyup function is not filtering the value in element <td><input type='text' style='width: 100%;' value = '${metric_alias[i].metric_alias}'></td>.

Please advice, Thanks.

What Machine Learning Library (Tensorflow.js or brain.js) is best for path finding in Javascript

Problem: I am doing a project where I’m creating a machine learning model that solves a randomly generated maze/path and I dunno what library to use.

Background: I will be using p5 and don’t have any experience using any machine learning library.

So far i’ve looked into Tensorflow.js and Brain.js but I don’t know which one would be best

Text on mobile website is not appearing correctly

Some text for a website I’m working on appears correctly using inspect element and viewing the website with the “toggle device” tool to view the mobile version on my laptop, however on my actual iphone website is not appearing as it should, and nothing I am doing is working to fix it.

Here is my html for the text:

<div id="pricesTextContainer">
    <p id="happyHour">HAPPY HOUR</p>
    <p id="discount">30% OFF KARAOKE<p>
    <p>MONDAY / TUESDAY / THURSDAY: 9PM - 12AM <br> SUNDAY: ALL DAY</p>
    <p id="reservations">Reservations Recommended<p>
</div>

Here is my CSS for the text:

#pricesTextContainer{
    text-align:center;
    color:white;
    font-family: 'Poppins', sans-serif;
    margin-top:50px;
    

    #happyHour{
        color: gold;
        font-size: 60px;
        font-weight: 800;
        margin:0;
        padding:0;
    }

    #discount{
        color: white;
        text-decoration: underline wavy  rgb(95, 204, 255);
        text-underline-offset: 10px;
        text-decoration-thickness: 4px;
        font-size: 60px;
        font-weight: 800;
        margin:0;
    }
    p{
        font-size: 40px;
        margin:0;
    }
    #reservations{
        font-size: 15px;
        font-weight: 100;
        margin-top:10px;
    }
}

Here is what it should look like (looks like on desktop “mobile view”):
Here is what it should look like (looks like on desktop "mobile view"):

Here is what it looks like on my actual iphone:
Here is what it looks like on my actual iphone

While executing the web project I get css related issue please provide exact answer to overcome these type of issues

CSS Related issues had got while executing the pivot table program.

Error: ./node_modules/pivottable/dist/pivot.min.css:1:0 – Error: Module parse failed: Unexpected token (1:0) in angular pivot.min.css file is not recognized.so please provide exact code for this issue.
github link

I have given github link given below please provide the answer for this issue.

https://github.com/pradeeprockz/pivottable-app

Control direction of container resizing / Whitespace direction

I’m having trouble with the direction a container resizes.

Essentially, I have an absolutely positioned element. I’ve justified the content inside to flex-end, as I’d like it to be positioned the at the end of the container. As the window shrinks, I’d like for the whitespace/extra space above the container to shrink and the content be pulled up towards the top. Right now, it goes further towards the bottom. I want the exact opposite of what is currently happening.

I’ve provided a video to help explain. I provide the real Netflix behaviour, you can see it resizes towards the top, whereas mine resizes towards the bottom.

Here is the component:

const HomePageHero = () => {
  return (
    <div className="debug-red absolute bottom-[35%] top-0 left-0 mx-[58px] flex flex-col justify-end items-center w-[36%] z-50">
      <div className=" block debug ">
        <div id="text" className="flex flex-col gap-[20px]">
          <img src={heroTitle} className="" />
          <p className="text-white font-normal text-[1.2vw]">
            Years after retiring from their formidable ninja lives, a
            dysfunctional family must return to shadowy missions to counteract a
            string of looming threats.
          </p>
        </div>
        <div id="buttons" className="flex gap-4">
          <Button title="Play" icon={PlayIconLarge} bgWhite={true} />
          <Button title="More Info" icon={InfoIconMedium} bgWhite={false} />
        </div>
      </div>
    </div>
  );
};

Video:

oops

Conditions to render NavBar

I have some problem when I display UI, here is my code.

I tried with is_public === false but it didn’t work as I expected, when I go back to another page with is_public === true it still hides my navBar

  useEffect(()=> {
    pages.map((item) =>{
      if(item.is_public === false) {
        console.log("sss")
      }
    })
  })

  return (
    <nav id="sidebar" class="">
      <div class="sidebar_blog_1">
        <div class="sidebar-header">
          <div class="logo_section">
            <a href="#">
              <img
                class="logo_icon img-responsive"
                src="/images/logo/logo_icon.png"
                alt="#"
              />
            </a>
          </div>
        </div>
        <div class="sidebar_user_info_custom">
          <div class="icon_setting"></div>
          <div class="user_profle_side">
            <div class="logo_section">
              <a href="#">
                <img
                  class="img-responsive"
                  src="/images/logo/logo.png"
                  alt="#"
                />
              </a>
            </div>
          </div>
        </div>
      </div>
       <Navbar_Render data={pages} isLogged={isLogged} />
      <div class="footer-custom">
        <p>&copy; 2023 - Designed by</p>
      </div>
    </nav>
  ); 

Cypress.io dynamic test generation with asynchrouns data

I have a data driven cypress code like below.
I’m trying to generate tests dynamically based on the values of “data” variable.

    let data:QuestionData[];
describe("Add data to admin", ()=>{
    before(async ()=>{
        data = await promisify(cy.task("readCSV",csvFile));
    });
    data.forEach((val,index)=>{
        it(`Should add val ${val}`, ()=>{
            console.log(index);
        })
    })

});

my “readCSV” method just reads a csv and resolve data.

when I run above code I’m getting this error -> Cannot read properties of undefined (reading ‘forEach’).

The reason is “data.forEach” runs before the variable gets initialized.
if I write a “console.log” inside the “before” hook I can see data is available.
But why data variable NOT getting available outside the BEFORE HOOK ?
My code works if I access “data” variable inside “it” block and use for lood.
but I want tests to be generated dynamically.

How can I fix this in cypress.io ?

Can OpenLayers(6+) implement interactive grid wind feathers? (As shown in the picture)

enter image description here

The wind feathers will change as the map is zoomed in or out, similar to an aggregation function. Could any experienced individuals who have worked on such projects provide some guidance to me?

OpenLayers has a plugin called ol-wind, but this plugin can only implement fluid animations. I hope to be able to display grid wind feathers and isobars.