How to extract text from between any given pair of spans?

I am trying to use Cheerio and Node.js to extract text from an interesting bit of HTML.

Let’s say I have the following HTML:

<p>
  <span class="sectionno" id="s1">1</span>
  Do you see that shelf?
  <span class="endsection"></span>
  <span class="sectionno" id="s2">2</span>The shelf is hanging
</p>
<p>on the wall</p>
<p>beside the clock.</p>
<h3>Title Here</h3>
<span class="endsection"></span>
<p>
  <span class="sectionno" id="s3">3</span>The clock
</p>
<p>was ticking slowly</p>
<p>telling time<span class="endsection"></span></p>

I want to be able to extract the following data, getting the text between each pair of span.sectionno and span.endsection:

[
  {
    no: 1,
    text: "Do you see that shelf?",
  },
  {
    no: 2,
    text: "The shelf is hanging on the wall, beside the clock.",
  },
  {
    no: 3,
    text: "The clock was ticking slowly telling time",
  },
]

Notice that I want to ignore any text in headings.

Because of the strange setup of the HTML I have been unable to successfully to do this with Cheerio. Any help is appreciated!

Having Stripe button responsive or smaller

I try to configure a simple Stripe payment button on my website. However, the blue button is way too large and not responsive.
I would like to have is responsive or at least smaller but there is no option for that in the Stripe website button configuration.

The code I got from the website is :

<script async
      src="https://js.stripe.com/v3/buy-button.js" class="stripe-button">
    </script>

<stripe-buy-button
  buy-button-id="buy_btn_..."
  publishable-key="pk_live_..."
>
</stripe-buy-button>

Is there a way to do that?
Thank you for your help.

How can I enforce valid nested folder routes when folder names in the URL may be manually changed?

I’m building a Next.js application that replicates functionality similar to Google Drive. Users can create nested folders under /dashboard/work-room using a catch-all dynamic route ([…folderId]). Each folder’s URL is structured as a pair of folder id and folder name. For example, when I create a folder named “data” with an id of 1, the URL becomes:

/dashboard/work-room/1/data

In my app, the folder id is used for API calls and data fetching, while the folder name is used in the breadcrumb display. Everything works correctly when the URL is generated by the app. However, if a user manually changes the folder name in the URL (or adds extra segments), the API still fetches data based solely on the folder id. For instance:

  • Navigating to /dashboard/work-room/1/random still fetches data for folder id 1, even though the name is now “random”.

  • Navigating to a nested route like /dashboard/work-room/1/wrongFolderName/2/data displays data for folder id 2.

Here’s a simplified version of the code I’m using to extract the folder id and build the URL:

// Extract dynamic segments from the URL
const pathname = usePathname();
const dynamicPath = pathname
  .replace("/dashboard/work-room", "")
  .split("/")
  .filter(Boolean);

// Folder id is assumed to be the second-to-last segment
const id =
  dynamicPath.length >= 2 ? dynamicPath[dynamicPath.length - 2] : null;

const handleOpenFolder = (id, name) => {
  router.push(
    `/dashboard/work-room/${[
      ...dynamicPath,
      id,
      encodeURIComponent(name),
    ].join("/")}`
  );
};

And for fetching data (while generating folder pairs):

const pathname = usePathname();
const dynamicPath = pathname
  .replace("/dashboard/work-room", "")
  .split("/")
  .filter(Boolean);

const id =
  dynamicPath.length >= 2 ? dynamicPath[dynamicPath.length - 2] : null;

// Generate folder pairs (id, name)
const folders = [];
for (let i = 0; i < dynamicPath.length; i += 2) {
  const id = dynamicPath[i];
  const name = dynamicPath[i + 1];
  if (id && name) {
    folders.push({ id, name });
  }
}

Even if the folder name in the URL is manipulated or incorrect, the component always fetches data based on the folder id. This leads to inconsistencies between the displayed breadcrumb and the actual folder data. Moreover, with deeply nested routes, if someone visits a URL like /dashboard/work-room/1/wrongFolderName/2/data, the component renders using folder id 2 without validating that the folder name for id 1 is correct.

My question is:
How can I validate the full nested folder chain so that if a user manually alters the folder name or adds extra segments. I need a robust approach that works with any level of nesting. tell me it will handle on frontend or from backend.

How can I validate the full nested folder chain so that if a user manually alters the folder name or adds extra segments.

POST WordPress Contact Form 7 Data to API [closed]

I need help trying to send my WordPress CF7 form data to an API, I have tried using the javascript inside of my code but it just runs straight away without waiting for the form to be filled out, I need to be able to run javascript in it.

<div class="small_field">[text* first-name placeholder"First Name"]</div>
<div class="small_field">[text* last-name placeholder"Last Name"]</div>
<div class="small_field">[email* your-email placeholder"Email"]</div>
<div class="small_field">[tel* your-phone placeholder"Phone"]</div>
<div class="large_field">[textarea* your-message]</div>
<div class="large_field">
<div class="animated_stars">
<span class="blink1">★</span><span class="blink2">★</span><span class="blink3">★</span><span class="blink4">★</span><span class="blink5">★</span> 
</div>
<p class="rating_text">2K+ Ratings of Happy Customers</p>
</div>
<div class="large_field btn_field">[submit "Submit"]</div>

I tried to add the javascript via <script type=”text/javascript>… but it would run straight away, and not wait for the form to be filled out first.

react-native-tab-view inside ScrollView is not scrollable by selecting TabView Items (react-navigation’s react-native-tab-view)

I am using react-native-tab-view (doc) in my react native project. These are the versions I use.

"react-native-tab-view": "^4.0.5",
"react-native-pager-view": "^6.6.1",
"react-native": "0.75.4",

In my home page, I have a scroll view and inside that I have different components as contents. When I try to scroll from any other component, it is working fine and scrollable. But when I try to scroll from component, it is not scrolling. I tried changing the styles, adding flex:1, height and a lot. But nothing is working.I don’t understand what I am doing wrong here. If anyoue can help my by suggesting some methods or ideas it will be really helpful.

This is my ScrollView from Home page. In here when I rey to scroll form any component other than HomePageTabContent is working fine.

  <ScrollView
      ref={this.scroll}
      refreshControl={
        <RefreshControl
          refreshing={this.state.refresh}
          onRefresh={this._onRefresh}
        />
      }
      style={[MyStyles.container]}
      scrollEventThrottle={1}
      bouncesZoom={true}
      onScroll={Animated.event(
        [
          {
            nativeEvent: {
              contentOffset: {y: this.state.scrollY},
            },
          },
        ],
        {useNativeDriver: false},
      )}
      stickyHeaderIndices={[1]}
      showsVerticalScrollIndicator={false}>
      <HomePageCarouselSlide pagination={true} colors={colors} />
      <HomePageTabView
        data={tabSlides}
        boxShadow={boxShadowTab}
        translateY={translateY}
      />
      <HomePageTabContent data={tabSlides} />
    </ScrollView>

This is my HomePageTabContent. In here I am able to scroll if I longpress from the . But is not scrollable.

import React from 'react';
import {
  ActivityIndicator,
  Animated,
  Dimensions,
  Platform,
  Text,
  View,
} from 'react-native';
import {Route, SceneMap, TabView} from 'react-native-tab-view';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import HomePageContentTab from '../homePageContentTab/HomePageContentTab';
import {deviceHeight} from '../../../helper';
import {screenHeight} from '../../../constants/styles/Variable';

interface ITabBottomNavProps {
  id: string;
  fields: {
    tabColorPallet: {
      id: string;
      url: string;
     fields: {
        tabColors: {
         id: string;
         fields: {colorCode: {value: string}};
         opacityPercent: {value?: string};
        }[];
      };
    };
    title: {value: string};
    textAndButtonColor: {
      id: string;
      url: string;
      fields: {
        colorCoode: {
          value: string;
        };
      };
    };
 };
}

interface IHomePageTabProps {
  data?: ITabBottomNavProps[];
  activeTabIndex: number; 
}

const HomePageTabContent = (props: IHomePageTabProps) => {
  const {data, activeTabIndex} = props;

  const anim = new Animated.Value(0.1);

  Animated.timing(anim, {
    toValue: 0.5,
    duration: 1000,
    useNativeDriver: true,
  }).start();

  if (data && data.length > 0) {
    const routes: Route[] = data?.map((item: any, index: number): Route => {
      return {key: String(index), title: item.fields.title.value};
    });

const arr = data?.map(_ => {
  return {name: HomePageContentTab};
});

const screenMap: any = {};
arr.forEach((val: {name: any}, index: number) => {
  screenMap[index] = val.name;
});

const tabView = {
  index: activeTabIndex,
  routes,
};

return (
  <View
    style={{
      marginTop: Platform.OS == 'ios' ? 30 : -30,
      minHeight: tabView.index === 2 ? deviceHeight / 2 : deviceHeight,
    }}>
    <TabView
      navigationState={tabView}
      onIndexChange={index => {}}
      renderScene={SceneMap(screenMap)}
      renderTabBar={props => <View style={[{width: '100%'}]} />}
      swipeEnabled={false}
      initialLayout={{width: Dimensions.get('window').width}}
      style={{height: 100}}
    />
    <Text style={{fontSize: 70}}>Hiiii</Text>
    <Text style={{fontSize: 70}}>Hiiii</Text>
    <Text style={{fontSize: 70}}>Hiiii</Text>
  </View>
);
}

return (
<View
  style={{
    height: screenHeight,
    width: '100%',
    position: 'absolute',
    left: 0,
    justifyContent: 'center',
    zIndex: 999,
  }}>
  <ActivityIndicator size="large" color="#e31b23" />
</View>
);
};


const mapStateToProps = (state: any) => {
  return {
    activeTabIndex: state.homePageReducer.homeReducer.activeTabIndex,
  };
};
const mapDispatchToProps = (dispatch: any) => bindActionCreators({}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(HomePageTabContent);

This is my HomePageContentTab.

render() {
return (
  <View>
    <Text style={{fontSize: 30}}>Tab component</Text>
  </View>
);

}

Please don’t suggest me to change the coding structure as I have shared you the minimalistic code, but this works fine other than the scroll issue. It would be really helpful if you can share some ideas to overcome this issue.

Thank you in advance.

How to find today and yesterdays date as dynamic variables in a google app script

I’m currently trying to write a script that copies a sheet from a master copy, then renames it based on todays date, then copies specific cells from the previous days sheet. I currently have the script written where it does all of this, except it instead of copying the previous days sheet based on the date, I can only figure it out to go by sheetname. So currently, the script will make a copy of the Master, rename it to the current date, then copy a specific name, not a dynamic name going by the date. This is because I can’t figure out how to create a “yesterday” that brings up the previous days date. The current date it pulls up is also not in my timezone, so when it creates a new sheet, depending on when I run it, it’ll be the next day instead. For example, its 7pm right now on the 12th of february, when I run the script right now, it names the duplicate sheet for the 13th of february. So I need to pull the current date based on my timezone, and I need to pull yesterdays date, and be able to use those in a getSheetByName way.

function FIguringoutYetserdat() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Master'));
  spreadsheet.duplicateActiveSheet();
  var today = new Date().toISOString().slice(0, 10); 
  spreadsheet.getActiveSheet().setName("Passdown - " + today);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Passdown - 2025-02-11'), true);
  spreadsheet.getRange('C5:O12').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName("Passdown - " + today), true);
  spreadsheet.getRange('C5:O12').activate();
  spreadsheet.setCurrentCell(spreadsheet.getRange('C12'));
  spreadsheet.getRange(''Passdown - 2025-02-11'!C5:O12').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Passdown - 2025-02-11'), true);
  spreadsheet.getRange('A49:O56').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName("Passdown - " + today), true);
  spreadsheet.getRange('A49:O56').activate();
  spreadsheet.getRange(''Passdown - 2025-02-11'!A49:O56').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Passdown - 2025-02-11'), true);
  spreadsheet.getRange('A65:O71').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName("Passdown - " + today), true);
  spreadsheet.getRange('A65:O71').activate();
  spreadsheet.getRange(''Passdown - 2025-02-11'!A65:O71').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

//This is what I have currently. in the areas where its showing “Passdown – 2025-02-11” thats because that’s the name of “yesterday” that I have to currently manually put in to pull info from yesterdays sheet. So thats the area where I want to change it to similar how todays date is putting as “Passdown – ” + today” to find yesterdays sheet by name as “Passdown – ” + yesterday” Thanks in advance.

//I have made some progress with pulling up yesterday’s date, however my issue is now the formatting. Im now using the code —

Utilities.formatDate(new Date(), spreadsheet.getSpreadsheetTimeZone(), "MM/dd/yyyy");
  var yesterday = new Date(Date.now() - 86400000);

The issue is that now the date that is printed is not the same formatting as my date that gets pulled when pulling today. However the formatting itself is also an issue due to how long it is. When pulling today it is a simple mm/dd/yyyy but when pulling yesterday, I’m getting an extensive MMM DD YYYY (HH, MM, SS) format. I do not need the time and would like to keep my mm/dd/yyyy formatting when pulling yesterdays date.

Cypress – How to store specific data set from json response body

I am trying to learn cypress then come across a topic in validating json response body but did not discuss on how to store it in a variable. I would like to know how to store specific data set in a variable for later use. In the response body below I would like to store userId, title, and body for dataset where id = 2.

[
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
        "userId": 1,
        "id": 2,
        "title": "qui est esse",
        "body": "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui aperiam non debitis possimus qui neque nisi nulla"
    },
    {
        "userId": 1,
        "id": 3,
        "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
        "body": "et iusto sed quo iurenvoluptatem occaecati omnis eligendi aut adnvoluptatem doloribus vel accusantium quis pariaturnmolestiae porro eius odio et labore et velit aut"
    },
    {
        "userId": 1,
        "id": 4,
        "title": "eum et est occaecati",
        "body": "ullam et saepe reiciendis voluptatem adipiscinsit amet autem assumenda provident rerum culpanquis hic commodi nesciunt rem tenetur doloremque ipsam iurenquis sunt voluptatem rerum illo velit"
    }
]

For now I can only do this by hardcoding it, I tried to use .each() but getting error message “cy.each() can only operate on an array like subject. Your subject was: “”

cy.request("GET", 'https://jsonplaceholder.typicode.com/posts/')
        .then((response) => {
            expect(response.status).to.equal(200);
            cy.wrap(response.body.id)
               .each(($el, index, $list) =>{
                  if ($el.text() === 2){
                      cy.log(response.body.userId)
                  }
            })
        })

Javascript fetch returning null even after stringify

I’m trying to send data through fetch using this code, but in the Action, i only get a null value and nothing more. I’m certain that the data is not null

async function sendData(epcData) {
    try {
        let formData = new FormData(document.querySelector('#rfidItemForm'));

        let formObject = {};

        formData.forEach((value, key) => {
            formObject[key] = value;
        });

        let send = {
            formData: formObject,
            epcData: epcData
        };
        console.log(send);
        fetch(`${window.location.origin}/EmployeItem/RfidCreate`, {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(send)
        }).catch(error => {
            console.error("Erro ao enviar os dados:", error);
        });
        // Lógica adicional se necessário
    } catch (error) {
        console.error("Erro ao enviar os dados:", error);
    }
}

Here is the structure of ‘send’

epcData: Array(83) [ "E2806995000050084E433050", "E2806995000050084E4891A0", "E2806995000040084E42AD38", … ]
​​0: "E2806995000050084E433050"
​​1: "E2806995000050084E4891A0"
​​2: "E2806995000040084E42AD38"
​​3: "E280699500005004C351ADA4"
4: "E2806995000050084E4941E8"
....

formData: Object { … }
​​EmployeItemId: "0"
​​FkEmployeId: "21019"
​​FkItemId: "55"
​​IsBarCode: "False"
​​IsValid: "True"
​​Size: ""

And here is the Action that has to receive the Json

[HttpPost]
public async Task<JsonResult> RfidCreate([FromBody] RfidCreateRequest send)
{
    try
    {
        
        Console.WriteLine("");
        return Json(new { success = true, message = "" });
    }
    catch (Exception ex)
    {
        return Json(new { success = false, message = ex.Message });
    }
}

Edit: the RfidCreateRequest is a class that have a formData propertie that is of type RfidEmployeItemDto (this class have all the properties that the formData is sending through the json) and another properties called epcData of type List<string>

public class RfidCreateRequest
{
    public RfidEmployeItemDto formData { get; set; } 
    public List<string> epcData { get; set; }
}

How to define a TypeScript type for a nested object as dot nation string

I’m working on a TypeScript project where I need to define a type for a nested object structure. Each object in the tree can have a parentPath property, which is a string that references the name and keys of its parent objects. I want strong TypeScript types for this parentPath so that it’s validated at compile time.

Here’s an example of the object structure I’m dealing with:

const test = {
  name: "Test",
  variables: {
    test: "test"
  },
  children: [
    {
      name: "Test2",
      states: {
        test: "test"
      },
      children: [
        {
          name: "Test3",
          parentPath: "Test.variables.test", // First value (Test) should be the value of "name" of any parent (i.e., Test2 or Test). After that, it should reference the object keys
          something: "hi",
          children: [
            {
              name: "Test4",
              parentPath: "Test3.something"
            },
            {
              name: "Test5",
              parentPath: "Test2.states.test"
            }
          ]
        }
      ]
    }
  ]
}

Android keyboards disappear in dropdown editor field in Tabulator

I think the keyboard causes a resize on the table, which triggers a table.redraw(), which causes the field to lose focus, making the keyboard disappear, but IDK

This happens in a Samsung Tablet with Android 13

Gif showing the problem

Gif taken from the Tabulator docs

var data=[
{location:"United Kingdom"},
{location:"Germany"}
]
//Build Tabulator

var table = new Tabulator("#example-table", {
  height: "311px",
  data:data,
  columns: [
  
    {
      title: "Location",
      field: "location",
      width: 130,
      editor: "list",
      editorParams: {
        autocomplete: "true",
        allowEmpty: true,
        listOnEmpty: true,
        valuesLookup: true
      }
    },
   
  ],
});
<link href="https://unpkg.com/[email protected]/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>

How to fix this problem?

Code hanging up in test, how should i fix?

So I am doing a course through coursera. Max pair in an array. Highest 2 numbers multiply.
The code works in my command prompt. But it is failing on the fourth case.


const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    terminal: false
});

process.stdin.setEncoding('utf8');
rl.on('line', (line) => {
    const arr = line.trim().split(' ').map(Number);
    if (arr.length >= 2 ) {
        console.log(max(arr));
    }
    rl.close();
});

function max(arr) {
    let highest = Math.max(arr[0], arr[1]);
    let secondHighest = Math.min(arr[0], arr[1]);
    for (let i = 2; i < arr.length; i++) {
        let num = arr[i];
        if (num > highest) {
            secondHighest = highest;
            highest = num;
        } else if (num > secondHighest) {
            secondHighest = num;
        }
    }

    let result = highest * secondHighest;
    return result;
}

module.exports = max; 

How to setup Vitest with React Native / Expo? Getting: RollupError: Parse failure: Expected ‘from’, got ‘typeof’

I can run my Vitest usually, but when I try to import a react native link, it breaks with the error below:

RollupError: Parse failure: Expected 'from', got 'typeof'
At file: /mobile-app/node_modules/react-native/index.js:15:8
  File: /mobile-app/node_modules/react-native/index.js:15:8
  13 |  
  14 |  // APIs
  15 |  import typeof ActionSheetIOS from "/node_modules/react-native/Libraries/ActionSheetIOS/ActionSheetIOS.js";
     |         ^
  16 |  import typeof Alert from "/node_modules/react-native/Libraries/Alert/Alert.js";
  17 |  import typeof Animated from "/node_modules/react-native/Libraries/Animated/Animated.js";
/// my test 
import { describe, test, expect, it } from 'vitest';

import { isSolanaAddress } from '@/helpers/formatters';
import * as Linking from 'expo-linking';

describe('deep-link-redirection', () => {
  test('deep-link', () => {
    const { hostname, path, queryParams } = Linking.parse('scheme://path');
    console.log(hostname, path, queryParams);
  });
});
// vite.config.mts 
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [tsconfigPaths()],
});
// babel.config.js
module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
  };
};

How to structure a form with reusable components while maintaining proper validation management?

Description:
I’m working on a Vue/Nuxt project where we typically create a single component that handles all inputs, their state, validation, and submission to the API.

While this approach works, it often leads to large components with hundreds of lines of code due to complex validation rules and business logic.

I’m considering a more modular approach, where each input is an independent component, like this:

<form>
  <select-options @select="data1"/>
  <input-address @value="data2"/>
  <input-phone @value="data3"/> 
  <input-mail @value="data4"/> 
</form>

// check if every required inputs aren't emty
if(!data1 || !data2 || !data3 || !data4) return

Pros of this approach:

  • ✅ Each input manages its own state and errors.
  • ✅ A field only emits its value if it is valid.
  • ✅ The parent form only aggregates validated values before submission.
  • ✅ Smaller, more reusable components.

Cons:

  • ❌ More complex coordination between the parent and child components (e.g., how to ensure all fields are valid?).
  • ❌ Increased number of events and synchronization logic.
  • ❌ Potential complexity if cross-field validation is needed.

On the other hand, a centralized approach:

  • ✅ Provides a unified way to handle validation and errors.
  • ✅ Keeps all business rules in one place.
  • ✅ Simplifies submission logic.

But:

  • ❌ Results in a bloated, hard-to-maintain component.
  • ❌ Reduces input reusability across different forms.

Question:
What are the best practices for handling this in Vue/Nuxt?
Should we favor a modular approach with independent inputs or a centralized approach with a master form?
Have you encountered similar challenges, and how did you solve them?