Stacked div levels showing next level’s back-ground colour

I have an interactive text Element which has grouped text segments. Each text segment can belong to several groups. Each group should be represented visually by a stack of Divs having the edge background colour visible.

Such that the user would realize this text segment belongs to all groups represented by their colour.

I followed this question but it doesn’t help me display the lower level background colours.

For example:

<div>
<div class="group1">Text segment</div>
<div class="group2"></div>
<div class="group3"></div>
<div class="group4"></div>
</div>

.Group1 {
  background-color: shade1;
  z-index:1;
}

.Group2 {
  background-color: shade2;
  z-index:2;
 /* and some other  properties which will show this level underneath */
}

Getting files order base on users selection

I’m trying to figure how can I feature the photos sequence that users select through the input file. e.g:

Users selected from a list of photos the sequece 1.png, 3.png, 10.png, 2.png, 4.png, 8.png…
o I found out that it will depend on the SO that the users are using. Is there a way to force it?

// JavaScript/jQuery
$(document).ready(function() {
  const selectedFiles = [];

  // Handle file input change event
  $("#fileInput").change(function() {
    const fileList = $("#fileInput")[0].files;
    const fileListContainer = $("#fileList");
    fileListContainer.empty();

    // Display selected file names and order
    for (let i = 0; i < fileList.length; i++) {
      const fileName = fileList[i].name;

      if (!selectedFiles.some(file => file.name === fileName)) {
        selectedFiles.push({ name: fileName, order: selectedFiles.length + 1 });
      }

      const listItem = $("<li>").text(selectedFiles.find(file => file.name === fileName).order + ". " + fileName);
      fileListContainer.append(listItem);
    }
  });

  // Attach click event to file input to capture file order
  $(".file-upload-container").on("click", function() {
    selectedFiles.length = 0;
    $("#fileInput").val(""); // Reset file input to allow re-selection of the same files
  });

  // Drag-and-drop functionality (optional)
  $(".file-upload-container").on("dragover", function(e) {
    e.preventDefault();
    $(this).addClass("file-upload-over");
  });

  $(".file-upload-container").on("dragleave", function(e) {
    e.preventDefault();
    $(this).removeClass("file-upload-over");
  });

  $(".file-upload-container").on("drop", function(e) {
    e.preventDefault();
    $(this).removeClass("file-upload-over");

    const droppedFiles = e.originalEvent.dataTransfer.files;
    $("#fileInput")[0].files = droppedFiles;
    $("#fileInput").change();
  });
});

Create a simple Feedback form using node.js as backend – issues connecting to database

This is my index.js which I’m trying to create the connection with my database and my server I want to store the answers from my feedback form to my database the port that I’m using is 3000:

const config = {
    server: "DESKTOP-07", // Replace this with the name or IP address of your MSSQL server
    database: "FeedbackDB",
    options: {
      encrypt: true, 
      trustServerCertificate: true, 
      integratedSecurity: true, 
    },
  };

I checked for any typo in my server name and my database but nothing.

Handling @nuxt/apollo response 400 from graph query

I use @nuxt/apollo in my nuxt3 app for handling graph and in my index.vue I do:

try {
  const { result } = useQuery(query, variables)
} catch (e) {
  console.log('error', e)
}

It works and fetch my data but when I return 400 from graph it’s crashing entire app with this screen (screenshot). How do I handle the error? It’s okey that graph sometimes return 400, I don’t want entire app to crash

enter image description here

“yargs” won’t trigger any command of a script

I have a NodeJs script in which I need parse command line arguments.

I’ve written this code:

import yargs from "yargs";
import { hideBin } from 'yargs/helpers';

  //....
  yargs(hideBin(process.argv)).command('--add-item <val1> <val2>', 'desc', {},
      async (argv) => {
        const { val1, val2 } = argv;
        if (val1 && val2) {
          /**/
        } else {
          console.log('Wrong command line arguments');
        }
    })
    .command('--print <val1>', 'description 123', {},
      async (argv) => {
        const { val1 } = argv;
        if (val1) {
            /**/
        } else {
           console.log('Wrong command line arguments');
        }
    })
    .demandCommand(1, 'You need to provide at least one command')
    .help()
    .alias('help', 'h')
    .parse();
    //......

Then I’ll run it:

$ node my_script.js --add-item 1 2
// or
// $ node my_script.js --print 33

And will always get:

my_script.js <command>

Commands:
my_script.js --add-item <val1> <val2>
// ...........

That is, it’ll show the help info; none of the commands will get triggered.

What’s the matter?

TouchableOpacity is not available in the currently-installed version of react-native [Jest – react native]

After updating react native from version 0.66 to version 0.71.0 with the help of the Upgrade Helper from the official website, the entire application worked normally.
However, the tests no longer worked.
This was probably due to Jest or babel lib updates. But I’m still not sure.
It is worth saying that, what actually happens is that: jest, apparently, no longer ignores the libs informed in transformIgnorePatterns and because of that, several parts of the test, end up breaking, informing that a certain import is undefined, when in reality, that particular imported lib was supposed to be ignored.
It is worth mentioning that even react native components are not being recognized now, after the update.
Below are most of the updates that have occurred in the application:
(https://i.stack.imgur.com/zzppz.png)
(https://i.stack.imgur.com/mF2RH.png)

Error generated after running a simple test on the login screen

Test suite failed to run

TouchableOpacity is not available in the currently-installed version of react-native

  48 | };
  49 |
> 50 | export const RButtonPrimary = styled.TouchableOpacity`
     |                                      ^
  51 |   height: 50px;
  52 |   padding: 10px;
  53 |   ${props => buttonThemeColor[props.theme]};

The error refers to this part of the code:

export const RButtonPrimary = styled.TouchableOpacity`
height: 50px;
padding: 10px;
${props => buttonThemeColor[props.theme]};
border-radius: 10px;
align-self: stretch;
align-items: center;
justify-content: center;
`;

Our jest.config.js:

module.exports = {
  bail: true,
  clearMocks: true,
  collectCoverage: true,
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  transform: {
    '^.+\.(js|ts|jsx|tsx)$': 'babel-jest',
  },
  transformIgnorePatterns: [
    'node_modules/(?!(@react-native|react-native' +
      '|react-navigation-tabs' +
      '|react-native-splash-screen' +
      '|react-native-screens' +
      '|react-native-date-picker' +
      '|react-native-reanimated' +
      '|react-native-vector-icons' +
      '|react-native-gesture-handler' +
      '|@react-native-community' +
      '|@react-navigation' +
      '|@react-navigation/stack' +
      '|react-native-iphone-x-helper' +
      '|react-native-rate' +
      ')/)',
  ],
  setupFiles: [
    './__tests__/mocks/rn-device-info.setup.js',
    './__tests__/mocks/flashmessage.setup.js',
    './__tests__/mocks/rn-elements.setup.js',
    './__tests__/mocks/rn-dash.setup.js',
    './__tests__/mocks/rn-snap-carousel.setup.js',
    './__tests__/mocks/rn-netinfo.setup.js',
    './__tests__/mocks/rn-woodpicker.setup.js',
    './__tests__/mocks/rn-gesture-handler.setup.js',
    './__tests__/mocks/alertmsg.setup.js',
    './__tests__/mocks/touchableopacity.setup.js',
    './__tests__/mocks/async.storage.setup.js',
    './__tests__/mocks/navigation.native.setup.js',
    './__tests__/mocks/auth.context.setup.js',
    './__tests__/mocks/notification.context.setup.js',
    './__tests__/mocks/content.payslip.resume.inf.setup.js',
    './__tests__/mocks/webview.setup.js',
    './__tests__/mocks/sentry.setup.js',
    './__tests__/mocks/react-native-device-info.setup.js',
    './__tests__/mocks/rn-keyboard-aware-scroll-view.setup.js',
    './__tests__/mocks/sleep.setup.js',
    './__tests__/mocks/usedarkmode.setup.js',
    './__tests__/mocks/saveEvent.setup.js',
    './__tests__/mocks/geolocation-service.setup.js',
  ],
  setupFilesAfterEnv: ['./__tests__/mocks/geolocation-service.setup.js'],
  collectCoverageFrom: [
    'src/pages/**/*.js',
    '!src/pages/**/styles.js',
    'src/pages/**/*.tsx',
    '!src/pages/**/styles.ts',
    '!src/services/api.js',
    '!src/config/ReactotronConfig.js',
  ],
  coverageReporters: ['json', 'lcov'],
  coverageDirectory: '__tests__/coverage',
  moduleNameMapper: {
    '^~/(.*)': '<rootDir>/src/$1',
  },
  testMatch: ['**/__tests__/**/*.test.js'],
  maxWorkers: 3,
  globals: {
    'ts-jest': {
      diagnostics: false,
      isolatedModules: true,
    },
  },
};

Difference between index and path=””

I’m now learning React Router. I have the following set of routes:

<Routes>
    <Route path="/" element={<Home />} />
    <Route path="/books">
        <Route path=":id" element={<Book />} />
        <Route path="new" element={<NewBook />} />
        <Route index element={<BookList />} />
    </Route>
</Routes>

If I replace index in the last route with path="" I see no difference in behavior.

{// ...
        <Route path="" element={<BookList />} />

Why should I prefer to use index, instead of path=""?

When we log in to the App, we are taken to the Home Screen. we have not visible Drawer navigation

    import { StatusBar } from 'expo-status-bar';
    import { StyleSheet, View } from 'react-native';
    import React from 'react';
    import Reg_form from './Frontend/Components/RegForm';
    import Login_form from './Frontend/Components/Signin';
    import ForgotPassword from './Frontend/Components/ForgotPassword';
    import { ApplicationProvider, Layout, Text } from '@ui-kitten/components';
    import { NavigationContainer } from "@react-navigation/native";
    import { createNativeStackNavigator } from "@react-navigation/native-stack";
    import {
      createDrawerNavigator,
      DrawerContentScrollView,
      DrawerItemList,
      DrawerItem,
    } from '@react-navigation/drawer';
    import * as eva from '@eva-design/eva';
    import ChangePassword from './Frontend/Components/ChangePassword';
    import VerifyOTP from './Frontend/Components/VerifyOTP';
    import Home from './Frontend/Components/Home Screen';
    import Profile from './Frontend/Components/Profile';
    import Icon from 'react-native-vector-icons'
    const Stack = createNativeStackNavigator();
    const Drawer = createDrawerNavigator();
    
    const CustomDrawer = props => {
    
      return (
        <View style={{ flex: 1 }}>
          <DrawerContentScrollView {...props}>
            <View
              style={{
                alignSelf: "center",
                padding: 20,
    
              }}
            >
              <View>
                <Text style={{ fontSize: 18, fontWeight: "bold" }}> App</Text>
              </View>
    
            </View>
            <DrawerItemList {...props} />
            <LogoutButton iconName="sign-out" color="black" />
          </DrawerContentScrollView>
    
        </View>
      );
    };
    
    
    
    function DrawerRoutes() {
    
    
      return (
    
        <Drawer.Navigator initialRouteName="Home"
    
          drawerContent={props => <CustomDrawer {...props} />}
        >
    
          <Drawer.Screen name="Home" component={Home}
    
            options={{
              headerShown: true,
              
              title: 'Home',
              drawerIcon: ({ focused, size }) => (
                <Icon
                  name="home"
                  size={size}
                  color='black'
    
                />
    
              )
            }}
          />
          <Drawer.Screen name="Profile" component={Profile}
    
            options={{
              headerShown: true,
              title: 'Profile',
              drawerIcon: ({ focused, size }) => (
                <Icon
                  name="user"
                  size={size}
                  color='black'
    
                />
    
              )
            }}
          />
        
    
    
    
        </Drawer.Navigator>
      );
    }
    
    export default function App() {
      return (
        <ApplicationProvider {...eva} theme={eva.light}> 
        
        <NavigationContainer>
        <Stack.Navigator>
                  <Stack.Screen name="Registration" component={Reg_form} />
                  <Stack.Screen name="Log In" component={Login_form}/>
                  <Stack.Screen name="Forgot" component={ForgotPassword}/>
                  <Stack.Screen name="Password" component={ChangePassword}/>
                  <Stack.Screen name="Verification" component={VerifyOTP}/>
                  <Stack.Screen name="Home" component={Home}  />
                  <Stack.Screen name="DrawerRoutes" component={DrawerRoutes}/>
                 
      </Stack.Navigator>
      
      </NavigationContainer>
        
      </ApplicationProvider>
      );
    }

*Error: When we log in to the App, we are taken to the Home Screen. However, we cannot see the Drawer navigation. The drawer navigation is hidden. Please go through this again. The HeaderShown option is set to true. we have updated the Home screen to show the drawer navigation menu. We have done this by setting the headerShown property to true. This will ensure that the drawer navigation menu is always visible when the Home screen is rendered but Drawer navigation is not visible on the Home Screen.

Incorrect Element Being Assigned Class

I created a toggle switch between two <p> elements. At first, the <p> element that contains the text Monthly has a class named .plan-type-active.

When the toggle switch is clicked, the toggle moves to the other side of the switch, and the class is removed from the Monthly <p> element and is then assigned to the Yearly <p> element. Whenever the toggle switch is clicked, the class is switched among the <p> elements.

Everything seems to be working as intended initially, but I found that when I rapidly click on the .slider element, eventually, the incorrect <p> element will get the plan-type-active class. Why is this? How do I fix it? It’s kind of annoying to reproduce the issue, but after a bit of rapid clicking of the element, something indeed does get messed up.

const toggleSwitch = document.querySelector(".slider");
const planPaymentType = document.querySelector(".plan-payment-type");


toggleSwitch.addEventListener("click", function () {
  const activePlanType = planPaymentType.querySelector(".plan-type-active");
  const nonActivePlanType = planPaymentType.querySelector("p:not(.plan-type-active)");
 

  activePlanType.classList.remove("plan-type-active");
  nonActivePlanType.classList.add("plan-type-active");
})
.plan-payment-type {
  display: flex;
  gap: 17px;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  background-color: hsl(217, 100%, 97%);
  padding: 10px;
  border-radius: 5px;
}

.toggle-switch {
  position: relative;
  display: inline-block;
  width: 33px;
  height: 18px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: hsl(213, 96%, 18%);
  transition: 0.4s;
  border-radius: 20px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 10px;
  width: 10px;
  left: 4px;
  top: 4px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50%;
}

input:checked + .slider:before {
  transform: translateX(15px);
}

.plan-type-active {
  color: hsl(213, 96%, 18%);
}

.plan-payment-type p:not(.plan-type-active) {
  color: hsl(231, 11%, 63%);
}
<div class="plan-payment-type">
    <p class="plan-type-active monthly-plan">Monthly</p>
    <label class="toggle-switch">
        <input type="checkbox" />
        <span class="slider"></span>
    </label>
    <p class="yearly-plan">Yearly</p>
</div>

Fill a empty value of a key-value pair using the next value

Fill a empty value of a key-value pair with the next value of the next key.

myitems = {
 'items1': [{first:true, second:false}, {first:true, second:true}],
 'items2': [], //should be filled with {first:true, second:false}
 'items3': [], //should be filled with {first:true, second:false}
 'items4': [{first:true, second:false}, {first:true, second:true}],
 'items5': [{first:false, second:true}],
 'items6': [], //should be filled with {first:true, second:true}
 'items7': [{first:true, second:true}],
}

I have tried the follow:

Object.entries(myItems).forEach(([key, value], index, values: any) => {
   if (!values[index][1].length && values[index+1] && values[index+1][1].length) {
   myItems[key] = [{...values[index + 1][1][0]}]
 }
})

react-native-maps not showing marker information when clicking on a pin

I have a react native project in which I am trying to integrate react-native-maps into the application. For each pin, I want to display some information when the user clicks on the pin itself. Right now I have MapView and Marker. I trued using Callout but it is not displaying correctly.

Here is the file:

import React, { useContext } from 'react'
import { View, Text, Image, StyleSheet } from 'react-native'
import MapView, { Marker, Callout } from 'react-native-maps';
import { PropertyContext } from '../../../../context/PropertyContext';

const MapViewComponent = () => {

  const { results, currentLat, currentLong } = useContext(PropertyContext)

  return (
    <>
      <MapView 
        scrollEnabled={true}
        zoomEnabled={true}
        zoomTapEnabled={true}
        style={styles.mapWindow} 
        initialRegion={{
          latitude: currentLat,
          longitude: currentLong,
          latitudeDelta: 0.5,
          longitudeDelta: 0.5,
        }}
      >
        {
          results.map((property) => {
            return(
              <Marker 
                pinColor='blue'
                key={property.zpid}
                coordinate={{
                  longitude: property.longitude,
                  latitude: property.latitude
                }}
              >
                <Callout 
                  onPress={() => {
                    return(
                      <View style={styles.homeContainer}>
                        <Text>{property.zpid}</Text>
                      </View>
                    )
                  }}
                />
              </Marker>
            )
          })
        }
      </MapView>
    </>
  )
}

const styles = StyleSheet.create({
  mapWindow: {
    height: '100%',
    width: '100%',
  },
  homeContainer: {
    height: 300,
    width: 300,
    backgroundColor: 'white',
    borderRadius: 12
  }
})

export default MapViewComponent

My Reload code does not work on Edge but does on Chrome

I am trying to refresh my screen after going back to it.

I go back to it with the code:

  window.history.back(); 

My ‘back’ page has this function that works on chrome:

(function () {
    console.log("anon function");
    window.onpageshow = function(event) {
        console.log("onpageshow");
        if (event.persisted) {
            console.log("event.persisted");
            window.location.reload();
        }
    };
})();

On Edge is see “anon function” and “onpageshow” on the console but not “event.persisted”

Anyone give me a more browser friendly approach. W3Schools says event.persisted works on Edge.

Running Version 114.0.1823.86 (Official build) (64-bit)

Issue with Dialogflow and forward slashes

I am using webhooks fulfillment for a Dialogflow chatbot which requires my parameters to be exactly as is in terms of spacing and characters. When I train my phrases, this seems to be working fine: enter image description here

However, when I try to use my agent, it doesn’t work because the area value seems to include spaces on either side of the forward slash. I tried resolving this within my inline editor by checking for the ‘ / ‘ pattern using regex in my variable storing my parameter and then replacing it with just a slash, but that didn’t work either. Any idea how I can fix this? I can’t create a custom entity and add synonyms for this parameter since there are too many possible options. This is what is happening:

enter image description here

Is there a way to validate that a regular expression will consume, at most, one character?

This is a particularly hard thing to Google, because most questions are about how one writes a regular expression to match a single character, which is not my question.

My question is: if I have a JavaScript / TypeScript API, that allows a user to supply any given regular expression, but their regular expression should match only 0-1 characters, how would I throw an error if the regular expression a user wrote can match more than one character?

For example:

/[a-z]/        // valid
/[a-z][A-Z]/   // invalid
/[a-z]{1}/     // valid
/[a-z]{2}/     // invalid
/[a-z]*/       // invalid
/[a-z]+/       // invalid

…etc

It feels like it could get tedious to think of all the ways someone could specify a regex to match multiple characters. Any thoughts on how this could be accomplished?

How do I use Media Queries in the Next.js App Router?

I am using Next.js 13 with the App Router and have the following client component, which uses media queries inside the javascript to display a sidebar differently for small/big screens.

"use client";

export default function Feed() {
    const [isLargeScreen, setIsLargeScreen] = useState(window.matchMedia("(min-width: 768px)").matches);

    useEffect(() => {
    window
        .matchMedia("(min-width: 1024px)")
        .addEventListener('change', e => setIsLargeScreen(e.matches));
    }, []);

    return (
        <div>
            <Sidebar isLargeScreen={isLargeScreen}/>
            <div>...</div>
        </div>
    )
}

Now, the site loads inside the client perfectly, but since the Next.js App Router renders this component once on the server and the server has no window property, I will always get this error on the server (the console running npm run dev in local development mode):

error ReferenceError: window is not defined
at Feed (./app/feed/page.tsx:32:95)
> 17 |     const [isLargeScreen, setIsLargeScreen] = useState(window.matchMedia("(min-width: 768px)").matches);

I can replace the troublesome line with a if-else like this:

const [isLargeScreen, setIsLargeScreen] = useState(typeof window == "undefined" ? true : window.matchMedia("(min-width: 768px)").matches);

which then results in an runtime error on the client, if the server renders the component with the state set to true, but the client (on a small screen in this example) renders the component with the state set to false:

Unhandled Runtime Error

Error: Hydration failed because the initial UI does not match what was rendered on the server.

How can change this component so the server and client will not throw any errors?