问:
after decimal why twoo zeros not consider in double
```<code>private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {
        double input = 300.00;

        System.out.println("double : " + input);

        Double d=Double.valueOf(df.format(input));
       System.out.println("##1::"+d);
       System.out.println("##2 ::"+df.format(input));
       System.out.println("##3 ::"+Double.valueOf(df.format(input)));
    }
}
</code>```

Output:

```<code>double : 300.0
##1::300.0
##2 ::300.00
##3 ::300.0
</code>```

Expected output: 300.00

答:
You can use BigDecimal for scale and round double. Try this :

```<code>import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test {

    public static void main(String[] args) {
        BigDecimal input = BigDecimal.valueOf(300);

        System.out.println("double 2 digit: " + Test.round(input, 2));
        System.out.println("double 5 digit: " + Test.round(input, 5));
    }

    public static BigDecimal round(BigDecimal bd, int scale) {
        return bd.setScale(scale, RoundingMode.HALF_UP);
    }
}
</code>```

Output like this :

```<code>double 2 digit: 300.00
double 5 digit: 300.00000
</code>```

Body:
private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {
        double input = 300.00;

        System.out.println("double : " + input);

        Double d=Double.valueOf(df.format(input));
       System.out.println("##1::"+d);
       System.out.println("##2 ::"+df.format(input));
       System.out.println("##3 ::"+Double.valueOf(df.format(input)));
    }
}

Output:

double : 300.0
##1::300.0
##2 ::300.00
##3 ::300.0

Expected output: 300.00

Body:
You can use BigDecimal for scale and round double. Try this :

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test {

    public static void main(String[] args) {
        BigDecimal input = BigDecimal.valueOf(300);

        System.out.println("double 2 digit: " + Test.round(input, 2));
        System.out.println("double 5 digit: " + Test.round(input, 5));
    }

    public static BigDecimal round(BigDecimal bd, int scale) {
        return bd.setScale(scale, RoundingMode.HALF_UP);
    }
}

Output like this :

double 2 digit: 300.00
double 5 digit: 300.00000


来源: stackexchange

问:
Mysql - split result when camelcase is found
I have my table with with one column called name, containing names of people in camelCase format, but I need to select those names separate by one space when a capital letter is found: for example, my table would be like this:

```<code>|name          |
----------------
| JosephJackson|
|AidenChase    |
|LukeBenjamin  |
</code>```

but I want to get in this way:

```<code> |name          |
 ----------------
 | Joseph Jackson|
 |Aiden Chase    |
 |Luke Benjamin  |
</code>```

How do I should use my SELECT? thanks

答:
I had improved @MaheshYadav code. This will change any string into proper case.

```<code>DELIMITER @@
DROP FUNCTION IF EXISTS change_case@@
CREATE FUNCTION change_case (word VARCHAR(15000)) RETURNS VARCHAR(15000)
COMMENT 'Change the case to Proper Case, A-Z (65-90 decimal|ASCII) ,
  but if first char in between a-z (97-122) than change case to upper' DETERMINISTIC
BEGIN
  SET @text = word; -- input str
  SET @result = ""; -- modified str
  SET @i = 2;       -- counter
  -- if first char is in between a-z than change to upper
  IF ASCII(SUBSTRING(@text, 1, 1)) BETWEEN 97 AND 122 THEN
    SET @text = CONCAT(UPPER(SUBSTRING(@text, 1, 1)), SUBSTRING(@text, 2));
  END IF;
  SET @result = UPPER(SUBSTRING(@text, 1, 1));
  WHILE @i <= LENGTH(@text) DO
    SET @t = SUBSTRING(@text, @i, 1);
    SET @p = SUBSTRING(@text, @i-1, 1);
    -- if curr_char is upper and pre_char is lower then insert space and the char       eg coName   > co Name
    IF ASCII(@t) BETWEEN 65 AND 90 AND ASCII(@p) BETWEEN 97 AND 122 THEN
    -- eg SomeCO   > Some CO
        SET @result = CONCAT(@result,' ', @t);
    -- pre_char is space & curr_char is lower
    ELSEIF (ASCII(@p) = 32 OR @p = '_' OR @p = '-') AND ASCII(@t) BETWEEN 97 AND 122 THEN
    -- eg some cO  > some CO
      SET @result = CONCAT(@result,' ', UPPER(@t));
    ELSEIF @t = '_' OR @t = '-' THEN
    -- Replace _ OR - > space
      SET @result = CONCAT(@result,' ');
    -- for lower case
    ELSE
    -- someco        > someco
      SET @result = CONCAT(@result, @t);
    END IF;
    SET @i = @i + 1;
  END WHILE;
  SET @result = REGEXP_REPLACE(@result, '[ ]+', ' ');
  RETURN @result;
END @@
</code>```

DELIMITER ;

Example use:

```<code>SET @val = 'someVillage';
SELECT @val, change_case(@val) `mod`;

SET @val = 'some village';
SELECT @val, change_case(@val) `mod`;

SET @val = 'some_village';
SELECT @val, change_case(@val) `mod`;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have my table with with one column called name, containing names of people in camelCase format, but I need to select those names separate by one space when a capital letter is found: for example, my table would be like this:

|name          |
----------------
| JosephJackson|
|AidenChase    |
|LukeBenjamin  |

but I want to get in this way:

 |name          |
 ----------------
 | Joseph Jackson|
 |Aiden Chase    |
 |Luke Benjamin  |

How do I should use my SELECT? thanks

Body:
I had improved @MaheshYadav code. This will change any string into proper case.

DELIMITER @@
DROP FUNCTION IF EXISTS change_case@@
CREATE FUNCTION change_case (word VARCHAR(15000)) RETURNS VARCHAR(15000)
COMMENT 'Change the case to Proper Case, A-Z (65-90 decimal|ASCII) ,
  but if first char in between a-z (97-122) than change case to upper' DETERMINISTIC
BEGIN
  SET @text = word; -- input str
  SET @result = ""; -- modified str
  SET @i = 2;       -- counter
  -- if first char is in between a-z than change to upper
  IF ASCII(SUBSTRING(@text, 1, 1)) BETWEEN 97 AND 122 THEN
    SET @text = CONCAT(UPPER(SUBSTRING(@text, 1, 1)), SUBSTRING(@text, 2));
  END IF;
  SET @result = UPPER(SUBSTRING(@text, 1, 1));
  WHILE @i <= LENGTH(@text) DO
    SET @t = SUBSTRING(@text, @i, 1);
    SET @p = SUBSTRING(@text, @i-1, 1);
    -- if curr_char is upper and pre_char is lower then insert space and the char       eg coName   > co Name
    IF ASCII(@t) BETWEEN 65 AND 90 AND ASCII(@p) BETWEEN 97 AND 122 THEN
    -- eg SomeCO   > Some CO
        SET @result = CONCAT(@result,' ', @t);
    -- pre_char is space & curr_char is lower
    ELSEIF (ASCII(@p) = 32 OR @p = '_' OR @p = '-') AND ASCII(@t) BETWEEN 97 AND 122 THEN
    -- eg some cO  > some CO
      SET @result = CONCAT(@result,' ', UPPER(@t));
    ELSEIF @t = '_' OR @t = '-' THEN
    -- Replace _ OR - > space
      SET @result = CONCAT(@result,' ');
    -- for lower case
    ELSE
    -- someco        > someco
      SET @result = CONCAT(@result, @t);
    END IF;
    SET @i = @i + 1;
  END WHILE;
  SET @result = REGEXP_REPLACE(@result, '[ ]+', ' ');
  RETURN @result;
END @@

DELIMITER ;

Example use:

SET @val = 'someVillage';
SELECT @val, change_case(@val) `mod`;

SET @val = 'some village';
SELECT @val, change_case(@val) `mod`;

SET @val = 'some_village';
SELECT @val, change_case(@val) `mod`;

ContentLicense: CC BY-SA 4.0


问:
How to display pages from a nested folder in asp.net core 3.1
I get the below exception when I try to run the application , I know the reason is it couldn't find the file. But any alternative to serve this file?

Folder structure :

I Tried using "UseContentRoot" but couldn't fix the issue

```<code>   CreateHostBuilder(args).UseContentRoot(Directory.GetCurrentDirectory() + "\\PersonalTab").Build().Run();
</code>```

Exception :
InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml

When I try the views from outside of "PersonalTab" folder it works fine, but for my requirement it needs to be inside "PersonalTab" folder?

Note : Am using asp.net core 3.1

答:
You can configure RazorViewEngineOptions to also look under PersonalTab folder. I tried to recreate a project and added this to Startup class ConfigureServices method and it worked for me:

```<code>services.Configure<RazorViewEngineOptions>(o =>
        {
            o.ViewLocationFormats.Add("/PersonalTab/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
            o.ViewLocationFormats.Add("/PersonalTab/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
        });
</code>```

Ref: Change Default Location of Views and Razor Pages in ASP.NET Core

Body:
I get the below exception when I try to run the application , I know the reason is it couldn't find the file. But any alternative to serve this file?

Folder structure :

I Tried using "UseContentRoot" but couldn't fix the issue

   CreateHostBuilder(args).UseContentRoot(Directory.GetCurrentDirectory() + "\\PersonalTab").Build().Run();

Exception :
InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml

When I try the views from outside of "PersonalTab" folder it works fine, but for my requirement it needs to be inside "PersonalTab" folder?

Note : Am using asp.net core 3.1

Body:
You can configure RazorViewEngineOptions to also look under PersonalTab folder. I tried to recreate a project and added this to Startup class ConfigureServices method and it worked for me:

services.Configure<RazorViewEngineOptions>(o =>
        {
            o.ViewLocationFormats.Add("/PersonalTab/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
            o.ViewLocationFormats.Add("/PersonalTab/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
        });

Ref: Change Default Location of Views and Razor Pages in ASP.NET Core


问:
Start download PDF file automatically
I want to download PDF file automatically. It is downloading but it is giving "Failed to load PDF document."</p>

```<code>$select = "SELECT * FROM `success-stories` where id='$id'";
       $result = $conn->query($select);
       $row = $result->fetch_assoc();
       $file=$row["download_pdf"];
       $file_arr=explode("/",$file);
       $path=$file_arr[0]."/".$file_arr[1]."/".$file_arr[2];
       $pdf_file=$file_arr[2];
      //  echo $file."<br/>";
      //  print_r($path);
      //  die;
       if(file_exists($path))
       {
        header("Content-disposition: attachment; filename=".$path."");
        header("Content-type: application/pdf");
        readfile($path);
       }
</code>```

答:
Change

```<code>header("Content-disposition: attachment; filename=".$path."");
</code>```

to

```<code>header('Content-disposition: attachment; filename="'.basename($path).'"');
</code>```

As mentioned by @kmoser in the comments, as a safety measure, you can do htmlentities() on the basename() if you are actually saving the uploaded file as is with the same name. So it would look like:

```<code>header('Content-disposition: attachment; filename="'.htmlentities(basename($path)).'"');
</code>```

Title: Start download PDF file automatically

Body:
I want to download PDF file automatically. It is downloading but it is giving "Failed to load PDF document."

$select = "SELECT * FROM `success-stories` where id='$id'";
       $result = $conn->query($select);
       $row = $result->fetch_assoc();
       $file=$row["download_pdf"];
       $file_arr=explode("/",$file);
       $path=$file_arr[0]."/".$file_arr[1]."/".$file_arr[2];
       $pdf_file=$file_arr[2];
      //  echo $file."
";
      //  print_r($path);
      //  die;
       if(file_exists($path))
       {
        header("Content-disposition: attachment; filename=".$path."");
        header("Content-type: application/pdf");
        readfile($path);
       }

Body:
Change

header("Content-disposition: attachment; filename=".$path."");

to

header('Content-disposition: attachment; filename="'.basename($path).'"');

As mentioned by @kmoser in the comments, as a safety measure, you can do htmlentities() on the basename() if you are actually saving the uploaded file as is with the same name. So it would look like:

header('Content-disposition: attachment; filename="'.htmlentities(basename($path)).'"');


问:
Set URLSession Delegate To Another Swift Class
I am attempting to call an API to login to a website. I currently have all my API calls in a swift class called APICalls. My view controller I'm using to login with is called CreateAccountViewController.

In my API call to login I create a URL session and set the delegate like this:

```<code>let task = URLSession.init(configuration: URLSessionConfiguration.default, delegate: CreateAccountViewController.init(), delegateQueue: nil)

task.dataTask(with: request).resume()
</code>```

Then in my VC class I have this function

```<code>func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError: Error?) {
    // Check the data returned from API call, ensure user is logged in
}
</code>```

This function is being called when the API is done, but I feel like I'm causing a memory leak or something by using .init in the delegate declaration when creating my URL session. Is there a better way to do this?

Also, how do I access the data from the API call? In completion handlers there's a data response I can get at, but not in this delegate call.

答:
Yes, you technically can have a separate object be the delegate for the session. But it doesn’t make much sense to instantiate a view controller for this, for a few reasons:

Your code is creating a view controller instance as the delegate object, but you’re handing this off to the URLSession without keeping a reference to it. Thus, there’s no way to add this to the view controller hierarchy (e.g. to present it, to push to it, perform a segue to it, whatever).

Sure, you might be presenting another instance of this view controller elsewhere, but that will be a completely separate instance, with no connection to the one you just created here. You’d end up with two separate CreateAccountViewController objects.

From an architectural perspective, many would argue that network delegate code doesn’t really belong in view controllers, anyway. View controllers are for populating views and responding to user events, not for network code.

So, in short, while you technically can have your API manager class use a separate object for the delegate calls, that’s a bit unusual. And if you did do that, you certainly wouldn’t create a UIViewController subclass for that.

A more common pattern (if you use the delegate pattern at all) might be to make the API manager, itself, the delegate for its URLSession. (Adding a separate dedicate delegate object in the mix probably only complicates the situation.) But by keeping all of this network-specific code out of the view controllers, you abstract your view controllers away from the gory details of parsing network responses, handling all of the various delegate methods, etc.

All of this begs the question: Do you really need to use the delegate-based API? It’s critical in those rare cases where you need the rich delegate API (handling custom challenge responses, etc.), but in most cases, the simple completion handler rendition of dataTask is much easier.

Give your API method a completion handler closure, so that the caller can specify what should happen if the network request succeeds. You can do this with delegate based sessions, but it’s a lot more complicated and we’d generally only go down that rabbit hole if absolutely necessary, which is not the case here.

So a common pattern would be to give your API manager (which I’ll assume is a singleton) a login method, like so:

```<code>/// Perform login request
///
/// - Parameters:
///   - userid: Userid string.
///   - password: Password string
///   - completion: Calls with `.success(true)` if successful. Calls `.failure(Error)` on error.
///
/// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

@discardableResult
func login(userid: String, password: String, completion: @escaping (Result<Bool, Error>) -> Void) -> URLSessionTask {
    let request = ... // Build your `URLRequest` here

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard
            error == nil,
            let responseData = data,
            let httpResponse = response as? HTTPURLResponse,
            200 ..< 300 ~= httpResponse.statusCode
        else {
            DispatchQueue.main.async { completion(.failure(error ?? APIManagerError.invalidResponse(data, response))) }
            return
        }

        // parse `responseData` here

        let success = true

        DispatchQueue.main.async {
            if success {
                completion(.success(true))
            } else {
                completion(.failure(error))
            }
        }
    }
    task.resume()
    return task
}
</code>```

Where you might have a custom error class like so:

```<code>enum APIManagerError: Error {
    case invalidResponse(Data?, URLResponse?)
    case loginFailed(String)
}
</code>```

And you’d call it like so:

```<code>APIManager.shared.login(userid: userid, password: password) { result in
    switch result {
    case .failure(let error):
        // update UI to reflect error
        print(error)

    case .success:
        // do whatever you want if the login was successful
    }
}
</code>```

Below is a more complete example, where I’ve broken up the network code down a bit (one to perform network requests, one generic method for parsing JSON, one specific method to parse the JSON associated with login), but the idea is still the same. When you perform an asynchronous method, give the method an @escaping completion handler closure which is called when the asynchronous task is done.

```<code>final class APIManager {
    static let shared = APIManager()

    private var session: URLSession

    private init() {
        session = .shared
    }

    let baseURLString = "https://example.com"

    enum APIManagerError: Error {
        case invalidResponse(Data?, URLResponse?)
        case loginFailed(String)
    }

    /// Perform network request with `Data` response.
    ///
    /// - Parameters:
    ///   - request: The `URLRequest` to perform.
    ///   - completion: Calls with `.success(Data)` if successful. Calls `.failure(Error)` on error.
    ///
    /// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

    @discardableResult
    func perform(_ request: URLRequest, completion: @escaping (Result<Data, Error>) -> Void) -> URLSessionTask {
        let task = session.dataTask(with: request) { data, response, error in
            guard
                error == nil,
                let responseData = data,
                let httpResponse = response as? HTTPURLResponse,
                200 ..< 300 ~= httpResponse.statusCode
            else {
                completion(.failure(error ?? APIManagerError.invalidResponse(data, response)))
                return
            }

            completion(.success(responseData))
        }

        task.resume()
        return task
    }

    /// Perform network request with JSON response.
    ///
    /// - Parameters:
    ///   - request: The `URLRequest` to perform.
    ///   - completion: Calls with `.success(Data)` if successful. Calls `.failure(Error)` on error.
    ///
    /// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

    @discardableResult
    func performJSON<T: Decodable>(_ request: URLRequest, of type: T.Type, completion: @escaping (Result<T, Error>) -> Void) -> URLSessionTask {
        return perform(request) { result in
            switch result {
            case .failure(let error):
                completion(.failure(error))

            case .success(let data):
                do {
                    let responseObject = try JSONDecoder().decode(T.self, from: data)
                    completion(.success(responseObject))
                } catch let parseError {
                    completion(.failure(parseError))
                }
            }
        }
    }

    /// Perform login request
    ///
    /// - Parameters:
    ///   - userid: Userid string.
    ///   - password: Password string
    ///   - completion: Calls with `.success()` if successful. Calls `.failure(Error)` on error.
    ///
    /// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

    @discardableResult
    func login(userid: String, password: String, completion: @escaping (Result<Bool, Error>) -> Void) -> URLSessionTask {
        struct ResponseObject: Decodable {
            let success: Bool
            let message: String?
        }

        let request = prepareLoginRequest(userid: userid, password: password)

        return performJSON(request, of: ResponseObject.self) { result in
            switch result {
            case .failure(let error):
                completion(.failure(error))

            case .success(let responseObject):
                if responseObject.success {
                    completion(.success(true))
                } else {
                    completion(.failure(APIManagerError.loginFailed(responseObject.message ?? "Unknown error")))
                }
                print(responseObject)
            }
        }
    }

    private func prepareLoginRequest(userid: String, password: String) -> URLRequest {
        var components = URLComponents(string: baseURLString)!
        components.query = "login"
        components.queryItems = [
            URLQueryItem(name: "userid", value: userid),
            URLQueryItem(name: "password", value: password)
        ]

        var request = URLRequest(url: components.url!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        return request
    }
}
</code>```

Body:
I am attempting to call an API to login to a website. I currently have all my API calls in a swift class called APICalls. My view controller I'm using to login with is called CreateAccountViewController.

In my API call to login I create a URL session and set the delegate like this:

let task = URLSession.init(configuration: URLSessionConfiguration.default, delegate: CreateAccountViewController.init(), delegateQueue: nil)

task.dataTask(with: request).resume()

Then in my VC class I have this function

func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError: Error?) {
    // Check the data returned from API call, ensure user is logged in
}

This function is being called when the API is done, but I feel like I'm causing a memory leak or something by using .init in the delegate declaration when creating my URL session. Is there a better way to do this?

Also, how do I access the data from the API call? In completion handlers there's a data response I can get at, but not in this delegate call.

Body:
Yes, you technically can have a separate object be the delegate for the session. But it doesn’t make much sense to instantiate a view controller for this, for a few reasons:

Your code is creating a view controller instance as the delegate object, but you’re handing this off to the URLSession without keeping a reference to it. Thus, there’s no way to add this to the view controller hierarchy (e.g. to present it, to push to it, perform a segue to it, whatever).

Sure, you might be presenting another instance of this view controller elsewhere, but that will be a completely separate instance, with no connection to the one you just created here. You’d end up with two separate CreateAccountViewController objects.

From an architectural perspective, many would argue that network delegate code doesn’t really belong in view controllers, anyway. View controllers are for populating views and responding to user events, not for network code.

So, in short, while you technically can have your API manager class use a separate object for the delegate calls, that’s a bit unusual. And if you did do that, you certainly wouldn’t create a UIViewController subclass for that.

A more common pattern (if you use the delegate pattern at all) might be to make the API manager, itself, the delegate for its URLSession. (Adding a separate dedicate delegate object in the mix probably only complicates the situation.) But by keeping all of this network-specific code out of the view controllers, you abstract your view controllers away from the gory details of parsing network responses, handling all of the various delegate methods, etc.

All of this begs the question: Do you really need to use the delegate-based API? It’s critical in those rare cases where you need the rich delegate API (handling custom challenge responses, etc.), but in most cases, the simple completion handler rendition of dataTask is much easier.

Give your API method a completion handler closure, so that the caller can specify what should happen if the network request succeeds. You can do this with delegate based sessions, but it’s a lot more complicated and we’d generally only go down that rabbit hole if absolutely necessary, which is not the case here.

So a common pattern would be to give your API manager (which I’ll assume is a singleton) a login method, like so:

/// Perform login request
///
/// - Parameters:
///   - userid: Userid string.
///   - password: Password string
///   - completion: Calls with `.success(true)` if successful. Calls `.failure(Error)` on error.
///
/// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

@discardableResult
func login(userid: String, password: String, completion: @escaping (Result<Bool, Error>) -> Void) -> URLSessionTask {
    let request = ... // Build your `URLRequest` here

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard
            error == nil,
            let responseData = data,
            let httpResponse = response as? HTTPURLResponse,
            200 ..< 300 ~= httpResponse.statusCode
        else {
            DispatchQueue.main.async { completion(.failure(error ?? APIManagerError.invalidResponse(data, response))) }
            return
        }

        // parse `responseData` here

        let success = true

        DispatchQueue.main.async {
            if success {
                completion(.success(true))
            } else {
                completion(.failure(error))
            }
        }
    }
    task.resume()
    return task
}

Where you might have a custom error class like so:

enum APIManagerError: Error {
    case invalidResponse(Data?, URLResponse?)
    case loginFailed(String)
}

And you’d call it like so:

APIManager.shared.login(userid: userid, password: password) { result in
    switch result {
    case .failure(let error):
        // update UI to reflect error
        print(error)

    case .success:
        // do whatever you want if the login was successful
    }
}

Below is a more complete example, where I’ve broken up the network code down a bit (one to perform network requests, one generic method for parsing JSON, one specific method to parse the JSON associated with login), but the idea is still the same. When you perform an asynchronous method, give the method an @escaping completion handler closure which is called when the asynchronous task is done.

final class APIManager {
    static let shared = APIManager()

    private var session: URLSession

    private init() {
        session = .shared
    }

    let baseURLString = "https://example.com"

    enum APIManagerError: Error {
        case invalidResponse(Data?, URLResponse?)
        case loginFailed(String)
    }

    /// Perform network request with `Data` response.
    ///
    /// - Parameters:
    ///   - request: The `URLRequest` to perform.
    ///   - completion: Calls with `.success(Data)` if successful. Calls `.failure(Error)` on error.
    ///
    /// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

    @discardableResult
    func perform(_ request: URLRequest, completion: @escaping (Result<Data, Error>) -> Void) -> URLSessionTask {
        let task = session.dataTask(with: request) { data, response, error in
            guard
                error == nil,
                let responseData = data,
                let httpResponse = response as? HTTPURLResponse,
                200 ..< 300 ~= httpResponse.statusCode
            else {
                completion(.failure(error ?? APIManagerError.invalidResponse(data, response)))
                return
            }

            completion(.success(responseData))
        }

        task.resume()
        return task
    }

    /// Perform network request with JSON response.
    ///
    /// - Parameters:
    ///   - request: The `URLRequest` to perform.
    ///   - completion: Calls with `.success(Data)` if successful. Calls `.failure(Error)` on error.
    ///
    /// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

    @discardableResult
    func performJSON<T: Decodable>(_ request: URLRequest, of type: T.Type, completion: @escaping (Result<T, Error>) -> Void) -> URLSessionTask {
        return perform(request) { result in
            switch result {
            case .failure(let error):
                completion(.failure(error))

            case .success(let data):
                do {
                    let responseObject = try JSONDecoder().decode(T.self, from: data)
                    completion(.success(responseObject))
                } catch let parseError {
                    completion(.failure(parseError))
                }
            }
        }
    }

    /// Perform login request
    ///
    /// - Parameters:
    ///   - userid: Userid string.
    ///   - password: Password string
    ///   - completion: Calls with `.success()` if successful. Calls `.failure(Error)` on error.
    ///
    /// - Returns: The `URLSessionTask` of the network request (in case caller wants to cancel request).

    @discardableResult
    func login(userid: String, password: String, completion: @escaping (Result<Bool, Error>) -> Void) -> URLSessionTask {
        struct ResponseObject: Decodable {
            let success: Bool
            let message: String?
        }

        let request = prepareLoginRequest(userid: userid, password: password)

        return performJSON(request, of: ResponseObject.self) { result in
            switch result {
            case .failure(let error):
                completion(.failure(error))

            case .success(let responseObject):
                if responseObject.success {
                    completion(.success(true))
                } else {
                    completion(.failure(APIManagerError.loginFailed(responseObject.message ?? "Unknown error")))
                }
                print(responseObject)
            }
        }
    }

    private func prepareLoginRequest(userid: String, password: String) -> URLRequest {
        var components = URLComponents(string: baseURLString)!
        components.query = "login"
        components.queryItems = [
            URLQueryItem(name: "userid", value: userid),
            URLQueryItem(name: "password", value: password)
        ]

        var request = URLRequest(url: components.url!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        return request
    }
}


问:
MVVM, Threading and Image Source DataBinidng
I have an MVVM implementation in which I have a WPF ListBox that will contain a collection of child WPF Image controls. The Source for each control may change as often as 3 times per second.  When I have just a single image in my list, life is grand and my app is responsive.  When I start having 4 or 5 my application child images, my app starts grinding, I should also mention that I have to a Bitmap to BitmapSource conversion for each new and or updated image that I have.

How should I update my children controls Source property while keeping my application as responsive as possible?

Here is the current code in my ViewModel:

```<code>public BitmapSource CameraBitmapSource
    {
        get
        {
            Application.Current.Dispatcher.BeginInvoke((Action)delegate
                    {
                        BuildImageSource();
                    }, DispatcherPriority.Background);

            return this.cameraBitmapSource;
         }
    }
</code>```

BuildImageSource() is where I fetch my new bitmap and convert to a BitmapSource and then assign to my private cameraBitmapSource object.

答:
Because you use Dispatcher.BeginInvoke, you're doing all the work on the UI thread, which makes your app unresponsive. You should build the images on a separate thread. The easiest way to do that is to make the binding asynchronous, and call your BuildImageSource method directly.

ViewModel

public BitmapSource CameraBitmapSource
{
    get
    {
        BuildImageSource();
        return this.cameraBitmapSource;
    }
}
```

<p><strong>XAML</strong></p>

```<Image Source="{Binding CameraBitmapSource, IsAsync=True}" />
```

Just remember to Freeze the ImageSource in BuildImageSource so that it can be used on the UI thread (DependencyObjects can only be used on the thread that created them, unless they're Freezable and frozen)

Body:
I have an MVVM implementation in which I have a WPF ListBox that will contain a collection of child WPF Image controls. The Source for each control may change as often as 3 times per second.  When I have just a single image in my list, life is grand and my app is responsive.  When I start having 4 or 5 my application child images, my app starts grinding, I should also mention that I have to a Bitmap to BitmapSource conversion for each new and or updated image that I have.

How should I update my children controls Source property while keeping my application as responsive as possible?

Here is the current code in my ViewModel:

public BitmapSource CameraBitmapSource
    {
        get
        {
            Application.Current.Dispatcher.BeginInvoke((Action)delegate
                    {
                        BuildImageSource();
                    }, DispatcherPriority.Background);

            return this.cameraBitmapSource;
         }
    }

BuildImageSource() is where I fetch my new bitmap and convert to a BitmapSource and then assign to my private cameraBitmapSource object.

Body:
Because you use Dispatcher.BeginInvoke, you're doing all the work on the UI thread, which makes your app unresponsive. You should build the images on a separate thread. The easiest way to do that is to make the binding asynchronous, and call your BuildImageSource method directly.

ViewModel

public BitmapSource CameraBitmapSource
{
    get
    {
        BuildImageSource();
        return this.cameraBitmapSource;
    }
}

XAML

<Image Source="{Binding CameraBitmapSource, IsAsync=True}" />

Just remember to Freeze the ImageSource in BuildImageSource so that it can be used on the UI thread (DependencyObjects can only be used on the thread that created them, unless they're Freezable and frozen)


问:
Artifact dependencies (destination) using Bamboo YAML specs
I'm trying to set up the Bamboo build plan configuration using Bamboo YAML specs (.yml file below). In the last stage (Create deployment artifacts) I want to use the shared artifacts from the previous stage. By specifying the artifacts of the jobs as "shared: true" I can use them in the second stage. However, they are  in the same destination folder. Using the UI this can be easily edited.

Artifact dependencies

But how can I specify the destination folder of the two artifacts in the Bamboo YAML specs, e.g. from "Root of working directory" to "./app" and "./wwwroot", respectively?

```<code>---
version: 2
plan:
  project-key: COCKPIT
  key: BE
  name: Cockpit - Continuous Build - Windows
stages:
  - Build Stage:
    - Build Backend
    - Build Frontend
  - Build Artifact:
    - Create Deployment Artifact

Build Backend:
  requirements:
    - Visual Studio Build Tools (32-bit)
  tasks:
    - checkout:
        repository: cockpit_backend
        path: 'cockpit_backend'
        force-clean-build: false
    - script:
      - dotnet publish .\cockpit_backend\src\Cockpit.WebApi\ --configuration Release

  artifacts:
    -
      name: BackendBuild
      location: cockpit_backend/src/Cockpit.WebApi/bin/Release/netcoreapp3.1/publish
      pattern: '**/*.*'
      required: true
      shared: true

Build Frontend:
  requirements:
    - os_linux
  tasks:
    - checkout:
        repository: 'Cockpit / cockpit_frontend'
        path: 'cockpit_frontend'
        force-clean-build: false
    - script:
      - cd cockpit_frontend
      - npm install
    - script:
      - cd cockpit_frontend
      - npm run build-prod
  docker:
    image: node:alpine
  artifacts:
    -
      name: FrontendBuild
      location: cockpit_frontend/dist
      pattern: '**/*.*'
      required: true
      shared: true

Create Deployment Artifact:
  requirements:
    - os_windows
  tasks:
    - script:
        interpreter: powershell
        scripts:
          - $buildDir = "Cockpit"
          - $dest = "Cockpit_${bamboo.buildNumber}.zip"
          - Add-Type -assembly "system.io.compression.filesystem"
          - '[io.compression.zipfile]::CreateFromDirectory($buildDir, $dest)'
  artifacts:
    -
      name: Completebuild
      pattern: 'Cockpit_${bamboo.buildNumber}.zip'
      required: true
</code>```

答: YAML specs doesn't support artifact dependency management and you need to have script task at "Create Deployment Artifact" job to put them into separate folders from root before compressing</p>

Body:
I'm trying to set up the Bamboo build plan configuration using Bamboo YAML specs (.yml file below). In the last stage (Create deployment artifacts) I want to use the shared artifacts from the previous stage. By specifying the artifacts of the jobs as "shared: true" I can use them in the second stage. However, they are  in the same destination folder. Using the UI this can be easily edited.

Artifact dependencies

But how can I specify the destination folder of the two artifacts in the Bamboo YAML specs, e.g. from "Root of working directory" to "./app" and "./wwwroot", respectively?

---
version: 2
plan:
  project-key: COCKPIT
  key: BE
  name: Cockpit - Continuous Build - Windows
stages:
  - Build Stage:
    - Build Backend
    - Build Frontend
  - Build Artifact:
    - Create Deployment Artifact

Build Backend:
  requirements:
    - Visual Studio Build Tools (32-bit)
  tasks:
    - checkout:
        repository: cockpit_backend
        path: 'cockpit_backend'
        force-clean-build: false
    - script:
      - dotnet publish .\cockpit_backend\src\Cockpit.WebApi\ --configuration Release

  artifacts:
    -
      name: BackendBuild
      location: cockpit_backend/src/Cockpit.WebApi/bin/Release/netcoreapp3.1/publish
      pattern: '**/*.*'
      required: true
      shared: true

Build Frontend:
  requirements:
    - os_linux
  tasks:
    - checkout:
        repository: 'Cockpit / cockpit_frontend'
        path: 'cockpit_frontend'
        force-clean-build: false
    - script:
      - cd cockpit_frontend
      - npm install
    - script:
      - cd cockpit_frontend
      - npm run build-prod
  docker:
    image: node:alpine
  artifacts:
    -
      name: FrontendBuild
      location: cockpit_frontend/dist
      pattern: '**/*.*'
      required: true
      shared: true

Create Deployment Artifact:
  requirements:
    - os_windows
  tasks:
    - script:
        interpreter: powershell
        scripts:
          - $buildDir = "Cockpit"
          - $dest = "Cockpit_${bamboo.buildNumber}.zip"
          - Add-Type -assembly "system.io.compression.filesystem"
          - '[io.compression.zipfile]::CreateFromDirectory($buildDir, $dest)'
  artifacts:
    -
      name: Completebuild
      pattern: 'Cockpit_${bamboo.buildNumber}.zip'
      required: true


问:
A logical condiditon in "with" operator doesn't work
I have this code:

```<code>  def edit(conn, params) do
    with m1 <- Repo.get(Model1, params["model1_id"]),
      m2 <- Repo.get(Model2, params["model2_id"]),
      !is_nil(m1) and !is_nil(m2)
    do
      # 1
      res = !is_nil(m1) and !is_nil(m2)
      IO.puts("***** res: #{res}")                              # ===> false

      IO.puts("***** m1: #{Kernel.inspect(m1)}")                # ===> prints a struct
      IO.puts("***** m1 is_nil: #{is_nil(m1)}")                 # ===> false

      IO.puts("***** m2: #{Kernel.inspect(m2)}")                # ===> nil
      IO.puts("***** m2 is_nil: #{is_nil(m2)}")                 # ===> true

    else
      #2
      _ -> raise ArgumentError, "not found"
    end
  end
</code>```

The flow #1 gets executed even though m2 is nil. How can it be? How to fix it?
Goal - ensure that m1 and m2 aren't nil and then execute the flow #1.

答:
The with

The with expression is used strictly for pattern matching. It is not a "chainable replacement" for if-else conditionals.

Basically the with will go through all your clauses and try to pattern match them to the left side of the <- arrow. It will only execute one of the error clauses when the first pattern match fails (doesn't match).

The issue with your code

Your third line in the with is !is_nil(m1) and !is_nil(m2), which always successfully pattern matches even though the expression itself equals to false.

The fix

To make the code do what you actually want you should add a left side to the third line so that it is forced to pattern match:

with m1 <- Repo.get(Model1, params["model1_id"]),
      m2 <- Repo.get(Model2, params["model2_id"]),
      {false, false} <- {is_nil(m1), is_nil(m2)} do
 ...
```

<h3>Idiomatic Elixir</h3>

<p>To make the code a bit more idiomatic Elixir, you can also use Guards, which <code>is_nil</code> is allowed as.
This would make your code look like:</p>

<pre class="lang-elixir prettyprint-override"><code>with m1 when not is_nil(m1) <- Repo.get(Model1, params["model1_id"]),
      m2 when not is_nil(m2) <- Repo.get(Model2, params["model2_id"]) do
 ...
</code>```

Even better readability

One last tip would be to always focus on readability. You are writing your code for humans to read, so less stuff happening on a line is usually easier to read.

Your code would be even more readable as:

m1 = Repo.get(Model1, params["model1_id"])
m2 = Repo.get(Model2, params["model2_id"])

with m1 when not is_nil(m1) <- m1,
      m2 when not is_nil(m2) <- m2 do
 ...
```

<h3>Do you actually need a <code>with</code> ?</h3>

<p>Your <code>with</code> is doing nothing except making sure <code>m1</code> and <code>m2</code> are not <code>nil</code>. This can easily be done with a <code>case</code> or <code>if</code> as well, since you don't actually need any pattern matching here:</p>

<pre class="lang-elixir prettyprint-override"><code>m1 = Repo.get(Model1, params["model1_id"])
m2 = Repo.get(Model2, params["model2_id"])

if !is_nil(m1) && !is_nil(m2) do
 ...
</code>```

Body:
I have this code:

  def edit(conn, params) do
    with m1 <- Repo.get(Model1, params["model1_id"]),
      m2 <- Repo.get(Model2, params["model2_id"]),
      !is_nil(m1) and !is_nil(m2)
    do
      # 1
      res = !is_nil(m1) and !is_nil(m2)
      IO.puts("***** res: #{res}")                              # ===> false

      IO.puts("***** m1: #{Kernel.inspect(m1)}")                # ===> prints a struct
      IO.puts("***** m1 is_nil: #{is_nil(m1)}")                 # ===> false

      IO.puts("***** m2: #{Kernel.inspect(m2)}")                # ===> nil
      IO.puts("***** m2 is_nil: #{is_nil(m2)}")                 # ===> true

    else
      #2
      _ -> raise ArgumentError, "not found"
    end
  end

The flow #1 gets executed even though m2 is nil. How can it be? How to fix it?
Goal - ensure that m1 and m2 aren't nil and then execute the flow #1.

Body:
The with

The with expression is used strictly for pattern matching. It is not a "chainable replacement" for if-else conditionals.

Basically the with will go through all your clauses and try to pattern match them to the left side of the <- arrow. It will only execute one of the error clauses when the first pattern match fails (doesn't match).

The issue with your code

Your third line in the with is !is_nil(m1) and !is_nil(m2), which always successfully pattern matches even though the expression itself equals to false.

The fix

To make the code do what you actually want you should add a left side to the third line so that it is forced to pattern match:

with m1 <- Repo.get(Model1, params["model1_id"]),
      m2 <- Repo.get(Model2, params["model2_id"]),
      {false, false} <- {is_nil(m1), is_nil(m2)} do
 ...

Idiomatic Elixir

To make the code a bit more idiomatic Elixir, you can also use Guards, which is_nil is allowed as.
This would make your code look like:

with m1 when not is_nil(m1) <- Repo.get(Model1, params["model1_id"]),
      m2 when not is_nil(m2) <- Repo.get(Model2, params["model2_id"]) do
 ...

Even better readability

One last tip would be to always focus on readability. You are writing your code for humans to read, so less stuff happening on a line is usually easier to read.

Your code would be even more readable as:

m1 = Repo.get(Model1, params["model1_id"])
m2 = Repo.get(Model2, params["model2_id"])

with m1 when not is_nil(m1) <- m1,
      m2 when not is_nil(m2) <- m2 do
 ...

Do you actually need a with ?

Your with is doing nothing except making sure m1 and m2 are not nil. This can easily be done with a case or if as well, since you don't actually need any pattern matching here:

m1 = Repo.get(Model1, params["model1_id"])
m2 = Repo.get(Model2, params["model2_id"])

if !is_nil(m1) && !is_nil(m2) do
 ...


问:
Iterate through dictionary returns None even the value was found
I am trying to get the values from data but the function below always give me None. I included the print inside the loop so that I could actually see that the condition is correct, not sure why its returning None instead. But the value being printed is correct.

```<code>data = {
    'test1': {
        'test1.1': {
            'a': 'a',
            'b': 'b'
        }
    },
    'test2': {
        'test2.1': {
            'test2.2': {
                'c': 'c',
                'd': 'd'
            }
        },
        'test_list': [1,2,3]
    }
}

def get_dict(key, dict_data):
    for k, v in dict_data.items():
        if k == key and isinstance(v, dict):
            print(v)
            return v
        else:
            if isinstance(v, dict):
                return get_dict(key, v) # <-- added return, same result
</code>```

get_dict('test1', data) returns OK

get_dict('test1.1', data) returns None but shoud have {'a': 'a', 'b': 'b'}

get_dict('test2', data) returns OK

get_dict('test2.1', data) returns None but should return {'test2.2': {'c': 'c', 'd': 'd'}}

答:
The problem is you never get to the second key because both paths return in your code and you can never get more than one iteration in the loop. You don't need to loop over the dict items. Just try to access the key. If it's not there loop over the values and recurse, returning the first thing you find:</p>

```<code>data = {
    'test1': {
        'test1.1': {
            'a': 'a',
            'b': 'b'
        }
    },
    'test2': {
        'test2.1': {
            'test2.2': {
                'c': 'c',
                'd': 'd'
            }
        },
        'test_list': [1,2,3]
    }
}

def get_dict(key, dict_data):
    if not isinstance(dict_data, dict):
        return
    try:
        return dict_data[key]
    except KeyError:
        for v in dict_data.values():
            found = get_dict(key, v)
            if found:
                return found

get_dict('test2.2', data)
# {'c': 'c', 'd': 'd'}

get_dict('test2.1', data)
# {'test2.2': {'c': 'c', 'd': 'd'}}
</code>```

Body:
I am trying to get the values from data but the function below always give me None. I included the print inside the loop so that I could actually see that the condition is correct, not sure why its returning None instead. But the value being printed is correct.

data = {
    'test1': {
        'test1.1': {
            'a': 'a',
            'b': 'b'
        }
    },
    'test2': {
        'test2.1': {
            'test2.2': {
                'c': 'c',
                'd': 'd'
            }
        },
        'test_list': [1,2,3]
    }
}

def get_dict(key, dict_data):
    for k, v in dict_data.items():
        if k == key and isinstance(v, dict):
            print(v)
            return v
        else:
            if isinstance(v, dict):
                return get_dict(key, v) # <-- added return, same result

get_dict('test1', data) returns OK

get_dict('test1.1', data) returns None but shoud have {'a': 'a', 'b': 'b'}

get_dict('test2', data) returns OK

get_dict('test2.1', data) returns None but should return {'test2.2': {'c': 'c', 'd': 'd'}}

Body:
The problem is you never get to the second key because both paths return in your code and you can never get more than one iteration in the loop. You don't need to loop over the dict items. Just try to access the key. If it's not there loop over the values and recurse, returning the first thing you find:

data = {
    'test1': {
        'test1.1': {
            'a': 'a',
            'b': 'b'
        }
    },
    'test2': {
        'test2.1': {
            'test2.2': {
                'c': 'c',
                'd': 'd'
            }
        },
        'test_list': [1,2,3]
    }
}

def get_dict(key, dict_data):
    if not isinstance(dict_data, dict):
        return
    try:
        return dict_data[key]
    except KeyError:
        for v in dict_data.values():
            found = get_dict(key, v)
            if found:
                return found

get_dict('test2.2', data)
# {'c': 'c', 'd': 'd'}

get_dict('test2.1', data)
# {'test2.2': {'c': 'c', 'd': 'd'}}


问:
Merging all the colunms in R with colunm names
I have the following data

```<code>> df
X1  X2  X3
1   3   4
1   0   0
1   1   0
</code>```

and I want to merge all the column so that the final output will be

```<code>new colName
1     X1
1     X1
1     X1
3     X2
0     X2
1     X2
4     X3
0     X3
0     X3
</code>```

答:
```<code>library (tidyverse)

pivot_longer(df,X1:X3)
</code>```

Body:
I have the following data

> df
X1  X2  X3
1   3   4
1   0   0
1   1   0

and I want to merge all the column so that the final output will be

new colName
1     X1
1     X1
1     X1
3     X2
0     X2
1     X2
4     X3
0     X3
0     X3


问:
hasMany called with something that's not an instance of Sequelize.Model
as you guys can see my issue is related to the title description, i created a User Model, and a Foto Model in sequelize, basicly a user can shoot many fotos, but each foto can be related to just 1 user.

My User model

```<code>    "use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var Foto = require('./Foto');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { username: value } })
            .then(function (user) {
              // reject if a different user wants to use the same username
              if (user && self.id !== user.id) {
                return next('username already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { email: value } })
            .then(function (user) {
              // reject if a different user wants to use the same email
              if (user && self.id !== user.id) {
                return next('Email already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    typeOfUser: {
      type: DataTypes.INTEGER,
      allowNull:true,
      defaultValue:null
    },

    country: {
      type: DataTypes.STRING,
      allowNull:true,
      defaultValue:null
    },

    birthDate:{
      type: DataTypes.DATEONLY,
      allowNull:true,
      defaultValue:null
    },

    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    password: {
      type: DataTypes.STRING,
      allowNull:false
    },

    numberFotos: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    }
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }

    });

  User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})

  return Foto;
}
</code>```

My foto model

```<code>"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var User = require('./User');

module.exports = function (sequelize, DataTypes) {
  var Foto = sequelize.define("Foto", {
    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false
    },
    date: {
      type: DataTypes.DATE,
      allowNull:true
    },
    position: {
      type: DataTypes.RANGE,
      allowNull: true
    }
  });

  Foto.belongsTo(User, {foreignKey: 'userId'});

  return Foto;
}
</code>```

答:
So I was getting this error and it took me some time to deal with the bug. I realised I was getting the Error because I was referencing the model wrongly. Sequelize is case sensitive so if you created the model with UpperCase ensure to keep it uniform throughout your referencing.

I would also point out you could try this out instead

```<code> User.hasMany(models.Foto ,{as: 'fotos', foreignKey: 'userId'})

</code>```

Body:
as you guys can see my issue is related to the title description, i created a User Model, and a Foto Model in sequelize, basicly a user can shoot many fotos, but each foto can be related to just 1 user.

My User model

    "use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var Foto = require('./Foto');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { username: value } })
            .then(function (user) {
              // reject if a different user wants to use the same username
              if (user && self.id !== user.id) {
                return next('username already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { email: value } })
            .then(function (user) {
              // reject if a different user wants to use the same email
              if (user && self.id !== user.id) {
                return next('Email already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    typeOfUser: {
      type: DataTypes.INTEGER,
      allowNull:true,
      defaultValue:null
    },

    country: {
      type: DataTypes.STRING,
      allowNull:true,
      defaultValue:null
    },

    birthDate:{
      type: DataTypes.DATEONLY,
      allowNull:true,
      defaultValue:null
    },

    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    password: {
      type: DataTypes.STRING,
      allowNull:false
    },

    numberFotos: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    }
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }

    });

  User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})

  return Foto;
}

My foto model

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var User = require('./User');

module.exports = function (sequelize, DataTypes) {
  var Foto = sequelize.define("Foto", {
    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false
    },
    date: {
      type: DataTypes.DATE,
      allowNull:true
    },
    position: {
      type: DataTypes.RANGE,
      allowNull: true
    }
  });

  Foto.belongsTo(User, {foreignKey: 'userId'});

  return Foto;
}

Body:
So I was getting this error and it took me some time to deal with the bug. I realised I was getting the Error because I was referencing the model wrongly. Sequelize is case sensitive so if you created the model with UpperCase ensure to keep it uniform throughout your referencing.

I would also point out you could try this out instead

 User.hasMany(models.Foto ,{as: 'fotos', foreignKey: 'userId'})


问:
curl fails to verify self signed certificate after redirection from HTTP to HTTPS
I have a problem with self-signed SSL certificate and curl.

Server is lighttpd. HTTPS works fine:

```<code>$ curl https://192.168.144.1/zxc -k
HELLO
</code>```

But with redirection from HTTP it fails:

```<code>curl http://192.168.144.1:81/zxc -kvL
*   Trying 192.168.144.1...
* TCP_NODELAY set
* Connected to 192.168.144.1 (192.168.144.1) port 81 (#0)
> GET /zxc HTTP/1.1
> Host: 192.168.144.1:81
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Location: https://192.168.144.1:81/zxc
< Content-Length: 0
< Date: Sat, 30 May 2020 06:59:57 GMT
< Server: lighttpd/1.4.48
<
* Connection #0 to host 192.168.144.1 left intact
* Issue another request to this URL: 'https://192.168.144.1:81/zxc'
* Hostname 192.168.144.1 was found in DNS cache
*   Trying 192.168.144.1...
* TCP_NODELAY set
* Connected to 192.168.144.1 (192.168.144.1) port 81 (#1)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):

........... HERE IT STACKS FOR A MINUTE ....................

* LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81
* stopped the pause stream!
* Closing connection 1
curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81
</code>```

One possible solution I found here https://stackoverflow.com/a/44494250/3743145: CURLOPT_SSL_VERIFYPEER=false. How to pass it to CURL CLI?

答:
```<code>> * LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81
</code>```

The error is SSL_ERROR_SYSCALL and this has nothing to do with certificate validation. In fact, a closer look at what you are doing shows that you are redirecting from plain HTTP on port 81 to HTTPS on the same port.

```<code>curl http://192.168.144.1:81/zxc -kvL
...
< HTTP/1.1 301 Moved Permanently
< Location: https://192.168.144.1:81/zxc
</code>```

This is very different from what you've tested before where you used HTTPS on the standard port (443). And it is very likely that your HTTP server does not speak HTTP and HTTPS on the same port 81 - most servers don't even support such kind of configuration.

Body:
I have a problem with self-signed SSL certificate and curl.

Server is lighttpd. HTTPS works fine:

$ curl https://192.168.144.1/zxc -k
HELLO

But with redirection from HTTP it fails:

curl http://192.168.144.1:81/zxc -kvL
*   Trying 192.168.144.1...
* TCP_NODELAY set
* Connected to 192.168.144.1 (192.168.144.1) port 81 (#0)
> GET /zxc HTTP/1.1
> Host: 192.168.144.1:81
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Location: https://192.168.144.1:81/zxc
< Content-Length: 0
< Date: Sat, 30 May 2020 06:59:57 GMT
< Server: lighttpd/1.4.48
<
* Connection #0 to host 192.168.144.1 left intact
* Issue another request to this URL: 'https://192.168.144.1:81/zxc'
* Hostname 192.168.144.1 was found in DNS cache
*   Trying 192.168.144.1...
* TCP_NODELAY set
* Connected to 192.168.144.1 (192.168.144.1) port 81 (#1)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):

........... HERE IT STACKS FOR A MINUTE ....................

* LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81
* stopped the pause stream!
* Closing connection 1
curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81

One possible solution I found here https://stackoverflow.com/a/44494250/3743145: CURLOPT_SSL_VERIFYPEER=false. How to pass it to CURL CLI?

Body:
> * LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 192.168.144.1:81

The error is SSL_ERROR_SYSCALL and this has nothing to do with certificate validation. In fact, a closer look at what you are doing shows that you are redirecting from plain HTTP on port 81 to HTTPS on the same port.

curl http://192.168.144.1:81/zxc -kvL
...
< HTTP/1.1 301 Moved Permanently
< Location: https://192.168.144.1:81/zxc

This is very different from what you've tested before where you used HTTPS on the standard port (443). And it is very likely that your HTTP server does not speak HTTP and HTTPS on the same port 81 - most servers don't even support such kind of configuration.


问:
Run some action after changes commit
I have a Java Application. Everytime a change is made to self hosted git server, I need to curl a endpoint of the application inorder to reload the properties. Here is what my curl look like: curl -X {} http://someurl:8080/abc.

I would like to automate this after a commit is made. I have read about git and found that "post commit" should get the job done but after reading about it for more than 2 hours I gave up. I would like to create a script that will curl the endpoint when commit is made. The hosted server is a linux machine.

答:
What you are trying to achieve is also known as webhook. Here is how to achieve this.

First cd .git/hooks and create post-commit file. Eg: touch post-commit. Now run the following to make it executable:

```<code>chmod +x post-commit
</code>```

Add the script to post-commit using nano post-commit (You can also write it in any other scripting language for eg python):

```<code>#!/bin/sh
curl -X {} http://someurl:8080/abc
</code>```

Now when you commit the changes, post-commit will run automatically.

Read more on git-scm.com

Title: Run some action after changes commit

Body:
What you are trying to achieve is also known as webhook. Here is how to achieve this.

First cd .git/hooks and create post-commit file. Eg: touch post-commit. Now run the following to make it executable:

chmod +x post-commit

Add the script to post-commit using nano post-commit (You can also write it in any other scripting language for eg python):

#!/bin/sh
curl -X {} http://someurl:8080/abc

Now when you commit the changes, post-commit will run automatically.

Read more on git-scm.com


答:
You can try gathering the column names with tidyr

```<code>library(tidyr)

X1 <- c(1,1,1)
X2 <- c(3,0,1)
X3 <- c(4,0,0)

df <- data.frame(X1, X2, X3)

df <- df %>%
  gather(new, colname, X1, X2, X3)

print(df)

  new colname
1  X1       1
2  X1       1
3  X1       1
4  X2       3
5  X2       0
6  X2       1
7  X3       4
8  X3       0
9  X3       0
</code>```

Title: Merging all the colunms in R with colunm names

Body:
You can try gathering the column names with tidyr

library(tidyr)

X1 <- c(1,1,1)
X2 <- c(3,0,1)
X3 <- c(4,0,0)

df <- data.frame(X1, X2, X3)

df <- df %>%
  gather(new, colname, X1, X2, X3)

print(df)

  new colname
1  X1       1
2  X1       1
3  X1       1
4  X2       3
5  X2       0
6  X2       1
7  X3       4
8  X3       0
9  X3       0


问:
Java for Iphone App Development?
I have been primarily using Java and have experience with it. I want to develop some iphone apps and wanted to know if there a way to develop iphone app using Java or iphone development can be only done using Objective-C?

Also if Objective-C is the only way to go then would really appreciate if you can recommend some books or links where I can get started on Iphone Development, my background is completely based on Java and I have not work with C or C++ professionally in the past.

Any recommendations/suggestions would highly help.

Can we have quick comparison of Objective-C vs Java or its like comparing oranges with Apple, am just trying to get some similarities in objective-c from java perspective so that I have some knowledge to leverage on while learning Objective-C, any suggestions?

答:
Check out:
http://www.xmlvm.org/iphone/

I've never tried it, but it seemed interesting at least .  I'd expect the performance would be subpar, however.

Title: Java for Iphone App Development?


问:
Accept/Reject Button in html
I am trying to accept or reject invitations through form elements in html.Here is the code :

```<code>             <form method="POST">
             <input type="submit" name="accept" id="accept" value="Accept">
             <input type="submit" name="decline" id="decline" value="Decline">
             </form>
</code>```

So whenever I try to accept or reject invitations ,the Accept or the Reject button should change to Accepted or Rejected.
I can make that happen using javascript onclick properties.But I am confused on how the response object should handle this in the post route in express js???What should my post route do?
When I click either accept or reject, the page should not reload and only the clicked button should change..

```<code>    response.send()
    response.redirect()
</code>```

My question is what method should my response object contain so that it achieves above(you can think of the 'add to cart' in shopping sites as example). How do I solve it?

答:
You can easily use JQUERY for this. If not, then I will post a Pure javascript solution for it.

To stop the form from submitting. useevent.preventDefault()

$("#accept").click(function(event) {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic ( Request to  express js endpoint )
    this.value = "Accepted"
});

$("#decline").click(function(event) {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
    this.value = "Declined"
});```

I haven't tested it but I believe it should work.

Title: Accept/Reject Button in html

Body:
I am trying to accept or reject invitations through form elements in html.Here is the code :

             <form method="POST">
             <input type="submit" name="accept" id="accept" value="Accept">
             <input type="submit" name="decline" id="decline" value="Decline">
             </form>

So whenever I try to accept or reject invitations ,the Accept or the Reject button should change to Accepted or Rejected.
I can make that happen using javascript onclick properties.But I am confused on how the response object should handle this in the post route in express js???What should my post route do?
When I click either accept or reject, the page should not reload and only the clicked button should change..

    response.send()
    response.redirect()

My question is what method should my response object contain so that it achieves above(you can think of the 'add to cart' in shopping sites as example). How do I solve it?

Body:
You can easily use JQUERY for this. If not, then I will post a Pure javascript solution for it.

To stop the form from submitting. useevent.preventDefault()

$("#accept").click(function(event) {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic ( Request to  express js endpoint )
    this.value = "Accepted"
});

$("#decline").click(function(event) {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
    this.value = "Declined"
});

I haven't tested it but I believe it should work.


问:
Form input elements are messing with URL of react page
ContactData.js

```<code>import React, { Component } from 'react';
import Button from '../../../components/UI/Button/Button';
import classes from './ContactData.module.css'
class ContactData extends Component {
    state = {
        name: '',
        age: '',
        address: {
            street: '',
            postalCode: ''
        }
    }

    orderHandler = () => {
        console.log(this.props.ingredients)
    }

    render() {
        console.log(this.props.ingredients);
        return (
            <div className={classes.ContactData}>
                <h4>Enter Your Contact Data</h4>
                <form>
                    <input type="text" name="name" placeholder="Your Name" />
                    <input type="email" name="email" placeholder="Your Mail" />
                    <input type="text" name="street" placeholder="Street" />
                    <input type="text" name="postal" placeholder="Postal Code" />
                    <Button btnType="Success" clicked={this.orderHandler}>ORDER</Button>
                </form>
            </div>
        );
    }
}

export default ContactData;
</code>```

CheckOut.js

```<code>    import React from 'react';
import CheckoutSum from '../../components/Checkout/Checkout'
import { Route } from 'react-router-dom';
import ContactData from '../../container/Checkout/ContactData/ContactData'
class Checkout extends React.Component {
    state = {
        ingredients: {
            salad: 1,
            meat: 1,
            cheese: 1,
            bacon: 1
        }
    }

    componentDidMount() {
        const query = new URLSearchParams(this.props.location.search);
        const ingredients = {};
        for (let param of query.entries()) {
            ingredients[param[0]] = parseInt(param[1]);
        }
        // console.log(ingredients);
        this.setState({ ingredients: ingredients });

    }

    cancelHandle = () => {
        this.props.history.goBack();
    }

    continueHandle = () => {
        this.props.history.replace('/checkout/contact-data');
    }
    render() {
        console.log(this.props)
        console.log(this.state.ingredients)
        return (
            <div>
                <CheckoutSum
                    cancel={this.cancelHandle}
                    continue={this.continueHandle}
                    ingredients={this.state.ingredients}
                />
                <Route
                    path={this.props.match.path + '/contact-data'}
                    exact
                    render={() => (<ContactData ingredients={this.state.ingredients} />)} />
            </div>

        );
    }
}

export default Checkout;
</code>```

Problem is when I hit Order button in CotanctData component the page reloads and for some reason my URL changes to  this  http://localhost:3000/checkout/contact-data?name=&email=&street=&postal= and then  Checkout component renders again and for some reason componentDidMount fires twice. At last I was expecting the printing of ingredients object.

Also, I'm using search query in URL to change the state of checkout component

Full Project At-https://github.com/aniket-hue/Burger-App-React/tree/Routes

Please bear with me if you don't like the question I didn't know how to frame the question.

答:
You have to add preventDefault to your orderHandler method, beacause if button in form has no type, the type is automaticlly submit, so on every click your submitting a form. Also can you add type="button" to your button inside form.

```<code>orderHandler = e => {
    e.preventDefault();
    console.log(this.props.ingredients);
}
</code>```

Body:
ContactData.js

import React, { Component } from 'react';
import Button from '../../../components/UI/Button/Button';
import classes from './ContactData.module.css'
class ContactData extends Component {
    state = {
        name: '',
        age: '',
        address: {
            street: '',
            postalCode: ''
        }
    }

    orderHandler = () => {
        console.log(this.props.ingredients)
    }

    render() {
        console.log(this.props.ingredients);
        return (

Enter Your Contact Data

                <form>
                    <input type="text" name="name" placeholder="Your Name" />
                    <input type="email" name="email" placeholder="Your Mail" />
                    <input type="text" name="street" placeholder="Street" />
                    <input type="text" name="postal" placeholder="Postal Code" />
                    <Button btnType="Success" clicked={this.orderHandler}>ORDER</Button>
                </form>

        );
    }
}

export default ContactData;

CheckOut.js

    import React from 'react';
import CheckoutSum from '../../components/Checkout/Checkout'
import { Route } from 'react-router-dom';
import ContactData from '../../container/Checkout/ContactData/ContactData'
class Checkout extends React.Component {
    state = {
        ingredients: {
            salad: 1,
            meat: 1,
            cheese: 1,
            bacon: 1
        }
    }

    componentDidMount() {
        const query = new URLSearchParams(this.props.location.search);
        const ingredients = {};
        for (let param of query.entries()) {
            ingredients[param[0]] = parseInt(param[1]);
        }
        // console.log(ingredients);
        this.setState({ ingredients: ingredients });

    }

    cancelHandle = () => {
        this.props.history.goBack();
    }

    continueHandle = () => {
        this.props.history.replace('/checkout/contact-data');
    }
    render() {
        console.log(this.props)
        console.log(this.state.ingredients)
        return (

                <CheckoutSum
                    cancel={this.cancelHandle}
                    continue={this.continueHandle}
                    ingredients={this.state.ingredients}
                />
                <Route
                    path={this.props.match.path + '/contact-data'}
                    exact
                    render={() => (<ContactData ingredients={this.state.ingredients} />)} />

        );
    }
}

export default Checkout;

Problem is when I hit Order button in CotanctData component the page reloads and for some reason my URL changes to  this  http://localhost:3000/checkout/contact-data?name=&email=&street=&postal= and then  Checkout component renders again and for some reason componentDidMount fires twice. At last I was expecting the printing of ingredients object.

Also, I'm using search query in URL to change the state of checkout component

Full Project At-https://github.com/aniket-hue/Burger-App-React/tree/Routes

Please bear with me if you don't like the question I didn't know how to frame the question.

Body:
You have to add preventDefault to your orderHandler method, beacause if button in form has no type, the type is automaticlly submit, so on every click your submitting a form. Also can you add type="button" to your button inside form.

orderHandler = e => {
    e.preventDefault();
    console.log(this.props.ingredients);
}


问:
What is the best way to directly return relations (one-to-many) value instead its Id?
How can I directly return the represented relations (specific) value out of the box without any further processes ?

Lets say I have tables and relations like below:

```<code>user
id name status_id
1  Jane 0
2  Joe  1

status
id title
1  pending
2  accepted
</code>```

Here user belongsTo status and status hasMany users.

```<code>public function status()
{
    return $this->belongsTo('App\User');
}

public function users()
{
    return $this->hasMany('App\Status');
}
</code>```

What I mean is instead this response (with eager load):

```<code>{
   {"id":"1", "user":"Jane","status_id":"1", "status":{"id":"1", "title":"pending"} },
   {"id":"2", "user":"Joe", "status_id":"2", "status":{"id":"2", "title":"accepted"} }
}
</code>```

Iam looking for this:

```<code>{
   {"id":"1", "user":"Jane","status":"pending" },
   {"id":"2", "user":"Joe", "status":"accepted" }
}
</code>```

PS: I am not sure if this was asked before, at least I could'nt find any. This could be asked in different ways.

答:
You can define an accessor which transfers the relationship to a custom field, then hide the relationship itself from JSON responses:</p>

```<code>protected $hidden = [ 'userStatus' ];
protected $with = [ 'userStatus' ]; // Always load it eagerly

public function userStatus()
{
    return $this->belongsTo('App\Status'); // I'm assuming this is what you actually have
}

public function getStatusAttribute() {
    return $this->userStatus->title;
}

protected $appends = [ 'status' ];
</code>```

Body:
How can I directly return the represented relations (specific) value out of the box without any further processes ?

Lets say I have tables and relations like below:

user
id name status_id
1  Jane 0
2  Joe  1

status
id title
1  pending
2  accepted

Here user belongsTo status and status hasMany users.

public function status()
{
    return $this->belongsTo('App\User');
}

public function users()
{
    return $this->hasMany('App\Status');
}

What I mean is instead this response (with eager load):

{
   {"id":"1", "user":"Jane","status_id":"1", "status":{"id":"1", "title":"pending"} },
   {"id":"2", "user":"Joe", "status_id":"2", "status":{"id":"2", "title":"accepted"} }
}

Iam looking for this:

{
   {"id":"1", "user":"Jane","status":"pending" },
   {"id":"2", "user":"Joe", "status":"accepted" }
}

PS: I am not sure if this was asked before, at least I could'nt find any. This could be asked in different ways.

Body:
You can define an accessor which transfers the relationship to a custom field, then hide the relationship itself from JSON responses:

protected $hidden = [ 'userStatus' ];
protected $with = [ 'userStatus' ]; // Always load it eagerly

public function userStatus()
{
    return $this->belongsTo('App\Status'); // I'm assuming this is what you actually have
}

public function getStatusAttribute() {
    return $this->userStatus->title;
}

protected $appends = [ 'status' ];


问:
Kotlin String max length? (Kotlin file with a long String is not compiling)
According to this answer Java can hold up to 2^31 - 1 characters. I was trying to do benchmarking and stuffs, so I tried to create a large amount of string and write it to a file like this:

import java.io.*

fun main() {
    val out = File("ouput.txt").apply { createNewFile() }.printWriter()
    sequence {
        var x = 0
        while (true) {
            yield("${++x} ${++x} ${++x} ${++x} ${++x}")
        }
    }.take(5000).forEach { out.println(it) }
    out.close()
}
```
<p>And then the <code>output.txt</code> file contains like this:</p>
<pre class="lang-kotlin prettyprint-override"><code>1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
// ... 5000 lines
</code>```

And then I copied all the contents of the file into a string for some benchmarking of some functions, so this is how it looks:

import kotlin.system.*

fun main() {
    val inputs = """
        1 2 3 4 5
        6 7 8 9 10
        11 12 13 14 15
        16 17 18 19 20
        21 22 23 24 25
        // ... 5000 lines
        24986 24987 24988 24989 24990
        24991 24992 24993 24994 24995
        24996 24997 24998 24999 25000

    """.trimIndent()
    measureNanoTime {
        inputs.reader().forEachLine { line ->
            val (a, b, c, d, e) = line.split(" ").map(String::toInt)
        }
    }.div(5000).let(::println)
}
```
<blockquote>
<p>The total character count of the file/string is 138894</p>
<p>String can hold up to 2147483647</p>
</blockquote>
<p><strong>But the Kotlin code does not compile (last file)</strong> It throws compilation error:</p>
<pre class="lang-kotlin prettyprint-override"><code>e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: wrong bytecode generated
// more lines
The root cause java.lang.IllegalArgumentException was thrown at: org.jetbrains.org.objectweb.asm.ByteVector.putUTF8(ByteVector.java:246)
    at org.jetbrains.kotlin.codegen.TransformationMethodVisitor.visitEnd(TransformationMethodVisitor.kt:92)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.endVisit(FunctionCodegen.java:971)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: UTF8 string too large
</code>```

Here is the total log of exception with stacktrace: https://gist.github.com/Animeshz/1a18a7e99b0c0b913027b7fb36940c07

答:
There is limit in java class file, length of string constant must fit in 16 bits ie. 65535 bytes (not characters) is max length of string in source code.

The class File Format

Body:
According to this answer Java can hold up to 2^31 - 1 characters. I was trying to do benchmarking and stuffs, so I tried to create a large amount of string and write it to a file like this:

import java.io.*

fun main() {
    val out = File("ouput.txt").apply { createNewFile() }.printWriter()
    sequence {
        var x = 0
        while (true) {
            yield("${++x} ${++x} ${++x} ${++x} ${++x}")
        }
    }.take(5000).forEach { out.println(it) }
    out.close()
}

And then the output.txt file contains like this:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
// ... 5000 lines

And then I copied all the contents of the file into a string for some benchmarking of some functions, so this is how it looks:

import kotlin.system.*

fun main() {
    val inputs = """
        1 2 3 4 5
        6 7 8 9 10
        11 12 13 14 15
        16 17 18 19 20
        21 22 23 24 25
        // ... 5000 lines
        24986 24987 24988 24989 24990
        24991 24992 24993 24994 24995
        24996 24997 24998 24999 25000

    """.trimIndent()
    measureNanoTime {
        inputs.reader().forEachLine { line ->
            val (a, b, c, d, e) = line.split(" ").map(String::toInt)
        }
    }.div(5000).let(::println)
}

The total character count of the file/string is 138894

String can hold up to 2147483647

But the Kotlin code does not compile (last file) It throws compilation error:

e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: wrong bytecode generated
// more lines
The root cause java.lang.IllegalArgumentException was thrown at: org.jetbrains.org.objectweb.asm.ByteVector.putUTF8(ByteVector.java:246)
    at org.jetbrains.kotlin.codegen.TransformationMethodVisitor.visitEnd(TransformationMethodVisitor.kt:92)
    at org.jetbrains.kotlin.codegen.FunctionCodegen.endVisit(FunctionCodegen.java:971)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: UTF8 string too large

Here is the total log of exception with stacktrace: https://gist.github.com/Animeshz/1a18a7e99b0c0b913027b7fb36940c07


问:
Change value of new Date() 's time
I am fetching the value of today's date using this code below:

```<code>var today = new Date();
console.log(today);
</code>```

The value of console log is Sat May 30 2020 12:13:18 GMT+0530 (India Standard Time)

But what I want to achieve is, whatever the time is I want value as

var today_morning = Sat May 30 2020 09:30:00 GMT+0530 (India Standard Time)

How do I get this value in today_morning irrespective of what time value is in var today?

答:
You can get day of week, month, date and year from today and append with the time string.
You can use an array of names, and getMonth(), getDay()  to return the month and day as name:

```<code>var today = new Date();

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

var today_morning = days[today.getDay()] + " " + months[today.getMonth()] + " " + today.getDate() + " " + today.getFullYear() + " 09:30:00 GMT+0530 (India Standard Time)";

console.log(today_morning);
</code>```

This will print "Sat May 30 2020 09:30:00 GMT+0530 (India Standard Time)"

Title: Change value of new Date() 's time

Body:
I am fetching the value of today's date using this code below:

var today = new Date();
console.log(today);

The value of console log is Sat May 30 2020 12:13:18 GMT+0530 (India Standard Time)

But what I want to achieve is, whatever the time is I want value as

var today_morning = Sat May 30 2020 09:30:00 GMT+0530 (India Standard Time)

How do I get this value in today_morning irrespective of what time value is in var today?

Body:
You can get day of week, month, date and year from today and append with the time string.
You can use an array of names, and getMonth(), getDay()  to return the month and day as name:

var today = new Date();

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

var today_morning = days[today.getDay()] + " " + months[today.getMonth()] + " " + today.getDate() + " " + today.getFullYear() + " 09:30:00 GMT+0530 (India Standard Time)";

console.log(today_morning);

This will print "Sat May 30 2020 09:30:00 GMT+0530 (India Standard Time)"


问:
Xamarin Forms - Save and Retrieve Prism Navigation Stack with ViewModels
I am implementing a Xamarin Forms Mobile application using Prism for Navigation.

Is there a way to retrieve the complete Navigation Stack along with the View Models from Prism?

The requirement is, if the user is in the middle of a workflow and the app is closed, the user should be able to continue the workflow when a new session is started.

So I am trying to periodically save the entire navigation stack to the data base.

答: You can now get the absolute navigation path of a page by calling INavigationService.GetNavigationUriPath.</p>


问:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 3 recorded
I know that it has been asked multiple times on this platform. I also checked the solution provided that either use all raw parameters or all Matcher arguments. In my case Argument Matcher(any, anyString) has been used for all parameters but still getting the error.

Code:

```<code>Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(Mockito.any(TermReq.class));
Mockito.when(utils.sendPOSTRequest(Mockito.anyString(),Mockito.anyString())).thenReturn(Mockito.anyString());
</code>```

Error on the above line is:

```<code>org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 3 recorded:
</code>```

Can somebody point out what may be the issue.

Thanks,

答:
You can't return an argument matcher from a mocked method like thenReturn(Mockito.any(TermReq.class)). This's an invalid use.

You should return an actual value or an argument captor.

Body:
I know that it has been asked multiple times on this platform. I also checked the solution provided that either use all raw parameters or all Matcher arguments. In my case Argument Matcher(any, anyString) has been used for all parameters but still getting the error.

Code:

Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(Mockito.any(TermReq.class));
Mockito.when(utils.sendPOSTRequest(Mockito.anyString(),Mockito.anyString())).thenReturn(Mockito.anyString());

Error on the above line is:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 3 recorded:

Can somebody point out what may be the issue.

Thanks,


答:
You need to either:

Call e.preventDefult() on the <form>'s submit event.

OR, add <button type="button"> to your button to make it not submit your form.

Title: Form input elements are messing with URL of react page


问:
FileNotFoundError: [Errno 2] No such file or directory: - Fastai, Although that file exists
```<code>Traceback (most recent call last):
  File "app.py", line 34, in <module>
    learn = setup_model_pth(PATH_TO_MODELS_DIR, NAME_OF_FILE, classes)
  File "app.py", line 31, in setup_model_pth
    learn.load(learner_name_to_load, device=torch.device('cpu'))
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\fastai\basic_train.py", line 269, in load
    state = torch.load(source, map_location=device)
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\torch\serialization.py", line 584, in load
    with _open_file_like(f, 'rb') as opened_file:
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\torch\serialization.py", line 234, in _open_file_like
    return _open_file(name_or_buffer, mode)
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\torch\serialization.py", line 215, in __init__
    super(_open_file, self).__init__(open(name, mode))
FileNotFoundError: [Errno 2] No such file or directory: 'models\\model_best.pth'
</code>```

I had cloned one github repository and while running it shows this error.
The main problem is its showing No such file or directory: 'models\model_best.pth' but actually there is a directory models/model_best.pth , so why its coming like models\model_best.pth and not like .models/models_bestpth'.

source code:
'''

```<code>from __future__ import division, print_function
import sys
import os
import glob
import re
from pathlib import Path
from io import BytesIO
import base64
import requests

# Import fast.ai Library
from fastai import *
from fastai.vision import *

# Flask utils
from flask import Flask, redirect, url_for, render_template, request
from PIL import Image as PILImage

# Define a flask app
app = Flask(__name__)

NAME_OF_FILE = 'model_best' # Name of your exported file
PATH_TO_MODELS_DIR = Path('') # by default just use /models in root dir
classes = ['Actinic keratoses', 'Basal cell carcinoma', 'Benign keratosis',
           'Dermatofibroma', 'Melanocytic nevi', 'Melanoma', 'Vascular lesions']

def setup_model_pth(path_to_pth_file, learner_name_to_load, classes):
    data = ImageDataBunch.single_from_classes(
        path_to_pth_file, classes, ds_tfms=get_transforms(), size=224).normalize(imagenet_stats)
    learn = cnn_learner(data, models.densenet169, model_dir='models')
    learn.load(learner_name_to_load, device=torch.device('cpu'))
    return learn

learn = setup_model_pth(PATH_TO_MODELS_DIR, NAME_OF_FILE, classes)

def encode(img):
    img = (image2np(img.data) * 255).astype('uint8')
    pil_img = PILImage.fromarray(img)
    buff = BytesIO()
    pil_img.save(buff, format="JPEG")
    return base64.b64encode(buff.getvalue()).decode("utf-8")

def model_predict(img):
    img = open_image(BytesIO(img))
    pred_class,pred_idx,outputs = learn.predict(img)
    formatted_outputs = ["{:.1f}%".format(value) for value in [x * 100 for x in torch.nn.functional.softmax(outputs, dim=0)]]
    pred_probs = sorted(
            zip(learn.data.classes, map(str, formatted_outputs)),
            key=lambda p: p[1],
            reverse=True
        )

    img_data = encode(img)
    result = {"class":pred_class, "probs":pred_probs, "image":img_data}
    return render_template('result.html', result=result)

@app.route('/', methods=['GET', "POST"])
def index():
    # Main page
    return render_template('index.html')

@app.route('/upload', methods=["POST", "GET"])
def upload():
    if request.method == 'POST':
        # Get the file from post request
        img = request.files['file'].read()
        if img != None:
        # Make prediction
            preds = model_predict(img)
            return preds
    return 'OK'

@app.route("/classify-url", methods=["POST", "GET"])
def classify_url():
    if request.method == 'POST':
        url = request.form["url"]
        if url != None:
            response = requests.get(url)
            preds = model_predict(response.content)
            return preds
    return 'OK'

if __name__ == '__main__':
    port = os.environ.get('PORT', 8008)

    if "prepare" not in sys.argv:
        app.run(debug=False, host='0.0.0.0', port=port)
</code>```

'''

答:
Your code is searching for the file in the root directory of the computer, which is not where your file is. It's there in some folder, and that's why the file couldn't be found.

Change path variable from

```<code>PATH_TO_MODELS_DIR = Path('')
</code>```

to

```<code>PATH_TO_MODELS_DIR = Path('.')
</code>```

It'll search for your folder models and file model_best.pth in current working directory.

Body:
Traceback (most recent call last):
  File "app.py", line 34, in <module>
    learn = setup_model_pth(PATH_TO_MODELS_DIR, NAME_OF_FILE, classes)
  File "app.py", line 31, in setup_model_pth
    learn.load(learner_name_to_load, device=torch.device('cpu'))
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\fastai\basic_train.py", line 269, in load
    state = torch.load(source, map_location=device)
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\torch\serialization.py", line 584, in load
    with _open_file_like(f, 'rb') as opened_file:
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\torch\serialization.py", line 234, in _open_file_like
    return _open_file(name_or_buffer, mode)
  File "C:\Users\Caden\anaconda3\envs\tf\lib\site-packages\torch\serialization.py", line 215, in __init__
    super(_open_file, self).__init__(open(name, mode))
FileNotFoundError: [Errno 2] No such file or directory: 'models\\model_best.pth'

I had cloned one github repository and while running it shows this error.
The main problem is its showing No such file or directory: 'models\model_best.pth' but actually there is a directory models/model_best.pth , so why its coming like models\model_best.pth and not like .models/models_bestpth'.

source code:
'''

from __future__ import division, print_function
import sys
import os
import glob
import re
from pathlib import Path
from io import BytesIO
import base64
import requests

# Import fast.ai Library
from fastai import *
from fastai.vision import *

# Flask utils
from flask import Flask, redirect, url_for, render_template, request
from PIL import Image as PILImage

# Define a flask app
app = Flask(__name__)

NAME_OF_FILE = 'model_best' # Name of your exported file
PATH_TO_MODELS_DIR = Path('') # by default just use /models in root dir
classes = ['Actinic keratoses', 'Basal cell carcinoma', 'Benign keratosis',
           'Dermatofibroma', 'Melanocytic nevi', 'Melanoma', 'Vascular lesions']

def setup_model_pth(path_to_pth_file, learner_name_to_load, classes):
    data = ImageDataBunch.single_from_classes(
        path_to_pth_file, classes, ds_tfms=get_transforms(), size=224).normalize(imagenet_stats)
    learn = cnn_learner(data, models.densenet169, model_dir='models')
    learn.load(learner_name_to_load, device=torch.device('cpu'))
    return learn

learn = setup_model_pth(PATH_TO_MODELS_DIR, NAME_OF_FILE, classes)

def encode(img):
    img = (image2np(img.data) * 255).astype('uint8')
    pil_img = PILImage.fromarray(img)
    buff = BytesIO()
    pil_img.save(buff, format="JPEG")
    return base64.b64encode(buff.getvalue()).decode("utf-8")

def model_predict(img):
    img = open_image(BytesIO(img))
    pred_class,pred_idx,outputs = learn.predict(img)
    formatted_outputs = ["{:.1f}%".format(value) for value in [x * 100 for x in torch.nn.functional.softmax(outputs, dim=0)]]
    pred_probs = sorted(
            zip(learn.data.classes, map(str, formatted_outputs)),
            key=lambda p: p[1],
            reverse=True
        )

    img_data = encode(img)
    result = {"class":pred_class, "probs":pred_probs, "image":img_data}
    return render_template('result.html', result=result)

@app.route('/', methods=['GET', "POST"])
def index():
    # Main page
    return render_template('index.html')

@app.route('/upload', methods=["POST", "GET"])
def upload():
    if request.method == 'POST':
        # Get the file from post request
        img = request.files['file'].read()
        if img != None:
        # Make prediction
            preds = model_predict(img)
            return preds
    return 'OK'

@app.route("/classify-url", methods=["POST", "GET"])
def classify_url():
    if request.method == 'POST':
        url = request.form["url"]
        if url != None:
            response = requests.get(url)
            preds = model_predict(response.content)
            return preds
    return 'OK'

if __name__ == '__main__':
    port = os.environ.get('PORT', 8008)

    if "prepare" not in sys.argv:
        app.run(debug=False, host='0.0.0.0', port=port)

'''

Body:
Your code is searching for the file in the root directory of the computer, which is not where your file is. It's there in some folder, and that's why the file couldn't be found.

Change path variable from

PATH_TO_MODELS_DIR = Path('')

to

PATH_TO_MODELS_DIR = Path('.')

It'll search for your folder models and file model_best.pth in current working directory.


答:
A idea might be to use a post-push hook and put the curl command in there.
On every commit the script with the curl will be exexuted.

in <project>/.git/hooks

put a file called post-push, this should be a shell script with the command required.

usually i prefer these type of things to be done on push not on every commit

Title: Run some action after changes commit

Body:
I have a Java Application. Everytime a change is made to self hosted git server, I need to curl a endpoint of the application inorder to reload the properties. Here is what my curl look like: curl -X {} http://someurl:8080/abc.

I would like to automate this after a commit is made. I have read about git and found that "post commit" should get the job done but after reading about it for more than 2 hours I gave up. I would like to create a script that will curl the endpoint when commit is made. The hosted server is a linux machine.