If function is called too many times

i’m using ml5 for a project, and what i’m trying to achieve is everytime my nose is detected inside an ellipse, a song starts and the ellipse moves with a perlin noise effect.

The problem is the “if function” is called too many times and I think it deteriorates the sound bc I think it starts it multiple times. Also even when my nose is inside the ellipse it keeps saying “false” and then “true” in the console and I don’t know why? What would be the best way to code this to make it work smoothly?

checkCollision(points) {
    points.forEach((keypoints) => {
      keypoints.forEach((keypoint) => {
        const pos = keypoint.position;
        const d = dist(pos.x, pos.y, this.x, this.y);
        const hasTriggered = d <= this.radius * 0.5;
        if (hasTriggered) {
          this.sound.play();
          this.maxnoise = lerp(this.maxnoise, 50, 0.05);
          console.log("true");
        } else {
          console.log("false");
          this.sound.stop();
          this.maxnoise = lerp(this.maxnoise, this.maxnoiseafter, 0.05);
        }
      });
    });
}

this is what my console looks like when i’m inside the ellipse and supposed to trigger the effect and the sound
this is what my console looks like when i'm inside the ellipse and supposed to trigger the effect and the sound

Process.binding is not defined in Gatsby + web3

I’m developing a web app on Gatsby using web3 and I have problems with the process.binding not defined. The develop works fine but not the build.

I understand that this comes from the process/browser not having “binding” and the fact I am not supposed to use Node.js functions but since it’s web3 which should work in the browser – Im not sure what to do.

Any direction will be appreciated. Have been banging my head at the wall for a while.

 ERROR 

Page data from page-data.json for the failed page "/[...]/": {
  "componentChunkName": "component---src-pages-js",
  "path": "/[...]/",
  "result": {
    "pageContext": {}
  },
  "staticQueryHashes": [],
  "matchPath": "/*"
}

failed Building static HTML for pages - 3.268s

 ERROR #95313 

Building static HTML failed for path "/[...]/"

See our docs page for more info on this error: https://gatsby.dev/debug-html


  175 |
  176 | process.binding = function (name) {
> 177 |     throw new Error('process.binding is not supported');
      | ^
  178 | };
  179 |
  180 | process.cwd = function () { return '/' };


  WebpackError: process.binding is not supported
  
  - browser.js:177 
    [artcart-buyers]/[process]/browser.js:177:1
  
  - index.js:7 
    [artcart-buyers]/[fs-minipass]/index.js:7:24
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - create.js:8 
    [artcart-buyers]/[tar]/lib/create.js:8:13
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - index.js:4 
    [artcart-buyers]/[tar]/index.js:4:13
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - files.js:19 
    [artcart-buyers]/[swarm-js]/lib/files.js:19:11
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - api-node.js:3 
    [artcart-buyers]/[swarm-js]/lib/api-node.js:3:13
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - index.js:23 
    [artcart-buyers]/[web3-bzz]/lib/index.js:23:13
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - index.js:34 
    [artcart-buyers]/[web3]/lib/index.js:34:11
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - bootstrap:19 
    artcart-buyers/webpack/bootstrap:19:1
  
  - static-entry.js:212 
    artcart-buyers/.cache/static-entry.js:212:27
  
  - Tokenizer.js:26 
    [artcart-buyers]/[stylis]/src/Tokenizer.js:26:1

the code for […].js:

import React from "react"
import { Auth0Provider } from "../utils/auth"
import  DataContextProvider  from "../utils/dataStore";
import EthereumContextProvider from "../utils/ethereumContext";
import { Router } from "@reach/router"
import PrivateRoute from "../components/PrivateRoute"
import Nft from '../components/pages/Nft'
import Transactions from '../components/pages/Transactions'
import Index from '../components/pages/Index'
import Account from '../components/pages/Account'
import "@ethersproject/shims"

const App = ({ element, location }) => {
    const isBrowser = typeof window !== "undefined"
    
    const onRedirectCallback = appState => {
        location.navigate(
          appState && appState.targetUrl
            ? appState.targetUrl
            : window.location.pathname
        )
      }

    if (isBrowser) {
        return (
            <>
            <EthereumContextProvider>
            <Auth0Provider
                domain={process.env.GATSBY_AUTH0_DOMAIN}
                client_id={process.env.GATSBY_AUTH0_CLIENTID}
                redirect_uri={window.location.origin}
                cacheLocation='localstorage'
                onRedirectCallback={onRedirectCallback}
            >
            <DataContextProvider>
            <Router>
                <PrivateRoute path="/" component={Index} />
                <PrivateRoute path="/nft" component={Nft} />
                <PrivateRoute path="/transactions" component={Transactions} />
                <PrivateRoute path="/account" component={Account} />
            </Router>
            </DataContextProvider>
            </Auth0Provider>
            </EthereumContextProvider>       
            </>
        )
    }
    else {
        return (
            <></>
        )
    }

}
export default App

To uppercase string index and replace it with current string index

I want a string (str) to get removed by the dashes and uppercase the char after where the dash has been removed.
The code removes the dashes successfully but don’t uppercase the next char.
I think the problem is at the line where I commented This code doesn’t work

So the variable str should get returned like: thisIsAnExample

str="this-is-an-example"

function toCamelCase(str) {
  if(str.includes("-")) {
    for(var i = 0; i < str.length; i++) {
      if (str[i] == "-") {
        str = str.replace(str[i], '');
        if (i < str.length-1) {
          str[i+1] = str[i+1].toUpperCase(); /*This code doesn't work*/
        }
      }
    }
  }
  return str;
}

Client-Side Routes with React Native Work Locally but not When Deployed with Heroic

I am in the middle of the development phase of this app, and we want to host it somewhere where the clients will be able to play around with it and see what features are currently existing. While all of the features and routes that we currently have are working properly on my machine locally, whenever we try to get the app running off of Expo-Go using Heroku to run the backend, none of the routes work anymore.
The Routes are all done on the client side of things, so the front-end files have everything involving routes. That part of my app.js file looks like this…

return (
    <NativeRouter>
      <RecoilRoot>
        <ApolloProvider client={client}>
          <PaperProvider>
            <View style={AppStyles.container}>
            
             <View>

                {loggedIn === false ? (<LandingPage handleLoggedIn={handleLoggedIn}/>) : null}
                
                {loggedIn === true ? (
                  <Banner handleLoggedIn={handleLoggedIn}/>
                ) : null}

                {loggedIn === true ? (
                  <Switch>
                    <Route exact path='/home' component={Home} />
                    <Route exact path='/shift_planner' component={ShiftPlanner} />

                    <Route exact path='/view_notifications' component={Notifications} />

                    <Route exact path='/leadership_notified' component={LeadershipNotified} />
                      <Route exact path='/police_contacted' component={PoliceContacted} />
                        <Route exact path='/please_remember' component={PleaseRemember} />
                          <Route exact path='/before_we_begin' component={BeforeWeBegin} />
                            <Route exact path='/create_or_add' component={CreateOrAdd} />
                              <Route exact path='/report_an_accident' component={ReportAnAccident} />
                        
                        
                        
                        <Route exact path='/reportcollision' component={ReportCollision} />
                        <Route exact path='/reportinjuryaccident' component={ReportInjuryAccident} />
                        <Route exact path='/reportpropertyaccident' component={ReportPropertyAccident} />
                        <Route exact path='/reporthitperson' component={ReportHitPerson} />
                        <Route exact path='/reportinjuryreport' component={ReportInjuryReport} />


                    <Route exact path='/reporting' component={Reporting} />
                    <Route exact path='/productivity' component={Productivity} /> 
                    <Route exact path='/admin_messages' component={Communication} />
                    <Route exact path='/analytics' component={Analytics} />


                    <Route exact path='/settings' component={Settings} />
                      <Route exact path='/account_information' component={AccountInformation} />
                        <Route exact path='/edit_account_information' component={EditAccountInformation} />
                        <Route exact path='/view_accidents' component={ViewAccidents} />
                      <Route exact path='/account_settings' component={AccountSettings} />

                    <Route exact path='/score_card' component={ScoreCard} />
                      <Route exact path='/quality' component={Quality} />
                      <Route exact path='/safetyandcompliance' component={SafetyAndCompliance} />
                      <Route exact path='/team' component={Team} />

                  </Switch>
                ) : null}
              <StatusBar style="auto" />
              </View>
            
            </View>
          </PaperProvider>
        </ApolloProvider>
      </RecoilRoot>
    </NativeRouter>
  );
}

To reiterate, this all worked perfectly whenever running on localhost. However now, whenever we attempt to change the route, nothing happens, and the app is permanently stuck on the domain with the route '/'

Since essentially every file has a route to another I’m not going to paste all of them here. The first example, however, will be the Login.js component. The user is to be rerouted to the '/home' page after successfully logging in

import React, { useEffect, useState } from 'react';
import { useRecoilState } from 'recoil'
import { userState } from '../../../../Recoil/atoms'
import { useHistory } from 'react-router-native';
import { Button } from 'react-native-paper';
import { View } from 'react-native';
import { ButtonStyles } from '../../../../Styles/LandingPageStyles';
import { useMutation } from '@apollo/client';
import { LOGIN } from '../../../../GraphQL/operations';
import stateChange from '../../../../Hooks/handleToken'

const LoginButton = ({ userData, handleLoggedIn }) => {
    const [login, { loading: loading, error: error, data: data }] =
        useMutation(LOGIN);
    const [buttonLoading, setButtonLoading] = useState(false)
    const [user, setUser] = useRecoilState(userState);
    let history = useHistory();

    useEffect( async () => {
        if (!loading && data) {
            await setUser(data.signinDriver)
            await stateChange(data.signinDriver.token);
            await handleLoggedIn()  // Throws an error if improper credentials entered
            await history.push("/home");
        }
    }, [data])

    const handleButtonLoading = () => {
        setButtonLoading(!buttonLoading)
    }

    return (
        <View>
            <View>
                <Button 
                    icon="login" 
                    mode="contained"
                    loading={buttonLoading} 
                    style={ButtonStyles.logInButton}
                    onPress={ async () => {
                        await handleButtonLoading()
                        await login({
                            variables: {
                                email: userData.email,
                                password: userData.password,
                            },
                        });
                    }}
                >
                        Login
                </Button>

            </View>
        </View>
    );
};

export default LoginButton;

Essentially, everywhere I have routing I use await history.push("/whatever_the_route_is"); And since the deployment on Heroku, I get nothing returned from this. Does anybody see a solution to this?

Appium with Webdriverio is not waiting for the element

I’ve just setup Appium with Webdriverio and I am having a trouble waiting for the element.
Session ends as soon as app is opened, and I can see from Appium logs that it waits 0ms for the element.

This is my test file login.test.js:

const welcome = require("../../pageObjects/welcome.page");

describe("Login", () => {
  it("Verify user can login", () => {
    driver.setImplicitTimeout(10000); // tried with implicit wait
    driver.pause(3000); // and with explicit wait
    welcome.signInBtn.click();
  });
});

welcome.page.js file:

class WelcomePage {
  /**
   * Define Elements
   */

  get signInBtn() {
    return $("~Sign in");
    
  }
}

module.exports = new WelcomePage();

package.json file:

{
  "name": "appium_js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/.bin/wdio wdio.conf.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@wdio/cli": "^7.16.13"
  },
  "devDependencies": {
    "@wdio/local-runner": "^7.16.13",
    "@wdio/mocha-framework": "^7.16.13",
    "@wdio/selenium-standalone-service": "^7.16.13",
    "@wdio/spec-reporter": "^7.16.13",
    "@wdio/sync": "^7.16.13"
  }
}

wdio.conf.js file:

let { join } = require("path");

exports.config = {
  
  runner: "local",
  port: 4723,
  path: "/wd/hub",
  
  specs: ["./test/specs/**/*.js"],
 
  maxInstances: 1,
  
  capabilities: [
    {
      platformName: "Android",
      "appium:deviceName": "Pixel XL API 31",
      "appium:app": join(process.cwd(), "./app-dev-debug.apk"),
    },
  ],
  
  logLevel: "info",
  
  
  bail: 0,
  
  
  baseUrl: "http://localhost",
  
  waitforTimeout: 0,
  
  connectionRetryTimeout: 120000,
  
  connectionRetryCount: 3,
  
  services: ["selenium-standalone"],

  
  framework: "mocha",
  
  
  reporters: ["spec"],

  
  mochaOpts: {
    ui: "bdd",
    timeout: 60000,
  }
};

Appium logs:

[W3C (10484f32)] Calling AppiumDriver.findElement() with args: ["accessibility id","Sign in","10484f32-220b-4a22-ae39-9b7c6ff9adfb"]
[BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[BaseDriver] Waiting up to 0 ms for condition
[WD Proxy] Matched '/element' to command name 'findElement'
[WD Proxy] Proxying [POST /element] to [POST http://127.0.0.1:8201/wd/hub/session/0b87b7c0-9b19-48ce-9e6e-02c6d5cc8d08/element] with body: {"strategy":"accessibility id","selector":"Sign in","context":"","multiple":false}
[HTTP] --> DELETE /wd/hub/session/10484f32-220b-4a22-ae39-9b7c6ff9adfb
[HTTP] {}
[W3C (10484f32)] Calling AppiumDriver.deleteSession() with args: ["10484f32-220b-4a22-ae39-9b7c6ff9adfb"]
[BaseDriver] Event 'quitSessionRequested' logged at 1642100255280 (19:57:35 GMT+0100 (Central European Standard Time))
[Appium] Removing session 10484f32-220b-4a22-ae39-9b7c6ff9adfb from our master session list
[UiAutomator2] Deleting UiAutomator2 session
[UiAutomator2] Deleting UiAutomator2 server session
[WD Proxy] Matched '/' to command name 'deleteSession'
[WD Proxy] Proxying [DELETE /] to [DELETE http://127.0.0.1:8201/wd/hub/session/0b87b7c0-9b19-48ce-9e6e-02c6d5cc8d08] with no body

Not sure why it doesn’t wait for the element as I’ve tried with implicit and explicit waits? Maybe it has do to with the driver?

How to handle Audio Mute on a crossplatform agora app?

I have a cross platform agora app. The Mobile version is using the Agora React Native SDK while the web version is using the Web SDK v4. When I was implementing the audio mute / unmute indication I found that the event does not trigger from mobile to web. Can anyone please help me with this, what should I do to make it work?

// This is the Code From React Native 
    const toggleAudio = useCallback(async () => {
    await RtcEngine.instance().enableLocalAudio(!audioEnabled);

    setCurrentUser(prev => {
        return { ...prev, audioEnabled: !audioEnabled }
    })
    setAudioEnabled(!audioEnabled);
}, [audioEnabled]);

And Here is the Web event Handler

 client.on("user-unpublished", (user, type) => {
            if (type === "audio") {
                user.audioTrack?.stop();
                setRemoteUsers(prev => {
                    return prev.map(ussr => ussr.uid == user.uid ? user : ussr);
                })
            }

            if (type == 'video') {
                setRemoteUsers(prev => {
                    return prev.map(ussr => ussr.uid == user.uid ? user : ussr);
                })
            }
        });

The handler works for web to web and also for the video event on mobile but doesn’t trigger the callback for the audio

Vue JS: add values from API JSon

i’m new developer in Vue JS.
below is my response body, and i wanted to add amount values that has is_paid:true with paid_amount only.. is there a way to do this in Vue JS?

{
    "payment" : {
        "installment_payment" : {
            "installments" : [
                          amount:"",
                                date: "",
                                is_paid: true,
                            },
                            {
                                amount: "",
                                date: "",
                                is_paid: false,

                            },
                            {
                                amount: "",
                                date: "",
                                is_paid: false,
                            },
                              {
                                amount: "",
                                date: "",
                                is_paid: true,
                            }
                        ],

                        remaining: ""

                    },
                    paid_amount: "",
                },]

}

Test with react-aria useButton gives me the famous “act” warning

i’m using react-aria and react testing-library.
In my Button component, i’m using react-aria’s useButton and I use onPress prop to pass the function to call once click. In the unit test, I just try to click it in order to trigger a simple jest.fn() function, and all I do after that is check if function have been called.

const handleOnClick = jest.fn();
render(<Button onPress={handleOnClick}>test me</Button>);

userEvent.click(screen.getByRole('button'));
expect(handleOnClick).toHaveBeenCalled();

That is showing the following warning:

console.error
    Warning: An update to Button inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

If I wrap the click with act the warning is gone, but seems it’s not a good practice to do that, because, in fact, testing library is doing an act internally in userEvent and in other methods. What can I do? Thanks.

Scroll bars not overlaying correctly

I’m trying to add scroll bars to my app so that individual sections can be scrolled, and I am expecting the styling to look like this: see desired behaviour.

However when I first load my page the scroll bars are appearing attached to the right of the parent div, rather than within it, or according to the inspector, in just enough width of padding for them to sit in. See incorrect behaviour

Currently to enable my show less/ show all option, the scroll behaviour is changed in the JS so perhaps resetting scroll behaviour is causing this?

I have tried to change the scrollbar-gutter property to auto, however this doesn’t seem to affect the scroll-bar behaviour in this case.

I have also tried to find other ways of styling the scroll bars but doesn’t seem to be much of that around.

Any help is appreciated!

How do I build an NPM package that can access a [my package]-conf.js file in the root of the main project

// this is for a Vue 3 project - not sure if that's important for the answer

// APPENDIX: 
//   package = npm package
//   project = vue 3 project that will import the npm package

I’m building an npm package that has reusable vue components using vue-sfc-rollup.

To allow for customisation I want to give the user the ability to make a config file in the root (same level as the package.json of the project) which can then be accessed by the package.

I was hoping it would look something like this.

import config from '@/my-package-conf.js' where @ (or other symbol) would indicate the root of the project

I assume this can be done using a relative path but that won’t be particularly easy for my implementation.

Thanks for any help you can provide!

Angular catching “standard” errors instead of my API’s errors

I have a service that looks like this:

return this.http
      .post(requestUrl, body, { headers, observe: 'response' })
      .toPromise()
      .then((res: any) => {
        return res.body?.data || res?.body?.message;
      }).catch((err) => {
        console.log('error', err);
      })

When i trigger an error, this is what i get on the console.log:

error Error Code: 400
Message: Http failure response for <MY API ENDPOINT>: 400 OK

But on the network tab (Google chrome dev tools) i see this:

{
    "message": "Unsupported value, please contact support.",
    "status": "failure"
}

How can i read my message that i’m sending from my Backend in my angular .catch block?

Libraries for selecting a date and time in ReactJS 15.4?

Currently need a Date and Time picker for a web application I’m working on. Its using React version 15.4, so I haven’t been able to find a suitable library online. Currently using DatePicker from material-ui, but I’m unable to select a time, and since it’s an old version of react I can’t find the documentation for it anywhere.

Any ideas? Thanks