问:
How to crop face detected via Mediapipe in Python
i have a problem with mediapipe coordinations. What i want to do is crop the box of the detected face.

https://google.github.io/mediapipe/solutions/face_detection.html

EXAMPLE OF PROCEDURE

And i use this code below:

```<code>    mp_face_detection = mp.solutions.face_detection

# Setup the face detection function.
face_detection = mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5)

# Initialize the mediapipe drawing class.
mp_drawing = mp.solutions.drawing_utils

# Read an image from the specified path.
sample_img = cv2.imread('12345.jpg')

# Specify a size of the figure.
plt.figure(figsize = [10, 10])

# Display the sample image, also convert BGR to RGB for display.
plt.title("Sample Image");plt.axis('off');plt.imshow(sample_img[:,:,::-1]);plt.show()

face_detection_results = face_detection.process(sample_img[:,:,::-1])

# Check if the face(s) in the image are found.
if face_detection_results.detections:

    # Iterate over the found faces.
    for face_no, face in enumerate(face_detection_results.detections):

        # Display the face number upon which we are iterating upon.
        print(f'FACE NUMBER: {face_no+1}')
        print('---------------------------------')

        # Display the face confidence.
        print(f'FACE CONFIDENCE: {round(face.score[0], 2)}')

        # Get the face bounding box and face key points coordinates.
        face_data = face.location_data

        # Display the face bounding box coordinates.
        print(f'\nFACE BOUNDING BOX:\n{face_data.relative_bounding_box}')

        # Iterate two times as we only want to display first two key points of each detected face.
        for i in range(2):

            # Display the found normalized key points.
            print(f'{mp_face_detection.FaceKeyPoint(i).name}:')
            print(f'{face_data.relative_keypoints[mp_face_detection.FaceKeyPoint(i).value]}')
</code>```

So the results are in this form:

```<code>FACE NUMBER: 1

FACE CONFIDENCE: 0.89

FACE BOUNDING BOX:
xmin: 0.2784463167190552
ymin: 0.3503175973892212
width: 0.1538110375404358
height: 0.23071599006652832

RIGHT_EYE:
x: 0.3447018265724182
y: 0.4222590923309326

LEFT_EYE:
x: 0.39114508032798767
y: 0.3888365626335144
</code>```

And i want to CROP the image in the coordinations of the BOX.
Like

```<code>face = Image.fromarray(image).crop(face_rect)
</code>```

or any other crop procedure.
My problem is that i can't get the coords of the detected item from mediapipe.

Any ideas?

答:
Got the solution guys</p>
```<code>import dlib
from PIL import Image
from skimage import io
</code>```
```<code>h, w, c = sample_img.shape
print('width:  ', w)
print('height: ', h)
</code>```
```<code>xleft = data.xmin*w
xleft = int(xleft)
xtop = data.ymin*h
xtop = int(xtop)
xright = data.width*w + xleft
xright = int(xright)
xbottom = data.height*h + xtop
xbottom = int(xbottom)
</code>```
```<code>detected_faces = [(xleft, xtop, xright, xbottom)]

for n, face_rect in enumerate(detected_faces):
    face = Image.fromarray(image_c).crop(face_rect)
    face_np = np.asarray(face)
    plt.imshow(face_np)
</code>```

Body:
i have a problem with mediapipe coordinations. What i want to do is crop the box of the detected face.

https://google.github.io/mediapipe/solutions/face_detection.html

EXAMPLE OF PROCEDURE

And i use this code below:

    mp_face_detection = mp.solutions.face_detection

# Setup the face detection function.
face_detection = mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5)

# Initialize the mediapipe drawing class.
mp_drawing = mp.solutions.drawing_utils

# Read an image from the specified path.
sample_img = cv2.imread('12345.jpg')

# Specify a size of the figure.
plt.figure(figsize = [10, 10])

# Display the sample image, also convert BGR to RGB for display.
plt.title("Sample Image");plt.axis('off');plt.imshow(sample_img[:,:,::-1]);plt.show()

face_detection_results = face_detection.process(sample_img[:,:,::-1])

# Check if the face(s) in the image are found.
if face_detection_results.detections:

    # Iterate over the found faces.
    for face_no, face in enumerate(face_detection_results.detections):

        # Display the face number upon which we are iterating upon.
        print(f'FACE NUMBER: {face_no+1}')
        print('---------------------------------')

        # Display the face confidence.
        print(f'FACE CONFIDENCE: {round(face.score[0], 2)}')

        # Get the face bounding box and face key points coordinates.
        face_data = face.location_data

        # Display the face bounding box coordinates.
        print(f'\nFACE BOUNDING BOX:\n{face_data.relative_bounding_box}')

        # Iterate two times as we only want to display first two key points of each detected face.
        for i in range(2):

            # Display the found normalized key points.
            print(f'{mp_face_detection.FaceKeyPoint(i).name}:')
            print(f'{face_data.relative_keypoints[mp_face_detection.FaceKeyPoint(i).value]}')

So the results are in this form:

FACE NUMBER: 1

FACE CONFIDENCE: 0.89

FACE BOUNDING BOX:
xmin: 0.2784463167190552
ymin: 0.3503175973892212
width: 0.1538110375404358
height: 0.23071599006652832

RIGHT_EYE:
x: 0.3447018265724182
y: 0.4222590923309326

LEFT_EYE:
x: 0.39114508032798767
y: 0.3888365626335144

And i want to CROP the image in the coordinations of the BOX.
Like

face = Image.fromarray(image).crop(face_rect)

or any other crop procedure.
My problem is that i can't get the coords of the detected item from mediapipe.

Any ideas?

Body:
Got the solution guys

import dlib
from PIL import Image
from skimage import io

h, w, c = sample_img.shape
print('width:  ', w)
print('height: ', h)

xleft = data.xmin*w
xleft = int(xleft)
xtop = data.ymin*h
xtop = int(xtop)
xright = data.width*w + xleft
xright = int(xright)
xbottom = data.height*h + xtop
xbottom = int(xbottom)

detected_faces = [(xleft, xtop, xright, xbottom)]

for n, face_rect in enumerate(detected_faces):
    face = Image.fromarray(image_c).crop(face_rect)
    face_np = np.asarray(face)
    plt.imshow(face_np)


来源: stackexchange

问:
C# SslStream throws "Verification failure during handshake"
I'm trying to establish a simple TLS-connection between a server and a client in Unity with C#'s SslStream-class. Currently, both client and server run on my machine and the hostIpAddress and serverName are set to "127.0.0.1". I created a (self-signed) certificate file with OpenSSL and saved it under pathToCertificate.

The certificate file is being read without issues and the server can be opened, but when a client tries connecting, an AuthentificationException (Outer: "Authentication failed, see inner exception.", Inner: "Verification failure during handshake") is thrown in sslStream.AuthenticateAsServer(hostCertificate, false, true);.

Server:

    hostCertificate = new X509Certificate2(pathToCertificate, "pw");
    listener = new TcpListener(IPAddress.Any, port);
    listener.Start();

    TcpClient tcpConnection = listener.AcceptTcpClient();

    // A client has connected. Create the
    // SslStream using the client's network stream.
    SslStream sslStream = new SslStream(tcpConnection.GetStream(), false);

    // Authenticate the server but don't require the client to authenticate.
    try
    {
        sslStream.AuthenticateAsServer(hostCertificate, false, true);

        // Set timeouts for the read and write to 2 seconds.
        sslStream.ReadTimeout = 2000;
        sslStream.WriteTimeout = 2000;
    }
    catch(AuthenticationException exc)
    {
        Debug.LogError("Exception during HostController Network Authentification:");
        Debug.LogError(exc.Message);
        if(exc.InnerException != null)
        {
            Debug.LogError(exc.InnerException.Message);
        }

        tcpConnection.Close();
        sslStream.Close();
        }
    }
```
<h3>Client:</h3>
<pre class="lang-cs prettyprint-override"><code>public ClientController()
{
    TcpClient tcpConnection = new TcpClient(hostIpAddress, port);

    // Create an SSL stream that will enclose the client's stream.
    hostStream = new SslStream(tcpConnection.GetStream(), false,
        new RemoteCertificateValidationCallback(ValidateServerCertificate));
    // The server name must match the name on the server certificate.
    try
    {
        hostStream.AuthenticateAsClient(serverName);
    }
    catch(AuthenticationException exc)
    {
        Debug.LogError("Exception during ClientController Network Authentification:");
        Debug.LogError(exc.Message);
        if(exc.InnerException != null)
        {
            Debug.LogError(exc.InnerException.Message);
        }

        tcpConnection.Close();
        hostStream.Close();
    }
}

// The following method is invoked by the RemoteCertificateValidationDelegate.
    public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if(sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;
        }

        Debug.LogError("Certificate error: " + sslPolicyErrors);

        // Do not allow this client to communicate with unauthenticated servers.
        return false;
    }
</code>```

OpenSSL-Commands to create Certificate:

```<code>openssl genrsa -out LocalCA.key 2048

openssl req -x509 -new -nodes -key LocalCA.key -sha256 -days 3650 -out LocalCA.crt -config localhost.cnf -extensions v3_ca -subj "/CN=SocketTools LocalCA"

openssl genrsa -out localhost.key 2048

openssl req -new -key localhost.key -out localhost.csr -config localhost.cnf -extensions v3_req

openssl x509 -req -in localhost.csr -CA LocalCA.crt -CAkey LocalCA.key -CAcreateserial -out localhost.crt -days 3650 -sha256 -extfile localhost.cnf -extensions v3_req

openssl pkcs12 -export -out localhost.pfx -inkey localhost.key -in localhost.crt -certfile LocalCA.crt -password pass:pw
</code>```

localhost.cnf:

```<code>[req]
default_bits = 2048
default_md = sha256
prompt = no
distinguished_name = req_distinguished_name
x509_extensions = v3_ca
req_extensions = v3_req

[req_distinguished_name]
C = AT
ST = Vienna
L = Vienna
O = FluffyVoxels
CN = localhost

[v3_ca]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[v3_req]
subjectKeyIdentifier = hash
basicConstraints = critical, CA:false
nsCertType = server
keyUsage = digitalSignature, nonRepudiation, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
IP.2 = 192.168.0.4
IP.3 = 2a02:8388:8a03:ac80:c8d6:6a1d:f2b0:c17d
IP.4 = ::1
</code>```

Wireshark Output during Connection

答:
Looks like a Unity Bug here (calling VerifyCertificate() with null and throwing an exception when null is not recognized as a valid certificate):

https://github.com/Unity-Technologies/mono/blob/06e6ccece853a5373a6545a821ca178f4ec57f20/mcs/class/System/Mono.UnityTls/UnityTlsContext.cs#L344

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to establish a simple TLS-connection between a server and a client in Unity with C#'s SslStream-class. Currently, both client and server run on my machine and the hostIpAddress and serverName are set to "127.0.0.1". I created a (self-signed) certificate file with OpenSSL and saved it under pathToCertificate.

The certificate file is being read without issues and the server can be opened, but when a client tries connecting, an AuthentificationException (Outer: "Authentication failed, see inner exception.", Inner: "Verification failure during handshake") is thrown in sslStream.AuthenticateAsServer(hostCertificate, false, true);.

Server:

    hostCertificate = new X509Certificate2(pathToCertificate, "pw");
    listener = new TcpListener(IPAddress.Any, port);
    listener.Start();

    TcpClient tcpConnection = listener.AcceptTcpClient();

    // A client has connected. Create the
    // SslStream using the client's network stream.
    SslStream sslStream = new SslStream(tcpConnection.GetStream(), false);

    // Authenticate the server but don't require the client to authenticate.
    try
    {
        sslStream.AuthenticateAsServer(hostCertificate, false, true);

        // Set timeouts for the read and write to 2 seconds.
        sslStream.ReadTimeout = 2000;
        sslStream.WriteTimeout = 2000;
    }
    catch(AuthenticationException exc)
    {
        Debug.LogError("Exception during HostController Network Authentification:");
        Debug.LogError(exc.Message);
        if(exc.InnerException != null)
        {
            Debug.LogError(exc.InnerException.Message);
        }

        tcpConnection.Close();
        sslStream.Close();
        }
    }

Client:

public ClientController()
{
    TcpClient tcpConnection = new TcpClient(hostIpAddress, port);

    // Create an SSL stream that will enclose the client's stream.
    hostStream = new SslStream(tcpConnection.GetStream(), false,
        new RemoteCertificateValidationCallback(ValidateServerCertificate));
    // The server name must match the name on the server certificate.
    try
    {
        hostStream.AuthenticateAsClient(serverName);
    }
    catch(AuthenticationException exc)
    {
        Debug.LogError("Exception during ClientController Network Authentification:");
        Debug.LogError(exc.Message);
        if(exc.InnerException != null)
        {
            Debug.LogError(exc.InnerException.Message);
        }

        tcpConnection.Close();
        hostStream.Close();
    }
}

// The following method is invoked by the RemoteCertificateValidationDelegate.
    public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if(sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;
        }

        Debug.LogError("Certificate error: " + sslPolicyErrors);

        // Do not allow this client to communicate with unauthenticated servers.
        return false;
    }

OpenSSL-Commands to create Certificate:

openssl genrsa -out LocalCA.key 2048

openssl req -x509 -new -nodes -key LocalCA.key -sha256 -days 3650 -out LocalCA.crt -config localhost.cnf -extensions v3_ca -subj "/CN=SocketTools LocalCA"

openssl genrsa -out localhost.key 2048

openssl req -new -key localhost.key -out localhost.csr -config localhost.cnf -extensions v3_req

openssl x509 -req -in localhost.csr -CA LocalCA.crt -CAkey LocalCA.key -CAcreateserial -out localhost.crt -days 3650 -sha256 -extfile localhost.cnf -extensions v3_req

openssl pkcs12 -export -out localhost.pfx -inkey localhost.key -in localhost.crt -certfile LocalCA.crt -password pass:pw

localhost.cnf:

[req]
default_bits = 2048
default_md = sha256
prompt = no
distinguished_name = req_distinguished_name
x509_extensions = v3_ca
req_extensions = v3_req

[req_distinguished_name]
C = AT
ST = Vienna
L = Vienna
O = FluffyVoxels
CN = localhost

[v3_ca]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[v3_req]
subjectKeyIdentifier = hash
basicConstraints = critical, CA:false
nsCertType = server
keyUsage = digitalSignature, nonRepudiation, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
IP.2 = 192.168.0.4
IP.3 = 2a02:8388:8a03:ac80:c8d6:6a1d:f2b0:c17d
IP.4 = ::1

Wireshark Output during Connection


问:
C# : is there an appropriate collection for fast range-related search?
I have data like that:

Time(seconds from start)
Value

15
2

16
4

19
2

25
9

There are a lot of entries (10000+), and I need a way to find fast enough sum of any time range, like sum of range 16-25 seconds (which would be 4+2+9=15). This data will be dynamically changed many times (always adding new entries at the bottom of list).

I am thinking about using sorted list + binary search to determinate positions and just make sum of values, but is can took too much time to calculate it. Is there are any more appropriate way to do so? Nuget packets or algorithm references would be appreciated.

答:
Just calculate cumulative sum:

```<code>Time Value CumulativeSum
15   2     2
16   4     6
19   2     8
25   9     17
</code>```

Then for range [16,25] it will be task to binary search left border of 16 and 25 exact, which turns into 17 - 2 = 15

Complexity: O(log(n)), where n - size of the list.

Binary search implementation for lower/upper bound can be found in my repo - https://github.com/eocron/Algorithm/blob/master/Algorithm/Sorted/BinarySearchExtensions.cs

Body:
Just calculate cumulative sum:

Time Value CumulativeSum
15   2     2
16   4     6
19   2     8
25   9     17

Then for range [16,25] it will be task to binary search left border of 16 and 25 exact, which turns into 17 - 2 = 15

Complexity: O(log(n)), where n - size of the list.

Binary search implementation for lower/upper bound can be found in my repo - https://github.com/eocron/Algorithm/blob/master/Algorithm/Sorted/BinarySearchExtensions.cs


问:
Passing compiler options in CMake command line
I know how to pass compiler options using the cmake command:

```<code>set(CMAKE_CXX_FLAGS "-Wall -Wno-dev -Wl,-rpath=/home/abcd/libs/")
</code>```

Is there also a way to pass the options from the command line that will override the CMakeLists.txt options? Something like:

```<code>cmake -Wl,-rpath=/home/abcd/newlibs/ path/to/CMakeLists.txt
</code>```

or

```<code>cmake -D CMAKE_CXX_FLAGS="-Wno-dev -Wl,-rpath=/home/abcd/libs/" path/to/CMakeLists.txt
</code>```

My main problem is that I want to know how to append flags and how to override existing compiler flags from the command line.

答:
I simply use the $ENV() operator to get the environment variable, for example in a CMakeLists.txt:

```<code>add_compile_options($ENV{MY_CXXFLAG})
</code>```

The only problem is that $ENV() is only read on in the configuration stage, so CMake does not see the environment setting on the current build stage. But reconfiguring is triggered by changed CMake files, so I just use touch to simulate a change. Here is an example of a command line:

```<code>touch CMakeLists.txt && MY_CXXFLAG="-D DEBUG" cmake --build build --config Debug
</code>```

or what other options do you use. With this simple example, there are still some quirks with the flag string of the environment variable, e.g., more than one option. But it shouldn't be a big problem with string handling in CMakeLists.txt to beautify this.

Body:
I know how to pass compiler options using the cmake command:

set(CMAKE_CXX_FLAGS "-Wall -Wno-dev -Wl,-rpath=/home/abcd/libs/")

Is there also a way to pass the options from the command line that will override the CMakeLists.txt options? Something like:

cmake -Wl,-rpath=/home/abcd/newlibs/ path/to/CMakeLists.txt

or

cmake -D CMAKE_CXX_FLAGS="-Wno-dev -Wl,-rpath=/home/abcd/libs/" path/to/CMakeLists.txt

My main problem is that I want to know how to append flags and how to override existing compiler flags from the command line.

Body:
I simply use the $ENV() operator to get the environment variable, for example in a CMakeLists.txt:

add_compile_options($ENV{MY_CXXFLAG})

The only problem is that $ENV() is only read on in the configuration stage, so CMake does not see the environment setting on the current build stage. But reconfiguring is triggered by changed CMake files, so I just use touch to simulate a change. Here is an example of a command line:

touch CMakeLists.txt && MY_CXXFLAG="-D DEBUG" cmake --build build --config Debug

or what other options do you use. With this simple example, there are still some quirks with the flag string of the environment variable, e.g., more than one option. But it shouldn't be a big problem with string handling in CMakeLists.txt to beautify this.


问:
How to automatically update the Hive external table metadata partitions for streaming data
I am writing the spark streaming data into hdfs partitions using pyspark.
please find the code

```<code>  data = (spark.readStream.format("json").schema(fileSchema).load(inputDirectoryOfJsonFiles))

  output = (data.writeStream
   .format("parquet")
   .partitionBy("date")
   .option("compression", "none")
   .option("path" , "/user/hdfs/stream-test")
   .option("checkpointLocation", "/user/hdfs/stream-ckp")
   .outputMode("append")
   .start().awaitTermination())
</code>```

After writing the data into hdfs, i am creating the hive external partition table.

```<code>CREATE EXTERNAL TABLE test (id string,record string)
PARTITIONED BY (`date` date)
STORED AS PARQUET
LOCATION '/user/hdfs/stream-test/'
TBLPROPERTIES ('discover.partitions' = 'true');
</code>```

But the newly created partitions are not been recognized Hive metastore. i am updating the metastore using the msck command.

```<code>msck repair table test sync partitions
</code>```

Now for the streaming data how to automate this task of updating the hive metastore with the real time partitions.

please suggest a solution to this problem.

答:
Spark structured streaming don't natively support this, but you can use foreachBatch as workaround

```<code>val yourStream = spark
  .read
  .format("kafka")
  .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
  .load()

val query = yourStream.writeStream.foreachBatch((batchDF: DataFrame, batchId: Long) => {
  batchDF
      .write
      .mode(SaveMode.Append)
      .insertInto("your_db.your_hive_table");
}).start()

query.awaitTermination()
</code>```

More details refer https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#foreachbatch

Body:
I am writing the spark streaming data into hdfs partitions using pyspark.
please find the code

  data = (spark.readStream.format("json").schema(fileSchema).load(inputDirectoryOfJsonFiles))

  output = (data.writeStream
   .format("parquet")
   .partitionBy("date")
   .option("compression", "none")
   .option("path" , "/user/hdfs/stream-test")
   .option("checkpointLocation", "/user/hdfs/stream-ckp")
   .outputMode("append")
   .start().awaitTermination())

After writing the data into hdfs, i am creating the hive external partition table.

CREATE EXTERNAL TABLE test (id string,record string)
PARTITIONED BY (`date` date)
STORED AS PARQUET
LOCATION '/user/hdfs/stream-test/'
TBLPROPERTIES ('discover.partitions' = 'true');

But the newly created partitions are not been recognized Hive metastore. i am updating the metastore using the msck command.

msck repair table test sync partitions

Now for the streaming data how to automate this task of updating the hive metastore with the real time partitions.

please suggest a solution to this problem.

Body:
Spark structured streaming don't natively support this, but you can use foreachBatch as workaround

val yourStream = spark
  .read
  .format("kafka")
  .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
  .load()

val query = yourStream.writeStream.foreachBatch((batchDF: DataFrame, batchId: Long) => {
  batchDF
      .write
      .mode(SaveMode.Append)
      .insertInto("your_db.your_hive_table");
}).start()

query.awaitTermination()

More details refer https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#foreachbatch


问:
Cypress unable to save current URL with `as`
My web app generates a UUIDv4 for every new 'post', and each post has its own URL like /posts/<uuid>. I'm not able to predict what uuid gets generated, and therefore I'm unable to go back to a specific post that was created earlier during testing.

According to the docs, cy.url() returns the URL as a string. I tried saving the URL using a .as(), but it didn't work:

```<code>cy.url().as('postUrl');
// go somewhere else
cy.visit('@postUrl');

// ends up visiting `localhost:3000/@postUrl`
</code>```

I saw in another SO question that I should use .then on cy.url(), but that didn't work either:

```<code>cy.url().then(url => url).as('postUrl');
// go somewhere else
cy.visit('@postUrl');
</code>```

How do I save the current URL for use later?

答:
```<code>var currentUrl=''

cy.url().then(url => {
    currentUrl = url;
});

cy.visit(currentUrl)
</code>```

Body:
My web app generates a UUIDv4 for every new 'post', and each post has its own URL like /posts/<uuid>. I'm not able to predict what uuid gets generated, and therefore I'm unable to go back to a specific post that was created earlier during testing.

According to the docs, cy.url() returns the URL as a string. I tried saving the URL using a .as(), but it didn't work:

cy.url().as('postUrl');
// go somewhere else
cy.visit('@postUrl');

// ends up visiting `localhost:3000/@postUrl`

I saw in another SO question that I should use .then on cy.url(), but that didn't work either:

cy.url().then(url => url).as('postUrl');
// go somewhere else
cy.visit('@postUrl');

How do I save the current URL for use later?


问:
Python convert decimal to hex
I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?</p>

```<code>def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        x =(n%16)
        if (x < 10):
            print(x),
        if (x == 10):
            print("A"),
        if (x == 11):
            print("B"),
        if (x == 12):
            print("C"),
        if (x == 13):
            print("D"),
        if (x == 14):
            print("E"),
        if (x == 15):
            print ("F"),
        ChangeHex( n / 16 )
</code>```

答:
```<code>def decimal_to_base(decimal_number, destination_base):
digits_array = []
hexadecimals = {10:"A", 11:"B", 12:"C", 13:"D", 14:"E", 15:"F"}
while decimal_number > 0:
    rest = decimal_number % destination_base
    if rest in hexadecimals:
        rest = hexadecimals[rest]
    digits_array.insert(0, rest)
    decimal_number = decimal_number // destination_base
return digits_array
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python convert decimal to hex

Body:
I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?

def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        x =(n%16)
        if (x < 10):
            print(x),
        if (x == 10):
            print("A"),
        if (x == 11):
            print("B"),
        if (x == 12):
            print("C"),
        if (x == 13):
            print("D"),
        if (x == 14):
            print("E"),
        if (x == 15):
            print ("F"),
        ChangeHex( n / 16 )


问:
Where can I see the source code for classes within my current ruby intallation?
I am new to ruby but nonetheless I have installed various versions of Ruby using RVM,
Here's the the output of my LOAD_PATH

```<code>ruby-1.9.2-p136 :001 > puts $LOAD_PATH
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/i686-linux
</code>```

Ok. So the question here is, Where within these directories can I see the source code for classes like Array, or Time ? (I know, it's an extremely n00b question, but I need to know.)

I've been needing to take a look at the source of Array for a long time.

Thanks in advance!

PS. Which class do you recommend looking at if I want to become a better ruby programmer?

答:
The coolest gadget for code browsing I found so far is pry:

http://pry.github.com/

It's an irb replacement with a lot of goodies. An example session so you can see how you can browse code with it (and you'll also see that it can show the C-implementation of a class):

```<code>> pry
pry(main)> show-
show-command  show-doc      show-input    show-method   show-source
pry(main)> show-source Array

From: object.c in Ruby Core (C Method):
Number of lines: 6

static VALUE
rb_f_array(obj, arg)
    VALUE obj, arg;
{
    return rb_Array(arg);
}
pry(main)> cd Array
pry(Array):1> show-source each

From: array.c in Ruby Core (C Method):
Number of lines: 12

VALUE
rb_ary_each(ary)
    VALUE ary;
{
    long i;

    RETURN_ENUMERATOR(ary, 0, 0);
    for (i=0; i<RARRAY(ary)->len; i++) {
    rb_yield(RARRAY(ary)->ptr[i]);
    }
    return ary;
}
pry(Array):1>
</code>```

Pry can of course also list the Ruby source of classes.

Another useful tool for browsing the C-source for Ruby is the Ruby code cross reference:

http://rxr.whitequark.org/

However right now it seems to be down, but hopefully it will be up again soon.

Body:
I am new to ruby but nonetheless I have installed various versions of Ruby using RVM,
Here's the the output of my LOAD_PATH

ruby-1.9.2-p136 :001 > puts $LOAD_PATH
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/i686-linux

Ok. So the question here is, Where within these directories can I see the source code for classes like Array, or Time ? (I know, it's an extremely n00b question, but I need to know.)

I've been needing to take a look at the source of Array for a long time.

Thanks in advance!

PS. Which class do you recommend looking at if I want to become a better ruby programmer?

Body:
The coolest gadget for code browsing I found so far is pry:

http://pry.github.com/

It's an irb replacement with a lot of goodies. An example session so you can see how you can browse code with it (and you'll also see that it can show the C-implementation of a class):

> pry
pry(main)> show-
show-command  show-doc      show-input    show-method   show-source
pry(main)> show-source Array

From: object.c in Ruby Core (C Method):
Number of lines: 6

static VALUE
rb_f_array(obj, arg)
    VALUE obj, arg;
{
    return rb_Array(arg);
}
pry(main)> cd Array
pry(Array):1> show-source each

From: array.c in Ruby Core (C Method):
Number of lines: 12

VALUE
rb_ary_each(ary)
    VALUE ary;
{
    long i;

    RETURN_ENUMERATOR(ary, 0, 0);
    for (i=0; i<RARRAY(ary)->len; i++) {
    rb_yield(RARRAY(ary)->ptr[i]);
    }
    return ary;
}
pry(Array):1>

Pry can of course also list the Ruby source of classes.

Another useful tool for browsing the C-source for Ruby is the Ruby code cross reference:

http://rxr.whitequark.org/

However right now it seems to be down, but hopefully it will be up again soon.


问:
How to conditionally add "checked" using a django template tag without causing htmlhint to throw an error?
I have 8 lines in my template where I have checkbox inputs.  I save their checked state in a cookie and use a template tag to insert checked if it should be checked when the page initially loads.  The code works just fine.  It looks like this:

```<code><td><input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" {% get_template_cookie selfmt 'showaverage' 'checked' %} /> Average</td>
</code>```

However, when I run superlinter, I end up with the following errors regarding the above line:

```<code><td><input type="checkbox" id="showaverage" onclick="set_template_cookie('showave...
    ^ Special characters must be escaped : [ < ]. (spec-char-escape)
...rage' 'checked' %} /> Average</td>
                       ^ Special characters must be escaped : [ > ]. (spec-char-escape)
</code>```

Oddly, if I run the exact same version of htmlhint manually on the command line using the same .htmlhintrc config file, I get no error:

```<code>>npx htmlhint -c .htmlhintrc DataRepo/search/results/fcirc.html
npx: installed 32 in 3.793s

   Config loaded: .htmlhintrc

Scanned 0 files, no errors found (6 ms).
</code>```

That config file contains:

```<code>{
  "tagname-lowercase": true,
  "attr-lowercase": true,
  "attr-value-double-quotes": true,
  "attr-value-not-empty": false,
  "attr-no-duplication": true,
  "doctype-first": false,
  "tag-pair": true,
  "tag-self-close": false,
  "spec-char-escape": true,
  "id-unique": true,
  "src-not-empty": true,
  "title-require": true,
  "alt-require": true,
  "doctype-html5": true,
  "id-class-value": false,
  "style-disabled": false,
  "inline-style-disabled": false,
  "inline-script-disabled": false,
  "space-tab-mixed-disabled": "space",
  "id-class-ad-disabled": false,
  "href-abs-or-rel": false,
  "attr-unsafe-chars": true,
  "head-script-disabled": true
}
</code>```

...where you see "spec-char-escape": true,, so if it's going to error, it should error in both places...

I don't understand why superlinter's htmlhint complains and mine doesn't, but I tried to silence superlinter's version by adding:

```<code><!-- htmlhint spec-char-escape:false -->
</code>```

But I still get the error.  Can anyone advise me on how to avoid the error?

ADDENDUM: I just tried working around this issue by using a conditional, inside which I either have checked or not, but when I do that, it complains about the ID needing to be unique.  Observe:

Work-around for the issue above:

```<code>                    <td>
                        {% get_template_cookie selfmt 'showaverage' 'checked' as avgchkd %}
                        {% if avgchkd == "checked" %}
                            <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" checked />
                        {% else %}
                            <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" />
                        {% endif %}
                        Average
                    </td>
</code>```

New problem:

```<code><input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage',...
                      ^ The id value [ showaverage ] must be unique. (id-unique)
</code>```

答:
htmlhint is not written to be used with templating frameworks.  It will largely ignore template tags wrapped in quotes, which generally isn't a problem until you conditionally need an attribute inside an html element/tag.  And what's worse, it will apply rules to the template tag, such as uniqueness of an ID, so to get around these issues without turning off otherwise useful htmlhint rules, you have to figure out a work-around.

Here's a work-around I got to solve this particular problem.  It's a lot more code and complexity to solve what should be a simple problem, so if anyone has a more elegant solution, please share.

To get around the conditionally added checked attribute spec-char-escape error from htmlhint, this works (as I noted in my addendum in the question):

```<code><td>
    {% get_template_cookie selfmt 'showaverage' 'checked' as avgchkd %}
    {% if avgchkd == "checked" %}
        <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" checked />
    {% else %}
        <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" />
    {% endif %}
    Average
</td>
</code>```

but that causes another problem: the id-unique error.  And to get around that, I added an otherwise pointless template tag:

```<code>@register.simple_tag
def uniquify(retval, unused):
    return retval
</code>```

Then you can make the ID's seem unique to htmlhint with:

```<code><td>
    {% get_template_cookie selfmt 'showaverage' 'checked' as avgchkd %}
    {% if avgchkd == "checked" %}
        <input type="checkbox" id="{% uniquify 'showaverage' 1 %}" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" checked />
    {% else %}
        <input type="checkbox" id="{% uniquify 'showaverage' 2 %}" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" />
    {% endif %}
    Average
</td>
</code>```

Body:
I have 8 lines in my template where I have checkbox inputs.  I save their checked state in a cookie and use a template tag to insert checked if it should be checked when the page initially loads.  The code works just fine.  It looks like this:

<input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" {% get_template_cookie selfmt 'showaverage' 'checked' %} /> Average

However, when I run superlinter, I end up with the following errors regarding the above line:

<input type="checkbox" id="showaverage" onclick="set_template_cookie('showave...
    ^ Special characters must be escaped : [ < ]. (spec-char-escape)
...rage' 'checked' %} /> Average
                       ^ Special characters must be escaped : [ > ]. (spec-char-escape)

Oddly, if I run the exact same version of htmlhint manually on the command line using the same .htmlhintrc config file, I get no error:

>npx htmlhint -c .htmlhintrc DataRepo/search/results/fcirc.html
npx: installed 32 in 3.793s

   Config loaded: .htmlhintrc

Scanned 0 files, no errors found (6 ms).

That config file contains:

{
  "tagname-lowercase": true,
  "attr-lowercase": true,
  "attr-value-double-quotes": true,
  "attr-value-not-empty": false,
  "attr-no-duplication": true,
  "doctype-first": false,
  "tag-pair": true,
  "tag-self-close": false,
  "spec-char-escape": true,
  "id-unique": true,
  "src-not-empty": true,
  "title-require": true,
  "alt-require": true,
  "doctype-html5": true,
  "id-class-value": false,
  "style-disabled": false,
  "inline-style-disabled": false,
  "inline-script-disabled": false,
  "space-tab-mixed-disabled": "space",
  "id-class-ad-disabled": false,
  "href-abs-or-rel": false,
  "attr-unsafe-chars": true,
  "head-script-disabled": true
}

...where you see "spec-char-escape": true,, so if it's going to error, it should error in both places...

I don't understand why superlinter's htmlhint complains and mine doesn't, but I tried to silence superlinter's version by adding:

But I still get the error.  Can anyone advise me on how to avoid the error?

ADDENDUM: I just tried working around this issue by using a conditional, inside which I either have checked or not, but when I do that, it complains about the ID needing to be unique.  Observe:

Work-around for the issue above:

                        {% get_template_cookie selfmt 'showaverage' 'checked' as avgchkd %}
                        {% if avgchkd == "checked" %}
                            <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" checked />
                        {% else %}
                            <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" />
                        {% endif %}
                        Average

New problem:

<input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage',...
                      ^ The id value [ showaverage ] must be unique. (id-unique)

Body:
htmlhint is not written to be used with templating frameworks.  It will largely ignore template tags wrapped in quotes, which generally isn't a problem until you conditionally need an attribute inside an html element/tag.  And what's worse, it will apply rules to the template tag, such as uniqueness of an ID, so to get around these issues without turning off otherwise useful htmlhint rules, you have to figure out a work-around.

Here's a work-around I got to solve this particular problem.  It's a lot more code and complexity to solve what should be a simple problem, so if anyone has a more elegant solution, please share.

To get around the conditionally added checked attribute spec-char-escape error from htmlhint, this works (as I noted in my addendum in the question):

<td>
    {% get_template_cookie selfmt 'showaverage' 'checked' as avgchkd %}
    {% if avgchkd == "checked" %}
        <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" checked />
    {% else %}
        <input type="checkbox" id="showaverage" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" />
    {% endif %}
    Average
</td>

but that causes another problem: the id-unique error.  And to get around that, I added an otherwise pointless template tag:

@register.simple_tag
def uniquify(retval, unused):
    return retval

Then you can make the ID's seem unique to htmlhint with:

<td>
    {% get_template_cookie selfmt 'showaverage' 'checked' as avgchkd %}
    {% if avgchkd == "checked" %}
        <input type="checkbox" id="{% uniquify 'showaverage' 1 %}" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" checked />
    {% else %}
        <input type="checkbox" id="{% uniquify 'showaverage' 2 %}" onclick="set_template_cookie('showaverage', this.checked ? 'checked' : '')" />
    {% endif %}
    Average
</td>


问:
problem in my int main when i am passing the values to the function
The whole program is working its just not showing name after running

```<code>#include<iostream>
#include<string.h>

using namespace std;

class employee{

private:
    char profession;
    int dob,sallery;

public:
    int hour;

    char names;

    void display(int hour,char names[20]){

        cout<<"thank you "<<names[20]<<"for working for our company\n here is your "<<endl;

        if(hour>=8){
            cout<<"for working 7-8 hours you will be payed 1500 Rupees"<<endl;
        }
        else if (hour>=6){
            cout<<"you have worked for 5-6 hours your wage will be 1250 Rupees"<<endl;
        }
        else if(hour>=4){
            cout<<"you have worked for 3-4 hours your wage will be 850 Rupees"<<endl;
        }
        else if(hour>=2){
            cout<<"you have worked for 1-2 hours your wage will be 500 Rupees"<<endl;
        }
        else {
            cout<<"you have entered wrong input"<<endl;
        }
    }
};

int main(){

    char x[20];
    int y;
    cout<<"enter your name here"<<endl;
    cin>>x;

    cout<<"enter the number of hours you worked"<<endl;
    cin>>y;

    employee c1;

    c1.display(y,x);

    return 0;
}
</code>```

i am not able to pass the above char from user to the function.

答:
If you are trying to take string as input, better to use string data type.

Instead of

```<code>char x[20];
int y;
cout<<"enter your name here"<<endl;
cin>>x;
</code>```

Try changing it to

```<code>string x;
int y;
cout<<"enter your name here"<<endl;
cin>>x;
</code>```

And in your void display() function
Change from

```<code>void display(int hour,char names[20]){

cout<<"thank you "<<names[20]<<"for working for our company\n here is your "<<endl;
</code>```

To this

```<code>void display(int hour,string name){

cout<<"thank you "<<name<<"for working for our company\n here is your "<<endl;
</code>```

Body:
The whole program is working its just not showing name after running

#include<iostream>
#include<string.h>

using namespace std;

class employee{

private:
    char profession;
    int dob,sallery;

public:
    int hour;

    char names;

    void display(int hour,char names[20]){

        cout<<"thank you "<<names[20]<<"for working for our company\n here is your "<<endl;

        if(hour>=8){
            cout<<"for working 7-8 hours you will be payed 1500 Rupees"<<endl;
        }
        else if (hour>=6){
            cout<<"you have worked for 5-6 hours your wage will be 1250 Rupees"<<endl;
        }
        else if(hour>=4){
            cout<<"you have worked for 3-4 hours your wage will be 850 Rupees"<<endl;
        }
        else if(hour>=2){
            cout<<"you have worked for 1-2 hours your wage will be 500 Rupees"<<endl;
        }
        else {
            cout<<"you have entered wrong input"<<endl;
        }
    }
};

int main(){

    char x[20];
    int y;
    cout<<"enter your name here"<<endl;
    cin>>x;

    cout<<"enter the number of hours you worked"<<endl;
    cin>>y;

    employee c1;

    c1.display(y,x);

    return 0;
}

i am not able to pass the above char from user to the function.

Body:
If you are trying to take string as input, better to use string data type.

Instead of

char x[20];
int y;
cout<<"enter your name here"<<endl;
cin>>x;

Try changing it to

string x;
int y;
cout<<"enter your name here"<<endl;
cin>>x;

And in your void display() function
Change from

void display(int hour,char names[20]){

cout<<"thank you "<<names[20]<<"for working for our company\n here is your "<<endl;

To this

void display(int hour,string name){

cout<<"thank you "<<name<<"for working for our company\n here is your "<<endl;


问:
React play different audio files at once - working with different refs
I'm creating a small app that plays an audio file and have some functionalities (loop, stop, mute). My goal is to add some more audio files that all should be played and stopped at once (one button to control all), but each will have a mute button, and  I'm not sure what is the best practice to do so. I used useRef and thought maybe I need to set a refs array but how will I be able to start/stop them all at once, but still have the ability to control the mute separately?

This is my code so far. I guess I should split and have a different component for the audio sounds. Thanks for helping!

```<code>import React, {useState, useRef, useEffect} from 'react'
import {ImPlay2} from "react-icons/im"
import {ImStop} from "react-icons/im"
import styled from "styled-components"
import drums from '../loopfiles/DRUMS.mp3'
//import other audio files//

const AudioPlayer = () => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLooping, setIsLooping] = useState(false);
    const [isOnMute, setIsOnMute] = useState(false);
    const audioRef = useRef(new Audio(drums));

    useEffect(() => {
        if (isOnMute) {
            audioRef.current.volume=0;
        }
        else {
            audioRef.current.volume=1;
        }
      }, [isOnMute]);
    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
        } else {
            audioRef.current.pause();
            audioRef.current.load();
        }
      }, [isPlaying]);
      useEffect(() => {
        if (isLooping) {
            audioRef.current.loop = true;
        } else {
            audioRef.current.loop = false;
        }
      }, [isLooping]);
  return (
    <div>
        {!isPlaying ? (
        <button type="button"
        className="play"
        onClick={() => setIsPlaying(true)}>
        <ImPlay2></ImPlay2> Play
        </button>
        ) : (
        <button type="button"
        className="pause"
        onClick={() => setIsPlaying(false)}>
        <ImStop></ImStop> Stop
        </button>
        )}
        <Flex>
            <Switcher selected={isLooping} />
            <Text
            onClick={() => setIsLooping(true)}>
            Loop
            </Text>
            <Text
            onClick={() => setIsLooping(false)}>
            Unloop
            </Text>
        </Flex>
        <Flex>
            <Switcher selected={isOnMute} />
            <Text
            onClick={() => setIsOnMute(true)}>
            Mute
            </Text>
            <Text
            onClick={() => setIsOnMute(false)}>
            UnMute
            </Text>
        </Flex>

    </div>
  )
}
const Flex = styled.div`
  margin-top: 5px;
  display: flex;
  align-items: center;
  border-radius: 2px;
  background: grey;
  height: 20px;
  width: 120px;
  position: relative;
  margin-bottom: 5px;
`;
const Switcher = styled.div`
  background: black;
  border-radius: 2px;
  height: 20px;
  line-height: 41px;
  width: 50%;
  cursor: pointer;
  position: absolute;
  transition: 0.5s;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  z-index: 1;
  left: ${({ selected }) =>
    selected === true ? "0px" : "60px"};
`;

const Text = styled.div`
  color: ${({ selected }) => (selected ? "black" : "white")};
  font-size: 13px;
  font-weight: 20;
  line-height: 4px;
  padding: 30;
  width: 50%;
  text-align: center;
  cursor: pointer;
`;
export default AudioPlayer
</code>```

答:
If you would like to mute/unmute individual sounds, but play/pause all sounds together, then you will need to create a mute/unmute slider for each sound. I can think of a number of ways to do this. The "best choice" might depend upon the standards in the rest of the application, how many sounds you're importing, and whether they're likely to change.

Method 1: One way to do this would be creating one array containing isOnMute values for each sound and another array containing all refs, and then map(...) over each of the elements of the isOnMute array to create your sliders.

Method 2: Another way would be to have one array of objects containing all sounds, and then the ref and the isOnMute values could be stored within each object. You could map(...) over that to create your sliders as well.

Method 3: You could also create separate child components for each sound like you said, and then pass the mute property between the parent AudioPlayer and the child AudioChannel components.

Then anytime the play/pause button is clicked, you would need to update each of the refs in the array (via a forEach or each of the child components via toggling a single isPlaying property).

Regardless of which you choose, I also might like to recommend the use-sound npm package. It makes managing multiple sounds and their properties a little bit less cumbersome in my opinion, including the ability to play and pause with a single method call.

Body:
I'm creating a small app that plays an audio file and have some functionalities (loop, stop, mute). My goal is to add some more audio files that all should be played and stopped at once (one button to control all), but each will have a mute button, and  I'm not sure what is the best practice to do so. I used useRef and thought maybe I need to set a refs array but how will I be able to start/stop them all at once, but still have the ability to control the mute separately?

This is my code so far. I guess I should split and have a different component for the audio sounds. Thanks for helping!

import React, {useState, useRef, useEffect} from 'react'
import {ImPlay2} from "react-icons/im"
import {ImStop} from "react-icons/im"
import styled from "styled-components"
import drums from '../loopfiles/DRUMS.mp3'
//import other audio files//

const AudioPlayer = () => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLooping, setIsLooping] = useState(false);
    const [isOnMute, setIsOnMute] = useState(false);
    const audioRef = useRef(new Audio(drums));

    useEffect(() => {
        if (isOnMute) {
            audioRef.current.volume=0;
        }
        else {
            audioRef.current.volume=1;
        }
      }, [isOnMute]);
    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
        } else {
            audioRef.current.pause();
            audioRef.current.load();
        }
      }, [isPlaying]);
      useEffect(() => {
        if (isLooping) {
            audioRef.current.loop = true;
        } else {
            audioRef.current.loop = false;
        }
      }, [isLooping]);
  return (

        {!isPlaying ? (
        <button type="button"
        className="play"
        onClick={() => setIsPlaying(true)}>
        <ImPlay2></ImPlay2> Play
        </button>
        ) : (
        <button type="button"
        className="pause"
        onClick={() => setIsPlaying(false)}>
        <ImStop></ImStop> Stop
        </button>
        )}
        <Flex>
            <Switcher selected={isLooping} />
            <Text
            onClick={() => setIsLooping(true)}>
            Loop
            </Text>
            <Text
            onClick={() => setIsLooping(false)}>
            Unloop
            </Text>
        </Flex>
        <Flex>
            <Switcher selected={isOnMute} />
            <Text
            onClick={() => setIsOnMute(true)}>
            Mute
            </Text>
            <Text
            onClick={() => setIsOnMute(false)}>
            UnMute
            </Text>
        </Flex>

  )
}
const Flex = styled.div`
  margin-top: 5px;
  display: flex;
  align-items: center;
  border-radius: 2px;
  background: grey;
  height: 20px;
  width: 120px;
  position: relative;
  margin-bottom: 5px;
`;
const Switcher = styled.div`
  background: black;
  border-radius: 2px;
  height: 20px;
  line-height: 41px;
  width: 50%;
  cursor: pointer;
  position: absolute;
  transition: 0.5s;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  z-index: 1;
  left: ${({ selected }) =>
    selected === true ? "0px" : "60px"};
`;

const Text = styled.div`
  color: ${({ selected }) => (selected ? "black" : "white")};
  font-size: 13px;
  font-weight: 20;
  line-height: 4px;
  padding: 30;
  width: 50%;
  text-align: center;
  cursor: pointer;
`;
export default AudioPlayer


问:
html css svg path align center on screen
I want to show dynamically svg but every time svg position is changing and sometimes overflowing from screen. I want to alignt this svg path center of screen.

```<code>function App() {
  const [city, setCity] = useState("");

  useEffect(() => {
    setCity(cities[Math.floor(Math.random() * cities.length)]);
  }, []);

  return (
    <div>
      <div className="svg-div">
        <svg height="100%" width="100%" className="svg" viewBox="0 0 600 600">
          <g>
            <path id="city" d={city?.d} />
          </g>
        </svg>
      </div>

      <Input cities={cities} />
    </div>
  );
}

export default App;
</code>```

答:
Add this css
. svg-div{
display: flex:
justify-content: center;
align-items: center;
}</p>

Body:
I want to show dynamically svg but every time svg position is changing and sometimes overflowing from screen. I want to alignt this svg path center of screen.

function App() {
  const [city, setCity] = useState("");

  useEffect(() => {
    setCity(cities[Math.floor(Math.random() * cities.length)]);
  }, []);

  return (

        <svg height="100%" width="100%" className="svg" viewBox="0 0 600 600">
          <g>
            <path id="city" d={city?.d} />
          </g>
        </svg>

      <Input cities={cities} />

  );
}

export default App;


问:
How to delete an element from a list in Julia?
```<code>v = range(1e10, -1e10, step=-1e8) # velocities [cm/s]
deleteat!(v, findall(x->x==0,v))
</code>```

I want to delete the value 0 from v. Following this tutorial, I tried deleteat! but I get the error

```<code>MethodError: no method matching deleteat!(::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}, ::Vector{Int64})
</code>```

What am I missing here?

答:
Use filter! or filter:

```<code>
julia> filter!(!=(0), [1,0,2,0,4])
3-element Vector{Int64}:
 1
 2
 4
</code>```

In case of a range you can collect it or use:

```<code>julia> filter(!=(0), range(2, -2, step=-1))
4-element Vector{Int64}:
  2
  1
 -1
 -2
</code>```

However for big ranges you might just not want to materialize them to save the memory footprint. In that case you could use:

```<code>(x for x in range(2, -2, step=-1) if x !== 0)
</code>```

To see what is being generated you need to collect it:

```<code>julia> collect(x for x in range(2, -2, step=-1) if x !== 0)
4-element Vector{Int64}:
  2
  1
 -1
 -2
</code>```

Body:
v = range(1e10, -1e10, step=-1e8) # velocities [cm/s]
deleteat!(v, findall(x->x==0,v))

I want to delete the value 0 from v. Following this tutorial, I tried deleteat! but I get the error

MethodError: no method matching deleteat!(::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}, ::Vector{Int64})

What am I missing here?

Body:
Use filter! or filter:

julia> filter!(!=(0), [1,0,2,0,4])
3-element Vector{Int64}:
 1
 2
 4

In case of a range you can collect it or use:

julia> filter(!=(0), range(2, -2, step=-1))
4-element Vector{Int64}:
  2
  1
 -1
 -2

However for big ranges you might just not want to materialize them to save the memory footprint. In that case you could use:

(x for x in range(2, -2, step=-1) if x !== 0)

To see what is being generated you need to collect it:

julia> collect(x for x in range(2, -2, step=-1) if x !== 0)
4-element Vector{Int64}:
  2
  1
 -1
 -2


问:
JqueryUI autocomplete in Rails3
```<code>$(document).ready ->
  $('#auto').autocomplete( source: "main/search" )
</code>```

the code beyond set up the autocomplete env,'#auto' is an input filed.

In my main controller I got the search action

```<code>def search
  @user = User.find_by_name 'castiel'
  respond_to do |format|
    format.json { render :json => @user.to_json(:only => :name) }
  end
end
</code>```

everything seems working perfectly fine.When I type in a char,let's say a "c",so the ajax request was sent and received the json data.

In firebug, it shows the ajax request successfully get the json data below

```<code>{"name":"castiel"}
</code>```

so far so good,but the json data's type is not the kind that autocomplete demanded.It demands that json data is like below.

```<code>{"id":"castiel", "label":"castiel", "value":"castiel"}
</code>```

So here is problem,how to modify the josn data to the kind that I wanted.

答:
Rails allows you to serve JSON in any structure from your controller. When using the jQuery autocomplete helper, you serve JSON back in the format needed by using the autocomplete library method json_for_autocomplete as follows:

```<code># app/controllers/example_controller.rb

def autocomplete_example
  items = Example.where(...)
  respond_to do |format|
    format.json do
      render :json => json_for_autocomplete(items, 'name', [])
    end
  end
end
</code>```

The first argument to json_for_autocomplete is your collection of objects to return. The second is the method to call on those objects to define the values in the JSON hash. The final argument is for any extra options, which can be found at:

https://github.com/crowdint/rails3-jquery-autocomplete/blob/master/lib/rails3-jquery-autocomplete/autocomplete.rb

Title: JqueryUI autocomplete in Rails3

Body:
$(document).ready ->
  $('#auto').autocomplete( source: "main/search" )

the code beyond set up the autocomplete env,'#auto' is an input filed.

In my main controller I got the search action

def search
  @user = User.find_by_name 'castiel'
  respond_to do |format|
    format.json { render :json => @user.to_json(:only => :name) }
  end
end

everything seems working perfectly fine.When I type in a char,let's say a "c",so the ajax request was sent and received the json data.

In firebug, it shows the ajax request successfully get the json data below

{"name":"castiel"}

so far so good,but the json data's type is not the kind that autocomplete demanded.It demands that json data is like below.

{"id":"castiel", "label":"castiel", "value":"castiel"}

So here is problem,how to modify the josn data to the kind that I wanted.

Body:
Rails allows you to serve JSON in any structure from your controller. When using the jQuery autocomplete helper, you serve JSON back in the format needed by using the autocomplete library method json_for_autocomplete as follows:

# app/controllers/example_controller.rb

def autocomplete_example
  items = Example.where(...)
  respond_to do |format|
    format.json do
      render :json => json_for_autocomplete(items, 'name', [])
    end
  end
end

The first argument to json_for_autocomplete is your collection of objects to return. The second is the method to call on those objects to define the values in the JSON hash. The final argument is for any extra options, which can be found at:

https://github.com/crowdint/rails3-jquery-autocomplete/blob/master/lib/rails3-jquery-autocomplete/autocomplete.rb


问:
Displaying a different option than selected value in MUI's autocomplete
Hello hello StackOverflow. Today I have a burning problem that needs an answer.

So I've been trying to make this work for the past week now, to no avail.

So the issue I am facing is I am trying to make an autocomplete using MUI's autocomplete component, but I want it to act a little different.

I want it to show auto complete options, and when you click them it insteads doesn't use the label value but instead the id value. But I also want it to be able to accept manual input aswell. So for example copying in stuff, or just writing it in instead of picking an autocomplete option.

This is what i've tried so far in terms of code:

```<code>    const [callNumber, setCallNumber] = useState("")
    const updateCallNumber = (_event: React.SyntheticEvent<Element, Event>, value: any) => {
      console.log(value.number)
      setCallNumber(value.number)
    }

        <Autocomplete
        id="free-solo-demo"
        freeSolo
        onChange={updateCallNumber}
        value={callNumber}
        options={contactsData}
        getOptionLabel={(option) => option.name}
        isOptionEqualToValue={(option, value) => option.name === value.name}
        renderInput={(params) => <TextField
          {...params}
          label="Number"
          variant="standard"
          InputProps={{
            ...params.InputProps,
            startAdornment: (
              <>
              <InputAdornment position="start">
                <CallIcon />
              </InputAdornment>
              {params.InputProps.startAdornment}
              </>
            )
            }}
          />
        }
      />
</code>```

P.S contactsData is an array that consists of ID, Name, Number

Thanks for reading, and kind regards

Klaus.

答:
You need to use the inputValue (property of Autocomplete) to display the value you want and keep the onChange and the value.

I code an sample that you can try :

```<code>import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export const friends = [
  { value: "Etienne", inputProps: "toto" },
  { value: "Deborah", inputProps: "tata" },
  { value: "Geneviève", inputProps: "titi" },
];

const initialState = { value: "", inputProps: "" };

export default function ControllableStates() {
  const [selected, setSelected] = useState(initialState);

  const getFirendsValue = () => {
    return friends.map((friend) => friend.value);
  };

  const getFriendSelecter = (value) => {
    return friends.filter((item) => item.value === value);
  };

  const handleChange = (newValue) => {
    if (newValue === null) {
      return setSelected(initialState);
    }
    const newState = getFriendSelecter(newValue);
    return setSelected(...newState);
  };

  return (
    <>
      <Autocomplete
        disablePortal
        id="demo"
        options={getFirendsValue()}
        value={selected.value}
        inputValue={selected.inputProps}
        sx={{ width: 300 }}
        onChange={(e, newValue) => handleChange(newValue)}
        renderInput={(params) => (
          <TextField {...params} label="Recommandé par" />
        )}
      />
    </>
  );
}
</code>```

Say me if it's good for you

Body:
Hello hello StackOverflow. Today I have a burning problem that needs an answer.

So I've been trying to make this work for the past week now, to no avail.

So the issue I am facing is I am trying to make an autocomplete using MUI's autocomplete component, but I want it to act a little different.

I want it to show auto complete options, and when you click them it insteads doesn't use the label value but instead the id value. But I also want it to be able to accept manual input aswell. So for example copying in stuff, or just writing it in instead of picking an autocomplete option.

This is what i've tried so far in terms of code:

    const [callNumber, setCallNumber] = useState("")
    const updateCallNumber = (_event: React.SyntheticEvent<Element, Event>, value: any) => {
      console.log(value.number)
      setCallNumber(value.number)
    }

        <Autocomplete
        id="free-solo-demo"
        freeSolo
        onChange={updateCallNumber}
        value={callNumber}
        options={contactsData}
        getOptionLabel={(option) => option.name}
        isOptionEqualToValue={(option, value) => option.name === value.name}
        renderInput={(params) => <TextField
          {...params}
          label="Number"
          variant="standard"
          InputProps={{
            ...params.InputProps,
            startAdornment: (
              <>
              <InputAdornment position="start">
                <CallIcon />
              </InputAdornment>
              {params.InputProps.startAdornment}
              </>
            )
            }}
          />
        }
      />

P.S contactsData is an array that consists of ID, Name, Number

Thanks for reading, and kind regards

Klaus.

Body:
You need to use the inputValue (property of Autocomplete) to display the value you want and keep the onChange and the value.

I code an sample that you can try :

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export const friends = [
  { value: "Etienne", inputProps: "toto" },
  { value: "Deborah", inputProps: "tata" },
  { value: "Geneviève", inputProps: "titi" },
];

const initialState = { value: "", inputProps: "" };

export default function ControllableStates() {
  const [selected, setSelected] = useState(initialState);

  const getFirendsValue = () => {
    return friends.map((friend) => friend.value);
  };

  const getFriendSelecter = (value) => {
    return friends.filter((item) => item.value === value);
  };

  const handleChange = (newValue) => {
    if (newValue === null) {
      return setSelected(initialState);
    }
    const newState = getFriendSelecter(newValue);
    return setSelected(...newState);
  };

  return (
    <>
      <Autocomplete
        disablePortal
        id="demo"
        options={getFirendsValue()}
        value={selected.value}
        inputValue={selected.inputProps}
        sx={{ width: 300 }}
        onChange={(e, newValue) => handleChange(newValue)}
        renderInput={(params) => (
          <TextField {...params} label="Recommandé par" />
        )}
      />
    </>
  );
}

Say me if it's good for you


问:
Sum of numbers in a Python list except 13 and numbers after it
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

```<code>def sum13(nums):
  if nums == []:
    return 0
  sum=0
  for i in range(len(nums)):
    if nums[i] == 13:
      break
  else:
    sum = sum+nums[i]
  return sum
</code>```

The above code is failing only at:

sum13([1, 2, 13, 2, 1, 13]) → 4 while my answer is 3 (how 4?)

sum13([13, 1, 2, 13, 2, 1, 13]) → 3  while my answer is 0 (again, how is 3 correct if there are no numbers before 13?)
Please explain the logic and what I've done wrong.

答:
If you´re surfing through stacks trying to find some elegant solution, here´s mine:</p>
```<code>def sum13(nums):

  if nums == 0:
    return 0
  soma = 0
  i = 0

  while i < len(nums):
    if nums[i] == 13:
      i += 2
      continue
    else:
      soma += nums[i]
      i += 1
  return soma
</code>```

Body:
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

def sum13(nums):
  if nums == []:
    return 0
  sum=0
  for i in range(len(nums)):
    if nums[i] == 13:
      break
  else:
    sum = sum+nums[i]
  return sum

The above code is failing only at:

sum13([1, 2, 13, 2, 1, 13]) → 4 while my answer is 3 (how 4?)

sum13([13, 1, 2, 13, 2, 1, 13]) → 3  while my answer is 0 (again, how is 3 correct if there are no numbers before 13?)
Please explain the logic and what I've done wrong.

Body:
If you´re surfing through stacks trying to find some elegant solution, here´s mine:

def sum13(nums):

  if nums == 0:
    return 0
  soma = 0
  i = 0

  while i < len(nums):
    if nums[i] == 13:
      i += 2
      continue
    else:
      soma += nums[i]
      i += 1
  return soma


问:
showip: command not found
I am trying to run one of the example from Beej's Guide to Network Programming (https://beej.us/guide/bgnet/), specifically showip.c (The link to the program is here: https://beej.us/guide/bgnet/examples/showip.c). Using gcc, I've typed in

```<code>gcc -o showip showip.c
</code>```

Then ran the program

```<code>showip www.example.net
</code>```

and I get an error showip: command not found on the same directory where the code and the program is compiled at. I'm not sure why this is the case. I've even cloned the code from his GitHub and used makefile to compile the program and yet I'm getting the same error. What exactly am I doing it wrong here?

答:
Since the program showip is not in your $PATH you have to tell
your shell that it's in the current directory:

```<code>./showip
</code>```

Or add the current directory to your $PATH but it's a less secure
option:

```<code>PATH=:$PATH
</code>```

or

```<code>PATH=.:$PATH
</code>```

and run it as you're trying now:

```<code>showip
</code>```

Title: showip: command not found

Body:
I am trying to run one of the example from Beej's Guide to Network Programming (https://beej.us/guide/bgnet/), specifically showip.c (The link to the program is here: https://beej.us/guide/bgnet/examples/showip.c). Using gcc, I've typed in

gcc -o showip showip.c

Then ran the program

showip www.example.net

and I get an error showip: command not found on the same directory where the code and the program is compiled at. I'm not sure why this is the case. I've even cloned the code from his GitHub and used makefile to compile the program and yet I'm getting the same error. What exactly am I doing it wrong here?

Body:
Since the program showip is not in your $PATH you have to tell
your shell that it's in the current directory:

./showip

Or add the current directory to your $PATH but it's a less secure
option:

PATH=:$PATH

or

PATH=.:$PATH

and run it as you're trying now:

showip


答:
Is the working directory on your path?  Likely not.

Try ./showip

Title: showip: command not found


问:
How to write unit test for URI create in java
Below is the method I'm trying to write unit test using junit 5

```<code>@Value("${proxy.host}")
    private String endpoint;

public Request<Void> setAwsRequestGETParameter(String setStatusPath) {
        Request<Void> requestAws = new DefaultRequest<Void>("sts");
        requestAws.setHttpMethod(HttpMethodName.GET);
        requestAws.setEndpoint(URI.create(endpoint));
        requestAws.setResourcePath(setStatusPath);
        return requestAws;
    }
</code>```

Below is the unit test I'm trying to run

```<code>@InjectMocks
    private AWSAuthHandler testAWSAuthHandler;

@Test
    public void testSetAwsRequestGETParameter() throws Exception {
        URI mockedURI = Mockito.mock(URI.class);
        assertNotNull(testAWSAuthHandler.setAwsRequestGETParameter("/status/7deaed5e-3080-45ec-89ba-403977d60c0c"));
    }
</code>```

Below is the stack trace:

```<code>java.lang.NullPointerException
    at java.base/java.net.URI$Parser.parse(URI.java:3106)
    at java.base/java.net.URI.<init>(URI.java:600)
    at java.base/java.net.URI.create(URI.java:881)
</code>```

Can someone please help me with the missing part? Thank you

答:
For setting properties of class that you can't mock you can use Spring Reflection Utils, like that:

```<code>ReflectionUtils.setField(field, target, value);
</code>```

where the field is the name of the field which you want to set ("endpoint" for your case),

target is the mocked class (testAWSAuthHandler for your case)

value is the wanted value

Body:
Below is the method I'm trying to write unit test using junit 5

@Value("${proxy.host}")
    private String endpoint;

public Request<Void> setAwsRequestGETParameter(String setStatusPath) {
        Request<Void> requestAws = new DefaultRequest<Void>("sts");
        requestAws.setHttpMethod(HttpMethodName.GET);
        requestAws.setEndpoint(URI.create(endpoint));
        requestAws.setResourcePath(setStatusPath);
        return requestAws;
    }

Below is the unit test I'm trying to run

@InjectMocks
    private AWSAuthHandler testAWSAuthHandler;

@Test
    public void testSetAwsRequestGETParameter() throws Exception {
        URI mockedURI = Mockito.mock(URI.class);
        assertNotNull(testAWSAuthHandler.setAwsRequestGETParameter("/status/7deaed5e-3080-45ec-89ba-403977d60c0c"));
    }

Below is the stack trace:

java.lang.NullPointerException
    at java.base/java.net.URI$Parser.parse(URI.java:3106)
    at java.base/java.net.URI.<init>(URI.java:600)
    at java.base/java.net.URI.create(URI.java:881)

Can someone please help me with the missing part? Thank you

Body:
For setting properties of class that you can't mock you can use Spring Reflection Utils, like that:

ReflectionUtils.setField(field, target, value);

where the field is the name of the field which you want to set ("endpoint" for your case),

target is the mocked class (testAWSAuthHandler for your case)

value is the wanted value


问:
Reading a txt file into a list without newlines in python
I have a txt file that looks like this:

```<code>FSDAF
HKLWF
AAKEP
</code>```

How can I read that into a list so it looks like this:
lst = ['FSDAF', 'HKLWF', 'AAKEP']

I did something like this but I cant get rid of the newlines:

```<code>file = open('dane.txt', 'r')
lst = file.readlines()
</code>```

And it displays the newlines like this:

```<code>['FSDAF\n', 'HKLWF\n', 'AAKEP\n']
</code>```

答:
You can use .rstrip():

data = ['FSDAF\n', 'HKLWF\n', 'AAKEP\n']
print([line.rstrip() for line in data])
```

Body:
I have a txt file that looks like this:

FSDAF
HKLWF
AAKEP

How can I read that into a list so it looks like this:
lst = ['FSDAF', 'HKLWF', 'AAKEP']

I did something like this but I cant get rid of the newlines:

file = open('dane.txt', 'r')
lst = file.readlines()

And it displays the newlines like this:

['FSDAF\n', 'HKLWF\n', 'AAKEP\n']


问:
Linking to different areas on a page
This may seem like a stupid question, but:

So what i would like to do is set up a menu section so that when the user clicked on the title of the section it would send them to that particular spot on the page with out having to scoll down. I am not entirely sure how this would work or how complicated it is to achieve.

So bacially i would have

Menu

item one (be a link)

item two (be a link)

etc (be a link)

then further down the page

item one (when item one in menu is clicked page comes to here)

"details about it here"

item two (when item two in menu is clicked page comes to here)

"details here"

How exactly would i go about doing this?

Any help or suggestions are greatly appreciated. Thanks.

答: If you're asking what I think you're asking, you just use anchor tags lower down the page as described in this article here</p>

Title: Linking to different areas on a page


答:
As Sweta Sharma said, you need to initialise AWSAuthHandler with some value for endpoint field. That's why it is better to use constructor injection rather than field one.

Assuming your AWSAuthHandler class look like this (as you didn't provide the code for the whole class):

public class AWSAuthHandler {

    @Value("${proxy.host}")
    private String endpoint;

    public Request<Void> setAwsRequestGETParameter(String setStatusPath) {
        Request<Void> requestAws = new DefaultRequest<Void>("sts");
        requestAws.setHttpMethod(HttpMethodName.GET);
        requestAws.setEndpoint(URI.create(endpoint));
        requestAws.setResourcePath(setStatusPath);
        return requestAws;
    }
```
<p>You can refactor it in the following way:</p>
<pre class="lang-java prettyprint-override"><code>public class AWSAuthHandler {

    private String endpoint;

    public AWSAuthHandler(@Value("${proxy.host}") String endpoint) {
        this.endpoint = endpoint;
    }

    public Request<Void> setAwsRequestGETParameter(String setStatusPath) {
        Request<Void> requestAws = new DefaultRequest<Void>("sts");
        requestAws.setHttpMethod(HttpMethodName.GET);
        requestAws.setEndpoint(URI.create(endpoint));
        requestAws.setResourcePath(setStatusPath);
        return requestAws;
    }
</code>```

Then you can create tests for this class:

private AWSAuthHandler testAWSAuthHandler;

@BeforeEach
void setUpTests() {
    this.testAWSAuthHandler = new AWSAuthHandler("some-endpoint-here");
}

@Test
public void testSetAwsRequestGETParameter() throws Exception {
   assertNotNull(testAWSAuthHandler.setAwsRequestGETParameter("/status/7deaed5e-3080-45ec-89ba-403977d60c0c"));
}
```

You can read more about Spring @Value annotation here, for example: https://www.baeldung.com/spring-value-annotation

Title: How to write unit test for URI create in java

Body:
As Sweta Sharma said, you need to initialise AWSAuthHandler with some value for endpoint field. That's why it is better to use constructor injection rather than field one.

Assuming your AWSAuthHandler class look like this (as you didn't provide the code for the whole class):

public class AWSAuthHandler {

    @Value("${proxy.host}")
    private String endpoint;

    public Request<Void> setAwsRequestGETParameter(String setStatusPath) {
        Request<Void> requestAws = new DefaultRequest<Void>("sts");
        requestAws.setHttpMethod(HttpMethodName.GET);
        requestAws.setEndpoint(URI.create(endpoint));
        requestAws.setResourcePath(setStatusPath);
        return requestAws;
    }

You can refactor it in the following way:

public class AWSAuthHandler {

    private String endpoint;

    public AWSAuthHandler(@Value("${proxy.host}") String endpoint) {
        this.endpoint = endpoint;
    }

    public Request<Void> setAwsRequestGETParameter(String setStatusPath) {
        Request<Void> requestAws = new DefaultRequest<Void>("sts");
        requestAws.setHttpMethod(HttpMethodName.GET);
        requestAws.setEndpoint(URI.create(endpoint));
        requestAws.setResourcePath(setStatusPath);
        return requestAws;
    }

Then you can create tests for this class:

private AWSAuthHandler testAWSAuthHandler;

@BeforeEach
void setUpTests() {
    this.testAWSAuthHandler = new AWSAuthHandler("some-endpoint-here");
}

@Test
public void testSetAwsRequestGETParameter() throws Exception {
   assertNotNull(testAWSAuthHandler.setAwsRequestGETParameter("/status/7deaed5e-3080-45ec-89ba-403977d60c0c"));
}

You can read more about Spring @Value annotation here, for example: https://www.baeldung.com/spring-value-annotation


问:
How do I translate a word received from the Api into another language?
I get the name of the city from the api, but unfortunately there is no type translation function in the api (lang=en). I get the name of the city written in English, but written translated into my language, but I want the correct language to be used</p>
```<code>MY_API:
data class WeatherLocation(
    val country: String,
    val lat: Double,
    @SerializedName("localtime_epoch")
    val localtimeEpoch: Long,
    val lon: Double,
    val name: String,
    val region: String,
    @SerializedName("tz_id")
    val tzId: String

)

    private fun updateCondition(condition: String) {
                textView_condition.text = condition
            }
</code>```

答: You are able to make requests in java with a lot of API-s on internet about this, Just search.</p>

Body:
I get the name of the city from the api, but unfortunately there is no type translation function in the api (lang=en). I get the name of the city written in English, but written translated into my language, but I want the correct language to be used

MY_API:
data class WeatherLocation(
    val country: String,
    val lat: Double,
    @SerializedName("localtime_epoch")
    val localtimeEpoch: Long,
    val lon: Double,
    val name: String,
    val region: String,
    @SerializedName("tz_id")
    val tzId: String

)

    private fun updateCondition(condition: String) {
                textView_condition.text = condition
            }


答:
You can open it...

```<code>with open('dane.txt', 'r') as file:
    ...
</code>```

...then (into the with/as block) read the file...

```<code>content = file.read()
</code>```

...then split it into a list:

```<code>myList = content.split('\n')
</code>```

Title: Reading a txt file into a list without newlines in python

Body:
You can open it...

with open('dane.txt', 'r') as file:
    ...

...then (into the with/as block) read the file...

content = file.read()

...then split it into a list:

myList = content.split('\n')


答:
This is actually problem with how you're running the program.

On Linux systems (unlike Windows systems) an executable in the current directory is not by default searched by the shell for programs to run.  If the given program does not contain a path element (i.e. there are no / characters in the name) then only the directories listed in the PATH environment variable are searched.

Since the current directory is not part of your PATH, prefix the command with the directory:

```<code>./showip www.example.net
</code>```

Title: showip: command not found

Body:
This is actually problem with how you're running the program.

On Linux systems (unlike Windows systems) an executable in the current directory is not by default searched by the shell for programs to run.  If the given program does not contain a path element (i.e. there are no / characters in the name) then only the directories listed in the PATH environment variable are searched.

Since the current directory is not part of your PATH, prefix the command with the directory:

./showip www.example.net


问:
Append rows of same data and Transpose it into columns
I have created a dataframe from an excel sheet using pandas. The issue with this data frame is the data structure provided to me. The data structure is somewhat complex where the same data types were given in rows structure. So I had to use df.transpose() to first transpose the data, but the issue occurs after transposing the data. so I am getting the data in multiple split sections and I need to append the transposed data in single columns.
Before Transpose of data

Data after Transposing

Needed output

Update fixed the issue:
Attaching the below code for reference.

df_in = pd.read_csv('sample_copy2.csv',index_col=['Year'])
df_t =df_in.transpose(copy=True)
print(df_t)

df = df_t
s = df.columns.to_series()

df.columns = [df.columns, s.groupby(s).cumcount()]
dft = df.stack().sort_index(level=1).fillna(0).reset_index(level=1, drop=True).reset_index()
df_f=dft.set_index('index')

print(df_f)

答:
since you haven't provided any reproducible code, we wouldn't be able to provide any solution as a code. However, I can answer at high level.

The transpose that you have done is absolutely right. Why don't you make a new data frame with the repeated data from columns E, F, G, H and then concat the two data frame. For concat in pandas go to this link: https://pandas.pydata.org/docs/reference/api/pandas.concat.html

Hope this is helpful.


问:
How to define Ordering[Array[Byte]]?
Is it necessary to provide the implementation from scratch? I could not find any matching implicit, not even in last-resort Implicits trait. seqDerivedOrdering obviously doesn't work, since Array is not a Seq.

答:
If you want it to be efficient, you'll have to write your own (this one handles nulls; if you can assume no nulls, just use the long else block):

```<code>val o = new math.Ordering[Array[Byte]] {
  def compare(a: Array[Byte], b: Array[Byte]): Int = {
    if (a eq null) {
      if (b eq null) 0
      else -1
    }
    else if (b eq null) 1
    else {
      val L = math.min(a.length, b.length)
      var i = 0
      while (i < L) {
        if (a(i) < b(i)) return -1
        else if (b(i) < a(i)) return 1
        i += 1
      }
      if (L < b.length) -1
      else if (L < a.length) 1
      else 0
    }
  }
}
</code>```

Otherwise, you can .toSeq to package into a WrappedArray and defer to a Seq compare instead of doing your own scan.  (This will end up boxing and unboxing your bytes, which is why it's not efficient.  Since byte boxing is generally done by lookup in a table of all bytes, it's not horribly inefficent, so you may be able to get away with it unless you're doing e.g. heavy duty binary file processing.)

Title: How to define Ordering[Array[Byte]]?

Body:
If you want it to be efficient, you'll have to write your own (this one handles nulls; if you can assume no nulls, just use the long else block):

val o = new math.Ordering[Array[Byte]] {
  def compare(a: Array[Byte], b: Array[Byte]): Int = {
    if (a eq null) {
      if (b eq null) 0
      else -1
    }
    else if (b eq null) 1
    else {
      val L = math.min(a.length, b.length)
      var i = 0
      while (i < L) {
        if (a(i) < b(i)) return -1
        else if (b(i) < a(i)) return 1
        i += 1
      }
      if (L < b.length) -1
      else if (L < a.length) 1
      else 0
    }
  }
}

Otherwise, you can .toSeq to package into a WrappedArray and defer to a Seq compare instead of doing your own scan.  (This will end up boxing and unboxing your bytes, which is why it's not efficient.  Since byte boxing is generally done by lookup in a table of all bytes, it's not horribly inefficent, so you may be able to get away with it unless you're doing e.g. heavy duty binary file processing.)


问:
Turn Pyspark DataFrame column to a list and return single value
Using Pyspark I would like to create a list out of a date column and get the max and min dates. However, when I use .collect(), I get a string containing not only the dates. Here is my code and the result that I get:

```<code>adjusted_end_date = max(df_adjusted_dates.select(col("MAX_DATE_TIME")).collect())
adjusted_start_date = min(df_adjusted_dates.select(col("ADJUSTED_DATE_TIME")).collect())

print(adjusted_end_date)
print(adjusted_start_date)
</code>```

Result:

```<code>Row(MAX_DATE_TIME=datetime.datetime(2019, 6, 25, 6, 56, 20, 406000))
Row(ADJUSTED_DATE_TIME=datetime.date(2019, 6, 11))
</code>```

How to get only the date/datetime part of the result?

答:
How about using this:</p>
```<code>val selectedColumnName = df.columns("columnName")
df.agg(min(selectedColumnName), max(selectedColumnName))
df.show()
</code>```

Body:
Using Pyspark I would like to create a list out of a date column and get the max and min dates. However, when I use .collect(), I get a string containing not only the dates. Here is my code and the result that I get:

adjusted_end_date = max(df_adjusted_dates.select(col("MAX_DATE_TIME")).collect())
adjusted_start_date = min(df_adjusted_dates.select(col("ADJUSTED_DATE_TIME")).collect())

print(adjusted_end_date)
print(adjusted_start_date)

Result:

Row(MAX_DATE_TIME=datetime.datetime(2019, 6, 25, 6, 56, 20, 406000))
Row(ADJUSTED_DATE_TIME=datetime.date(2019, 6, 11))

How to get only the date/datetime part of the result?

Body:
How about using this:

val selectedColumnName = df.columns("columnName")
df.agg(min(selectedColumnName), max(selectedColumnName))
df.show()


问:
How to hide certain texts retrieved from Strings.xml
I have an English teaching app where the users are given some sentences with their Turkish equivalents. I retrieve the data from Strings.xml as follows:

<.b>Possession (Aitlik)\n\nhave
        (sahip olmak)\npossess (sahip olmak)\nown (sahip olmak)\nbelong (ait olmak)\nconsist (-den meydana gelmek)\nlack (eksik olmak)\ninvolve
        (içermek)\n\n<.b>Emotions (Duygular)\n\nlike (sevmek)\ndislike (sevmemek)\nprefer (tercih etmek)\nappreciate (takdir etmek)\nneed
        (ihtiyacı olmak)\nwish (istemek, dilemek)\nhope (ummak)\nvalue (değer vermek)\nadore (hayran olmak)\nfear (korkmak)\nsurprise (şaşırtmak)\nenvy
        (kıskanmak)\nhate (nefret etmek)\nlove (sevmek)\n\n
    ...
```
<p>If the user wishes, I'd like to hide the translations of the words. Is there a way to do it? So far, I tried separating the example sentences from their translations and hiding the translations from the code:</p>
<pre class="lang-xml prettyprint-override"><code><string name=header_one>"<.b>Possession</b>"</string>
<string name=header_one_translation>"<.b>Aitlik</b>"</string>
</code>```

binding.hideTranslationsButton.setOnClickListener {
            binding.headerOneTranslation.isGone = true
            binding.translationOne.isGone = true
            binding.translationTwo.isGone = true
            binding.translationThree.isGone = true
            binding.translationFour.isGone = true
            binding.translationFive.isGone = true
            binding.translationSix.isGone = true
            ...
        }
```

but it took too much time and it feels like my code has gotten messier considering I have 50 other grammar topics like this (I put dots intentionally --> <.b>).

答:
You can use a regex like

```<code>(\(.*\)) *(.*)
</code>```

It simply says there is a group (first parenthesis pair - group 1) inside that we expect
a opening parenthesis \(

then anything except linebreak . with any count * (probably + is even better instead of * so it can skip empty items)

then we expect a closing parentheses \)

then there might be some spaces which we don't care about  *

and then another group (group 2) which is whatever with any count .* (again, + seems more suitable)

So you can use something like

```<code>"(\(.+\)) *(.+)".toRegex().matches(getString(R.string.blah_blah)).forEach{
    val en = it.groups[1]
    val tr = it.groups[2]
}
</code>```

Body:
I have an English teaching app where the users are given some sentences with their Turkish equivalents. I retrieve the data from Strings.xml as follows:

<.b>Possession (Aitlik)\n\nhave
        (sahip olmak)\npossess (sahip olmak)\nown (sahip olmak)\nbelong (ait olmak)\nconsist (-den meydana gelmek)\nlack (eksik olmak)\ninvolve
        (içermek)\n\n<.b>Emotions (Duygular)\n\nlike (sevmek)\ndislike (sevmemek)\nprefer (tercih etmek)\nappreciate (takdir etmek)\nneed
        (ihtiyacı olmak)\nwish (istemek, dilemek)\nhope (ummak)\nvalue (değer vermek)\nadore (hayran olmak)\nfear (korkmak)\nsurprise (şaşırtmak)\nenvy
        (kıskanmak)\nhate (nefret etmek)\nlove (sevmek)\n\n
    ...

If the user wishes, I'd like to hide the translations of the words. Is there a way to do it? So far, I tried separating the example sentences from their translations and hiding the translations from the code:

<string name=header_one>"<.b>Possession"</string>
<string name=header_one_translation>"<.b>Aitlik"</string>

binding.hideTranslationsButton.setOnClickListener {
            binding.headerOneTranslation.isGone = true
            binding.translationOne.isGone = true
            binding.translationTwo.isGone = true
            binding.translationThree.isGone = true
            binding.translationFour.isGone = true
            binding.translationFive.isGone = true
            binding.translationSix.isGone = true
            ...
        }

but it took too much time and it feels like my code has gotten messier considering I have 50 other grammar topics like this (I put dots intentionally --> <.b>).

Body:
You can use a regex like

(\(.*\)) *(.*)

It simply says there is a group (first parenthesis pair - group 1) inside that we expect
a opening parenthesis \(

then anything except linebreak . with any count * (probably + is even better instead of * so it can skip empty items)

then we expect a closing parentheses \)

then there might be some spaces which we don't care about  *

and then another group (group 2) which is whatever with any count .* (again, + seems more suitable)

So you can use something like

"(\(.+\)) *(.+)".toRegex().matches(getString(R.string.blah_blah)).forEach{
    val en = it.groups[1]
    val tr = it.groups[2]
}


问:
How to trigger an on-prem Jenkins job when opening a PR on github
I have a public Github repo and an on-prem Jenkins server (this could not be changed)

I want a Jenkins job to start every time a PR is opened in the github repo.

Now, if my Jenkins had public access I will simply set up a webhook on github, but since github can not access my Jenkins what can I do to trigger the job?

Is there an option to set a webhook the other way around? meaning the Jenkins will check every few seconds/minutes if a PR was opened and if so it will trigger the job.

答:
You can configure the GitHub Pull Request Builder Plugin to poll for PR refspecs, although it works somewhat differently than using webhooks.

Alternatively, assuming you have connectivity from the on-premise environment to the outside, you can setup ngrok / webhook relay / smee to have a publicly-accessible address that forwards GitHub webhooks. CloudBees have a video on forwarding webhooks using ngrok.

If a DMZ is possible then using tunnels such as GitWebhookProxy, stunnel, or SSH are also good options.


问:
How can I make a set of numbers increase every second and for each increment, print the current set on a new line?
I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;

20220215155

20220215156

20220215157 etc...

I tried adding the n tag buh it returned an error.

```<code>var i = 20220215155
    function increment() {
    i+, + </n>;

document.getElementById('test').innerHTML = i
     }
  ('increment()', 1000);
</code>```

Please I really need help as I have been trying to get this for so long.

答:
Your code is not valid JS

Here is something that does work - I am using setInterval here

var i = 20220215155

function increment() {
  i++; // increment
  document.getElementById('test').innerHTML += i + "
"; // add it with a breakline
}
setInterval(increment, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

You can use a template literal for the string too

```<code>`${i}<br/>`
</code>```

Body:
I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;

20220215155

20220215156

20220215157 etc...

I tried adding the n tag buh it returned an error.

var i = 20220215155
    function increment() {
    i+, + </n>;

document.getElementById('test').innerHTML = i
     }
  ('increment()', 1000);

Please I really need help as I have been trying to get this for so long.

Body:
Your code is not valid JS

Here is something that does work - I am using setInterval here

var i = 20220215155

function increment() {
  i++; // increment
  document.getElementById('test').innerHTML += i + "<br/>"; // add it with a breakline
}
setInterval(increment, 1000);

<div id="test"></div>

You can use a template literal for the string too

`${i}<br/>`


问:
What is the difference between an ORM and an ODM?
I am trying to figure out what the difference is between ORM and ODM, as far as I understand the concept, ORM (Object Relational Mapper) maps the relations between data, where as ODM (Object Document Mapper) deals with documents. Am I right in assuming that mySQL is an example of ORM and MongoDB is a example of ODM?

As I am sure you can see, I am not too familiar with the theory of the concept. Could someone please clarify the differences between the two?

答:
To understand the difference between an ORM and an ODM, I think that it would be helpful to first review the differences between a relational database, and a document database. I'll do so in a hand-wavy way.

A relational database is the one that you're probably used to. The one that stores data in tables, like this:

Common examples of relational databases are MySQL, Postgres, and SQLite. To query a relational database, you'd use SQL.

What about document databases? Well, with document databases, data is stored in JSON instead of in tables.

Actually, that's not 100% accurate. MongoDB explains:

Documents store data in field-value pairs. The values can be a variety of types and structures, including strings, numbers, dates, arrays, or objects. Documents can be stored in formats like JSON, BSON, and XML.

Ok, so now, what is an ORM, what is an ODM, and how do they compare?

Well, ORM stands for... actually, I'll let this answer explain:

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".

Basically, in your application code, you are usually dealing with objects. But in your database, you have tables. An ORM is a library that maps between the two. As Wikipedia explains:

This creates, in effect, a "virtual object database" that can be used from within the programming language.

Here is an example. Active Record is a popular ORM for Ruby on Rails. With Active Record, you could do something like User.find_by(name: 'David') and get back something like { id: 1, name: 'David' }. So the ORM is doing the following mapping for you:

And then with an ODM, it's basically doing the same thing, except for document databases. It's mapping from the objects in your application code to the documents in the database. Mongoose is a good example of an ODM. It works with MongoDB.


答:
You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.

// Cache the element
const test = document.querySelector('#test');

let n = 20220215155;

// `increment` accepts `n` as an argument
function increment(n) {

  // Add a new HTML string to the element
  test.innerHTML += `${n}</br>`;

  // Call the function again with an new `n`
  setTimeout(increment, 1000, ++n);
}

increment(n);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

Additional documentation

Template/string literals

Title: How can I make a set of numbers increase every second and for each increment, print the current set on a new line?

Body:
You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.

// Cache the element
const test = document.querySelector('#test');

let n = 20220215155;

// `increment` accepts `n` as an argument
function increment(n) {

  // Add a new HTML string to the element
  test.innerHTML += `${n}</br>`;

  // Call the function again with an new `n`
  setTimeout(increment, 1000, ++n);
}

increment(n);

<div id="test"></div>

Additional documentation

Template/string literals