问:
Why does pushing to private, secured docker registry fail?
I would like to run a private, secure, authenticated docker registry on a self healing AWS ECS cluster. The cluster setup is done and works properly, but I struggled getting the registry:latest running. The problem was, that every time I push an image, pushing the blobs fails, and goes into a retry cycle unless I get a timeout.

To make sure, that my ECS setup isn’t the blocker, I tried to setup everything locally using Docker4Mac 1.12.0-a.

First, the very basic setup works. I created my own version of the registry image, where there I put my TLS certificate bundle and key as well as the necessary htpasswd file directly into the image. [I know, this is insecure, I just do that for the testing purpose]. So here is my Dockerfile:

```<code>FROM registry:latest

COPY htpasswd /etc/docker
COPY server_bundle.pem /etc/docker
COPY server_key.pem /etc/docker
</code>```

server_bundle.pem has a wildcard certificate for my domain mydomain.com (CN=*.mydomain.com) as the first one, followed by the intermediate CA certificates, so clients should be happy. My htpasswd file was created using the recommended approach:

```<code>docker run --entrypoint htpasswd registry:2 -Bbn heyitsme mysupersecurepassword > htpasswd
</code>```

I build my image:

```<code>docker build -t heyitsme/registry .
</code>```

and afterwards I run a very basic version w/o TLS and authentication:

```<code>docker run --restart=always -p 5000:5000 heyitsme/registry
</code>```

and I can actually pull, tag and re-push an image:

```<code>docker pull alpine
docker tag alpine localhost:5000/alpine
docker push localhost:5000/alpine
</code>```

This works. Next I make TLS and basic auth work via environment variables:

```<code>docker run -h registry.mydomain.com --name registry --restart=always -p 5000:5000 \
  -e REGISTRY_HTTP_HOST=http://registry.mydomain.com:5000 \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/etc/docker/server_bundle.pem \
  -e REGISTRY_HTTP_TLS_KEY=/etc/docker/server_key.pem \
  -e REGISTRY_AUTH=htpasswd \
  -e REGISTRY_AUTH_HTPASSWD_REALM=Registry-Realm \
  -e REGISTRY_AUTH_HTPASSWD_PATH=/etc/docker/htpasswd heyitsme/registry
</code>```

For the time being I create an entry in /etc/hosts which says:

```<code>127.0.0.1 registry.mydomain.com
</code>```

And then I login:

```<code>docker login registry.mydomain.com:5000
Username: heyitsme
Password: ***********
Login Succeeded
</code>```

So now, let’s tag and push the image here:

```<code>docker tag alpine registry.mydomain.com:5000/alpine
docker push registry.mydomain.com:5000/alpine

The push refers to a repository [registry.mydomain.com:5000/alpine]
4fe15f8d0ae6: Retrying in 4 seconds
</code>```

What happens is, that the docker clients tries to push fragments and fails. Then it retries and fails again until I get a timeout. So next check, whether the V2 API works properly:

```<code>curl -i -XGET https://registry.mydomain.com:5000/v2/
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
Www-Authenticate: Basic realm="Registry-Realm"
X-Content-Type-Options: nosniff
Date: Thu, 15 Sep 2016 10:06:04 GMT
Content-Length: 87

{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
</code>```

Ok, as expected. So let’s authenticate next time:

```<code>curl -i -XGET https://heyitsme:mysupersecretpassword@registry.mydomain.com:5000/v2/
HTTP/1.1 200 OK
Content-Length: 2
Content-Type: application/json; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
X-Content-Type-Options: nosniff
Date: Thu, 15 Sep 2016 10:06:16 GMT

{}%
</code>```

Works. But pushing still fails.

The logs say:

```<code>time="2016-09-15T10:24:34Z" level=warning msg="error authorizing context: basic authentication challenge for realm \"Registry-Realm\": invalid authorization credential" go.version=go1.6.3 http.request.host="registry.mydomain.com:5000" http.request.id=6d2ec080-6824-4bf7-aac2-5af31db44877 http.request.method=GET http.request.remoteaddr="172.17.0.1:40878" http.request.uri="/v2/" http.request.useragent="docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))" instance.id=be3a8877-de64-4574-b47a-70ab036e7b79 version=v2.5.1
172.17.0.1 - - [15/Sep/2016:10:24:34 +0000] "GET /v2/ HTTP/1.1" 401 87 "" "docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))"
time="2016-09-15T10:24:34Z" level=info msg="response completed" go.version=go1.6.3 http.request.host="registry.mydomain.com:5000" http.request.id=8f81b455-d592-431d-b67d-0bc34155ddbf http.request.method=POST http.request.remoteaddr="172.17.0.1:40882" http.request.uri="/v2/alpine/blobs/uploads/" http.request.useragent="docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))" http.response.duration=30.515131ms http.response.status=202 http.response.written=0 instance.id=be3a8877-de64-4574-b47a-70ab036e7b79 version=v2.5.1
172.17.0.1 - - [15/Sep/2016:10:24:34 +0000] "POST /v2/alpine/blobs/uploads/ HTTP/1.1" 202 0 "" "docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))"
2016/09/15 10:24:34 http: TLS handshake error from 172.17.0.1:40886: tls: first record does not look like a TLS handshake
</code>```

I also tested different versions of the original registry image, especially several versions above 2. All yield the same error. If someone could help me on that issue, that would be awesome.

答:
Thanks a lot, it's working now!

I added the variable in my kubernetes deployment manifest:

```<code>(...)
      - env:
        - name: REGISTRY_STORAGE_DELETE_ENABLED
          value: "true"
        - name: REGISTRY_HTTP_HOST
          value: "https://registry.k8sprod.acme.domain:443"
(...)
</code>```

For those who use nginx ingress in front, you have to set extra attribute in your ingress manifest file if you have push size errors:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-registry
  namespace: default
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-body-size: "8192m"
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-next-upstream-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-next-upstream-tries: "10"
    nginx.ingress.kubernetes.io/proxy-request-buffering: "off"
  labels:
    k8s-app: kube-registry
    app: kube-registry
spec:
  rules:
    - host: registry.k8sprod.acme.domain
      http:
        paths:
        - path: /
          backend:
            serviceName: svc-kube-registry
            servicePort: 5000

</code>```

Body:
I would like to run a private, secure, authenticated docker registry on a self healing AWS ECS cluster. The cluster setup is done and works properly, but I struggled getting the registry:latest running. The problem was, that every time I push an image, pushing the blobs fails, and goes into a retry cycle unless I get a timeout.

To make sure, that my ECS setup isn’t the blocker, I tried to setup everything locally using Docker4Mac 1.12.0-a.

First, the very basic setup works. I created my own version of the registry image, where there I put my TLS certificate bundle and key as well as the necessary htpasswd file directly into the image. [I know, this is insecure, I just do that for the testing purpose]. So here is my Dockerfile:

FROM registry:latest

COPY htpasswd /etc/docker
COPY server_bundle.pem /etc/docker
COPY server_key.pem /etc/docker

server_bundle.pem has a wildcard certificate for my domain mydomain.com (CN=*.mydomain.com) as the first one, followed by the intermediate CA certificates, so clients should be happy. My htpasswd file was created using the recommended approach:

docker run --entrypoint htpasswd registry:2 -Bbn heyitsme mysupersecurepassword > htpasswd

I build my image:

docker build -t heyitsme/registry .

and afterwards I run a very basic version w/o TLS and authentication:

docker run --restart=always -p 5000:5000 heyitsme/registry

and I can actually pull, tag and re-push an image:

docker pull alpine
docker tag alpine localhost:5000/alpine
docker push localhost:5000/alpine

This works. Next I make TLS and basic auth work via environment variables:

docker run -h registry.mydomain.com --name registry --restart=always -p 5000:5000 \
  -e REGISTRY_HTTP_HOST=http://registry.mydomain.com:5000 \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/etc/docker/server_bundle.pem \
  -e REGISTRY_HTTP_TLS_KEY=/etc/docker/server_key.pem \
  -e REGISTRY_AUTH=htpasswd \
  -e REGISTRY_AUTH_HTPASSWD_REALM=Registry-Realm \
  -e REGISTRY_AUTH_HTPASSWD_PATH=/etc/docker/htpasswd heyitsme/registry

For the time being I create an entry in /etc/hosts which says:

127.0.0.1 registry.mydomain.com

And then I login:

docker login registry.mydomain.com:5000
Username: heyitsme
Password: ***********
Login Succeeded

So now, let’s tag and push the image here:

docker tag alpine registry.mydomain.com:5000/alpine
docker push registry.mydomain.com:5000/alpine

The push refers to a repository [registry.mydomain.com:5000/alpine]
4fe15f8d0ae6: Retrying in 4 seconds

What happens is, that the docker clients tries to push fragments and fails. Then it retries and fails again until I get a timeout. So next check, whether the V2 API works properly:

curl -i -XGET https://registry.mydomain.com:5000/v2/
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
Www-Authenticate: Basic realm="Registry-Realm"
X-Content-Type-Options: nosniff
Date: Thu, 15 Sep 2016 10:06:04 GMT
Content-Length: 87

{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}

Ok, as expected. So let’s authenticate next time:

curl -i -XGET https://heyitsme:mysupersecretpassword@registry.mydomain.com:5000/v2/
HTTP/1.1 200 OK
Content-Length: 2
Content-Type: application/json; charset=utf-8
Docker-Distribution-Api-Version: registry/2.0
X-Content-Type-Options: nosniff
Date: Thu, 15 Sep 2016 10:06:16 GMT

{}%

Works. But pushing still fails.

The logs say:

time="2016-09-15T10:24:34Z" level=warning msg="error authorizing context: basic authentication challenge for realm \"Registry-Realm\": invalid authorization credential" go.version=go1.6.3 http.request.host="registry.mydomain.com:5000" http.request.id=6d2ec080-6824-4bf7-aac2-5af31db44877 http.request.method=GET http.request.remoteaddr="172.17.0.1:40878" http.request.uri="/v2/" http.request.useragent="docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))" instance.id=be3a8877-de64-4574-b47a-70ab036e7b79 version=v2.5.1
172.17.0.1 - - [15/Sep/2016:10:24:34 +0000] "GET /v2/ HTTP/1.1" 401 87 "" "docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))"
time="2016-09-15T10:24:34Z" level=info msg="response completed" go.version=go1.6.3 http.request.host="registry.mydomain.com:5000" http.request.id=8f81b455-d592-431d-b67d-0bc34155ddbf http.request.method=POST http.request.remoteaddr="172.17.0.1:40882" http.request.uri="/v2/alpine/blobs/uploads/" http.request.useragent="docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))" http.response.duration=30.515131ms http.response.status=202 http.response.written=0 instance.id=be3a8877-de64-4574-b47a-70ab036e7b79 version=v2.5.1
172.17.0.1 - - [15/Sep/2016:10:24:34 +0000] "POST /v2/alpine/blobs/uploads/ HTTP/1.1" 202 0 "" "docker/1.12.0 go/go1.6.3 git-commit/8eab29e kernel/4.4.15-moby os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.0 \\(darwin\\))"
2016/09/15 10:24:34 http: TLS handshake error from 172.17.0.1:40886: tls: first record does not look like a TLS handshake

I also tested different versions of the original registry image, especially several versions above 2. All yield the same error. If someone could help me on that issue, that would be awesome.

Body:
Thanks a lot, it's working now!

I added the variable in my kubernetes deployment manifest:

(...)
      - env:
        - name: REGISTRY_STORAGE_DELETE_ENABLED
          value: "true"
        - name: REGISTRY_HTTP_HOST
          value: "https://registry.k8sprod.acme.domain:443"
(...)

For those who use nginx ingress in front, you have to set extra attribute in your ingress manifest file if you have push size errors:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-registry
  namespace: default
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-body-size: "8192m"
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-next-upstream-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-next-upstream-tries: "10"
    nginx.ingress.kubernetes.io/proxy-request-buffering: "off"
  labels:
    k8s-app: kube-registry
    app: kube-registry
spec:
  rules:
    - host: registry.k8sprod.acme.domain
      http:
        paths:
        - path: /
          backend:
            serviceName: svc-kube-registry
            servicePort: 5000


来源: stackexchange

问:
Why does Stream.reduce take BinaryOperator<T> rather than BiFunction<T, T, T>?
For my specific case I want to use functional composition in a reduction; for example:

```<code>BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());
</code>```

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator
```

<p>Instead, I need to do:</p>

```ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());
```

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

答:
I don't think there is likely to be a satisfying answer to your actual question; the only benefit I can think of for taking the stricter type BinaryOperator<T> as an argument is readability, but that may or may not have been on the minds of the API designers. We will probably never know what the rationale for the decision was unless one of the people who made the decision writes an answer.

That said, in your particular case it seems like the Sets.SetView::immutableCopy function is unnecessary inside the reduction, because the Sets::intersection function doesn't require its arguments to be of type ImmutableSet<E>, so long as we specify that the stream values are the weaker type Set<E>. So the following should be logically equivalent:

ImmutableSet<Integer> intersection =
  Stream.<Set<Integer>>of(/* the sets */)
        .reduce(Sets::intersection)
        .map(ImmutableSet::copyOf)
        .orElse(ImmutableSet.of());
```

There may be performance differences due to the fact that Sets::intersection returns a view, without doing any copying. If the intersections are likely to be large relative to the original sets, and the number of sets is not large, then this version should be more efficient due to doing less memory allocation and copying. Otherwise if the intersections are likely to be small, or the number of sets is large, then the copying could be beneficial since it's faster to iterate over a smaller set than a view of the intersection of two large sets.

That said, in the second case I would recommend writing this in the imperative style with a for loop, so you can stop early if the accumulator is already empty.

ContentLicense: CC BY-SA 4.0

Body:
For my specific case I want to use functional composition in a reduction; for example:

BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator

Instead, I need to do:

ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

Body:
I don't think there is likely to be a satisfying answer to your actual question; the only benefit I can think of for taking the stricter type BinaryOperator<T> as an argument is readability, but that may or may not have been on the minds of the API designers. We will probably never know what the rationale for the decision was unless one of the people who made the decision writes an answer.

That said, in your particular case it seems like the Sets.SetView::immutableCopy function is unnecessary inside the reduction, because the Sets::intersection function doesn't require its arguments to be of type ImmutableSet<E>, so long as we specify that the stream values are the weaker type Set<E>. So the following should be logically equivalent:

ImmutableSet<Integer> intersection =
  Stream.<Set<Integer>>of(/* the sets */)
        .reduce(Sets::intersection)
        .map(ImmutableSet::copyOf)
        .orElse(ImmutableSet.of());

There may be performance differences due to the fact that Sets::intersection returns a view, without doing any copying. If the intersections are likely to be large relative to the original sets, and the number of sets is not large, then this version should be more efficient due to doing less memory allocation and copying. Otherwise if the intersections are likely to be small, or the number of sets is large, then the copying could be beneficial since it's faster to iterate over a smaller set than a view of the intersection of two large sets.

That said, in the second case I would recommend writing this in the imperative style with a for loop, so you can stop early if the accumulator is already empty.


问:
is it possible to add a link in google's datatable?
is it possible to add a link in google's datatable?

http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable, http://code.google.com/apis/chart/interactive/docs/examples.html#table_example

答:
yes, it is possible. Google's DataTable has a property: allowHtml:

```<code>table.draw(data, {showRowNumber: true, allowHtml: true});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
yes, it is possible. Google's DataTable has a property: allowHtml:

table.draw(data, {showRowNumber: true, allowHtml: true});


问:
Make Thymeleaf th:field consume Lombok-generated boolean getter
I'm creating a simple Spring MVC app with Thymeleaf. Being lazy, I'm using Lombok as well. I have a simple DTO, passing to and from Thymeleaf:

```<code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TypeDto {

    private Long id;
    private String title;
    private boolean isActive;
}
</code>```

but I'm getting the following error trying to access page:
Bean property 'isActive' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? It's failing in the following Thymeleaf snippet:

```<code>    <td><input type="checkbox" th:field="*{isActive}"/></td>
</code>```

If I'd rename isActive to active in both DTO and Thymeleaf template it works fine, so my guess Thymeleaf is trying to read property with getIsActive, which OFC doesn't exist. As much as I'm up for simple solutions, is there a way to leave boolean as isActive and still make Thymeleaf work?

答: While typing this question, I've found out that if I change property matcher in Thymeleaf template itself to active, everything works as expected and no need to change anything on DTO level and below.

Body:
I'm creating a simple Spring MVC app with Thymeleaf. Being lazy, I'm using Lombok as well. I have a simple DTO, passing to and from Thymeleaf:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TypeDto {

    private Long id;
    private String title;
    private boolean isActive;
}

but I'm getting the following error trying to access page:
Bean property 'isActive' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? It's failing in the following Thymeleaf snippet:

    <input type="checkbox" th:field="*{isActive}"/>

If I'd rename isActive to active in both DTO and Thymeleaf template it works fine, so my guess Thymeleaf is trying to read property with getIsActive, which OFC doesn't exist. As much as I'm up for simple solutions, is there a way to leave boolean as isActive and still make Thymeleaf work?


问:
How do we add an event in C++/WinRt project?
I am currently work on a C++/WinRt which connects(Sender) to one of the available devices(Client) around a specific region using WifiDirect. When the device wants to connect, it sends a connection request to the sender. The sender needs to detect the connection request sent by the client and connect to the client. For this I need to add an event - (On Connection requested). As soon as I add it should execute the code of OnConnectionRequested.

#include "pch.h"
#include <winrt/Windows.Foundation.Collections.h>
#include "winrt/Windows.Devices.WiFiDirect.h"
#pragma once
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::WiFiDirect;
using namespace Windows::Storage::Streams;
using namespace winrt::Windows::Devices::WiFiDirect;
using namespace winrt::Windows::Devices::Enumeration;
```
<pre class="lang-cpp prettyprint-override"><code>enum class NotifyType
{
    StatusMessage,
    ErrorMessage
};
</code>```

enum class CallbackContext
{
    Any,
    Same
};
```
<pre class="lang-cpp prettyprint-override"><code>class st
{
public:
    void OnConnectionRequested(WiFiDirectConnectionListener sender,
                               WiFiDirectConnectionRequestedEventArgsconnection EventArgs)
    {
        WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
        printf("Connection request received from ", connectionRequest.DeviceInformation().Name(), "Connection Request");
        printf("Connecting to ", connectionRequest.DeviceInformation().Name(), NotifyType::StatusMessage);
    }

    void start()
    {
        Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher _publisher;
        Windows::Devices::WiFiDirect::WiFiDirectConnectionListener _listener;
        winrt::event_token _connectionRequestedToken;

        try
        {
            _connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
            _publisher.Start();
            printf("Advertisement started, waiting for StatusChangedcallback...", NotifyType::StatusMessage);
        }
        catch (...)
        {
            printf("Error starting Advertisement: ", NotifyType::ErrorMessage);
        }

        getchar();
    }
};
</code>```

int main()
{
    st s;
    s.start();
}
```
<p>Is this the right way to add an event in C++/WinRt :</p>
```_connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
```

The errors are :

LNK1120 1 unresolved externals   - error in Winrt.exe file

LNK2019
unresolved external symbol "public: struct winrt::hstring __thiscall
winrt::impl::consume_Windows_Devices_Enumeration_IDeviceInformation::Name(void)const
"
(?Name@?$consume_Windows_Devices_Enumeration_IDeviceInformation@UIDeviceInformation@Enumeration@Devices@Windows@winrt@@@impl@winrt@@QBE?AUhstring@3@XZ)
referenced in function "public: void __thiscall
st::OnConnectionRequested(struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionListener,struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionRequestedEventArgs)"
(?OnConnectionRequested@st@@QAEXUWiFiDirectConnectionListener@WiFiDirect@Devices@Windows@winrt@@UWiFiDirectConnectionRequestedEventArgs@3456@@Z) - error in Program.obj 1

What changes should I make at this line to clear the error? What does the error actually mean ? Or is there any other way to add an event in C++/WinRt project?

答:
You are missing an #include directive:

#include <winrt/Windows.Devices.Enumeration.h>
```

See Why is the linker giving me a "LNK2019: Unresolved external symbol" error?:

If the unresolved symbol is an API from the Windows namespace headers for the C++/WinRT projection (in the winrt namespace), then the API is forward-declared in a header that you've included, but its definition is in a header that you haven't yet included. Include the header named for the API's namespace, and rebuild. For more info, see C++/WinRT projection headers.

For general instructions on how to handle events see Handle events by using delegates in C++/WinRT.

Capturing this (raw pointer) into the delegate might be dangerous, too. This breaks the link between object lifetime and visibility, and puts the burden of lifetime management on you. See Safely accessing the this pointer with an event-handling delegate for safer, more manageable alternatives.

Body:
I am currently work on a C++/WinRt which connects(Sender) to one of the available devices(Client) around a specific region using WifiDirect. When the device wants to connect, it sends a connection request to the sender. The sender needs to detect the connection request sent by the client and connect to the client. For this I need to add an event - (On Connection requested). As soon as I add it should execute the code of OnConnectionRequested.

#include "pch.h"
#include <winrt/Windows.Foundation.Collections.h>
#include "winrt/Windows.Devices.WiFiDirect.h"
#pragma once
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::WiFiDirect;
using namespace Windows::Storage::Streams;
using namespace winrt::Windows::Devices::WiFiDirect;
using namespace winrt::Windows::Devices::Enumeration;

enum class NotifyType
{
    StatusMessage,
    ErrorMessage
};

enum class CallbackContext
{
    Any,
    Same
};

class st
{
public:
    void OnConnectionRequested(WiFiDirectConnectionListener sender,
                               WiFiDirectConnectionRequestedEventArgsconnection EventArgs)
    {
        WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
        printf("Connection request received from ", connectionRequest.DeviceInformation().Name(), "Connection Request");
        printf("Connecting to ", connectionRequest.DeviceInformation().Name(), NotifyType::StatusMessage);
    }

    void start()
    {
        Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher _publisher;
        Windows::Devices::WiFiDirect::WiFiDirectConnectionListener _listener;
        winrt::event_token _connectionRequestedToken;

        try
        {
            _connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
            _publisher.Start();
            printf("Advertisement started, waiting for StatusChangedcallback...", NotifyType::StatusMessage);
        }
        catch (...)
        {
            printf("Error starting Advertisement: ", NotifyType::ErrorMessage);
        }

        getchar();
    }
};

int main()
{
    st s;
    s.start();
}

Is this the right way to add an event in C++/WinRt :

_connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});

The errors are :

LNK1120 1 unresolved externals   - error in Winrt.exe file

LNK2019
unresolved external symbol "public: struct winrt::hstring __thiscall
winrt::impl::consume_Windows_Devices_Enumeration_IDeviceInformation::Name(void)const
"
(?Name@?$consume_Windows_Devices_Enumeration_IDeviceInformation@UIDeviceInformation@Enumeration@Devices@Windows@winrt@@@impl@winrt@@QBE?AUhstring@3@XZ)
referenced in function "public: void __thiscall
st::OnConnectionRequested(struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionListener,struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionRequestedEventArgs)"
(?OnConnectionRequested@st@@QAEXUWiFiDirectConnectionListener@WiFiDirect@Devices@Windows@winrt@@UWiFiDirectConnectionRequestedEventArgs@3456@@Z) - error in Program.obj 1

What changes should I make at this line to clear the error? What does the error actually mean ? Or is there any other way to add an event in C++/WinRt project?

Body:
You are missing an #include directive:

#include <winrt/Windows.Devices.Enumeration.h>

See Why is the linker giving me a "LNK2019: Unresolved external symbol" error?:

If the unresolved symbol is an API from the Windows namespace headers for the C++/WinRT projection (in the winrt namespace), then the API is forward-declared in a header that you've included, but its definition is in a header that you haven't yet included. Include the header named for the API's namespace, and rebuild. For more info, see C++/WinRT projection headers.

For general instructions on how to handle events see Handle events by using delegates in C++/WinRT.

Capturing this (raw pointer) into the delegate might be dangerous, too. This breaks the link between object lifetime and visibility, and puts the burden of lifetime management on you. See Safely accessing the this pointer with an event-handling delegate for safer, more manageable alternatives.


问:
gitconfig difftool setup not working in Visual Studio 19
Having the following diff tool settings:

```<code>[difftool "edp"]
    cmd = \"C:/Program Files/ExamDiff Pro/ExamDiff.exe\" \"$REMOTE\" \"$LOCAL\" //nh
    prompt = false
    trustexistcode = true
</code>```

in .gitconfig results in a working diff tool from the console
git difftool or by right clicking in VS Code in the pending changes window.

How ever running from Visual Studio 19's integrated pending change windows: it does not work.

It seems that arguments are not properly quoted???:

```<code>[difftool "edp"]
   cmd = "\"powershell.exe\" \"echoArgs.ps1\" \"...Bla bla bla...\"
[diff]
    tool = edp
    guitool = edp
</code>```

prints

Args 1: '...Bla'
Args 2: 'bla'
...
```

<p>You can replace <code>powershell</code> with <code>C:/Program Files/Git/bin/bash.exe</code>, the same happens...
How can you fix this absolutely stupid freaking backslash/quotes escaping mess happening?</p>

<p><strong>Update</strong>: VS 19 installes the following command:</p>

```[difftool "vsdiffmerge"]
    cmd = \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Professional\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\vsdiffmerge.exe\" \"$LOCAL\" \"$REMOTE\" //t
    keepBackup = false
```

Which is basically very similar to mine...??

Any insight is very appreciated.

答:
Try changing cmd to look like the following:

cmd = \"C:\\Program Files\\ExamDiff Pro\\ExamDiff.exe\" \"$REMOTE\" \"$LOCAL\" //nh

Body:
Having the following diff tool settings:

[difftool "edp"]
    cmd = \"C:/Program Files/ExamDiff Pro/ExamDiff.exe\" \"$REMOTE\" \"$LOCAL\" //nh
    prompt = false
    trustexistcode = true

in .gitconfig results in a working diff tool from the console
git difftool or by right clicking in VS Code in the pending changes window.

How ever running from Visual Studio 19's integrated pending change windows: it does not work.

It seems that arguments are not properly quoted???:

[difftool "edp"]
   cmd = "\"powershell.exe\" \"echoArgs.ps1\" \"...Bla bla bla...\"
[diff]
    tool = edp
    guitool = edp

prints

Args 1: '...Bla'
Args 2: 'bla'
...

You can replace powershell with C:/Program Files/Git/bin/bash.exe, the same happens...
How can you fix this absolutely stupid freaking backslash/quotes escaping mess happening?

Update: VS 19 installes the following command:

[difftool "vsdiffmerge"]
    cmd = \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Professional\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\vsdiffmerge.exe\" \"$LOCAL\" \"$REMOTE\" //t
    keepBackup = false

Which is basically very similar to mine...??

Any insight is very appreciated.


问:
SSH.NET SocketException An attempt was made to access a socket in a way forbidden by its access permissions
I'm using SSH.NET to access some folders to show  on my website via SFTP host and port 22.

but it gives me an exception after uploading the function's page to the online host "smarterasp.net"..

```<code>[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]
</code>```

How can I solve this problem ?

答: Server OS on smarterasp.net that hosts your website has firewall rules to deny Outbound SFTP 22 port connections.</p>

Body:
I'm using SSH.NET to access some folders to show  on my website via SFTP host and port 22.

but it gives me an exception after uploading the function's page to the online host "smarterasp.net"..

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]

How can I solve this problem ?


问:
What is the true minimum API level of Android Google Maps V2 (17.0.0)?
Somewhere on the official pages they list a really low API level for maps v2, however, i am currently compiling with play-services-maps 17.0.0 and this seems to require a certain version of the play services app to be installed and THAT in turn requires a certain minimum API level of the device.

But how do i find out what that minimum is ? On an old device with 4.4.2 the play services app is stuck at somewhere 13.8 ish and the map does not run giving the "App is having trouble with Google Play Services. Please try again".

If i google this i find answers here on SO suggesting to just lower the maps to 16.0.0 which is NOT a solution. I have no problem setting the apps minium API to something higher IF i only could find out how high i need to go. Android Studio is letting me compile just fine with minsdk 19 but a device with 19 will not run the map so...

Any ideas/answers are welcome

答:
Didn't find any minimum sdk version in the official documentation. But found some observations. Check below:

Warning: This release is a MAJOR version update and breaking change. The latest update to Google Play services and Firebase includes the following changes:

Migration from Android Support Libraries to Jetpack (AndroidX) Libraries. Libraries will not work unless you make the following changes in your app:

Upgrade com.android.tools.build:gradle to v3.2.1 or later.

Upgrade compileSdkVersion to 28 or later.

Update your app to use Jetpack (AndroidX); follow the instructions in Migrating to AndroidX.

Version 17.0.0 of Google Maps includes in this release.


问:
Default vs optional function parameters with type hints
So the function gendata accepts two optional parameters (name and source) and then based on the value of source invokes parser with the same parameters that are however required in this function.

What is the recommended way to solve the required vs. none required parameters?

There is an example in Python docs for typing.Types and it shows that Type[SuperClass] should accept all child classes that inherit from it. Why mypy complains in this case and why only for arg 1 and 2 but not 3 (source)?

exmaple.py:

```<code>from dataclasses import dataclass
from typing import List, Optional, Type

@dataclass
class BaseItem:
    name: str
    value: int

@dataclass
class Item(BaseItem):
    pass

@dataclass
class AnotherItem(BaseItem):
    pass

def parser(item: Type[BaseItem], name: str, source: int) -> Type[BaseItem]:
    item.value = source
    return item

def gendata(
    items: List[Item], name: Optional[str] = None, source: Optional[int] = None
) -> None:
    for item in items:
        if source:
            item = parser(item, name, source)
</code>```

Testing:

```<code>$ mypy example.py
e.py:31: error: Incompatible types in assignment (expression has type "Type[BaseItem]", variable has type "Item")
e.py:31: error: Argument 1 to "parser" has incompatible type "Item"; expected "Type[BaseItem]"
e.py:31: error: Argument 2 to "parser" has incompatible type "Optional[str]"; expected "str"
Found 3 errors in 1 file (checked 1 source file)
</code>```

答:
First thing, about the Type[Something] errors, according to the documentation, you should use Type[Something] when you're receiving the type as parameter, if you're receiving an instance of BaseItem, you should just use BaseItem.

Example:

```<code>a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'
</code>```

Reference: https://docs.python.org/3/library/typing.html#typing.Type

About the Optional error, I usually read optional as nullable (in the documentation they even say Optional[X] is equivalent to Union[X, None].

Reference: https://docs.python.org/3/library/typing.html#typing.Optional

So if you're receiving a parameter with type Optional[str] and try to pass to a function that receives a str, this will raise an error, one solution is just check if the value is None and put a default string instead, like:

```<code>def gendata(
    items: List[Item], name: Optional[str] = None, source: Optional[int] = None
) -> None:
    if name is None:
        name = ''
    if source:
        for item in items:
            item = parser(item, name, source)
</code>```

Body:
So the function gendata accepts two optional parameters (name and source) and then based on the value of source invokes parser with the same parameters that are however required in this function.

What is the recommended way to solve the required vs. none required parameters?

There is an example in Python docs for typing.Types and it shows that Type[SuperClass] should accept all child classes that inherit from it. Why mypy complains in this case and why only for arg 1 and 2 but not 3 (source)?

exmaple.py:

from dataclasses import dataclass
from typing import List, Optional, Type

@dataclass
class BaseItem:
    name: str
    value: int

@dataclass
class Item(BaseItem):
    pass

@dataclass
class AnotherItem(BaseItem):
    pass

def parser(item: Type[BaseItem], name: str, source: int) -> Type[BaseItem]:
    item.value = source
    return item

def gendata(
    items: List[Item], name: Optional[str] = None, source: Optional[int] = None
) -> None:
    for item in items:
        if source:
            item = parser(item, name, source)

Testing:

$ mypy example.py
e.py:31: error: Incompatible types in assignment (expression has type "Type[BaseItem]", variable has type "Item")
e.py:31: error: Argument 1 to "parser" has incompatible type "Item"; expected "Type[BaseItem]"
e.py:31: error: Argument 2 to "parser" has incompatible type "Optional[str]"; expected "str"
Found 3 errors in 1 file (checked 1 source file)

Body:
First thing, about the Type[Something] errors, according to the documentation, you should use Type[Something] when you're receiving the type as parameter, if you're receiving an instance of BaseItem, you should just use BaseItem.

Example:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

Reference: https://docs.python.org/3/library/typing.html#typing.Type

About the Optional error, I usually read optional as nullable (in the documentation they even say Optional[X] is equivalent to Union[X, None].

Reference: https://docs.python.org/3/library/typing.html#typing.Optional

So if you're receiving a parameter with type Optional[str] and try to pass to a function that receives a str, this will raise an error, one solution is just check if the value is None and put a default string instead, like:

def gendata(
    items: List[Item], name: Optional[str] = None, source: Optional[int] = None
) -> None:
    if name is None:
        name = ''
    if source:
        for item in items:
            item = parser(item, name, source)


问:
How to trigger profiling in NodeJS at runtime?
We have a very stateful NodeJS based web server (Meteor) that occasionally, randomly becomes slow in production. The problem is not reproducible in any of our tests, and we don't know what's triggering it.

To diagnose this, we are using the v8-profiler package. This lets us trigger a 10-second CPU profile and download it for offline analysis.

Despite not having received any commits in 3 years, the package used to work fairly well. It has given us compilation trouble in the past, and now it looks like it stopped compiling entirely, breaking our build. The build happens inside a Docker container with all versions pinned, including NodeJS and v8-profiler itself, so it's unlikely that we can fix this on our end.

I'm thinking there must be some alternative, better maintained approach. But where is it?

(Note that restarting the server with additional flags (like --profile) is not an option, because it destroys all the evidence of the problem.)

答:
I found there has been v8-profiler-next which is a successor of v8-profiler.

I hope this works for you.


问:
Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord in Android Studio
I am getting this error when I am trying to read contacts from phone and I included READ_CONTACTS permission in Manifest file. And the strange thing is that it was working fine in Eclipse but when I converted my project to Gradle and run it in Android Studio I'm getting this error.

logcat says:

Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{302f069 29282:com.GP/u0a322} (pid=29282, uid=10322) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS

here is the Manifest code:

```<code><uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <!-- Read Contacts from phone -->
    <uses-permission android:name="android.permission.read_contacts" />
    <uses-permission android:name="android.permission.read_phone_state" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
</code>```

答:
According to Google's Documentation on requesting permission, here's the thing to bear in mind when you're handling it.

For example, suppose you list both READ_CONTACTS and WRITE_CONTACTS in
  your app manifest.

If you request READ_CONTACTS and the user grants
  the permission, and you then request WRITE_CONTACTS, the system
  immediately grants you that permission without interacting with the
  user.

https://developer.android.com/training/permissions/requesting

Body:
I am getting this error when I am trying to read contacts from phone and I included READ_CONTACTS permission in Manifest file. And the strange thing is that it was working fine in Eclipse but when I converted my project to Gradle and run it in Android Studio I'm getting this error.

logcat says:

Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{302f069 29282:com.GP/u0a322} (pid=29282, uid=10322) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS

here is the Manifest code:

<uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.read_contacts" />
    <uses-permission android:name="android.permission.read_phone_state" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />


问:
After parsing xml files in perl, getting special characters
I'm parsing a xml file & storing it in Database [using perl]. At the time of parsing am getting special characters like - &[quot;amp;lt;gt;].
What is the meaning of these special characters ? </p>

答:
Those are html-safe / xml-safe translations of characters that wouldn't be legal embedded within the document in their bare form.  >"&< are all 'special characters', with special meaning in the context of HTML and XML.  Well... technically > isn't reserved, but the others are.  & is a 'safe' way of specifying an ampersand character without throwing grit into the gears of the XML or HTML parser.

HTML::Entities is a module that helps you to deal with them.

Body:
Those are html-safe / xml-safe translations of characters that wouldn't be legal embedded within the document in their bare form.  >"&< are all 'special characters', with special meaning in the context of HTML and XML.  Well... technically > isn't reserved, but the others are.  &amp; is a 'safe' way of specifying an ampersand character without throwing grit into the gears of the XML or HTML parser.

HTML::Entities is a module that helps you to deal with them.


问:
R - tmap how to add datasets
I'm new in spatial graphics. I have to present the tmap package for an exam at university. So I was wondering is there a way to add general graphics such as those in the preloaded "World", "Rivers", "Land"... datasets? which are basically "ready to use". Maybe from a repository i don't know of... I tried to look up online and on stack but couldn't find anything useful.
I tried to use some .shp file downloaded online and load it as:
fvg <- readOGR("./FVG/CRN25000ED2_066_AREA.shp", layer = "CRN25000ED2_066_AREA").
But i always have problems with the projection and honestly that's not what i'm looking for. I'd like to have something more slick if possible.
Thanks in advance.

答:
I think your question is too general.

As a starting point you can check a tutorial I gave last year in Uruguay, this tutorial includes a tmap section.

The whole tutorial

the tmap section

hope it helps you

Title: R - tmap how to add datasets


问:
How to get bind value in vue js?
I am having difficulty to get model.title's value and display it into console when click event triggered. For example,there is total 3 records into my json file.The first model's title name is IRIS.When I click on link then I want to also display it on console. Can anyone help me please.

```<code><div id="app">

            <div v-for="model in myData">

          <h1>{{model.title}}</h1>
          <p>{{model.project}}</p>
          <p>{{model.bedrooms}}</p>
          <a href="#" @click="getTitle">View Detail</a>

        </div>

    </div>

 var vm = new Vue({

        el:'#app',
        data:{
            myData:[]

        },
        created:function(){
        this.fetchData();
        this.getTitle();
         },

        methods:{
        fetchData: function(){
        var url='data.json';
        axios.get(url)
        .then(function(res){
        vm.myData= res.data.models;
        console.log(this.myData);

        });
     },
     getTitle:function() {
        var url='j.json';
        axios.get(url)
        .then(function(res){
        //vm.myData= res.data.models.getTitle;
        console.log(res.data.models.getTitle);

        });

     }

}

    });
</code>```

The below code is from data.json file

```<code>{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }
</code>```

答:
you can pass variable in method called on click

like this:
View Detail

and then in method:

getTitle:function(model) {
   console.log(model);
}

Title: How to get bind value in vue js?

Body:
I am having difficulty to get model.title's value and display it into console when click event triggered. For example,there is total 3 records into my json file.The first model's title name is IRIS.When I click on link then I want to also display it on console. Can anyone help me please.

{{model.title}}

{{model.project}}

{{model.bedrooms}}

          View Detail

 var vm = new Vue({

        el:'#app',
        data:{
            myData:[]

        },
        created:function(){
        this.fetchData();
        this.getTitle();
         },

        methods:{
        fetchData: function(){
        var url='data.json';
        axios.get(url)
        .then(function(res){
        vm.myData= res.data.models;
        console.log(this.myData);

        });
     },
     getTitle:function() {
        var url='j.json';
        axios.get(url)
        .then(function(res){
        //vm.myData= res.data.models.getTitle;
        console.log(res.data.models.getTitle);

        });

     }

}

    });

The below code is from data.json file

{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }

Body:
you can pass variable in method called on click

like this:
<a href="#" @click="getTitle(model)">View Detail</a>

and then in method:

getTitle:function(model) {
   console.log(model);
}


问:
big dotted geom_line, but dots closer together
I am curious if it is possible to increase the size of dots on a dotted line within geom_line but keep the dots closer together. The R code below produces a basic reproducible example of what I see, and then I include another chart showing what I would like to see.

```<code>library(dplyr)
library(ggplot2)
set.seed(5223)
myDF <- data.frame(x=rnorm(20,0,1),
                   y=runif(20,0,20))
myDF <- myDF %>%
  mutate(From8to12 = y>=8 & y<=12)

ggplot(myDF,aes(x=x,y=y,col=From8to12)) +
  geom_point() +
  geom_hline(yintercept=8,lty="dotted") +
  geom_hline(yintercept=12,lty="dotted",size=1.5)
</code>```

Unedited Image

(Manually) Edited Image (In Paint)

I would like to make the dots bigger, but closer together. Is this possible? I've found nothing online.

答:
It's something like lty in base R plot, and one way is to specify specifically how long should the dash and gap be:

```<code>ggplot(myDF,aes(x=x,y=y,col=From8to12)) +
  geom_point() +
  geom_hline(yintercept=8,lty="dotted") +
  geom_hline(yintercept=12,lty="11",size=1.5)
</code>```

the "11" means length of 1 for dash, length of 1 for gap, and it will replicate this. you can see more about it here

Body:
I am curious if it is possible to increase the size of dots on a dotted line within geom_line but keep the dots closer together. The R code below produces a basic reproducible example of what I see, and then I include another chart showing what I would like to see.

library(dplyr)
library(ggplot2)
set.seed(5223)
myDF <- data.frame(x=rnorm(20,0,1),
                   y=runif(20,0,20))
myDF <- myDF %>%
  mutate(From8to12 = y>=8 & y<=12)

ggplot(myDF,aes(x=x,y=y,col=From8to12)) +
  geom_point() +
  geom_hline(yintercept=8,lty="dotted") +
  geom_hline(yintercept=12,lty="dotted",size=1.5)

Unedited Image

(Manually) Edited Image (In Paint)

I would like to make the dots bigger, but closer together. Is this possible? I've found nothing online.

Body:
It's something like lty in base R plot, and one way is to specify specifically how long should the dash and gap be:

ggplot(myDF,aes(x=x,y=y,col=From8to12)) +
  geom_point() +
  geom_hline(yintercept=8,lty="dotted") +
  geom_hline(yintercept=12,lty="11",size=1.5)

the "11" means length of 1 for dash, length of 1 for gap, and it will replicate this. you can see more about it here


问:
'TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined'
I'm working on a project in React and ran into a problem that has me stumped.

Whenever I run yarn start I get this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
string. Received type undefined

I have no idea why this is happening.

答:
We ejected from react-scripts and so could not simply upgrade the package.json entry to fix this.

Instead, we did this:

in a new directory, create a new project -> $> npx create-react-app foo-project

and then eject it -> cd ./foo-project && npm run eject

now copy the files from /foo-project/config into the config directory of our main app and fire up your dev server

hope this helps others in a similar bind.


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
I would recomend writing a Tetris clone.
You can learn a lot of c++ concepts with this and learn a 2d library like SDL or maybe even OpenGL throgh SDL.

It is always good to have a project with visual results and at the end of it you can play it.

OwnerDisplayName: climatewarrior

OwnerDisplayName: dean nolan

ContentLicense: CC BY-SA 2.5


问:
Split terminal output while keeping spaces
I'm trying to split the output of a program on a fixed position. I found the recommendation of awk, but I need to keep the empty spaces in the last part of the output. This is what I need to do:

The output I'm trying to split looks like this:

```<code>  trace-cmd-16029 [000]  5635.254957: function:             switch_mm_irqs_off
  trace-cmd-16029 [000]  5635.254961: function:                load_new_mm_cr3
  trinity-c0-16027 [000]  5635.254961: function:             finish_task_switch
  trinity-c0-16027 [000]  5635.254963: function:             smp_reschedule_interrupt
  trinity-c0-16027 [000]  5635.254965: function:             scheduler_ipi
  trinity-c0-16027 [000]  5635.254965: function:                irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_nmi_enter
  trinity-c0-16027 [000]  5635.254965: function:                sched_ttwu_pending
</code>```

I need it to be formatted like this:

```<code>load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending
</code>```

Basically the preamble always ends with "function:", followed by a lot of empty spaces. Some empty spaces are not from formatting but show called subfunctions (e.g. the empty space infront of "load_nw_mm_cr3" is there because its a subfunction of "switch_mm_irqs_off"). AWK will remove all empty spaces even the ones I still need.

Anybody with some tips how I can format this output in the terminal?

答:
If you don't want to hardcode number of spaces and number of spaces can be dynamic then try following.

```<code>awk '
FNR==NR{
  sub(/.*function:/,"")
  match($0,/[[:space:]]+/)
  val=substr($0,RSTART,RLENGTH)
  num=gsub(/ /,"&",val)
  a[FNR]=num
  min=min<num?min?min:num:num
  next
}
{
  if(a[FNR]-min>1){
    printf("%"a[FNR]-min"s%s\n",OFS,$NF)
  }
  else{
    print $NF
  }
}
' Input_file  Input_file
</code>```

For shown samples output will be as follows.

```<code>switch_mm_irqs_off
   load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending
</code>```

Body:
I'm trying to split the output of a program on a fixed position. I found the recommendation of awk, but I need to keep the empty spaces in the last part of the output. This is what I need to do:

The output I'm trying to split looks like this:

  trace-cmd-16029 [000]  5635.254957: function:             switch_mm_irqs_off
  trace-cmd-16029 [000]  5635.254961: function:                load_new_mm_cr3
  trinity-c0-16027 [000]  5635.254961: function:             finish_task_switch
  trinity-c0-16027 [000]  5635.254963: function:             smp_reschedule_interrupt
  trinity-c0-16027 [000]  5635.254965: function:             scheduler_ipi
  trinity-c0-16027 [000]  5635.254965: function:                irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_nmi_enter
  trinity-c0-16027 [000]  5635.254965: function:                sched_ttwu_pending

I need it to be formatted like this:

load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending

Basically the preamble always ends with "function:", followed by a lot of empty spaces. Some empty spaces are not from formatting but show called subfunctions (e.g. the empty space infront of "load_nw_mm_cr3" is there because its a subfunction of "switch_mm_irqs_off"). AWK will remove all empty spaces even the ones I still need.

Anybody with some tips how I can format this output in the terminal?

Body:
If you don't want to hardcode number of spaces and number of spaces can be dynamic then try following.

awk '
FNR==NR{
  sub(/.*function:/,"")
  match($0,/[[:space:]]+/)
  val=substr($0,RSTART,RLENGTH)
  num=gsub(/ /,"&",val)
  a[FNR]=num
  min=min<num?min?min:num:num
  next
}
{
  if(a[FNR]-min>1){
    printf("%"a[FNR]-min"s%s\n",OFS,$NF)
  }
  else{
    print $NF
  }
}
' Input_file  Input_file

For shown samples output will be as follows.

switch_mm_irqs_off
   load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending


问:
Restrict Autocomplete search to a particular country in Google Places Android API
My goal is to restrict the Autocomplete results from the Google Places Android API to a particular country (United States) only.

I am using the following API:

```<code>        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);
</code>```

Looks like LatLngBounds is supposed to do this job.

If yes, then what are the values of LatLngBounds for United States?

Which source did you use to get LatLngBounds for a country?

LatLngBounds is a rectange - so it can include other countries in the result as well. What about that?

Is there a better way to do it?

答:
```<code>    val autocompleteFragment =
        supportFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment?

    // Specify the types of place data to return.
    autocompleteFragment!!
        .setPlaceFields(listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG))
        .setCountry("UG")
</code>```

Body:
My goal is to restrict the Autocomplete results from the Google Places Android API to a particular country (United States) only.

I am using the following API:

        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

Looks like LatLngBounds is supposed to do this job.

If yes, then what are the values of LatLngBounds for United States?

Which source did you use to get LatLngBounds for a country?

LatLngBounds is a rectange - so it can include other countries in the result as well. What about that?

Is there a better way to do it?


问:
torch.cuda.is_available() returns false in colab
I am trying to use GPU in google colab. Below are the details of the versions of pytorch and cuda installed in my colab.

```<code>Torch 1.3.1 CUDA 10.1.243

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:01_CDT_2018
Cuda compilation tools, release 10.0, V10.0.130
</code>```

I am pretty new to using a GPU for transfer learning on pytorch models. My torch.cuda.is_available() returns false and I am unabel to use a GPU. torch.backends.cudnn.enabled returns true. What might be going wrong here?

答:
Make sure your Hardware accelerator is set to GPU.

Runtime > Change runtime type > Hardware Accelerator

Body:
I am trying to use GPU in google colab. Below are the details of the versions of pytorch and cuda installed in my colab.

Torch 1.3.1 CUDA 10.1.243

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:01_CDT_2018
Cuda compilation tools, release 10.0, V10.0.130

I am pretty new to using a GPU for transfer learning on pytorch models. My torch.cuda.is_available() returns false and I am unabel to use a GPU. torch.backends.cudnn.enabled returns true. What might be going wrong here?


问:
How to find from which JAR , class loader is trying to load a specific class?
Our spark job is run on spark cluster, but the during spark executor trying to run spark job am seeing class not found exception, the thing is am very sure the jar which contains that class is loaded, so am not getting why this exception is coming, is classloader trying to load some different jar? if it is, is their way which jar it is looking?</p>

答:
I guess you can use -verbose:class to start your app and see verbose logs
How to Use Verbose Options in Java

```<code>[Opened C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Object from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.io.Serializable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Comparable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.CharSequence from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
..............................................................................
..............................................................................
..............................................................................
[Loaded java.lang.Void from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Shutdown from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Shutdown$Lock from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
</code>```

Body:
I guess you can use -verbose:class to start your app and see verbose logs
How to Use Verbose Options in Java

[Opened C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Object from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.io.Serializable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Comparable from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.CharSequence from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
..............................................................................
..............................................................................
..............................................................................
[Loaded java.lang.Void from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Shutdown from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]
[Loaded java.lang.Shutdown$Lock from C:\Program Files\Java\jdk1.7.0_04\jre\lib\rt.jar]


问:
Trying Test Scripts spec.ts fails because expect(like return) executes before create response came and shows undefined in console
I am using angular 6 and parse database and I have implemented a test script for creating method.

Implemented create function in sample page component and service is implemented in the test service file. when I run ionic serve command and save using angular it created properly
   but when I implemented test script for creating function it creates data but spec fails because expect executes before create response came and shows undefined in the console in the spec file.

Here Implemented the sample Test script File sample.page.spec.ts:

```<code>      it('units page create function spec', () => {
        component.formData.optionName="testpiece";
        component.formData.optionDesc="testdescription";

        component.save();

        fixture.detectChanges();
        console.log("component.designationObject",component.designationObject);

        expect(component.designationObject).toEqual("Units Created Successfully");
      })
</code>```

Fails because expect(like return)  executes before create response came and shows undefined in the console.

答:
How does your create/save method exactly look like? For this answer, I assume that you are working with promises. If so, you have to call your async code as follows:

```<code> it('units page create function spec', (done) => {
        component.formData.optionName="testpiece";
        component.formData.optionDesc="testdescription";

        component.save().then(result => {
          fixture.detectChanges();
          console.log("component.designationObject",component.designationObject);

          expect(component.designationObject).toEqual("Units CreatedSuccessfully");
          done();
        });

      })
</code>```

This will trigger the expect call after your promise completes.
Note the call of the done callback after expect.

Body:
I am using angular 6 and parse database and I have implemented a test script for creating method.

Implemented create function in sample page component and service is implemented in the test service file. when I run ionic serve command and save using angular it created properly
   but when I implemented test script for creating function it creates data but spec fails because expect executes before create response came and shows undefined in the console in the spec file.

Here Implemented the sample Test script File sample.page.spec.ts:

      it('units page create function spec', () => {
        component.formData.optionName="testpiece";
        component.formData.optionDesc="testdescription";

        component.save();

        fixture.detectChanges();
        console.log("component.designationObject",component.designationObject);

        expect(component.designationObject).toEqual("Units Created Successfully");
      })

Fails because expect(like return)  executes before create response came and shows undefined in the console.

Body:
How does your create/save method exactly look like? For this answer, I assume that you are working with promises. If so, you have to call your async code as follows:

 it('units page create function spec', (done) => {
        component.formData.optionName="testpiece";
        component.formData.optionDesc="testdescription";

        component.save().then(result => {
          fixture.detectChanges();
          console.log("component.designationObject",component.designationObject);

          expect(component.designationObject).toEqual("Units CreatedSuccessfully");
          done();
        });

      })

This will trigger the expect call after your promise completes.
Note the call of the done callback after expect.


问:
Java array of objects with defined keys
I am new in Java and I would like to write a code like PHP or Javasript or Python alowes me to write where I am able to write a literal to create an array of couples. The thing I want to achieve in PHP looks like:

```<code>$arr = [
   ['key1' => 'aaa', 'key2' => 'bbb'],
   ['key1' => 'ccc', 'key2' => 'ddd'],
   ['key1' => 'eee', 'key2' => 'fff']
];
</code>```

It looks like it is not possible in Java. Hope it is. Thank you. Please write as simple code as possible.

答:
If you are using Java version >= 9 use this way:

```<code>    List.of(
            Map.of("key1", "aaa", "key2", "bbb"),
            Map.of("key1", "ccc", "key2", "ddd"),
            Map.of("key1", "eee", "key2", "fff")
    );
</code>```

For Java < 8 version:

```<code>    Arrays.asList(
            new HashMap<String, String>() {{
                put("key1", "aaa");
                put("key2", "bbb");
            }},
            new HashMap<String, String>() {{
                put("key1", "ccc");
                put("key2", "ddd");
            }},
            new HashMap<String, String>() {{
                put("key1", "eee");
                put("key2", "fff");
            }}
    );
</code>```

Title: Java array of objects with defined keys

Body:
I am new in Java and I would like to write a code like PHP or Javasript or Python alowes me to write where I am able to write a literal to create an array of couples. The thing I want to achieve in PHP looks like:

$arr = [
   ['key1' => 'aaa', 'key2' => 'bbb'],
   ['key1' => 'ccc', 'key2' => 'ddd'],
   ['key1' => 'eee', 'key2' => 'fff']
];

It looks like it is not possible in Java. Hope it is. Thank you. Please write as simple code as possible.

Body:
If you are using Java version >= 9 use this way:

    List.of(
            Map.of("key1", "aaa", "key2", "bbb"),
            Map.of("key1", "ccc", "key2", "ddd"),
            Map.of("key1", "eee", "key2", "fff")
    );

For Java < 8 version:

    Arrays.asList(
            new HashMap<String, String>() {{
                put("key1", "aaa");
                put("key2", "bbb");
            }},
            new HashMap<String, String>() {{
                put("key1", "ccc");
                put("key2", "ddd");
            }},
            new HashMap<String, String>() {{
                put("key1", "eee");
                put("key2", "fff");
            }}
    );


问:
How to push data but not change the MaterialPageRoute in Flutter?
I want to stay on the same page that I'm in, but push some data to the next page, how can I achieve this?</p>

答:
From my experience with Flutter, the views are only built when you open them.

The next page is not initiated, so you should only push the data to the next page when you navigate to it.

You can do this by passing arguments to it, or use an external database (sql lite) or file.


问:
Excel function to find nth to last non blank value in a row
I have a sheet filled with blood pressure (BP) data, arranged by month.

I am interested in storing the last three BP values in a range per patient, each of which is assigned a row. Note that there are months which do not have BP readings, so there are blanks in the dataset.

The range for the blood pressures is BB:BL.

I was able to find formulas for the last:

```<code>=LOOKUP(2,1/(ISNUMBER(BB3:BL3)),BB3:BL3)
</code>```

and second-to-last:

```<code>=LOOKUP(9.99E+307,BB3:INDEX(BB3:BL3,MATCH(9.99E+307,BB3:BL3)-1))
</code>```

But I am not able to modify the formula above to find the third-to-last non-blank BP value.

Any advice is appreciated!

答:
To find the third-to-last non-blank value, try using INDEX+AGGREGATE function

1] For data range placed in vertically

In C2, enter formula :

```<code>=INDEX(A1:A100,AGGREGATE(14,6,ROW(A1:A100)/(A1:A100<>""),3))
</code>```

2] For data range placed in horizontally

In B3, enter formula :

```<code>=INDEX(1:1,AGGREGATE(14,6,COLUMN(1:1)/(1:1<>""),3))
</code>```

2.a] If the data range placed in a specified position, e.g. BB3:BH3

The formula become, in B3 formula : >>

```<code>=INDEX(BB3:BH3,AGGREGATE(14,6,COLUMN(BB3:BH3)-COLUMN(BA3)/(BB3:BH3<>""),3))
</code>```

Remark : the Column number must adjusted to COLUMN(BB3:BH3)-COLUMN(BA3) in become {1,2,3,4,5....}

Body:
I have a sheet filled with blood pressure (BP) data, arranged by month.

I am interested in storing the last three BP values in a range per patient, each of which is assigned a row. Note that there are months which do not have BP readings, so there are blanks in the dataset.

The range for the blood pressures is BB:BL.

I was able to find formulas for the last:

=LOOKUP(2,1/(ISNUMBER(BB3:BL3)),BB3:BL3)

and second-to-last:

=LOOKUP(9.99E+307,BB3:INDEX(BB3:BL3,MATCH(9.99E+307,BB3:BL3)-1))

But I am not able to modify the formula above to find the third-to-last non-blank BP value.

Any advice is appreciated!

Body:
To find the third-to-last non-blank value, try using INDEX+AGGREGATE function

1] For data range placed in vertically

In C2, enter formula :

=INDEX(A1:A100,AGGREGATE(14,6,ROW(A1:A100)/(A1:A100<>""),3))

2] For data range placed in horizontally

In B3, enter formula :

=INDEX(1:1,AGGREGATE(14,6,COLUMN(1:1)/(1:1<>""),3))

2.a] If the data range placed in a specified position, e.g. BB3:BH3

The formula become, in B3 formula : >>

=INDEX(BB3:BH3,AGGREGATE(14,6,COLUMN(BB3:BH3)-COLUMN(BA3)/(BB3:BH3<>""),3))

Remark : the Column number must adjusted to COLUMN(BB3:BH3)-COLUMN(BA3) in become {1,2,3,4,5....}


问:
curl through proxy syntax
I don't understand how to read this general syntax.  I want to request a URL through our proxy and it requires a specific host, port, username, and password.  I don't know how to figure out what the protocol is.
I want to do curl through a proxy.  Based on the helpfile below, I would guess the line should be:

curl -x [whatever-my-protocol-is://]my-host-which-i-know[:my-port-which-i-know] -U my-username-which-i-know[:my-pass-which-i-know] http://www.google.com

Is this right?  How do I figure out the protocol?

Relevant info from man:

```<code>-x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port
     --proxy-anyauth Pick "any" proxy authentication method (H)
     --proxy-basic   Use Basic authentication on the proxy (H)
     --proxy-digest  Use Digest authentication on the proxy (H)
     --proxy-negotiate Use Negotiate authentication on the proxy (H)
     --proxy-ntlm    Use NTLM authentication on the proxy (H)
 -U, --proxy-user USER[:PASSWORD]  Proxy user and password
     --proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port
</code>```

答:
If you use domain</p>

```<code>curl -x proxy:81 -U domain\login:password https://stackoverflow.com/
</code>```

Title: curl through proxy syntax

Body:
I don't understand how to read this general syntax.  I want to request a URL through our proxy and it requires a specific host, port, username, and password.  I don't know how to figure out what the protocol is.
I want to do curl through a proxy.  Based on the helpfile below, I would guess the line should be:

curl -x [whatever-my-protocol-is://]my-host-which-i-know[:my-port-which-i-know] -U my-username-which-i-know[:my-pass-which-i-know] http://www.google.com

Is this right?  How do I figure out the protocol?

Relevant info from man:

-x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port
     --proxy-anyauth Pick "any" proxy authentication method (H)
     --proxy-basic   Use Basic authentication on the proxy (H)
     --proxy-digest  Use Digest authentication on the proxy (H)
     --proxy-negotiate Use Negotiate authentication on the proxy (H)
     --proxy-ntlm    Use NTLM authentication on the proxy (H)
 -U, --proxy-user USER[:PASSWORD]  Proxy user and password
     --proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port

Body:
If you use domain

curl -x proxy:81 -U domain\login:password https://stackoverflow.com/


问:
Cropping an image with imagepickercontroller in swift
I am currently making a program in swift that involves a screen of choosing an image from either camera or photo library using action sheet. This is fully functional however I would like to be able to choose a square section from the selected image, similar to apple default apps. How can I implement this? Here is my functional code:</p>

```<code>func chooseImage(_ sender: Any) {

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self

    let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in

        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePickerController.sourceType = .camera
            self.present(imagePickerController, animated: true, completion: nil)
        }else{
            print("Camera not available")
        }

    }))

    actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
        imagePickerController.sourceType = .photoLibrary
        self.present(imagePickerController, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Default", style: .default, handler: { (action:UIAlertAction) in
        self.avatarImageView.image = UIImage(named: "Avatar.png")

    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(actionSheet, animated: true, completion: nil)

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    avatarImageView.image = image

    picker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}
// Saves the User singleton object onto the device
static func saveData() {
    let savedData = NSKeyedArchiver.archivedData(withRootObject: User.sharedUser)
    UserDefaults.standard.set(savedData, forKey: "user")
}
</code>```

答:
```<code>- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle
</code>```

{

```<code>[[NSUserDefaults standardUserDefaults] setObject:UIImageJPEGRepresentation(image, 1) forKey:@"image"];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"cameraOn"];

[cropViewController dismissViewControllerAnimated:YES completion:^{

    [self performSegueWithIdentifier:@"YourSegueIdentifier" sender:self];

}];
//UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
</code>```

}

For (iOS13): Do all ViewController "cropController.modalPresentationStyle =.fullScreen"  using  storyboard or code.

This is work good and easily navigate to another controller. I also attached image so you can easily understand how to change presentation style.

Body:
I am currently making a program in swift that involves a screen of choosing an image from either camera or photo library using action sheet. This is fully functional however I would like to be able to choose a square section from the selected image, similar to apple default apps. How can I implement this? Here is my functional code:

func chooseImage(_ sender: Any) {

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self

    let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in

        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePickerController.sourceType = .camera
            self.present(imagePickerController, animated: true, completion: nil)
        }else{
            print("Camera not available")
        }

    }))

    actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
        imagePickerController.sourceType = .photoLibrary
        self.present(imagePickerController, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Default", style: .default, handler: { (action:UIAlertAction) in
        self.avatarImageView.image = UIImage(named: "Avatar.png")

    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(actionSheet, animated: true, completion: nil)

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    avatarImageView.image = image

    picker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}
// Saves the User singleton object onto the device
static func saveData() {
    let savedData = NSKeyedArchiver.archivedData(withRootObject: User.sharedUser)
    UserDefaults.standard.set(savedData, forKey: "user")
}

Body:
- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle

{

[[NSUserDefaults standardUserDefaults] setObject:UIImageJPEGRepresentation(image, 1) forKey:@"image"];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"cameraOn"];

[cropViewController dismissViewControllerAnimated:YES completion:^{

    [self performSegueWithIdentifier:@"YourSegueIdentifier" sender:self];

}];
//UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

}

For (iOS13): Do all ViewController "cropController.modalPresentationStyle =.fullScreen"  using  storyboard or code.

This is work good and easily navigate to another controller. I also attached image so you can easily understand how to change presentation style.


问:
Spark Unit Testing: How to initialize sc only once for all the Suites using FunSuite
I want to write spark unit test cases and I am using FunSuite for it.
But i want that my sparkContext is initialized only once , used by all the Suites and then is killed when all Suites completes.

```<code>abstract class baseClass extends FunSuite with BeforeAndAfter{
  before {
    println("initialize spark context")
  }
  after {
    println("kill spark context")
  }

}

@RunWith(classOf[JUnitRunner])
class A extends baseClass{
test("for class A"){
//assert
}

@RunWith(classOf[JUnitRunner])
class B extends baseClass{
test(for class b){
//assert
}
}
</code>```

but when i run sbt test
I can see println statement baseClass has been called from both the tests. Obsiously When the object is created for both the classes A and B , Abstract
baseclass is called.
But then how can we achieve my purpose i.e spark context is iniliazed only once while all the test cases are run

答:
I strongly recommend using the spark-testing-base library in order to manage the lifecycle of a sparkContext or sparkSession during your tests.
You won't have to pollute your tests by overriding the beforeAll, afterAll methods and managing the lifecycle of the sparkSession/sparkContext.

You can share one sparkSession/sparkContext for all the tests by overriding the following method :
def reuseContextIfPossible: Boolean = true

for more details : https://github.com/holdenk/spark-testing-base/wiki/SharedSparkContext

I hope it helps!

Body:
I want to write spark unit test cases and I am using FunSuite for it.
But i want that my sparkContext is initialized only once , used by all the Suites and then is killed when all Suites completes.

abstract class baseClass extends FunSuite with BeforeAndAfter{
  before {
    println("initialize spark context")
  }
  after {
    println("kill spark context")
  }

}

@RunWith(classOf[JUnitRunner])
class A extends baseClass{
test("for class A"){
//assert
}

@RunWith(classOf[JUnitRunner])
class B extends baseClass{
test(for class b){
//assert
}
}

but when i run sbt test
I can see println statement baseClass has been called from both the tests. Obsiously When the object is created for both the classes A and B , Abstract
baseclass is called.
But then how can we achieve my purpose i.e spark context is iniliazed only once while all the test cases are run


问:
Compare current time to file date time last modified in Windows Batch File
I would like a command in a batch file to only execute if it has not been ran for the last 15 minutes. To achieve this I can create a "last_run" file to log the time last ran.

Where I am stuck is comparing the time last modified to the current time and taking action if the time last modified.

Here is my current code:

```<code>@echo off
set filename=last_run.txt
if not exist %filename% (
   rem NOT EXISTS, CREATE FILE THEN PRINT THE LIST
   echo.>"%filename%"
   GOTO PrintList
) else (
   rem FILE EXISTS, GET TIME LAST MODIFIED
   FOR %%? IN (%filename%) DO (set filetime=%%~t?)
   echo %filetime%
   rem IF TIME LAST MODIFIED > 15 MINS PRINT THE LIST
   if timediff??(%filetime%, current) > 15 mins {
      GOTO PrintList
   } else {
      GOTO End
   }
)

:PrintList
rem PRINT THE LIST
echo now print the list
rem WRITE TO THE FILE TO UPDATE TIME LAST MODIFIED
echo.>"%filename%"
GOTO End

:End
</code>```

答:
You could use total minutes with a powerhell command.

```<code>@echo off
set error=0
if not exist last_run.txt echo File not yet existed, first run will be now & set /a error+=1
    for /f "delims=," %%i in ('powershell -command "(New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date)).TotalMinutes"') do set "now=%%i"
    if "%error%" == "1" goto :run
    for /f %%a in (last_run.txt) do set earlier=%%a
    set /a result=%now%-%earlier%
    if %result% geq 15 (
        :run
           echo RUN COMMANDS HERE
           echo %now%>tmp.tmp
    )
</code>```

The concept is simple. We get the epoch time in minutes. Store the value in a file. Then compare the current minutes with the minutes in the file. if %now% is equal to or more than 15 from %earlier% the command will run. Additionally, if the file does not yet exist, it will create it and run the command first time. From there it will only run if the seconds in the file is 15 or less than current minutes.

Body:
I would like a command in a batch file to only execute if it has not been ran for the last 15 minutes. To achieve this I can create a "last_run" file to log the time last ran.

Where I am stuck is comparing the time last modified to the current time and taking action if the time last modified.

Here is my current code:

@echo off
set filename=last_run.txt
if not exist %filename% (
   rem NOT EXISTS, CREATE FILE THEN PRINT THE LIST
   echo.>"%filename%"
   GOTO PrintList
) else (
   rem FILE EXISTS, GET TIME LAST MODIFIED
   FOR %%? IN (%filename%) DO (set filetime=%%~t?)
   echo %filetime%
   rem IF TIME LAST MODIFIED > 15 MINS PRINT THE LIST
   if timediff??(%filetime%, current) > 15 mins {
      GOTO PrintList
   } else {
      GOTO End
   }
)

:PrintList
rem PRINT THE LIST
echo now print the list
rem WRITE TO THE FILE TO UPDATE TIME LAST MODIFIED
echo.>"%filename%"
GOTO End

:End

Body:
You could use total minutes with a powerhell command.

@echo off
set error=0
if not exist last_run.txt echo File not yet existed, first run will be now & set /a error+=1
    for /f "delims=," %%i in ('powershell -command "(New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date)).TotalMinutes"') do set "now=%%i"
    if "%error%" == "1" goto :run
    for /f %%a in (last_run.txt) do set earlier=%%a
    set /a result=%now%-%earlier%
    if %result% geq 15 (
        :run
           echo RUN COMMANDS HERE
           echo %now%>tmp.tmp
    )

The concept is simple. We get the epoch time in minutes. Store the value in a file. Then compare the current minutes with the minutes in the file. if %now% is equal to or more than 15 from %earlier% the command will run. Additionally, if the file does not yet exist, it will create it and run the command first time. From there it will only run if the seconds in the file is 15 or less than current minutes.


问:
Python ctypes 'c_char_p' memory leak
I'm developing a Python library for cryptography. I wanted to optimize my library by writing the main classes in C++ with GMP. I wrote my C++ classes and I wrote the extern methods to use the main arithmetic operations: addition, subtraction, etc... These methods returns the results as char* to avoid cast problems. I built the DLL of my library and I declared the methods in a Python wrapper with ctypes. I noticed that after each arithmetic operation with huge numbers the memory grew exponentially. I was looking for problems in my C++ implementation, but there were no problems thanks to the C++ garbage collector. I was looking for a possible solution, so I discovered that I had to implement a C++ method to free up memory of the string created by the DLL. So I wrote this simple method:

```<code>extern "C" {

    __declspec(dllexport) void free_memory(char * n)
    {
        free(n);
    }
    ...
}
</code>```

I implemented this code in the Python wrapper to free up the memory allocated by the DLL:

```<code>import os
import ctypes

DIR_PATH = os.path.dirname(os.path.realpath(__file__))
NUMERIC = ctypes.CDLL(DIR_PATH + "/numeric.dll")
...
NUMERIC.free_memory.argtypes = [ctypes.c_void_p]
NUMERIC.free_memory.restype = None

def void_cast(n):
    a = ctypes.cast(n, ctypes.c_char_p)
    res = ctypes.c_char_p(a.value)
    NUMERIC.free_memory(a)
    return res
</code>```

So with res = ctypes.c_char_p (a.value) I create a new variable that no longer points to a. This way I correctly delete a using the DLL method, but I still have memory leak problems. It is as if the Python garbage collector does not free up correctly the memory of strings of type c_char_p. In the previous implementation I used only Python and the gmpy2 library, so all the numbers were converted to mpz or mpq. I tested the memory consumption using the memory_profiler package. I created 40 objects of type projective point, defined on an elliptical curve, and I calculated the products i*P, withi from 1 to 40. With gmpy2 about 70MB in total were used. Instead, using ctypes with the classes in C++ the consumption of the memory rose to 1.5GB. It's obvious that there is something wrong, especially when only the base classes that deal with arithmetic operations change. How can I properly free the memory without having memory leak problems?
I put an example of extern method for calculating an arithmetic operation, but I have already checked that the problem lies only in correctly freeing the memory via thefree_memory function and reassigning the string so that the garbage collector of Python will free the string when needed.

```<code>extern "C" {
    __declspec(dllexport) const char* rat_add(const char * n, const char * m)
    {
        return (RationalNum(n) + RationalNum(m)).getValue();
    }
}
</code>```

Thanks in advance and have a nice day.

PS: Clearly in C++ I correctly implemented the destructor method to free up the space of the mpz_t and mpq_t objects created.

答:
The problem is in this line:

```<code>res = ctypes.c_char_p(a.value)
</code>```

This creates a copy of a.value and sets res to a c_char_p that points to the copy. However, Python does not do memory management for ctypes pointers, so the copy will be leaked!

The leak should be fixed if you replace above line with:

```<code>res = bytes(memoryview(a.value))
</code>```

This also creates a copy, but res will be a real Python object.

Title: Python ctypes 'c_char_p' memory leak

Body:
I'm developing a Python library for cryptography. I wanted to optimize my library by writing the main classes in C++ with GMP. I wrote my C++ classes and I wrote the extern methods to use the main arithmetic operations: addition, subtraction, etc... These methods returns the results as char* to avoid cast problems. I built the DLL of my library and I declared the methods in a Python wrapper with ctypes. I noticed that after each arithmetic operation with huge numbers the memory grew exponentially. I was looking for problems in my C++ implementation, but there were no problems thanks to the C++ garbage collector. I was looking for a possible solution, so I discovered that I had to implement a C++ method to free up memory of the string created by the DLL. So I wrote this simple method:

extern "C" {

    __declspec(dllexport) void free_memory(char * n)
    {
        free(n);
    }
    ...
}

I implemented this code in the Python wrapper to free up the memory allocated by the DLL:

import os
import ctypes

DIR_PATH = os.path.dirname(os.path.realpath(__file__))
NUMERIC = ctypes.CDLL(DIR_PATH + "/numeric.dll")
...
NUMERIC.free_memory.argtypes = [ctypes.c_void_p]
NUMERIC.free_memory.restype = None

def void_cast(n):
    a = ctypes.cast(n, ctypes.c_char_p)
    res = ctypes.c_char_p(a.value)
    NUMERIC.free_memory(a)
    return res

So with res = ctypes.c_char_p (a.value) I create a new variable that no longer points to a. This way I correctly delete a using the DLL method, but I still have memory leak problems. It is as if the Python garbage collector does not free up correctly the memory of strings of type c_char_p. In the previous implementation I used only Python and the gmpy2 library, so all the numbers were converted to mpz or mpq. I tested the memory consumption using the memory_profiler package. I created 40 objects of type projective point, defined on an elliptical curve, and I calculated the products i*P, withi from 1 to 40. With gmpy2 about 70MB in total were used. Instead, using ctypes with the classes in C++ the consumption of the memory rose to 1.5GB. It's obvious that there is something wrong, especially when only the base classes that deal with arithmetic operations change. How can I properly free the memory without having memory leak problems?
I put an example of extern method for calculating an arithmetic operation, but I have already checked that the problem lies only in correctly freeing the memory via thefree_memory function and reassigning the string so that the garbage collector of Python will free the string when needed.

extern "C" {
    __declspec(dllexport) const char* rat_add(const char * n, const char * m)
    {
        return (RationalNum(n) + RationalNum(m)).getValue();
    }
}

Thanks in advance and have a nice day.

PS: Clearly in C++ I correctly implemented the destructor method to free up the space of the mpz_t and mpq_t objects created.

Body:
The problem is in this line:

res = ctypes.c_char_p(a.value)

This creates a copy of a.value and sets res to a c_char_p that points to the copy. However, Python does not do memory management for ctypes pointers, so the copy will be leaked!

The leak should be fixed if you replace above line with:

res = bytes(memoryview(a.value))

This also creates a copy, but res will be a real Python object.


问:
How to Change 0 to 1 in TextInput
What is the best approach to change 0 to 1 on a PowerApps TextInput. Trying to figure out with OnSelect Function. Don't want a user to input a 0 Quantity to an order. If a user type in 0 it will automatic change to a 1

Hope l explain myself clearly. Thank you in advance.

答:
You cannot, today, have a rule that will update the value of a control based on the value of the same control (as this may create a cyclical dependency). What you can do is to show to the user an error saying that they have made an error, and possibly prevent them from advancing in the app, like in the example below:

To make that example, I updated the following properties in the screen control:

```<code>btnAdd.DisplayMode: If(Value(TextInput1.Text) >= 1, DisplayMode.Edit, DisplayMode.Disabled)
lblErrorMessage.Visible: Value(TextInput1.Text) < 1
txtQuantity.BorderColor: If(Value(TextInput1.Text) >= 1, RGBA(0, 18, 107, 1), Color.Red)
</code>```

Hope this helps!

Title: How to Change 0 to 1 in TextInput

Body:
You cannot, today, have a rule that will update the value of a control based on the value of the same control (as this may create a cyclical dependency). What you can do is to show to the user an error saying that they have made an error, and possibly prevent them from advancing in the app, like in the example below:

To make that example, I updated the following properties in the screen control:

btnAdd.DisplayMode: If(Value(TextInput1.Text) >= 1, DisplayMode.Edit, DisplayMode.Disabled)
lblErrorMessage.Visible: Value(TextInput1.Text) < 1
txtQuantity.BorderColor: If(Value(TextInput1.Text) >= 1, RGBA(0, 18, 107, 1), Color.Red)

Hope this helps!