问:
How to test with jest puppeteer a number input in react?
I'm using Puppeteer for test, and I am now trying to set an input field with the code below:
`

```<code>await page.click('input#numberQuestionToAdd');
await page.type('input#numberQuestionToAdd', '2');
</code>```

`
I think my input never set to 2. I've tried other things but there is never worked

That's my input in React
`

```<code><TextField
    id="numberQuestionToAdd"
    //label="Nombre de questions (Max. 60)"
    label={<span style={{ fontSize: '21px'}}>{"Nombre de questions (Max. 60)"}</span>}
    type="number"
    style={textFieldStyle}
    value={number}
    onChange={(event) => {
        if(event.target.value.length > 2) {
            event.target.value = event.target.value.substr(0, 2)
        }
        if(event.target.valueAsNumber < 1){
            event.target.value = '1'
        }
        if(event.target.valueAsNumber > 60){
            event.target.value = '60'
        }
        setNumber(event.target.value)
    }}
    inputProps={{min:'1', max:'60'}}
    InputLabelProps={{shrink: true}}
    error = {errors.questions}
/>
</code>```

`

Do you have an idea on the problem ?

Body:
I'm using Puppeteer for test, and I am now trying to set an input field with the code below:
`

await page.click('input#numberQuestionToAdd');
await page.type('input#numberQuestionToAdd', '2');

`
I think my input never set to 2. I've tried other things but there is never worked

That's my input in React
`

<TextField
    id="numberQuestionToAdd"
    //label="Nombre de questions (Max. 60)"
    label={{"Nombre de questions (Max. 60)"}}
    type="number"
    style={textFieldStyle}
    value={number}
    onChange={(event) => {
        if(event.target.value.length > 2) {
            event.target.value = event.target.value.substr(0, 2)
        }
        if(event.target.valueAsNumber < 1){
            event.target.value = '1'
        }
        if(event.target.valueAsNumber > 60){
            event.target.value = '60'
        }
        setNumber(event.target.value)
    }}
    inputProps={{min:'1', max:'60'}}
    InputLabelProps={{shrink: true}}
    error = {errors.questions}
/>

`

Do you have an idea on the problem ?


来源: stackexchange

问:
socket python library. client crashes
I start the server, then the client, the server gets the data and the client does not get a response, crashes

server

```<code>import pygame, socket, time
pygame.init()

main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
main_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
main_socket.bind(("localhost", 10000))
main_socket.setblocking(0)
main_socket.listen(5)

players_sockets = []

while True:

    try:
        new_socket, addr = main_socket.accept()
        print("Connect", addr)
        new_socket.setblocking(0)
        players_sockets.append(new_socket)
    except:
        pass

    for i in players_sockets:
        try:
            data = i.recv(1024)
            data = data.decode()
        except:
            pass

    for i in players_sockets:
        try:
                 i.send("server data").encode()
        except:
            players_sockets.remove(i)
            print("Disconnect")
            i.close()

    time.sleep(1)
</code>```

client

```<code>import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.connect(("localhost", 10000))

while True:

    sock.send("Command".encode())

    data = sock.recv(1024)
    data = data.decode()

    print(data)
</code>```

error:

```<code>" data = sock.recv(1024)
ConnectionAbortedError: [WinError 10053] The program on your host computer has broken an established connection."
</code>```

ContentLicense: CC BY-SA 4.0

Title: socket python library. client crashes

Body:
I start the server, then the client, the server gets the data and the client does not get a response, crashes

server

import pygame, socket, time
pygame.init()

main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
main_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
main_socket.bind(("localhost", 10000))
main_socket.setblocking(0)
main_socket.listen(5)

players_sockets = []

while True:

    try:
        new_socket, addr = main_socket.accept()
        print("Connect", addr)
        new_socket.setblocking(0)
        players_sockets.append(new_socket)
    except:
        pass

    for i in players_sockets:
        try:
            data = i.recv(1024)
            data = data.decode()
        except:
            pass

    for i in players_sockets:
        try:
                 i.send("server data").encode()
        except:
            players_sockets.remove(i)
            print("Disconnect")
            i.close()

    time.sleep(1)

client

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.connect(("localhost", 10000))

while True:

    sock.send("Command".encode())

    data = sock.recv(1024)
    data = data.decode()

    print(data)

error:

" data = sock.recv(1024)
ConnectionAbortedError: [WinError 10053] The program on your host computer has broken an established connection."


问:
Could not initialize class org.codehaus.groovy.reflection.ReflectionCache [in thread "Daemon worker"]
Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

Exception java.lang.NoClassDefFoundError: Could not initialize class org.codehaus.groovy.reflection.ReflectionCache [in thread "Daemon worker"]

How do i fix this issue?It's a flutter code and it rends well in apk but when i try to builds bundle it give me this error


问:
Expected a ':' after a key at 1332 - Selenium JAVA/TestNG
I have a project with selenium in java and i use TestNG for the suits to execute regression tests. Im trying to execute one, and doesnt matter wheter i try doing it on Firefox or Chrome that i get an error. The explorer opens with 'data' as url and with empty content, and then immediatly closes to do the same once and once again. I get the following error message:

The 'Hubo un error al intentar obtener variables' is a custom exception message.


问:
Illegal string offset 'theme' Problem Laravel Hosting
ErrorException
HTTP 500 Internal Server Error
Illegal string offset 'theme'

Who can help me, error when uploading to the hosting server, and in local XAMPP it works perfectly...
I speak Spanish

Problem uploading to hosting


问:
How can get offset from panResponder

I have an element(red) in the center of Screen and is able for drag and drop. I make it only move Vertical. I want when move/drag the element down of up, get h (new position - default/first position).

How can find h?

```<code>onPanResponderMove:
Animated.event([
null,
{
dx: pan.x,
dy: pan.y,
},
],{useNativeDriver: false}),

onPanResponderRelease: () => {
Animated.spring(
pan, // Auto-multiplexed
{ toValue: { x: 0, y: 0 }, useNativeDriver: false } // Back to zero
).start();
},
});
</code>```

I try this but the element isn't able to drag/move.

```<code>onPanResponderMove: (event, gestureState) => {
alert(gestureState.dy)
Animated.event([
null,
{
dx: pan.x,
dy: pan.y,
},
],{useNativeDriver: false})
},
</code>```

Title: How can get offset from panResponder

Body:
I have an element(red) in the center of Screen and is able for drag and drop. I make it only move Vertical. I want when move/drag the element down of up, get h (new position - default/first position).

How can find h?

onPanResponderMove:
Animated.event([
null,
{
dx: pan.x,
dy: pan.y,
},
],{useNativeDriver: false}),

onPanResponderRelease: () => {
Animated.spring(
pan, // Auto-multiplexed
{ toValue: { x: 0, y: 0 }, useNativeDriver: false } // Back to zero
).start();
},
});

I try this but the element isn't able to drag/move.

onPanResponderMove: (event, gestureState) => {
alert(gestureState.dy)
Animated.event([
null,
{
dx: pan.x,
dy: pan.y,
},
],{useNativeDriver: false})
},


问:
Terminate a graphql request from Apollo Link
I have an ApolloLink setup for the AWSAppSyncClient in my React project to check if the user is authorized to make the graphql request. If the user is not authorized then, link should not invoke the forward method rather just return an Error for unauthorized access (making it a terminating link).

I tried returning the plain Error response (also tried it with Observable.of), but the request doesn't resolves but keeps on to retry the request on an endless loop.

Need a better solution to implement it.

```<code>const authLink = new ApolloLink((operation, forward) => {
  const { operationName } = operation;
  if (checkIfNotAuthorized(operationName)) {
    const error = new Error('Access denied');
    return { errors: [error], data: null };
  }
  return forward(operation);
});
</code>```

Body:
I have an ApolloLink setup for the AWSAppSyncClient in my React project to check if the user is authorized to make the graphql request. If the user is not authorized then, link should not invoke the forward method rather just return an Error for unauthorized access (making it a terminating link).

I tried returning the plain Error response (also tried it with Observable.of), but the request doesn't resolves but keeps on to retry the request on an endless loop.

Need a better solution to implement it.

const authLink = new ApolloLink((operation, forward) => {
  const { operationName } = operation;
  if (checkIfNotAuthorized(operationName)) {
    const error = new Error('Access denied');
    return { errors: [error], data: null };
  }
  return forward(operation);
});


问:
I want to calculate p95 latency every 5 minutes over 30 minutes in Datadog monitor and set alert when out of 6 calculated p95, 3 are above threshold
I want to create a monitor which calculates p95 latency over the last 5 minutes and want to continue calculating for 30 minutes ( six p95 latencies in the last 30 minutes time period )
After that, I want to set alert conditions when 3 out of 6 calculated p95 latencies cross the given threshold.
My question is -

Is it possible with Datadog monitors?

If yes then how can I achieve this?


问:
Find and replace word VBA macro to search folder and subfolders
I currently have this VBA macro that can search through a single folder for docx files and run  find and replace in headers and footers. I am new to VBA and just good and manipulations of code, and was wondering how I can could modify this one to add in the ability to search subfolders as well?

```<code>Sub FindAndReplaceInFolder()
Dim objDoc As Document
Dim strFile As String
Dim strFolder As String
Dim strFindText As String
Dim strReplaceText As String
Dim xSelection As Selection
Dim xSec As Section
Dim xHeader As HeaderFooter
Dim xFooter As HeaderFooter

'  Pop up input boxes for user to enter folder path, the finding and replacing texts.
strFolder = InputBox("Enter folder path here:")
strFile = Dir(strFolder & "" & "\*.docx", vbNormal)
strFindText = InputBox("Enter finding text here:")
strReplaceText = InputBox("Enter replacing text here:")

'  Open each file in the folder to search and replace texts. Save and close the file after the action.
While strFile \<\> ""
Set objDoc = Documents.Open(FileName:=strFolder & "" & strFile)
With objDoc
For Each xSec In objDoc.Sections
For Each xHeader In xSec.Headers
xHeader.Range.Select
Set xSelection = objDoc.Application.Selection
With xSelection
.HomeKey Unit:=wdStory
With xSelection.Find
.Text = strFindText
.Replacement.Text = strReplaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
xSelection.Find.Execute Replace:=wdReplaceAll
End With
Next xHeader
For Each xFooter In xSec.Footers
xFooter.Range.Select
Set xSelection = objDoc.Application.Selection
With xSelection
.HomeKey Unit:=wdStory
With xSelection.Find
.Text = strFindText
.Replacement.Text = strReplaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
xSelection.Find.Execute Replace:=wdReplaceAll
End With
Next xFooter
Next xSec
objDoc.Save
objDoc.Close
strFile = Dir()
End With
Wend
End Sub
</code>```

Not sure how to get started with this so looking for some help

Body:
I currently have this VBA macro that can search through a single folder for docx files and run  find and replace in headers and footers. I am new to VBA and just good and manipulations of code, and was wondering how I can could modify this one to add in the ability to search subfolders as well?

Sub FindAndReplaceInFolder()
Dim objDoc As Document
Dim strFile As String
Dim strFolder As String
Dim strFindText As String
Dim strReplaceText As String
Dim xSelection As Selection
Dim xSec As Section
Dim xHeader As HeaderFooter
Dim xFooter As HeaderFooter

'  Pop up input boxes for user to enter folder path, the finding and replacing texts.
strFolder = InputBox("Enter folder path here:")
strFile = Dir(strFolder & "" & "\*.docx", vbNormal)
strFindText = InputBox("Enter finding text here:")
strReplaceText = InputBox("Enter replacing text here:")

'  Open each file in the folder to search and replace texts. Save and close the file after the action.
While strFile \<\> ""
Set objDoc = Documents.Open(FileName:=strFolder & "" & strFile)
With objDoc
For Each xSec In objDoc.Sections
For Each xHeader In xSec.Headers
xHeader.Range.Select
Set xSelection = objDoc.Application.Selection
With xSelection
.HomeKey Unit:=wdStory
With xSelection.Find
.Text = strFindText
.Replacement.Text = strReplaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
xSelection.Find.Execute Replace:=wdReplaceAll
End With
Next xHeader
For Each xFooter In xSec.Footers
xFooter.Range.Select
Set xSelection = objDoc.Application.Selection
With xSelection
.HomeKey Unit:=wdStory
With xSelection.Find
.Text = strFindText
.Replacement.Text = strReplaceText
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
xSelection.Find.Execute Replace:=wdReplaceAll
End With
Next xFooter
Next xSec
objDoc.Save
objDoc.Close
strFile = Dir()
End With
Wend
End Sub

Not sure how to get started with this so looking for some help


Title: How to read raw audio data sent by BT

Body:
I'm trying to read raw data sent from a BT recording device in python.
The device is closed so I don't know the streaming format it uses.

I have code in python that listens to the BT characteristic value updated.
The raw data looks like this:

bytearray(b'\x08\x91\x91\x00\x91\x00\x00\t\x11\t\x91\x01\x99\x01\t\x19\x19\t\x10\x99\x02\x00\x99\x01)\x90\x91)\x99!\t\x99!\x1a\n\x91\x92\x99\x11\t\x90\x11\x91\xa1\x91\x91\x92\x99\x91\x10\x1a\x0b\x00 \x99\x01\x19\xa1\x11\x99\x19\x10\t\x01\x19\x90\x01\x19\x0c\t\x11\t\x92\x01\xa9\x11\t\x91\x1a\x00\x11\x99\x91\x10\x90\r\x92\x91\xa1\x10\x1b\x11\x19\x90\x11\t\x90!\x9a\x91\x12\xaa\x0e\x03\t\xa0\x12\t\xa1\x11\x99\x19\x10\t\x01\x19\t\x00)\x0f\x991\xba\x12\x11\xba\x11)\x90\x01\x91\x91\x92\x99\x01\x91\x00\x10\x9a)\x11\x90\x92\xa0\x11\x91\x91\x90\x92\x01\xb1\x91\x19\x01\x91\t\x19\x19\x01\x19\x91\x92\x90\x91\x00\x90\x11\x99\x92\x91\x02\t\x91\x19\x00\x10\t\x00\x11\x99\x10\t\x10\x19\t\x19\x10\x03\x00\x1a\x92\x00\x01\x90\xa1\x11\x99\x92\x19\x90\x11\n\x01\x19\x04\x90\x11\x99\x00\x10\x19\x9a1\x90\x99\x10\x10\t\x19\x10\t\x05\x10\x01\x99\x19\x10\x00\x19\x90\x11\n\x00\x19\x00\x11\x99\x91')

I get about 9 chunks like this every second.

I tried many variations and found that this line of codes works best in understanding the meaning of the raw data:

for section in struct.iter_unpack("<beeeeeeee",data):
    print (section)

I get this 14 sections composed of one index number (0-15) & 8 2 byte floats:

(14, 0.0301971435546875, -0.00022161006927490234, -0.84130859375, 10.1484375, -0.74072265625, 4.0078125, -0.0025043487548828125, -0.69189453125)
(15, 0.1297607421875, -0.04473876953125, 0.1292724609375, -0.0007157325744628906, -11.078125, 49.09375, 1.4901161193847656e-06, -0.0005536079406738281)
(0, -0.11346435546875, 0.0005841255187988281, 0.00015366077423095703, 4.64320182800293e-05, -0.9033203125, 0.0221099853515625, 0.0021419525146484375, 0.0217437744140625)
(1, -0.00409698486328125, -0.002368927001953125, 0.0401611328125, -0.00283050537109375, -0.05206298828125, -5.435943603515625e-05, -0.00019669532775878906, 12312.0)
(2, 0.00012302398681640625, -0.0006847381591796875, -1.2978515625, -0.0005645751953125, 0.18994140625, -0.8349609375, 14360.0, -0.0005002021789550781)
(3, 0.1939697265625, -0.00018525123596191406, -0.974609375, -0.053131103515625, 1.5735626220703125e-05, 0.01381683349609375, -0.0008597373962402344, -0.00016033649444580078)
(4, 0.00061798095703125, -0.00513458251953125, -0.01119232177734375, 0.00031685829162597656, 0.0008287429809570312, 0.00015652179718017578, 0.0005116462707519531, 0.0035114288330078125)
(5, -0.0033473968505859375, 0.482666015625, 0.00806427001953125, 49.09375, 0.0008587837219238281, -1.5791015625, -4.2498111724853516e-05, -0.080078125)
(6, -0.0007071495056152344, -0.06353759765625, 0.00115203857421875, 0.1331787109375, -0.0004930496215820312, 0.0025424957275390625, -0.72412109375, 41.09375)
(7, -0.0008068084716796875, 0.2020263671875, -0.0024585723876953125, 0.00794219970703125, -11.3515625, 0.0001983642578125, -0.053131103515625, 0.00794219970703125)
(8, -0.83349609375, -0.0032196044921875, -253.5, 0.00067138671875, -0.0024890899658203125, 58.71875, -9.5367431640625e-07, 48.625)
(9, -0.04718017578125, 3.505859375, -1.025390625, 1.0967254638671875e-05, -295.25, 4.0590763092041016e-05, -1.2822265625, 0.0184478759765625)
(10, -0.00513458251953125, 0.0184326171875, -0.0035419464111328125, 0.02197265625, -0.00018906593322753906, 0.0011682510375976562, -0.08203125, 0.01508331298828125)
(11, -16.375, 0.014892578125, -0.0035247802734375, -4.0650367736816406e-05, -0.003543853759765625, 0.0186920166015625, 0.541015625, -0.00937652587890625)

The numbers just look like static noise.
I have no knowledge in audio formats and I don't know if I am unpacking the data correctly.
I know that the device can create mono 4000hz wav files.

I'd appreciate any guidance
Thanks


问:
Jenkins pipeline log displays different printenv than from container commandline
1.Created image from bitnami/jenkins as base and installed following binaries as part of image creation: - PMD,NVM,SFDX,sfdx-git-delta,sfci
2.Jenkins plugin to run dynamic agents in a Kubernetes cluster.Agents are launched as inbound agents, so it is expected that the container connects automatically to the Jenkins controller. 3.Using multibranch pipeline pulling image from ACR and deploying pipeline but not finding installed binaries.
/home/jenkins/agent/workspace/Salesforce_Synlab_PR-359@tmp/durable-a79ea535/script.sh: 1: sfdx: not found
printenv of Jenkins log is different than printenv output of Container
Please find below outputs from both Jenkins pipeline log and Container CLI

**echo $PATH from Container Command line */usr/local/nvm/versions/node/v16.17.1/bin: /opt/bitnami/common/bin: /opt/bitnami/java/bin: /usr/local/sbin:/usr/local/bin: /usr/sbin:/usr/bin:/sbin:/bin: /node/bin:/sfdx/bin: /sfci-project: /jdk-11.0.4/bin/: /usr/local/nvm*** = **$PATH from Jenkins pipeline log***

PATH=/var/lib/jenkins/sfdx/bin: /var/lib/jenkins/sfci/scripts: /var/lib/jenkins/sfdx/bin: /var/lib/jenkins/sfci/scripts: /opt/java/openjdk/bin: /usr/local/sbin: /usr/local/bin: /usr/sbin: /usr/bin: /sbin: /bin We tried to use absolute path of sfdx in deployment scripts but path was not found.


问:
How do I use BootstrapFX in my Maven JavaFX project with FXML?
Using IntelliJ, I wanted to create a new JavaFX project using BootstrapFX framework in order to improve the look of my app. I thought it would be easy to include it and use it but I couldn't find any documentation online.

The only example I found is this: Link but this doesn't mention anything about settings in the FXML files and controller classes since it does everything in the start() method. Can somebody help me? I anticipately apologize for any incorrect thing I could have said since I am new to this.


问:
Logic behind using nested useContext provider
I was learning about useContext and I get confused and can't really picture a use case for nested providers...
Here is an example from React's documentation:

// Theme context, default to light theme
const ThemeContext = React.createContext('light');

// Signed-in user context
const UserContext = React.createContext({
  name: 'Guest',
});

class App extends React.Component {
  render() {
    const {signedInUser, theme} = this.props;

    // App component that provides initial context values
    return (
      <ThemeContext.Provider value={theme}>
        <UserContext.Provider value={signedInUser}>
          <Layout />
        </UserContext.Provider>
      </ThemeContext.Provider>
    );
  }
}

function Layout() {
  return (

      <Sidebar />
      <Content />

  );
}

// A component may consume multiple contexts
function Content() {
  return (
    **<ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>**
  );
}```

And the explanation about this example that is given in that page is:

To keep context re-rendering fast, React needs to make each context consumer a separate node in the tree.
If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.

So speed is the only concern and reason why would we want to create multiple createContext & providers? Is there any other use case for such approach? I guess the biggest question I could ask is why would we need multiple useContext at all... Isn't it universal? I can use it wherever I want in the app. So why would one need second context...

Body:
I was learning about useContext and I get confused and can't really picture a use case for nested providers...
Here is an example from React's documentation:

// Theme context, default to light theme
const ThemeContext = React.createContext('light');

// Signed-in user context
const UserContext = React.createContext({
  name: 'Guest',
});

class App extends React.Component {
  render() {
    const {signedInUser, theme} = this.props;

    // App component that provides initial context values
    return (
      <ThemeContext.Provider value={theme}>
        <UserContext.Provider value={signedInUser}>
          <Layout />
        </UserContext.Provider>
      </ThemeContext.Provider>
    );
  }
}

function Layout() {
  return (

      <Sidebar />
      <Content />

  );
}

// A component may consume multiple contexts
function Content() {
  return (
    **<ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>**
  );
}

And the explanation about this example that is given in that page is:

To keep context re-rendering fast, React needs to make each context consumer a separate node in the tree.
If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.

So speed is the only concern and reason why would we want to create multiple createContext & providers? Is there any other use case for such approach? I guess the biggest question I could ask is why would we need multiple useContext at all... Isn't it universal? I can use it wherever I want in the app. So why would one need second context...


问:
Make the Edit option work in a CRUD in ReactJS
I can't make the edit option work, the add option works and the UI is working fine but when i select the option edit it sends me where im going to edit but it doesn't let me write or delete anything.

I can't make the Edit option work, im using a hook called useForm.

```<code>import React, { useState } from "react";

export const useForm = (initialState = {}) => {
  const [values, setValues] = useState(initialState);

  const reset = () => {
    setValues(initialState);
  };

  const handleInputChange = (target) => {
    console.log(target.value);
    setValues({
      ...values,
      [target.name]: target.value,
    });
  };

  return {
    values,
    handleInputChange,
    reset,
  };
};
</code>```

Then i called it in the file where it was suposed to edit but it doesn't let me to write anything.

```<code>import React, { useState, useContext, useEffect } from "react";
import { GlobalContext } from "./context/GlobalState";
import { Link, useNavigate, useParams } from "react-router-dom";
import { useForm } from "./context/useForm";

const EditUser = () => {
  const { values, handleInputChange } = useForm({
    name: "",
    lastName: "",
    email: "",
    description: "",
    location: "",
    services: "",
    price: "",
    schedule: "",
  });

  const [selectedUser, setSelectedUser] = useState({
    name: values.name,
    lastName: values.lastName,
    email: values.email,
    description: values.description,
    location: values.location,
    services: values.services,
    price: values.price,
    schedule: values.schedule,
  });

  const { users, editUser } = useContext(GlobalContext);

  const history = useNavigate();

  const { id } = useParams();

  const currentUserId = id;

  useEffect(() => {
    const userId = currentUserId;
    const selectedUser = users.find((user) => user.id === userId);
    setSelectedUser(selectedUser);
  }, [currentUserId, users]);

  const onSubmit = () => {
    editUser(selectedUser);
    history("/customers");
  };

  return (
    <>
      <div
        onSubmit={onSubmit}
        className="w-screen h-screen flex justify-center items-center"
      >
        <div className="box-border shadow-md bg-white border-current border-1 h-4/5 w-4/12 p-4 rounded-xl flex justify-center place-items-center flex-col text-black">
          <p className="text-lg font-semibold">
            Actualiza los datos del usuario
          </p>
          <div>
            <input
              type="text"
              name="name"
              value={selectedUser.name}
              // onChange={onChangeName}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Nombre"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="lastName"
              value={selectedUser.lastName}
              // onChange={onChangeLastName}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Apellidos"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="email"
              value={selectedUser.email}
              // onChange={onChangeEmail}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Correo electronico"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="description"
              value={selectedUser.description}
              // onChange={onChangeDescription}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Descripcion"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="location"
              value={selectedUser.location}
              // onChange={onChangeLocation}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Ubicacion"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="services"
              value={selectedUser.services}
              // onChange={onChangeServices}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Servicios"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="price"
              value={selectedUser.price}
              // onChange={onChangePrice}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Precio"
              required
            />
          </div>
          <div>
            <input
              type="text"
              name="schedule"
              value={selectedUser.schedule}
              // onChange={onChangeEmail}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Horarios"
              required
            />
          </div>
          <button
            type="addUser"
            className="normal-button"
            onClick={() => onSubmit()}
          >
            Actualizar
          </button>
          <Link to="/customers">
            <button type="cancel" className="normal-button">
              Cancelar
            </button>
          </Link>
        </div>
      </div>
    </>
  );
};

export default EditUser;

</code>```

Body:
I can't make the edit option work, the add option works and the UI is working fine but when i select the option edit it sends me where im going to edit but it doesn't let me write or delete anything.

I can't make the Edit option work, im using a hook called useForm.

import React, { useState } from "react";

export const useForm = (initialState = {}) => {
  const [values, setValues] = useState(initialState);

  const reset = () => {
    setValues(initialState);
  };

  const handleInputChange = (target) => {
    console.log(target.value);
    setValues({
      ...values,
      [target.name]: target.value,
    });
  };

  return {
    values,
    handleInputChange,
    reset,
  };
};

Then i called it in the file where it was suposed to edit but it doesn't let me to write anything.

import React, { useState, useContext, useEffect } from "react";
import { GlobalContext } from "./context/GlobalState";
import { Link, useNavigate, useParams } from "react-router-dom";
import { useForm } from "./context/useForm";

const EditUser = () => {
  const { values, handleInputChange } = useForm({
    name: "",
    lastName: "",
    email: "",
    description: "",
    location: "",
    services: "",
    price: "",
    schedule: "",
  });

  const [selectedUser, setSelectedUser] = useState({
    name: values.name,
    lastName: values.lastName,
    email: values.email,
    description: values.description,
    location: values.location,
    services: values.services,
    price: values.price,
    schedule: values.schedule,
  });

  const { users, editUser } = useContext(GlobalContext);

  const history = useNavigate();

  const { id } = useParams();

  const currentUserId = id;

  useEffect(() => {
    const userId = currentUserId;
    const selectedUser = users.find((user) => user.id === userId);
    setSelectedUser(selectedUser);
  }, [currentUserId, users]);

  const onSubmit = () => {
    editUser(selectedUser);
    history("/customers");
  };

  return (
    <>

            Actualiza los datos del usuario

            <input
              type="text"
              name="name"
              value={selectedUser.name}
              // onChange={onChangeName}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Nombre"
              required
            />

            <input
              type="text"
              name="lastName"
              value={selectedUser.lastName}
              // onChange={onChangeLastName}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Apellidos"
              required
            />

            <input
              type="text"
              name="email"
              value={selectedUser.email}
              // onChange={onChangeEmail}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Correo electronico"
              required
            />

            <input
              type="text"
              name="description"
              value={selectedUser.description}
              // onChange={onChangeDescription}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Descripcion"
              required
            />

            <input
              type="text"
              name="location"
              value={selectedUser.location}
              // onChange={onChangeLocation}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Ubicacion"
              required
            />

            <input
              type="text"
              name="services"
              value={selectedUser.services}
              // onChange={onChangeServices}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Servicios"
              required
            />

            <input
              type="text"
              name="price"
              value={selectedUser.price}
              // onChange={onChangePrice}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Precio"
              required
            />

            <input
              type="text"
              name="schedule"
              value={selectedUser.schedule}
              // onChange={onChangeEmail}
              onChange={({ target }) => handleInputChange(target)}
              className="textfield-outline"
              placeholder="Horarios"
              required
            />

          <button
            type="addUser"
            className="normal-button"
            onClick={() => onSubmit()}
          >
            Actualizar
          </button>
          <Link to="/customers">
            <button type="cancel" className="normal-button">
              Cancelar
            </button>
          </Link>

    </>
  );
};

export default EditUser;


问:
I want Unity's slider value to handle large numbers precisely (it only works in the format of "xxx e+X")
I've been using Unity's slider to handle large numbers, and it accepts them. The problem is that the value stored is in the format "xxx e+X" (for instance, 9.999998e+08),
enter image description here
so, if I wanted to subtract one to this value, or add one to it, it doesn't change the value (for instance, the OnValueChanged callback doesn't get called) as it is only sensitive to larger steps (like, for example, changes over 50-100 units/integers and above.

Is there a way to make the slider work with long integers (plain number format)?

Thank you.

What I tried:

The slider max value is set to 999999799 (ended in 799). Then it translates into  "9.999998e+08". if I convert this float value (9.999998e+08) to "long", I get 999999800, probably because it doesn't take into account small figures and goes by larger steps.

The only way that occurs to me to get the correct "long" is to convert the "slider max value" to string (string stringValue = _mySlider.value.ToString("F0")) and then get the "long" (long longValue= Convert.ToInt64(stringValue)). This way, I get the expected long (999999799).

However, this is not suitable since I cannot convert this long value into the slider value. If I wanted to subtract one from the long value (longValue--; (999999798)) and then set the slider value to the long value:
_mySlider.value = (float) longValue, the value of the slider doesn't change, it keeps being the same: 9.999998e+08. When translating the number, it yields 999999799 instead of 999999798. (Same happens if I did _mySlider.value--; directly)

I need the slider to handle large numbers too.


问:
Simr: Power for model comparison = 0%, test did not return a p-value
I'm trying to use the simr to package to look at the effects of sample size on power. I keep having issues when running the powerSim(), with the output saying that power = 0% and that the test did not return a p-value. I was wondering if anyone had an idea as to why this would be? Here is my code:

```<code>##3 sites
sites_id <- factor(1:3)

##3 tiles types
tile <- c("A", "B","C")

site_full<-rep(sites_id, each=15)
length(site_full)

tile_full <- rep(rep(tile, each=5),3)
length(tile_full)

covars <- data.frame(site=factor(site_full), tile=factor(tile_full))
levels(covars$tile)

fixed <- c(11, -1, 4)

rand <- list(2)
res <- 2

str(covars)

model <- makeLmer(y ~ tile + (1|site),
                  fixef=fixed, VarCorr=rand, sigma=res, data=covars)
model
summary(model)

sim_treat <- powerSim(model, nsim=100, test = fcompare(y~tile))
sim_treat
lastResult()$errors
</code>```

I want to go on to increase the sample size and then crease a power curve plot to look at the effects of sample size on power:

```<code>model_ext <- extend(model, within="tile+site", n=30)
model_ext

p_curve_treat <- powerCurve(model_ext, test=fcompare(y~tile),
                            within="tile+site", breaks=c(5,10,15,20,25,30))
plot(p_curve_treat)
</code>```

Thanks in advance for any help!

Body:
I'm trying to use the simr to package to look at the effects of sample size on power. I keep having issues when running the powerSim(), with the output saying that power = 0% and that the test did not return a p-value. I was wondering if anyone had an idea as to why this would be? Here is my code:

##3 sites
sites_id <- factor(1:3)

##3 tiles types
tile <- c("A", "B","C")

site_full<-rep(sites_id, each=15)
length(site_full)

tile_full <- rep(rep(tile, each=5),3)
length(tile_full)

covars <- data.frame(site=factor(site_full), tile=factor(tile_full))
levels(covars$tile)

fixed <- c(11, -1, 4)

rand <- list(2)
res <- 2

str(covars)

model <- makeLmer(y ~ tile + (1|site),
                  fixef=fixed, VarCorr=rand, sigma=res, data=covars)
model
summary(model)

sim_treat <- powerSim(model, nsim=100, test = fcompare(y~tile))
sim_treat
lastResult()$errors

I want to go on to increase the sample size and then crease a power curve plot to look at the effects of sample size on power:

model_ext <- extend(model, within="tile+site", n=30)
model_ext

p_curve_treat <- powerCurve(model_ext, test=fcompare(y~tile),
                            within="tile+site", breaks=c(5,10,15,20,25,30))
plot(p_curve_treat)

Thanks in advance for any help!


问:
How to figure out xpath for IMPORTXML in Google Sheets
Thank you guys in advance for your attention

I'm trying to use the IMPORTXML function on Google Sheets.

For example:=IMPORTXML("https://www.linkedin.com/in/salesmanagerdigital/, XMLPATH) should return "Senior Enterprise Account Executive, Southern Europe", which is the complete Role.

Firefox Full xPath Finder extension gives me:

/html/body/div[5]/div[3]/div/div/div[2]/div/div/main/section[6]/div[3]/ul/li[1]/div/div[2]/div/div[1]/div/span/span[1]

When I try this in Google Sheets it returns an error: #N/A (Import Content is Empty).

Thanks you so much for your support.


问:
Display a message between a date range in velocity language
I want to display a message between a date range in Velocity language. Like from 1/3/2023 to 23/3/2023. How can I do that.
I tried to put condition but it's not working.

```<code>#set($user = SpermissionChecker.getUser() if (Guser.female)
</code>```

#set($genre = "Madame")

#else

#set($genre = "Monsieur")

#end

#get (fact-Suser.getExpandoBridge ().getAttribute("active_"))

if("$/act"=="RESILIE"}

Suite à la résiliation de votre contrat, l'acces

contenu est limité à 6 mois, nous vous conseillons de sauvegarder vos documer

#set ($timete dateUtil.getCurrentDate ("dd/MM/yyyy", Locale))

#end

#if($timet =="03/12/2022" && $timet =="10/12/2022")

Rapprochement des banques du Groupe Crédit du Nord et portail et votre application mobile Santé évoluent </span

Body:
I want to display a message between a date range in Velocity language. Like from 1/3/2023 to 23/3/2023. How can I do that.
I tried to put condition but it's not working.

#set($user = SpermissionChecker.getUser() if (Guser.female)

#set($genre = "Madame")

#else

#set($genre = "Monsieur")

#end

#get (fact-Suser.getExpandoBridge ().getAttribute("active_"))

if("$/act"=="RESILIE"}

Suite à la résiliation de votre contrat, l'acces

contenu est limité à 6 mois, nous vous conseillons de sauvegarder vos documer

#set ($timete dateUtil.getCurrentDate ("dd/MM/yyyy", Locale))

#end

#if($timet =="03/12/2022" && $timet =="10/12/2022")

Rapprochement des banques du Groupe Crédit du Nord et portail et votre application mobile Santé évoluent </span


Title: Pulp: Minimization; Sum product within lpSUM

Body:
I have 20 components and 5 models that I am working with. Using the inventory of component in stock I am trying to identify what additional inventory to order and which models to build in order to minimise inventory.

#Importing libraries
import pulp
from pulp import *

#Data
row_number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

component = {1: "C 1", 2: "C 2", 3: "C 3", 4: "C 4", 5: "C 5", 6: "C 6", 7: "C 7", 8: "C 8", 9: "C 9", 10: "C 10", 11: "C 11", 12: "C 12", 13: "C 13", 14: "C 14", 15: "C 15", 16: "C 16", 17: "C 17", 18: "C 18", 19: "C 19", 20: "C 20"}

stock = {1: 250, 2: 20, 3: 0, 4: 300, 5: 750, 6: 400, 7: 100, 8: 150, 9: 200, 10: 250, 11: 500, 12: 1000, 13: 10, 14: 300, 15: 250, 16: 100, 17: 150, 18: 200, 19: 400, 20: 300}

std_cost = {1: 10, 2: 5, 3: 100, 4: 10, 5: 5, 6: 100, 7: 100, 8: 5, 9: 100, 10: 10, 11: 5, 12: 10, 13: 5, 14: 100, 15: 10, 16: 5, 17: 100, 18: 10, 19: 5, 20: 100}

#Utilization of 20 components for Model 1
Mod1 = {1: 0, 2: 0, 3: 1, 4: 0, 5: 0, 6: 0, 7: 2, 8: 0, 9: 0, 10: 0, 11: 1, 12: 0, 13: 0, 14: 3, 15: 1, 16: 0, 17: 0, 18: 0, 19: 2, 20: 0}

#Utilization of 20 components for Model 2
Mod2 = {1: 0, 2: 1, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 1, 17: 0, 18: 2, 19: 1, 20: 2}

#Utilization of 20 components for Model 3
Mod3 = {1: 3, 2: 2, 3: 1, 4: 4, 5: 2, 6: 3, 7: 2, 8: 1, 9: 2, 10: 2, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, 18: 0, 19: 0, 20: 0}

#Utilization of 20 components for Model 4
Mod4 = {1: 2, 2: 0, 3: 0, 4: 3, 5: 3, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 3, 12: 4, 13: 1, 14: 0, 15: 0, 16: 0, 17: 0, 18: 1, 19: 0, 20: 0}

#Utilization of 20 components for Model 5
Mod5 = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 1, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 2, 13: 0, 14: 0, 15: 5, 16: 1, 17: 1, 18: 0, 19: 0, 20: 1}

max_range = 6 #(as we have 5 models)

# Problem- Minimize
prob = LpProblem("Inventory",LpMinimize)

# Decision Varibales
#Dictionary for quantities of model to be built
for i in range(1, max_range):
    exec(f'Mod{i}_vars = LpVariable("Mod{i}",0,cat="Integer")')

#dictionary of additional components to order
additional_vars = LpVariable.dicts("Additional",row_number,0,cat='Integer')

# Objective function
prob += lpSum([(stock[i] + additional_vars[i] - (Mod1[i] * Mod1_vars) - (Mod2[i] * Mod2_vars) - (Mod3[i] * Mod3_vars) - (Mod4[i] * Mod4_vars) - (Mod5[i] * Mod5_vars)) * std_cost[i] for i in row_number])

# Constraints
#Inventory cannot be negative
for i in row_number:
     prob += sum([stock[i] + additional_vars[i] - (Mod1[i] * Mod1_vars) - (Mod2[i] * Mod2_vars) - (Mod3[i] * Mod3_vars) - (Mod4[i] * Mod4_vars) - (Mod5[i] * Mod5_vars)]) >= 0

#Additional cost cannot exceed budget for additional inventory
prob += lpSum([std_cost[i] * additional_vars[i] for i in row_number]) <= 10000

prob.solve()
print("Status:", LpStatus[prob.status])
value(prob.objective)

Output: 71810

I am getting the output with the above code. However, I am working with 5 models at the moment which will increase to more when I work with complete data set.

I tried to change objective function to:

prob += lpSum([(stock[i] + additional_vars[i] - exec(f'(sum([Mod{f}[i] * Mod{f}_vars]) for f in range(1,6))')) * std_cost[i] for i in row_number]), "Objective Function"

NameError: name 'f' is not defined

How can I make my objective function dynamic?


问:
When adding DataGridPremium to private library, it is giving undefined prototype error in inherits browser in FrontEnd (ctor)
When applying DataGridPremium in Frontend, it is working fine but using yalc to consume it, ii is giving error but DataGridPro doesnt have error.
I am using rollup to create small bundle `

```<code>"build": "rollup -c"
</code>```

`
and the environment

Error

I want to create a component library and build it using rollup. After that consuming any FE as a library

Body:
When applying DataGridPremium in Frontend, it is working fine but using yalc to consume it, ii is giving error but DataGridPro doesnt have error.
I am using rollup to create small bundle `

"build": "rollup -c"

`
and the environment

Error

I want to create a component library and build it using rollup. After that consuming any FE as a library


问:
Remove "Deploying to <environment>" text GitHub Actions

As I'm using the environment feature only for handling .env files in different environments and I'm not deploying, I'd like to remove the "Deploying to production" text as it's misleading. Is there a way to remove the progress bar and the text from the workflow UI?


问:
using pyautogui in python with a picture that is in a different directory
I am trying to grab a picture from a different directory than the actual python script and use pyautogui click function to click on anything that looks like it.

My project directory looks like this:
-Project
main.py
src(folder)
-pic.png

I tried using this code

```<code>import pyautogui as pe
pe.click(folder/pic.png)
</code>```

Body:
I am trying to grab a picture from a different directory than the actual python script and use pyautogui click function to click on anything that looks like it.

My project directory looks like this:
-Project
main.py
src(folder)
-pic.png

I tried using this code

import pyautogui as pe
pe.click(folder/pic.png)


问:
Wordpress - Pass Parameter to other internal pages
We want to generate a QR for a website homepage with a specific parameter (?store_ref=antonio) since that will change and show specific phone numbers in this page.

But we need that after coming from this URL, any internal link clicked add this parameter after so the phone number on the subsequently pages change as well.

Thank you so much in advance!

Best,
Hansel


问:
Why does vb series POINTS.color set wrong point color?
I'm drawing points horizontally across the graph.

I want some of the points to be different colors.

I get the x-axis index returned by......>  index = .ADDXY( x_value, y_value )

Then, I set the point's color..........>   .POINTS( index ).color = Color.FromName("Green")

But the color is yellow instead of green.

```<code>MONEY_Chart.Series("profitability").ChartType = 1' FastPoint chart type
MONEY_Chart.Series( "profitability").MarkerSize =             8
MONEY_Chart.Series( "profitability").POINTS.CLEAR

' event_timestamp_DATETIME = first
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, 22 )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.FromName("Green")

' event_timestamp_DATETIME = next
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, 22 )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.FromName("Green")

' event_timestamp_DATETIME = next
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, 22 )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.FromName("Green")
'   . . .  for each point
</code>```

Body:
I'm drawing points horizontally across the graph.

I want some of the points to be different colors.

I get the x-axis index returned by......>  index = .ADDXY( x_value, y_value )

Then, I set the point's color..........>   .POINTS( index ).color = Color.FromName("Green")

But the color is yellow instead of green.

MONEY_Chart.Series("profitability").ChartType = 1' FastPoint chart type
MONEY_Chart.Series( "profitability").MarkerSize =             8
MONEY_Chart.Series( "profitability").POINTS.CLEAR

' event_timestamp_DATETIME = first
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, 22 )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.FromName("Green")

' event_timestamp_DATETIME = next
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, 22 )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.FromName("Green")

' event_timestamp_DATETIME = next
dim point_index = MONEY_Chart.Series( "profitability").POINTS.ADDXY( event_timestamp_DATETIME, 22 )
MONEY_Chart.Series( "profitability").POINTS( point_index ).color = Color.FromName("Green")
'   . . .  for each point


问:
Undefined type Aws\S3\S3Client how to fix it. Me use PHP
i tried a system s3 object storage from idrive and i did composer install for composer require aws/aws-sdk-php.

but it shows error like that in my code window.

enter image description here

```<code><?php

require "../vendor/autoload.php";

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Create an S3 client for IDrive e2
$profile_credentials = [
    "profile" => "default",
    "endpoint" => "l4g4.ch11.idrivee2-2.com",
    "region" => "Chicago",
    "version" => "latest",
    "use_path_style_endpoint" => true,
];
$s3 = S3Client::factory($profile_credentials);

// Get list of buckets
try {
    $buckets = $s3->listBuckets();
    // print bucket names
    foreach ($buckets["Buckets"] as $bucket) {
        echo "{$bucket["Name"]}\n";
    }
} catch (AwsException $e) {
    echo "Error: {$e->getMessage()}" . PHP_EOL;
}
</code>```

I just want an example for this s3 object strong to work I have also tried things on the amazon aws documentation but haven't found any results and the error keeps coming

Body:
i tried a system s3 object storage from idrive and i did composer install for composer require aws/aws-sdk-php.

but it shows error like that in my code window.

enter image description here

<?php

require "../vendor/autoload.php";

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Create an S3 client for IDrive e2
$profile_credentials = [
    "profile" => "default",
    "endpoint" => "l4g4.ch11.idrivee2-2.com",
    "region" => "Chicago",
    "version" => "latest",
    "use_path_style_endpoint" => true,
];
$s3 = S3Client::factory($profile_credentials);

// Get list of buckets
try {
    $buckets = $s3->listBuckets();
    // print bucket names
    foreach ($buckets["Buckets"] as $bucket) {
        echo "{$bucket["Name"]}\n";
    }
} catch (AwsException $e) {
    echo "Error: {$e->getMessage()}" . PHP_EOL;
}

I just want an example for this s3 object strong to work I have also tried things on the amazon aws documentation but haven't found any results and the error keeps coming


问:
how can i enable login with email and phone number in Django rest framework?
I want to enable login with an email and phone no in the Django project. Like users can put their email or phone number in the input field as their wish.</p>


问:
How to fetch a process variable of type File in an external JS worker?
The case:

I have a process deployed on Camunda engine (running on localhost), which is triggered by an API call.

In the API call, a process variable of type File is sent, as shown below:

```<code>
"file" : {
                                                        "value": base64str,
                                                            "type":"File",
                                                                    "valueInfo":{
                                                                        "filename":nameOfFile, //this variable stores the name of the file that the user uploaded in the form on the website, e.g., *myAttachment.pdf
                *                                                       "mimetype":typeOfFile, //this variable stores the mimetype of the file that the user uploaded in the form on the website, e.g., *application/pdf*
                                                                        "encoding":"UTF-8"
                                                                    }
                                                        };
</code>```

Once the process is triggered, a process variable "file" of type "File" is created.

Then, I have an external worker written in javascript. In this worker, I want to fetch the base64 value of the process variable "file" of type "File".

Then, once I have the base64 value of the process variable "file", I will have a REST API call to a third system to pass the attachment there.

In order to complete this logic, I need somehow to complete the step 4. However, I can't get the base64 value of the process variable file. How could I solve this?

I have tried the following, but it does not work.

```<code>var file=task.variables.get("file");
var content=file.content;
</code>```

Body:
The case:

I have a process deployed on Camunda engine (running on localhost), which is triggered by an API call.

In the API call, a process variable of type File is sent, as shown below:

"file" : {
                                                        "value": base64str,
                                                            "type":"File",
                                                                    "valueInfo":{
                                                                        "filename":nameOfFile, //this variable stores the name of the file that the user uploaded in the form on the website, e.g., *myAttachment.pdf
                *                                                       "mimetype":typeOfFile, //this variable stores the mimetype of the file that the user uploaded in the form on the website, e.g., *application/pdf*
                                                                        "encoding":"UTF-8"
                                                                    }
                                                        };

Once the process is triggered, a process variable "file" of type "File" is created.

Then, I have an external worker written in javascript. In this worker, I want to fetch the base64 value of the process variable "file" of type "File".

Then, once I have the base64 value of the process variable "file", I will have a REST API call to a third system to pass the attachment there.

In order to complete this logic, I need somehow to complete the step 4. However, I can't get the base64 value of the process variable file. How could I solve this?

I have tried the following, but it does not work.

var file=task.variables.get("file");
var content=file.content;


问:
How to download component as JPEG/PNG without using html2canvas dependency
I want solution on how to download a component as JPEG/PNG without using html2canvas dependency, any javascript library available for that. Please help me in this.

I have tried with all react dependencies related to that functionality but every dependency is related to html2canvas, but I need to try this functionality without using react dependency. I only want Javascript library which gives me a solution.


问:
How to clear "memory cache" and "disk cache" from chrome?
I'm building a NextJS application, which uses SSR. I'm soon going to host this website online, but I need to check how much bandwidth is used, by first-time users, when they load our application. I try resorting to the chrome developers tool for that but it seems that even after clearing browsing data, cache, temporary files, prefetch, and restarting the PC it does not removes the files at any cost.


问:
How to make images the same height and keep quality using bootstrap, MDBootstrap?
I am new to coding! I am working on a simple image gallery using both bootstrap and MDBootstrap. My goal is to make an image hover overlay with text gallery in a mosaic style. I have three images side by side.This is what I have so far. I have everything working so far, but my last issue is how to resize the middle image to match the height of the outside images? without losing quality, and still keeping my image overlays/text?

I don't mind resizing the width or making the image smaller, but I want the height of all of the images in the row to line up evenly.

Ive tried addng a container div around the row and adjusting the height. As well, I tried adjusting the height of the row itself.

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.css" rel="stylesheet" />

  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="gridgallerycss.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Cedarville+Cursive&family=Cutive+Mono&display=swap"
    rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous">
  </script>

<style>
.row {
  display: flex;
  align-items: center;
  justify-content: center;
}

.mid-pic{
  margin-right: -1rem;
  margin-left: -1rem;
}

</style>

</head>

<body>

  <section class="border p-4 text-center mb-4 " style="border-radius: 0.5rem;">

    <!-- Picture Row 1 -->

    <div class="row">

      <div class="col-lg-3 col-md-12 mb-4">
        <div class="bg-image hover-overlay">
          <img src="Emma_Allerd_Images/emmapic2.jpg" class="w-100">
          <div class="mask" style="background-color: rgba(0, 0, 0, 0.6)">
            <div class="d-flex justify-content-center align-items-center h-100">
              <p class="text-white mb-0">Championnet</p>
            </div>
          </div>
        </div>
      </div>

      <div class="col-lg-3 col-md-12 mb-4 mid-pic">
        <div class="bg-image hover-overlay">
          <img src="Emma_Allerd_Images/emmapic5.jpg" class="w-100">
          <div class="mask" style="background-color: rgba(18, 102, 241, 0.5)">
            <div class="d-flex justify-content-center align-items-center h-100">
              <p class="text-white mb-0">Image 2</p>
            </div>
          </div>
        </div>
      </div>

      <div class="col-lg-3 col-md-12 mb-4">
        <div class="bg-image hover-overlay">
          <img src="Emma_Allerd_Images/emmapic4.jpg" class="w-100">
          <div class="mask" style="background-color: rgba(18, 102, 241, 0.5)">
            <div class="d-flex justify-content-center align-items-center h-100">
              <p class="text-white mb-0">Image 3</p>
            </div>
          </div>
        </div>
      </div>
    </div>

  </section>

</body>

</html>
</code>```

Body:
I am new to coding! I am working on a simple image gallery using both bootstrap and MDBootstrap. My goal is to make an image hover overlay with text gallery in a mosaic style. I have three images side by side.This is what I have so far. I have everything working so far, but my last issue is how to resize the middle image to match the height of the outside images? without losing quality, and still keeping my image overlays/text?

I don't mind resizing the width or making the image smaller, but I want the height of all of the images in the row to line up evenly.

Ive tried addng a container div around the row and adjusting the height. As well, I tried adjusting the height of the row itself.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.css" rel="stylesheet" />

  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="gridgallerycss.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Cedarville+Cursive&family=Cutive+Mono&display=swap"
    rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">

Championnet

Image 2

Image 3


问:
Why is the spinner.setOnItemSelectedListener() not getting executed?
UPDATE:
I have found a work around that isn't necessarily the solution, but has solved my problem. To my interpretation, I think the use of online database causes a little delay or something that when the spinner.setOnItemSelectedListener() is set the list passed to the adapter is empty. So to counter that, I set the listener in the OnDataChange() method of firebase (which was fetching the data from database and creating the list). After that it worked fine.

Original Question

I have a simple spinner inside a layout in xml, and I have a query that creates a String type array of the items I want to show in the spinner. The list is being created and the spinner shows the items. But when I call the setOnItemSelectedListener() on it, it is not getting executed.

This is the xml:

```<code>           <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    >

                    <Spinner
                        android:id="@+id/spinner_category_name_add_expense"
                        android:layout_width="wrap_content"
                        android:layout_height="24dp"
                        android:layout_alignParentEnd="true" />
                </RelativeLayout>
</code>```

There are more widgets around it, I don't know if that matters.

This is the java file:

```<code>public class AddExpense extends AppCompatActivity {

    Spinner spinner_category_name_add_expense;
    SharedPreferences sharedPreferences;
    String userKey, userName, selected_cat;
    DatabaseReference dbref;
    ArrayList<String> categoryModelArrayList;
    ArrayAdapter<String> spinnerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_expense);
        fetchSharedPreferences();
        categoryModelArrayList = new ArrayList<String>();
        spinner_category_name_add_expense = findViewById(R.id.spinner_category_name_add_expense);
        createCategoryList();
        addCategoriesToSpinner();
        spinner_category_name_add_expense.setOnItemSelectedListener(new
            AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(AddExpense.this, "Selected", Toast.LENGTH_SHORT).show();
                // not executing this
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                Toast.makeText(AddExpense.this, "Not Selected", Toast.LENGTH_SHORT).show();
                // nor this
            }
        });

}

    }

    private void fetchSharedPreferences() {
        sharedPreferences = this.getSharedPreferences("shared_prefs", Context.MODE_PRIVATE);
        userKey = sharedPreferences.getString("user_key", null);

    }

// gets the data from firebase database, works as the ArrayList is populated
    public void createCategoryList() {
        String currentUserCategoriesPath = "AssignmentUsers/" + userKey + "/userCategories";
        dbref = FirebaseDatabase.getInstance().getReference(currentUserCategoriesPath);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    String categoryModel = snapshot.getKey();
                    categoryModelArrayList.add(categoryModel);
                    Log.d("firebase", String.valueOf(categoryModelArrayList.get(i)));
                    i++;
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d("firebase", "Error");
            }
        });

    }

    public void addCategoriesToSpinner() {
        spinnerAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                categoryModelArrayList
        );

        spinner_category_name_add_expense.setAdapter(spinnerAdapter);
        spinnerAdapter.notifyDataSetChanged();

    }
}

</code>```

Body:
UPDATE:
I have found a work around that isn't necessarily the solution, but has solved my problem. To my interpretation, I think the use of online database causes a little delay or something that when the spinner.setOnItemSelectedListener() is set the list passed to the adapter is empty. So to counter that, I set the listener in the OnDataChange() method of firebase (which was fetching the data from database and creating the list). After that it worked fine.

Original Question

I have a simple spinner inside a layout in xml, and I have a query that creates a String type array of the items I want to show in the spinner. The list is being created and the spinner shows the items. But when I call the setOnItemSelectedListener() on it, it is not getting executed.

This is the xml:

           <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    >

                    <Spinner
                        android:id="@+id/spinner_category_name_add_expense"
                        android:layout_width="wrap_content"
                        android:layout_height="24dp"
                        android:layout_alignParentEnd="true" />
                </RelativeLayout>

There are more widgets around it, I don't know if that matters.

This is the java file:

public class AddExpense extends AppCompatActivity {

    Spinner spinner_category_name_add_expense;
    SharedPreferences sharedPreferences;
    String userKey, userName, selected_cat;
    DatabaseReference dbref;
    ArrayList<String> categoryModelArrayList;
    ArrayAdapter<String> spinnerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_expense);
        fetchSharedPreferences();
        categoryModelArrayList = new ArrayList<String>();
        spinner_category_name_add_expense = findViewById(R.id.spinner_category_name_add_expense);
        createCategoryList();
        addCategoriesToSpinner();
        spinner_category_name_add_expense.setOnItemSelectedListener(new
            AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(AddExpense.this, "Selected", Toast.LENGTH_SHORT).show();
                // not executing this
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                Toast.makeText(AddExpense.this, "Not Selected", Toast.LENGTH_SHORT).show();
                // nor this
            }
        });

}

    }

    private void fetchSharedPreferences() {
        sharedPreferences = this.getSharedPreferences("shared_prefs", Context.MODE_PRIVATE);
        userKey = sharedPreferences.getString("user_key", null);

    }

// gets the data from firebase database, works as the ArrayList is populated
    public void createCategoryList() {
        String currentUserCategoriesPath = "AssignmentUsers/" + userKey + "/userCategories";
        dbref = FirebaseDatabase.getInstance().getReference(currentUserCategoriesPath);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    String categoryModel = snapshot.getKey();
                    categoryModelArrayList.add(categoryModel);
                    Log.d("firebase", String.valueOf(categoryModelArrayList.get(i)));
                    i++;
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d("firebase", "Error");
            }
        });

    }

    public void addCategoriesToSpinner() {
        spinnerAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                categoryModelArrayList
        );

        spinner_category_name_add_expense.setAdapter(spinnerAdapter);
        spinnerAdapter.notifyDataSetChanged();

    }
}


问:
Trigger all bootstrap collapses with jquery at once
Hello I am using bootstrap-5 collapses. I have multiple collapses an I need to trigger them all using jquery(not bootstrap button).Here are my collapses.Here is my code</p>
```<code><p>
  <a class="btn btn-primary" data-bs-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>
</p>
<div class="row">
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample1">
      <div class="card card-body">
        Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
      </div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample2">
      <div class="card card-body">
        Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
      </div>
    </div>
  </div>
</div>
</code>```

Body:
Hello I am using bootstrap-5 collapses. I have multiple collapses an I need to trigger them all using jquery(not bootstrap button).Here are my collapses.Here is my code

  Toggle first element
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>

        Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.

        Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.


问:
Binomial GLM function for specific values vs all other values
I am doing a study on specific needs for kinship caregivers. I want to look at county vs needs to see if certain counties have more significant needs than other counties. This will hopefully be used to allocate funding or policies. I am looking for need (which has various columns for each need) and county (one variable with counties 1-39,99). Some counties only have a few participants, so I only want to compare counties with >50 respondents (6,17,27, 31, 32). So, county "6" vs other counties. I was using a similar function for my other calculations that were binomial 1,0 options so I want to figure out what to use for this comparison.

```<code>model1 <-glm(need_1 ~ factor(county), family="binomial", data=Clean.Data)
coef(summary(model1))
exp(coef(model1))
exp(confint.default(model1))
</code>```

I have also tried

```<code>model1 <-glm(need_1 ~ factor(county==6), family="binomial", data=Clean.Data)
coef(summary(model1))
exp(coef(model1))
exp(confint.default(model1))
</code>```

I really want to use a binomial of county choosen vs other. I would like to make the comparisons between the counties listed above and not other smaller counties.

Best,
Adrienne

```<code>model1 <-glm(need_1 ~ factor(county), family="binomial", data=Clean.Data)
coef(summary(model1))
exp(coef(model1))
exp(confint.default(model1))
</code>```

My exp of my coefficients are 0 to Inf so I am not expecting that.

I also tried to create a new binomial variable using:

Clean.Data$Clark <- ifelse(Clean.Data$live == 6,1,0) but this is not quite what I want because then it compares to all counties rather than the ones that have at least 50.

Body:
I am doing a study on specific needs for kinship caregivers. I want to look at county vs needs to see if certain counties have more significant needs than other counties. This will hopefully be used to allocate funding or policies. I am looking for need (which has various columns for each need) and county (one variable with counties 1-39,99). Some counties only have a few participants, so I only want to compare counties with >50 respondents (6,17,27, 31, 32). So, county "6" vs other counties. I was using a similar function for my other calculations that were binomial 1,0 options so I want to figure out what to use for this comparison.

model1 <-glm(need_1 ~ factor(county), family="binomial", data=Clean.Data)
coef(summary(model1))
exp(coef(model1))
exp(confint.default(model1))

I have also tried

model1 <-glm(need_1 ~ factor(county==6), family="binomial", data=Clean.Data)
coef(summary(model1))
exp(coef(model1))
exp(confint.default(model1))

I really want to use a binomial of county choosen vs other. I would like to make the comparisons between the counties listed above and not other smaller counties.

Best,
Adrienne

model1 <-glm(need_1 ~ factor(county), family="binomial", data=Clean.Data)
coef(summary(model1))
exp(coef(model1))
exp(confint.default(model1))

My exp of my coefficients are 0 to Inf so I am not expecting that.

I also tried to create a new binomial variable using:

Clean.Data$Clark <- ifelse(Clean.Data$live == 6,1,0) but this is not quite what I want because then it compares to all counties rather than the ones that have at least 50.


问:
How do players/browsers handle DISCONTINUITY tags in HLS?
How do browsers and video players handle DISCONTINUITY tags in HLS? Do browsers/players do reset or flush buffers or timecodes when they encounter this tag? How does this tag affect video and audio streams in HLS segments?</p>


问:
Query Spring Entity using join on list propery
I have an entity (say Person) and the person contains list of address.

```<code>class Person {
  val addresses : List<Address>
  .
  .
}

class Address {
   val street : String
   val city: String
   val state: String
   .
   .
}
</code>```

Now My requirement is, I want to pass a list of city and find all people living in those city. Can someone please help me to find if there's a way to write Spring data JPA query (like findByAddress_City) for this requirement?

Body:
I have an entity (say Person) and the person contains list of address.

class Person {
  val addresses : List<Address>
  .
  .
}

class Address {
   val street : String
   val city: String
   val state: String
   .
   .
}

Now My requirement is, I want to pass a list of city and find all people living in those city. Can someone please help me to find if there's a way to write Spring data JPA query (like findByAddress_City) for this requirement?


问:
What does y_test[0] means exactly?
why y_test[0] works fine here

```<code>from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(X_train, y_train)
predictions = lr.predict(X_test)

print("Actual value of the house:- ", y_test[0])
print("Model Predicted Value:- ", predictions[0])
</code>```

but y_test[1] can't.

here shape of y_test shape is (102,)

so by the array logic it should give me value upto 102.

y_test[0]
y_test[1]
.
.
.
.
.
y_test[102]

but only y_test[0] works.

I thought y_test[1] should work the same as y_test[0] but something is wrong with that idk what.
what does y_test[0] means exactly?

Title: What does y_test[0] means exactly?

Body:
why y_test[0] works fine here

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(X_train, y_train)
predictions = lr.predict(X_test)

print("Actual value of the house:- ", y_test[0])
print("Model Predicted Value:- ", predictions[0])

but y_test[1] can't.

here shape of y_test shape is (102,)

so by the array logic it should give me value upto 102.

y_test[0]
y_test[1]
.
.
.
.
.
y_test[102]

but only y_test[0] works.

I thought y_test[1] should work the same as y_test[0] but something is wrong with that idk what.
what does y_test[0] means exactly?


问:
Javascript (Mui) - fill capsule shape dynamically
I have a capsule shape that needs to fill with color dynamically. I have an issue where if the capsule is over 95% full, the color overlay does not align with my base capsule shape.

To achieve this shape, I made a div with a border-radius of 20px, and then added another with with an absolute position over it to give the effect of the capsule being filled.

I am just unsure how to make the top bits align.

Picture 1

Picture 2

Here is my code:

```<code>  const percentageFull = current / capacity;
  const materialTubeHeight = 298;
  const materialOverlayHeight = materialTubeHeight * percentageFull;
  const greenOverlay = percentageFull >= 0.5;
  const yellowOverlay = percentageFull < 0.5 && percentageFull >= 0.05;
  const redOverlay = percentageFull < 0.05;
  const baseWidth = 51;
</code>```
```<code>      <Box
        sx={{ display: "flex", justifyContent: "center", position: "relative" }}
      >
        <Box
          className={styles.materialOutline}
          sx={{ height: `${materialTubeHeight}px` }}
        />
        {!disabled && (
          <Box
            className={clsx(
              styles.materialOverlay,
              greenOverlay
                ? styles.materialOverlayGreen
                : yellowOverlay
                ? styles.materialOverlayYellow
                : styles.materialOverlayRed
            )}
            sx={{
              height: `${materialOverlayHeight}px`,
              width: `51px`,
            }}
          />
        )}
        </Box>
      </Box>
</code>```

And my CSS

```<code>.materialOutline {
  width: 51px;
  border-radius: 20px;
  box-shadow: 0px 8px 10px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 0;
  padding-top: 30px;
}

.materialOutline:before {
  content: "";
  position: absolute;
  z-index: -1;
  inset: 0;
  padding: 1px;
  border-radius: 20px;
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  background: linear-gradient(to bottom, #d9d9d9, #d9d9d900);
}

.materialOverlay {
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
  box-shadow: 0px 8px 10px rgba(0, 0, 0, 0.05);
  position: absolute;
  z-index: 0;
  padding-top: 30px;
  bottom: 0;
}

.materialOverlay:before {
  content: "";
  position: absolute;
  z-index: -1;
  inset: 0;
  padding: 1px;
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
}

.materialOverlayGreen {
  background-color: #f3faea;
}

.materialOverlayGreen:before {
  background: linear-gradient(to bottom, #7aca0d, #d9d9d900);
}

.materialOverlayYellow {
  background-color: #faf8e8;
}

.materialOverlayYellow:before {
  background: linear-gradient(to bottom, #e9c441, #d9d9d900);
}

.materialOverlayRed {
  background-color: #f9e1e1;
}

.materialOverlayRed:before {
  background: linear-gradient(to bottom, #db3737, #d9d9d900);
}
</code>```

Body:
I have a capsule shape that needs to fill with color dynamically. I have an issue where if the capsule is over 95% full, the color overlay does not align with my base capsule shape.

To achieve this shape, I made a div with a border-radius of 20px, and then added another with with an absolute position over it to give the effect of the capsule being filled.

I am just unsure how to make the top bits align.

Picture 1

Picture 2

Here is my code:

  const percentageFull = current / capacity;
  const materialTubeHeight = 298;
  const materialOverlayHeight = materialTubeHeight * percentageFull;
  const greenOverlay = percentageFull >= 0.5;
  const yellowOverlay = percentageFull < 0.5 && percentageFull >= 0.05;
  const redOverlay = percentageFull < 0.05;
  const baseWidth = 51;

      <Box
        sx={{ display: "flex", justifyContent: "center", position: "relative" }}
      >
        <Box
          className={styles.materialOutline}
          sx={{ height: `${materialTubeHeight}px` }}
        />
        {!disabled && (
          <Box
            className={clsx(
              styles.materialOverlay,
              greenOverlay
                ? styles.materialOverlayGreen
                : yellowOverlay
                ? styles.materialOverlayYellow
                : styles.materialOverlayRed
            )}
            sx={{
              height: `${materialOverlayHeight}px`,
              width: `51px`,
            }}
          />
        )}
        </Box>
      </Box>

And my CSS

.materialOutline {
  width: 51px;
  border-radius: 20px;
  box-shadow: 0px 8px 10px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 0;
  padding-top: 30px;
}

.materialOutline:before {
  content: "";
  position: absolute;
  z-index: -1;
  inset: 0;
  padding: 1px;
  border-radius: 20px;
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  background: linear-gradient(to bottom, #d9d9d9, #d9d9d900);
}

.materialOverlay {
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
  box-shadow: 0px 8px 10px rgba(0, 0, 0, 0.05);
  position: absolute;
  z-index: 0;
  padding-top: 30px;
  bottom: 0;
}

.materialOverlay:before {
  content: "";
  position: absolute;
  z-index: -1;
  inset: 0;
  padding: 1px;
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
}

.materialOverlayGreen {
  background-color: #f3faea;
}

.materialOverlayGreen:before {
  background: linear-gradient(to bottom, #7aca0d, #d9d9d900);
}

.materialOverlayYellow {
  background-color: #faf8e8;
}

.materialOverlayYellow:before {
  background: linear-gradient(to bottom, #e9c441, #d9d9d900);
}

.materialOverlayRed {
  background-color: #f9e1e1;
}

.materialOverlayRed:before {
  background: linear-gradient(to bottom, #db3737, #d9d9d900);
}


问:
Problem when extracting data from a database. Node.js login
I work with a mySQL DB, and I want to check the user credits in a database ;

```<code>function checkInfo(login, password) {
  var idDB;
  var passDB;
  db.query(
    `SELECT * FROM users WHERE login = '${login}' AND password = '${password}'`,
    (err, rep) => {
      values = JSON.parse(JSON.stringify(rep));
      idDB = values[0].login;
      passDB = values[0].password;
      console.log(
        "Login login entered by the user: " + login + " Login DB : " + idDB,
        "\nPassword entered by the user :" + password,
        "Password DB " + passDB
      );
    }
  );
  if (idDB == login && passDB == password) return 1;
  else return 0;
}

console.log(checkInfo("root", "root"))
</code>```

And this is my output :

```<code>0
URL: http://localhost:8080/login
Login login entered by the user: root Login DB : root
Password entered by the user :root Password DB root
</code>```

After some debugging, I found that I could extract the data from the database, but yet when running the program the data does not seem accurate.
And of course my database contain a table user with two columns "login" and "password", and I have an account with credits "root" and "root"

I want to know how can I check if the user inputs are the same that the data stored into the database. I mean

Body:
I work with a mySQL DB, and I want to check the user credits in a database ;

function checkInfo(login, password) {
  var idDB;
  var passDB;
  db.query(
    `SELECT * FROM users WHERE login = '${login}' AND password = '${password}'`,
    (err, rep) => {
      values = JSON.parse(JSON.stringify(rep));
      idDB = values[0].login;
      passDB = values[0].password;
      console.log(
        "Login login entered by the user: " + login + " Login DB : " + idDB,
        "\nPassword entered by the user :" + password,
        "Password DB " + passDB
      );
    }
  );
  if (idDB == login && passDB == password) return 1;
  else return 0;
}

console.log(checkInfo("root", "root"))

And this is my output :

0
URL: http://localhost:8080/login
Login login entered by the user: root Login DB : root
Password entered by the user :root Password DB root

After some debugging, I found that I could extract the data from the database, but yet when running the program the data does not seem accurate.
And of course my database contain a table user with two columns "login" and "password", and I have an account with credits "root" and "root"

I want to know how can I check if the user inputs are the same that the data stored into the database. I mean


Title: Unable to decrypt XOR

Body:
I have a xored encrypted string "\97\192\192\152\193\196\197\152\193\192\152\193\192\67\192\152\193\197\152\194\200\200\197\152\193\193\152\193\193\67\192\152\197\193\198\196\196\201\152\195\193\201\201\197\152\193\192\152\193\194\152\193\193\152\200\193\198\199\201\195\198\194\200\152\195\193\194\198\197\152\193\192\152\193\193\152\193\192\152\199\200\195\200\200\198\195\200\152\195\193\200\196\152\193\194\7\152\193\197\176\178\169\174\180\7\152\193\194\245\249\152\193\192" that is encrypted with the key 192, and I'm unable to decrypt it, completely.

I have tried doing this

const BitwiseXOR = function(value, key) {
      return value ^ key;
};
const Decrypt = function(string, key) {
      let out = "";
      for (let Idx = 0; Idx < string.length; Idx++) out += String.fromCharCode(BitwiseXOR(string.charCodeAt(Idx), key))
      return out;
};

const XORKey =  192;
const XORString = "\97\192\192\152\193\196\197\152\193\192\152\193\192\67\192\152\193\197\152\194\200\200\197\152\193\193\152\193\193\67\192\152\197\193\198\196\196\201\152\195\193\201\201\197\152\193\192\152\193\194\152\193\193\152\200\193\198\199\201\195\198\194\200\152\195\193\194\198\197\152\193\192\152\193\193\152\193\192\152\199\200\195\200\200\198\195\200\152\195\193\200\196\152\193\194\7\152\193\197\176\178\169\174\180\7\152\193\194\245\249\152\193\192";

console.log(Decrypt(XORString, XORKey))

This has given me lots of wrong outputs and I'm unable to find the way around this, thanks in advice.


问:
using Subject in Angular
I am trying to use Subject to display the name of the connected person in the menu component.
But nothing happens when I call the next() function. I can see the log of de call.
How can i investegate ?

in the sidebar component :

```<code>ngOnInit() {
    console.log("sidebar.component.ngOnInit()");
    this.sidebarnavItems = ROUTES.filter((sidebarnavItem) => sidebarnavItem);
    this.authService.userSubject$.subscribe((name) => {
      alert(`name ${name}`);
      this.username = name;
    });
  }
</code>```

and in the service i create the subject and i have a function that call the next function.

```<code>export class AuthService {
  user: User = new User();
  private _userSubjectSource = new Subject<string>();
  userSubject$ = this._userSubjectSource.asObservable();

  constructor(private http: HttpClient) {}

  sendUser() {
    console.log("_userSubjectSource.next()", this.user.name);
    this._userSubjectSource.next(this.user.name);
  }

</code>```

I copied a tutorial that I also tested and it works very well and yet I can't get my project to work.

Title: using Subject in Angular

Body:
I am trying to use Subject to display the name of the connected person in the menu component.
But nothing happens when I call the next() function. I can see the log of de call.
How can i investegate ?

in the sidebar component :

ngOnInit() {
    console.log("sidebar.component.ngOnInit()");
    this.sidebarnavItems = ROUTES.filter((sidebarnavItem) => sidebarnavItem);
    this.authService.userSubject$.subscribe((name) => {
      alert(`name ${name}`);
      this.username = name;
    });
  }

and in the service i create the subject and i have a function that call the next function.

export class AuthService {
  user: User = new User();
  private _userSubjectSource = new Subject<string>();
  userSubject$ = this._userSubjectSource.asObservable();

  constructor(private http: HttpClient) {}

  sendUser() {
    console.log("_userSubjectSource.next()", this.user.name);
    this._userSubjectSource.next(this.user.name);
  }

I copied a tutorial that I also tested and it works very well and yet I can't get my project to work.


问:
Semantic-UI Search component results not clearing and building up
I'm using the Search component to grab a customer from a mongodb database.

The very first time I search (on the first character typed in) I get the expected results.
When I type the second character I get nearly duble the results.

When I type a word that should only return one result I still get many that should not be there.
I'm doing the filtering myself use in the entry point that collects customer data from the database.
I inspect my results and I collect the correct data.   It's the Search component that isn't doing as expected.

Here is the GUI code.

```<code>import React from 'react';
import { Search, Grid} from 'semantic-ui-react';
import _ from 'lodash';
// Use the semantic-ui search modual
// https://react.semantic-ui.com/modules/search/

const initialState = { loading: false, results: [],  numrecords : 0}
export default class SelectCustomerList  extends React.Component {

  constructor(props){
      super(props);
  }
  state = initialState;

  handleResultSelect = (e, { result }) => this.setState({ value: result.title })

  handleSearchChange = async (e, { value }) => {

    //this.setState({ loading: true, value, results : [], actualRes : '' })

    if(value=='')
    {
      return this.setState({results : [], loading : false, numrecords : 0});
    }
    let tempsource = await this.fetchCustomers(value);

    if (tempsource.length == 0) {
      return this.setState({results : [], loading : false, numrecords : 0});
    }

    this.setState({
      results : tempsource,
      loading : false,
      numrecords : tempsource.length,
      actualRes : JSON.stringify(tempsource)
    });
  }

  fetchCustomers = async(searchString) =>{

    let postObject = {
      act : 'findCustomer',
      searchString : searchString,
    };

    const waitRun = async () =>{
      let response = await fetch('/api/customer', {
        method: 'POST',
        body: JSON.stringify(postObject),
      });
      let d = await response.json();
      return d.result.data;
    }
    return waitRun();

  }
  render() {
    return (
      <Grid columns={2}>
      <Grid.Row>
          <Grid.Column>
            Num of res : {this.state.numrecords}<br/>
            Actual res : {this.state.actualRes}<br/>
          <Search
              className='search-bar-customers'
              onResultSelect={(e, data) => {
                  alert(data.result._id);
                  //onResultSelect={this.handleResultSelect}
                }
              }
              onSearchChange={(e, data) => {
                  this.handleSearchChange(e, data);
                }
              }
              loading={this.state.loading}
              results={this.state.results}
              value={this.state.value}
            />
          </Grid.Column>
      </Grid.Row>
    </Grid>
    );
  }
}
</code>```

The Actual res and Num of res end up with the expeted number of results and object properties.
But it's as if the Search modual is not emptying out first before put the newly found results in.

I've just thought maybe I'm not using it the way it's intended, by dynamically changing the results object and filtering myself before I give the results my data.  Is there a more appropriate component to use?

Many thanks
Graham

#semantic-ui-react

I've tried writting this as a functional and a class compnent.  I've tried multiple ways insdie the code to achieve what I desire.

I expect the Search box to simply display all and only the records / results I give it.

Body:
I'm using the Search component to grab a customer from a mongodb database.

The very first time I search (on the first character typed in) I get the expected results.
When I type the second character I get nearly duble the results.

When I type a word that should only return one result I still get many that should not be there.
I'm doing the filtering myself use in the entry point that collects customer data from the database.
I inspect my results and I collect the correct data.   It's the Search component that isn't doing as expected.

Here is the GUI code.

import React from 'react';
import { Search, Grid} from 'semantic-ui-react';
import _ from 'lodash';
// Use the semantic-ui search modual
// https://react.semantic-ui.com/modules/search/

const initialState = { loading: false, results: [],  numrecords : 0}
export default class SelectCustomerList  extends React.Component {

  constructor(props){
      super(props);
  }
  state = initialState;

  handleResultSelect = (e, { result }) => this.setState({ value: result.title })

  handleSearchChange = async (e, { value }) => {

    //this.setState({ loading: true, value, results : [], actualRes : '' })

    if(value=='')
    {
      return this.setState({results : [], loading : false, numrecords : 0});
    }
    let tempsource = await this.fetchCustomers(value);

    if (tempsource.length == 0) {
      return this.setState({results : [], loading : false, numrecords : 0});
    }

    this.setState({
      results : tempsource,
      loading : false,
      numrecords : tempsource.length,
      actualRes : JSON.stringify(tempsource)
    });
  }

  fetchCustomers = async(searchString) =>{

    let postObject = {
      act : 'findCustomer',
      searchString : searchString,
    };

    const waitRun = async () =>{
      let response = await fetch('/api/customer', {
        method: 'POST',
        body: JSON.stringify(postObject),
      });
      let d = await response.json();
      return d.result.data;
    }
    return waitRun();

  }
  render() {
    return (
      <Grid columns={2}>
      <Grid.Row>
          <Grid.Column>
            Num of res : {this.state.numrecords}

            Actual res : {this.state.actualRes}

          <Search
              className='search-bar-customers'
              onResultSelect={(e, data) => {
                  alert(data.result._id);
                  //onResultSelect={this.handleResultSelect}
                }
              }
              onSearchChange={(e, data) => {
                  this.handleSearchChange(e, data);
                }
              }
              loading={this.state.loading}
              results={this.state.results}
              value={this.state.value}
            />
          </Grid.Column>
      </Grid.Row>
    </Grid>
    );
  }
}

The Actual res and Num of res end up with the expeted number of results and object properties.
But it's as if the Search modual is not emptying out first before put the newly found results in.

I've just thought maybe I'm not using it the way it's intended, by dynamically changing the results object and filtering myself before I give the results my data.  Is there a more appropriate component to use?

Many thanks
Graham

#semantic-ui-react

I've tried writting this as a functional and a class compnent.  I've tried multiple ways insdie the code to achieve what I desire.

I expect the Search box to simply display all and only the records / results I give it.