Unable to retrieve correct values from deployed contract in hardhat

I have created a simpleStorage contract and deploying it using hardhat, everything is working fine but in there is a store function to change the value of a variable. After executing it, when I am retrieveing value, it is not giving me updated value, but the default value.

This is my contract

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    //this line defines the start of a contract
    uint256 favouriteNumber = 7;
    People[] public people;

    mapping(string => uint256) public nametonum;

    struct People {
        uint256 favouriteNumber;
        string name;
    }

    function store(uint256 _favouriteNumber) public virtual {
        favouriteNumber = _favouriteNumber;
    }

    function retrieve() public view returns (uint256) {
        return favouriteNumber;
    }

    function addperson(string memory _name, uint256 _favouriteNumber) public {
        people.push(People(_favouriteNumber, _name)); //push function of array, creating struct without{}
        nametonum[_name] = _favouriteNumber;
    }
}

and this my deploy script

const { ethers, run, network } = require("hardhat")

async function main() {
    const simpleStorageFactory = await ethers.getContractFactory(
        "SimpleStorage"
    )
    console.log("Deploying... Please wait")
    const simpleStorageContract = await simpleStorageFactory.deploy()
    await simpleStorageContract.waitForDeployment()
    console.log(
        `Deployed contract to: ${(
            await simpleStorageContract.getAddress()
        ).toString()}`
    )
    if (network.config.chainId === 11155111 && process.env.ETHERSCAN_API_KEY)
        await simpleStorageContract.deploymentTransaction().wait(6)
    await verify((await simpleStorageContract.getAddress()).toString(), [])

    const currentValue = await simpleStorageContract.retrieve()
    console.log(currentValue.toString())

    const changeNumberResponse = await simpleStorageContract.store("10")
    changeNumberResponse.wait()
    const updatedValue = await simpleStorageContract.retrieve()
    console.log(updatedValue.toString())
}

async function verify(contractAddress, args) {
    console.log("Verifying Contract...")
    try {
        await run("verify:verify", {
            address: contractAddress,
            constructorArguments: args,
        })
    } catch (error) {
        if (error.message.toLowerCase().includes("already been verified")) {
            console.log("Already verified!")
        } else {
            console.error(error)
        }
    }
}

main()
    .then(() => process.exit(0))
    .catch((eroor) => {
        console.error(eroor)
        process.exit(1)
    })

updated value is not getting changed value after store function call
response–

Deploying... Please wait
Deployed contract to: 0xDA63Fc7a82d1eD19b8cC301206AaFC4e56Fd9C75
Verifying Contract...
Successfully submitted source code for contract
contracts/SimpleStorage.sol:SimpleStorage at 0xDA63Fc7a82d1eD19b8cC301206AaFC4e56Fd9C75
for verification on the block explorer. Waiting for verification result...

Successfully verified contract SimpleStorage on the block explorer.
https://sepolia.etherscan.io/address/0xDA63Fc7a82d1eD19b8cC301206AaFC4e56Fd9C75#code

7
7

Please help!

Python Selenium JavaScript Horizontal Scroll

I’m not very good at using pyhton/selenium on a website using javascript.

I have a website that will only read the source for what is visible. So I am trying to scroll to the right a handful of pixels at a time to get the whole table eventually.

The scroll element looks like this:

<div class="ag-body-horizontal-scroll" aria-hidden="true" style="height: 17px; max-height: 17px; min-height: 17px;">
        <div class="ag-horizontal-left-spacer ag-scroller-corner" ref="eLeftSpacer" style="width: 0px; max-width: 0px; min-width: 0px;"></div>
        <div class="ag-body-horizontal-scroll-viewport" ref="eViewport" style="height: 17px; max-height: 17px; min-height: 17px;">
        <div class="ag-body-horizontal-scroll-container" ref="eContainer" style="height: 17px; max-height: 17px; min-height: 17px; width: 7400px;"></div>
        </div>
        <div class="ag-horizontal-right-spacer ag-scroller-corner" ref="eRightSpacer" style="width: 17px; max-width: 17px; min-width: 17px;"></div>
    </div>

Would love some help on getting this to work.

interaction.client.commands.get is not a function error in discord.js

I have followed the documents to create my first discord.js bot (Ive always used discord.py) and I have run into an error regarding one of the functions within the documented code.
I have attempted to use the following block of code for running the command builder commands from other files. I have surrounded the error line in the code with comments

client.on(Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;
//////////////////////////////////////////////////////////////////////////////////
    const command = interaction.client.commands.get(interaction.commandName);
//////////////////////////////////////////////////////////////////////////////////
    if (!command) {
        console.error(`No command matching ${interaction.commandName} was found.`);
        return;
    }

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        if (interaction.replied || interaction.deferred) {
            await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
        } else {
            await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
        }
    }
});

The error I have been getting is saying that interaction.client.commands.get is not a function, even though that is what discord.js has in their documents here. I just want to know how to solve this issue, as I have no clue what to do to solve it.

How can we make this qubit heatmap in Vega spec

I want to create this type of hexagonal heatmap, but can’t seem to find this anywhere.

Heat map

I tried to make it but no luck.

here’s my vega spec :

`{
“$schema”: “https://vega.github.io/schema/vega/v5.json”,
“width”: 500,
“height”: 300,
“padding”: {“left”: 10, “top”: 10, “right”: 10, “bottom”: 10},

“signals”: [
{
“name”: “hexRadius”,
“value”: 35
},
{
“name”: “hexWidth”,
“update”: “sqrt(0) * hexRadius”
},
{
“name”: “hexHeight”,
“update”: “0 * hexRadius”
}
],

“data”: [
{
“name”: “heatmapData”,
“values”: [
{“row”: 1, “column”: 1, “metric”: 0.01},
{“row”: 2, “column”: 1, “metric”: 0.02},
{“row”: 3, “column”: 1, “metric”: 0.03},
{“row”: 1, “column”: 2, “metric”: 0.04},
{“row”: 2, “column”: 2, “metric”: 0.05},
{“row”: 3, “column”: 2, “metric”: 0.06},
{“row”: 1, “column”: 3, “metric”: 0.07},
{“row”: 2, “column”: 3, “metric”: 0.08},
{“row”: 3, “column”: 3, “metric”: 0.09}
]
}
],

“scales”: [
{
“name”: “x”,
“type”: “point”,
“domain”: {“data”: “heatmapData”, “field”: “column”},
“range”: “width”,
“padding”: 0.5
},
{
“name”: “y”,
“type”: “point”,
“domain”: {“data”: “heatmapData”, “field”: “row”},
“range”: “height”,
“padding”: 1
},
{
“name”: “color”,
“type”: “linear”,
“domain”: [0.01, 0.09],
“range”: {“scheme”: “purples”}
}
],

“axes”: [
{
“orient”: “left”,
“scale”: “y”,
“title”: “Row”,
“tickCount”: 3
},
{
“orient”: “bottom”,
“scale”: “x”,
“title”: “Column”,
“tickCount”: 3
}
],

“marks”: [
{
“type”: “path”,
“from”: {“data”: “heatmapData”},
“encode”: {
“enter”: {
“path”: {
“signal”: “‘M’ + (0) + ‘,’ + (-hexRadius) + ‘ L’ + (hexRadius * sin(60)) + ‘,’ + (-hexRadius/2) + ‘ L’ + (hexRadius * sin(60)) + ‘,’ + (hexRadius/2) + ‘ L’ + (0) + ‘,’ + (hexRadius) + ‘ L’ + (-hexRadius * sin(60)) + ‘,’ + (hexRadius/2) + ‘ L’ + (-hexRadius * sin(60)) + ‘,’ + (-hexRadius/2) + ‘ Z'”
},
“x”: {
“scale”: “x”,
“field”: “column”,
“offset”: {“signal”: “datum.column % 2 === 0 ? hexWidth / 2 : 0”}
},
“y”: {
“scale”: “y”,
“field”: “row”,
“offset”: {“signal”: “datum.row % 2 === 0 ? hexHeight / 2 : 0”}
},
“fill”: {“scale”: “color”, “field”: “metric”},
“stroke”: {“value”: “white”},
“strokeWidth”: {“value”: 1}
}
}
},
{
“type”: “text”,
“from”: {“data”: “heatmapData”},
“encode”: {
“enter”: {
“x”: {
“scale”: “x”,
“field”: “column”,
“offset”: {“signal”: “datum.column % 2 === 0 ? hexWidth / 2 : 0”}
},
“y”: {
“scale”: “y”,
“field”: “row”,
“offset”: {“signal”: “datum.row % 2 === 0 ? hexHeight / 2 : 0”}
},
“text”: {“field”: “metric”},
“align”: {“value”: “center”},
“baseline”: {“value”: “middle”},
“fill”: {“value”: “black”}
}
}
}
]
}
`

How to post from dropzone and other inputs with one button

I’m about to post/upload image(s) using dropzone.js and post some other text form. Here’s my code:

<div class="post-new">
  <div class="post-newmeta">
    <form method="post" class="dropzone" action="<?= base_url() ?>posts/create" id="my-dropzone">
       <div class="fallback">
          <input name="userfile" type="file" />
       </div>
    </form>
  </div>
  <form id="text-form"  class="c-form" action="<?= base_url() ?>posts/create" method="post">
    <textarea name="content" id="emojionearea1" placeholder="What's On Your Mind?"></textarea>
    <input type="text" name="youtube" id="yt" class="margin-top-10" placeholder="https://www.youtube.com/watch?v=vgvsuiFlA-Y&t=56s">
    <button type="submit" name="submit" value="Submit" class="main-btn" id="submit-all">Publish</button>
  </form>
</div>

From the code above, I have 2 forms (one for dropzone, one for text-form). But I want both forms to be posted in one click using button.

Please help.

Select simples + Array

Eu tenho 3 selects simples no meu HTML e as opções são listadas de um array, quando eu escolho uma opção ela já some do próprio select onde estou selecionando uma opção, mas com esse comportamento o placeholder não é substituído pelo item selecionado. Eu quero que a opção selecionada continue aparecendo nas opções do select onde selecionei a tal, mas no próximo select o array sem o item já selecionado e com o comportamento de não sumir o selecionado no próprio select, apenas sumir no próximo select simples.
Alguma sugestão de como deixar a lógica assim?

Obs: seria meio que um array dinâmico, por exemplo: select 1: banana, maçã, pera
selecionei banana
continua o mesmo array
select 2: maçã, pera
selecionei maçã
agora as opções do select 1 são apenas banana (que tá selecionado) e pera
e as opções do select 1 seguem sendo maçã (selecionado) e pera

Obs2: o select não possui a tag options, apenas input e label que estão recebendo um forEach do array

Local SMTP Server with node js

I created a local smtp server using localhost and port 25, I want to be able to create a custom local smtp server and send email using nodemailer. Currently I have this code:

const SMTPServer = require('smtp-server').SMTPServer;

const server = new SMTPServer({
  authOptional: true,
  onData(stream, session, callback) {
    let message = '';

    stream.on('data', (chunk) => {
      message += chunk.toString();
    });

    stream.on('end', () => {
      console.log('Received message:');
      console.log(message);
      callback();
    });
  },
  onClose(session) {
    console.log('Connection closed');
  },
});

server.on('error', (err) => {
  console.error('SMTP Server Error:', err);
});

server.listen(25, '0.0.0.0', () => {
  console.log('SMTP Server listening on port 25');
  const nodemailer = require('nodemailer');



const transporter = nodemailer.createTransport({
  host: 'localhost',  // Replace with your SMTP server address
  port: 25,           // Use the appropriate port
  secure: false,
  tls : { rejectUnauthorized: false }
});

const mailOptions = {
  from: 'myTesteEmail@localhost',
  to: '[email protected]',
  subject: 'Test Email',
  text: 'Hello, this is a test email.',
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error('Error sending email:', error);
  } else {
    console.log('Email sent:', info.response);
  }
});
});

I am getting this message everyTime I try to run de code:

SMTP Server listening on port 25
Received message:
Content-Type: text/plain; charset=utf-8
From: myTesteEmail@localhost
To: [email protected]
Subject: Test Email
Message-ID: da0329f7-8b6f-9005-e154-eeff9c62c61e@localhost
Content-Transfer-Encoding: 7bit
Date: Sat, 23 Dec 2023 01:45:02 +0000
MIME-Version: 1.0

Hello, this is a test email.

Email sent: 250 OK: message queued
Connection closed

But when I check my email, I got no email from my local smtp. I even tried putting the from email to the same as To email with my real gmail account, but still not working, how can I make this working?

I searched a lot, but I coudln’t find any tutorial using a custom local smtp server, they was using an already existing smtp services like mailtril, bravo..

I tried Chat gpt, but no working

Can String.prototype.matchAll() return overlapping matches?

Is it possible to pass String.prototype.matchAll a regex that will return overlapping matches? Every idea I’ve come up with chooses one match when multiple could work:

function logMatches(str, re) {
  console.log(`"${str}".matchAll(/${re.source}/${re.flags}) = [`);
  [...str.matchAll(re)].map(matchProperties).forEach((props) => {
    console.log("t", props);
  })
  console.log("];");
  console.log();
}

function matchProperties(match) {
  return "{ " + (Object.getOwnPropertyNames(match).map((propName) => {
    return propName + ": " + JSON.stringify(match[propName])
  }).join(", ")) + " }, // Note: this element is an Array";
}

logMatches("foo bar baz", /foo|baz/g); // no overlap expected
logMatches("foo bar baz", / .*/g);
logMatches("foo bar baz", /b.*/g);
logMatches("foo bar baz", /b.*?/g);  // no overlap expected
logMatches("foo bar baz", /ba.*$/g);
logMatches("foo bar baz", /ba| .* /g);

Here’s what I expected to see from that last example:

"foo bar baz".matchAll(/ba| .* /g) = [
     { 0: " bar ", length: 1, index: 3, input: "foo bar baz", groups: undefined }, // Note: this element is an Array
     { 0: "ba", length: 1, index: 4, input: "foo bar baz", groups: undefined }, // Note: this element is an Array
     { 0: "ba", length: 1, index: 8, input: "foo bar baz", groups: undefined }, // Note: this element is an Array
];

Is this the way matchAll works or does it have something to do with regular expressions in general? Or, and this might be more likely, is a bug in my example code?

Unisharp/Filemanager in laravel 10 javascript is not updating the input field

I’m using laravel to run my application and in it, I’m using the unisharp/filemanager to upload files and choose for blog post submittions and avatar changes and all that sort of thing. It works perfectly in my summernote implementation but now I’ve being struggling to implement it to update the user’s profile avatar.

The Javascript I use to open the filemanager window is:

(function( $ ){

    $.fn.filemanager = function(type) {
        this.on('click', function(e) {
            var route_prefix = '/filemanager';
            window.open(route_prefix + '?type=' + type, 'FileManager', 'width=900,height=600');
            window.SetUrl = function (items) {
                var file_path = items.map(function (item) {
                    const image = item.url;
                    return item.url;
                });
        
                $("#preview-container").css("background-image", "url(" + file_path + ")");
                $('#avatar-path').value = file_path;
                $('#file-input').value = file_path;
            };
            return false;
        });
    }
    
})(jQuery);

$('#file-input').filemanager('image');

/* I've also tried the following way to use the filemanager and it had the same results as the previous method
$('#invoke-file-input').filemanager('image'); */

The corresponding HTML for that javascript is:

<div id="preview-container">
</div>
<!-- Custom Styled File Input Button -->
<label for="file-input" id="invoke-file-input" class="btn btn-primary" data-input="file-input" data-preview="preview-container">
    Choose File
</label>
<!-- File Input -->
<input type="file" name="avatar" id="file-input" class="form-control visually-hidden">

<!-- Hidden input fields to store background path a second time -->
<input type="hidden" name="avatar-path" id="avatar-path">

and the css for those aren’t relevant

I’m hiding the input field since I want just the preview box and a button underneath it to upload the image and that part works.

I click on that label disguised as a button and it opens the file manager and uploads the image and selects the image and inserts it into the preview container just like I want it to… but I can’t manage to get the input field populated as hard as I try. I’m not very good at javascript so there might be issues here that I’m not noticing, but to be fair, chatGPT has being helping me for the past few hours on this thing and we didn’t get anywhere.

I’ve tried clearing my cache and restarting the artisan server. I literally don’t know what to do. I just need that url path so I can update the database as everything else is done, but it isn’t working.

The console doesn’t show anything and inspecting the element I see that when I select an image it doesn’t add the value to either ‘file-input’ or ‘avatar-path’ (I tried a second hidden field in case it might work, but it doesn’t).

I’ve got other hidden fields in there and they get updated VIA javascript just fine.

I’m not using react or any of those javascript front-end frameworks.

Integration test with selenium chrome webdriver and mocha when using selenium/standalone-chrome

I use selenium-driver with nodejs and mocha for integration testing.
I have download and install selenium/standalone-chrome:latest

  • docker pull selenium/standalone-chrome:latest
  • docker run -d -p 4444:4444 -p 7900:7900 –shm-size=”2g” selenium/standalone-chrome:latest

I use the following code to test my website by using the remove server selenium/standalone-chrome using this url http://localhost:4444/wd/hub.

import { assert } from "chai";
import { Builder, By, logging, WebDriver } from "selenium-webdriver";
import {
  browserType,
  chromeOptions,
  is_debugging,
  site_url,
} from "../utils/TestHelper";

var driver: WebDriver;

describe("Test App", () => {
  before(async () => {
    driver = new Builder()
      .forBrowser(browserType())
      .setChromeOptions(chromeOptions())
      .usingServer("http://localhost:4444/wd/hub")
      .build();

    const urlWeb = site_url();
    await driver.get(urlWeb);
  });

...

After running the test with mocha, I get the following error :

1) Test App
       "before all" hook for "Le Titre de la page est-il bon ?":
     WebDriverError: unknown error: net::ERR_CONNECTION_REFUSED
  (Session info: chrome-headless-shell=120.0.6099.109)
      at Object.throwDecodedError (C:devtaalalprojectsmainTestColiCheapnode_modulesselenium-webdriverliberror.js:524:15)
      at parseHttpResponse (C:devtaalalprojectsmainTestColiCheapnode_modulesselenium-webdriverlibhttp.js:601:13)
      at Executor.execute (C:devtaalalprojectsmainTestColiCheapnode_modulesselenium-webdriverlibhttp.js:529:28)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at async thenableWebDriverProxy.execute (C:devtaalalprojectsmainTestColiCheapnode_modulesselenium-webdriverlibwebdriver.js:745:17)   

Can you help me please to fix this error. I use .usingServer(“http://localhost:4444/wd/hub”) and .usingServer(“http://localhost:4444”) and have always the same error.

Thanks.

simpler coding in js

How can I convert this hard code to simpler code in JS:

if (data) {
    var { title, slug } = data.movie;
}

or this:

if (data) var { title, slug } = data.movie;

I try this and saw I can’t assign in ternary operator:

data?.movie ? const {title, slug} = data.movie : null

and this :

data?.movie && const {title, slug} = data.movie

Is it possible to Proxy a JavaScript class’s extended methods

Given a class like:

class A {}

Is it possible to modify in any way so that I can proxy when methods are subclassed like so:

// proxy the `A` object in some way
const handler = {
  get(target, property) {
    console.log("getting", arguments);
    return target[property];
  },
  set(target, property, value) {
    console.log("setting", arguments);
    return target[property] = value;
  },
};

const A_proxied = new Proxy(A, handler);

I want the message setting hello (or similar) to be logged in the following case.

class B extends A_proxied {
  hello() {
    return "world";
  }
}

The above code just logs getting prototype and nothing else. Any ideas?

Access icm20948-sensor data on raspberry pi 4 via chirimen-node-lib

I’m using the @chirimen/icm20948 lib to read data from icm20948 motion tracking sensor on my waveshare environment sensor hat via i2c.

code:

  private mod!: any;

  constructor() {

    console.log('init');

    this.init().catch(err => console.log(err)).then(() => {

      console.log('initialized:');

      //read data
      setInterval(() => {
        this.read().catch(err => console.log(err));
      }, 2000);

    });
  }


  async init() {

    const i2cAccess = await requestI2CAccess();
    const port = i2cAccess.ports.get(1);

    this.mod = new ICM20948(port)

    await this.mod.init();
  }

  async read() {

    await this.mod.getdata()
    console.log("ACCELL: ", await this.mod.Accel);
    console.log("GYRO: ", await this.mod.Gyro);
    console.log("MAG:", await this.mod.Mag);
  }

output:

ACCELL:  [ 0, 0, 0 ]
GYRO:  [ 0, 0, 0 ]
MAG: [ -17790.75, 22288.75, 31548 ]

i can´t get the values for the accelerometer and gyro-sensor.

the getdata-function should update the sensor data.

Remix run hydration error only on index route

I am starting a project on remix v2, when I test my code locally everything works fine. However, when I deploy my project to a EC2 server I get an error on my index route
Initial URL (/index.html) does not match URL at time of hydration (/), reloading page...
This only occurs on my index route and only occurs after a server side render. When I navigate to another page it works fine, and I click back to the index page it still works fine when using client side rendering. When I refresh, I see the error again. I also noticed when I create a route like index[.].html.tsx it would work, weirdly enough. Any reason why this might be happening?

npx remix routes output

<Routes>
  <Route file="root.tsx">
    <Route path="domain" index file="routes/domain._index.tsx" />
    <Route index file="routes/_index.tsx" />
    <Route path="*" file="routes/$.tsx" />
  </Route>
</Routes>

Vue.js Component Only Renders Background Colors from a Subset of Tailwind CSS Colors

I have a card component:

<template>
  <div
    class="z-50 flex w-[15vw] flex-col items-center justify-center gap-5 rounded-md border-2 border-gray-300 bg-[#f3f3f3] p-5 transition-all duration-300 hover:scale-105 hover:font-bold"
  >
    <div class="w-[100%]">
      <div
        :class="color"
        class="flex w-fit items-center justify-center rounded-3xl px-2 text-sm text-white"
      >
        {{ collection }}
      </div>
    </div>
    <div
      class="flex w-[100%] flex-col items-center justify-center gap-2 text-2xl font-thin text-black"
    >
      <div class="italic">{{ question }}</div>
      <div class="w-[100%] rounded-3xl border-2 border-gray-200"></div>
      <div class="font-semibold">{{ answer }}</div>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  collection: String,
  question: String,
  answer: String,
  color: String
})
</script>

<style lang="scss" scoped></style>

and how i use it:

   <UsersFavoriteCard
        :color="color"
        collection="AsyncJs"
        question="does it work"
        answer="yes"
      ></UsersFavoriteCard>
const color = computed(() => {
  const colors = ['orange', 'blue', 'green', 'amber', 'rose', 'teal']
  const randomColor = colors[Math.floor(Math.random() * colors.length)].toLocaleLowerCase()
  const randomRange = 300
  const color = `bg-${randomColor}-${randomRange}`
  console.log(color)
  return color
})

the function works, fine, it generatas for example:
bg-red-300
bg-blue-300
bg-amber-300

but from all of the color, only blue and green are applied.
So if i load the page and the color is:
bg-blue-300 or bg-green-300

the card element has this color.

but when the output is bg-red-300 or bg-rose-300 which are valid tailwind colors, the element has no color and i have to refresh the page so the blue or green are choosen.
If i manually set color to
color=’bg-red-300′
it works.
Why it is so inconsistent? Why valid tailwind color generated by function doesnt work, but set manually works but green and blue works all the time?

I tried many examples using tailwind colors, but all set manually works, but generated by functions it doesnt.