How to decode nested numeric patterns in strings like 2[2[32]1[82]] in JavaScript?

I’m trying to solve a variation of the classic “Decode String” problem in JavaScript, but instead of characters or strings inside brackets, my inputs contain numbers — and they can be nested.

let sampleA = "3[2]5[8]"; 
// Expected output: "22288888"

let sampleB = "2[2[32]1[82]]"; 
// Expected output: "323282323282"

Thanks in advance!

What I tried and what I expected:

I started by modifying a standard decoder that handles strings like "3[a]2[bc]". Here’s a simplified version of what I tried:

function decodeString(s) {
  const stack = [];
  let current = "";
  let k = 0;

  for (let ch of s) {
    if (!isNaN(ch)) {
      k = k * 10 + parseInt(ch);
    } else if (ch === '[') {
      stack.push([current, k]);
      current = "";
      k = 0;
    } else if (ch === ']') {
      const [prev, repeat] = stack.pop();
      current = prev + current.repeat(repeat);
    } else {
      current += ch;
    }
  }

  return current;
}

This works fine for alphabetic inputs like "3[a2[c]]""accaccacc".
But for my case with numeric content like "2[2[32]1[82]]", it fails because:

  • It treats numbers only as repeat counts.

  • It doesn’t distinguish numbers inside brackets from the ones outside.

  • The inner numeric strings get interpreted incorrectly or ignored.

Can’t run npm run android for react native app

I am completely new to React-Native world. I was setting up React-Native ENV locally for existing project. I am getting Task :app:mergeDebugAssets FAILED error when i run npm run android please help me. Thanks in advance.

I have attached screenshot of technical stacks i am using for env setup and also attached important file info, please let me know if any other info is required.

Here is my npx react-native info

Error info

> Task :app:mergeDebugAssets FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.9/userguide/command_line_interface.html#sec:command_line_warnings
86 actionable tasks: 86 executed

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugAssets'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform annotation-experimental-1.4.0.aar (androidx.annotation:annotation-experimental:1.4.0) to match attributes {artifactType=android-assets, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Execution failed for JetifyTransform: /Users/bahubali/.gradle/caches/modules-2/files-2.1/androidx.annotation/annotation-experimental/1.4.0/c7a2038d831d0cfbfb9a440890b287c2e839ecf/annotation-experimental-1.4.0.aar.
         > Failed to transform '/Users/bahubali/.gradle/caches/modules-2/files-2.1/androidx.annotation/annotation-experimental/1.4.0/c7a2038d831d0cfbfb9a440890b287c2e839ecf/annotation-experimental-1.4.0.aar' using Jetifier. Reason: IllegalArgumentException, message: Unsupported class file major version 61. (Run with --stacktrace for more details.)
           Suggestions:
            - Check out existing issues at https://issuetracker.google.com/issues?q=componentid:460323&s=modified_time:desc, it's possible that this issue has already been filed there.
            - If this issue has not been filed, please report it at https://issuetracker.google.com/issues/new?component=460323 (run with --stacktrace and provide a stack trace if possible).

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 7m 25s

gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions/gradle-6.9-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

App leve build.gradle

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
    }
    dependencies {
    }
}


apply plugin: "com.android.application"

import com.android.build.OutputFile



project.ext.react = [
    enableHermes: true,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"


def enableSeparateBuildPerCPUArchitecture = true

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false


def jscFlavor = 'org.webkit:android-jsc:+'


def enableHermes = project.ext.react.get("enableHermes", false);

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    dexOptions {
        incremental true
        javaMaxHeapSize "4g"
    }


    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode MYAPP_UPLOAD_VERSION_CODE.toInteger()
        versionName MYAPP_UPLOAD_VERSION_NAME
        vectorDrawables.useSupportLibrary = true
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk true  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            storeFile file(MYAPP_UPLOAD_STORE_FILE)
            storePassword MYAPP_UPLOAD_STORE_PASSWORD
            keyAlias MYAPP_UPLOAD_KEY_ALIAS
            keyPassword MYAPP_UPLOAD_KEY_PASSWORD
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    packagingOptions {
        pickFirst "lib/armeabi-v7a/libc++_shared.so"
        pickFirst "lib/arm64-v8a/libc++_shared.so"
        pickFirst "lib/x86/libc++_shared.so"
        pickFirst "lib/x86_64/libc++_shared.so"
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    implementation project(':react-native-splash-screen')

    implementation project(':lottie-react-native')

    implementation 'com.airbnb.android:lottie:4.2.0'

    implementation project(':react-native-maps')
    implementation project(':react-native-code-push')

    compile project(':react-native-exception-handler')


    //implementation group: 'com.cloudinary', name: 'cloudinary-android'

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())

allprojects {
    configurations.all {
        resolutionStrategy {
            // Remove this override in 0.65+, as a proper fix is included in react-native itself.
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
        }
    }
}

Root level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        ndkVersion = "20.1.5948944"
        playServicesVersion = "17.0.0"
        androidMapsUtilsVersion = "2.2.2"
        supportLibVersion = "28.0.0"
        RNMapboxMapsImpl = "maplibre" // optinal - as this is the default

        RNMapboxMapsLibs = { // optional - only required if you want to customize it
            implementation ("org.maplibre.gl:android-sdk:9.5.2")
            implementation ("org.maplibre.gl:android-sdk-turf:5.9.0")

            implementation ("org.maplibre.gl:android-plugin-localization-v9:1.0.0")
            implementation ("org.maplibre.gl:android-plugin-annotation-v9:1.0.0")
            implementation ("org.maplibre.gl:android-plugin-markerview-v9:1.0.0")
        }
    }
    repositories {
        google()
        mavenCentral()
        //jcenter()
        //maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.1")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    tasks.withType(Javadoc).all { enabled = false }
    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
            maven { url "https://maven.google.com" }
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        //jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

How to define props with nested structure and generics?

I’m trying to define props with nested structure and generics, but I’m encountering an error

Current issue: error on line 46

Desired solution path, only modify the generics and parameter types of defineProps, do not modify other types.

import { Ref } from "vue";

interface IPropDef<T> {
  title: string | Ref<string>;
  default: T;
  editorOnly?: boolean;
  exit?: boolean;
}

type IInvalidConfigKey = `$${string}` | keyof IPropDef<unknown>;

type IPropConfig<T> = {
    [P in keyof T]: P extends IInvalidConfigKey
        ? never
        : T[P] extends Record<string, unknown>
          ? IPropConfig<T[P]>
          : IPropDef<T[P]>;
};

type DeepIPropConfig = {
  [key: string]: IPropDef<unknown> | DeepIPropConfig;
}

function defineProps<T extends Record<string, unknown> = Record<string, unknown>>(
  props: IPropConfig<T> & DeepIPropConfig
): void {}


//-------------- split-line --------------
// Test case
// Constraints to be met:
// 1. Users can choose to pass in generics or not (case1 and case2)
// 2. When users pass in generics
  // 2.1 They can pass in only some keys in props or all keys (case1 and case2)
  // 2.2 The type corresponding to the passed key needs to include the type inferred from the default defined in props (case3)
// 3. Both T and props are nested structures

// case1
defineProps({
  trigger: {
      title: 'string',
      default: true,
  },
  mask: {
      // Error: Object literal may only specify known properties, and 'isShow' does not exist in type 'IPropDef<string>'
      isShow: {
          title: "just show",
          default: true,
      },
      close: {
          title: "Just close",
          default: false,
      },
  },
});

// case1
defineProps<{
  trigger: boolean;
}>({
  trigger: {
      title: 'string',
      editorOnly: true,
      default: true,
  },
  mask: {
      isShow: {
          title: "just Show",
          default: true,
          // Notice: When I type "edi", The IDEA can give me the correct type hint.(editorOnly)
          // edi
      },
      close: {
          title: "just Close",
          default: false,
      },
  },
});

// case3:
defineProps<{
  // Manually provide a more precise, expected type
  trigger: boolean | string;
}>({
  trigger: {
    title: 'string',
    default: true,
  },
});

Typescript playground: playground

SwiperJs not working properly when rendering it conditionally

In my angular application, I have 4 swiper slide, which i want to render conditionally. But its not working properly. I have added images as well at bottom.

Issue – On initial load all swiper are rendering properly with 4 slides per view. But suppose if select swiper_1 then its showing 1 slide per view but according to swiperParam it should show 4 slide per view.
If I select others like swiper_2, or swiper_3, then its showing 4 slides per view, and then if i select all then all swiper are showing 4 slide per view except the previous selected swiper “swiper_2 or swiper_3”.

I think the parameters are not getting applied properly.

Typescript ->

import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, ElementRef, NgZone, QueryList, Renderer2, ViewChild, ViewChildren, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-swiper-testing',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './swiper-testing.component.html',
  styleUrls: ['./swiper-testing.component.scss'],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  encapsulation: ViewEncapsulation.None,
})
export class SwiperTestingComponent {

  constructor(private el: ElementRef, private cdRef: ChangeDetectorRef, private ngZone: NgZone, private renderer: Renderer2) { }

  @ViewChild('swiper_1') swiper_1!: ElementRef;
  @ViewChild('swiper_2') swiper_2!: ElementRef;
  @ViewChild('swiper_3') swiper_3!: ElementRef;
  @ViewChild('swiper_4') swiper_4!: ElementRef;

  selectedCategories: string = 'all';

  swiperParams = {
    loop: false,
    slidesPerView: 1,
    spaceBetween: 24,
    breakpoints: {
      640: {
        slidesPerView: 2,
      },
      1024: {
        slidesPerView: 3,
      },
      1200: {
        slidesPerView: 4,
      },
      1500: {
        slidesPerView: 4.5,
      },
      1700: {
        slidesPerView: 5,
      },
      1900: {
        slidesPerView: 5.5,
      },
    },
    navigation: true,
  };
  
  
  ngAfterViewInit() {
    this.swiper_1Swiper();
    this.swiper_2Swiper();
    this.swiper_3Swiper();
    this.swiper_4Swiper();
  }

  categoriesSelect(value: string) {
    if (this.selectedCategories === value) return;
  
    this.selectedCategories = value;
    this.cdRef.detectChanges();
  
    // Let Angular fully update the view first
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.ngZone.run(() => {
          if (value === 'all' || value === 'swiper_1') this.swiper_1Swiper();
          if (value === 'all' || value === 'swiper_2') this.swiper_2Swiper();
          if (value === 'all' || value === 'swiper_3') this.swiper_3Swiper();
          if (value === 'all' || value === 'swiper_4') this.swiper_4Swiper();
        });
      }, 0);
    });
  }
  
  swiper_1Swiper() {
    if (this.swiper_1?.nativeElement) {
      const swiperEl = this.swiper_1.nativeElement;
      Object.assign(swiperEl, this.swiperParams );
      swiperEl.initialize();
    }
  }
  
  
  swiper_2Swiper() {
    if (this.swiper_2?.nativeElement) {
      const swiperEl = this.swiper_2.nativeElement;
      Object.assign(swiperEl, this.swiperParams);
      swiperEl.initialize();
    }
  }
  swiper_3Swiper() {
    if (this.swiper_3?.nativeElement) {
      const swiperEl = this.swiper_3.nativeElement;
      Object.assign(swiperEl, this.swiperParams);
      swiperEl.initialize();
    }
  }
  swiper_4Swiper() {
    if (this.swiper_4?.nativeElement) {
      const swiperEl = this.swiper_4.nativeElement;
      Object.assign(swiperEl, this.swiperParams);
      swiperEl.initialize();
    }
  }
  

}

HTML ->

<div>
    <div class="main">
        <div class="filter-container d-flex justify-content-between align-items-start">
            <button type="button" class="btn btn-primary selected" (click)="categoriesSelect('all')">All
                swiper</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_1')">swiper 1</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_2')">swiper 2</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_3')">swiper 3</button>
            <button type="button" class="btn btn-primary" (click)="categoriesSelect('swiper_4')">swiper 4</button>
        </div>
        <div class="d-flex flex-column gap-4 mt-48">

            <div class="cards-swiper-container"
                *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_1'">
                <h4 class="mb-0">swiper_1 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_1>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
            <div class="cards-swiper-container" *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_2'">
                <h4 class="mb-0">swiper_2 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_2>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
            <div class="cards-swiper-container"
                *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_3'">
                <h4 class="mb-0">swiper_3 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_3>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
            <div class="cards-swiper-container" *ngIf="selectedCategories === 'all' || selectedCategories === 'swiper_4'">
                <h4 class="mb-0">swiper_4 </h4>
                <div class="navigation-wrapper"></div>
                <swiper-container class="mySwiper" init="false" #swiper_4>
                    <swiper-slide *ngFor="let item of [1,2,3,4,5,6,7,8];">
                    </swiper-slide>
                </swiper-container>
            </div>
        </div>
    </div>
</div>

All selected ->

enter image description here

Selected Swiper_1 ->

enter image description here

Selected Swiper_2 ->

enter image description here

Selected All again ->

enter image description here

Google Apps Script, getStartTime/getEndTime

Im currently working on a simple internal add-on for google calendar. When we click a event we will choose a option from a dropdown and click a button. When that happens, take the selected item with its corresponding attributes (working) and the events start and end- time. I cannot for the love of me get the time to work. What am I missing?

For now the logic is not there i just simply want to see the start and end times in the Log.

When this runs, and a item is selected, and we press the button we will in the log get the following:

  • Apr 23, 2025, 8:40:24 AM Info Selected customer ID: 1337
  • Apr 23, 2025, 8:40:24 AM Info Event start time: Invalid Date
  • Apr 23, 2025, 8:40:24 AM Info Event end time: Invalid Date

This is the script:

/**
 * Callback for opening a calendar event.
 * @param {Object} e The event object for the open callback.
 * @return {CardService.Card} The card to show to the user.
 */
function onCalendarEventOpen(e) {
  var cardBuilder = CardService.newCardBuilder();
  var customerData = getCustomersFromApi();

  var selectionInput = CardService.newSelectionInput()
      .setType(CardService.SelectionInputType.DROPDOWN)
      .setFieldName("dropdown_field")
      .setTitle("Select a customer");

  customerData.forEach(function(customer) {
    selectionInput.addItem(customer.name, customer.id, false);
  });

  var startTime = "";
  var endTime = "";

  // SAFELY extract start and end time strings from calendar event
  if (e && e.calendarEvent) {
    var event = e.calendarEvent;
    if (event.getStartTime && event.getEndTime) {
      startTime = event.getStartTime().toISOString();
      endTime = event.getEndTime().toISOString();
    }
  }

  var action = CardService.newAction()
    .setFunctionName("onTidsraporteraClick")
    .setParameters({
      startTime: startTime,
      endTime: endTime
    });

  var button = CardService.newTextButton()
      .setText("Tidsraportera")
      .setOnClickAction(action);

  var section = CardService.newCardSection()
      .addWidget(selectionInput)
      .addWidget(button);

  return cardBuilder.addSection(section).build();
}

/**
 * Callback for when the "Tidsraportera" button is clicked.
 * Logs the selected customer and the calendar event start/end times.
 * @param {Object} e The event object containing form inputs and parameters.
 * @return {CardService.ActionResponse}
 */
function onTidsraporteraClick(e) {
  try {
    var selectedCustomerId = e.commonEventObject.formInputs["dropdown_field"].stringInputs.value[0];
    Logger.log("Selected customer ID: " + selectedCustomerId);

    var startTime = new Date(e.parameters.startTime);
    var endTime = new Date(e.parameters.endTime);

    Logger.log("Event start time: " + startTime);
    Logger.log("Event end time: " + endTime);
  } catch (error) {
    Logger.log("Error in onTidsraporteraClick: " + error);
  }

  return CardService.newActionResponseBuilder()
    .setNotification(CardService.newNotification()
      .setText("Customer: " + selectedCustomerId + "nStart: " + startTime + "nEnd: " + endTime))
    .build();
}

This is a part of the appscript.json:

{
  "timeZone": "Europe/Berlin",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/calendar.addons.execute",
    "https://www.googleapis.com/auth/script.locale",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.googleapis.com/auth/calendar",
    "https://www.google.com/calendar/feeds",
    "https://www.googleapis.com/auth/script.external_request"
  ],

Ive experimented with grabing it as a date, a string and then passing it to the onClick to then convert it back to Date. For this version we are getting Invalid date, but before that mostly I was getting Undefined so there is something wrong when i try to grab the events time.

How to populate a field in array?

How can I populate the Amount $ (Tax Included) field based on input from the respective Quantity field? E.g. When user enter a quality of 5 in the Flower row (Row #2), 5 is supposed to be populated in the respective Amount $ (Tax Included) row (Row #2).

Both the Quantity & Amount $ (Tax Included) fields are arrays.

<td align="right"><input class="amt" id="amt" name="amt[]" step="0.01" type="number" required /></td>
<td align="right" height="32" class="label"><span id="sum" name="sum[]">0.00&nbsp;</span></td>

I’m able to get the quantity value entered in the respective rows but I’m not sure how to populate the value into the respective Amount $ (Tax Included) row.

$(document).ready(function() {
var cnt = 0;


$('[name="amt[]"]').change(function() {         
    var amt_list = $("input[name^='amt']").map(function (idx, ele) {
        return $(ele).val();    
    }).get();

    cnt = amt_list.length;

    for (i = 0; i < cnt; i++) {
        if (!isEmpty(amt_list[i])) {
            alert(i);
            $("input[name='sum[i]']").html(amt_list[i]); // Stuck here
        }
    }
});     

});

enter image description here

Thanks in advance for any suggestions.

How to properly handle CSS animations in sync with JavaScript events?

I’m working on a project where I need to trigger a CSS animation in response to a JavaScript event, but I’m running into issues where the animation either doesn’t trigger correctly and plays multiple times when it should only happen once.

Specifically, I’m using a JavaScript click event to trigger a CSS animation on an element. The problem is that the animation continues to play even after the event is triggered once, and I need it to run only once per click.

I added an event listener for the click event, so when I click the cat, it adds the animate class to trigger the scaling animation. I expected the cat to scale up just once on the first click and not repeat, but instead, the animation keeps playing every time I click, and it doesn’t reset, causing it to repeat even after one click.

save and credit system management

web based in php and js

SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
SET time_zone = “+00:00”;

— Customers Table
CREATE TABLE IF NOT EXISTS customers (
acc_number INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
phone VARCHAR(20) NOT NULL,
image_path VARCHAR(2000) NOT NULL,
branch_name VARCHAR(33) NOT NULL,
pass VARCHAR(255) NOT NULL,
balance DECIMAL(10, 2) DEFAULT 0.00,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Employee Table
CREATE TABLE IF NOT EXISTS employee (
emp_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
emp_username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) NOT NULL,
pass VARCHAR(255) NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
salary DECIMAL(10, 2) NOT NULL,
phone VARCHAR(20) NOT NULL,
files VARCHAR(2000) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Admin Table
CREATE TABLE IF NOT EXISTS e_admins (
admin_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
admin_username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) NOT NULL,
pass VARCHAR(255) NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
phone VARCHAR(20) NOT NULL,
files VARCHAR(2000) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Branch Admin Table
CREATE TABLE IF NOT EXISTS branchs_admins (
branch_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
b_username VARCHAR(255) UNIQUE NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
b_email VARCHAR(255) UNIQUE NOT NULL,
pass VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
files VARCHAR(255) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Super Admin Table
CREATE TABLE IF NOT EXISTS super_admin (
sup_id INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(255) NOT NULL,
lname VARCHAR(255) NOT NULL,
sup_username VARCHAR(255) UNIQUE NOT NULL,
sex VARCHAR(10) NOT NULL,
age INT NOT NULL,
sup_email VARCHAR(255) UNIQUE NOT NULL,
pass VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
files VARCHAR(255) NOT NULL,
hire_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Saving Table
CREATE TABLE IF NOT EXISTS saving (
save_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
save_amount DECIMAL(10,2) NOT NULL,
save_interest DECIMAL(5,2) NOT NULL,
interest_year VARCHAR(100) NOT NULL,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE customers
MODIFY acc_number INT NOT NULL;
ALTER TABLE saving
MODIFY customer_acc VARCHAR(20) NOT NULL,
DROP FOREIGN KEY saving_ibfk_1,
ADD FOREIGN KEY (customer_acc)
REFERENCES customers(acc_number);

— Loan Table
CREATE TABLE IF NOT EXISTS loan (
l_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
loan_status ENUM(‘pending’, ‘accepted’, ‘completed’, ‘canceled’) DEFAULT ‘pending’,
loan_amount DECIMAL(10,2) NOT NULL,
loan_interest DECIMAL(5,2) NOT NULL,
files VARCHAR(3000) NOT NULL,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Loan Payment Table
CREATE TABLE IF NOT EXISTS loan_pay (
p_id INT AUTO_INCREMENT PRIMARY KEY,
loan_id INT NOT NULL,
customer_acc INT NOT NULL,
loan_status ENUM(‘pending’, ‘accepted’, ‘completed’, ‘canceled’) DEFAULT ‘pending’,
loan_amount DECIMAL(10,2) NOT NULL,
loan_interest DECIMAL(5,2) NOT NULL,
strt_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (loan_id) REFERENCES loan(l_id),
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Transactions Table
CREATE TABLE IF NOT EXISTS transactions (
t_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
t_type ENUM(‘deposit’, ‘withdraw’) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
t_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Other Bank Transactions Table
CREATE TABLE IF NOT EXISTS transaction_otherbanks (
t_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
from_bank ENUM(‘CBE’,’BOA’,’Zemen’,’otherbanks’) NOT NULL,
t_type ENUM(‘receive’, ‘send’) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
t_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Feedback Table
CREATE TABLE IF NOT EXISTS feedback (
fe_id INT AUTO_INCREMENT PRIMARY KEY,
for_role ENUM(‘customers’, ’employee’, ‘e_admins’, ‘branchs_admins’, ‘super_admin’) NOT NULL,
txts VARCHAR(2000) NOT NULL,
feedback ENUM(‘suggestion’, ‘complaint’) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

— Contact Table
CREATE TABLE IF NOT EXISTS contact (
ct_id INT AUTO_INCREMENT PRIMARY KEY,
customer_acc INT NOT NULL,
contact_type ENUM(’email’, ‘call’) NOT NULL,
FOREIGN KEY (customer_acc) REFERENCES customers(acc_number)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Why is my user being logged out from my React Native app, using firebase/auth

I have a react native app where I use firebase/auth.

This is what I have in my package.json file:

"dependencies": {
    ....
    "@react-native-firebase/analytics": "^21.7.1",
    "@react-native-firebase/app": "^21.7.1",
    "firebase": "10.13",
    ....
}

Please let me know if I need to have something else in my dependencies.

This is my App.js file:

import { getAuth, signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth";

const App = () => {

  const [verified, setVerified] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  ...
  ...
  ...
  useEffect(() => {
      const auth = getAuth();
      const unsubscribe = onAuthStateChanged(auth, (user) => {
        if(user){
          setCurrentUser(user);
          setVerified(user.emailVerified);
        }else{
          setCurrentUser(null);
        }
      });
      return () => unsubscribe();
    }, []);
    ...
    ...
    ...
    if(!currentUser){
      return (
        <NavigationContainer>
          <AuthNavigator />
        </NavigationContainer>
      );
  }
  else if (currentUser && !verified){
    return (
      <NavigationContainer>
        <VerifyEmail setVerified={setVerified}/>
      </NavigationContainer>
    );
  }
  else{
    return (
      <Provider store={store}>
        <NavigationContainer>
          <MainNavigator />
        </NavigationContainer>
      </Provider>
    );
  }
};
  export default App;

Users can log in, they can log out, and for some STRANGE reason, which I can not figure out, after I leave my phone untouched for 20 minutes, they are once again logged out, without even touching the app.

What am I doing wrong?

navigator.mediaDevices.getDisplayMedia doesn’t show current tab as an option

Looked at similar answers and followed the guidelines there,but I can’t get the current tab to show up as an option in any browser that I’ve tried (Chrome, Edge, Opera). The rest of my code requires CropTarget, which is why I didn’t try FireFox, as it’s not supported.

Code that asks for permissions:

const stream = await navigator.mediaDevices.getDisplayMedia({
  video: { displaySurface: "browser", selfBrowserSurface: "include", preferCurrentTab: true }
});

And the user action that makes the function call:

<div class="row">
    <button onclick="captureElement('myId')">Capture</button>
</div>

I’ve also enabled Experimental Web Flag features in flags, but that has also not helped.

Is it possible to target the caller tab when using getDisplayMedia?

Trying to set a max-width to a column of text in a table the scrolls horizontally?

Is it possible to set a max-width to the third <col> such that the first table will wrap at that max-width, and the second table will not even reach that width but just fit the content?

Using min-width works for the first table but leaves the column too wide in the second table.

If no width styles are used, (since the table is wider than its parent element and all other columns are set to not wrap), the 3rd column wraps on just about each word. That’s why tried a minimum width.

The max-content style will not permit wrapping.

I don’t want to use a fixed width table otherwise.

There is only one table but the text content varies with each load of the tbody content; thus, one set of styles must work for both.

Thank you.

div {
  width:500px;
  overflow-x:auto;
  overflow-y:auto;
  border: 1px solid blue;
}

table {
  border-collapse: collapse;
  margin-bottom: 20px;
}
thead {
  background-color: rgb(200,200,200);
}

th,td {
  border: 1px solid gray;
  padding: 10px 20px;
}

td:not(:nth-child(3)) {
  white-space: nowrap;
}

table col:nth-child(3) {
  min-width:300px;
}

/*
table.cat_1 {
  width: max-content;
}

table.cat_1 col:nth-child(3) {
  max-width: 200px;
}
*/
<div class="prnt">
  <table class="cat_1">
    <colgroup>
      <col><col><col><col><col><col><col>
    </colgroup>
    <thead>
      <tr>
         <th>Id</th>
         <th>Size</th>
         <th>Text</th>
         <th>Col 4</th>
         <th>Col 5</th>
         <th>Col 6</th>
         <th>Col 7</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1001</td>
        <td>2028</td>
        <td>A line of text that exceeds the desired maximum width of third column.</td>
        <td>td 4 data</td>
        <td>td 5 data</td>
        <td>td 6 data</td>
        <td>td 7 data</td>
      </tr>
    </tbody>
  </table>
  <table class="cat_2">
    <colgroup>
      <col><col><col>
    </colgroup>
    <thead>
      <tr>
         <th>Id</th>
         <th>Size</th>
         <th>Text</th>
         <th>Col 4</th>
         <th>Col 5</th>
         <th>Col 6</th>
         <th>Col 7</th>         
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1001</td>
        <td>2028</td>
        <td>A short line.</td>
        <td>td 4 data</td>
        <td>td 5 data</td>
        <td>td 6 data</td>
        <td>td 7 data</td>        
      </tr>
    </tbody>
  </table>
</div>

   

How can I memoize a JS Object on a per item basis?

I am positive that this is a very easy question to solve, however my attempts have yielded no results and no LLM is giving me an answer that works. I have the below memoizedList which works fine. The problem is it has 50 items in it, and every time one item changes, every single list item gets rerendered which is causing lag.

const [selectorInstruments, setSelectorInstruments] = useState<Record<string, InstrumentSelectorInstrument>>({});
const InstrumentList = useMemo(() => {
        return Object.values(selectorInstruments).map((selectorInstrument: InstrumentSelectorInstrument) => (
            <SelectorInstrumentItem key={selectorInstrument.id} selectorInstrument={selectorInstrument}/>
            ))
      }, [selectorInstruments]);

Below is the List item using React.memo. I have tried setting the callback to check for prop changes, but the callback never even runs. I have console.logged() inside to verify that each item is rendering each time.

const SelectorInstrumentItem = React.memo(({selectorInstrument}: { selectorInstrument: InstrumentSelectorInstrument}) => {
        return <StyledMenuItem
        key={selectorInstrument.id}
        view={selectorInstrument.view}
        sx={{
            paddingX: 1.5, 
            borderRadius: 2,
        }}
        className='flex rounded-sm'
        onClick={(e: any) => {
            e.stopPropagation();
            handleDropdownItemEvent(e, selectorInstrument.id);
        }}

    >

  
    </StyledMenuItem>
      });

Below is how im updating selectedItems. It updates two of them, but as I said all 50 get rerendered

setSelectorInstruments(prevState => {
            const newState: Record<string, InstrumentSelectorInstrument> = {...prevState}
            
            const newInstrument = newState[instrumentId];
            if (newInstrument) {
                newState[instrumentId] = {
                    ...newInstrument,
                    view: instrumentInformation.view
                }
            }
            const prevInstrument = newState[oldPrimaryInstrument.instrument.id];
            if (prevInstrument) {
                newState[oldPrimaryInstrument.instrument.id] = {
                    ...prevInstrument,
                    view: oldPrimaryInstrument.view
                }
            }

            return newState;
            });

there is an associated function `from_str` with a similar name in Rust

i am using Rust as WSAM inside Angular app here is my cargo.toml i am looking to filter JSON and find the object by key

[package]
name = "my-rust-wasm"
version = "0.1.0"
edition = "2024"

[dependencies]
wasm-bindgen = "0.2"
regex = "1"
chrono = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.5"
serde_json = "1.0"


[lib]
crate-type = ["cdylib", "rlib"]

Now here is my lib.rus file

 #[wasm_bindgen]
 #[derive(Serialize, Deserialize)]
  pub struct Object {
   key: String,
   value: String,
 }

#[wasm_bindgen]
 pub fn find_object_by_key(arr: JsValue, target_key: &str) -> JsValue {
  let objects: Vec<Object> = arr.into_serde().unwrap_or_default();
  let result: Vec<Object> = objects
    .into_iter()
    .filter(|obj| obj.key == target_key)
    .collect();
  JsValue::from_serde(&result).unwrap()
}

And this is component.ts code

 let objects = [
    { key: "id1", value: "Object 1" },
    { key: "id2", value: "Object 2" },
    { key: "id3", value: "Object 3" },
  ];
  
  let targetKey = "id2";
  console.log(wasmModule.find_object_by_key(objects, targetKey)); // Expected Output: [{ key: "id2", value: "Object 2" }]

But i am getting this error there is an associated function from_str with a similar name
Error

Error 2