Why does my image disappear when I apply the width attribute?

I’m trying to create an app with react native,

this is the code atm:

import { View, Text, Image } from 'react-native'
import React from 'react'

export default function Login() {
  return (
    <View>
        <Image source={require('./../assets/images/login.jpg')}
            style={{
              width: '100%',      
            }}
        />
    </View>
  )
}

The problem is when I apply the width attribute, because my image just disappear.
If I don’t use that attribute it’s all good, I can use height and it’s working properly, but as soon as I use width I just see a white screen. I tried different images, different %, but same result.

PS:This error is only when I use %, if I use px is working.

Can you explain to me why this is happening?

Thank you.

I wanted the image to cover the entire width of the background.

Replace every second letter with an underscore and return the result as a string

A challenge question “Given is a string hangmanString. Replace every second letter with an underscore and return the result as a string. The first character must be an underscore.”.

My result kept repeating the words and adding the underscore in each words. I have attached a screenshot of my solution for better understanding.enter image description here

function hangman(hangmanString) {
  var result = "";
  var replacement = "";
  
  for(let i = 0; i < hangmanString.length; i++){
      if(i % 2 === 0){
     replacement = hangmanString.replace(hangmanString[i], "_");
     result = result + replacement;
   }
  }
return result;
}
hangman("TestString");

Any suggestion what the issue might be?

react native Image component cannot display photos from expo media library

im trying to access media gallery from a phone is display it in my expo app using the expo media gallery, everything seem to work fine but the image are not displaying.

it seems to be an issue with the uri path which is prefix with ph:// instead of assets://* for iOS and file://* for Android as stated in the documentation

import { useState, useEffect } from 'react';
import { Button, Text, SafeAreaView, ScrollView, StyleSheet, Image, View, Platform } from 'react-native';
import * as MediaLibrary from 'expo-media-library';

function AlbumEntry({ album }) {
  const [assets, setAssets] = useState([]);


  useEffect(() => {
    async function getAlbumAssets() {
      const albumAssets = await MediaLibrary.getAssetsAsync({ album });
      setAssets(albumAssets.assets);
    }

    getAlbumAssets();
  }, [album]);

  return (
    <View key={album.id} style={styles.albumContainer}>
      <Text>
        {album.title} - {album.assetCount ?? 'no'} assets
      </Text>
      <View style={styles.albumAssetsContainer}>
        {assets && assets.map((asset) =>{

    console.log(asset.uri)
          return  (
            <View key={asset.id}>
              <Image source={{ uri: asset.uri }} style={{ width: 50, height: 50 }} />
            </View>
          )
        })}
      </View>
    </View>
  );
}

export default function MediaGallery() {
  const [albums, setAlbums] = useState(null);
  const [permissionResponse, requestPermission] = MediaLibrary.usePermissions();

  async function getAlbums() {
    if (permissionResponse.status !== 'granted') {
      await requestPermission();
    }
    const fetchedAlbums = await MediaLibrary.getAlbumsAsync({
      includeSmartAlbums: true,
    });
    setAlbums(fetchedAlbums);
  }

  return (
    <SafeAreaView style={styles.container}>
      <Button onPress={getAlbums} title="Get albums" />
      <ScrollView>
        {albums && albums.map((album) => <AlbumEntry key={album.id} album={album} />)}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    gap: 8,
    justifyContent: 'center',
    ...Platform.select({
      android: {
        paddingTop: 40,
      },
    }),
  },
  albumContainer: {
    paddingHorizontal: 20,
    marginBottom: 12,
    gap: 4,
  },
  albumAssetsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
});

so i have been able to make the image display by using expo-image package.

Java Script- Onclick event doesn’t open popup modal

This is Salesforce lwc component code. For some reason when I click “New Correspondence” button, nothing happens and no debug log on F12 dev console.

This button does not get registered for some reason.

<lightning-button class="new-correspondence-button" label="New Correspondence" onclick={showNewCorrespondenceModal}></lightning-button>

Full code is below for HTML and JS

<template>
<div class="button-container">
    <lightning-button class="new-correspondence-button" label="New Correspondence" onclick={showNewCorrespondenceModal}></lightning-button>
    <template if:true={hasExistingCorrespondences}>
        <lightning-button class="existing-correspondence-button" label="Select Existing Correspondence" onclick={handleSelectExisting}></lightning-button>
    </template>
</div>

<div class="correspondence-list-container">
    <template if:true={showCorrespondenceList}>
        <c-correspondence-list parent-id={recordId} oncorrespondenceselected={handleCorrespondenceSelected}></c-correspondence-list>
    </template>

    <template if:true={selectedCorrespondenceId}>
        <c-message-list correspondence-id={selectedCorrespondenceId} key={selectedCorrespondenceId}></c-message-list>
        <c-message-input correspondence-id={selectedCorrespondenceId} onmessagesent={handleMessageSent}></c-message-input>
    </template>
</div>

<template if:true={showNewCorrespondenceModal}>
    <c-new-correspondence-modal onclose={hideNewCorrespondenceModal} onsave={createNewCorrespondence}></c-new-correspondence-modal>
</template>

import { LightningElement, api, track, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import createCorrespondence from '@salesforce/apex/MessageService.createCorrespondence';
import getCorrespondences from '@salesforce/apex/MessageService.getCorrespondences';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class MessagingApp extends LightningElement {
    @api recordId;
    @api objectApiName;
    @track selectedCorrespondenceId;
    @track showCorrespondenceList = false;
    @track hasExistingCorrespondences = false;
    @track showNewCorrespondenceModal = false; // This is the tracked property to manage modal visibility

    @wire(getObjectInfo, { objectApiName: '$objectApiName' })
    objectInfo;

    get objectType() {
        return this.objectInfo.data ? this.objectInfo.data.apiName : null;
    }

    connectedCallback() {
        console.log('connectedCallback called');
        this.checkExistingCorrespondences();
    }

    handleCorrespondenceSelected(event) {
        console.log('handleCorrespondenceSelected called with event:', event);
        this.selectedCorrespondenceId = event.detail;
        this.showCorrespondenceList = false;
    }

    showNewCorrespondenceModal() {
        console.log('showNewCorrespondenceModal called');
        this.showNewCorrespondenceModal = true; // Show the modal by setting the tracked property to true
        console.log('showNewCorrespondenceModal state:', this.showNewCorrespondenceModal);
    }

    hideNewCorrespondenceModal() {
        console.log('hideNewCorrespondenceModal called');
        this.showNewCorrespondenceModal = false; // Hide the modal by setting the tracked property to false
        console.log('showNewCorrespondenceModal state:', this.showNewCorrespondenceModal);
    }

    createNewCorrespondence(event) {
        console.log('createNewCorrespondence called with event:', event);
        const subject = event.detail.subject;
        if (!subject) {
            console.log('Subject is required');
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error',
                    message: 'Subject is required',
                    variant: 'error'
                })
            );
            return;
        }

        console.log('Creating correspondence with subject:', subject);

        createCorrespondence({
            parentId: this.recordId,
            parentObjectType: this.objectType,
            correspondenceName: subject
        })
        .then(correspondenceId => {
            console.log('Correspondence created with ID:', correspondenceId);
            this.selectedCorrespondenceId = correspondenceId;
            this.showNewCorrespondenceModal = false; // Hide the modal after creating the correspondence
            console.log('showNewCorrespondenceModal state:', this.showNewCorrespondenceModal);
        })
        .catch(error => {
            console.error('Error creating correspondence:', error);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error',
                    message: 'Failed to create correspondence',
                    variant: 'error'
                })
            );
        });
    }

    handleSelectExisting() {
        console.log('handleSelectExisting called');
        this.showCorrespondenceList = true;
    }

    checkExistingCorrespondences() {
        console.log('checkExistingCorrespondences called');
        getCorrespondences({ parentId: this.recordId })
        .then(data => {
            console.log('Existing correspondences:', data);
            this.hasExistingCorrespondences = data.length > 0;
        })
        .catch(error => {
            console.error('Error fetching correspondences:', error);
        });
    }

    handleMessageSent() {
        console.log('handleMessageSent called');
        this.template.querySelector('c-message-list').refreshMessages();
    }
}

Cannot populate through schemas properly

Listing schema :

const listingSchema = new Schema({
    title : {
        type :String,
        required : true,
    },
    description : String,
    image : {
        type : String,
        default :
        "https://images.app.goo.gl/oMwfut7SSe1GwpyS7",
        set : (v) => 
        v === undefined 
        ? "https://images.app.goo.gl/oMwfut7SSe1GwpyS7"
        : v,
    },
    price : Number,
    location : String,
    country : String,
    reviews : [
        {
            type : Schema.Types.ObjectId,
            ref : "Review",
        },
   ],
   blogs : [
    {
        type : Schema.Types.ObjectId,
        ref : "Blog",
    },
   ],
   owner : {
        type : Schema.Types.ObjectId,
        ref : "User",
   },
});


//create the model using Scehma created
const Listing = mongoose.model("Listing", listingSchema);

//export Model to app.js
module.exports = Listing;

Blog schema :


const blogSchema = {
    blogCreator : {
        type: Schema.Types.ObjectId,
        ref : "User",
    },
    description :{ 
        type : String,
        required : true,
    },
    amenities : {
        type :String,
        required : true,
    },
    rating : {
        type :Number,
        min : 1,
        max : 5
    },
    convenience : {
        type : String,
        required : true,
    },
    checkIn : {
        type : String,
        required : true,
    },
    security : {
        type : String,
        required : true,
    },
    cancellation : {
        type : String,
        required : true,
    },
    pets : {
        type : String,
        required : true,
    },
};

let Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog;

The Listing schema and Blog schema has one to many relation. I’m trying to populate from listing schema to blog schema using the blogId’s in the “blogs[]” property of listing schema in the following route to print the “blogCreator” and “description” of each blog of that listing using the following ejs template :

<div class="list-group">
                <% listing.blogs.forEach(blog => { %>
                    
                    <a href="/listings/<%= listing._id %>/blogs/<%= blog._id %>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                        <div>
                            <strong><%= blog.blogCreator %></strong>
                            <p class="mb-1"><%= blog.description ? blog.description.substring(0, 50) : '' %>...</p>
                        </div>
                    </a>
                <% }) %>
            </div>

The routes used for this particular function is :


router.get('/', wrapAsync(async (req, res) => {
    const listing = await Listing.findById(req.params.id)
        .populate({
            path: "blogs",
            populate: {
                path: "blogCreator",
                model: 'User'
            }
        })
        //also render reviews for blog path {the path has changed so the previous render review code does not work for this path anymore}
        .populate({
            path : "reviews",
            populate : {
                path: "author",
                model: 'User'
            }
        })
        .populate("owner","User");
    // const blog = await Blog.findById(req.params.blogId).populate('blogCreator');
    if (!listing) {
        return res.status(404).send('Listing not found');
    }
    res.render('listings/show', { listing });
}));
router.get('/:blogId', wrapAsync(async (req, res) => {
    const listing = await Listing.findById(req.params.id)
        .populate({
            path: 'blogs',
            populate: {
                path: 'blogCreator',
                model: 'User'
            }
        })
        //also render reviews for blog path {the path has changed so the previous render review code does not work for this path anymore}
        .populate({
            path : "reviews",
            populate : {
                path: "author",
                model: 'User'
            }
        })
        .populate("owner","User");
    const blog = await Blog.findById(req.params.blogId).populate('blogCreator');

    //render views properly in blog route

    if(!listing){
        req.flash("error","Listing you requested for does not exist!");
        res.redirect("/listings");
    }
    if (!blog) {
        req.flash("error", "Blog you requested for does not exist!");
        return res.redirect(`/listings/${listing._id}`);
    }
    //render page
    res.render('listings/show', { listing, selectedBlog: blog });
}));

I tried changing the

<a href="/listings/<%= listing._id %>/blogs/<%= blog._id %>" 

to

<a href="/listings/<%= listing._id %>/blogs" 

so that i could change the display of the blogs of the listing when one single blog isn’t selected and add the blog decription and it’s creator’s name to the list instead of printing just ‘…’ for every blog in the list.
This results in display of the required after the blog is selected inside the tab, and then it doesn’t switch back.
Before, the after selectedBlog feature was working properly and I just wanted to display the name of the creator and description in the list name like a whatsapp chat, now it doen’t open the blog at all, and nothing is displayed on the list name just ‘…’ like before.

NodeJS/discord.js issue: TypeError: Cannot read properties of undefined (reading ‘id’)

I am working on a bot and am building an Audit Logging system based on a tutorial from The North Solution on YouTube. I keep getting this error when an audit log event is generated. I’ve spent hours looking through the code and using the debugger to track it down. The debugger points to a line of code that is for sure not wrong as it is identical to the tutorial video.

const { EmbedBuilder } = require("discord.js");
const loggingSchema = require("../../schemas/auditLogging");
const mConfig = require("../../messageConfig.json");
const aConfig = require("../../auditConfig.json");

module.exports = async (client, auditLogEntry, guild) => {
    let dataGD = await loggingSchema.findOne({ GuildID: guild.id });
    if (!dataGD) return;
    const auditActionValue = auditLogEntry.action;

Error from the debugger
Error in the console

Is there a better way to track down the error? I can provide any additional info as needed.

The file the error seems to be coming from

CodeMirror Editor with Editor.js: Enter Key Moves Cursor Outside of Editor

I’m integrating a CodeMirror editor within Editor.js, but I’m encountering an issue where pressing the **Enter** key causes the cursor to move outside of the CodeMirror editor and create a new block in Editor.js instead of adding a new line within the editor.

Here’s a simplified version of the code I’m using:

import "./code-editor.css";

export class SimpleCodeTool {
  static get toolbox() {
    return {
      title: "Code Editor",
      icon: `
        <svg width="17" height="15" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M14.5 15L17.5 12L14.5 9M9.5 9L6.5 12L9.5 15M7.8 21H16.2C17.8802 21 18.7202 21 19.362 20.673C19.9265 20.3854 20.3854 19.9265 20.673 19.362C21 18.7202 21 17.8802 21 16.2V7.8C21 6.11984 21 5.27976 20.673 4.63803C20.3854 4.07354 19.9265 3.6146 19.362 3.32698C18.7202 3 17.8802 3 16.2 3H7.8C6.11984 3 5.27976 3 4.63803 3.32698C4.07354 3.6146 3.6146 4.07354 3.32698 4.63803C3 5.27976 3 6.11984 3 7.8V16.2C3 17.8802 3 18.7202 3.32698 19.362C3.6146 19.9265 4.07354 20.3854 4.63803 20.673C5.27976 21 6.11984 21 7.8 21Z" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      `,
    };
  }

  constructor({ data }) {
    this.data = data;
    this.wrapper = null;
    this.editor = null;
  }

  render() {
    this.wrapper = document.createElement("div");
    this.wrapper.classList.add("simple-js-editor");

    this._createEditor(this.data ? this.data.code : "");

    return this.wrapper;
  }

  _createEditor(code) {
    const container = document.createElement("div");
    container.classList.add("code-editor-container");

    const textarea = document.createElement("textarea");
    container.appendChild(textarea);

    if (typeof CodeMirror !== "undefined") {
      this.editor = CodeMirror.fromTextArea(textarea, {
        mode: "javascript",
        theme: "dracula",
        lineNumbers: true,
      });

      if (typeof code === "string") {
        this.editor.setValue(code);
      } else {
        console.error("Code data is not a string:", code);
      }

      setTimeout(() => {
        this.editor.focus(); // Ensure the editor is focused after rendering
        this.editor.setCursor({
          line: 0, // Set to the desired line
          ch: 0    // Set to the desired character position
        });
      }, 0);

      textarea.addEventListener("keydown", (e) => {
        if (e.key === "Enter") {
          e.preventDefault(); // Prevent the default behavior
          this.editor.execCommand("newlineAndIndent"); // Handle newline within CodeMirror
        }
      });

      // Optionally adjust the height of the editor container
      this.editor.on("change", () => {
        this._adjustHeight(container);
      });
    } else {
      console.error("CodeMirror is not defined.");
      return;
    }

    this.wrapper.appendChild(container);
  }

  _adjustHeight(container) {
    const editorHeight = this.editor.getScrollInfo().height;
    container.style.height = Math.min(650, Math.max(650, editorHeight + 20)) + "px";
  }

  save(blockContent) {
    return {
      code: this.editor.getValue(),
    };
  }
}
.simple-js-editor {
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 4px;
  background-color: #282c34; /* Background color for the editor */
}

.code-editor-container {
  position: relative;
  min-height: 200px;
}

.CodeMirror {
  font-family: "Fira Code", monospace;
  height: auto;
}

Problem:
When I press **Enter** in the CodeMirror editor, the cursor moves outside the editor and creates a new block in Editor.js instead of adding a new line within the CodeMirror editor.

Expected Behavior:
Pressing **Enter** should add a new line within the CodeMirror editor, not affect the Editor.js block or move the cursor outside of the editor.

Steps to Reproduce:

  • Integrate CodeMirror editor into Editor.js using the code above.
  • Click into the CodeMirror editor and press Enter.

What I’ve Tried:

  • Used e.preventDefault() to stop the default behavior.

  • Used CodeMirror.execCommand(“newlineAndIndent”) to handle newline insertion.

Any Suggestions?
How can I resolve this issue so that pressing Enter only affects the CodeMirror editor and doesn’t interact with Editor.js?

Thank you for any help or insights you can provide!

Errors when signing and sending transaction with Ethers

I get the error in the browser console when the function attempt to execute signTransaction, even though the transaction was successfully broadcasted to the blockchain. The loading variable never get set to false which is when the function ends it executions.

Uncaught (in promise) TypeError: invalid BytesLike value (argument="value", value={ "_type": "TransactionResponse", "accessList": null, "blobVersionedHashes": null, "blockHash": null, "blockNumber": null, "chainId": null, "data": "0x3f4a5d0a00000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000066a5e97e00000000000000000000000000000000000000000000000000000000000000067064736b6a6600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006717064776a6600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000966616473662e636f6d0000000000000000000000000000000000000000000000", "from": "0xc768B39DBcBCCfD6dECae24b0a591e78BEA3382F", "gasLimit": "203181", "gasPrice": "35133400011", "hash": "0x9c31df9f6bd4778fbdd32f0438711a3d555f2482094275235069e4b6221f66ee", "index": null, "maxFeePerBlobGas": null, "maxFeePerGas": "35133400011", "maxPriorityFeePerGas": "35133399990", "nonce": 23, "signature": { "_type": "signature", "networkV": null, "r": "0x7c377e75a739b7f81a2e148641e5b577e32c5fb592d0bbe0d42a2ac76be9e038", "s": "0x4e62a1e353b4aeb5645f8bae9325e8661e841f9a354cd851314923b1fd28f3b5", "v": 27 }, "to": "0x0Bc1FcA0bC7b0B06fDa8DB3A1Cb0504A06404923", "type": 2, "value": "0" }, code=INVALID_ARGUMENT, version=6.13.1)
'use client'

import { useRouter } from "next/navigation";
import React, { useEffect } from "react";
import { useData } from "../../contexts/DataContext";
import { usePrivy, useWallets } from "@privy-io/react-auth";

const Admin = () => {
  const router = useRouter();
  const { goMarket, loadBlockchainData, account, walletSigner, feeData, provider } = useData!();
  const [loading, setLoading] = React.useState(false);

  const [title, setTitle] = React.useState("");
  const [description, setDescription] = React.useState("");
  const [category, setCategory] = React.useState("");
  const [url, setURL] = React.useState("");
  const [timestamp, setTimestamp] = React.useState<
    string | number | readonly string[] | undefined
  >(Date());

  useEffect(() => {
    loadBlockchainData();
  }, [loading, account]);

  const handleSubmit = async () => {
    setLoading(true);

    let dateInWeek = new Date();
    dateInWeek.setDate(dateInWeek.getDate() + 7);
    const deadline = Math.floor(dateInWeek.getTime() / 1000);
    setTimestamp(deadline);

    const gasLimit = await goMarket.createMarket.estimateGas(title, description, category, url, timestamp);

    const tx = {
      from: walletSigner.address,
      to: goMarket.target,
      gas: gasLimit,
      nonce: await walletSigner.getNonce(),
      maxPriorityFeePerGas: feeData.maxPriorityFeePerGas.toString(),
      maxFeePerGas: feeData.maxFeePerGas.toString(),
      chainId: 80002,
      // data: goMarket.interface.encodeFunctionData('createMarket', [title, description, category, url, timestamp])
      data: await goMarket.createMarket(title, description, category, url, timestamp)
    };

    const signedTx = await walletSigner.signTransaction(tx);
    const sentTx = await provider.broadcastTransaction(signedTx);

    await sentTx.wait();

    setLoading(false);
    setTitle("");
    setDescription("");
    setCategory("");
    setURL("");
    setTimestamp(undefined);
    router.push("/");
  };
};

export default Admin;

I have tried to encode the data to be sent, but the transaction was unsuccessful.
data: goMarket.interface.encodeFunctionData('createMarket', [title, description, category, url, timestamp]), therefore, I used contract.METHOD_NAME to send the data.

Responsive nav overlapped behind content with Scrollreveal

i got a problem with my website that I made, it seems that my sidebar is overlapped within my content, I already turned the z-index to high. this only occurs when I implemented the scrollreveal js animation Problem:

HTML

    <!-- Nav -->
    <header>
      <div class="border">
        <div class="logo">
          <img src="../images/site_logo.png" alt="Borcelle-logo" />
          <h2>Borcelle</h2>
        </div>

        <nav>
          <!-- Sidebar (for smaller screens) -->
          <ul class="sidebar">
            <li onclick="hideSidebar()">
              <a href=""
                ><img
                  src="../images/close_24dp_E8EAED_FILL0_wght400_GRAD0_opsz24.svg"
                  alt=""
                  style="background-color: black; border-radius: 100%"
              /></a>
            </li>
            <li>
              <a
                href="Home.html"
                style="
                  color: var(--nav-bar-clicked);
                  font-weight: 600;
                  font-size: 1em;
                "
                >Home</a
              >
            </li>
            <li><a href="About.html">About</a></li>
            <li><a href="Courses.html">Courses</a></li>
            <li><a href="Shop.html">Shop</a></li>
            <li><a href="Contact.html">Contact</a></li>
          </ul>

          <!-- Navbar -->
          <ul>
            <li class="hideOnMobile">
              <a
                href="Home.html"
                style="
                  color: var(--nav-bar-clicked);
                  font-weight: 600;
                  font-size: 1em;
                "
                >Home</a
              >
            </li>
            <li class="hideOnMobile"><a href="About.html">About</a></li>
            <li class="hideOnMobile"><a href="Courses.html">Courses</a></li>
            <li class="hideOnMobile"><a href="Shop.html">Shop</a></li>
            <li class="hideOnMobile"><a href="Contact.html">Contact</a></li>
            <li class="menu-button" onclick="showSidebar()">
              <a href="#"
                ><img
                  src="../images/menu_24dp_E8EAED_FILL0_wght400_GRAD0_opsz24.svg"
                  alt=""
                  style="background-color: #d1c8c1"
              /></a>
            </li>
          </ul>
        </nav>
      </div>
    </header>

CSS

.sidebar {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
  height: 100vh;
  width: 250px;
  background-color: rgba(255, 255, 255, 0.132);
  backdrop-filter: blur(10px);
  box-shadow: -10px 0 10px rgba(0, 0, 0, 0.1);
  display: none;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
}

.menu-button {
  display: none;
}

@media (max-width: 780px) {
  .hideOnMobile {
    display: none;
  }

  .menu-button {
    display: block;
  }
}

Javascript (sidebar function alongside w/ scrollreveal)

//Sidebar Functions
function showSidebar() {
  const sidebar = document.querySelector(".sidebar");
  sidebar.style.display = "flex";
}

function hideSidebar() {
  const sidebar = document.querySelector(".sidebar");
  sidebar.style.display = "none";
}

ScrollReveal({
  reset: true,
  distance: "60px",
  duration: 2500,
  delay: 400,
});

//Navigation Animation

ScrollReveal().reveal("nav", {
  delay: 200,
  origin: "right",
});

ScrollReveal().reveal(".menu-button", {
  delay: 200,
  origin: "right",
});

ScrollReveal().reveal("header", {
  delay: 300,
  origin: "left",
});

actually tried setting each of my content into position so i can control the z-index and lower it but ti still doesnt work

Parameter “obj” to Document() must be an object, got “” (type string)

I have a problem, in Postman, the result of the request is this:

Mensaje de Error en Postman

This is my Model:

const mongoose = require("mongoose");
const mongoosePaginate = require("mongoose-paginate-v2");

const ComentariosSchema = mongoose.Schema({
    creator: String,
    comentario: String,
    created_at: { type: Date, default: Date.now },
    raiting: Number
});

const SoporteSchema = mongoose.Schema({
    folio: {
        type: Number,
        unique: true
    },
    documentos: String,
    servicio: String,
    descripcion: String,
    dueno: String,
    asignado: String,
    estado: String,
    prioridad: String,
    created_at: Date,
    MotivoCancel: String,
    CancelDate: Date,
    Cancelby: String,
    AsignDate: Date,
    comentarios: [ComentariosSchema]
});

SoporteSchema.plugin(mongoosePaginate);

module.exports = mongoose.model("Soporte", SoporteSchema);

This is my Controller:

const Soporte = require("../models/soporte");
async function addComnentarios(req, res) {
    try {
        const soporteId = req.params.id;
        const comentario = req.body;
        console.log("Comentario: ", comentario);
        if (!comentario || typeof comentario !== 'object' || Array.isArray(comentario)) {
            return res.status(400).send({ msg: "Comentario inválido" });
        }
        console.log("Req.body", req.body);
        const soporte = await Soporte.findById(soporteId);
        console.log(soporte);
        if (!soporte) {
            return res.status(404).send({ msg: "Ticket no encontrado" });
        }
        soporte.comentarios.push(comentario);
        const comentarioUpdated = await soporte.save();
        console.log(comentarioUpdated);
        res.status(200).send({ msg: "Comentario creado", comentarioUpdated });
    } catch (error) {
        res.status(400).send({ msg: "Error al crear el comentario", error });
    }
}

This should save the information. I compared with other answers and solutions, but the only result is the same error. Can you help me please?

tensorflowjs_converter utility adds suffixes to variable names that cause errors

I am trying to use tensorflowjs_converter to convert a model that I am training in python (using tensorflow) to a JSON layers format so that I can run it on the web. I installed the latest version, and converted a testing model. For this model, it gave me a model.json and .bin file as expected, but when I went to run it on the web, I ran into an error:

Uncaught (in promise) Error: Provided weight data has no target variable: sequential/conv2d/kernel
    at a.value (container.js:643:15)
    at models.js:331:11
    at h (tf.min.js:17:2100)
    at Generator.<anonymous> (tf.min.js:17:3441)
    at Generator.next (tf.min.js:17:2463)
    at u (tf.min.js:17:8324)
    at o (tf.min.js:17:8527)

Code I’m using to generate the .h5 file: model.save("mnist_model.h5") (can provide all code including training if need be)

Code I’m using to run the model on the web:

const modelPath = "new_model/model.json"

const model = await tf.loadLayersModel(modelPath, strict=false)

Version info:

python         3.9.13  
tensorflow     2.16.2  
tensorflowjs   4.20.0  
numpy          1.26.4  

After doing some searching (looking up “Error: Provided weight data has no target variable:”), I found this stack overflow question and this github issue that bring up the same problem.

The stack overflow question was not useful since I plan on building a more complicated model that would be extremely tedious to manually (or even write a script to) fix the errors in the model file.

The github issue suggested multiple solutions that all don’t work for me like loading the model once (that’s what I was already doing), using the command line tool instead of the python code (both ways don’t work), adding false to the function call (they are using tf.loadModel which is deprecated while I am using tf.loadLayersModel because that post is like 6 years old), running keras.backend.clear_session() or tf.keras.backend.clear_session() (didn’t work), and restarting the session in colab and running each cell once (didn’t work).

Automatic Horizontal Scroll Working But Manual Scroll Doesn’t

I want a scroll bar that is able to automatically scroll as well as having two buttons that be manually clicked to scroll right / left.

Problem:

  • Manual scroll Buttons are not working but the automatic scroll is, They are using the exact same code to scroll: “adverts.scrollBy({ left: 20, behavior: ‘smooth’ });”

  • Even after i remove the automatic scroll code the manual scroll buttons do not work.

What i need help with:

Having Manual scroll buttons and Automatic scroll working at the same time.

HTML Code:

    <div class="scrollbar">
        <div class="adverts">
            <a href="" class="advert w">
                <div class="img"></div>
                
            </a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
            <a href="" class="advert w"></a>
            <a href="" class="advert b"></a>
        </div>
    </div>
    <div class="scroll right" onclick="scrollLeft">right</div>
    <div class="scroll left" onclick="scrollRight">left</div>

    <script>
        const adverts = document.querySelector('.adverts');

        //Manual Scroll
        function scrollRight() {
            adverts.scrollLeft -= 100;
        }
        function scrollLeft() {
            adverts.scrollBy({ left: 100, behavior: 'smooth' });
        }
        
        // Automatic Scroll (Wait 3 seconds before start)
        setTimeout(() => {
            setInterval(() => {
            adverts.scrollBy({ left: 20, behavior: 'smooth' });
        }, 10);

        }, 3000);
        var text = 0;

        

    </script>

CSS Code

.scrollbar {
    margin-top: 50px;
}

.scroll {
    width: 50px;
    height: 50px;
    outline: 1px solid black;
    cursor: pointer;
}

.adverts {
    /*position: absolute;*/
    white-space: nowrap;
    overflow: auto;
    width: 100%;
    height: 300px;
    background: grey;
    padding-top: 10px;
    padding-bottom: 10px;
    padding-right: 10px;
    scrollbar-width: none;
    text-align: center;
    
}

.advert {
    margin-left: 10px;
    display: inline-block;
    width: 250px;
    height: 100%;
    background-color: white;
    
}

.advert .img {
    width: 90%;
    margin: 5%;
    height: 60%;
    outline: black 3px solid;
}

Typescript – Pass ‘this’ context inside For loop

I want to pass the current ‘this’ context to a for loop which could iterate over an array.

I have this code for example:

someArray : [] = [];

this.service.user.isAworking ? this.someArray.push ({key:'A', value: 'Yes'}) : ({key:'A', value: 'No'})

this.service.user.isBworking ? this.someArray.push ({key:'B', value: 'Yes'}) : ({key:'B', value: 'No'})

this.service.user.isCworking ? this.someArray.push ({key:'C', value: 'Yes'}) : ({key:'C', value: 'No'})

this.service.user.isDworking ? this.someArray.push ({key:'D', value: 'Yes'}) : ({key:'D', value: 'No'})

this.service.user.isEworking ? this.someArray.push ({key:'E', value: 'Yes'}) : ({key:'E', value: 'No'})

isAworking,isBworking,isCworking etc are properties of this.user.
These properties could be extended later, let’s say till isZworking.

Now, if I have to simplify the above code and put in a forEach loop? What would the way be?

I believed creating an array of the properties (isAworking,isBworking,isCworking etc) and iterating them over the values of “Key” in the object stored in an array, but I’m unable to reach a working code.

Example:

propertiesArray = ['.isAworking', '.isBworking', '.isCworking', ......]

keyArray = ['A' , 'B', 'C' ......]

Problem is when I try to put them in a loop and iterate like:

this.service.user + propertiesArray[0];

This appends it like a string and the answer I get is:

[object][object]’.isAworking’

How do I pass the context? Tried call(), bind(), apply() but I’m unable to get it correct.

Ajax call every some seconds

I have a problem with my script, i want to do a POST call, to a script file.php, and then call the file2.php every 10000 seconds until timeout when (1800000 seconds pass) OR return the response we want and clear the timeout and output the info

the script is working. the problem i have is this area

if (datareturn == "isgood") {
$("#returninfo").show();
$("#results").hide();
clearTimeout(myVar);
clearTimeout(myVa);
}

the file2.php returns response in json
{"info":"isgood"}

but still it doesn’t clear timeout or show returninfo

when i check the browser file2.php returns very well, and also file.php works, am not seeing any errror in my browser console about jquery or post.
so am confused, i will be glad to get some help

function BtnCk() {
    $("#BtnCheck").click(function(event) {
        Execute();
    });
    
    function Execute() {
        $.ajax({
            type: "POST",
            url: "file.php",
            data: {
                fullname: $("input[name='fullname']").val(),
            },

            beforeSend: function() {
                if ($("form input[name='fullname']").val() == "") {
                    $("#report_error").html("<p>input needed</p>");
                    return false;
                }

            },

            complete: function() {
                $("#report_error").hide();
            },
            
            success: function(response) {
                $("#results").html(response.info);
                myVa = setTimeout(() => {
                    $("#results").hide();
                    clearTimeout(myVar);
                }, 1800000);
                setTimeout(Rsponse, 10000);
            },
            error: function() {
                alert("errror .");
            },
        });
    }
}

function Rsponse() {
    myVar = setTimeout(Rsponse, 10000);
    $.ajax({
        type: "POST",
        url: "ajax/file2.php",
        data: {
            fullname: $("input[name='fullname']").val(),
        },
        success: function(resp) {
            var datareturn = resp.info;

            if (datareturn == "isgood") {
                $("#returninfo").show();
                $("#results").hide();
                clearTimeout(myVar);
                clearTimeout(myVa);
            }
        },
    });
}

$(document).ready(function() {
    BtnCk();
});