Stream Pipeline stops midway

So, I wanted to execute a process in a stream.
At first, it works well with just few data/iterations
but if there’s more data involved, the pipeline just stops midway.

Here’s what my code looks like.

Basically, for this example, I wanted to process around 200 data.

but only 30 data are processed successfully. It stops after that. No error message and I don’t have any clue why.

import { pipeline } from "stream/promises"

async function* func() {
  for (let i = 0; i < 200; i++) {
    console.log(`func ${i}`)
    yield i
  }
}
async function* func2(iterator: AsyncIterable<number>) {
  for await (let i of iterator) {
;    console.log(`func2 ${i}`)
    yield i
  }
}
async function* func3(iterator: AsyncIterable<number>) {
  for await (let i of iterator) {
    console.log(`func3 ${i}`)
    yield i
  }
}

async function main() {
  await pipeline(
    func,
    func2,
    func3
  )
}

main();

Expected output:

Iteration completes 200

Actual output:

Iteration stops at 30

Custom Arrow Buttons Not Working with SplideJS Slider in PHP

I’m trying to integrate custom arrow buttons for navigation in a SplideJS slider within my PHP code. However, the custom buttons don’t seem to trigger the slide movement. Here’s the relevant part of my code:

<!-- PHP and HTML structure -->
<div class="splide w-100 notes-slider">
    <!-- ... other slider elements ... -->
    <div class="s_btn-wr d-flex">
        <button id="btnPrev" class="splide__arrows--prev splide_prev">
            <!-- SVG for left arrow -->
        </button>
        <button id="btnNext" class="splide__arrows--next splide_next">
            <!-- SVG for right arrow -->
        </button>
    </div>
</div>

<script>
    waitForSplide(() => {
        var splide = new Splide('.notes-slider', {
            // ... Splide options ...
        }).mount();

        document.getElementById('btnNext').addEventListener('click', function () {
            splide.go('>');
            console.log('next');
        });

        document.getElementById('btnPrev').addEventListener('click', function () {
            splide.go('<');
            console.log('prev');
        });

    }, '.notes-slider');
</script>

Problem: When I click on the custom arrow buttons (btnNext and btnPrev), nothing happens. The console doesn’t logs ‘next’ or ‘prev’ correctly.

I’m not sure if the issue is with how I’m referencing the Splide instance or with the event listeners. How can I fix this so that the custom buttons control the slider as expected?

How to identify which image belongs to which person after uploading excel sheet (exceljs)?

When I put the same picture in Excel for different rows and try to get it in React using the following,

workbook.getImage(image.imageId)

I notice that even if the pictures are in different rows, I always get the same numbers for ‘nativeRow’ and ‘imageId’. How to identify which image belongs to which row or which person in exceljs?

Is there any other way I can follow to achieve the same?

cypress: error during conditional testing

hey guys 🙂 I’m trying conditional testing in cypress

cy.get("body").then(($body) => {
    if ($body.find("element1").length > 0,  {timeout: 10000}) {
        cy.get("element1").should("be.visible")
    } else {         
        cy.get("element2").should('be.visible').within(() => {
            //do this and that
        })
    }
});

but the problem here that in case it doesn’t find element1, test won’t move forward. I tried different approaches but none worked. either 1st part or 2nd part works but never both. could you please advise what might be wrong? thanks a lot in advance, struggling with it for ages and now it’s a matter of honor to solve this 😀

Network request failed with fetch method in React Native for Rapid API

I am developing an app in react native.

I would like to make a call to RapidAPI, such as:

  useEffect(() => {
    fetch("https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes", {
      method: "GET",
      headers: {
        'X-RapidAPI-Key': 'myapi',
        'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com'
      }
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => console.log(error));
  }, []);

I am getting this error: [TypeError: Network request failed].

I also tried with the axios package and led to the same thing.

I used the python snippet from Rapid API and it worked strait away.

What am I doing wrong ?

Custom Error Handling with http-proxy-middleware in Express.js

I am trying to implement custom error handling for a proxy server in an Express.js application using http-proxy-middleware. The goal is to display a custom error page when the target domain returns a 404 error. Here’s the simplified code structure:

const express = require('express');
const http = require('http');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');

const app = express();
const port = 3000;

// Configure proxy middleware for a single domain
const proxyOptions = {
  target: 'http://example.com',
  changeOrigin: true,
  pathRewrite: {
    '^/proxy': '',
  },
};

const proxy = createProxyMiddleware('/proxy', proxyOptions);

// Use the middleware
app.use('/proxy', proxy);

// Custom error handling for 404 errors
app.use((err, req, res, next) => {
  if (err.status === 404) {
    // Serve custom 404 error page
    res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
  } else {
    // Handle other errors
    res.status(err.status || 500);
    res.send({
      message: err.message,
      error: err,
    });
  }
});

// Start the server
const server = http.createServer(app);

server.listen(port, () => {
  console.log(`Proxy server listening on port ${port}`);
});

However, the custom error page is not being served when a 404 error occurs on the target domain (example.com). Instead, the default error message from the target domain is displayed. I have verified that the custom error page (404.html) exists in the ‘public’ directory.

What am I missing in my implementation, and how can I ensure that the custom error page is served for 404 errors?

How to write into contenteditable div on Threads

I’m trying to create a Chrome extension that can write text into the reply field of a thread on Threads.net. It is a contenteditable div and as far as I see I need to edit the text of the nexted p-element.

<div class="xzsf02u xw2csxc x1odjw0f x1n2onr6 x1hnll1o xpqswwc notranslate" contenteditable="true" role="textbox" spellcheck="true" tabindex="0" data-lexical-editor="true" style="user-select: text; white-space: pre-wrap; word-break: break-word;"><p class="xdj266r x11i5rnm xat24cr x1mh8g0r"><br></p></div>

I tried with innerHTML, innerText, textContent. I tried to duplicate the element, remove the original, replace it with mine… nothing of that worked. I asked ChatGPT which couldn’t help either.

Reducing the amount of space taken in a v-dialog

I am trying to write a Vue 3 dialog to hold a date picker and a radio button to collect the hour. It seems to take a great deal of space in the vertical direction.

For example I like to move the label for the radio button to be in line with the radio buttons and to reduce the amount of space taken by the rulers.

enter image description here

I have already turned of the chosen date, but I can not workout how to reduce the space allocated between components

Calling code

    <template>
  <v-container>
    <v-row>
      <v-col cols="12">
        <date-dialog dialogTitle="Select the date"
             startDate="2018/01/01"
             endDate="2018/12/31"
             year="2018"
             :propDate="'2018-12-17T12:06:00'"
             :propHourFormated="'6'"
             @clicked="onDateClicked"
        />
      </v-col>  
    </v-row>
  </v-container>
  
</template>
<script>
import DateDialog from './components/DateDialog.vue';
export default {
  methods: {
      onDateClicked(value){
          console.log("Value is " + value)
      }
  },
  components: {
    DateDialog,
  },
}
</script>
<style>
  /* remove calander frrom date picker */
  .v-date-picker-header {
     display: none
  }
</style>

Dialog code

    <template>
  <div>
  <v-container class="fill-height">
    <v-row>
      <v-col
        cols="12"
        sm="6"
        md="4" >
        <v-dialog
          ref="dialog"
          v-model="modal"
          :return-value.sync="date"
          persistent
          width="290px" >
          <template v-slot:activator="{ attrs }">
              <!-- label="Select a date" -->
            <v-text-field v-model="computedDateFormatted"
              :label="dialogTitle" prepend-icon="mdi-calendar" readonly
               @click="modal = true" v-bind="attrs" persistent-hint >
            </v-text-field>
          </template>
          <v-card width="360px">
            <v-date-picker v-model="date" color="primary"
            :year="year" :min="startDate" :max="endDate"
            scrollable :title="dialogTitle" hide-actions >
              <!-- remove the selected date--> 
              <template v-slot:header></template>
            </v-date-picker> 
            <hr>
            <v-container>
              <v-radio-group v-model="computedHourFormatted" label="Time" inline @change="this.RBchanged">
                <v-radio label="00" value="0"></v-radio>
                <v-radio label="06" value="6"></v-radio>
                <v-radio label="12" value="12"></v-radio>
                <v-radio label="18" value="18"></v-radio>
              </v-radio-group>
            </v-container>
            <hr>
            <v-card-actions>
              <v-btn text color="primary" @click="this.dialogOK" >OK </v-btn>
              <v-btn text color="primary" @click="this.dialogCancel" >Cancel </v-btn>
            </v-card-actions> 
          </v-card>
        </v-dialog>
      </v-col>
    </v-row>
  </v-container>
  </div>
</template>
<script>
  export default {
    props: {
        dialogTitle:{ type:String},
        startDate:{ type:String},
        endDate:{ type:String},
        year:{ type:String},
        propHourFormated:{ type:String},
        propDateFormated:{ type:String},
        propDate:{ type:String},
    },
    methods:{
      // inserted to show that clicking of the radio buttons is working
      RBchanged(){
        console.log('changed')
        console.log("VM "+this.hourFormatted);
      },
      dialogOK(){
          this.modal=false;
          console.log("OK " );
          this.$emit('clicked',this.date);
      },
      dialogCancel(){
          console.log("Cancelled " );
          // reset to the orginal value
          this.date= new Date(this.propDate);
          this.dateFormatted= new Date(this.propDateFormatted);
          this.modal=false;
          this.$emit('clicked',this.date);
      },
      // write a date in to the textfield object, note expects to 
      // receive a date object
      formatDate (mydate) {
        if (!mydate) 
          return null
        var hours="00",mins="00";
        if(mydate.getHours() !== "" && mydate.getHours() !==0 ){
           hours=mydate.getHours();
        }
        return mydate.getDate()+"-"+
          mydate.toLocaleString('en-GB', { month: 'long' })+" "+
          mydate.getUTCFullYear() + " "+
          hours+ ":" +
          mins
          ;
      },
      // set a value of the radio button should
      // be a value of 0,6,12,18
      formatHour(myhour) { 
        console.log("formatHour: new Hours " + myhour);
        return myhour.toString();
      },
    },
    computed: {
      computedDateFormatted () {
        this.date.setHours(this.hourFormatted)
        return this.formatDate(this.date)
      }, 
      computedHourFormatted:{ 
        get() { 
          console.log("XXXXget #" + this.date.getHours().toString()+"#");
          return this.hourFormatted;
        },
        set(value){
          console.log("SET:Formating hours " + value);
          this.hourFormatted=value;
        }
      },
    },
    watch: {
      date (val) {
        //this.hourFormatted = this.formatHour(this.date.getHours())
        this.dateFormatted = this.formatDate(this.date)
      },
    }, 
    data () {  return {
      // starting value for the date picker
      date: new Date(this.propDate),  
      // starting value for the textfield
      dateFormatted: new Date(this.propDate),  
      // starting value for the radio buttons
      hourFormatted: this.propHourFormated,
      modal: false,
    }},
  };
</script>

How can I pass parameter that would be my max loop condition to create multiple test cases (“it” function)?

so I have been thinking to try to create test case to be more dynamic based on the 1st test case of how much data do I have and I tried to validate it in batches by divide it from the total data that I have. the reason behind this is to reduce the memory consumption and to mitigate the Crash error from Chromium. but, so far I have been facing a problem in my code as follow:

describe("Issue fetch data", () => {
  let totalData: number;
  let maxBatches: number;

it("fetch total data", () => {
  cy.fixture("token").then((token) => {
    // logic to fetch total data
    ).then((res) => {
      totalData = res.body.total;
      maxBatches = Math.ceil(totalData / 1000);
      Cypress.env("testdata", maxBatches)
    });
  });
});

it("check if testdata shown", () => {
  cy.log(Cypress.env("testdata")); // it does shown
});

// But when it comes to here, this test case does not shown up.
// only "fetch total data" & "check if testdata shown"

for (let i = 1; i <= Cypress.env("testdata"); i++) {
  it(`get data on batch ${i}`, () => {
    // my code logic
  });
}

The problem that I am facing is that, the loop over test case it does not appears, unless I hard coded the max limit loop. I have tried to follow the instruction in here so far no luck.

Problem

I am expecting something like this. Note: I hard coded the loop from for (let i = 1; i <= Cypress.env("testdata"); i++) to for (let i = 1; i <= 2; i++) {

Expectation

Alternatively, I also have tried to do this:

for (let i = 1; i <= maxBatches; i++) {
  it(`get data on batch ${i}`, () => {
    // my code logic
  });
}

Does anyone know alternative to do this? I have also tried to create another param above for loop to be the maximum limit looping, but it still doesn’t works. Thank you guys!

is it good practice to create a variable in a return in javascript?

in Javascript, in the return statement of a function, I cannot explicitly declare a variable like that return let text = "hello world!", so far so good

But also, when I declare a variable I can do it without a keyword like var, let or const, it’s what w3school call an automatically declared variable : https://www.w3schools.com/js/js_variables.asp like that : newVariable = "I'm a new variable" instead of that : let newVariable = "I'm a new variable" or that : const newVariable = "I'm a new const variable"

Now, I noticed that if I use an automatically declared variable in a return statement, it seems to have declared the variable outside of the function scope :

let myP = document.getElementById("output");

function printInfos(name, age) {
  return info = `${name} is ${age}`;
}

printInfos("john", 4);

myP.textContent = info; // output "john is 4"
<p id="output"></p>

What I suppose is happening is the following :

  1. the function return the whole expression after expansion info = 'john is 4'
  2. then it is evaluated as an automatically declared variable info

But I wonder how much it is good practice or not ?

I already consider automatically declared variables as bad practice, but in most cases I’m not even sure why other than readability (when I see the variable without keyword I wrongly assume it has been declared earlier), since I can treat them just like a declaration with let

But the case of a declaration inside a return statement confuses me since it allows me to do something I cannot do when I “properly” declare the variable, it feels like a bug

so what is it ? Can I use it ?

Hide grid items when space is not available

I have a grid container that has 4 items. The first 2 items and the 4th items will always take up similar space and the 3 items can be long or short and it must take up all the leftover space as shown below

function handleWidth() {
  const inputValue = document.getElementById("widthInput").value;

  document.getElementsByClassName("grid-container")[0].style["width"] = inputValue + '%';
}
.grid-container {
  display: grid;
  grid-template-columns: auto auto 1fr auto;
}

.grid-container>div {
  padding-right: 10px;
}
<div class="grid-container">
  <div>Jira-123</div>
  <div>Icon</div>
  <div>Summary - This is a summary of jira item</div>
  <div>In progress</div>
</div>
<br />
<br />
<div><input type="number" value="100" id="widthInput" /></div>
<button onclick="handleWidth()">set width</button>

But if you reduce the available space in which the grid container fits (you can do so by entering a value, say 25, in the input field, in the sample given above), you’ll see that the summary/title is shown in multiline.

What I desire to do

As the space reduces, I want to remove the status(“In progress” in the above example) and show the “summary/title” with an ellipsis and as the space reduces further, I want to remove the “summary/title” as well. The first grid item i.e. JIRA-123 should not wrap.

I am a noob when it comes to grid layout. Please help if you can, thanks in advance.

In React, is passing a decently big object better or should I just pass the required fields of an object?

Let’s say I have a function that retrieves data from API and the API returns array of objects. Each object has a lot of fields(20 or so). Now I want to use ONLY ‘id’ and ‘name’ of each object.

Is it better to use that map function to reduce the objects to 2 fields each or would it be better to just pass the object as is and let the Dropdown component destructure the fields itself?

const SomeComponent () =>{
const [companies, setCompanies] = useState([]);

const fetch =async () => {
await api.get("/companies").then((response) => {
      const rows = response.data.rows;

      const updateCompanies = rows.map((item) => ({
        //extract only name and id of statusLabels
        id: item.id,
        name: item.name,
      }));

      setCompanies(updateCompanies); //set companies
    })
};

useEffect(()=>{
 if(companies.length === 0){
 (async () => await fetch())();
}
},[])


return (
<>
      <Dropdown
        data={companies}
        placeholderStyle={styles.placeholder}
        labelField="name"
        valueField="id"
        placeholder={"Companies"}
        onChange={(item) => {
          setCompanyFilter(item.id);
        }}
        style={styles.inputContainer}
      />
</>

)


}

tried passing both ways but i don’t know how to benchmark

React app changes not reflecting when application deployed

Hi I have react application deployed in kubernetes. I am facing some issues in my application. when I make some changes in code, for example lets say I have added some console.log its not appearing in browser when deploy my code. Below is my configuration of dockerfile

# syntax = docker/dockerfile:1.2

FROM node:17-alpine as builder

ENV NODE_ENV=production
ARG NODE_AUTH_TOKEN
ARG NEXUS_AUTH_TOKEN

WORKDIR /src

ENV PATH /src/node_modules/.bin:$PATH

COPY .npmrc ./
COPY package.json ./

COPY ./ ./

RUN npm i -f --production

RUN npm run build --silent

RUN rm -f ./.npmrc

COPY . .
# Expose port
EXPOSE 3000
# Start the app
CMD [ "npm", "start" ]

Below is my .env file

REACT_APP_NOLOGIN=1
REACT_APP_ENTITY_TYPE=''
REACT_APP_ENTITY_CODE=''
REACT_APP_POST_LOGOUT_URI=''
FAST_REFRESH=false

Below is my package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest --coverage",
    "eject": "react-scripts eject"
  }

Below is my deployment file

apiVersion: apps/v1
kind: Deployment 
metadata: #Dictionary
  name: #{KUBERNETES_WEB_APP_NAME}#
spec: # Dictionary
  replicas: 1
  strategy:
    type: RollingUpdate
    rollingUpdate:
      # maxUnavailable will set up how many pods we can add at a time
      maxUnavailable: 50%
      # maxSurge define how many pods can be unavailable during the rolling update
      maxSurge: 1
  selector:
    matchLabels:
      app: #{KUBERNETES_WEB_APP_NAME}#
      instance: #{KUBERNETES_APP_INSTANCE}#
  template:  
    metadata: # Dictionary
      name: #{KUBERNETES_WEB_APP_NAME}#
      labels: # Dictionary
        app: #{KUBERNETES_WEB_APP_NAME}#  # Key value paids
        instance: #{KUBERNETES_APP_INSTANCE}#
        product_id: app
        app.kubernetes.io/component: app
        app.kubernetes.io/name: app
      annotations:
        vault.security.banzaicloud.io/vault-role: #{KUBERNETES_NAMESPACE}#
        prometheus.io/path: /metrics
        prometheus.io/port: "80"
        prometheus.io/scrape: "true"
    spec:
      serviceAccountName: default
      terminationGracePeriodSeconds: 30
      containers: # List
        - name: webapp-container
          image: #{WEB_IMAGE_TAG}#
          #command: ["sh", "-c", "echo $mypassword echo going to sleep... && sleep 1"]
                    imagePullPolicy: Always
          ports: 
            - containerPort: 3000
          resources:
            requests:
              memory: "2Gi"
              cpu: "1300m"     
            limits:
              memory: "2Gi"
              cpu: "1500m"    

These are my configurations. When i make some changes in the code and deploy my changes not appearing but strange thing what i observed in when I check my file in source in browser i can see my changes but those changes does not reflect in browser. Latest code changes I see in file in source. I am not sure any problem with compiling or any other issues. Struggling to find out issue since two days. can someone help me to fix this? Thanks a lot