问:
How to access Huawei API gateway by authorization in swift?
As per Huawei API Gateway App Authentication documentation I'm trying to access an API through app authentication, standardize the request content, and then sign the request. As the client I must follow the same request specifications as API Gateway so that each HTTP request can obtain the same signing result from the frontend and backend to complete identity authentication.

I complete it using following class. However the documentation is really poor to understand. It returns error Incorrect app authentication information: Authorization format is incorrect APIG.0303.

I couldn't complete the process and I'm really thankful if you can give any sample to do this.

```<code>import Foundation
import CommonCrypto

public class SimpleHMACAuth {

    /// APP key to authenticate with
    public var appKey: String?

    /// Secret key to authenticate with
    public var secret: String?

    /// Algorithm to generate HMAC hash with
    public var algorithm: HMACAlgorithm = .sha256

    public enum HMACAlgorithm: String {
        case sha256 = "sha256"
        case sha512 = "sha512"
    }

    enum RequestSigningError: Error {
        case missingAPPKey
        case missingSecret
        case invalidAlgorithm
        case invalidURL
    }

    fileprivate let dateFormatter: DateFormatter

    /// Instantiate with an APP key and secret
    /// - Parameters:
    ///   - appKey: APP key
    ///   - secret: Secret key
    public convenience init(appKey: String, secret: String) {
        self.init()

        self.appKey = appKey
        self.secret = secret
    }

    /// Instantiate
    public init() {
        self.dateFormatter = DateFormatter()
        self.dateFormatter.dateFormat = "dd MMM yyyy HH:mm:ss zzz"
    }

    /// Returns a signed version of an input request
    /// - Parameter request: Request to sign
    /// - Throws: If the request, APP key, secret, or algorithm are invalid
    /// - Returns: Signed version of the request
    public func sign(_ request: URLRequest) throws -> URLRequest {

        guard let signedRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
            throw RequestSigningError.invalidURL
        }

        guard let appKey = self.appKey else {
            throw RequestSigningError.missingAPPKey
        }

        guard let secret = self.secret else {
            throw RequestSigningError.missingSecret
        }

        // Add the "Authorization" header

        signedRequest.addValue("APP key \(appKey)", forHTTPHeaderField: "Authorization")

        // Confirm the "Date" header exists, and add it if not

        if signedRequest.value(forHTTPHeaderField: "Date") == nil {

            signedRequest.addValue(self.dateFormatter.string(from: Date()), forHTTPHeaderField: "X-Sdk-Date")
        }

        // If this request has a body but does not yet have the "Content-Length" header, calculate and append it

        if let data = signedRequest.httpBody, signedRequest.value(forHTTPHeaderField: "Content-Length") == nil {

            signedRequest.addValue("\(data.count)", forHTTPHeaderField: "Content-Length")
        }

        // Canonicalize the request

        let canonicalized = try self.canonicalize(signedRequest as URLRequest)

        // Generate a signature from the canonicalized representation of the request

        let signature = try self.signature(canonicalized: canonicalized, secret: secret, algorithm: algorithm);

        // Append the "Signature" header

        signedRequest.addValue("SDK-HMAC-SHA256", forHTTPHeaderField: "Authorization")
        signedRequest.addValue(appKey, forHTTPHeaderField: "Access")
        signedRequest.addValue("SDK-HMAC-SHA256 \(signature)", forHTTPHeaderField: "Signature")

        return signedRequest as URLRequest
    }

    /// Generate a string for a request
    /// - Parameter request: Request to sign
    /// - Throws: Throws if request is invalid
    /// - Returns: Signed request
    internal func canonicalize(_ request: URLRequest) throws -> String {

        guard let url = request.url else {
            throw RequestSigningError.invalidURL
        }

        let method = (request.httpMethod ?? "GET").uppercased()
        var path = url.path
        let queryString = url.query != nil ? "?\(url.query!)" : ""
        let allHeaders = request.allHTTPHeaderFields ?? [String : String]()
        let data = request.httpBody ?? Data()

        if let component = URLComponents(string: url.absoluteString) {
            path = component.path
        }

        // Only sign these headers

        let allowedHeaders = [
            "authorization",
            "date",
            "content-length",
            "content-type"
        ]

        // Create a new list of headers, with the keys all lower case

        var headers = [String: String]();

        for (key, value) in allHeaders {

            let lowerCaseKey = key.lowercased()

            if allowedHeaders.contains(lowerCaseKey) == false {
                continue
            }

            if lowerCaseKey == "content-length" && value == "0" {
                continue
            }

            headers[lowerCaseKey] = value;
        }

        // Sort the header keys alphabetically

        let headerKeys = headers.keys.sorted()

        // Create a string of all headers, arranged alphabetically, seperated by newlines

        var headerString = ""

        for (index, key) in headerKeys.enumerated() {

            guard let value = headers[key] else {
                continue
            }

            headerString += "\(key):\(value)"

            if index != headerKeys.count - 1 {
                headerString += "\n"
            }
        }

        // Hash the data payload

        var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        data.withUnsafeBytes { bytes in
            _ = CC_SHA256(bytes.baseAddress, CC_LONG(data.count), &digest)
        }

        let dataHash = Data(digest).map { String(format: "%02hhx", $0) }.joined()

        // Combine all components of this request into a string

        let components: [String] = [method, path, queryString, headerString, dataHash]

        return components.joined(separator: "\n");
    }

    /// Generate a HMAC hash for a canonicalized request
    /// - Parameters:
    ///   - canonicalized: canonicalized version of a request
    ///   - secret: Secret key
    ///   - algorithm: Algorithm to use to generate the hmac
    /// - Throws: If algorithm is not supported
    /// - Returns: Signature for the request
    internal func signature(canonicalized: String, secret: String, algorithm: HMACAlgorithm) throws -> String {

        let supportedAlgorithms = ["sha1":   (kCCHmacAlgSHA1,   CC_SHA1_DIGEST_LENGTH),
                                   "sha256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
                                   "sha512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]

        guard let (algorithmKey, digestLength) = supportedAlgorithms[algorithm.rawValue] else {
            throw RequestSigningError.invalidAlgorithm
        }

        var digest = [UInt8](repeating: 0, count: Int(digestLength))

        CCHmac(CCHmacAlgorithm(algorithmKey), secret, secret.count, canonicalized, canonicalized.count, &digest)

        let data = Data(digest)

        return data.map { String(format: "%02hhx", $0) }.joined()
    }
}
</code>```

答:
Error code APIG.303 is for: Incorrect app authentication information, usually Incorrect app authentication information. In your case, it could be Authorization format is incorrect

Please check whether the request method, path, query strings, and request body are consistent with those used for signing; check whether the date and time on the client are correct; and check whether the signing code is correct by referring to Calling APIs Through App Authentication.

Here is the detailed API Gateway user guide for your reference: https://support.huaweicloud.com/intl/en-us/ae-ad-1-usermanual-apig/ae-APIG-usermanual.pdf

Below are two examples for Signature verification, see if they can give you some ideas on why your error occurs:

```<code>private static finÃ Pattern authorizationPattern = Pattern.compile("SDK-HMAC-SHA256\\s+Access=([^,]+),\
\s?SignedHeaders=([^,]+),\\s?Signature=(\\w+)");
...
String authorization = request.getHeader("Authorization");
if (authorization == null || authorization.length() == 0) {
 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization not found.");
 return;
}
Matcher m = authorizationPattern.matcher(authorization);
if (Ȃmȇfin()) {
 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization format incorrect.");
 return;
}
String signingKey = m.group(1);
String signingSecret = secrets.get(signingKey);
if (signingSecret == null) {
 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Signing key not found.");
 return;
}
String[] signedHeaders = m.group(2).split(";")
;
</code>```

another one:

```<code>if "authorization" not in request.headers:
 return 'Authorization not found.', 401
authorization = request.headers['authorization']
m = authorizationPattern.match(authorization)
if m is None:
 return 'Authorization format incorrect.', 401
signingKey = m.group(1)
signedHeaders = m.group(2).split(";")if "authorization" not in request.headers:
 return 'Authorization not found.', 401
authorization = request.headers['authorization']
m = authorizationPattern.match(authorization)
if m is None:
 return 'Authorization format incorrect.', 401
signingKey = m.group(1)
signedHeaders = m.group(2).split(";")
</code>```

Body:
As per Huawei API Gateway App Authentication documentation I'm trying to access an API through app authentication, standardize the request content, and then sign the request. As the client I must follow the same request specifications as API Gateway so that each HTTP request can obtain the same signing result from the frontend and backend to complete identity authentication.

I complete it using following class. However the documentation is really poor to understand. It returns error Incorrect app authentication information: Authorization format is incorrect APIG.0303.

I couldn't complete the process and I'm really thankful if you can give any sample to do this.

import Foundation
import CommonCrypto

public class SimpleHMACAuth {

    /// APP key to authenticate with
    public var appKey: String?

    /// Secret key to authenticate with
    public var secret: String?

    /// Algorithm to generate HMAC hash with
    public var algorithm: HMACAlgorithm = .sha256

    public enum HMACAlgorithm: String {
        case sha256 = "sha256"
        case sha512 = "sha512"
    }

    enum RequestSigningError: Error {
        case missingAPPKey
        case missingSecret
        case invalidAlgorithm
        case invalidURL
    }

    fileprivate let dateFormatter: DateFormatter

    /// Instantiate with an APP key and secret
    /// - Parameters:
    ///   - appKey: APP key
    ///   - secret: Secret key
    public convenience init(appKey: String, secret: String) {
        self.init()

        self.appKey = appKey
        self.secret = secret
    }

    /// Instantiate
    public init() {
        self.dateFormatter = DateFormatter()
        self.dateFormatter.dateFormat = "dd MMM yyyy HH:mm:ss zzz"
    }

    /// Returns a signed version of an input request
    /// - Parameter request: Request to sign
    /// - Throws: If the request, APP key, secret, or algorithm are invalid
    /// - Returns: Signed version of the request
    public func sign(_ request: URLRequest) throws -> URLRequest {

        guard let signedRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
            throw RequestSigningError.invalidURL
        }

        guard let appKey = self.appKey else {
            throw RequestSigningError.missingAPPKey
        }

        guard let secret = self.secret else {
            throw RequestSigningError.missingSecret
        }

        // Add the "Authorization" header

        signedRequest.addValue("APP key \(appKey)", forHTTPHeaderField: "Authorization")

        // Confirm the "Date" header exists, and add it if not

        if signedRequest.value(forHTTPHeaderField: "Date") == nil {

            signedRequest.addValue(self.dateFormatter.string(from: Date()), forHTTPHeaderField: "X-Sdk-Date")
        }

        // If this request has a body but does not yet have the "Content-Length" header, calculate and append it

        if let data = signedRequest.httpBody, signedRequest.value(forHTTPHeaderField: "Content-Length") == nil {

            signedRequest.addValue("\(data.count)", forHTTPHeaderField: "Content-Length")
        }

        // Canonicalize the request

        let canonicalized = try self.canonicalize(signedRequest as URLRequest)

        // Generate a signature from the canonicalized representation of the request

        let signature = try self.signature(canonicalized: canonicalized, secret: secret, algorithm: algorithm);

        // Append the "Signature" header

        signedRequest.addValue("SDK-HMAC-SHA256", forHTTPHeaderField: "Authorization")
        signedRequest.addValue(appKey, forHTTPHeaderField: "Access")
        signedRequest.addValue("SDK-HMAC-SHA256 \(signature)", forHTTPHeaderField: "Signature")

        return signedRequest as URLRequest
    }

    /// Generate a string for a request
    /// - Parameter request: Request to sign
    /// - Throws: Throws if request is invalid
    /// - Returns: Signed request
    internal func canonicalize(_ request: URLRequest) throws -> String {

        guard let url = request.url else {
            throw RequestSigningError.invalidURL
        }

        let method = (request.httpMethod ?? "GET").uppercased()
        var path = url.path
        let queryString = url.query != nil ? "?\(url.query!)" : ""
        let allHeaders = request.allHTTPHeaderFields ?? [String : String]()
        let data = request.httpBody ?? Data()

        if let component = URLComponents(string: url.absoluteString) {
            path = component.path
        }

        // Only sign these headers

        let allowedHeaders = [
            "authorization",
            "date",
            "content-length",
            "content-type"
        ]

        // Create a new list of headers, with the keys all lower case

        var headers = [String: String]();

        for (key, value) in allHeaders {

            let lowerCaseKey = key.lowercased()

            if allowedHeaders.contains(lowerCaseKey) == false {
                continue
            }

            if lowerCaseKey == "content-length" && value == "0" {
                continue
            }

            headers[lowerCaseKey] = value;
        }

        // Sort the header keys alphabetically

        let headerKeys = headers.keys.sorted()

        // Create a string of all headers, arranged alphabetically, seperated by newlines

        var headerString = ""

        for (index, key) in headerKeys.enumerated() {

            guard let value = headers[key] else {
                continue
            }

            headerString += "\(key):\(value)"

            if index != headerKeys.count - 1 {
                headerString += "\n"
            }
        }

        // Hash the data payload

        var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        data.withUnsafeBytes { bytes in
            _ = CC_SHA256(bytes.baseAddress, CC_LONG(data.count), &digest)
        }

        let dataHash = Data(digest).map { String(format: "%02hhx", $0) }.joined()

        // Combine all components of this request into a string

        let components: [String] = [method, path, queryString, headerString, dataHash]

        return components.joined(separator: "\n");
    }

    /// Generate a HMAC hash for a canonicalized request
    /// - Parameters:
    ///   - canonicalized: canonicalized version of a request
    ///   - secret: Secret key
    ///   - algorithm: Algorithm to use to generate the hmac
    /// - Throws: If algorithm is not supported
    /// - Returns: Signature for the request
    internal func signature(canonicalized: String, secret: String, algorithm: HMACAlgorithm) throws -> String {

        let supportedAlgorithms = ["sha1":   (kCCHmacAlgSHA1,   CC_SHA1_DIGEST_LENGTH),
                                   "sha256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
                                   "sha512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]

        guard let (algorithmKey, digestLength) = supportedAlgorithms[algorithm.rawValue] else {
            throw RequestSigningError.invalidAlgorithm
        }

        var digest = [UInt8](repeating: 0, count: Int(digestLength))

        CCHmac(CCHmacAlgorithm(algorithmKey), secret, secret.count, canonicalized, canonicalized.count, &digest)

        let data = Data(digest)

        return data.map { String(format: "%02hhx", $0) }.joined()
    }
}

Body:
Error code APIG.303 is for: Incorrect app authentication information, usually Incorrect app authentication information. In your case, it could be Authorization format is incorrect

Please check whether the request method, path, query strings, and request body are consistent with those used for signing; check whether the date and time on the client are correct; and check whether the signing code is correct by referring to Calling APIs Through App Authentication.

Here is the detailed API Gateway user guide for your reference: https://support.huaweicloud.com/intl/en-us/ae-ad-1-usermanual-apig/ae-APIG-usermanual.pdf

Below are two examples for Signature verification, see if they can give you some ideas on why your error occurs:

private static finÃ Pattern authorizationPattern = Pattern.compile("SDK-HMAC-SHA256\\s+Access=([^,]+),\
\s?SignedHeaders=([^,]+),\\s?Signature=(\\w+)");
...
String authorization = request.getHeader("Authorization");
if (authorization == null || authorization.length() == 0) {
 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization not found.");
 return;
}
Matcher m = authorizationPattern.matcher(authorization);
if (Ȃmȇfin()) {
 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization format incorrect.");
 return;
}
String signingKey = m.group(1);
String signingSecret = secrets.get(signingKey);
if (signingSecret == null) {
 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Signing key not found.");
 return;
}
String[] signedHeaders = m.group(2).split(";")
;

another one:

if "authorization" not in request.headers:
 return 'Authorization not found.', 401
authorization = request.headers['authorization']
m = authorizationPattern.match(authorization)
if m is None:
 return 'Authorization format incorrect.', 401
signingKey = m.group(1)
signedHeaders = m.group(2).split(";")if "authorization" not in request.headers:
 return 'Authorization not found.', 401
authorization = request.headers['authorization']
m = authorizationPattern.match(authorization)
if m is None:
 return 'Authorization format incorrect.', 401
signingKey = m.group(1)
signedHeaders = m.group(2).split(";")


来源: stackexchange

问:
Does Docker HEALTHCHECK disable container networking when unhealthy?
I need some clarification in regards to using HEALTHCHECK on a docker service.

Context:

We are experimenting with a multi-node mariadb cluster and by utilizing HEALTHCHECK we would like the bootstrapping containers to remain unhealthy until bootstrapping is complete. We want this so that front-end users don’t access that particular container in the service until it is fully online and sync’d with the cluster. The issue is that bootstrapping relies on the network between containers in order to do a state transfer and it won’t work when a container isn’t accessible on the network.

Question:

When a container’s status is either starting or unhealthy does HEALTHCHECK completely kill network access to and from the container?
As an example, when a container is healthy I can run the command getent hosts tasks.<service_name>
inside the container which returns the IP address of other containers in a service. However, when the same container is unhealthy that command does not return anything… Hence my suspicion that HEALTHCHECK kills the network at the container level (as opposed to at the service/load balancer level) if the container isn’t healthy.

Thanks in advance

答: I ran some more tests and found my own answer. Basically docker does not kill container networking when it is either in the started or unhealthy phase. The reason getent hosts tasks.<service_name> command does not work during those phases is that that command goes back to get the container IP address through the service which does not have the unhealthy container(s) assigned to it.

ContentLicense: CC BY-SA 4.0


问:
What is the cause of the 'not found' error in my user-defined function?
```<code>df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(var) {

  export_df <- df %>%
    filter(!is.na(var)) %>%
    select(var)

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

#Calling the function
export_ids(wspid)
</code>```

I keep getting the same error:

```<code>Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `!is.na(var)`.
x object 'wspid' not found
</code>```

I suspect there's some issue with the scoping of the function but no matter what combinations I try-- such as defining the tibble within the function or referencing the tibble directly within the function (as in, df$var) I still get an error.

答:
As we pass unquoted variable, use {{}} (curly-curly opertor) for evaluation

```<code>export_ids <- function(var) {

  export_df <- df %>%
    filter(!is.na({{var}})) %>%
    select({{var}})

  write_csv(export_df, "~/Downloads/final_ids.csv")

}
</code>```

-testing

```<code>export_ids(wspid)
</code>```

Body:
df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(var) {

  export_df <- df %>%
    filter(!is.na(var)) %>%
    select(var)

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

#Calling the function
export_ids(wspid)

I keep getting the same error:

Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `!is.na(var)`.
x object 'wspid' not found

I suspect there's some issue with the scoping of the function but no matter what combinations I try-- such as defining the tibble within the function or referencing the tibble directly within the function (as in, df$var) I still get an error.

Body:
As we pass unquoted variable, use {{}} (curly-curly opertor) for evaluation

export_ids <- function(var) {

  export_df <- df %>%
    filter(!is.na({{var}})) %>%
    select({{var}})

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

-testing

export_ids(wspid)


问:
how to pass pointer to constructor in c++
have a derived class that needs to take a pointer as a constructor for the base class.

how do you do this in c++, i tried it but it gave me a bug.

```<code>#include <iostream>

using namespace std;

class Base {
protected:
    int *num;
public:
    Base(int *num);
    virtual void print();
};

Base::Base(int *num){
    this->num = num;
};

class Derived : public Base {
public:
    Derived(int *num) : Base(*num);
    void print();
};

Derived::print(){
    cout << "int value : " << *(this->num);
};

int main(){
    int num = 5;
    int *p = #

    Derived derived(p);
    derived.print();

    return 0;
}

</code>```

答:
In the constructor initializer list of Derived you have to write Base(num) instead of Base(*num) as shown below:

```<code>Derived(int *num): Base(num)
{
   //code here
}
</code>```

Note that you don't have to dereference the pointer num which you were doing while using it in the constructor initializer list. When you dereference num, you got an int. And so you were passing that int to the Base constructor.

Body:
have a derived class that needs to take a pointer as a constructor for the base class.

how do you do this in c++, i tried it but it gave me a bug.

#include <iostream>

using namespace std;

class Base {
protected:
    int *num;
public:
    Base(int *num);
    virtual void print();
};

Base::Base(int *num){
    this->num = num;
};

class Derived : public Base {
public:
    Derived(int *num) : Base(*num);
    void print();
};

Derived::print(){
    cout << "int value : " << *(this->num);
};

int main(){
    int num = 5;
    int *p = #

    Derived derived(p);
    derived.print();

    return 0;
}

Body:
In the constructor initializer list of Derived you have to write Base(num) instead of Base(*num) as shown below:

Derived(int *num): Base(num)
{
   //code here
}

Note that you don't have to dereference the pointer num which you were doing while using it in the constructor initializer list. When you dereference num, you got an int. And so you were passing that int to the Base constructor.


问:
In MIPS pipeline, does the ID/EX register hold the value of the registers, or the address of the register
Say I have a MIPS pipeline with 32bits words. The pipeline stages are IF, ID, EX, MEM, WB, and there is no forwarding.

My question is: When executing the ID stage, say for a sub command, are the values of the registers stored in the ID/EX register, or does the ID/EX register simply store the address of the register (5 bits) and then proceeds to read them from the register file at the EX step?

This question was formed while I was studying my class notes, and I came upon the following image:

Personally, in the second line of the image (the sub command) I was expecting the ID step to be placed after the stalls, so the WB step of lw is first executed, and then the ID step of sub can get the updated value of the registers.

But, the image shows that the ID step of sub can actually be before the WB step of lw causing me to believe that the actual value of the registers are not stored in the ID/EX register, since if that was the case, the values propagated to EX would be not valid.

答:
We have discovered that your instructor is proposing a hypothetical processor.  That's ok, hypotheticals are used all the time.  It's just not the usual MIPS.

The answer below speaks to the classic MIPS pipelined processor.

This diagram looks like the processor is using both 2 stalls and a bypass, which is overkill, if you ask me.  The load data is ready at the end of the MEM stage in cycle 4.  The EX stage for the sub can execute in cycle 5 with only 1 stall — there's no benefit to waiting until cycle 6, because the data is ready at the beginning of cycle 5, and in cycle 6 a bypass is still needed (the last alternative would be to re-run the subs ID stage in cycle 6 to pick up the load data, though that would cost 3 stall cycles, but eliminate the need for a bypass).

However, to answer your question about the contents of the pipeline register, the ID/EX pipeline stage register sits on the boundary between ID and EX, and holds whatever is computed earlier e.g. by IF and ID, that is needed by any stage later, e.g. EX, MEM, and WB.

This includes both register lookup value as well as register numbers.  RAW hazards do not always happen so the register values are needed for the case there is no RAW hazard at the moment.

The register numbers are used in detection of the presence of RAW hazards, by comparing register target numbers from prior instructions with register source numbers in the current instruction.

So, the answer is both: the pipeline stage registers will have 32-bit register values and 5-bit register numbers.  This data is also forwarded from EX to MEM b/c there are also MEM/MEM hazards that can be avoided using bypass.

In handling of exceptions, like bad address in load or store, and also for taken branches, the program counter is required, so the program counter is probably forwarded from IF to ID to EX to MEM, via those pipeline registers.
  From ID on, control signals will also be forwarded.  WB, for example, needs to know RegWrite (yes/no) and WriteReg (5-bit reg number).


问:
Are there any ways to get/test the actual request body in Mock HttpMessageHandler?
```<code>public async AddName(){
    var requestUri = "someuri";
    var payload = new AddNameRequest()
            {
                NameParts = new string[] { "Name001" },
                Formula = string.Empty
            };

        // Act
        var responseMessage = await this.httpClient.PostAsJsonAsync(requestUri, payload);
}
</code>```

And UnitTest for it:

```<code>    public async AddName_ExpectedBeh(){
//Create URI
//Create responseMessage
        var mockHandler = new Mock<HttpMessageHandler>();
                    mockHandler.Protected()
                        .Setup<Task<HttpResponseMessage>>(
                        "SendAsync",
                        ItExpr.Is<HttpRequestMessage>(r => r.Method == responseMessage.RequestMessage.Method && r.RequestUri.ToString().EndsWith(responseMessage.RequestMessage.RequestUri.ToString())),
                        ItExpr.IsAny<CancellationToken>())
                        .ReturnsAsync(responseMessage);

                    var httpClient = new HttpClient(mockHandler.Object);
//Pass HttpClient to Main Class
//Do Request
//Assert the response
    }
</code>```

The issue in the previous Unit test is that I'm unable to test payload(request body). I see that mockHandler can read HttpRequestMessage, but I couldn't read it outside of the mockHandler.Setup(). So are there any ways to get/test HttpRequestMessage and how can I do that?
For example, I want to check if the request body contains "Name001".

答:
The payload is available in the Setup method. The way you can test it is you can add a method in which you can test what you want with it. For example

```<code>public async Task<bool> IsRequestValid(HttpRequestMessage requestMessage)
{
    string stringContent = await requestMessage.Content.ReadAsStringAsync();

    // Example of some validation...
    return stringContent.Contains("myProperty");
}
</code>```

And if this method returns true, the mockHandler will return the desired message, if it's not it will return default (null). This is how you will know that your request is correct. Alternatively, from this method, you can throw exception or Assert.False().

You can append this check in your existing Setup expression with && IsRequestValid(r.Content).

Body:
public async AddName(){
    var requestUri = "someuri";
    var payload = new AddNameRequest()
            {
                NameParts = new string[] { "Name001" },
                Formula = string.Empty
            };

        // Act
        var responseMessage = await this.httpClient.PostAsJsonAsync(requestUri, payload);
}

And UnitTest for it:

    public async AddName_ExpectedBeh(){
//Create URI
//Create responseMessage
        var mockHandler = new Mock<HttpMessageHandler>();
                    mockHandler.Protected()
                        .Setup<Task<HttpResponseMessage>>(
                        "SendAsync",
                        ItExpr.Is<HttpRequestMessage>(r => r.Method == responseMessage.RequestMessage.Method && r.RequestUri.ToString().EndsWith(responseMessage.RequestMessage.RequestUri.ToString())),
                        ItExpr.IsAny<CancellationToken>())
                        .ReturnsAsync(responseMessage);

                    var httpClient = new HttpClient(mockHandler.Object);
//Pass HttpClient to Main Class
//Do Request
//Assert the response
    }

The issue in the previous Unit test is that I'm unable to test payload(request body). I see that mockHandler can read HttpRequestMessage, but I couldn't read it outside of the mockHandler.Setup(). So are there any ways to get/test HttpRequestMessage and how can I do that?
For example, I want to check if the request body contains "Name001".

Body:
The payload is available in the Setup method. The way you can test it is you can add a method in which you can test what you want with it. For example

public async Task<bool> IsRequestValid(HttpRequestMessage requestMessage)
{
    string stringContent = await requestMessage.Content.ReadAsStringAsync();

    // Example of some validation...
    return stringContent.Contains("myProperty");
}

And if this method returns true, the mockHandler will return the desired message, if it's not it will return default (null). This is how you will know that your request is correct. Alternatively, from this method, you can throw exception or Assert.False().

You can append this check in your existing Setup expression with && IsRequestValid(r.Content).


问:
jQuery load content when scroll to bottom of page
i need to do when i'm scrolling down of my page load more

```<code><div class="container">
<div class="news">News 1</div>
<div class="news">News 2</div>
<div class="news">News 3</div>
<div class="news">News 4</div>
</div>
</code>```

i have only html site, no PHP and MySQL, all news are i one page.
for example  when scroll to bottom for 500 px, load more content

答:
The correct code for this is:

$(document).ready(function(){
    var element = $(document).height();
    $(window).scroll(function(){
        var y = parseInt($(window).scrollTop()) + parseInt($(window).height());
        if (y >= element){
            $("#loader_bars").show();
            //Make post to server from last id recieved
        }
    });
});```

Its bug free, I used all the time.....Also the lazyload the Mirakurun said is just for images

ContentLicense: CC BY-SA 3.0

Body:
i need to do when i'm scrolling down of my page load more

News 1

News 2

News 3

News 4

i have only html site, no PHP and MySQL, all news are i one page.
for example  when scroll to bottom for 500 px, load more content

Body:
The correct code for this is:

$(document).ready(function(){
    var element = $(document).height();
    $(window).scroll(function(){
        var y = parseInt($(window).scrollTop()) + parseInt($(window).height());
        if (y >= element){
            $("#loader_bars").show();
            //Make post to server from last id recieved
        }
    });
});

Its bug free, I used all the time.....Also the lazyload the Mirakurun said is just for images


问:
Error when installing and loading libraries from list in R
I have a function that loads libraries from a list, and installs packages if required:

```<code># List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))
</code>```

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

```<code>Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7
</code>```

If I now run the loadLibrary function again, the new installed package gets loaded:

```<code>invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7
</code>```

Why is the package not loaded the first time I run the loadLibrary function?

答:
You need to always load the library but only install them if they are missing:</p>
```<code># List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
  if (!require(x, character.only = TRUE)) {
    install.packages(x)
  }
  # always load
  library(x, character.only = TRUE)
}

# Load packages
invisible(lapply(lib_List, loadLibrary))
</code>```

Body:
I have a function that loads libraries from a list, and installs packages if required:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7

If I now run the loadLibrary function again, the new installed package gets loaded:

invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7

Why is the package not loaded the first time I run the loadLibrary function?

Body:
You need to always load the library but only install them if they are missing:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
  if (!require(x, character.only = TRUE)) {
    install.packages(x)
  }
  # always load
  library(x, character.only = TRUE)
}

# Load packages
invisible(lapply(lib_List, loadLibrary))


问:
Wear Engine how to cancel/abort file sending on wearable (Java)?
I use Wear Engine to send files from watch (HarmonyOS) to phone (Android).
I can't find any method to cancel/abort file transfer. I imagine a file can weigh many megabytes and there is no option to stop the bytes transfer.

P2pClient object doesn't expose any method to cancel file sending.
P2pClient send() method returns Task result but I was unable to find here any way to stop this Task returned by P2pClient.

Wear Engine API Java

答: After further investigating Wear Engine, it seems to me that there is no such API for canceling a file sending from watch app to phone app. Wear Engine has an API, cancelFileTransfer, for canceling a file transfer from phone app to watch app. I am not sure if the unregister on watch app can stop the file transfer.</p>


问:
Disable child component to take height of parent scroll view
I have a horizontal scroll view and inside of it I've some views:

```<code>                        <ScrollView
                            horizontal={true}
                            showsHorizontalScrollIndicator={false}>
                            {myData.map((dataObj, index) =>
                                <MyTestCell />
                            )}
                        </ScrollView>
</code>```

The MyTestCell is a custom component and everything in it inside a <View></View>

Based on the content some MyTestCell are larger in height than others. Is there a way to NOT let MyTestCell View take the height of the longest component?

For example here is a screenshot of the bottom part of a cell which is just there because another cell in the scroll view is of that height:

So, is there a fix to this? Basically, I'm asking if there is a way to absolute the height of a view inside scroll view rather than inheriting the height of its parent it should just keep the height which it requires.

答: It might be late but you can do it but setting the flexGrow to 0 on the child component.

Body:
I have a horizontal scroll view and inside of it I've some views:

                        <ScrollView
                            horizontal={true}
                            showsHorizontalScrollIndicator={false}>
                            {myData.map((dataObj, index) =>
                                <MyTestCell />
                            )}
                        </ScrollView>

The MyTestCell is a custom component and everything in it inside a <View></View>

Based on the content some MyTestCell are larger in height than others. Is there a way to NOT let MyTestCell View take the height of the longest component?

For example here is a screenshot of the bottom part of a cell which is just there because another cell in the scroll view is of that height:

So, is there a fix to this? Basically, I'm asking if there is a way to absolute the height of a view inside scroll view rather than inheriting the height of its parent it should just keep the height which it requires.


问:
How can I balance "Pythonic" and "convenient" in this case?
I have an "interface" that will be implemented by client code:

```<code>class Runner:
    def run(self):
        pass
</code>```

run should in general return a docutils node but because the far far most
common case is plain text, the caller allows run to return a string, which will be
checked using type() and turned into a node.

However, the way I understand "Pythonic", this is not "Pythonic" because
checking the type() of something doesn't let it "be" a type by "acting" like
one -- ie "Pythonic" code should use duck typing.

I considered

```<code>def run_str(self):
    pass

def run_node(self):
    return make_node(self.run_str())
</code>```

but I don't care for this because it puts the not-so-interesting return type
right there in the name; it's distracting.

Are there any ideas I've missed? Also, are there problems I might encounter
down the road with my "bad" system (it seems more or less safe to me)?

答:
Using type() to detect a variable's type is really a bad practice, as it wouldn't allow an object inheriting from the desired type (str in your case), a better way is to use isinstance():

```<code>if isinstance(my_var, str):
    my_code_here()
</code>```

Also, a pythonic way of doing this would be duck-typing as you mentionned, why don't you just put the code in a try/except block? So an exception would be catched only if the value doesn't act as expected (if it quacks and walks like a duck, it's a duck).

Body:
I have an "interface" that will be implemented by client code:

class Runner:
    def run(self):
        pass

run should in general return a docutils node but because the far far most
common case is plain text, the caller allows run to return a string, which will be
checked using type() and turned into a node.

However, the way I understand "Pythonic", this is not "Pythonic" because
checking the type() of something doesn't let it "be" a type by "acting" like
one -- ie "Pythonic" code should use duck typing.

I considered

def run_str(self):
    pass

def run_node(self):
    return make_node(self.run_str())

but I don't care for this because it puts the not-so-interesting return type
right there in the name; it's distracting.

Are there any ideas I've missed? Also, are there problems I might encounter
down the road with my "bad" system (it seems more or less safe to me)?

Body:
Using type() to detect a variable's type is really a bad practice, as it wouldn't allow an object inheriting from the desired type (str in your case), a better way is to use isinstance():

if isinstance(my_var, str):
    my_code_here()

Also, a pythonic way of doing this would be duck-typing as you mentionned, why don't you just put the code in a try/except block? So an exception would be catched only if the value doesn't act as expected (if it quacks and walks like a duck, it's a duck).


问:
Snowflake - replace selective double quotes
I have data in a table with one column (varchar) that contains the following -

```<code>COL_A
-----
"trying to remove "double" quotes"
</code>```

I would like to remove the inner double quotes and keep the outer ones intact. Which function should I be using?

Essentially I should get the below output -

```<code>COL_A
-----
"trying to remove double quotes"
</code>```

答:
There are probably many ways to do this, one quick and dirty solution would be to replace all the double quotes and then just add the first and last quote, something like this:</p>
```<code>with cte as (select '\"trying to remove \"double\" quotes\"' as colA)
select colA, '\"'||replace(colA, '\"')||'\"' as colA_replaced
from cte;
</code>```

Body:
I have data in a table with one column (varchar) that contains the following -

COL_A
-----
"trying to remove "double" quotes"

I would like to remove the inner double quotes and keep the outer ones intact. Which function should I be using?

Essentially I should get the below output -

COL_A
-----
"trying to remove double quotes"

Body:
There are probably many ways to do this, one quick and dirty solution would be to replace all the double quotes and then just add the first and last quote, something like this:

with cte as (select '\"trying to remove \"double\" quotes\"' as colA)
select colA, '\"'||replace(colA, '\"')||'\"' as colA_replaced
from cte;


问:
Find certain colons in string using Regex
I'm trying to search for colons in a given string  so as to split the string at the colon for preprocessing based on the following conditions

Preceeded or followed by a word e.g A Book: Chapter 1 or A Book :Chapter 1

Do not match if it is part of emoticons i.e :( or ): or :/ or :-) etc

Do not match if it is part of a given time i.e 16:00 etc

I've come up with a regex as such

(\:)(?=\w)|(?<=\w)(\:)

which satisfies conditions 2 & 3 but still fails on condition 3 as it matches the colon present in the string representation of time. How do I fix this?

edit: it has to be in a single regex statement if possible

答:
Word characters \w include numbers [a-zA-Z0-9_]
So just use [a-ZA-Z] instead

(\:)(?=[a-zA-Z])|(?<=[a-zA-Z])(\:)

Test Here


问:
Getting the docstring from a function
I have the following function:

```<code>def my_func():
    """My docstring is both funny and informative"""
    pass
</code>```

How do I get access to the docstring?

答:
```<code>import ast
import sys
f = open(sys.argv[1], "r") #filename input
module = ast.parse(f.read())
class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)]
method_definitions = []
for class_def in class_definitions:
        print(class_def.name)
        print(ast.get_docstring(class_def))
        function_definitions = [node for node in class_def.body if isinstance(node, ast.FunctionDef)]
        for f in function_definitions:
                print('\t---')
                print('\t'+f.name)
                print('\t---')
                print('\t'+'\t'.join(ast.get_docstring(f).splitlines(True)))
        print('----')
</code>```

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 2.5

Title: Getting the docstring from a function

Body:
I have the following function:

def my_func():
    """My docstring is both funny and informative"""
    pass

How do I get access to the docstring?


问:
Splitting text files and returning only the end in scala
I want to read a text file from scala named "c.txt" that contains

```<code>CatManC_NAA
Foranz_CSW
Foresan_SQW
</code>```

and return only the second part of the txt file as a string. Ex: NAA, CSW when entering "CatManC" or "Foranz" as a parameter while ignoring capitalization.
This is my code at the moment.

```<code>object Test {
  def getCode(fileName: String, nameInput:String): String={
  code:String=""
  for (line <- Source.fromFile(filename).getLines) {
    line.split("_")
   if (nameInput==line){
    line.takeRight(3)
     code+=line
}
   else{
   return ""
}

  }
code
}
</code>```

I'm an amateur at coding and also new to the language. Any help will be appreciated.

答:
I suggest to write something like this:

```<code>  def getCode(fileName: String, nameInput: String): String = {
    import scala.util.control.Breaks
    var code = ""
    val source = Source.fromFile(fileName)
    val loopBreak = new Breaks
    loopBreak.breakable {
      for (line <- source.getLines()) {
        if (line.toLowerCase.contains(nameInput.toLowerCase)) {
          code = line.split("_")(1)
          loopBreak.break()
        }
      }
    }
    source.close()
    code
  }
</code>```

Here Breaks needs to stop read file when we find what we are looking for. Method toLowerCase need to ignore capitalisation on both sides in file and in input.

Body:
I want to read a text file from scala named "c.txt" that contains

CatManC_NAA
Foranz_CSW
Foresan_SQW

and return only the second part of the txt file as a string. Ex: NAA, CSW when entering "CatManC" or "Foranz" as a parameter while ignoring capitalization.
This is my code at the moment.

object Test {
  def getCode(fileName: String, nameInput:String): String={
  code:String=""
  for (line <- Source.fromFile(filename).getLines) {
    line.split("_")
   if (nameInput==line){
    line.takeRight(3)
     code+=line
}
   else{
   return ""
}

  }
code
}

I'm an amateur at coding and also new to the language. Any help will be appreciated.

Body:
I suggest to write something like this:

  def getCode(fileName: String, nameInput: String): String = {
    import scala.util.control.Breaks
    var code = ""
    val source = Source.fromFile(fileName)
    val loopBreak = new Breaks
    loopBreak.breakable {
      for (line <- source.getLines()) {
        if (line.toLowerCase.contains(nameInput.toLowerCase)) {
          code = line.split("_")(1)
          loopBreak.break()
        }
      }
    }
    source.close()
    code
  }

Here Breaks needs to stop read file when we find what we are looking for. Method toLowerCase need to ignore capitalisation on both sides in file and in input.


问:
Arrange columns of two different grids with gaps in line
How do I get the two grid cells "right" and "col" in a line below each other without adjusting the HTML?
Without gaps this is not a problem, but as soon as gaps are added, the columns are no longer in line.

*, *::before, *::after {
  box-sizing: border-box;
}

.OuterContainer {
  display: grid;
  column-gap: 32px;
  grid-template-columns: 1fr 3fr;
}

.Col4Grid {
    display: grid;
    column-gap: 32px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
}

.Col {
  background-color: #e7e7e7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="OuterContainer">
  <div class="Col">
    left
  </div>
  <div class="Col">
    right
  </div>
</div>

<div class="Col4Grid">
  <div class="Col">col</div>
  <div class="Col">col</div>
  <div class="Col">col</div>
  <div class="Col">col</div>
</div></code>```

答:
I hope I got your intended layout correct. Just apply the same grid-column rule to both containers. then let the column (right)  span 3 columns with: grid-column: span 3;

*, *::before, *::after {
  box-sizing: border-box;
}

.OuterContainer,
.Col4Grid {
  display: grid;
  column-gap: 32px;
  grid-template-columns: repeat(4, 1fr);
}

.Col {
  background-color: #e7e7e7;
}

.OuterContainer .Col:nth-child(2) {
  grid-column: span 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="OuterContainer">
  <div class="Col">
    left
  </div>
  <div class="Col">
    right
  </div>
</div>

<div class="Col4Grid">
  <div class="Col">col</div>
  <div class="Col">col</div>
  <div class="Col">col</div>
  <div class="Col">col</div>
</div></code>```

Body:
How do I get the two grid cells "right" and "col" in a line below each other without adjusting the HTML?
Without gaps this is not a problem, but as soon as gaps are added, the columns are no longer in line.

*, *::before, *::after {
  box-sizing: border-box;
}

.OuterContainer {
  display: grid;
  column-gap: 32px;
  grid-template-columns: 1fr 3fr;
}

.Col4Grid {
    display: grid;
    column-gap: 32px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
}

.Col {
  background-color: #e7e7e7;
}

    left

    right

col

col

col

col

Body:
I hope I got your intended layout correct. Just apply the same grid-column rule to both containers. then let the column (right)  span 3 columns with: grid-column: span 3;

*, *::before, *::after {
  box-sizing: border-box;
}

.OuterContainer,
.Col4Grid {
  display: grid;
  column-gap: 32px;
  grid-template-columns: repeat(4, 1fr);
}

.Col {
  background-color: #e7e7e7;
}

.OuterContainer .Col:nth-child(2) {
  grid-column: span 3;
}

<div class="OuterContainer">
  <div class="Col">
    left
  </div>
  <div class="Col">
    right
  </div>
</div>

<div class="Col4Grid">
  <div class="Col">col</div>
  <div class="Col">col</div>
  <div class="Col">col</div>
  <div class="Col">col</div>
</div>


问:
Getting Firefox's history
I am making a windows application to get a list of accessed website addresses of Firefox browser. I have no idea how to achieve this ? I am thinking accessing cache may be fine but computer cache contains more information than those I actually need. Would you please recommend a COM or method used to get this done ? I am grateful for your help.

Thank you.

答: Firefox uses SQLite databases to store most of it's information. So probably easiest way to achive this would be study of this database files, and then all should be as simple as writing a couple of SQL queries.</p>

Title: Getting Firefox's history


问:
How do I pass R.drawable.XXX value to a function in kotlin?
Here's my code:

```<code>private fun roomChange(animation: Int)
{
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        setBackgroundResource(R.drawable.animation)
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}
</code>```

I have anim.xml file and would like to pass it to a function but "animation" is an unresolved reference. How would I go about passing it correctly? Thanks in advance!

答:
Here's the enum thing I mentioned in the comments:

```<code>// Basic enum with an animation resource property - add one for each anim
// The @AnimRes annotation is optional, just gives you a warning if you use something else
enum class StateAnimation(@AnimRes val animationId: Int) {
    ANIM(R.drawable.animation),
    RUN(R.drawable.run)
}

...

// set your function to take one of your animation definitions instead
private fun roomChange(stateAnim: StateAnimation) {
    // pull out the resource ID from the passed animation
    setBackgroundResource(stateAnim.animationId)
}

// call your function using the animation you want
roomChange(StateAnimation.RUN)
</code>```

The idea here is you can create an enum class that defines all your animations, so you can name each one however you like, and they all have a resource ID for the animation they represent. Then you pass one of those to your function instead, and the function can refer to its resource ID

This way you get code completion and type checking (you have to pass one of the StateAnimations, not any other animation ID, resource ID, or random int). Your code can be cleaner because StateAnimation.RUN is pretty clear (you might want to rename that but you get the idea), and it's safer than passing a string like "run" and converting that into a resource lookup which may or may not exist

And if you want, you can just import everything in StateAnimation (put your cursor on RUN and do Alt+Enter or click the lightbulb and it'll offer to do it for you) and then you can just call roomChange(RUN) and it's nice and concise!

Body:
Here's my code:

private fun roomChange(animation: Int)
{
    val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
        setBackgroundResource(R.drawable.animation)
        foxanim = background as AnimationDrawable
        foxanim.start()
    }
}

I have anim.xml file and would like to pass it to a function but "animation" is an unresolved reference. How would I go about passing it correctly? Thanks in advance!

Body:
Here's the enum thing I mentioned in the comments:

// Basic enum with an animation resource property - add one for each anim
// The @AnimRes annotation is optional, just gives you a warning if you use something else
enum class StateAnimation(@AnimRes val animationId: Int) {
    ANIM(R.drawable.animation),
    RUN(R.drawable.run)
}

...

// set your function to take one of your animation definitions instead
private fun roomChange(stateAnim: StateAnimation) {
    // pull out the resource ID from the passed animation
    setBackgroundResource(stateAnim.animationId)
}

// call your function using the animation you want
roomChange(StateAnimation.RUN)

The idea here is you can create an enum class that defines all your animations, so you can name each one however you like, and they all have a resource ID for the animation they represent. Then you pass one of those to your function instead, and the function can refer to its resource ID

This way you get code completion and type checking (you have to pass one of the StateAnimations, not any other animation ID, resource ID, or random int). Your code can be cleaner because StateAnimation.RUN is pretty clear (you might want to rename that but you get the idea), and it's safer than passing a string like "run" and converting that into a resource lookup which may or may not exist

And if you want, you can just import everything in StateAnimation (put your cursor on RUN and do Alt+Enter or click the lightbulb and it'll offer to do it for you) and then you can just call roomChange(RUN) and it's nice and concise!


问:
Changing order in flex and removing elements in mobile phone viewing mode
Here is my code and I want to change the order of buttons when we are in the mobile viewing mode.
I used "column-reverse" but what if I want them to be like this?
button 2
button 3
button 1
How can I customize their order?

My second question is how can i get rid of the "this is a lable" text in mobile viewing mode?
I tried "display: none" but since the label class contains all the buttons as well, all the buttons will be removed.

html {
  box-sizing: border-box;
  font-size: 62.5%;
  font-family: 'Georama', sans-serif;
}
body {
  background-color: #555;
  color: #fff;
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
}

button {
  margin: 2rem;
  width: 200px;
  height: 50px;
}

.label {
  font-size: 2rem;
  display: flex;
  flex-direction: column;
}

@media only screen and (max-width: 600px) {
  .label {
    flex-direction: column-reverse;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <html>
    <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    </head>
    <body>
      <label class="label">
        this is a label
        <button>Btn 1</button>
        <button>Btn 2</button>
        <button>Btn 3</button>
      </label>
    </body>
  </html>
</html></code>```

答:
You do not have necessarily to use flex-direction: column-reverse

Since you are using flex-box, it is quite easy to determine the order of elements using the order CSS property.

As for the second question, wrap the text in a div and add display: none in the mobile viewing mode.

html:

this is a label

    <button>Btn 1</button>
    <button>Btn 2</button>
    <button>Btn 3</button>

```
<p><code>css</code>:</p>
<pre class="lang-css prettyprint-override"><code>@media only screen and (max-width: 600px) {

 label button:nth-of-type(1) { order: 3; }

 label div { display: none; }
}
</code>```

https://jsfiddle.net/kongallis/jsraL3g9/41/

Body:
Here is my code and I want to change the order of buttons when we are in the mobile viewing mode.
I used "column-reverse" but what if I want them to be like this?
button 2
button 3
button 1
How can I customize their order?

My second question is how can i get rid of the "this is a lable" text in mobile viewing mode?
I tried "display: none" but since the label class contains all the buttons as well, all the buttons will be removed.

html {
  box-sizing: border-box;
  font-size: 62.5%;
  font-family: 'Georama', sans-serif;
}
body {
  background-color: #555;
  color: #fff;
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
}

button {
  margin: 2rem;
  width: 200px;
  height: 50px;
}

.label {
  font-size: 2rem;
  display: flex;
  flex-direction: column;
}

@media only screen and (max-width: 600px) {
  .label {
    flex-direction: column-reverse;
  }
}

<!DOCTYPE html>

      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

        this is a label
        <button>Btn 1</button>
        <button>Btn 2</button>
        <button>Btn 3</button>

Body:
You do not have necessarily to use flex-direction: column-reverse

Since you are using flex-box, it is quite easy to determine the order of elements using the order CSS property.

As for the second question, wrap the text in a div and add display: none in the mobile viewing mode.

html:

<label class="label">
    <div>this is a label</div>
    <button>Btn 1</button>
    <button>Btn 2</button>
    <button>Btn 3</button>
</label>

css:

@media only screen and (max-width: 600px) {

 label button:nth-of-type(1) { order: 3; }

 label div { display: none; }
}

https://jsfiddle.net/kongallis/jsraL3g9/41/


问:
three blured circles in background UI design challenge
How to create this kind of app background.it uses three circle in three parts of screen.
how to create a background color like this???

答:
Please check it, I think this is what you need.
As you can see, you can set Colors.transparent as the color of the container and then use box-shadow to create something like that picture.

class CustomScaffold extends StatelessWidget {
  const CustomScaffold({Key? key}) : super(key: key);

  coloredContainer(double size, Color color) => Container(
        width: size,
        height: size,
        decoration: BoxDecoration(
          color: Colors.transparent,
          boxShadow: [
            BoxShadow(color: color, blurRadius: 100),
          ],
          shape: BoxShape.circle,
        ),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 152, 204, 246),
      body: Stack(
        children: [
          Positioned(
            top: -100,
            left: -100,
            child:
                coloredContainer(500, const Color.fromARGB(255, 104, 136, 224)),
          ),
          Positioned(
            top: 700,
            left: 100,
            child:
                coloredContainer(400, const Color.fromARGB(255, 93, 128, 226)),
          ),
        ],
      ),
    );
  }
}
```

result :

Body:
Please check it, I think this is what you need.
As you can see, you can set Colors.transparent as the color of the container and then use box-shadow to create something like that picture.

class CustomScaffold extends StatelessWidget {
  const CustomScaffold({Key? key}) : super(key: key);

  coloredContainer(double size, Color color) => Container(
        width: size,
        height: size,
        decoration: BoxDecoration(
          color: Colors.transparent,
          boxShadow: [
            BoxShadow(color: color, blurRadius: 100),
          ],
          shape: BoxShape.circle,
        ),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 152, 204, 246),
      body: Stack(
        children: [
          Positioned(
            top: -100,
            left: -100,
            child:
                coloredContainer(500, const Color.fromARGB(255, 104, 136, 224)),
          ),
          Positioned(
            top: 700,
            left: 100,
            child:
                coloredContainer(400, const Color.fromARGB(255, 93, 128, 226)),
          ),
        ],
      ),
    );
  }
}

result :


问:
Type problems with reduce in TypeScript
I have a simple reduce function which would work in JS, but obviously TypeScript doesn't want to allow me use that.
I am supposed to be group clients and find how much they paid for their orders. I wanted to at first make a reduce on orders, so I get an object with idOfClient -> Array of prices.
Then I wanted to make a reduce on the Array of prices, so I would get the sum of the array, but it seems like TypeScript doesn't know that there is an array as a value of key, it sees idClientsWithPrice as empty Object I guess.
With my code I get an error:

```<code>Property 'reduce' does not exist on type 'never'.
</code>```

My code:

```<code>export const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        if (acc[curr.client as keyof typeof acc]) {
            return {...acc, [curr.client]: [...acc[curr.client as keyof typeof acc], curr.price]}
        }
        return {...acc, [curr.client]: [curr.price]}

        // acc[curr.client as keyof typeof acc] ?  {...acc, [curr.client]: [...acc[curr.client as keyof typeof acc],curr]} :
        // {...acc, [curr.client]: [curr]}
    }, {})
    const idClientsWithSum = Object.keys(idClientsWithPrices).map(id => {
        return {
            id: id,
            sum: idClientsWithPrices[id as keyof typeof idClientsWithPrices].reduce((acc: number,curr: number) => {
                acc+curr
            }, 0)}
    })
}
</code>```

Is there any way to handle that?
My second question would be also why the commented code is not equivalent to my if statement? I wanted to do it using tenary operator, but it says that it was not an expression or call

答:
The source of the problem for the error you are getting is in the first reduce call, because the initialValue parameter (the value {}) determines the return type of the first reduce call and also the type of its acc parameter.
Since you are providing just the value {} as the initial value, without specifying any type along with it, TS correctly assigns it the type of {}.
That is also why you had other errors to take care of before you ended with the code that you have now. All those as keyof typeof acc would not be needed, if this initial value would have a type specified along with it.

So let's define the type that we expect the {} to be. Since we want to make a map/dictionary/LUT (lookup table) from scratch, it will clearly start empty, so the initial value of {} is correct.
The type of this value should be an object that we can index with a key and the values at these keys should have a type of an array of numbers. However when we index a key that does not exist, we will get undefined back.

So the type is then

```<code>{} // for the initial value
as { [key: <key-type>]: undefined | <value-type> }
// an object that we can index with a key and returns undefined or a value
</code>```

Here I assume that your key is of type string | number. In TS an index signature parameter type must be string, number, symbol, or a template literal type anyway.
If we put the actual types in, we get

```<code>{} as { [key: string | number]: undefined | Array<number> }
</code>```

If you don't want to repeat this type every time you need it, you can write it down somewhere in your code base as a type with a generic type parameter, so that it is reusable for other value types as well.

```<code>type Lookup<T> = { [key: string | number]: undefined | T }
</code>```

(TS also has the Map<KeyType, ValueType> type, but that one is for when you use an actual JS Map with new Map() and allows the keys to be of any type, and has a get(key: KeyType) and set(key: KeyType, value: ValueType) API)

Then you can use it anywhere in your code like {} as Lookup<Array<number>> or {} as Lookup<number[]> (or whatever other type you might need).

As you can see this Lookup<T> type assumes that not every key will return a value, thus the type of values is undefined | T. This is to ensure that TS will force you to check that the returned values are not undefined. You might be tempted to use a different type, where all keys have a defined value, but that will cause TS to not force you to cover the cases when the value might be undefined and might cause runtime errors, if some parts of the code are ever refactored and are not covered by exhaustive (unit) tests.

But if you want to use such a type (at your own risk), it would be something like this

```<code>type DefinedLookup<T> = { [key: string | number]: T }
</code>```

So defining the type of the initial value for the first reduce call is the important first step and with that in place we can also get rid of all the as keyof typeof acc and as keyof typeof idClientsWithPrices in the code.

Using the DefinedLookup<number[]> as the type for the initial value, solves the type check problems, uncovering a new error of a missing return type in the second part of the code. If we add the missing return statement, TS is happy again, and we get

```<code>type DefinedLookup<T> = { [key: string | number]: T }

const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        if (acc[curr.client]) {
            return {...acc, [curr.client]: [...acc[curr.client], curr.price]}
        }
        return {...acc, [curr.client]: [curr.price]}
    }, {} as DefinedLookup<number[]>)

    const idClientsWithSum = Object.keys(idClientsWithPrices).map(id => {
        return {
            id: id,
            sum: idClientsWithPrices[id].reduce((acc: number,curr: number) => {
                return acc + curr
            }, 0)
        }
    })
}
</code>```

Then if we switch to the Lookup<number[]> type, TS will complain about us not checking for the undefined values. in this case both are false-positives, since we made sure that we are constructing the lookup in such a way so that it will always include the keys that we are iterating over.

To tell TS that we as the developer are sure that those key/value pairs will always exists, we can use the non-null assertion operator, which is a post-fix exclamation mark (!). We have to add it in two places, where TS complains about possible undefined values, and we get

```<code>type Lookup<T> = { [key: string | number]: undefined | T }

const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        if (acc[curr.client]) {
            return {...acc, [curr.client]: [...acc[curr.client]!, curr.price]}
        }
        return {...acc, [curr.client]: [curr.price]}
    }, {} as Lookup<number[]>)

    const idClientsWithSum = Object.keys(idClientsWithPrices).map(id => {
        return {
            id: id,
            sum: idClientsWithPrices[id]!.reduce((acc: number,curr: number) => {
                return acc + curr
            }, 0)
        }
    })
}
</code>```

But we could also simplify this part

```<code>   if (acc[curr.client]) {
       return {...acc, [curr.client]: [...acc[curr.client]!, curr.price]}
   }
   return {...acc, [curr.client]: [curr.price]}
</code>```

to just

```<code>   return {...acc, [curr.client]: [...acc[curr.client] || [], curr.price]}
</code>```

Then you don't need the if check or the ternary operator that you have in the commented out code.

And the second part from

```<code>    idClientsWithPrices[id]!.reduce((acc: number,curr: number) => {
        return acc + curr
    }, 0)
</code>```

to

```<code>    idClientsWithPrices[id]?.reduce((acc: number,curr: number) => {
        return acc + curr
    }, 0) || 0
</code>```

or alternatively to

```<code>{} as { [key: string | number]: undefined | Array<number> }
</code>```0

The difference between using ! versus || [] (or ? with || 0) is that in case that the first reduce ever gets refactored and if we ever access a missing key, the first approach with ! will result in a runtime error (because the ! operator does not emit any additional code, it is just an operator to tell TS that we know what we are doing as developers), the second approach, however, won't result in a runtime error, because the extra "safety" code will make sure that even when the value is undefined the sum will simply default to 0. The approach you choose really depends on what type of behavior you want to achieve in your code.

Another change could be to use Object.entries instead of Object.keys when you know that you will have to access the value anyway.
The code is then

```<code>{} as { [key: string | number]: undefined | Array<number> }
</code>```1

From your commented out code (with the ternary operator) I assume that you wanted to pass the whole object along into the lookup table and not just the prices. If you want that, you can just use a different type for the generic type T in Lookup<T>. So first we change {} as Lookup<number[]> to {} as Lookup<Array<typeof state.orders.orders[number]>> and then we fix the first reduce to just return curr instead of curr.price. TS then tells us that there is an error in the second part of the code, which we fix changing the code from curr to curr.price.

The changed code is

```<code>{} as { [key: string | number]: undefined | Array<number> }
</code>```2

Run this code and various options from above in TS Playground

Title: Type problems with reduce in TypeScript

Body:
I have a simple reduce function which would work in JS, but obviously TypeScript doesn't want to allow me use that.
I am supposed to be group clients and find how much they paid for their orders. I wanted to at first make a reduce on orders, so I get an object with idOfClient -> Array of prices.
Then I wanted to make a reduce on the Array of prices, so I would get the sum of the array, but it seems like TypeScript doesn't know that there is an array as a value of key, it sees idClientsWithPrice as empty Object I guess.
With my code I get an error:

Property 'reduce' does not exist on type 'never'.

My code:

export const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        if (acc[curr.client as keyof typeof acc]) {
            return {...acc, [curr.client]: [...acc[curr.client as keyof typeof acc], curr.price]}
        }
        return {...acc, [curr.client]: [curr.price]}

        // acc[curr.client as keyof typeof acc] ?  {...acc, [curr.client]: [...acc[curr.client as keyof typeof acc],curr]} :
        // {...acc, [curr.client]: [curr]}
    }, {})
    const idClientsWithSum = Object.keys(idClientsWithPrices).map(id => {
        return {
            id: id,
            sum: idClientsWithPrices[id as keyof typeof idClientsWithPrices].reduce((acc: number,curr: number) => {
                acc+curr
            }, 0)}
    })
}

Is there any way to handle that?
My second question would be also why the commented code is not equivalent to my if statement? I wanted to do it using tenary operator, but it says that it was not an expression or call

Body:
The source of the problem for the error you are getting is in the first reduce call, because the initialValue parameter (the value {}) determines the return type of the first reduce call and also the type of its acc parameter.
Since you are providing just the value {} as the initial value, without specifying any type along with it, TS correctly assigns it the type of {}.
That is also why you had other errors to take care of before you ended with the code that you have now. All those as keyof typeof acc would not be needed, if this initial value would have a type specified along with it.

So let's define the type that we expect the {} to be. Since we want to make a map/dictionary/LUT (lookup table) from scratch, it will clearly start empty, so the initial value of {} is correct.
The type of this value should be an object that we can index with a key and the values at these keys should have a type of an array of numbers. However when we index a key that does not exist, we will get undefined back.

So the type is then

{} // for the initial value
as { [key: <key-type>]: undefined | <value-type> }
// an object that we can index with a key and returns undefined or a value

Here I assume that your key is of type string | number. In TS an index signature parameter type must be string, number, symbol, or a template literal type anyway.
If we put the actual types in, we get

{} as { [key: string | number]: undefined | Array<number> }

If you don't want to repeat this type every time you need it, you can write it down somewhere in your code base as a type with a generic type parameter, so that it is reusable for other value types as well.

type Lookup<T> = { [key: string | number]: undefined | T }

(TS also has the Map<KeyType, ValueType> type, but that one is for when you use an actual JS Map with new Map() and allows the keys to be of any type, and has a get(key: KeyType) and set(key: KeyType, value: ValueType) API)

Then you can use it anywhere in your code like {} as Lookup<Array<number>> or {} as Lookup<number[]> (or whatever other type you might need).

As you can see this Lookup<T> type assumes that not every key will return a value, thus the type of values is undefined | T. This is to ensure that TS will force you to check that the returned values are not undefined. You might be tempted to use a different type, where all keys have a defined value, but that will cause TS to not force you to cover the cases when the value might be undefined and might cause runtime errors, if some parts of the code are ever refactored and are not covered by exhaustive (unit) tests.

But if you want to use such a type (at your own risk), it would be something like this

type DefinedLookup<T> = { [key: string | number]: T }

So defining the type of the initial value for the first reduce call is the important first step and with that in place we can also get rid of all the as keyof typeof acc and as keyof typeof idClientsWithPrices in the code.

Using the DefinedLookup<number[]> as the type for the initial value, solves the type check problems, uncovering a new error of a missing return type in the second part of the code. If we add the missing return statement, TS is happy again, and we get

type DefinedLookup<T> = { [key: string | number]: T }

const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        if (acc[curr.client]) {
            return {...acc, [curr.client]: [...acc[curr.client], curr.price]}
        }
        return {...acc, [curr.client]: [curr.price]}
    }, {} as DefinedLookup<number[]>)

    const idClientsWithSum = Object.keys(idClientsWithPrices).map(id => {
        return {
            id: id,
            sum: idClientsWithPrices[id].reduce((acc: number,curr: number) => {
                return acc + curr
            }, 0)
        }
    })
}

Then if we switch to the Lookup<number[]> type, TS will complain about us not checking for the undefined values. in this case both are false-positives, since we made sure that we are constructing the lookup in such a way so that it will always include the keys that we are iterating over.

To tell TS that we as the developer are sure that those key/value pairs will always exists, we can use the non-null assertion operator, which is a post-fix exclamation mark (!). We have to add it in two places, where TS complains about possible undefined values, and we get

type Lookup<T> = { [key: string | number]: undefined | T }

const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        if (acc[curr.client]) {
            return {...acc, [curr.client]: [...acc[curr.client]!, curr.price]}
        }
        return {...acc, [curr.client]: [curr.price]}
    }, {} as Lookup<number[]>)

    const idClientsWithSum = Object.keys(idClientsWithPrices).map(id => {
        return {
            id: id,
            sum: idClientsWithPrices[id]!.reduce((acc: number,curr: number) => {
                return acc + curr
            }, 0)
        }
    })
}

But we could also simplify this part

   if (acc[curr.client]) {
       return {...acc, [curr.client]: [...acc[curr.client]!, curr.price]}
   }
   return {...acc, [curr.client]: [curr.price]}

to just

   return {...acc, [curr.client]: [...acc[curr.client] || [], curr.price]}

Then you don't need the if check or the ternary operator that you have in the commented out code.

And the second part from

    idClientsWithPrices[id]!.reduce((acc: number,curr: number) => {
        return acc + curr
    }, 0)

to

    idClientsWithPrices[id]?.reduce((acc: number,curr: number) => {
        return acc + curr
    }, 0) || 0

or alternatively to

    (idClientsWithPrices[id] || []).reduce((acc: number,curr: number) => {
        return acc + curr
    }, 0)

The difference between using ! versus || [] (or ? with || 0) is that in case that the first reduce ever gets refactored and if we ever access a missing key, the first approach with ! will result in a runtime error (because the ! operator does not emit any additional code, it is just an operator to tell TS that we know what we are doing as developers), the second approach, however, won't result in a runtime error, because the extra "safety" code will make sure that even when the value is undefined the sum will simply default to 0. The approach you choose really depends on what type of behavior you want to achieve in your code.

Another change could be to use Object.entries instead of Object.keys when you know that you will have to access the value anyway.
The code is then

const idClientsWithSum = Object.entries(idClientsWithPrices).map(([clientId, clientPrices]) => {
        return {
            id: clientId,
            sum: (clientPrices || []).reduce((acc, curr) => {
                return acc + curr
            }, 0)
        }
    })

From your commented out code (with the ternary operator) I assume that you wanted to pass the whole object along into the lookup table and not just the prices. If you want that, you can just use a different type for the generic type T in Lookup<T>. So first we change {} as Lookup<number[]> to {} as Lookup<Array<typeof state.orders.orders[number]>> and then we fix the first reduce to just return curr instead of curr.price. TS then tells us that there is an error in the second part of the code, which we fix changing the code from curr to curr.price.

The changed code is

type Lookup<T> = { [key: string | number]: undefined | T }

const summaryOfClient = (state: RootStore) => {

    const idClientsWithPrices = state.orders.orders.reduce((acc,curr) => {
        return {...acc, [curr.client]: [...(acc[curr.client] || []), curr]}
    }, {} as Lookup<Array<typeof state.orders.orders[number]>>)

    const idClientsWithSum = Object.entries(idClientsWithPrices).map(([clientId, clientData]) => {
        return {
            id: clientId,
            sum: (clientData || []).reduce((acc, curr) => {
                return acc + curr.price
            }, 0)
        }
    })
}

Run this code and various options from above in <a href="https://www.typescriptlang.org/play?noFallthroughCasesInSwitch=false&suppressImplicitAnyIndexErrors=false#code/C4TwDgpgBASg9nYBlYcBO0C8UDeAoKQqdAEwjQGcAuXAo+086qAQTTQEMQAefe-ogGMANgEsIAO2A0KwNKIkBzKAB8oEgK4BbAEbkANHQH0w8wRBqbd5I-wC+APkK27eV3lCQoAGQQBrDTBuABUnbBwoAG0-CBAZOQVlNSs9NABdGg0JMgAzBQgSVShgqFdPaAARCDyJAt84AKDQqHComLioWXklIpTyDOLSvDwAehGoAHkwYFE4CSgARigACizc-JIRzWFhKCyKDhyIAEoaRTQ4QMSoU1FzChWOB452Lge4HPVtVIpjqB0QFAROIpFBRIUALROYAAC0kYOA5A4Mx6sOgGAoGmEwCgAHdRLDJjoAFYQQTAAB07Qoo3GwThUAARGtqhstljdvtDhBGVASKIKCIOKItOR-mSOBoKNApdcqjU6v5AiEnApZBAOIUPj4lU0nPidupEHiXvMOIphRJZFA0Tc4BQKKIdKIxKAbTDkbT3dB2lAtKJFDCcRJjRAAB4CnEcbLu5HeqAYYAaNC1QoANw4wg00ANuz0e2yrMkJApUAA6jC7jC-RqrbGcaJPrbBHAyGD5ra8pQcRgSBpzGCHhA02KMDkOOT0AUvdHCgKjTiWyPe3iCdXwx6pTMRzaILIKPp44IPUo936A0H23JW-30VkZqKoOQLpRiGgC+tU1AM1m96W8C2Vo4piWhaC8IATDkADCYiSMAAD6cDTLMEjwQs8HCHuFDwQcRwtCssjIhYsAIMgqAYH8mBOPgtiAda4IwSCwAUGWa4AApmGe2CEYiFKMJQfFoGQAm9reyzLBOgj6IIyZoJR1G2PQjaPIIgiRDJ7AUsCcFpH8fDGPQibJvMOAUmZkmHupslabBUgDJEZkUpJVmadpdmHhpaAUrc5hpK4Bn+cYRkprgjkWVEnk2Ux9mRT5EB+YpRBjN68yyqiDKIim4FAnCgh+Hi6B+A8Cjxgcj64lwUBPHiEA7IlhDJToGgNg2DxZGSWHZdK0BITMcyLFVMa9ShUAAMzisIcC4vVUDJcFZqqS5XlucAaRQAA-KF5mqZZkUrfZYWLXttmrR51lxX5UA0KZ21SRF1n7TQS3eZxCX0HYh44HYVUPPKGz1I03B9GgkRpA4xzDPQdENiQjFwSxa5INo+ETCSZKUtSywMSdCOwhxdx7scFJgWAWOFFRtAGfNlMGUQ4I0OChi00QIEM7DOOsXjnEUJE4JpBSonmOJ4WefJNPM4ZEBJiFklQAA1ECskze9h4AAwQwFLgQ7Y1PY0xuMwkjWhuMMyVTH18wLGcFxXD0cUPBJzyvCA7yfMDvz-ICK1gpC0JwvMBJIiiyi2hiWI4vihKo6S5JUrENLQ502hgWgEHQSdiHIXMaH4csPHEfAiAoFOYs0VDcz0ez+uczC+P3Ph+eCcJFBN0wAsFGJEk7Yr7ClzN1M3U53fPY9USOV3anHdFqhqKDxxnZpF2BYQH24N91UA8qwOg+DkNCBXMNw1IBtGyjaOx5jevwzXdeE8THCk+CLQKVTUvGeLtP0z7TMS8luIytKeMABCFYIYJAQm2LsJ40o0AW2IJATg5E-ioCgJhHEwQkBQD8CGXE9YapVQwEnQhsJ5xP0zBVF2T4Iz7h+vGdoysWbaDZkfZiN9ua8xIGkIB7c+xCwngvOSz8P4SwTG-GWql5Y9zQAwleasNbGGXqUbWktpYByrtfRG2gTZenNiNAATNbS4YBrj20eE7TglDtTuz+ACIEJ0fZQChClBEQdrihz3OHVcUdz6UjgvIPcAED5J1AuBSCLDM4W3gno3O+caCFzIiXIRZd95AR9iwg2t8HjcWAERVuAl+It0FhAYWO1RZJP7mIkyh07ojxOgdMyE9anTxULPXSAiXoEzekQVeX1aGbyCGwCxQNvjkAcLvWiQSr7HxrqfbA0d0YUj8eICgZN0lsIJr8e+pNljqROgASRIB5E6mTdLlNfqo4Rxgv4rQOT-ZmrM7FMUyetHhncRayT7iIlR79ZYK08jI0ociZ5QFVjNRRdhlFEF1uo6ZmjjbuDNlneYo1DG22ULiGEcBMIrBWn8EgyIODEB8cVKQcACEWIeLY72T8nFogDplZEbiGRh2xF46s8zY5LICYnECKc07hOGtnca2A845MRHE0ixcKLlImakqZrD2LcwbmKiAeSW4FNeXwiyZSKb6QEAPapu0Hp1KeuPZyU8dLArngIrpsi159N1NwQZXBuDlG1I3DVBTIjAzBuM8ucqYUKthLMokMdfFSH8Ss+VGTuZExJuJXZTFbmPLghUAlpzdUVIuXqz+JAaA3MOQCh5ywVpppyVa3Smrin8KkZ8r5DVxieUHPGDFWLoAkJ6HCDAh4SqCCeNAEAlx1AQAKMQNE75TBIXIDMM8KC+3CBksIIig0QAdsUAC754jBCSNipxAFq91Zgq1nvQg0K1lwu0YnREsgy2EvCLYAp10ZqPqiACiIK0aAAHIVoQgWJ+w8cUaBLA+m+lNUgv0-r0f+m4nEaDRJAyI99J0IMnQhKNaDgGxqAtAx+qA37UN-oA7BqAAAWbDiGwPSDw5BjDxGACs5HjBpBcJeiubaKSTUUHnZOoT05MQiShNCGEsI4W5Msa9wBb3HAhnRdjnHuMhNTmEjOgrUILHE3uSTBLpOBKtHJuAXHeW8YFUiqJGmb3aZk2xzCHGDMKb5cp-jqn4KjXM1pnJOmgA" rel="nofollow noreferrer">TS Playground


问:
What is 'cycle' in specman events
I have stumbled upon e code written like that:

event a is cycle @b;

Removing the 'cycle' from this event, made no difference in behavior.

What is the meaning of cycle here?

Thanks

答:
"event a is cycle @b;" is a trick to respond to event triggering, but do so at the end of the current tick.
For example, the following code would print "hello world", instead of "world hello" if we did "on b".</p>
```<code>event b;
event a is cycle @b;

foo() is {
  emit b;
  message(NONE, "hello");
};

on a {
    message(NONE, "world");
};
</code>```

Title: What is 'cycle' in specman events

Body:
"event a is cycle @b;" is a trick to respond to event triggering, but do so at the end of the current tick.
For example, the following code would print "hello world", instead of "world hello" if we did "on b".

event b;
event a is cycle @b;

foo() is {
  emit b;
  message(NONE, "hello");
};

on a {
    message(NONE, "world");
};


问:
SelectList always null on POST causes Model State to be Invalid
I understand that the SelectListItems are meant to not return back the items on post and perhaps be null, but because of this my ModelState.IsValid condition is always false and the Studies field which contains the list is the one with the invalid attribute. I tried different methods and am stuck on resolving this

View

```<code> <label asp-for="Studies" class="form-label"></label>
 <select asp-for="SelectedStudyGuid" asp-items="@Model.Studies" class="form-control" autocomplete="off">
   <option value="">Select Study</option>
 </select>
 <span asp-validation-for="SelectedStudyGuid" class="text-danger"></span>
</code>```

ViewModel

```<code>public class AddStudyViewModel
{
    public string ParticipantGuid { get; set; }

    public IEnumerable<SelectListItem> Studies { get; set; }
    public string SelectedStudyGuid { get; set; }

    [DataType(DataType.Date)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EndDate { get; set; }
}
</code>```

Controller

```<code>  private List<SelectListItem> GetStudyCatalog()
    {
        return _repo.GetStudyCatalog().Select(s => new SelectListItem
        {
            Text = s.Name,
            Value = s.Guid
        }).ToList();
    }

    [HttpGet]
    public IActionResult AddStudy(string participantGuid)
    {
        var model = new AddStudyViewModel
        {
            Studies = GetStudyCatalog(),
            ParticipantGuid = participantGuid
        };

        return PartialView("_AddStudyModal", model);
    }

    [HttpPost]
    public IActionResult AddStudy(AddStudyViewModel model)
    {
        if (ModelState.IsValid)
        {
           var response= _repo.AddStudy(model.SelectedStudyGuid, model.ParticipantGuid, model.StartDate, model.EndDate);

            if (response.Success)
            {
                TempData["Message"] = response.Message;
                return RedirectToAction("EditParticipant", new {id = response.NewGuid});
            }
        }

        model.Studies = GetStudyCatalog();
        return PartialView("_AddStudyModal", model);
    }
</code>```

答:
This can happen only if you use net 6. To fix it simply make Studies nullable

```<code>public List<SelectListItem>? Studies { get; set; }
</code>```

or what is the smart developers do , they just remove nullables from the projests

```<code> <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
</code>```

to use a ViewBag instead of a ViewModel is very unprofessional

Body:
I understand that the SelectListItems are meant to not return back the items on post and perhaps be null, but because of this my ModelState.IsValid condition is always false and the Studies field which contains the list is the one with the invalid attribute. I tried different methods and am stuck on resolving this

View

 <select asp-for="SelectedStudyGuid" asp-items="@Model.Studies" class="form-control" autocomplete="off">
   <option value="">Select Study</option>
 </select>

ViewModel

public class AddStudyViewModel
{
    public string ParticipantGuid { get; set; }

    public IEnumerable<SelectListItem> Studies { get; set; }
    public string SelectedStudyGuid { get; set; }

    [DataType(DataType.Date)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EndDate { get; set; }
}

Controller

  private List<SelectListItem> GetStudyCatalog()
    {
        return _repo.GetStudyCatalog().Select(s => new SelectListItem
        {
            Text = s.Name,
            Value = s.Guid
        }).ToList();
    }

    [HttpGet]
    public IActionResult AddStudy(string participantGuid)
    {
        var model = new AddStudyViewModel
        {
            Studies = GetStudyCatalog(),
            ParticipantGuid = participantGuid
        };

        return PartialView("_AddStudyModal", model);
    }

    [HttpPost]
    public IActionResult AddStudy(AddStudyViewModel model)
    {
        if (ModelState.IsValid)
        {
           var response= _repo.AddStudy(model.SelectedStudyGuid, model.ParticipantGuid, model.StartDate, model.EndDate);

            if (response.Success)
            {
                TempData["Message"] = response.Message;
                return RedirectToAction("EditParticipant", new {id = response.NewGuid});
            }
        }

        model.Studies = GetStudyCatalog();
        return PartialView("_AddStudyModal", model);
    }

Body:
This can happen only if you use net 6. To fix it simply make Studies nullable

public List<SelectListItem>? Studies { get; set; }

or what is the smart developers do , they just remove nullables from the projests

 <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->

to use a ViewBag instead of a ViewModel is very unprofessional


问:
The request was missing an Authentication Key, Error 401
I am trying to send Notifications and Data from Postman, To FCM, to my App. However i run into this 401 Error about me missing my authentication key. I have no clue what i have done wrong, i have correctly put in my Authentication key so i am very confused as to what is going on. Can someone please help.

I Followed this Tutorial

答: It was a rather silly mistake. Simply i needed to put my values in Header, not Params


问:
Azure function which just inserts a record into a snowflake table is working fine but failing because of timeout issue sometime
I have an Azure function that inserts a record into a snowflake table. The function is working fine but sometimes the function is failing because of a timeout issue. The below work code is handled in the host.json file. The application insight logs say that it is a timeout error. Though the retry option is given as 3. The function fails again.

"extensions": {
"concurrency": {
"dynamicConcurrencyEnabled": true,
"snapshotPersistenceEnabled": true
}
}
}

Any solution to fix this issue?

答:
Timeout on the back end trying to reach an external resource. Outside of the external resource not accepting the connection SNAT port exhaustion is the most common reason for these time out failures. This article does a great job of describing SNAT https://4lowtherabbit.github.io/blogs/2019/10/SNAT/

you can also check if this is an issue using the Diagnose and Solve problems blade in the Azure portal
https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-intermittent-outbound-connection-errors#:~:text=To%20find%20SNAT%20port%20allocation%20information%2C%20follow%20the,to%20keep%20it%20below%20128.%20...%20See%20More.