问:
Stunnel certificate verify failed
I am trying to setup stunnel with REDIS in windows.After installing stunnel and redis, I have following configuration fro server and client mode :

Client Machine Configuration:

```<code>[redis-stunnel]
client = yes
cert = stunnel.pem
accept = 127.0.0.1:6379
connect = 172.30.12.28:6390
verifyChain = yes
CAfile = stunnel.pem
checkHost = 172.30.12.28:6390
OCSPaia = yes
</code>```

Server Machine configuration :

```<code>[redis-stunnel-server]
accept  = 6380
connect = 6379
cert = stunnel.pem
</code>```

Configuration is loading successfully, But when i try to connect from client machine to the port number :6379, I am getting the following error :

```<code>Service [redis-stunnel] connected remote server from 172.30.12.120:65484
2018.03.19 21:03:41 LOG4[229]: CERT: No matching host name found
2018.03.19 21:03:41 LOG4[229]: Rejected by CERT at depth=0: C=IN, ST=KARNATAKA, L=BANGALORE, O=AHC, OU=healthcare, CN=172.30.12.120
2018.03.19 21:03:41 LOG3[229]: SSL_connect: 14090086: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
2018.03.19 21:03:41 LOG5[229]: Connection reset: 0 byte(s) sent to TLS, 0 byte(s) sent to socket
</code>```

What is wrong here ?

答:
You should replace checkHost = 172.30.12.28:6390 with checkIP = 172.30.12.28.

checkHost option checks if the specified DNS host name or wildcard matches any of those provided in peer certificate's SAN or CN fields.

To check against an IP address one has to use checkIP option.

Under the hood stunnel uses OpenSSL's X509_check_host and X509_check_ip_asc functions. Here's their description.

Title: Stunnel certificate verify failed

Body:
I am trying to setup stunnel with REDIS in windows.After installing stunnel and redis, I have following configuration fro server and client mode :

Client Machine Configuration:

[redis-stunnel]
client = yes
cert = stunnel.pem
accept = 127.0.0.1:6379
connect = 172.30.12.28:6390
verifyChain = yes
CAfile = stunnel.pem
checkHost = 172.30.12.28:6390
OCSPaia = yes

Server Machine configuration :

[redis-stunnel-server]
accept  = 6380
connect = 6379
cert = stunnel.pem

Configuration is loading successfully, But when i try to connect from client machine to the port number :6379, I am getting the following error :

Service [redis-stunnel] connected remote server from 172.30.12.120:65484
2018.03.19 21:03:41 LOG4[229]: CERT: No matching host name found
2018.03.19 21:03:41 LOG4[229]: Rejected by CERT at depth=0: C=IN, ST=KARNATAKA, L=BANGALORE, O=AHC, OU=healthcare, CN=172.30.12.120
2018.03.19 21:03:41 LOG3[229]: SSL_connect: 14090086: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
2018.03.19 21:03:41 LOG5[229]: Connection reset: 0 byte(s) sent to TLS, 0 byte(s) sent to socket

What is wrong here ?


来源: stackexchange

问:
How can I detect when a web page finishes loading in a WebBrowser control?
I'm talking about that "webbrowser" control which uses internet explorer.
How can I detect when it finishes loading?</p>

答: Always look for events in such cases. In this case, DocumentCompleted event.

ContentLicense: CC BY-SA 3.0


问:
moment.js will not parse UK format date even when setting the locale
Quite simply, this is my code:

http://jsfiddle.net/NibblyPig/k9zb4ysp/

```<code>moment.locale('en-GB');

var d = moment('22/12/2019');

alert(d);
</code>```

I would expect this to parse, however it says invalid date.

I have referenced moment.js and the locale/en-gb.js

I'm writing a global control so the date may come in in a variety of formats.

If I put in a variety of American dates they all work, for example 12/12/2019, 12/12/2019 23:04 etc.

However the locale command does not appear to do anything and I cannot get a single date to parse. What am I doing wrong?

答:
You can return a date using moment.js in a desired format -</p>

```<code>return moment(aDateVar).format('DD/MM/YYYY');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Quite simply, this is my code:

http://jsfiddle.net/NibblyPig/k9zb4ysp/

moment.locale('en-GB');

var d = moment('22/12/2019');

alert(d);

I would expect this to parse, however it says invalid date.

I have referenced moment.js and the locale/en-gb.js

I'm writing a global control so the date may come in in a variety of formats.

If I put in a variety of American dates they all work, for example 12/12/2019, 12/12/2019 23:04 etc.

However the locale command does not appear to do anything and I cannot get a single date to parse. What am I doing wrong?

Body:
You can return a date using moment.js in a desired format -

return moment(aDateVar).format('DD/MM/YYYY');


问:
Passing tuple returned by function to other function
Considering two functions

```<code>def bar()
  return 1,2
end

def foo(a,b)
  puts %{#{a},#{b}}
end
</code>```

I would like to be able to call foo both with explicit parameters (e.g. foo(3,4)) as well as with parameters returned by bar (e.g. foo(bar)).

Unfortunately, the 2nd call produces an ArgumentError: "wrong number of arguments (given 1, expected 2)".

Declaring foo() to take a tuple (def foo(c); a,b = c; puts %{#{a},#{b}}; end) doesn't work either, because then the 1st call parameter raises the ArgumentError.

I thought of defining foo to take a Hash:

```<code>def foo(c)
  a,b = c['a'],c['b']
  puts %{#{a},#{b}}
end
</code>```

but this makes the use with explicit parameters rather unhandy. Same with an Array.

What's the Ruby-esque way to solve this?

答:
You need to splat the two-element array returned by bar: foo(*bar). That’s because foo has two arguments, each an element of the array returned by bar, not one argument that is that array.

Recall that the splat operator converts foo(*[1,2]) to foo(1,2).

Body:
Considering two functions

def bar()
  return 1,2
end

def foo(a,b)
  puts %{#{a},#{b}}
end

I would like to be able to call foo both with explicit parameters (e.g. foo(3,4)) as well as with parameters returned by bar (e.g. foo(bar)).

Unfortunately, the 2nd call produces an ArgumentError: "wrong number of arguments (given 1, expected 2)".

Declaring foo() to take a tuple (def foo(c); a,b = c; puts %{#{a},#{b}}; end) doesn't work either, because then the 1st call parameter raises the ArgumentError.

I thought of defining foo to take a Hash:

def foo(c)
  a,b = c['a'],c['b']
  puts %{#{a},#{b}}
end

but this makes the use with explicit parameters rather unhandy. Same with an Array.

What's the Ruby-esque way to solve this?


答:
Subscribe to the WebBrowser control's DocumentCompleted event. i.e.</p>

```<code>this.webBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.WebBrowser_DocumentCompleted);

private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
  // Do stuff here
}
</code>```

Title: How can I detect when a web page finishes loading in a WebBrowser control?

Body:
I'm talking about that "webbrowser" control which uses internet explorer.
How can I detect when it finishes loading?

Body:
Subscribe to the WebBrowser control's DocumentCompleted event. i.e.

this.webBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.WebBrowser_DocumentCompleted);

private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
  // Do stuff here
}


问:
Universal Links
I'm trying to implement Universal links I'm able to launch the app but stuck in routing. How to decode ids and bind them with viewcontrollers. Link looks like this.

https://myapp.com/#/observation/c2hhcmlhcl9pY29udHJvbGFwcF9zZV9faXJlcG9ydGxpdGVfdG9rZW4/project_1496669822_ea024600-3b13-4565-bc1e-b5892c521121/party_1496669822_618ecdd4-5649-4ebd-a43f-46fa64b56732/inspection_test_8853A89C-2F66-4B10-9DD4-2B248D4010F7/defect_2017-08-31_16_53_test_15041912125876/%22

Here is how looks my code

```<code>class DeeplinkParser {

    static let shared = DeeplinkParser()
    private init(){}

    func parseDeepLink(_ url: URL) -> DeeplinkType? {

        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true), let host = components.host else {
            return nil
        }

        var token = components.user?.components(separatedBy: "/")
        var pathComponents = components.path.components(separatedBy: "/")
        var linkFragment = components.fragment?.components(separatedBy: "/")
        let queryItems = components.queryItems
        //var pathComponents = url.pathComponents

        pathComponents.removeFirst()

        switch host {
            case "app.icontrolapp.se":
                let projectIdString = pathComponents.filter({ $0.hasPrefix("project_")}).first
                if let projectId = projectIdString?.components(separatedBy: "_").last {
                    findSession(components: components)

                    if let urlPath = parseDeepLink(url) {
                        //print("Url Path: \(urlPath)")
                        let proj = URLSession.shared.dataTask(with: url) {(data, response, error) in
                            if error != nil {
                                print("Error\(error)")
                            } else {
                                if let usableData = data {
                                    print(usableData)
                                }
                            }
                        }
                        proj.resume()
                    }

                    print("Path Components 0: \(pathComponents[0])")
                    print("Path Components 1: \(pathComponents[1])")
                    print("Path Components 2: \(pathComponents[2])")
                    print("Path Components 3: \(pathComponents[3])")

                    print("ProjectId: \(projectId)")
                    print(findSession(components: components))

                    return DeeplinkType.projects(.details(id: projectId))
                }
            case "closeout.icontrolapp.se":
                guard var tokenId = linkFragment?[2], let projetId = linkFragment?[3], let teamId = linkFragment?[4], let inspectionId = linkFragment?[5], let issueId = linkFragment?[6] else { return nil }

                //guard let userId = linkFragment?[2], let teamId = linkFragment?[4], let inspectionId = linkFragment?[5], let issueId = linkFragment?[6] else { return nil }

                print("Token ID \(tokenId)")
                print("Project ID \(projetId)")
                print("Team ID  \(teamId)")
                print("Inspection ID \(inspectionId)")
                print("Issue ID \(issueId)")
 let session = Session.currentSession()
                session?.userID?.append(tokenId)

                tokenId.append((session?.userID)!)

                let project = ProjectEntity.get(projetId)
                let report = Report.get(inspectionId)

                print("Report: \(report!)")

                let issue = Issue.get(issueId)

                session?.selectProject(project)
                session?.selectReport(report)

                //session?.selectReport(report)
                CurrentIssue.sharedInstance.makeIssueCurrentSelection(issue!, db: CBLDatabase.db()!)

                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                let window = appDelegate.window!
                return DeeplinkType.observation(tokenId: tokenId, projectId: projetId, teamId: teamId, issueId: issueId, inspectionId: inspectionId)
        default:
            break
        }
        return nil
    }

}

import UIKit

enum DeeplinkType{
    enum Projects {
        case root
        case details(id: String)
    }

    case projects(Projects)
    case projectId(Projects)
    case observation(tokenId: String, projectId: String, teamId: String, issueId: String, inspectionId: String)
    case teamId
    case request(id: String)
}

enum Route {
    case issue
    case bluePrint

    init?(url: URL) {
        switch url.absoluteString {
        case "\(url)//defect_2017-08-31_16_53_test_15041912125876": self = .issue
        default: return nil
        }
    }
}

var Deeplinker = DeepLinkManager()
class DeepLinkManager{

    fileprivate init(){}

    private var deeplinkType: DeeplinkType?

    func handleRoute(route: Route) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let window = appDelegate.window!

        let issueVC = window.rootViewController as! IssuesViewController

        switch route {
        case .issue: issueVC.showMenu()
        default: brea
        }
    }

    @discardableResult
    func handleDeeplink(url: URL) -> Bool {
        deeplinkType = DeeplinkParser.shared.parseDeepLink(url)
        return deeplinkType != nil
    }

    func checkDeepLink() {
        guard let deeplinkType = deeplinkType else {
            return
        }

        DeeplinkNavigator.shared.proceedToDeeplink(deeplinkType)

        self.deeplinkType = nil
    }
}

class DeeplinkNavigator: UIViewController {

    static let shared = DeeplinkNavigator()
    //private init() {}

    var window: UIWindow?

    private var alertController = UIAlertController()

    func proceedToDeeplink(_ type: DeeplinkType) {
        switch type {
        case .observation(let tokenId, let projectId, let teamId, let issueId, let photoId):
            presentView()
        case .projects(.root):
            displayAlert(title: "Project Root")
        case .projects(.details(id: let id)):
            displayAlert(title: "Project Details bla bla bla \(id)")
        case .request(id: let id):
            displayAlert(title: "Request Details \(id)")
        /*case .project(id: let id):
            displayAlert(title: "project details \(id)")*/
        default: break
        }
    }

    private func displayAlert(title: String) {
        alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alertController.addAction(okButton)
        alertController.title = title
        if let vc = UIApplication.shared.keyWindow?.rootViewController{
            if vc.presentedViewController != nil {
                alertController.dismiss(animated: false, completion: {
                    vc.present(self.alertController, animated: true, completion: nil)
                })
            } else {
                vc.present(alertController, animated: true, completion: nil)
            }
        }
    }
</code>```

答: My personal experience has shown that this is not FE responsibility. One possible scenario is after receiving the URL to send it to the BackEnd and from that point you should receive deeplink or error for translation. Also, your app should navigate through screens with deeplinks.

Title: Universal Links

Body:
I'm trying to implement Universal links I'm able to launch the app but stuck in routing. How to decode ids and bind them with viewcontrollers. Link looks like this.

https://myapp.com/#/observation/c2hhcmlhcl9pY29udHJvbGFwcF9zZV9faXJlcG9ydGxpdGVfdG9rZW4/project_1496669822_ea024600-3b13-4565-bc1e-b5892c521121/party_1496669822_618ecdd4-5649-4ebd-a43f-46fa64b56732/inspection_test_8853A89C-2F66-4B10-9DD4-2B248D4010F7/defect_2017-08-31_16_53_test_15041912125876/%22

Here is how looks my code

class DeeplinkParser {

    static let shared = DeeplinkParser()
    private init(){}

    func parseDeepLink(_ url: URL) -> DeeplinkType? {

        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true), let host = components.host else {
            return nil
        }

        var token = components.user?.components(separatedBy: "/")
        var pathComponents = components.path.components(separatedBy: "/")
        var linkFragment = components.fragment?.components(separatedBy: "/")
        let queryItems = components.queryItems
        //var pathComponents = url.pathComponents

        pathComponents.removeFirst()

        switch host {
            case "app.icontrolapp.se":
                let projectIdString = pathComponents.filter({ $0.hasPrefix("project_")}).first
                if let projectId = projectIdString?.components(separatedBy: "_").last {
                    findSession(components: components)

                    if let urlPath = parseDeepLink(url) {
                        //print("Url Path: \(urlPath)")
                        let proj = URLSession.shared.dataTask(with: url) {(data, response, error) in
                            if error != nil {
                                print("Error\(error)")
                            } else {
                                if let usableData = data {
                                    print(usableData)
                                }
                            }
                        }
                        proj.resume()
                    }

                    print("Path Components 0: \(pathComponents[0])")
                    print("Path Components 1: \(pathComponents[1])")
                    print("Path Components 2: \(pathComponents[2])")
                    print("Path Components 3: \(pathComponents[3])")

                    print("ProjectId: \(projectId)")
                    print(findSession(components: components))

                    return DeeplinkType.projects(.details(id: projectId))
                }
            case "closeout.icontrolapp.se":
                guard var tokenId = linkFragment?[2], let projetId = linkFragment?[3], let teamId = linkFragment?[4], let inspectionId = linkFragment?[5], let issueId = linkFragment?[6] else { return nil }

                //guard let userId = linkFragment?[2], let teamId = linkFragment?[4], let inspectionId = linkFragment?[5], let issueId = linkFragment?[6] else { return nil }

                print("Token ID \(tokenId)")
                print("Project ID \(projetId)")
                print("Team ID  \(teamId)")
                print("Inspection ID \(inspectionId)")
                print("Issue ID \(issueId)")
 let session = Session.currentSession()
                session?.userID?.append(tokenId)

                tokenId.append((session?.userID)!)

                let project = ProjectEntity.get(projetId)
                let report = Report.get(inspectionId)

                print("Report: \(report!)")

                let issue = Issue.get(issueId)

                session?.selectProject(project)
                session?.selectReport(report)

                //session?.selectReport(report)
                CurrentIssue.sharedInstance.makeIssueCurrentSelection(issue!, db: CBLDatabase.db()!)

                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                let window = appDelegate.window!
                return DeeplinkType.observation(tokenId: tokenId, projectId: projetId, teamId: teamId, issueId: issueId, inspectionId: inspectionId)
        default:
            break
        }
        return nil
    }

}

import UIKit

enum DeeplinkType{
    enum Projects {
        case root
        case details(id: String)
    }

    case projects(Projects)
    case projectId(Projects)
    case observation(tokenId: String, projectId: String, teamId: String, issueId: String, inspectionId: String)
    case teamId
    case request(id: String)
}

enum Route {
    case issue
    case bluePrint

    init?(url: URL) {
        switch url.absoluteString {
        case "\(url)//defect_2017-08-31_16_53_test_15041912125876": self = .issue
        default: return nil
        }
    }
}

var Deeplinker = DeepLinkManager()
class DeepLinkManager{

    fileprivate init(){}

    private var deeplinkType: DeeplinkType?

    func handleRoute(route: Route) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let window = appDelegate.window!

        let issueVC = window.rootViewController as! IssuesViewController

        switch route {
        case .issue: issueVC.showMenu()
        default: brea
        }
    }

    @discardableResult
    func handleDeeplink(url: URL) -> Bool {
        deeplinkType = DeeplinkParser.shared.parseDeepLink(url)
        return deeplinkType != nil
    }

    func checkDeepLink() {
        guard let deeplinkType = deeplinkType else {
            return
        }

        DeeplinkNavigator.shared.proceedToDeeplink(deeplinkType)

        self.deeplinkType = nil
    }
}

class DeeplinkNavigator: UIViewController {

    static let shared = DeeplinkNavigator()
    //private init() {}

    var window: UIWindow?

    private var alertController = UIAlertController()

    func proceedToDeeplink(_ type: DeeplinkType) {
        switch type {
        case .observation(let tokenId, let projectId, let teamId, let issueId, let photoId):
            presentView()
        case .projects(.root):
            displayAlert(title: "Project Root")
        case .projects(.details(id: let id)):
            displayAlert(title: "Project Details bla bla bla \(id)")
        case .request(id: let id):
            displayAlert(title: "Request Details \(id)")
        /*case .project(id: let id):
            displayAlert(title: "project details \(id)")*/
        default: break
        }
    }

    private func displayAlert(title: String) {
        alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alertController.addAction(okButton)
        alertController.title = title
        if let vc = UIApplication.shared.keyWindow?.rootViewController{
            if vc.presentedViewController != nil {
                alertController.dismiss(animated: false, completion: {
                    vc.present(self.alertController, animated: true, completion: nil)
                })
            } else {
                vc.present(alertController, animated: true, completion: nil)
            }
        }
    }


问:
How do i get first day of year whe i select year in parameter
IN SSRS
I am trying to get first day of year when i select only year in parameter.
I know how to make it in SQL.
e.g. when i select 2020 in paramater i must get 01.01.2020 as output
when i select 2019 in paramater i must get 01.01.2019 as output

i tried to get by
DateAdd("d",-DatePart(DateInterval.DayOfYear,Today,0,0)+1,Today)
 here i get 1st day of year, but i am not getting where should i replace with my year parameter
Can someone please help me.

Thank you in advance

答:
Assuming your year parameter is just a simple integer then you can just do.</p>

```<code>=DateSerial(Parameters!myYearParam.Value, 1, 1)
</code>```

Body:
Assuming your year parameter is just a simple integer then you can just do.

=DateSerial(Parameters!myYearParam.Value, 1, 1)


问:
How to enable @UseAdviceWith in Camel tests
I'm new to Camel and I'm trying to write some tests that use Spring context and @UseAdviceWith annotation. What I need is to make @UseAdviceWith annotation work properly (to not to start Camel context before it is altered) and I found two ways: one is to add loader attribute like this (that was mentioned in Camel in Action book)

```<code>@ContextConfiguration(locations = {"classpath:/META-INF/spring/testContext.xml"},
        loader = CamelSpringDelegatingTestContextLoader.class)
</code>```

Another way is to use

```<code>@BootstrapWith(CamelTestContextBootstrapper.class)
</code>```

What is the difference and what is the right way of using it in unit tests? The version of Camel I currently have to use is 2.15.3.

答:
What is the difference

@BootstrapWith was introduced with Spring 4.1

For older Spring versions use @ContextConfigurations loader parameter

Both of them are Spring annotations, not Camel!

what is the right way of using it in unit tests

Camel offers three different Spring testing modes. To use @UseAdviceWith you have to use "Camel Enhanced Spring Test".

If you are using SpringBoot, there was an issue with @UseAdviceWith that was fixed in Camel 2.21.

JUnit 5 is supported in Camel 3.0. Camel 2.x supports JUnit 4 or the vintage runner of JUnit 5.

In general it is a huge muddle how to correctly configure Camel-Spring-Testing because it depends on the test mode and at least on the versions of Camel, JUnit and Spring. If you add SpringBoot you have another dependency.

However, this is a working Route test class signature with Camel 2.24, SpringBoot 2.1, Spring 5.1 and JUnit Vintage

```<code>@RunWith(CamelSpringBootRunner.class)
@SpringBootTest(
    classes = {
        [Classes to load for the test]
    }
)
@EnableAutoConfiguration
@UseAdviceWith
public class MyTestClass { ... }
</code>```

Body:
I'm new to Camel and I'm trying to write some tests that use Spring context and @UseAdviceWith annotation. What I need is to make @UseAdviceWith annotation work properly (to not to start Camel context before it is altered) and I found two ways: one is to add loader attribute like this (that was mentioned in Camel in Action book)

@ContextConfiguration(locations = {"classpath:/META-INF/spring/testContext.xml"},
        loader = CamelSpringDelegatingTestContextLoader.class)

Another way is to use

@BootstrapWith(CamelTestContextBootstrapper.class)

What is the difference and what is the right way of using it in unit tests? The version of Camel I currently have to use is 2.15.3.

Body:
What is the difference

@BootstrapWith was introduced with Spring 4.1

For older Spring versions use @ContextConfigurations loader parameter

Both of them are Spring annotations, not Camel!

what is the right way of using it in unit tests

Camel offers three different Spring testing modes. To use @UseAdviceWith you have to use "Camel Enhanced Spring Test".

If you are using SpringBoot, there was an issue with @UseAdviceWith that was fixed in Camel 2.21.

JUnit 5 is supported in Camel 3.0. Camel 2.x supports JUnit 4 or the vintage runner of JUnit 5.

In general it is a huge muddle how to correctly configure Camel-Spring-Testing because it depends on the test mode and at least on the versions of Camel, JUnit and Spring. If you add SpringBoot you have another dependency.

However, this is a working Route test class signature with Camel 2.24, SpringBoot 2.1, Spring 5.1 and JUnit Vintage

@RunWith(CamelSpringBootRunner.class)
@SpringBootTest(
    classes = {
        [Classes to load for the test]
    }
)
@EnableAutoConfiguration
@UseAdviceWith
public class MyTestClass { ... }


问:
Multiply each row of one dataframe by all rows of a second dataframe
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

```<code>df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Can somebody point me to an efficient way to do this in R?

答:
One option involving purrr could be:

```<code>map_dfr(.x = asplit(df2[-1], 1), ~ sweep(df1, 2, FUN = `*`, .x))

  intercept  age male
1       3.4 3.20 0.07
2       3.6 2.00 0.06
3       3.7 2.40 0.07
4       3.4 3.60 0.00
5       3.6 2.25 0.00
6       3.7 2.70 0.00
</code>```

If also the id column is important:

```<code>data.frame(map_dfr(.x = asplit(df2[-1], 1), ~ sweep(df1, 2, FUN = `*`, .x)),
           id = rep(df2$id, each = nrow(df1)))

  intercept  age male id
1       3.4 3.20 0.07  a
2       3.6 2.00 0.06  a
3       3.7 2.40 0.07  a
4       3.4 3.60 0.00  b
5       3.6 2.25 0.00  b
6       3.7 2.70 0.00  b
</code>```

The same with base R:

```<code>do.call(rbind, lapply(asplit(df2[-1], 1), function(x) sweep(df1, 2, FUN = `*`, x)))
</code>```

Or:

```<code>data.frame(do.call(rbind, lapply(asplit(df2[-1], 1), function(x) sweep(df1, 2, FUN = `*`, x))),
           id = rep(df2$id, each = nrow(df1)))
</code>```

Body:
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))

Can somebody point me to an efficient way to do this in R?

Body:
One option involving purrr could be:

map_dfr(.x = asplit(df2[-1], 1), ~ sweep(df1, 2, FUN = `*`, .x))

  intercept  age male
1       3.4 3.20 0.07
2       3.6 2.00 0.06
3       3.7 2.40 0.07
4       3.4 3.60 0.00
5       3.6 2.25 0.00
6       3.7 2.70 0.00

If also the id column is important:

data.frame(map_dfr(.x = asplit(df2[-1], 1), ~ sweep(df1, 2, FUN = `*`, .x)),
           id = rep(df2$id, each = nrow(df1)))

  intercept  age male id
1       3.4 3.20 0.07  a
2       3.6 2.00 0.06  a
3       3.7 2.40 0.07  a
4       3.4 3.60 0.00  b
5       3.6 2.25 0.00  b
6       3.7 2.70 0.00  b

The same with base R:

do.call(rbind, lapply(asplit(df2[-1], 1), function(x) sweep(df1, 2, FUN = `*`, x)))

Or:

data.frame(do.call(rbind, lapply(asplit(df2[-1], 1), function(x) sweep(df1, 2, FUN = `*`, x))),
           id = rep(df2$id, each = nrow(df1)))


问:
Is there a way to specify CICD Pipeline target path in yaml file?
I have a Maven based project that is hosted on Gitlab, but does not exactly follow the Maven based layout :

The layout is as follows :

branch "example"

```<code>-App
 - Service
  - SubService
   - src
    -main
     -java
      - Core.java
    - test
     -java
      - CoreTest.java
   -pom.xml
</code>```

As you can see, the actual Maven specific code is in SubService, not the root

Now, when I have a commit on Core.java, I want to run a set of maven commands to build and test.

However, I havent understood how to specify (in the Gitlab CI YAML file) to build and test the code found in App/Service/SubService[/..]

I have only been able to specify the branch - is there any way to specify a specific repository endpoint to test from in Gitlab ?

Thanks!

答:
Within your .gitlab-ci.yml-file, you can specify the commands that should be run in order to build your project.

You can e.g. cd to the directory App/Server/SubService and execute the maven build within this directory:

```<code>build:
  stage: build
  script:
     -cd App/Server/SubService
    - mvn package
</code>```

Body:
I have a Maven based project that is hosted on Gitlab, but does not exactly follow the Maven based layout :

The layout is as follows :

branch "example"

-App
 - Service
  - SubService
   - src
    -main
     -java
      - Core.java
    - test
     -java
      - CoreTest.java
   -pom.xml

As you can see, the actual Maven specific code is in SubService, not the root

Now, when I have a commit on Core.java, I want to run a set of maven commands to build and test.

However, I havent understood how to specify (in the Gitlab CI YAML file) to build and test the code found in App/Service/SubService[/..]

I have only been able to specify the branch - is there any way to specify a specific repository endpoint to test from in Gitlab ?

Thanks!

Body:
Within your .gitlab-ci.yml-file, you can specify the commands that should be run in order to build your project.

You can e.g. cd to the directory App/Server/SubService and execute the maven build within this directory:

build:
  stage: build
  script:
     -cd App/Server/SubService
    - mvn package


问:
Unhandled Exception: MissingPluginException(No implementation found for method getToken on channel plugins.flutter.io/firebase_messaging)
I try to get a firebase cloud messaging token to the my flutter app. which is running on the android emulator What went wrong here?. I tried flutter run but this is not working, I here I used 1.firebase_messaging: ^6.0.9 as a dependency and 2.

```<code>    import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

class Notifications_ extends StatefulWidget {
  @override
  _Notifications_State createState() => _Notifications_State();
}

class _Notifications_State extends State<Notifications_> {

  final FirebaseMessaging _messaging=FirebaseMessaging();

  @override
  void initState() {
    super.initState();

    _messaging.getToken().then((token)
    {
      print(token);
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('notification'),
      ),
      body: Text('body testing'),
    );
  }
}
</code>```

```<code> E/flutter ( 5931): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getToken on channel plugins.flutter.io/firebase_messaging)
</code>```

E/flutter ( 5931): #0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:319:7)
              E/flutter ( 5931):
              E/flutter ( 5931): #1      FirebaseMessaging.getToken (package:firebase_messaging/firebase_messaging.dart:150:27)
              E/flutter ( 5931): #2      _Notifications_State.initState (package:sampletestingpro/Notification.dart:17:16)
              E/flutter ( 5931): #3      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
              E/flutter ( 5931): #4      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
              E/flutter ( 5931): #5      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
              E/flutter ( 5931): #6      Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
              E/flutter ( 5931): #7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #8      Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #9      StatelessElement.update (package:flutter/src/widgets/framework.dart:4298:5)
              E/flutter ( 5931): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #11     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #12     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #13     StatelessElement.update (package:flutter/src/widgets/framework.dart:4298:5)
              E/flutter ( 5931): #14     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #15     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #16     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #17     ProxyElement.update (package:flutter/src/widgets/framework.dart:4557:5)
              E/flutter ( 5931): #18     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #19     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #20     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #21     ProxyElement.update (package:flutter/src/widgets/framework.dart:4557:5)
              E/flutter ( 5931): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #23     RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5161:32)
              E/flutter ( 5931): #24     MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5561:17)
              E/flutter ( 5931): #25     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #26     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #27     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #28     StatefulElement.update (package:flutter/src/widgets/framework.dart:4413:5)
              E/flutter ( 5931): #29     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #30     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #31     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #32     ProxyElement.update (package:flutter/src/widgets/framework.dart:4557:5)
              E/flutter ( 5931): #33     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #34     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #35     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #36     StatefulElement.update (package:flutter/src/widgets/framework.dart:4413:5)
              E/flutter ( 5931): #37     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #38     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5452:14)
              E/flutter ( 5931): #39     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #40     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #41     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #42     StatelessElement.update (package:flutter/src/widgets/framework.dart:4298:5)
              E/flutter ( 5931): #43     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #44     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5452:14)
              E/flutter ( 5931): #45     Element.update.

答: Keep the google JSON service file inside the app folder, I wrongly put the JSON file inside the src/ folder that's why I got an error

Body:
I try to get a firebase cloud messaging token to the my flutter app. which is running on the android emulator What went wrong here?. I tried flutter run but this is not working, I here I used 1.firebase_messaging: ^6.0.9 as a dependency and 2.

    import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

class Notifications_ extends StatefulWidget {
  @override
  _Notifications_State createState() => _Notifications_State();
}

class _Notifications_State extends State<Notifications_> {

  final FirebaseMessaging _messaging=FirebaseMessaging();

  @override
  void initState() {
    super.initState();

    _messaging.getToken().then((token)
    {
      print(token);
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('notification'),
      ),
      body: Text('body testing'),
    );
  }
}

 E/flutter ( 5931): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getToken on channel plugins.flutter.io/firebase_messaging)

E/flutter ( 5931): #0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:319:7)
              E/flutter ( 5931):
              E/flutter ( 5931): #1      FirebaseMessaging.getToken (package:firebase_messaging/firebase_messaging.dart:150:27)
              E/flutter ( 5931): #2      _Notifications_State.initState (package:sampletestingpro/Notification.dart:17:16)
              E/flutter ( 5931): #3      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
              E/flutter ( 5931): #4      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
              E/flutter ( 5931): #5      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
              E/flutter ( 5931): #6      Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
              E/flutter ( 5931): #7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #8      Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #9      StatelessElement.update (package:flutter/src/widgets/framework.dart:4298:5)
              E/flutter ( 5931): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #11     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #12     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #13     StatelessElement.update (package:flutter/src/widgets/framework.dart:4298:5)
              E/flutter ( 5931): #14     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #15     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #16     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #17     ProxyElement.update (package:flutter/src/widgets/framework.dart:4557:5)
              E/flutter ( 5931): #18     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #19     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #20     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #21     ProxyElement.update (package:flutter/src/widgets/framework.dart:4557:5)
              E/flutter ( 5931): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #23     RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5161:32)
              E/flutter ( 5931): #24     MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5561:17)
              E/flutter ( 5931): #25     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #26     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #27     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #28     StatefulElement.update (package:flutter/src/widgets/framework.dart:4413:5)
              E/flutter ( 5931): #29     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #30     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #31     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #32     ProxyElement.update (package:flutter/src/widgets/framework.dart:4557:5)
              E/flutter ( 5931): #33     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #34     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #35     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #36     StatefulElement.update (package:flutter/src/widgets/framework.dart:4413:5)
              E/flutter ( 5931): #37     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #38     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5452:14)
              E/flutter ( 5931): #39     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #40     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
              E/flutter ( 5931): #41     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
              E/flutter ( 5931): #42     StatelessElement.update (package:flutter/src/widgets/framework.dart:4298:5)
              E/flutter ( 5931): #43     Element.updateChild (package:flutter/src/widgets/framework.dart:2977:15)
              E/flutter ( 5931): #44     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5452:14)
              E/flutter ( 5931): #45     Element.update.


问:
<NameError: name 'categorical_crossentropy' is not defined> when trying to load a model
I have a custom keras model built:

```<code>def create_model(input_dim,
                     filters,
                     kernel_size,
                     strides,
                     padding,
                     rnn_units=256,
                     output_dim=30,
                     dropout_rate=0.5,
                     cell=GRU,
                     activation='tanh'):
"""
Creates simple Conv-Bi-RNN model used for word classification approach.

:params:
    input_dim - Integer, size of inputs (Example: 161 if using spectrogram, 13 for mfcc)
    filters - Integer, number of filters for the Conv1D layer
    kernel_size - Integer, size of kernel for Conv layer
    strides - Integer, stride size for the Conv layer
    padding - String, padding version for the Conv layer ('valid' or 'same')
    rnn_units - Integer, number of units/neurons for the RNN layer(s)
    output_dim - Integer, number of output neurons/units at the output layer
                          NOTE: For speech_to_text approach, this number will be number of characters that may occur
    dropout_rate - Float, percentage of dropout regularization at each RNN layer, between 0 and 1
    cell - Keras function, for a type of RNN layer * Valid solutions: LSTM, GRU, BasicRNN
    activation - String, activation type at the RNN layer

:returns:
    model - Keras Model object

"""

keras.losses.custom_loss = 'categorical_crossentropy'

#Defines Input layer for the model
input_data = Input(name='inputs', shape=input_dim)

#Defines 1D Conv block (Conv layer +  batch norm)
conv_1d = Conv1D(filters,
                 kernel_size,
                 strides=strides,
                 padding=padding,
                 activation='relu',
                 name='layer_1_conv',
                 dilation_rate=1)(input_data)
conv_bn = BatchNormalization(name='conv_batch_norm')(conv_1d)

#Defines Bi-Directional RNN block (Bi-RNN layer + batch norm)
layer = cell(rnn_units, activation=activation,
            return_sequences=True, implementation=2, name='rnn_1', dropout=dropout_rate)(conv_bn)
layer = BatchNormalization(name='bt_rnn_1')(layer)

#Defines Bi-Directional RNN block (Bi-RNN layer + batch norm)
layer = cell(rnn_units, activation=activation,
            return_sequences=True, implementation=2, name='final_layer_of_rnn')(layer)
layer = BatchNormalization(name='bt_rnn_final')(layer)

layer = Flatten()(layer)

#squish RNN features to match number of classes
time_dense = Dense(output_dim)(layer)

#Define model predictions with softmax activation
y_pred = Activation('softmax', name='softmax')(time_dense)

#Defines Model itself, and use lambda function to define output length based on inputs
model = Model(inputs=input_data, outputs=y_pred)

model.output_length = lambda x: cnn_output_length(x, kernel_size, padding, strides)

#Adds categorical crossentropy loss for the classification model

model = add_categorical_loss(model , output_dim)

#compile the model with choosen loss and optimizer

model.compile(loss={'categorical_crossentropy': lambda y_true, y_pred: y_pred},
optimizer=keras.optimizers.RMSprop(), metrics=['accuracy'])
print("\r\ncompile the model with choosen loss and optimizer\r\n")

print(model.summary())
return model
</code>```

and after training model:

```<code>checkpointer = ModelCheckpoint(filepath=save_path+'tst_model.hdf5')
#Train the choosen model with the data generator

hist = model.fit_generator(generator=generator.next_train(),            #Calls generators next_train function which generates new batch of training data
                            steps_per_epoch=steps_per_epoch,            #Defines how many training steps are there
                            epochs=epochs,                              #Defines how many epochs does a training process takes
                            validation_data=generator.next_valid(),     #Calls generators next_valid function which generates new batch of validation data
                            validation_steps=validation_steps,          #Defines how many validation steps are theere
                            callbacks=[checkpointer],                   #Defines all callbacks (In this case we only have molde checkpointer that saves the model)
                            verbose=verbose)
</code>```

Adter thet I am trying to load the latest checkpoint model as follows:

from keras.models import load_model
model = load_model(filepath=save_path+'tst_model.hdf5')

and get:

```<code>NameError: name 'categorical_crossentropy' is not defined
</code>```

What i doing wrong?

Using:
Ubuntu 18.04
Python 3.6.8
TensorFlow 2.0
TensorFlow backend 2.3.1

答:
You must import the library.

from tensorflow.keras.losses import categorical_crossentropy
```

Body:
I have a custom keras model built:

def create_model(input_dim,
                     filters,
                     kernel_size,
                     strides,
                     padding,
                     rnn_units=256,
                     output_dim=30,
                     dropout_rate=0.5,
                     cell=GRU,
                     activation='tanh'):
"""
Creates simple Conv-Bi-RNN model used for word classification approach.

:params:
    input_dim - Integer, size of inputs (Example: 161 if using spectrogram, 13 for mfcc)
    filters - Integer, number of filters for the Conv1D layer
    kernel_size - Integer, size of kernel for Conv layer
    strides - Integer, stride size for the Conv layer
    padding - String, padding version for the Conv layer ('valid' or 'same')
    rnn_units - Integer, number of units/neurons for the RNN layer(s)
    output_dim - Integer, number of output neurons/units at the output layer
                          NOTE: For speech_to_text approach, this number will be number of characters that may occur
    dropout_rate - Float, percentage of dropout regularization at each RNN layer, between 0 and 1
    cell - Keras function, for a type of RNN layer * Valid solutions: LSTM, GRU, BasicRNN
    activation - String, activation type at the RNN layer

:returns:
    model - Keras Model object

"""

keras.losses.custom_loss = 'categorical_crossentropy'

#Defines Input layer for the model
input_data = Input(name='inputs', shape=input_dim)

#Defines 1D Conv block (Conv layer +  batch norm)
conv_1d = Conv1D(filters,
                 kernel_size,
                 strides=strides,
                 padding=padding,
                 activation='relu',
                 name='layer_1_conv',
                 dilation_rate=1)(input_data)
conv_bn = BatchNormalization(name='conv_batch_norm')(conv_1d)

#Defines Bi-Directional RNN block (Bi-RNN layer + batch norm)
layer = cell(rnn_units, activation=activation,
            return_sequences=True, implementation=2, name='rnn_1', dropout=dropout_rate)(conv_bn)
layer = BatchNormalization(name='bt_rnn_1')(layer)

#Defines Bi-Directional RNN block (Bi-RNN layer + batch norm)
layer = cell(rnn_units, activation=activation,
            return_sequences=True, implementation=2, name='final_layer_of_rnn')(layer)
layer = BatchNormalization(name='bt_rnn_final')(layer)

layer = Flatten()(layer)

#squish RNN features to match number of classes
time_dense = Dense(output_dim)(layer)

#Define model predictions with softmax activation
y_pred = Activation('softmax', name='softmax')(time_dense)

#Defines Model itself, and use lambda function to define output length based on inputs
model = Model(inputs=input_data, outputs=y_pred)

model.output_length = lambda x: cnn_output_length(x, kernel_size, padding, strides)

#Adds categorical crossentropy loss for the classification model

model = add_categorical_loss(model , output_dim)

#compile the model with choosen loss and optimizer

model.compile(loss={'categorical_crossentropy': lambda y_true, y_pred: y_pred},
optimizer=keras.optimizers.RMSprop(), metrics=['accuracy'])
print("\r\ncompile the model with choosen loss and optimizer\r\n")

print(model.summary())
return model

and after training model:

checkpointer = ModelCheckpoint(filepath=save_path+'tst_model.hdf5')
#Train the choosen model with the data generator

hist = model.fit_generator(generator=generator.next_train(),            #Calls generators next_train function which generates new batch of training data
                            steps_per_epoch=steps_per_epoch,            #Defines how many training steps are there
                            epochs=epochs,                              #Defines how many epochs does a training process takes
                            validation_data=generator.next_valid(),     #Calls generators next_valid function which generates new batch of validation data
                            validation_steps=validation_steps,          #Defines how many validation steps are theere
                            callbacks=[checkpointer],                   #Defines all callbacks (In this case we only have molde checkpointer that saves the model)
                            verbose=verbose)

Adter thet I am trying to load the latest checkpoint model as follows:

from keras.models import load_model
model = load_model(filepath=save_path+'tst_model.hdf5')

and get:

NameError: name 'categorical_crossentropy' is not defined

What i doing wrong?

Using:
Ubuntu 18.04
Python 3.6.8
TensorFlow 2.0
TensorFlow backend 2.3.1


问:
How to change react-dates input css
I am using react-dates but I can't find any way of changing the css of the input field.

e.g. border, background color etc. since the regular css doesn't work with react-dates.

```<code><SingleDatePicker
    date={this.state.dateOfPurchase}
    onDateChange={date => {
        this.setState({ dateOfPurchase: date })

    }}
    focused={this.state.focused}
    onFocusChange={({ focused }) => this.setState({ focused })}
    id="your_unique_id"
    isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
    numberOfMonths= "1"
/>
</code>```

答:
You can override specific classes.

```<code>.CalendarDay__selected_span {
  background: #82e0aa; //background
  color: white; //text
  border: 1px solid $light-red; //default styles include a border
}
</code>```

See document

Title: How to change react-dates input css

Body:
I am using react-dates but I can't find any way of changing the css of the input field.

e.g. border, background color etc. since the regular css doesn't work with react-dates.

<SingleDatePicker
    date={this.state.dateOfPurchase}
    onDateChange={date => {
        this.setState({ dateOfPurchase: date })

    }}
    focused={this.state.focused}
    onFocusChange={({ focused }) => this.setState({ focused })}
    id="your_unique_id"
    isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
    numberOfMonths= "1"
/>

Body:
You can override specific classes.

.CalendarDay__selected_span {
  background: #82e0aa; //background
  color: white; //text
  border: 1px solid $light-red; //default styles include a border
}

See document


问:
Recommended Prism v2 Silverlight/WPF Project Structure
I'm currently tasked with teaching all the developers, in the company I work in, about Silverlight (v2). The only problem is that I don't have any real Silverlight experience myself. Of course I've studied all the technical details about stuff like databinding, layout etc. so I can help my colleagues. But one thing that is hard to find any information about is the general project structure.

I've decided to follow the P&P Prism 2 path (and maybe even throw some WPF in the mix later on) and so I was wondering if any of you clever people have experience in developing a real project using Prism 2 or even just WPF, and if you had any suggestions about the project/solution structure? Such as "Where do you put views?" or "Do you have any module project naming conventions?" etc.

Any help will be greatly appreciated.

答:
This is purely based on my experience using Prism for WPF, not Silverlight. I'm not an expert at Prism and could easily change my mind on some of these. :-)

It's tempting to make a module for everything. Don't. Your build time will quickly blow out and you're left dealing with a very fractured solution. Instead I have one Main Module, which is loaded statically, and contains everything I want in the base package. Any addons or extras become other modules that are loaded dynamically. It might be worth breaking that one module down a bit, but keep the number small. This also helps with load time.

Not sure if this ones a good idea, but I like to keep the View and ViewModel interfaces in the same file as the View/ViewModel themselves. I like this because the MVVM pattern can produce alot of files, and this keeps the file count down. The down-side is that the Inteface and it's implementation are harder to separate, but I'm unlikely to need to do this, and this technique doesn't interfere with testing, which is the other benefit.

Views tend to go into a Views folder, then a folder for each View. The folder for each View includes the View, the ViewModel, and the Presenter if one is needed.

From the reference implementation, make an Infrastructure project for all common classes that need to be shared between modules. The reference implementation has more details but this can be used for all sorts of things like common service interfaces, constants, etc.

OwnerDisplayName: JohannesH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Cameron MacFarland


问:
FirebaseRemoteConfig fetchAndActivate not updating new value
I have already set the minimum interval to be 0 when in Debug mode.
Currently what I do to fetch new data is by clearing the app storage first before launching the app.

Here is my code:

```<code>private fun initRemoteConfig() {
    remoteConfig = FirebaseRemoteConfig.getInstance()
    configSettings = FirebaseRemoteConfigSettings.Builder()
        .setMinimumFetchIntervalInSeconds(if (BuildConfig.DEBUG) 0 else 3600)
        .build()
    remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
    fetch()
}

private fun fetch() {
    remoteConfig.fetchAndActivate()
        .addOnCompleteListener {
            if (it.isSuccessful) {
                val updated = it.result
                Logger.d(TAG, "Config params updated: $updated. Fetch and activate succeeded") // updated = false

                checkVersion()
            } else {
                Logger.d(TAG, "Fetch failed")
            }
        }

}
</code>```

答:
Try this</p>

```<code>private fun initRemoteConfig() {
  remoteConfig = FirebaseRemoteConfig.getInstance()
  configSettings = FirebaseRemoteConfigSettings.Builder()
    .setMinimumFetchIntervalInSeconds(if (BuildConfig.DEBUG) 0 else 3600)
    .build()
  remoteConfig.setConfigSettingsAsync(configSettings)  //You missed this line
  remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
  fetch()
}

private fun fetch() {
  remoteConfig.fetchAndActivate()
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            val updated = task.result
            Logger.d(TAG, "Config params updated: $updated. Fetch and activate succeeded") // updated = false
            checkVersion()
        } else {
            Logger.d(TAG, "Fetch failed")
        }
    }
}
</code>```

Body:
I have already set the minimum interval to be 0 when in Debug mode.
Currently what I do to fetch new data is by clearing the app storage first before launching the app.

Here is my code:

private fun initRemoteConfig() {
    remoteConfig = FirebaseRemoteConfig.getInstance()
    configSettings = FirebaseRemoteConfigSettings.Builder()
        .setMinimumFetchIntervalInSeconds(if (BuildConfig.DEBUG) 0 else 3600)
        .build()
    remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
    fetch()
}

private fun fetch() {
    remoteConfig.fetchAndActivate()
        .addOnCompleteListener {
            if (it.isSuccessful) {
                val updated = it.result
                Logger.d(TAG, "Config params updated: $updated. Fetch and activate succeeded") // updated = false

                checkVersion()
            } else {
                Logger.d(TAG, "Fetch failed")
            }
        }

}

Body:
Try this

private fun initRemoteConfig() {
  remoteConfig = FirebaseRemoteConfig.getInstance()
  configSettings = FirebaseRemoteConfigSettings.Builder()
    .setMinimumFetchIntervalInSeconds(if (BuildConfig.DEBUG) 0 else 3600)
    .build()
  remoteConfig.setConfigSettingsAsync(configSettings)  //You missed this line
  remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
  fetch()
}

private fun fetch() {
  remoteConfig.fetchAndActivate()
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            val updated = task.result
            Logger.d(TAG, "Config params updated: $updated. Fetch and activate succeeded") // updated = false
            checkVersion()
        } else {
            Logger.d(TAG, "Fetch failed")
        }
    }
}


问:
Android EditText text control - how to disable possibility to insert GIF from Google Keyboard?
My app's target API is 27 (Oreo). My app uses EditText control for text input. However, from Google Keyboard it's now possible to insert GIF. In this case, my app receives ACTION_SEND intent, with gif inserted from a keyboard, which is implemented for completely different functionality. So it just messes entire app flow and takes the user to completely different activity.

I want my EditText to accept text only and don't allow users to insert any gif there. How can I configure EditText to stop allow inserting GIFS from keyboard?

答:
In the Activity that receives intent with action ACTION_SEND, add this in onCreate()

```<code> if (!isTaskRoot()) {
            Toast.makeText(context, "GIF is not allowed here", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
</code>```

So, when app is already open, isTaskRoot() returns false and Activity will be closed and app will be resumed from where it is left.

Body:
In the Activity that receives intent with action ACTION_SEND, add this in onCreate()

 if (!isTaskRoot()) {
            Toast.makeText(context, "GIF is not allowed here", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

So, when app is already open, isTaskRoot() returns false and Activity will be closed and app will be resumed from where it is left.


问:
ScopedModelDescendant raises NoSuchMethodError
Output Error:

```<code>The following NoSuchMethodError was thrown building ScopedModelDescendant<MainModel>(dirty, dependencies: [_InheritedModel<MainModel>]):
The getter 'sampleVariable' was called on null.
Receiver: null
Tried calling: sampleVariable
</code>```

Scenario:
I have multiple classes that extends Model chained to one main class (i.e. MainModel). Now, i've updated a variable within one of the classes that I have extended from the Model of "scoped model". When I tried to access that variable after navigated to another component it raises a "NoSuchMethodError" => The getter "variable" was called on null. Could that be a bug?

The one that populates the variable:

```<code>...
sampleVariable = 'NewData';
notifyListeners();
Navigator.pushNamed(context, 'newPage');
</code>```

newPage component tries to get the variable "sampleVariable":

```<code>...
ScopedModelDescendant<MainModel>(
          builder: (BuildContext context, Widget child, MainModel model) {
        print(model.sampleVariable);
...
}),
...
</code>```

And the wierd part is it prints the variable "sampleVariable" value when "Restart" button triggered from the vscode flutter actions.

答: Looks like I have a duplicate class object across the whole app. I fixed it by relying on just one class object of a single class that extends the Model of "Scoped Model".</p>

Body:
Output Error:

The following NoSuchMethodError was thrown building ScopedModelDescendant<MainModel>(dirty, dependencies: [_InheritedModel<MainModel>]):
The getter 'sampleVariable' was called on null.
Receiver: null
Tried calling: sampleVariable

Scenario:
I have multiple classes that extends Model chained to one main class (i.e. MainModel). Now, i've updated a variable within one of the classes that I have extended from the Model of "scoped model". When I tried to access that variable after navigated to another component it raises a "NoSuchMethodError" => The getter "variable" was called on null. Could that be a bug?

The one that populates the variable:

...
sampleVariable = 'NewData';
notifyListeners();
Navigator.pushNamed(context, 'newPage');

newPage component tries to get the variable "sampleVariable":

...
ScopedModelDescendant<MainModel>(
          builder: (BuildContext context, Widget child, MainModel model) {
        print(model.sampleVariable);
...
}),
...

And the wierd part is it prints the variable "sampleVariable" value when "Restart" button triggered from the vscode flutter actions.


问:
<Cucumber-JVM> pass values between steps in cucumber
How do I pass the values between two steps in cucumber JVM?

In the following scenario, I want to access username provided When step in Then step.
How do I pass the values between two steps in cucumber JVM? Currently I'm accessing those by saving that value into a public variable. Is the approach correct (or) any other way I can access those between the steps?

Scenario:

Given user is on login page
When user enters username as user1 and password as pass1
And clicked on login button
Then post login page is displayed

```<code>@When("^user enters username as ([^\"]*) and password as ([^\"]*)$")
public void enterLoginDetails(String username,String password){
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
}
</code>```

In the following step definition, I want to access username from the previous step definition

```<code>@Then("^post login page is displayed$")
public void postLoginValidation(){
// i would like access username and verify username is displayed
}
</code>```

Thanks in Advance

答:
Best Solution :

If you are using scenario outline:

```<code>When user enters username as <username> and password as <password>
Then post login page is displayed with <username>

Examples:

| username|password|
|Kiran|1234|
</code>```

Step Defination Code:

```<code>@When("user enters username as (.*) and password as (.*)")
public void enterLoginDetails(String userName,String password)
{
    //You will get userName=Kiran and Password=1234

}
@Then("post login page is displayed with (.*)")
public void postLoginValidation(String userName)
{
   //You will be access the same username which is you are passing while login
  ////You will get userName=Kiran
}
</code>```

Body:
How do I pass the values between two steps in cucumber JVM?

In the following scenario, I want to access username provided When step in Then step.
How do I pass the values between two steps in cucumber JVM? Currently I'm accessing those by saving that value into a public variable. Is the approach correct (or) any other way I can access those between the steps?

Scenario:

Given user is on login page
When user enters username as user1 and password as pass1
And clicked on login button
Then post login page is displayed

@When("^user enters username as ([^\"]*) and password as ([^\"]*)$")
public void enterLoginDetails(String username,String password){
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
}

In the following step definition, I want to access username from the previous step definition

@Then("^post login page is displayed$")
public void postLoginValidation(){
// i would like access username and verify username is displayed
}

Thanks in Advance

Body:
Best Solution :

If you are using scenario outline:

When user enters username as <username> and password as <password>
Then post login page is displayed with <username>

Examples:

| username|password|
|Kiran|1234|

Step Defination Code:

@When("user enters username as (.*) and password as (.*)")
public void enterLoginDetails(String userName,String password)
{
    //You will get userName=Kiran and Password=1234

}
@Then("post login page is displayed with (.*)")
public void postLoginValidation(String userName)
{
   //You will be access the same username which is you are passing while login
  ////You will get userName=Kiran
}


问:
How does App connect to multiple components and multi-level components?
I have seen a code sample, inside of the file App.js, setting up ComponentA:

```<code>let connectedComponent = connect(
    mapStateToProps,
    mapDispatchToProps
)(ComponentA);

export default connectedComponent;
</code>```

but what if App needs to use ComponentB as well -- how do you set it up?  What if ComponentB need to use ComponentC and also need to set it up?

答:
what if App needs to use ComponentB as well -- how do you set it up? What if ComponentB need to use ComponentC and also need to set it up?

If I get your question correct, componentB and componentC or/and componentN will be defined as child components of App.js.

Basically, connect() will link your component with the redux store so that whenever a change is detected in store each connected component will be notified with the change using mapStateToProps. Also, mutually exclusive components can be connected similarly with multiple connect().

Body:
I have seen a code sample, inside of the file App.js, setting up ComponentA:

let connectedComponent = connect(
    mapStateToProps,
    mapDispatchToProps
)(ComponentA);

export default connectedComponent;

but what if App needs to use ComponentB as well -- how do you set it up?  What if ComponentB need to use ComponentC and also need to set it up?


问:
React Native gradlew clean commant is not working
i just formatted my PC and reinstalled the envs for react native.

and after i built a empty project getting weird erros.
Than i tryed to run gradlew clean in android folder and even this code is not working.

答:
first be in the react native project directory the follow the commands one by one:

```<code>cd android
./gradlew clean
cd ..
npx react-native run-android
</code>```

tell me if it helps

Body:
first be in the react native project directory the follow the commands one by one:

cd android
./gradlew clean
cd ..
npx react-native run-android

tell me if it helps


问:
Python: Extract field values into new columns, write to Excel
I am reading a CSV file and intend to write to an Excel file.  The CSV file only has two columns, however I want to use regex to extract column data and create new columns, before writing to Excel.

CSV file: test.csv

```<code>name, file_info
test, c:\folder1\subfolder1\subfolder2\example.xls | history 12345 at 2020-01-01
</code>```

Here is the code I have so far:

```<code>import csv

with open('test.csv',mode='r') as testFile
     reader = csv.DictReader(testFile, delimiter=',')
     for row in reader:
          ### This is where i assume i need to perform the regex operation on the current row
</code>```

I want to extract the filename (example.xlsx), history (12345) and date (2020-01-01) as columns in an Excel file.

I have a tested regex successfully

```<code>"\\([^\\|]*)\s*\|\"
</code>```

I am sure there are multiple ways to do this.  Would Pandas be better?  I am able to simply read and write the file to excel by:

```<code>df = pd.read_csv('test.csv')
df.to_excel('text.xlsx)
</code>```

I don't have any experience with Pandas so not sure how to perform the operations I want with regex and tie it all together.

The end product is an excel spreadsheet with five (5) columns

name | path | file | history | date

答:
Here is a technique which uses Pandas df['column'].str.extract() function.

You can pass a compiled (or non-compiled) regex string into the extract() function.  This will use the named groups in the expression and extract those groups into columns by the same name.

Sample Data:

```<code>name,file_info
test1,c:\folder1\subfolder1\subfolder2\example1.xls | history 12345 at 2020-01-01
test2,c:\folder1\subfolder1\subfolder2\example2.xls | history 24687 at 2020-01-12
test3,c:\folder1\subfolder1\subfolder2\example3.xls | history 33445 at 2020-01-13
test4,c:\folder1\subfolder1\subfolder2\example4.xls | history 55664 at 2020-01-14
</code>```

The Code:

```<code>import os
import pandas as pd
import re

# Define constants
COLS = ['name', 'path', 'file', 'history', 'date']
PATH = './test.csv'
PATH_XL = './test.xlsx'
RE_EXP = re.compile(r'^'
                    '(?P<path>.*)\|\shistory\s'
                    '(?P<history>\d+)\sat\s'
                    '(?P<date>\d{4}-\d{2}-\d{2})$',
                    re.IGNORECASE)

# Read CSV file.
df = pd.read_csv(PATH)
# Create new columns using named regex groups.
df[['path', 'history', 'date']] = df['file_info'].str.extract(RE_EXP)
# Extract the filename from the path using a built-in function.
df['file'] = df['path'].apply(os.path.basename)
# Convert date to datetime format.
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d').dt.date
# Subset DataFrame to only the columns we require.
df = df[COLS]
# Write results to Excel.
df.to_excel(PATH_XL, index=False)
</code>```

Excel Output:

Body:
I am reading a CSV file and intend to write to an Excel file.  The CSV file only has two columns, however I want to use regex to extract column data and create new columns, before writing to Excel.

CSV file: test.csv

name, file_info
test, c:\folder1\subfolder1\subfolder2\example.xls | history 12345 at 2020-01-01

Here is the code I have so far:

import csv

with open('test.csv',mode='r') as testFile
     reader = csv.DictReader(testFile, delimiter=',')
     for row in reader:
          ### This is where i assume i need to perform the regex operation on the current row

I want to extract the filename (example.xlsx), history (12345) and date (2020-01-01) as columns in an Excel file.

I have a tested regex successfully

"\\([^\\|]*)\s*\|\"

I am sure there are multiple ways to do this.  Would Pandas be better?  I am able to simply read and write the file to excel by:

df = pd.read_csv('test.csv')
df.to_excel('text.xlsx)

I don't have any experience with Pandas so not sure how to perform the operations I want with regex and tie it all together.

The end product is an excel spreadsheet with five (5) columns

name | path | file | history | date

Body:
Here is a technique which uses Pandas df['column'].str.extract() function.

You can pass a compiled (or non-compiled) regex string into the extract() function.  This will use the named groups in the expression and extract those groups into columns by the same name.

Sample Data:

name,file_info
test1,c:\folder1\subfolder1\subfolder2\example1.xls | history 12345 at 2020-01-01
test2,c:\folder1\subfolder1\subfolder2\example2.xls | history 24687 at 2020-01-12
test3,c:\folder1\subfolder1\subfolder2\example3.xls | history 33445 at 2020-01-13
test4,c:\folder1\subfolder1\subfolder2\example4.xls | history 55664 at 2020-01-14

The Code:

import os
import pandas as pd
import re

# Define constants
COLS = ['name', 'path', 'file', 'history', 'date']
PATH = './test.csv'
PATH_XL = './test.xlsx'
RE_EXP = re.compile(r'^'
                    '(?P<path>.*)\|\shistory\s'
                    '(?P<history>\d+)\sat\s'
                    '(?P<date>\d{4}-\d{2}-\d{2})$',
                    re.IGNORECASE)

# Read CSV file.
df = pd.read_csv(PATH)
# Create new columns using named regex groups.
df[['path', 'history', 'date']] = df['file_info'].str.extract(RE_EXP)
# Extract the filename from the path using a built-in function.
df['file'] = df['path'].apply(os.path.basename)
# Convert date to datetime format.
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d').dt.date
# Subset DataFrame to only the columns we require.
df = df[COLS]
# Write results to Excel.
df.to_excel(PATH_XL, index=False)

Excel Output:


问:
.NET Core project with native library dependency
I am writing an app in .NET Core that depends on native code using [DllImport]. I have the native compiled library artifacts for win-x64, win-x86, and linux-x64.

My project structure is like:

```<code>MyApp
|--Main.cs
|--runtimes
   |--win-x86
      |--native
         |--somelibrary.dll
   |--win-x64
      |--native
         |--somelibrary.dll
   |--linux-x64
      |--native
         |--libsomelibrary.so
</code>```

I get then DLL not found exceptions when I run the app.

I have tried to use MSBuild targets solution here, but this only copies one dll to the main output folder at compile time. However, I want to the output to include all three native libraries in the output folder in the same structure as the runtimes folder above, and leave the selection of the compatible native library to .NET Core runtime host.

So if the user runs the app in Windows x86, it will use the win-x86, and so on.

I have noticed when I reference native wrappers like SkiaSharp from NuGet, it will actually integrate nicely into my app, and will include all assets in a runtimes folder structure to work on multiple environments at runtime. How can I do this?

Edit:

I ended up creating a nuget package for the native library binding, and reference the nuget in my other projects.

答:
This should copy your folder structure to the output folder, just put it right away under the first </PropertyGroup> in your MyApp.csproj:

<ItemGroup>
    <None Update="runtimes\**" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup>
```
<p>Just in case, there is a method to have more control on how you are loading the native libraries using <code>DllImport</code> by <code>DllImportResolver</code> delegate for your assembly.</p>
<pre class="lang-cs prettyprint-override"><code>public delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath);
</code>```

There is also NativeLibrary class which allows to set and load native libraries for .net core. Some sample code:

static class Sample
{
    const string NativeLib = "NativeLib";

    static Sample()
    {
        NativeLibrary.SetDllImportResolver(typeof(Sample).Assembly, ImportResolver);
    }

    private static IntPtr ImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
    {
        IntPtr libHandle = IntPtr.Zero;
        //you can add here different loading logic
        if (libraryName == NativeLib && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.Is64BitProcess)
        {
            NativeLibrary.TryLoad("./runtimes/win-x64/native/somelib.dll", out libHandle);
        } else
        if (libraryName == NativeLib)
        {
            NativeLibrary.TryLoad("libsomelibrary.so", assembly, DllImportSearchPath.ApplicationDirectory, out libHandle);
        }
        return libHandle;
    }

    [DllImport(NativeLib)]
    public static extern int DoSomework();
}
```

Body:
I am writing an app in .NET Core that depends on native code using [DllImport]. I have the native compiled library artifacts for win-x64, win-x86, and linux-x64.

My project structure is like:

MyApp
|--Main.cs
|--runtimes
   |--win-x86
      |--native
         |--somelibrary.dll
   |--win-x64
      |--native
         |--somelibrary.dll
   |--linux-x64
      |--native
         |--libsomelibrary.so

I get then DLL not found exceptions when I run the app.

I have tried to use MSBuild targets solution here, but this only copies one dll to the main output folder at compile time. However, I want to the output to include all three native libraries in the output folder in the same structure as the runtimes folder above, and leave the selection of the compatible native library to .NET Core runtime host.

So if the user runs the app in Windows x86, it will use the win-x86, and so on.

I have noticed when I reference native wrappers like SkiaSharp from NuGet, it will actually integrate nicely into my app, and will include all assets in a runtimes folder structure to work on multiple environments at runtime. How can I do this?

Edit:

I ended up creating a nuget package for the native library binding, and reference the nuget in my other projects.

Body:
This should copy your folder structure to the output folder, just put it right away under the first </PropertyGroup> in your MyApp.csproj:

<ItemGroup>
    <None Update="runtimes\**" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup>

Just in case, there is a method to have more control on how you are loading the native libraries using DllImport by DllImportResolver delegate for your assembly.

public delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath);

There is also NativeLibrary class which allows to set and load native libraries for .net core. Some sample code:

static class Sample
{
    const string NativeLib = "NativeLib";

    static Sample()
    {
        NativeLibrary.SetDllImportResolver(typeof(Sample).Assembly, ImportResolver);
    }

    private static IntPtr ImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
    {
        IntPtr libHandle = IntPtr.Zero;
        //you can add here different loading logic
        if (libraryName == NativeLib && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.Is64BitProcess)
        {
            NativeLibrary.TryLoad("./runtimes/win-x64/native/somelib.dll", out libHandle);
        } else
        if (libraryName == NativeLib)
        {
            NativeLibrary.TryLoad("libsomelibrary.so", assembly, DllImportSearchPath.ApplicationDirectory, out libHandle);
        }
        return libHandle;
    }

    [DllImport(NativeLib)]
    public static extern int DoSomework();
}


问:
GetKeyState function not working when checking if left mouse button is clicked
I am trying to see if the left mouse button is clicked and if it is it will output You clicked I have this piece of code which will work the first time you click. After that though, I have to right click and then left click in order for it to work again. If I just left click nothing will happen. Why is this?

```<code>#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    while (true)
    {
        if (GetKeyState(VK_LBUTTON) < 0) {
            cout << "clicked" << endl;
        }
    }

}
</code>```

答:
After that though, I have to right click and then left click in order
  for it to work again. If I just left click nothing will happen. Why is
  this?

Yes, I can reproduce this issue when click on client area of the console window.

There is a console edit mode misleading us. When you click on client area of the console window, cause it enter edit mode and program stops. To solve this issue you can uncheck the "Quick Edit Mode" option (You can find it via click icon at left top of the console window then select Properties -> Options -> Edit Options), or click on title bar of the console window instead of on client area.

Please check if it is your situation.

Body:
I am trying to see if the left mouse button is clicked and if it is it will output You clicked I have this piece of code which will work the first time you click. After that though, I have to right click and then left click in order for it to work again. If I just left click nothing will happen. Why is this?

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    while (true)
    {
        if (GetKeyState(VK_LBUTTON) < 0) {
            cout << "clicked" << endl;
        }
    }

}


问:
How to add shared and local parameter in same test case in Azure Test Plans?
While creating test cases in Azure Test Plan, I want to add shared as well as local parameter for test data.
Currently when I add shared parameters, it is not allowing to add value to local parameters.

Created shared parameters and added to test case.
Created local parameter and try to add value for that parameter.

If we add local parameter first and then click on Add a shared parameters set, message "Changing local parameters to shared parameters deletes any local parameter values. Do you want to continue?" displayed.

If we add shared parameter first and then try to add local parameter then it is now allowing to assign value for that local parameter.

答:
In Azure Test Plans.

Go to any test plan and create a New Test Case OR Directly Click on New Test Case Button.

After clicking on new test case , you will be taken to new window.
In Steps Field, You will be having 2nd icon insert shared parameter
Choose any shared parameter set among the list and Click on Insert Shared Parameter Button.

Now in the steps field ,first step will be the name of shared parameter in bold format.
In that second step you can add you own step (i.e Local Parameter)
Shown Below


问:
ViewResult or ActionResult | does it makes sense to use ViewResult if ActionResult is good for everything anyways?
In asp.net mvc there is ViewResult for returning a View and ActionResult for returning whatever you want, so is there some good reason why should I use ViewResult instead of ActionResult when I'm sure that I will return a View ?</p>

答: If you want to do unit testing then change it in the controller from ActionResult to ViewResult.  Then you will have the intellisense in your Test Controller and life is good.  </p>


问:
open serialport and log data automatically under various events
I am using a COM3 port and iam using the serialport module to read from the serialport. What I want is an automatic logging system which logs the data from serialport under the following events.

1.close program and reopening the program

2.restart my pc

3.unplug the usb cable and plug it again

4.restart the Arduino device

I want to open the serialport and log data received from it automatically whenever the above events occur. How to handle these cases.

Currently, this is the code iam using

```<code>var fs = require('fs');

const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
const port = new SerialPort('COM3')
const parser = new Readline()
port.pipe(parser)
parser.on('data', function (data) {

 const index = data.indexOf('*#SENSOR_DATA')

 if(index != -1){

    fs.appendFileSync("sensor_data.txt", new Date(), 'utf8')
    fs.appendFileSync("sensor_data.txt", data, 'utf8')

 }

})

port.on('error', function(err) {
    fs.appendFileSync("sensor_data.txt", new Date(), 'utf8')
    fs.appendFileSync("sensor_data.txt", err, 'utf8')
    console.log(err);
})

port.write('ROBOT PLEASE RESPOND\n')

</code>```

How can I handle the above mentioned cases?

答:
close program and reopening the program

Logging the data from the port on starting of the program, should be straight forward, i.e. the running of your script.

Closing of the program, depends on what you scenarios you want to handle, graceful or non graceful exits of the program. To implement this you can add event listeners on the nodeJS process object. You can register event handlers for when the process is going to exit to do some action.

```<code>process.on('SIGINT', () => {
    // read my data from Serial
    process.exit(-1);
})
</code>```

restart my pc

Depending on what your OS is, you could configure your nodejs process as a service, or you could run it via cron. For example cron (depending on the OS) has the option for scheduling jobs on reboot. Regardless of your OS, you will be able to schedule jobs or create a service to ensure your process starts when your machine restarts.

unplug the usb cable and plug it again &
restart the Arduino device

For this I would look at the different parsers that are available for serialport. For example the ReadyParser.

Body:
I am using a COM3 port and iam using the serialport module to read from the serialport. What I want is an automatic logging system which logs the data from serialport under the following events.

1.close program and reopening the program

2.restart my pc

3.unplug the usb cable and plug it again

4.restart the Arduino device

I want to open the serialport and log data received from it automatically whenever the above events occur. How to handle these cases.

Currently, this is the code iam using

var fs = require('fs');

const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
const port = new SerialPort('COM3')
const parser = new Readline()
port.pipe(parser)
parser.on('data', function (data) {

 const index = data.indexOf('*#SENSOR_DATA')

 if(index != -1){

    fs.appendFileSync("sensor_data.txt", new Date(), 'utf8')
    fs.appendFileSync("sensor_data.txt", data, 'utf8')

 }

})

port.on('error', function(err) {
    fs.appendFileSync("sensor_data.txt", new Date(), 'utf8')
    fs.appendFileSync("sensor_data.txt", err, 'utf8')
    console.log(err);
})

port.write('ROBOT PLEASE RESPOND\n')

How can I handle the above mentioned cases?

Body:
close program and reopening the program

Logging the data from the port on starting of the program, should be straight forward, i.e. the running of your script.

Closing of the program, depends on what you scenarios you want to handle, graceful or non graceful exits of the program. To implement this you can add event listeners on the nodeJS process object. You can register event handlers for when the process is going to exit to do some action.

process.on('SIGINT', () => {
    // read my data from Serial
    process.exit(-1);
})

restart my pc

Depending on what your OS is, you could configure your nodejs process as a service, or you could run it via cron. For example cron (depending on the OS) has the option for scheduling jobs on reboot. Regardless of your OS, you will be able to schedule jobs or create a service to ensure your process starts when your machine restarts.

unplug the usb cable and plug it again &
restart the Arduino device

For this I would look at the different parsers that are available for serialport. For example the ReadyParser.


问:
How to rollback when error occurred in the second query execution| NodeJS
I used to use rollback in PHP, I want to implement the same concept in NodeJS. I am calling a function that inserts a data to the database, and on success I am calling another function from another Model to insert data into another table.

My Code

StoreReport

```<code>'use strict';

var sql = require('./db.js');

// IMPORT ANOTHER MODEL
var CashDetailModel = require('./cashDetailModel.js');

var StoreReport =function(storeReport){
    this.store_id=storeReport.store_id;
    this.cash_expense=storeReport.cash_expense_amount;

}

StoreReport.addNewStoreReport = function (report_details,request,result){

    sql.query('INSERT INTO store_report SET ?',report_details, function(err,res){
        if(err){
            result(err,null);
        }else{
            var new_cash_detail = new CashDetailModel(report_details);
            new_cash_detail.store_report_id=res.insertId;
            CashDetailModel.addCashDetail(new_cash_detail,function(err,CashDetailModel){
                if(err){

                  // I NEED TO ROLLBACK IF ERROR OCCURED IN THIS PHASE
                    res.send(err);
                }else{
                    result(null,res.inserted);
                }
            })
        }
    })
}

module.exports = StoreReport;
</code>```

答:
It depends on which mysql engine you are using, transnational engines like innodb considers each query as separate transaction if you are explicitly not defining the transaction.

So in order to revert the change you have two options :

Revert changes using update or delete query, which is a wrong approch.

Explicitly define transaction using connection.beginTransaction() and commit or rollback accordingly.

Body:
I used to use rollback in PHP, I want to implement the same concept in NodeJS. I am calling a function that inserts a data to the database, and on success I am calling another function from another Model to insert data into another table.

My Code

StoreReport

'use strict';

var sql = require('./db.js');

// IMPORT ANOTHER MODEL
var CashDetailModel = require('./cashDetailModel.js');

var StoreReport =function(storeReport){
    this.store_id=storeReport.store_id;
    this.cash_expense=storeReport.cash_expense_amount;

}

StoreReport.addNewStoreReport = function (report_details,request,result){

    sql.query('INSERT INTO store_report SET ?',report_details, function(err,res){
        if(err){
            result(err,null);
        }else{
            var new_cash_detail = new CashDetailModel(report_details);
            new_cash_detail.store_report_id=res.insertId;
            CashDetailModel.addCashDetail(new_cash_detail,function(err,CashDetailModel){
                if(err){

                  // I NEED TO ROLLBACK IF ERROR OCCURED IN THIS PHASE
                    res.send(err);
                }else{
                    result(null,res.inserted);
                }
            })
        }
    })
}

module.exports = StoreReport;


问:
Does Google AutoML Vision normalize images?
I would expect normalization to be done according to best practices, but there's no documentation on that. </p>

<p>According to this answer, AutoML does augmentation behind the scenes, but there's no documentation on that. </p>

答: As per the official documentation the suggested maximum is 1024 pixels by 1024 pixels. Images much larger than 1024 pixels by 1024 pixels there may be some image quality loss during AutoML Vision Object Detection's image normalization process. Please review Preparing your training data</p>

Body:
I would expect normalization to be done according to best practices, but there's no documentation on that.

According to this answer, AutoML does augmentation behind the scenes, but there's no documentation on that.


问:
mysql grant permissions on all but system tables
I am trying to grant a set of permissions to " all databases all tables" . excepted mysql system databases (mysql,information_schema,performance_schema, and sys (I believed I named them all?)).

I am not sure how to do that.

I need for instance a GRANT SELECT ON . excepted system tables.

答:
Use:

SELECT CONCAT("GRANT ALL PRIVILEGES ON ",SCHEMA_NAME,".* TO 'test_user'@'localhost';") FROM information_schema.SCHEMATA WHERE SCHEMA_NAME NOT IN ('mysql','information_schema',
'performance_schema','sys')

This will provide you queries for individual databases that you can use to grant the privileges to a particular user.

After that, use:

FLUSH PRIVILEGES;

I hope this helps!


问:
Listen to certain values changed on Class
i would like to run a method, every time certain values are changed on a object.

I was wondering if i could create a Custom attribute to add to the values i want to trigger my method, when their value is changed.

Fx:

```<code>public class Program
{
    public static void Main()
    {
        A a = new A("Hello", true);
        a.text = "Goodbye";
        a.check = false;
    }
}
public class A{
   public string text {get; set;}
   [RunMyMethod]
   public bool check {get; set;}

   public A(string t, bool c){
       this.text = t;
       this.check = c;
   }
}

public class RunMyMethod : System.Attribute
{
}
</code>```

I am aware of the fact that i simply just go add something to every fields Set method, but the class i want to implement this on, is rather huge, and it wouldn't be pretty.

答:
This is why we have field for!

So, first of all, change

```<code>public bool check {get; set;}
</code>```

to

```<code>private bool _check;
</code>```

And define Property for setting this value:

```<code>public bool Check
{
  get { return _check; }
  set
  {
    // here you can add your logic,
    // If this logic is common for every field, you
    // can wrap it in method and call it here.
    // Also here you can use variable named "value", which holds
    // value to be set.
    // At the end, set the value:
    _check = value;
  }
}
</code>```

Body:
i would like to run a method, every time certain values are changed on a object.

I was wondering if i could create a Custom attribute to add to the values i want to trigger my method, when their value is changed.

Fx:

public class Program
{
    public static void Main()
    {
        A a = new A("Hello", true);
        a.text = "Goodbye";
        a.check = false;
    }
}
public class A{
   public string text {get; set;}
   [RunMyMethod]
   public bool check {get; set;}

   public A(string t, bool c){
       this.text = t;
       this.check = c;
   }
}

public class RunMyMethod : System.Attribute
{
}

I am aware of the fact that i simply just go add something to every fields Set method, but the class i want to implement this on, is rather huge, and it wouldn't be pretty.

Body:
This is why we have field for!

So, first of all, change

public bool check {get; set;}

to

private bool _check;

And define Property for setting this value:

public bool Check
{
  get { return _check; }
  set
  {
    // here you can add your logic,
    // If this logic is common for every field, you
    // can wrap it in method and call it here.
    // Also here you can use variable named "value", which holds
    // value to be set.
    // At the end, set the value:
    _check = value;
  }
}