问:
Is there any Callback that gives me feedback about lost packages in Twilio beta8 SDK?
I'm developing an app in Android that uses Twilio to communicate through VoIP the users. I´m using beta-8 of the Voice SDK. My problem is that the call sometimes goes to "black" and you can´t hear anything from one side or another. This is because of the network, because I have been monitoring this.

My question is if there is some way to know when this is happening to notify the App and inform the user that we are trying to reconnect the call with some layout.

Any help is appreciated.

答:
Twilio developer evangelist here.

There is almost a way to do this.

We have a Voice Insights Dashboard right now, which you can enable in your account and see account reports for your calls.

In the latest JavaScript Twilio Client you can also get call quality events. However this is still under development for Android and iOS Clients.

So, the overall answer is: not yet, but it's being developed so keep an eye on the Twilio blog for announcements.


来源: stackexchange

问:
Close on Click outside Angular 2 (4)
recently I posted similar question but I couldn't make it work, so I'll reference it here and ask for help again since I haven't been able to do it.

Question: Hide on click Outside of element angular 4

So, I need to do the following: I have a side menu and on click of one list item in that menu, I open another sidebar menu (it's not a dropdown), and I need to close it when clicking anywhere but on that new side menu.

My component structure is the following: Layout component > Sidebar Component > Small Menu Component.

So I open small menu on click inside sidebar component. I have tried: https://www.npmjs.com/package/angular2-click-outside

https://www.npmjs.com/package/ng2-click-outside

They dont seem to work.

Thanks.

答:
So I've actually dealt with this but only with a single dropdown but I feel like it would be similar to what you are looking for.

In your component/directive

```<code>constructor() {
    document.addEventListener('click', this.offClickHandler.bind(this));
}

offClickHandler(event:any) {
    if (!event.target.closest(".select-options") && !event.target.closest(".select-input")) {
        // do whatever you want here
    }
}
</code>```

This will check to see if there was a click close to but not in the div/dropdown that is open. Then the code inside of the offClickHandler would execute. So just set the classes inside the offClickHandler to be the side menu that you want to close when clicking away and then hide it inside of the if statement.

ContentLicense: CC BY-SA 3.0

Title: Close on Click outside Angular 2 (4)

Body:
So I've actually dealt with this but only with a single dropdown but I feel like it would be similar to what you are looking for.

In your component/directive

constructor() {
    document.addEventListener('click', this.offClickHandler.bind(this));
}

offClickHandler(event:any) {
    if (!event.target.closest(".select-options") && !event.target.closest(".select-input")) {
        // do whatever you want here
    }
}

This will check to see if there was a click close to but not in the div/dropdown that is open. Then the code inside of the offClickHandler would execute. So just set the classes inside the offClickHandler to be the side menu that you want to close when clicking away and then hide it inside of the if statement.


问:
How to properly return values from unmanaged interface method?
I'm in the process of extending GeckoFx (http://geckofx.org) and am having some problems returning array values from unmanaged interfaces provided by XPCom.

I've added a great amount of new feature support to GeckoFx using the latest XulRunner 1.9.2.13 build but, I'm getting access violation exceptions when attempting to return arrays from interface methods.
Eg:

```<code>[Guid("43987F7B-0FAA-4019-811E-42BECAC73FC5"), ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface mozISpellCheckingEngine
{
    //...
    void GetDictionaryList([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)]ref string[] dictionaries, out uint count);
    //...
}

public static string[] GetAvailableDictionaries()
{
    string[] _dictionaries = null;
    uint count = 0;

    //GetSpellChecker() returns a valid mozISpellCheckingEngine object
    GetSpellChecker().GetDictionaryList(ref _dictionaries, out count);
    if (count > 0)
    {
        if (_dictionaries != null)
        {
            return _dictionaries;
        }
    }
    return null;
}
</code>```

The problem is when GetDictionaryList returns sometimes it will return a list with a single index and containing the name of one dictionary (I have 2 dictionaries in the location this method searches in) and count returns with the correct value of 2; other times the method will fail and throw an access violation and the value of _dictionaries is string[0] while count remains correct with the value of 2.

I guess the biggest part of this question would have to be 'Am I marshaling the method and its parameters correctly in the interface declaration?'.

This example code is just that - an example. There are several other XulRunner features I would like to implement in GeckoFx but, they return arrays as well and suffer from the same problem. Until I can get past this issue my work is at a bit of a stand-still.

Thanks for any and all help you can provide.

-Scott

答:
Change:

```<code>void GetDictionaryList([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)]ref string[] dictionaries, out uint count);
</code>```

to:

```<code>void GetDictionaryList(ref IntPtr dictionaries, out uint count);
</code>```

and use it like:

```<code>IntPtr dictionaries = IntPtr.Zero;
int count;

GetDictionaryList(ref dictionaries, count);

 // check dictionaries != IntPtr.Zero; and count > 0

 // dictionaries will be a IntPtr to array IntPtr (of size count)

 string vals = new string[count];

 for(int i = 0; i < count; ++i)
  vals[i] = Marshal.PtrToStringUni(Marshal.SizeOf(typeof(IntPtr)) * i);
</code>```

(I haven't compiled this code so there may be typos.)

ContentLicense: CC BY-SA 2.5

Body:
I'm in the process of extending GeckoFx (http://geckofx.org) and am having some problems returning array values from unmanaged interfaces provided by XPCom.

I've added a great amount of new feature support to GeckoFx using the latest XulRunner 1.9.2.13 build but, I'm getting access violation exceptions when attempting to return arrays from interface methods.
Eg:

[Guid("43987F7B-0FAA-4019-811E-42BECAC73FC5"), ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface mozISpellCheckingEngine
{
    //...
    void GetDictionaryList([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)]ref string[] dictionaries, out uint count);
    //...
}

public static string[] GetAvailableDictionaries()
{
    string[] _dictionaries = null;
    uint count = 0;

    //GetSpellChecker() returns a valid mozISpellCheckingEngine object
    GetSpellChecker().GetDictionaryList(ref _dictionaries, out count);
    if (count > 0)
    {
        if (_dictionaries != null)
        {
            return _dictionaries;
        }
    }
    return null;
}

The problem is when GetDictionaryList returns sometimes it will return a list with a single index and containing the name of one dictionary (I have 2 dictionaries in the location this method searches in) and count returns with the correct value of 2; other times the method will fail and throw an access violation and the value of _dictionaries is string[0] while count remains correct with the value of 2.

I guess the biggest part of this question would have to be 'Am I marshaling the method and its parameters correctly in the interface declaration?'.

This example code is just that - an example. There are several other XulRunner features I would like to implement in GeckoFx but, they return arrays as well and suffer from the same problem. Until I can get past this issue my work is at a bit of a stand-still.

Thanks for any and all help you can provide.

-Scott

Body:
Change:

void GetDictionaryList([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)]ref string[] dictionaries, out uint count);

to:

void GetDictionaryList(ref IntPtr dictionaries, out uint count);

and use it like:

IntPtr dictionaries = IntPtr.Zero;
int count;

GetDictionaryList(ref dictionaries, count);

 // check dictionaries != IntPtr.Zero; and count > 0

 // dictionaries will be a IntPtr to array IntPtr (of size count)

 string vals = new string[count];

 for(int i = 0; i < count; ++i)
  vals[i] = Marshal.PtrToStringUni(Marshal.SizeOf(typeof(IntPtr)) * i);

(I haven't compiled this code so there may be typos.)


问:
Iterating over an array batch script
While following a tutorial for iterating over arrays in a batch script I didn't get the same result:

```<code>@echo off
setlocal enabledelayedexpansion
set topic[0] = comments
set topic[1] = variables
set topic[2] = Arrays
set topic[3] = Decision making
set topic[4] = Time and date
set topic[5] = Operators

for /l %%n in (0,1,5) do (
   echo !topic[%%n]!
)
</code>```

When I run this command I get:

答:
in batch spaces matter because it's an argument delimiter

```<code>set topic[0] = comments
</code>```

should be

```<code>set topic[0]=comments
</code>```

Something strange with cmd is that variables can terminate with a space

```<code>set topic[0] = comments
echo %topic[0] %
 comments
</code>```

Title: Iterating over an array batch script

Body:
While following a tutorial for iterating over arrays in a batch script I didn't get the same result:

@echo off
setlocal enabledelayedexpansion
set topic[0] = comments
set topic[1] = variables
set topic[2] = Arrays
set topic[3] = Decision making
set topic[4] = Time and date
set topic[5] = Operators

for /l %%n in (0,1,5) do (
   echo !topic[%%n]!
)

When I run this command I get:

Body:
in batch spaces matter because it's an argument delimiter

set topic[0] = comments

should be

set topic[0]=comments

Something strange with cmd is that variables can terminate with a space

set topic[0] = comments
echo %topic[0] %
 comments


问:
Gitlab docker registry pull failed EOF

1. Introduction

I've got Gitlab setup using a docker image https://github.com/sameersbn/docker-gitlab (sameersbn/docker-gitlab) and want to setup gitlab private registry.

1.1  Problem

All of this is behind reverse proxy load balancer using nginx. I am able to push into registry, but pull has some problem I am not able to resolve.

The output tells me retrying in 5sec and then increases over time, but after about minute it outputs Download complete on some layers. When all layers outputs Download complete. Pull results then like Unexpected EOF.

Infrastructure goes like this:

Proxy load balancer -----> gitlab registry
                                     |
                                     |
Another proxy load balancer -----> Gitlab

2. Terminal outputs

Docker login and push works fine. The problem is with pull.

2.1 Docker pull

2.1.1 expected result

```<code>root@server:~# docker pull registry.dalten.com/docker/php5.6-cli/image
Using default tag: latest
latest: Pulling from docker/php5.6-cli/image
10a267c67f42: Already exists
370377701f89: Pulling fs layer
455c73a122bc: Pulling fs layer
2cdcd82f5338: Pulling fs layer
3ac634f20449: Waiting
a19eeb6546ae: Waiting
4ca536f5a464: Waiting
4788559f39db: Waiting
cc1917e72a80: Waiting
42feb0ca362a: Pull complete
f74f29b91bbc: Pull complete
d104213bfd22: Pull complete
6db9d2d35d48: Pull complete
806b8ac2f0b7: Pull complete
661bb76178ac: Pull complete
3727be25d45f: Pull complete
04fed213644a: Pull complete
a78f18e044f7: Pull complete
849a2f576c66: Pull complete
259300decf26: Pull complete
0d9f42b121be: Pull complete
2483d273017a: Pull complete
3dfaf57e1d54: Pull complete
92fbf8438206: Pull complete
7d5100ec575c: Pull complete
52b1dff7320d: Pull complete
500fa7f84392: Pull complete
aff937c2773b: Pull complete
92f8bc1201f3: Pull complete
Digest: sha256:d3d06d2cebd333af21565639503ddded64db47d5641ee9ff93167200b5fcad7a
Status: Downloaded newer image for registry.dalten.com/docker/php5.6-cli/image:latest
</code>```

2.1.2 Actual behavior

```<code>docker pull registry.dalten.com/docker/php5.6-cli/image
Using default tag: latest
latest: Pulling from docker/php5.6-cli/image
10a267c67f42: Already exists
370377701f89: Pulling fs layer
455c73a122bc: Pulling fs layer
2cdcd82f5338: Pulling fs layer
3ac634f20449: Waiting
a19eeb6546ae: Waiting
a19eeb6546ae: Downloading 4.398 MB/4.398 MB
4788559f39db: Downloading 102.6 MB/102.6 MB
cc1917e72a80: Download complete
42feb0ca362a: Download complete
f74f29b91bbc: Download complete
d104213bfd22: Download complete
6db9d2d35d48: Download complete
806b8ac2f0b7: Download complete
661bb76178ac: Download complete
3727be25d45f: Download complete
04fed213644a: Download complete
a78f18e044f7: Download complete
849a2f576c66: Download complete
259300decf26: Download complete
0d9f42b121be: Download complete
2483d273017a: Downloading 24.12 MB/24.12 MB
3dfaf57e1d54: Download complete
92fbf8438206: Download complete
7d5100ec575c: Download complete
52b1dff7320d: Download complete
500fa7f84392: Download complete
aff937c2773b: Download complete
92f8bc1201f3: Download complete
unexpected EOF
</code>```

2.3 Docker login

```<code>sudo docker login registry.dalten.com
Username (xxxxxx):
Password:
Login Succeeded
</code>```

2.4 Docker push

```<code>sudo docker push registry.dalten.com/docker/php5.6-cli/image
The push refers to a repository [registry.dalten.com/docker/php5.6-cli/image]
d8b353eb3025: Pushed
f2e85bc0b7b1: Pushed
fc9e1e5e38f7: Pushed
fe9a3f9c4559: Pushed
6a8bf8c8edbd: Pushed
latest: digest: sha256:ea1d854d38be82f54d39efe2c67000bed1b03348bcc2f3dc094f260855dff368 size: 1357
</code>```

3. Configurations

Configurations contains docker-compose.yml files which I use for running services. Gitlab is running fine. Every configuration works. The only problem is with registry.

Another thing is that registry works while in insecured state. The problem must be hidden somewhere inside load balancer (nginx) configuration. (Some header has not been sent, limit exceeded, or so)

3.1 Gitlab Docker-compose

Note: I cutted compose of irrelevant information

```<code>version: '2'
services:
  registry:
    image: registry:latest
    environment:
      REGISTRY_AUTH_TOKEN_ISSUER: gitlab-issuer
      REGISTRY_AUTH_TOKEN_REALM: https://git.dalten.cz/jwt/auth
      REGISTRY_AUTH_TOKEN_SERVICE: container_registry
      REGISTRY_LOG_LEVEL: debug
      REGISTRY_STORAGE_DELETE_ENABLED: 'true'
      REGISTRY_AUTH_TOKEN_ROOTCERTBUNDLE: /certs/fullchain.pem
      REGISTRY_HTTP_SECRET: secret
    volumes:
    - /mnt/storage/srv/gitlab1/data/shared/registry:/registry
    - /mnt/storage/srv/gitlab1/certs:/certs
    ports:
    - 5000:5000/tcp
  gitlab:
    image: sameersbn/gitlab:latest
    hostname: git.dalten.cz
    environment:
      GITLAB_REGISTRY_ENABLED: 'true'
      GITLAB_REGISTRY_HOST: registry.dalten.com
      GITLAB_REGISTRY_API_URL: http://registry:5000
      GITLAB_REGISTRY_ISSUER: gitlab-issuer
      GITLAB_REGISTRY_CERT_PATH: /certs/fullchain.pem
      GITLAB_REGISTRY_KEY_PATH: /certs/privkey.pem
    volumes:
    - /mnt/storage/srv/gitlab1/certs:/certs
    - /mnt/storage/srv/gitlab1/data:/home/git/data/
    ports:
    - 8643:80/tcp
    - 1022:22/tcp
</code>```

3.2 Nginx registry docker-compose

```<code>version: '2'
services:
  nginx:
    image: sameersbn/nginx:1.10.3
    volumes:
    - /srv/nginx/sites-enabled:/etc/nginx/sites-enabled
    - /mnt/storage/lb/letsencrypt:/etc/nginx/ssl
    ports:
    - 80:80/tcp
    - 443:443/tcp
</code>```

3.2.1 Nginx Virtual host file

I use Nginx for my reverse proxy configuration (Load Balancer). There are stored all certificates for https traffic.

```<code>    # For versions of Nginx > 1.3.9 that include chunked transfer encoding
# support Replace with appropriate values where necessary
upstream docker-registry {
 server 10.126.0.242:5000;
}

server {
  listen 80;
  server_name registry.dalten.com
  return 301 https://$http_host:$request_uri;
  access_log /var/log/nginx/access.log;
  error_log  /var/log/nginx/error.log;
}

server {
 listen 443 default_server;
 server_name registry.dalten.com

 add_header Docker-Distribution-Api-Version registry/2.0 always;

 ssl on;
 ssl_certificate /etc/nginx/ssl/live/registry.dalten.com/fullchain.pem;
 ssl_certificate_key /etc/nginx/ssl/live/registry.dalten.com/privkey.pem;

  ssl_session_timeout 5m;

 client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image
uploads
 # required to avoid HTTP 411: see Issue #1486
 # (https://github.com/dotcloud/docker/issues/1486)
 chunked_transfer_encoding on;
 proxy_set_header X-Original-URI $request_uri;
 proxy_set_header Docker-Distribution-Api-Version registry/2.0;

access_log /var/log/nginx/access.log;
 error_log /var/log/nginx/error.log;

location /
{
     # let Nginx know about our auth file
     proxy_pass http://docker-registry;
     proxy_set_header Host $host; # required for docker client's sake
     proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;
 }
 location /_ping {
     proxy_pass http://docker-registry;
 }
 location /v1/_ping {
     proxy_pass http://docker-registry;
 }
 location /v2/ {
     # To add basic authentication to v2 use auth_basic setting plus
     # add_header
     add_header 'Docker-Distribution-Api-Version' 'registry/2.0' always;
     proxy_pass http://docker-registry;
     proxy_set_header Host $http_host; # required for docker client's sake
     proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_read_timeout 900;
 }
}
</code>```

3. Logs

If you require any more logs feel free to ask!

3.1 Docker pull

4. Thank you for all your help!

答: Problem solved by adding proxy_max_temp_file_size 0; inside nginx virtual host configuration!

Title: Gitlab docker registry pull failed EOF

Body:
1. Introduction

I've got Gitlab setup using a docker image https://github.com/sameersbn/docker-gitlab (sameersbn/docker-gitlab) and want to setup gitlab private registry.

1.1  Problem

All of this is behind reverse proxy load balancer using nginx. I am able to push into registry, but pull has some problem I am not able to resolve.

The output tells me retrying in 5sec and then increases over time, but after about minute it outputs Download complete on some layers. When all layers outputs Download complete. Pull results then like Unexpected EOF.

Infrastructure goes like this:

Proxy load balancer -----> gitlab registry
                                     |
                                     |
Another proxy load balancer -----> Gitlab

2. Terminal outputs

Docker login and push works fine. The problem is with pull.

2.1 Docker pull

2.1.1 expected result

root@server:~# docker pull registry.dalten.com/docker/php5.6-cli/image
Using default tag: latest
latest: Pulling from docker/php5.6-cli/image
10a267c67f42: Already exists
370377701f89: Pulling fs layer
455c73a122bc: Pulling fs layer
2cdcd82f5338: Pulling fs layer
3ac634f20449: Waiting
a19eeb6546ae: Waiting
4ca536f5a464: Waiting
4788559f39db: Waiting
cc1917e72a80: Waiting
42feb0ca362a: Pull complete
f74f29b91bbc: Pull complete
d104213bfd22: Pull complete
6db9d2d35d48: Pull complete
806b8ac2f0b7: Pull complete
661bb76178ac: Pull complete
3727be25d45f: Pull complete
04fed213644a: Pull complete
a78f18e044f7: Pull complete
849a2f576c66: Pull complete
259300decf26: Pull complete
0d9f42b121be: Pull complete
2483d273017a: Pull complete
3dfaf57e1d54: Pull complete
92fbf8438206: Pull complete
7d5100ec575c: Pull complete
52b1dff7320d: Pull complete
500fa7f84392: Pull complete
aff937c2773b: Pull complete
92f8bc1201f3: Pull complete
Digest: sha256:d3d06d2cebd333af21565639503ddded64db47d5641ee9ff93167200b5fcad7a
Status: Downloaded newer image for registry.dalten.com/docker/php5.6-cli/image:latest

2.1.2 Actual behavior

docker pull registry.dalten.com/docker/php5.6-cli/image
Using default tag: latest
latest: Pulling from docker/php5.6-cli/image
10a267c67f42: Already exists
370377701f89: Pulling fs layer
455c73a122bc: Pulling fs layer
2cdcd82f5338: Pulling fs layer
3ac634f20449: Waiting
a19eeb6546ae: Waiting
a19eeb6546ae: Downloading 4.398 MB/4.398 MB
4788559f39db: Downloading 102.6 MB/102.6 MB
cc1917e72a80: Download complete
42feb0ca362a: Download complete
f74f29b91bbc: Download complete
d104213bfd22: Download complete
6db9d2d35d48: Download complete
806b8ac2f0b7: Download complete
661bb76178ac: Download complete
3727be25d45f: Download complete
04fed213644a: Download complete
a78f18e044f7: Download complete
849a2f576c66: Download complete
259300decf26: Download complete
0d9f42b121be: Download complete
2483d273017a: Downloading 24.12 MB/24.12 MB
3dfaf57e1d54: Download complete
92fbf8438206: Download complete
7d5100ec575c: Download complete
52b1dff7320d: Download complete
500fa7f84392: Download complete
aff937c2773b: Download complete
92f8bc1201f3: Download complete
unexpected EOF

2.3 Docker login

sudo docker login registry.dalten.com
Username (xxxxxx):
Password:
Login Succeeded

2.4 Docker push

sudo docker push registry.dalten.com/docker/php5.6-cli/image
The push refers to a repository [registry.dalten.com/docker/php5.6-cli/image]
d8b353eb3025: Pushed
f2e85bc0b7b1: Pushed
fc9e1e5e38f7: Pushed
fe9a3f9c4559: Pushed
6a8bf8c8edbd: Pushed
latest: digest: sha256:ea1d854d38be82f54d39efe2c67000bed1b03348bcc2f3dc094f260855dff368 size: 1357

3. Configurations

Configurations contains docker-compose.yml files which I use for running services. Gitlab is running fine. Every configuration works. The only problem is with registry.

Another thing is that registry works while in insecured state. The problem must be hidden somewhere inside load balancer (nginx) configuration. (Some header has not been sent, limit exceeded, or so)

3.1 Gitlab Docker-compose

Note: I cutted compose of irrelevant information

version: '2'
services:
  registry:
    image: registry:latest
    environment:
      REGISTRY_AUTH_TOKEN_ISSUER: gitlab-issuer
      REGISTRY_AUTH_TOKEN_REALM: https://git.dalten.cz/jwt/auth
      REGISTRY_AUTH_TOKEN_SERVICE: container_registry
      REGISTRY_LOG_LEVEL: debug
      REGISTRY_STORAGE_DELETE_ENABLED: 'true'
      REGISTRY_AUTH_TOKEN_ROOTCERTBUNDLE: /certs/fullchain.pem
      REGISTRY_HTTP_SECRET: secret
    volumes:
    - /mnt/storage/srv/gitlab1/data/shared/registry:/registry
    - /mnt/storage/srv/gitlab1/certs:/certs
    ports:
    - 5000:5000/tcp
  gitlab:
    image: sameersbn/gitlab:latest
    hostname: git.dalten.cz
    environment:
      GITLAB_REGISTRY_ENABLED: 'true'
      GITLAB_REGISTRY_HOST: registry.dalten.com
      GITLAB_REGISTRY_API_URL: http://registry:5000
      GITLAB_REGISTRY_ISSUER: gitlab-issuer
      GITLAB_REGISTRY_CERT_PATH: /certs/fullchain.pem
      GITLAB_REGISTRY_KEY_PATH: /certs/privkey.pem
    volumes:
    - /mnt/storage/srv/gitlab1/certs:/certs
    - /mnt/storage/srv/gitlab1/data:/home/git/data/
    ports:
    - 8643:80/tcp
    - 1022:22/tcp

3.2 Nginx registry docker-compose

version: '2'
services:
  nginx:
    image: sameersbn/nginx:1.10.3
    volumes:
    - /srv/nginx/sites-enabled:/etc/nginx/sites-enabled
    - /mnt/storage/lb/letsencrypt:/etc/nginx/ssl
    ports:
    - 80:80/tcp
    - 443:443/tcp

3.2.1 Nginx Virtual host file

I use Nginx for my reverse proxy configuration (Load Balancer). There are stored all certificates for https traffic.

    # For versions of Nginx > 1.3.9 that include chunked transfer encoding
# support Replace with appropriate values where necessary
upstream docker-registry {
 server 10.126.0.242:5000;
}

server {
  listen 80;
  server_name registry.dalten.com
  return 301 https://$http_host:$request_uri;
  access_log /var/log/nginx/access.log;
  error_log  /var/log/nginx/error.log;
}

server {
 listen 443 default_server;
 server_name registry.dalten.com

 add_header Docker-Distribution-Api-Version registry/2.0 always;

 ssl on;
 ssl_certificate /etc/nginx/ssl/live/registry.dalten.com/fullchain.pem;
 ssl_certificate_key /etc/nginx/ssl/live/registry.dalten.com/privkey.pem;

  ssl_session_timeout 5m;

 client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image
uploads
 # required to avoid HTTP 411: see Issue #1486
 # (https://github.com/dotcloud/docker/issues/1486)
 chunked_transfer_encoding on;
 proxy_set_header X-Original-URI $request_uri;
 proxy_set_header Docker-Distribution-Api-Version registry/2.0;

access_log /var/log/nginx/access.log;
 error_log /var/log/nginx/error.log;

location /
{
     # let Nginx know about our auth file
     proxy_pass http://docker-registry;
     proxy_set_header Host $host; # required for docker client's sake
     proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;
 }
 location /_ping {
     proxy_pass http://docker-registry;
 }
 location /v1/_ping {
     proxy_pass http://docker-registry;
 }
 location /v2/ {
     # To add basic authentication to v2 use auth_basic setting plus
     # add_header
     add_header 'Docker-Distribution-Api-Version' 'registry/2.0' always;
     proxy_pass http://docker-registry;
     proxy_set_header Host $http_host; # required for docker client's sake
     proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_read_timeout 900;
 }
}

3. Logs

If you require any more logs feel free to ask!

3.1 Docker pull

4. Thank you for all your help!


问:
Coding a Scatter plot with smooth lines in VBA
I am trying to code for a Scatter Plot using smooth lines with VBA.
I am trying to take data off of a worksheet and create a scatter plot with lines and no markers in the same workbook different sheet using VBA.

This is part snapshot of my worksheet

The values below 247 and between 263 to 455 in column A will have corresponding -1.75 in column B.

The x values are in range A1:A401

y-values are in range B1:B401

Also I want to have title to my graph and X and Y axis labelled. I am having trouble figuring how to get the y-values to plot with the x-values instead of excel making two seperate lines on the chart.

This is graph I need

This is the code I have used

```<code>Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)

Set GraphRange = Union(xData, yData)

'Create a chart
  Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2

'Give chart some data
  cht.Chart.SetSourceData Source:=GraphRange

'Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines
</code>```

This is what it gives me in Excel.

How can I get the desired result ?

Also what can I do if the range is dynamic ?

答:
My code is</p>

```<code>Sub setChart()
Dim LastRow_this As Long
Dim Ws As Worksheet, chtWs As Worksheet
Dim xData As Range, yData As Range
Dim Cht As Chart

    Set Ws = ThisWorkbook.Worksheets(2)
    Set chtWs = ThisWorkbook.Worksheets(1)
    With Ws
        LastRow_this = .Range("a" & Rows.Count).End(xlUp).Row
        Set xData = .Range("A1:A" & LastRow_this)
        Set yData = .Range("B1:B" & LastRow_this)
    End With

    Set Cht = chtWs.Shapes.AddChart.Chart

    With Cht
        .ChartType = xlXYScatterLinesNoMarkers
        .HasLegend = False
        .SeriesCollection.NewSeries
        With .SeriesCollection(1)
            .XValues = xData
            .Values = yData
        End With
        .Axes(xlCategory).MajorUnit = 50
        .Axes(xlCategory).HasMajorGridlines = True
        .Axes(xlValue).HasMajorGridlines = True
        .Axes(xlCategory).MaximumScale = 460
        .Axes(xlCategory).MinimumScale = 50
    End With

End Sub
</code>```

Body:
I am trying to code for a Scatter Plot using smooth lines with VBA.
I am trying to take data off of a worksheet and create a scatter plot with lines and no markers in the same workbook different sheet using VBA.

This is part snapshot of my worksheet

The values below 247 and between 263 to 455 in column A will have corresponding -1.75 in column B.

The x values are in range A1:A401

y-values are in range B1:B401

Also I want to have title to my graph and X and Y axis labelled. I am having trouble figuring how to get the y-values to plot with the x-values instead of excel making two seperate lines on the chart.

This is graph I need

This is the code I have used

Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)

Set GraphRange = Union(xData, yData)

'Create a chart
  Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2

'Give chart some data
  cht.Chart.SetSourceData Source:=GraphRange

'Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines

This is what it gives me in Excel.

How can I get the desired result ?

Also what can I do if the range is dynamic ?

Body:
My code is

Sub setChart()
Dim LastRow_this As Long
Dim Ws As Worksheet, chtWs As Worksheet
Dim xData As Range, yData As Range
Dim Cht As Chart

    Set Ws = ThisWorkbook.Worksheets(2)
    Set chtWs = ThisWorkbook.Worksheets(1)
    With Ws
        LastRow_this = .Range("a" & Rows.Count).End(xlUp).Row
        Set xData = .Range("A1:A" & LastRow_this)
        Set yData = .Range("B1:B" & LastRow_this)
    End With

    Set Cht = chtWs.Shapes.AddChart.Chart

    With Cht
        .ChartType = xlXYScatterLinesNoMarkers
        .HasLegend = False
        .SeriesCollection.NewSeries
        With .SeriesCollection(1)
            .XValues = xData
            .Values = yData
        End With
        .Axes(xlCategory).MajorUnit = 50
        .Axes(xlCategory).HasMajorGridlines = True
        .Axes(xlValue).HasMajorGridlines = True
        .Axes(xlCategory).MaximumScale = 460
        .Axes(xlCategory).MinimumScale = 50
    End With

End Sub


问:
Changing iframe src with Javascript
I am trying to change an  when someone clicks a radio button. For some reason my code is not working correctly and I am having trouble figuring out why. Here is what I have:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Untitled 1</title>

  <form method="post">
    <input name="calendarSelection" type="radio" onselect="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
    <input name="calendarSelection" type="radio" onselect="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
    <input name="calendarSelection" type="radio" onselect="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
  </form>

```

答:
You can solve it by making the iframe in javascript

  document.write(" ");```

ContentLicense: CC BY-SA 4.0

Title: Changing iframe src with Javascript

Body:
You can solve it by making the iframe in javascript

  document.write(" <iframe  id='frame' name='frame' src='" + srcstring + "' width='600'  height='315'   allowfullscreen></iframe>");


问:
C# Fastest search object which has nearest value given
I try to find an object in list which has nearest value that given
I wrote this :

```<code>float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]
</code>```

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

答:
Sort and search times

This is where things get very difficult for developers without formal education.
If your list of Objects is already sorted. You can use binary search for this.
If the you first need to sort the list, you are not going to save time, since your approach takes Θ(n log(n)) time and sorting takes Θ(n log(n)) time and searching a sorted list takes Θ(log(n)) time, that would be slower than your approach.

Buf if your list is already sorted for example by using sortedList.
Finding the closest item can be done with binary search in Θ(log(n)) time. (Which is incredible fast)

The big Problem: Binary search will find you one exact item, and not the closest. This means we need to roll our own implementation. Here's an example application that does this, the function public T findClosest is our binary search implementation.

Finding the closest value with binary search (Visual Studio C# Console Application)

You can use this to test, play around and learn more about recursive structures.

Copyright 2017 Eldar Kersebaum

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FindingClosestObjectInList
{
    class exampleObject
    {
        public float value;
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Generate objectList with some random value
            var objectList = new SortedList<float, exampleObject>();
            var rnd = new Random();
            for (int i = 0; i < 10000; i++)
            {
                var o = new exampleObject();
                o.value = (float)(rnd.NextDouble());
                //Values need to be Unique, that might be a problem for you.
                if (!objectList.Keys.Contains(o.value))
                {
                    objectList.Add(o.value, o);
                }
            }
            float target = .314f;
            var closestToTarget = objectList.Keys.FindClosest(target);
            Console.WriteLine(closestToTarget);
            Console.ReadKey();
        }
    }
    public static class ExtensionMethod
    {
        public static T FindClosest<T>(this IList<T> sortedCollection, T target)
            where T : IComparable<T>, IConvertible
        {
            //Initialize borders for binary search
            int begin = 0;
            int end = sortedCollection.Count;
            T lastElement = target;

            while (end > begin)
            {
                int index = (begin + end) / 2;
                lastElement = sortedCollection[index];

                //Small change to binary search, to make sure we pick the closer one,
                //when we two values left.
                if (end - begin == 2)
                {
                    //Distanzes between the two values and the
                    var a = sortedCollection[begin];
                    var b = sortedCollection[begin + 1];
                    var aDist = substractGeneric(a, target);
                    var bDist = substractGeneric(b, target);

                    return a.CompareTo(b) <= 0 ? a : b;
                }
                //Actual binary search
                if (lastElement.CompareTo(target) >= 0)
                    end = index;
                else
                    begin = index + 1;
            }
            //Normal ending of binary search.
            return lastElement;
        }
        //If your Type that doesn't support substraction, this will explode at RUNTIME.
        public static T substractGeneric<T>(T a, T b)
            where T : IConvertible  //Will make it more difficult to call this function with stupid Ts, but might still explode.
        {
            return (dynamic)a - (dynamic)b;
        }
    }
}
</code>```

Body:
I try to find an object in list which has nearest value that given
I wrote this :

float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

Body:
Sort and search times

This is where things get very difficult for developers without formal education.
If your list of Objects is already sorted. You can use binary search for this.
If the you first need to sort the list, you are not going to save time, since your approach takes Θ(n log(n)) time and sorting takes Θ(n log(n)) time and searching a sorted list takes Θ(log(n)) time, that would be slower than your approach.

Buf if your list is already sorted for example by using sortedList.
Finding the closest item can be done with binary search in Θ(log(n)) time. (Which is incredible fast)

The big Problem: Binary search will find you one exact item, and not the closest. This means we need to roll our own implementation. Here's an example application that does this, the function public T findClosest is our binary search implementation.

Finding the closest value with binary search (Visual Studio C# Console Application)

You can use this to test, play around and learn more about recursive structures.

Copyright 2017 Eldar Kersebaum

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FindingClosestObjectInList
{
    class exampleObject
    {
        public float value;
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Generate objectList with some random value
            var objectList = new SortedList<float, exampleObject>();
            var rnd = new Random();
            for (int i = 0; i < 10000; i++)
            {
                var o = new exampleObject();
                o.value = (float)(rnd.NextDouble());
                //Values need to be Unique, that might be a problem for you.
                if (!objectList.Keys.Contains(o.value))
                {
                    objectList.Add(o.value, o);
                }
            }
            float target = .314f;
            var closestToTarget = objectList.Keys.FindClosest(target);
            Console.WriteLine(closestToTarget);
            Console.ReadKey();
        }
    }
    public static class ExtensionMethod
    {
        public static T FindClosest<T>(this IList<T> sortedCollection, T target)
            where T : IComparable<T>, IConvertible
        {
            //Initialize borders for binary search
            int begin = 0;
            int end = sortedCollection.Count;
            T lastElement = target;

            while (end > begin)
            {
                int index = (begin + end) / 2;
                lastElement = sortedCollection[index];

                //Small change to binary search, to make sure we pick the closer one,
                //when we two values left.
                if (end - begin == 2)
                {
                    //Distanzes between the two values and the
                    var a = sortedCollection[begin];
                    var b = sortedCollection[begin + 1];
                    var aDist = substractGeneric(a, target);
                    var bDist = substractGeneric(b, target);

                    return a.CompareTo(b) <= 0 ? a : b;
                }
                //Actual binary search
                if (lastElement.CompareTo(target) >= 0)
                    end = index;
                else
                    begin = index + 1;
            }
            //Normal ending of binary search.
            return lastElement;
        }
        //If your Type that doesn't support substraction, this will explode at RUNTIME.
        public static T substractGeneric<T>(T a, T b)
            where T : IConvertible  //Will make it more difficult to call this function with stupid Ts, but might still explode.
        {
            return (dynamic)a - (dynamic)b;
        }
    }
}


问:
Extracting field from both actual and expected objects when testing with AssertJ
I would like to check that a list contains a sub-list of another list. Here's a dummy example of how I do it currently:

```<code>@Test
public void testExtracting() throws Exception {
    final List<User> users = new ArrayList<>();
    users.add(new User(5234, "Adam"));
    users.add(new User(4635, "David"));

    final List<User> newUsers = new ArrayList<>();
    newUsers.add(new User(6143, "Bob"));
    newUsers.add(new User(3465, "Cindy"));

    users.addAll(newUsers);

    assertThat(users).extracting("id").contains(newUsers.get(0).id, newUsers.get(1).id);
}

public static class User {
    public long id;
    public String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
</code>```

Is it possible to achieve the same result in a more compact way, without overriding the equals method of User class? I'm looking for something along the lines of:

```<code>assertThat(users).contains(newUsers.get(0), newUsers.get(1)).extracting("id");
</code>```

Or, better yet:

```<code>assertThat(users).contains(newUsers.subList(0, 2)).extracting("id");
</code>```

答:
If you are able to add a getId() method to User, you can solve this with an extractor:

```<code>assertThat(users)
    .extracting("id")
    .containsAll(extractProperty("id").from(newUsers));
</code>```

Without being able to change User (so no overriding hashcode() or equals(), or adding getters), you will need to extract the id from both sets and compare them. This worked for me, but I'll admit it's a bit ugly.

```<code>assertThat(users)
    .extracting("id")
    .containsAll(newUsers.stream().map(it -> it.id).collect(Collectors.toSet()));
</code>```

What I'm doing is using assertJ to extract the id from the users set and Java 8 streams/map to get all the newUser ids in one collection. This way your newUsers collection can be arbitrarily large and you don't have to hard code the mapping yourself.

Note that the stream/map work in the second example is the same work being done in the first example by extractProperty, we're just doing it manually.

Body:
I would like to check that a list contains a sub-list of another list. Here's a dummy example of how I do it currently:

@Test
public void testExtracting() throws Exception {
    final List<User> users = new ArrayList<>();
    users.add(new User(5234, "Adam"));
    users.add(new User(4635, "David"));

    final List<User> newUsers = new ArrayList<>();
    newUsers.add(new User(6143, "Bob"));
    newUsers.add(new User(3465, "Cindy"));

    users.addAll(newUsers);

    assertThat(users).extracting("id").contains(newUsers.get(0).id, newUsers.get(1).id);
}

public static class User {
    public long id;
    public String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

Is it possible to achieve the same result in a more compact way, without overriding the equals method of User class? I'm looking for something along the lines of:

assertThat(users).contains(newUsers.get(0), newUsers.get(1)).extracting("id");

Or, better yet:

assertThat(users).contains(newUsers.subList(0, 2)).extracting("id");

Body:
If you are able to add a getId() method to User, you can solve this with an extractor:

assertThat(users)
    .extracting("id")
    .containsAll(extractProperty("id").from(newUsers));

Without being able to change User (so no overriding hashcode() or equals(), or adding getters), you will need to extract the id from both sets and compare them. This worked for me, but I'll admit it's a bit ugly.

assertThat(users)
    .extracting("id")
    .containsAll(newUsers.stream().map(it -> it.id).collect(Collectors.toSet()));

What I'm doing is using assertJ to extract the id from the users set and Java 8 streams/map to get all the newUser ids in one collection. This way your newUsers collection can be arbitrarily large and you don't have to hard code the mapping yourself.

Note that the stream/map work in the second example is the same work being done in the first example by extractProperty, we're just doing it manually.


问:
How do I map with rarely used state in clojure?
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

```<code>int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}
</code>```

However in Clojure the best I've come up with is:

```<code>(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))
</code>```

Which is pretty ugly considering that without the special case this would become:

```<code>(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)
</code>```

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

答:
You can just use an atom to track it:

```<code>(def special-values-handled (atom 0))

(defn handle-cases [value]
  (cond
    (case-1? value) (handle-case-1 value)
    (case-2? value) ...
    (special? value) (do (swap! special-values-handled inc)
                         (handle-special @special-values-handled value))))
</code>```

Then you can just do

```<code>(map handle-cases values)
</code>```

Body:
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}

However in Clojure the best I've come up with is:

(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))

Which is pretty ugly considering that without the special case this would become:

(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

Body:
You can just use an atom to track it:

(def special-values-handled (atom 0))

(defn handle-cases [value]
  (cond
    (case-1? value) (handle-case-1 value)
    (case-2? value) ...
    (special? value) (do (swap! special-values-handled inc)
                         (handle-special @special-values-handled value))))

Then you can just do

(map handle-cases values)


问:
Updating data in Vaadin's grid
Hello everyone my problem is that my grid doesn't update data.

I've a Thread that get new values from a database but when I assign the new DataProvider from the collection that get new values, the grid doesn't change anything.

For example, the Grid contains the orders from clients, every 30 seconds a Thread search if there are new orders available, then y get all the orders in an ArrayList and set the new ArrayList in the grid’s DataProvider but the Grid continues having the same values as before.

How can I refresh data in the Grid without refresh all the web page?

Sorry for my English

Thank you.

答:
Poll

You can set browser to check servers for updates with given interval. I have added couple of code samples how to use poll interval for this.

For example, If you want the browser to update every 30 seconds then you can enable polling like this:

```<code>MyUI ui = getMyUi();
ui.setPollInterval(30000);
if (ui.isPollListenerRegistered()) {
    Registration r = ui.addPollListener(this::reloadFromDatabase);
    ui.setPollRegistration(r);
}
</code>```

Setting pollInterval to value greater than -1 makes browser to call server with the given delay. Adding a poll listener allows you to notice these checks on server and load from database.

If only 1 page needs to refresh like this then add navigation listener as well which can set poll interval back to -1 so that other pages do not send unnecessary poll events.

```<code>MyUI ui = getMyUi();
ui.setPollInterval(-1);
if (ui.isPollListenerRegistered()) {
    ui.getPollRegistration().unregister();
}
</code>```

There is some documentation in Vaadin wiki but you do not need a background thread if you can read values from database.

https://vaadin.com/wiki?p_p_id=36

Push

Using Vaadin Push you can update data in the background and then request only clients that should be updated to refresh. This allows you to optimise requests because clients do not do unnecessary polling. You can also have single request to get data from web service and then update all clients with the same data.

You can read more in Vaadin documentation:

https://vaadin.com/docs/-/part/framework/advanced/advanced-push.html

I pushed an example project that shows how to use a single repeating background thread to do updated to data and then update contents of a grid with it. There are more than just a few lines of code for a complete push example so you can find the code here:

https://github.com/m1kah/vaadin-grid-push

Title: Updating data in Vaadin's grid

Body:
Poll

You can set browser to check servers for updates with given interval. I have added couple of code samples how to use poll interval for this.

For example, If you want the browser to update every 30 seconds then you can enable polling like this:

MyUI ui = getMyUi();
ui.setPollInterval(30000);
if (ui.isPollListenerRegistered()) {
    Registration r = ui.addPollListener(this::reloadFromDatabase);
    ui.setPollRegistration(r);
}

Setting pollInterval to value greater than -1 makes browser to call server with the given delay. Adding a poll listener allows you to notice these checks on server and load from database.

If only 1 page needs to refresh like this then add navigation listener as well which can set poll interval back to -1 so that other pages do not send unnecessary poll events.

MyUI ui = getMyUi();
ui.setPollInterval(-1);
if (ui.isPollListenerRegistered()) {
    ui.getPollRegistration().unregister();
}

There is some documentation in Vaadin wiki but you do not need a background thread if you can read values from database.

https://vaadin.com/wiki?p_p_id=36

Push

Using Vaadin Push you can update data in the background and then request only clients that should be updated to refresh. This allows you to optimise requests because clients do not do unnecessary polling. You can also have single request to get data from web service and then update all clients with the same data.

You can read more in Vaadin documentation:

https://vaadin.com/docs/-/part/framework/advanced/advanced-push.html

I pushed an example project that shows how to use a single repeating background thread to do updated to data and then update contents of a grid with it. There are more than just a few lines of code for a complete push example so you can find the code here:

https://github.com/m1kah/vaadin-grid-push


问:
Stripe no longer supports API requests made with TLS 1.0
I am using the Python Stripe package. I get the error Stripe no longer supports API requests made with TLS 1.0. I am using Python 2.7 on Mac. How do I fix this?

```<code># Set this to your Stripe secret key (use your test key!)
stripe.api_key = "sk_test_VAjLc9DN9BXMS3GPvFn5W92c"

# Get the credit card details
token = info['stripeToken']
amount = info['amount']
description = info['description']

# Create the charge on Stripe's servers - this will charge the user's card
charge = stripe.Charge.create(
    amount=amount,
    currency="usd",
    card=token,
    description=description
)
</code>```

```<code>Traceback (most recent call last):
  File "/Users/vertace/Desktop/payableApp-Sumup/payableAppServer.py", line 23, in pay
    description=description
  File "/Library/Python/2.7/site-packages/stripe/resource.py", line 466, in create
    response, api_key = requestor.request('post', url, params, headers)
  File "/Library/Python/2.7/site-packages/stripe/api_requestor.py", line 140, in request
    resp = self.interpret_response(rbody, rcode, rheaders)
  File "/Library/Python/2.7/site-packages/stripe/api_requestor.py", line 288, in interpret_response
    self.handle_api_error(rbody, rcode, resp, rheaders)
  File "/Library/Python/2.7/site-packages/stripe/api_requestor.py", line 163, in handle_api_error
    rheaders)
AuthenticationError: Request req_A4IYdjtgwILuyV: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.
</code>```

答:
```<code>pip install pyopenssl

pip uninstall requests

pip install requests
</code>```

Body:
I am using the Python Stripe package. I get the error Stripe no longer supports API requests made with TLS 1.0. I am using Python 2.7 on Mac. How do I fix this?

# Set this to your Stripe secret key (use your test key!)
stripe.api_key = "sk_test_VAjLc9DN9BXMS3GPvFn5W92c"

# Get the credit card details
token = info['stripeToken']
amount = info['amount']
description = info['description']

# Create the charge on Stripe's servers - this will charge the user's card
charge = stripe.Charge.create(
    amount=amount,
    currency="usd",
    card=token,
    description=description
)

Traceback (most recent call last):
  File "/Users/vertace/Desktop/payableApp-Sumup/payableAppServer.py", line 23, in pay
    description=description
  File "/Library/Python/2.7/site-packages/stripe/resource.py", line 466, in create
    response, api_key = requestor.request('post', url, params, headers)
  File "/Library/Python/2.7/site-packages/stripe/api_requestor.py", line 140, in request
    resp = self.interpret_response(rbody, rcode, rheaders)
  File "/Library/Python/2.7/site-packages/stripe/api_requestor.py", line 288, in interpret_response
    self.handle_api_error(rbody, rcode, resp, rheaders)
  File "/Library/Python/2.7/site-packages/stripe/api_requestor.py", line 163, in handle_api_error
    rheaders)
AuthenticationError: Request req_A4IYdjtgwILuyV: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.


问:
Communications link failure due to: java.io.EOFException
My webapp is running on Tomcat 5.5, I declared the datasource in web.xml:

```<code><resource-ref>
    <res-ref-name>jdbc/OrdiniWebDS</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</code>```

In context.xml (tomcat conf):

```<code><Resource
  auth="Container"
  driverClassName="com.mysql.jdbc.Driver"
  maxActive="100"
  maxIdle="30"
  maxWait="10000"
  name="jdbc/OrdiniWebDS"
  password="[mypassword]"
  type="javax.sql.DataSource"
  url="jdbc:mysql://[myHost:port]/ordiniweb"
  username="[myusername]"
 />
</code>```

The database is a MySql 5.0.
Everything works well except that sometimes, after several hours of "unuse", at first access I got this Exception:

```<code>com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.io.EOFException

STACKTRACE:

java.io.EOFException
 at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1956)
 at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2368)
 at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2867)
 at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
 at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
 at com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
 at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
 at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
 at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
 at com.blasetti.ordiniweb.dao.OrdiniDAO.caricaOrdine(OrdiniDAO.java:263)
...
** END NESTED EXCEPTION **

Last packet sent to the server was 0 ms ago.
 com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2579)
 com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2867)
 com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
 com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
 com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
 com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
 com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
 org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
 com.blasetti.ordiniweb.dao.OrdiniDAO.caricaOrdine(OrdiniDAO.java:263)
...
</code>```

I need to refresh and it works well again. Any idea? Thanks.

答:
MySQL drops unused connections after a while because it assumes that the other side forgot to close it.

What you need to do is to configure a check that Tomcat should apply before it reuses a pooled connection. To do this, add ?autoReconnect=true&useUnicode=true&characterEncoding=utf8 to the end of the URL and add validationQuery="Select 1" to the Resource element:

```<code><Resource
  auth="Container"
  driverClassName="com.mysql.jdbc.Driver"
  maxActive="100"
  maxIdle="30"
  maxWait="10000"
  name="jdbc/OrdiniWebDS"
  password="[mypassword]"
  type="javax.sql.DataSource"
  url="jdbc:mysql://[myHost:port]/ordiniweb?autoReconnect=true&useUnicode=true&characterEncoding=utf8"
  username="[myusername]"
  validationQuery="Select 1"
 />
</code>```

[EDIT] This page gives more details: Configuring a MySQL Datasource in Apache Tomcat

Body:
My webapp is running on Tomcat 5.5, I declared the datasource in web.xml:

<resource-ref>
    <res-ref-name>jdbc/OrdiniWebDS</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

In context.xml (tomcat conf):

<Resource
  auth="Container"
  driverClassName="com.mysql.jdbc.Driver"
  maxActive="100"
  maxIdle="30"
  maxWait="10000"
  name="jdbc/OrdiniWebDS"
  password="[mypassword]"
  type="javax.sql.DataSource"
  url="jdbc:mysql://[myHost:port]/ordiniweb"
  username="[myusername]"
 />

The database is a MySql 5.0.
Everything works well except that sometimes, after several hours of "unuse", at first access I got this Exception:

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.io.EOFException

STACKTRACE:

java.io.EOFException
 at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1956)
 at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2368)
 at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2867)
 at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
 at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
 at com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
 at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
 at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
 at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
 at com.blasetti.ordiniweb.dao.OrdiniDAO.caricaOrdine(OrdiniDAO.java:263)
...
** END NESTED EXCEPTION **

Last packet sent to the server was 0 ms ago.
 com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2579)
 com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2867)
 com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
 com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
 com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
 com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
 com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
 org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
 com.blasetti.ordiniweb.dao.OrdiniDAO.caricaOrdine(OrdiniDAO.java:263)
...

I need to refresh and it works well again. Any idea? Thanks.

Body:
MySQL drops unused connections after a while because it assumes that the other side forgot to close it.

What you need to do is to configure a check that Tomcat should apply before it reuses a pooled connection. To do this, add ?autoReconnect=true&useUnicode=true&characterEncoding=utf8 to the end of the URL and add validationQuery="Select 1" to the Resource element:

<Resource
  auth="Container"
  driverClassName="com.mysql.jdbc.Driver"
  maxActive="100"
  maxIdle="30"
  maxWait="10000"
  name="jdbc/OrdiniWebDS"
  password="[mypassword]"
  type="javax.sql.DataSource"
  url="jdbc:mysql://[myHost:port]/ordiniweb?autoReconnect=true&useUnicode=true&characterEncoding=utf8"
  username="[myusername]"
  validationQuery="Select 1"
 />

[EDIT] This page gives more details: Configuring a MySQL Datasource in Apache Tomcat


问:
Update doors attributes by dxl script giving input csv file
Update doors attributes by dxl script giving input csv file.
I want to take values from csv file and want to update doors attribute  with same using dxl script</p>

答: Doors can already do that. File->import->spreadsheet.</p>


问:
NullPointerException with custom font in android
I am getting this error on using a custom font. I have tried using the code in MainActivity and the Respective xml activity(Enquiry) too ( in this case there's no error but the font wont apply).

MainActivity

```<code>public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    WebView webView;
   TextView tv_appname;
    Typeface typeface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String fontpath="font/batman.ttf";
        tv_appname=(TextView)findViewById(R.id.tv_appname);
        typeface= Typeface.createFromAsset(getAssets(),fontpath);
        tv_appname.setTypeface(typeface);
</code>```

Acitivity Enquiry(In which the text is placed whose font I want to change)

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    tools:context="mayank2511.galgotiasuniversity.EnquiryActivity"
    android:id="@+id/nav_enq"
    android:paddingLeft="20dp"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enquiry Form"
        android:textSize="34sp"
        android:textColor="#fff"
        android:id="@+id/tv_appname"
        android:layout_marginTop="10dp"
        android:gravity="center"/>
</code>```

Enquiry Activity (incase it helps- it's commented rn)

```<code>public class EnquiryActivity extends AppCompatActivity {
   /* TextView tv_appname;
    Typeface typeface; */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enquiry);
        /*String fontpath="font/batman.ttf";
        tv_appname=(TextView)findViewById(R.id.tv_appname);
        typeface= Typeface.createFromAsset(getAssets(),fontpath);
        tv_appname.setTypeface(typeface);
        getSupportActionBar().hide();*/
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
}
</code>```

Font Directory and main activity

答:
Did you try to debug or check the stack trace to see which line exactly throws the NPE?

Other than tv_appname.setTypeface(typeface) (which will not throw a NPE if you're using the layout you provided), I see only one line that could throw a NPE and that is getSupportActionBar().hide(). You should always check if the action bar is not null first.

Body:
I am getting this error on using a custom font. I have tried using the code in MainActivity and the Respective xml activity(Enquiry) too ( in this case there's no error but the font wont apply).

MainActivity

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    WebView webView;
   TextView tv_appname;
    Typeface typeface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String fontpath="font/batman.ttf";
        tv_appname=(TextView)findViewById(R.id.tv_appname);
        typeface= Typeface.createFromAsset(getAssets(),fontpath);
        tv_appname.setTypeface(typeface);

Acitivity Enquiry(In which the text is placed whose font I want to change)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    tools:context="mayank2511.galgotiasuniversity.EnquiryActivity"
    android:id="@+id/nav_enq"
    android:paddingLeft="20dp"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enquiry Form"
        android:textSize="34sp"
        android:textColor="#fff"
        android:id="@+id/tv_appname"
        android:layout_marginTop="10dp"
        android:gravity="center"/>

Enquiry Activity (incase it helps- it's commented rn)

public class EnquiryActivity extends AppCompatActivity {
   /* TextView tv_appname;
    Typeface typeface; */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enquiry);
        /*String fontpath="font/batman.ttf";
        tv_appname=(TextView)findViewById(R.id.tv_appname);
        typeface= Typeface.createFromAsset(getAssets(),fontpath);
        tv_appname.setTypeface(typeface);
        getSupportActionBar().hide();*/
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
}

Font Directory and main activity


问:
Determine element is at bottom of viewport and add class to it?
need some help here. I need to determine when a certain element is at bottom position of the viewport and then to add fixed class to it. So on scroll down add class when element is at bottom 0 and remove class when i scroll back up. </p>

```<code>$(window).scroll(function() {
            var $el = $('.content-btn-row');
            if ($($el).position().top + $($el).height()) {
                console.log("bottom!");
                $(".content-btn-row").addClass("fixed");
            } else {
                $(".scontent-btn-row").removeClass("fixed");
            }
        });
</code>```

答:
IMO we should take into account inner height of a window's content area (it can be different that window height) and check if document has been scrolled.

window.innerHeight - returns the inner height of a window's content area

window.pageYOffset - returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window

If the element is below viewport at the beginning this code should be ok:

```<code>var elem = window.innerHeight + $($el).height(); //position of the element
var winScroll = window.innerHeight + window.pageYOffset; //viewport height + scroll
if (elem) >= (winScroll) {
            console.log("bottom!");
                $(".content-btn-row").addClass("fixed");
            } else {
                $(".scontent-btn-row").removeClass("fixed");
            }
}
</code>```

and it will be better to check if there is a class "fixed" with hasClass before we add or remove it.

Body:
need some help here. I need to determine when a certain element is at bottom position of the viewport and then to add fixed class to it. So on scroll down add class when element is at bottom 0 and remove class when i scroll back up.

$(window).scroll(function() {
            var $el = $('.content-btn-row');
            if ($($el).position().top + $($el).height()) {
                console.log("bottom!");
                $(".content-btn-row").addClass("fixed");
            } else {
                $(".scontent-btn-row").removeClass("fixed");
            }
        });

Body:
IMO we should take into account inner height of a window's content area (it can be different that window height) and check if document has been scrolled.

window.innerHeight - returns the inner height of a window's content area

window.pageYOffset - returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window

If the element is below viewport at the beginning this code should be ok:

var elem = window.innerHeight + $($el).height(); //position of the element
var winScroll = window.innerHeight + window.pageYOffset; //viewport height + scroll
if (elem) >= (winScroll) {
            console.log("bottom!");
                $(".content-btn-row").addClass("fixed");
            } else {
                $(".scontent-btn-row").removeClass("fixed");
            }
}

and it will be better to check if there is a class "fixed" with hasClass before we add or remove it.


问:
Some strings in a array match another array
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}
</code>```

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

答:
I'm not quite sure what your looking for here.

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]
</code>```

If you want to know if verifiedUsers and usersInData have any elements in common.

```<code>if !Set(verifiedUsers).isDisjoint(with: usersInData) {
    print("special user")
} else {
    print("regular user")
}
</code>```

If you want to know if every element in verifiedUsers is in usersInData

```<code>if Set(verifiedUsers).isSubset(of: usersInData) {
    print("special user")
} else {
    print("regular user")
}
</code>```

or

```<code>if Set(usersInData).isSuperset(of: verifiedUsers) {
    print("special user")
} else {
    print("regular user")
}
</code>```

If you want to know if usersInData contains the subsequence verifiedUsers, then that's a bit trickery.

```<code>for i in usersInData.startIndex ..< usersInData.endIndex - verifiedUsers.count {
    if verifiedUsers.elementsEqual(usersInData[i ..< i + verifiedUsers.count]) {
        print("special user")
        break
    }
}
</code>```

I'm sure there is a better answer for the subsequence problem.

UPDATE

Inspired by @iLandes API, I added wrapped my subsequence test.

```<code>extension Array where Element: Equatable {
    func hasSubsequence(_ other: Array) -> Bool {
        for i in startIndex ..< endIndex - other.count {
            if other.elementsEqual(self[i ..< i + other.count]) {
                return true
            }
        }

        return false
    }
}

if usersInData.hasSubsequence(verifiedUsers) {
    print("special user")
} else {
    print("regular user")
}
</code>```

Body:
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

Body:
I'm not quite sure what your looking for here.

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

If you want to know if verifiedUsers and usersInData have any elements in common.

if !Set(verifiedUsers).isDisjoint(with: usersInData) {
    print("special user")
} else {
    print("regular user")
}

If you want to know if every element in verifiedUsers is in usersInData

if Set(verifiedUsers).isSubset(of: usersInData) {
    print("special user")
} else {
    print("regular user")
}

or

if Set(usersInData).isSuperset(of: verifiedUsers) {
    print("special user")
} else {
    print("regular user")
}

If you want to know if usersInData contains the subsequence verifiedUsers, then that's a bit trickery.

for i in usersInData.startIndex ..< usersInData.endIndex - verifiedUsers.count {
    if verifiedUsers.elementsEqual(usersInData[i ..< i + verifiedUsers.count]) {
        print("special user")
        break
    }
}

I'm sure there is a better answer for the subsequence problem.

UPDATE

Inspired by @iLandes API, I added wrapped my subsequence test.

extension Array where Element: Equatable {
    func hasSubsequence(_ other: Array) -> Bool {
        for i in startIndex ..< endIndex - other.count {
            if other.elementsEqual(self[i ..< i + other.count]) {
                return true
            }
        }

        return false
    }
}

if usersInData.hasSubsequence(verifiedUsers) {
    print("special user")
} else {
    print("regular user")
}


问:
Angular - How to sort by last name pipe
For my Angular project, I want to display the EmpID values in a combo box and have them sorted by the last name.

Here's an html snippet where I'm trying to implement the pipe.

    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{emp.EmpID | orderByLast}}</option>
    </select>
```

<p>and here's  my orderByLast.pipe.ts :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
    transform(array: Array<string>): Array<string> {
        array.sort((a: any, b: any) => {
            if (a < b) {
                return -1;
            }
            else if (a > b) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return array;
    }
}</code>```

and here's my emp-info.ts array:

export class EmpInfo {
    EmpKey: number;
    EmpID: string;
    Firstname: string;
    LastName: string;
    EmpStat: string;
    StartDate: Date;
    AdjustedStart: Date;
    Anniversary: number;
    PTOYear: number;
    STDLTD: number;
    Uncharged: number;
    ETOEarned: number;
    ETORequests: number;
    ETORemaining: number;
    PTOBase: number;
    PTOCarry: number;
    PTOBorrowed: number;
    PTOBalance: number;
    PTORequests: number;
    PTORemaining: number;
}```

答:
You need to implement a transform function:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
  transform() { // add your object as a parameter to transform()
    //write your code to do the sort
  }
}
</code>```

See the 'Custom Pipes' section here: https://angular.io/docs/ts/latest/guide/pipes.html (Please note that as @torazaburo pointed it out it's not recommended to do sorts using pipes which is also explained in the link under the 'Appendix: No FilterPipe or OrderByPipe' section.)

Title: Angular - How to sort by last name pipe

Body:
For my Angular project, I want to display the EmpID values in a combo box and have them sorted by the last name.

Here's an html snippet where I'm trying to implement the pipe.

    <select id="empName" [(ngModel)]="selectedEmployee">
      <option selected="selected" disabled>Employee Name...</option>
      <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{emp.EmpID | orderByLast}}</option>
    </select>

and here's  my orderByLast.pipe.ts :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
    transform(array: Array<string>): Array<string> {
        array.sort((a: any, b: any) => {
            if (a  b) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return array;
    }
}

and here's my emp-info.ts array:

export class EmpInfo {
    EmpKey: number;
    EmpID: string;
    Firstname: string;
    LastName: string;
    EmpStat: string;
    StartDate: Date;
    AdjustedStart: Date;
    Anniversary: number;
    PTOYear: number;
    STDLTD: number;
    Uncharged: number;
    ETOEarned: number;
    ETORequests: number;
    ETORemaining: number;
    PTOBase: number;
    PTOCarry: number;
    PTOBorrowed: number;
    PTOBalance: number;
    PTORequests: number;
    PTORemaining: number;
}

Body:
You need to implement a transform function:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'orderByLast' })

export class OrderByLast implements PipeTransform {
  transform() { // add your object as a parameter to transform()
    //write your code to do the sort
  }
}

See the 'Custom Pipes' section here: https://angular.io/docs/ts/latest/guide/pipes.html (Please note that as @torazaburo pointed it out it's not recommended to do sorts using pipes which is also explained in the link under the 'Appendix: No FilterPipe or OrderByPipe' section.)


问:
Xampp localhost not working
I am running laravel on xampp and I have problem with accessing pages,
http://localhost/laravel/public/ I get a login page which is good
however when I go for example http://localhost/laravel/public/smokeyard

I get 404 error with The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

Route:

```<code>Route::get('smokeyard', 'GuzzleController@smokeyard');
</code>```

Controller:

```<code>function smokeyard(){
    return view('smokeyard');
}
</code>```

All my views are located in resources folder.

答:
Run php artisan serve and access your server at http://localhost:8000. Your routes should work fine then.

You can't access your laravel application routes straight away through the folder structure with xampp. You need to setup the web root to point to the public folder and access localhost or run the laravel server and use it. This is because the url rewriting would fail when you access the routes in laravel the way you do.

Title: Xampp localhost not working

Body:
I am running laravel on xampp and I have problem with accessing pages,
http://localhost/laravel/public/ I get a login page which is good
however when I go for example http://localhost/laravel/public/smokeyard

I get 404 error with The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

Route:

Route::get('smokeyard', 'GuzzleController@smokeyard');

Controller:

function smokeyard(){
    return view('smokeyard');
}

All my views are located in resources folder.


问:
Undefined method `html_safe?' error when using rails-ckeditor with formtastic
I'm trying to get the rails-ckeditor gem to work. I followed the instructions on the README.
But I get this error

```<code>undefined method `html_safe?' for #<String:0xb6b6d080>
</code>```

This is my formtastic form code:

```<code><%= f.input :content, :as => :ckeditor %>
</code>```

Any ideas? Thanks!

UPDATE
I'm using Rails 2.3.8. And here's the stack trace.

```<code>  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/safe_buffer.rb:6:in `<<'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/view_helper.rb:52:in `ckeditor_textarea'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `send'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `ckeditor_input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `inline_input_for'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `map'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `input'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:4
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:2:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:1:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:10
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:3:in `_run_erb_app47views47articles47new46html46erb'
</code>```

答:
Do you have a stack trace? Based on the error, I'm assuming that the plugin load order is causing a string to not be instantiated with SafeBuffer support (which also leads me to believe you're using Rails 2).

Can you provide some context?

Body:
I'm trying to get the rails-ckeditor gem to work. I followed the instructions on the README.
But I get this error

undefined method `html_safe?' for #<String:0xb6b6d080>

This is my formtastic form code:

<%= f.input :content, :as => :ckeditor %>

Any ideas? Thanks!

UPDATE
I'm using Rails 2.3.8. And here's the stack trace.

  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/safe_buffer.rb:6:in `<<'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/view_helper.rb:52:in `ckeditor_textarea'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `send'
  /usr/lib/ruby/gems/1.8/gems/ckeditor-3.4.3/lib/ckeditor/formtastic.rb:9:in `ckeditor_input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:1281:in `inline_input_for'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `send'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:109:in `input'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `map'
  /usr/lib/ruby/gems/1.8/gems/formtastic-1.1.0/lib/formtastic.rb:108:in `input'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:4
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:2:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/_form.html.erb:1:in `_run_erb_app47views47articles47_form46html46erb_locals_form_object'
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:10
  /home/shreyas/repos/citymgmt/app/views/articles/new.html.erb:3:in `_run_erb_app47views47articles47new46html46erb'