AppScript Events

Please help me on how to code an events in Appscript manually. When I submit the form. It will log the user information that he fillin from the form.

Registration using forms putting in firstname and lastname. Then onSubmit it will log the data in the spreadsheet. but I want to use the event on this.

“X is assignable to the constraint of type ‘T’, but ‘T’ could be instantiated with a different subtype of constraint” for void function

I have a React Context where a function takes in another function as an argument. A generic hook then uses this.

// Context
export type A = { id: string }

const TestProvider = () => {
  function test(doStuff: (a: A) => void) {...}
  return <TestContext.Provider value={{test}}>{children}</TestContext.Provider>
}

// Hook
export function useThing<T extends A>() {
  const { test } = useContext(TestContext)
  const [stuff, setStuff] = useState<T[]>()

  function doStuff(a: T) {
    setStuff([...stuff, a])
  }

  function doMoreStuff() {
    test(doStuff) // The error occurs here
  }
}

I’ve looked at a lot of posts with this same problem, but they all have some sort of return value. How do I fix this for a function that returns nothing?

If I change the function signature in the hook to doStuff(a: Pick<T, 'id'>), the error disappears. However, this will cause an error in the setter function:

Type ‘T | Pick<T, “id”>’ is not assignable to type ‘T’.
‘T | Pick<T, “id”>’ is assignable to the constraint of type ‘T’, but ‘T’ could be instantiated with a different subtype of constraint ‘A’.

Correctly passing parameters to sinon spy

I have the below code:

import { expect } from 'chai'
import * as sinon from 'sinon'
import { runStripeOnboarding } from '../../src/vetting/helper/stripe-onboarding-helper'
import { API } from '../../src/apis'
import { Register, UUID } from '@boostercloud/framework-types'
import { Provider } from '../../src/entities/provider'
import { faker } from '@faker-js/faker'
import * as Capabilities from '../../src/capabilities'
import Stripe from 'stripe'
import * as entityHelpers from '../../src/helpers/entity-helpers'
import * as dataModelTransformation from '../../src/common/datamodel-transformations'
import * as stripeApiHelper from '../../src/helpers/stripe-api-helper'
import * as logger from '../../src/logger'

describe('Stripe Onboarding Helper', () => {
  let provider: Provider, kycId: UUID, bankVettingWorkflowId: UUID, register: Register

  const LOGGER = sinon.replace(
    logger,
    'getLogger',
    sinon.fake.returns({
      info: () => sinon.stub(),
      warn: () => sinon.stub(),
      error: () => sinon.stub(),
    })
  )

  beforeEach(() => {
    const tin = faker.random.alphaNumeric(9)
    const username = faker.internet.userName()
    const baseCurrentUser = {
      id: faker.datatype.uuid(),
      username,
      roles: [Capabilities.KYCSubmitter.name],
      claims: {
        jti: faker.datatype.uuid(),
        validatedTIN: tin,
        validatedTINForDelegation: true,
        otpGenerationTries: 0,
        otpValidated: false,
        username,
        firstName: faker.name.firstName(),
        lastName: faker.name.lastName(),
        email: faker.internet.email(),
      },
    }
    provider = {
      id: faker.random.alphaNumeric(9),
      providerName: 'Test Provider',
      tin: '123456789',
      stripeAccount: undefined,
      status: 'OnboardingAccountCreated',
      salesforceStatus: {
        updateRequired: false,
      },
      latestKYCOrThrow: () =>
        Promise.resolve({
          id: faker.random.uuid(),
          tin,
          status: 'KYCSubmitted',
          statusTransitions: [],
          hasRelatedAcceptedOffer: false,
          hasKYCApprovalExpired: () => false,
          approvalDate: () => faker.datatype.string(25),
        }),
      latestKYC: () =>
        Promise.resolve({
          id: faker.random.uuid(),
          tin,
          status: 'KYCSubmitted',
          statusTransitions: [],
          hasRelatedAcceptedOffer: false,
          hasKYCApprovalExpired: () => false,
          approvalDate: () => faker.datatype.string(25),
        }),
      latestApprovedKYC: () => Promise.resolve(undefined),
      latestUnexpiredApprovedKYC: () => Promise.resolve(undefined),
    }
    kycId = 'kyc-123'
    bankVettingWorkflowId = 'workflow-123'
    register = new Register(faker.datatype.uuid(), {}, sinon.stub(), baseCurrentUser)
  })

  afterEach(() => {
    sinon.restore()
  })

  it.only('should create a new Stripe account if not already exists', async () => {
    sinon.replace(
      API.Stripe.accounts,
      'create',
      sinon.fake.resolves({ id: 'acct_123', created: Date.now() } as unknown as Stripe.Response<Stripe.Account>)
    )
    sinon.stub(API.Stripe.accounts, 'update')
    sinon.replace(
      API.Stripe.accounts,
      'listPersons',
      sinon.fake.resolves({ data: [], has_more: false } as unknown as Stripe.Response<Stripe.ApiList<Stripe.Person>>)
    )
    sinon.replace(entityHelpers, 'getKYCOrThrow', sinon.fake.returns({ submittedKYC: {} }))
    sinon.replace(dataModelTransformation, 'toUnsafeProviderKYCInfo', sinon.fake.resolves({}))
    sinon.replace(
      stripeApiHelper,
      'getStripeReqParams',
      sinon.fake.returns({ paramsToCreateAccount: {}, paramsToAddPersons: [] })
    )

    await runStripeOnboarding(provider, kycId, bankVettingWorkflowId, register)

    expect(LOGGER).to.have.been.calledWith(
      `Created Stripe connected account for the provider - ${provider.providerName}`
    )
  })
})

I want to compare arguments for my LOGGER.info() which, I create using: const LOGGER: Logger = getLogger('StripeVettingHelper') in the same file where runStripeOnboarding() is defined.

When I am running the test, the call count to LOGGER is 0.

What am I doing wrong?

Invitation to Participate in Research on Open-Source Software Contributions

I hope this message finds you well. My name is Vahid Jafarzadeh, and I am conducting research on the motivations and incentives for contributing to open-source software (OSS) projects as part of my graduate studies at Avans Plus University.
The aim of this research is to understand the diverse motivations and factors that drive individuals to contribute to OSS projects. Your experience and insights as an active OSS contributor would be incredibly valuable in helping us explore these motivations and their impact on the OSS ecosystem.
I would like to invite you to participate by answering a few questions via message at your convenience. Your responses will be kept confidential and used solely for academic purposes. Below are the questions I would appreciate your insights on:
1-Can you tell me about your background and how you first became involved in open-source software projects?
2-How long have you been contributing to OSS, and which projects have you contributed to?
3-What motivates you personally to contribute to open-source software projects?
4-How important is personal satisfaction and enjoyment in your decision to contribute to OSS?
5-Can you describe how contributing to OSS projects has helped you develop your skills or advance your career?
6-How do you perceive the role of community and collaboration in your contributions to OSS projects?
7-Can you share an experience where community support or feedback influenced your work on an OSS project?
8-What challenges or barriers have you faced in contributing to OSS projects, and how have you overcome them?
9-Are there any factors that discourage you from contributing more to OSS projects?
10-What would encourage you to increase your involvement or contributions to open-source projects in the future?
11-Are there any specific types of projects or technologies you are particularly interested in contributing to going forward?
Please feel free to respond directly to this message with your answers. If you have any questions or need further clarification, don’t hesitate to reach out. Thank you very much for considering this request. Your insights will be invaluable to the success of this research.

Kind regards,

Please feel free to respond directly to this message with your answers. If you have any questions or need further clarification, don’t hesitate to reach out. Thank you very much for considering this request. Your insights will be invaluable to the success of this research.

How to use css next sibling selector with cached element

I have a cached element and I wish to use that reference to find the next (sibling) element in the DOM tree. Is this possible?

Initially, I thought this could be a use-case for the new :scope rule, but I was reminded that the scope rule only applies to descendent elements (i.e. desired element must be a descendant of the cached element).

const aa = document.querySelector('div');
const bb = aa.querySelector(':scope + aside');
//const bb = aa.querySelector(':scope > aside');

console.log(bb.classList[0]);
<div>Div<aside class="zoe yip xin"> span</aside></div>
<aside class="abe bob cam">Aside</aside>

So, how would one do this?

I am starting with a cached element – how would I use myEl.querySelector(blah blah) to get the sibling of that cached element?

For those desiring, here is a snippet with which to fiddle.

= – = – = – =

Note: I prefer not to use the parentNode or such, since the cached element is reasonably easy to find (has an ID), whereas its sibling (desired element) would be quite difficult to target from the parentNode.

How to make a field inside the canvas that can be moved? [closed]

I want to make something like draw.io using blazor. How would it be possible to make a field like in draw.io that moves by pressing the mouse wheel?

At the moment I have implemented the functionality of the application without a moving field using canvas tools. Now I am looking for information on how to implement this idea without using mxGraph from draw.io.

How to filter one array from another array conditionally, comparing child objects – Javascript/Typescript [closed]

How to filter/delete entries from Input using conditional input and get the expected output.

I tried using filter but i have to compare Category (parent) and also child(name).

Below is the input
Input

[
    {
        "category": "fruits",
        "images": [
            {
                "name": "apple",
                "src": "apple.git"
            },
            {
                "name": "grapes",
                "src": "grapes.gig"
            },
            {
                "name": "pear",
                "src": "pear.gif"
            }
            
        ]
    },
    {
        "category": "vegetables",
        "images": [
            {
                "name": "potato",
                "src": "potato.gif"
            },
            {
                "name": "tomato",
                "src": "tomato.gif"
            }
        ]
    }
]

Below is the conditional input which I want to get from above input and in input format only.
Conditional Input

[
    {
        "category": "fruits",
        "name": "apple"
    },
    {
        "category": "fruits",
        "name": "grapes"
    },
    {
        "category": "vegetables",
        "name": "potato"
    }
]

Below is the expected output, basically it is input only but filter objects which are not in conditional input.

Expected Output

[
  {
    "category": "fruits",
    "images": [
      {
        "name": "apple",
        "src": "apple.git"
      },
      {
        "name": "grapes",
        "src": "grapes.gig"
      }
    ]
  },
  {
    "category": "vegetables",
    "images": [
      {
        "name": "potato",
        "src": "potato.gif"
      }
    ]
  }
]

Link from browser to Apple app store or android app store [duplicate]

I’m creating a banner with a button that would allow a user who is on my website on mobile device to click that button and be taken to that app in the apple app store or the equivalent for the google play store on android. I’ve looked over previous stackoverflow posts and can’t find any recent information. What link would that button’s onClick redirect to for both devices?

I’m not sure if I should try to access the app on apple connect and use that URL or if there is another preferred way of going about it.

WordPress to Contentack Blog Migration

I’m trying to figure out how to migrate the blog posts from WordPress website to Contentstack.

I was trying to follow this guide:
https://www.contentstack.com/docs/developers/content-migration/wordpress-to-contentstack

I installed node.js on a vps machine and instaled WordPress-xml-to-contentstack-converter.

In WordPress I exported the blog to a xml file and copied that to the vps.

As described in the guide I added the xml file path to the configuration file index.json.

enter image description here

When I run “npm run export” it shows this error: “error: failed to parse xml:”

enter image description here

Please do you know what I’m doing wrong?

Web OTP API read the OTP from sms message but return undefined

I have JS for getting OTP from sms message and autofill input on login.
The modal below open to allow or deny to read and enter the code from the sms, but when i allow it nothing happened.
While I debugged it on real mobile device I saw that the code break before the .then() function.
This is my JS code:

$(document).ready(function () { 
    if ('OTPCredential' in window) {
        try {
            navigator.credentials.get({ otp: { transport: ['sms'] } })
                .then((content) => {
                    // code not arrive here!
                    $('#my-otp-inp').val(content.code);
                })
                .catch((err) => {
                    console.error('Error fetching OTP:', err);
                });
        } catch (err) {
            console.error('Error initializing OTP retrieval:', err);
        }
    }
});

So, the code break before the .then() so I cannot set the OPT code in my input, and I didn’t get any console.log() message.

This is a screenshot of my site’s login:
enter image description here

What am I missing here?

Can’t start Nuxt 3 dev server, cannot find module ‘@volar/typescript/lib/node/proxyCreateProgram

When I try to run npm run dev dev server triesto start but it shows the following error:

Cannot start nuxt:  Cannot find module '@volar/typescript/lib/node/proxyCreateProgram
Require stack:
  - node_modulesvite-plugin-checkerdistesmcheckersvueTscprepareVueTsc.js

I tried installing @volar as part of my dependencies and vite-plugin-checker but server still not able to run, am I missing some dependency or a configuration in my project?

Tweets are not loading on the dashboard automatically

In this jQuery code, what I’m trying to achieve is that when the logged-in user clicks the follow button, the tweets of the person they are following should appear on the dashboard, and the follow text should change to unfollow.

When I run this code, it does follow the user and saves it to the database, but the follow text does not change to unfollow, and I need to manually refresh the page for the tweets to appear. I want this to happen automatically, with the tweets appearing directly on the screen, and also for the follow text to change to unfollow. What do I need to change or do in this code?

// Follow or unfollow function
document.addEventListener('click', function (event) {
    if (event.target.classList.contains('follow-btn')) {
        var userId = event.target.getAttribute('data-userid');
        var followBtn = event.target;

        $.ajax({
            type: "POST",
            url: '/Home/Follow', // URL to send the follow action
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ UserId: userId }), // UserId property in the FollowUnfollowViewModel model
            success: function (response) {
                if (response.success) {
                    // Append the received tweets to the screen
                    response.tweets.forEach(function (tweet) {
                        $('#tweets-container').append(
                            `<div class="tweet" id="tweet-${tweet.Id}">
                        <time>${new Date(tweet.CreatedAt).toLocaleString()}</time>
                        <p>
                            <strong>${tweet.TwitterUser.FirstName} ${tweet.TwitterUser.LastName}</strong>
                            <span class="text-muted">${tweet.TwitterUser.UserName}</span>
                        </p>
                        <p>${tweet.Content}</p>
                        <div class="tweet-actions">
                            <i class="fas fa-comment"></i>
                            <i class="fas fa-retweet"></i>
                            <i class="fas fa-heart"></i>
                        </div>
                    </div>`
                        );
                    });

                    // Change the follow button to unfollow button
                    followBtn.classList.remove('follow-btn');
                    followBtn.classList.add('unfollow-btn');
                    followBtn.textContent = 'Unfollow';
                }
            },
            error: function () {
               
            }
        });
    }

    if (event.target.classList.contains('unfollow-btn')) {
        var userId = event.target.getAttribute('data-userid');
        var unfollowBtn = event.target;

        $.ajax({
            type: "POST",
            url: '/Home/Unfollow', // URL to send the unfollow action
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ UserId: userId }), // UserId property in the FollowUnfollowViewModel model
            success: function (response) {
                if (response.success) {
                    // Remove the tweets of the unfollowed user from the screen
                    response.tweets.forEach(function (tweet) {
                        document.getElementById(`tweet-${tweet.Id}`).remove();
                    });

                    // Change the unfollow button to follow button
                    unfollowBtn.classList.remove('unfollow-btn');
                    unfollowBtn.classList.add('follow-btn');
                    unfollowBtn.textContent = 'Follow';
                }
            },
            error: function () {
               
            }
        });
    }
});

Access buttons of a div as an array

This is a problem I was having:

I am trying to access the button inside of the div and make each of them log its own text content on click. But all of them display all of the text content. And it has to be in vanilla JavaScript.

const array = document.querySelectorAll(".div");
array.forEach(button => {
    button.addEventListener('click', function (){
        console.log(this.textContent)
    })
});
 <div class=div>
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
  <button>Button 4</button>
</div>

I Used a for loop and a for each loop. None worked.

how to get dropdown values from append function

I have a function that I am using to append data elements from one dropdown option to another
The function is working properly. What I am looking for is to get the values of the second dropdown option which is an array

<select id="sel1" multiple size="5">
<option value="test1">1st test</option>
<option value="test2">2nd test</option>
<option value="test3">3rd test</option>
<option value="test4">4th test</option>
<option value="test5">5th test</option>
</select>
<select id="sel2" name = "sel2[]" multiple size="4">
<option value="dummy">Dummy</option>
</select>
<br>
<input type="button" id="doBtn" value="do it">
<input type="button" id="submit" value="add">
 

and this is my javascript for appending elements

$('#doBtn').click(function () {
$('#sel1 option:selected').each(function () {
    $("<option/>").
    val($(this).val()).
    text($(this).text()).
    appendTo("#sel2");
});
});

when I submit it, I expect the $diag_string to have values but it returns empty

if(isset($_POST[submit]))
{
 $diag_string = implode(', ', $_POST['sel2']);

$sql ="INSERT INTO  ...... values ('...... ')";
    $qsql = mysqli_query($con,$sql);
}

what has to be done to sel2[] select option to obtain values from it?