问:
Error "Request failed with status code 404"
I'm running a "universal" Nuxt project on NGINX+MYSQL+PHP Ubuntu 18.04 server. Some pages use Axios to get data from a database (JSON files created by PHP). The project is working fine on dev and production mode. Server using nginx as a reverse proxy (localhost:3000 -> localhost:80).

But after I installed HTTPS and SSL certificates (DigitalOcean manual: How To Secure Nginx with Let's Encrypt on Ubuntu 18.04) server starts to show error in production mode:

```<code> ERROR  Request failed with status code 404

  at createError (node_modules/axios/lib/core/createError.js:16:15)
  at settle (node_modules/axios/lib/core/settle.js:18:12)
  at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:201:11)
  at IncomingMessage.emit (events.js:194:15)
  at IncomingMessage.EventEmitter.emit (domain.js:441:20)
  at endReadableNT (_stream_readable.js:1125:12)
  at process._tickCallback (internal/process/next_tick.js:63:19)
</code>```

I tried an example of nginx configuration from Nuxt official site. But Error keep appears.

My config file /etc/nginx/site-available/web_site.com

```<code>map $sent_http_content_type $expires {
    "text/html"                 epoch;
    "text/html; charset=utf-8"  epoch;
    default                     off;
}

server {
    root /var/www/html;
    server_name web_site.com www.web_site.com;
    gzip            on;
    gzip_types      text/plain application/xml text/css application/javascript;
    gzip_min_length 1000;
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/web_site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/web_site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location /basemysql {
    auth_basic "Admin Login";
        auth_basic_user_file /etc/nginx/pma_pass;
    }

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }
}

server {
    if ($host = www.web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        server_name web_site.com www.web_site.com;
    return 404; # managed by Certbot

}
</code>```

The app fully functional until you try to reload it.  An error appears every time I'm trying to reload any page that has Axios.

答:
I found the problem. Redirection from HTTP to HTTPS causing the error.
I deleted these configurations and it works fine. </p>

```<code>server {
    if ($host = www.web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        server_name web_site.com www.web_site.com;
    return 404; # managed by Certbot

}
</code>```

Body:
I'm running a "universal" Nuxt project on NGINX+MYSQL+PHP Ubuntu 18.04 server. Some pages use Axios to get data from a database (JSON files created by PHP). The project is working fine on dev and production mode. Server using nginx as a reverse proxy (localhost:3000 -> localhost:80).

But after I installed HTTPS and SSL certificates (DigitalOcean manual: How To Secure Nginx with Let's Encrypt on Ubuntu 18.04) server starts to show error in production mode:

 ERROR  Request failed with status code 404

  at createError (node_modules/axios/lib/core/createError.js:16:15)
  at settle (node_modules/axios/lib/core/settle.js:18:12)
  at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:201:11)
  at IncomingMessage.emit (events.js:194:15)
  at IncomingMessage.EventEmitter.emit (domain.js:441:20)
  at endReadableNT (_stream_readable.js:1125:12)
  at process._tickCallback (internal/process/next_tick.js:63:19)

I tried an example of nginx configuration from Nuxt official site. But Error keep appears.

My config file /etc/nginx/site-available/web_site.com

map $sent_http_content_type $expires {
    "text/html"                 epoch;
    "text/html; charset=utf-8"  epoch;
    default                     off;
}

server {
    root /var/www/html;
    server_name web_site.com www.web_site.com;
    gzip            on;
    gzip_types      text/plain application/xml text/css application/javascript;
    gzip_min_length 1000;
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/web_site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/web_site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location /basemysql {
    auth_basic "Admin Login";
        auth_basic_user_file /etc/nginx/pma_pass;
    }

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }
}

server {
    if ($host = www.web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        server_name web_site.com www.web_site.com;
    return 404; # managed by Certbot

}

The app fully functional until you try to reload it.  An error appears every time I'm trying to reload any page that has Axios.

Body:
I found the problem. Redirection from HTTP to HTTPS causing the error.
I deleted these configurations and it works fine.

server {
    if ($host = www.web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = web_site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        server_name web_site.com www.web_site.com;
    return 404; # managed by Certbot

}


来源: stackexchange

问:
Buffered level of music showing in seekbar

Hi there. As you can see i want to show buffered level of media that stream to user in android music player.
The solution i imagine for this issue is that:

Should i create a seekbar and a progressbar with transparent background and overlap progressbar to seek bar, whereas progreesbar showing buffered level of music.

but im not sure about this strategy. is anyone to help me for best way to reaching the goal at this issue.

答:
Just because setting percentage directly doesn't work. Here is the code that worked for me.

```<code>mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
            double per = percent * 1.00;
            per = (per / 100);
            double f = (seekBar.getMax() * 1.00);
            f = f * per;
            if (percent < binder.seekBar.getMax()) {
                seekBar.setSecondaryProgress((int) f);
            }
        }
    });
</code>```

These int to double conversions are necessary because int division by 100 will give you 0 if result was to be 0.12 or 0.xx.

ContentLicense: CC BY-SA 3.0

Body:
Just because setting percentage directly doesn't work. Here is the code that worked for me.

mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
            double per = percent * 1.00;
            per = (per / 100);
            double f = (seekBar.getMax() * 1.00);
            f = f * per;
            if (percent < binder.seekBar.getMax()) {
                seekBar.setSecondaryProgress((int) f);
            }
        }
    });

These int to double conversions are necessary because int division by 100 will give you 0 if result was to be 0.12 or 0.xx.

ContentLicense: CC BY-SA 4.0


问:
How to reload code when HTTP server is running?
When starting an http server using HTTP.serve there is apparently no way to reload the code that is actually handling the HTTP request.
In the example below I would like to have the modifications in my_httphandler taken into account without having to restart the server.
For the moment I need to stop the server from the REPL by pressing CTRL+C twice and then run the script again.

Is there a workaround ?

```<code>module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end
</code>```

答:
I'm not sure whether Mux caches handlers. As long as it does not, this should work:</p>

```<code>module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const functionref = Any[my_httphandler]

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", functionref[1])

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end

function newhandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world 2")
end

MyModule.functionref[1] = newhandler
</code>```

Body:
When starting an http server using HTTP.serve there is apparently no way to reload the code that is actually handling the HTTP request.
In the example below I would like to have the modifications in my_httphandler taken into account without having to restart the server.
For the moment I need to stop the server from the REPL by pressing CTRL+C twice and then run the script again.

Is there a workaround ?

module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end

Body:
I'm not sure whether Mux caches handlers. As long as it does not, this should work:

module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const functionref = Any[my_httphandler]

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", functionref[1])

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end

function newhandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world 2")
end

MyModule.functionref[1] = newhandler


问:
What assembly is SerializeableAttribute in?
I'm trying to set up serialization for a class. When I added:

```<code>[Serializeable]
</code>```

I got the error:
"The type or namespace name could not be found (are you missing a using directive or an assembly reference?)"

I added System.Runtime.Serialization.Formatters.Soap and System.Runtime.Serialization but they didn't work. I also tried to find the other assemblies listed on the documentation page. I only found mscorlib in the VS Reference Manager and it was already added.

I wrote the code like so:

```<code>[Serializeable]
public class Test { }
</code>```

Edit: I also tried:

```<code>[Serializeable()]
public class Test { }
</code>```

I expected the code to compile without errors.

Edit: fixed wrong name for an assembly

答:
Per MSDN, the SerializableAttribute type can be found in the following assemblies:

System.Runtime.Serialization.Formatters.dll

mscorlib.dll

netstandard.dll

System.Runtime.dll

EDIT

It may be easier to try the below.  There may be namespace conflicts.

```<code>[System.SerializableAttribute]
public class Test {}
</code>```

Body:
I'm trying to set up serialization for a class. When I added:

[Serializeable]

I got the error:
"The type or namespace name could not be found (are you missing a using directive or an assembly reference?)"

I added System.Runtime.Serialization.Formatters.Soap and System.Runtime.Serialization but they didn't work. I also tried to find the other assemblies listed on the documentation page. I only found mscorlib in the VS Reference Manager and it was already added.

I wrote the code like so:

[Serializeable]
public class Test { }

Edit: I also tried:

[Serializeable()]
public class Test { }

I expected the code to compile without errors.

Edit: fixed wrong name for an assembly

Body:
Per MSDN, the SerializableAttribute type can be found in the following assemblies:

System.Runtime.Serialization.Formatters.dll

mscorlib.dll

netstandard.dll

System.Runtime.dll

EDIT

It may be easier to try the below.  There may be namespace conflicts.

[System.SerializableAttribute]
public class Test {}


问:
Java: Why internal class has to be static?
I know that internal class has to be static because will link between public and internal classes and internal class will be created all times that created public classes.
And my question how to check it?
I mean write some simple application and make some loop for creating objects and see that objects do not deleted by GC in some profiler, Can I to do something like that nad some one done it?
Thanks.</p>

答:
internal class will be created all times that created public classes

If you mean that an instance of the inner class will always be created when you create an instance of the outer class, that is not true.

You can have outer instances with no attached inner instances, and the same outer instance can have any number of attached inner instances (and of different inner classes, too).

It is (somewhat) the opposite rather: When you create an instance of the (non-static) inner class, that instance will contain a reference to its outer instance (but that is a reference to an already existing object, not a new one: You cannot create the inner instance without having the outer one first).


问:
EC2 SSH connection broken pipe; cannot reconnect
I successfully connected to an EC2 instance like so:

```<code>ssh -i .ssh/ec2docker.cer user@SOMEIP
</code>```

After about an hour of using the instance, I leave and come back further two hours to this:

```<code>$ packet_write_wait: Connection to xx port 22: Broken pipe
</code>```

Now, when trying to connect, nothing happens at all:

```<code>OpenSSH_7.9p1, OpenSSL 1.1.1b FIPS  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final'
debug2: match not found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only)
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug1: configuration requests final Match pass
debug1: re-parsing configuration
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final'
debug2: match found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolving "xxxx" port 22
debug2: ssh_connect_direct
debug1: Connecting to xxx [xx] port 22.
debug1: Connection established.
debug1: identity file .ssh/ec2docker.cer type -1
debug1: identity file .ssh/ec2docker.cer-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9
</code>```

ssh does not terminate or give an error. The EC2 monitor shows that the instance is running with non-zero CPU utilization (around 25%) and non-zero network read and write.

答:
Have you check the public ip of your EC2 in AWS?

It seems like a reboot and if you do not have and "Elastic IP", now you have a new public ip.

Body:
I successfully connected to an EC2 instance like so:

ssh -i .ssh/ec2docker.cer user@SOMEIP

After about an hour of using the instance, I leave and come back further two hours to this:

$ packet_write_wait: Connection to xx port 22: Broken pipe

Now, when trying to connect, nothing happens at all:

OpenSSH_7.9p1, OpenSSL 1.1.1b FIPS  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final'
debug2: match not found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only)
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug1: configuration requests final Match pass
debug1: re-parsing configuration
debug1: Reading configuration data /etc/ssh/ssh_config
debug3: /etc/ssh/ssh_config line 52: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0
debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf
debug2: checking match for 'final all' host xxx originally xxx
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final'
debug2: match found
debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1
debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config
debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-]
debug3: kex names ok: [curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1]
debug2: resolving "xxxx" port 22
debug2: ssh_connect_direct
debug1: Connecting to xxx [xx] port 22.
debug1: Connection established.
debug1: identity file .ssh/ec2docker.cer type -1
debug1: identity file .ssh/ec2docker.cer-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9

ssh does not terminate or give an error. The EC2 monitor shows that the instance is running with non-zero CPU utilization (around 25%) and non-zero network read and write.


问:
OSX - Compiling training tools for Tesseract 4.0 - pango libraries not found
I am having trouble getting the configure script to recognise the pango libraries i have installed via Homebrew, which are dependancies for the training tools. So far, I've followed all steps detailed here:

https://github.com/tesseract-ocr/tesseract/issues/1453

and here:

https://github.com/tesseract-ocr/tesseract/wiki/Compiling#macos

and after running the configure script, I keep on getting these warnings in the output:

checking for pango >= 1.22.0... no

configure: WARNING: pango 1.22.0 or higher is required, but was not
  found.

configure: WARNING: Training tools WILL NOT be built.

configure: WARNING: Try to install libpango1.0-dev package.

checking for cairo... no

configure: WARNING: Training tools WILL NOT be built because of
  missing  cairo library.

configure: WARNING: Try to install libcairo-dev?? package.

The libraries are located where they should be, at /usr/local/Cellar/pango/1.42.4_1

I've tried running the configure script as per the instructions above:

```<code>./configure CPPFLAGS=-I/usr/local/opt/icu4c/include LDFLAGS=-L/usr/local/opt/icu4c/lib
</code>```

as well as trying to add the path to the linking flags:

```<code>./configure LDFLAGS="-L/usr/local/opt/icu4c/lib -L/usr/local/Cellar/pango/1.42.4_1/lib" CPPFLAGS="-I/usr/local/opt/icu4c/include"
</code>```

and I still can't get the script to see the libraries.

Thanks in advance for any advice on how to solve this.

答:
This is the most elegant solution to the problem I found:

```<code>brew install cairo pango icu4c autoconf libffi libarchive libpng
export PKG_CONFIG_PATH=\
$(brew --prefix)/lib/pkgconfig:\
$(brew --prefix)/opt/libarchive/lib/pkgconfig:\
$(brew --prefix)/opt/icu4c/lib/pkgconfig:\
$(brew --prefix)/opt/libffi/lib/pkgconfig:\
$(brew --prefix)/opt/libpng/lib/pkgconfig
./configure
</code>```

https://github.com/tesseract-ocr/tesseract/wiki/TrainingTesseract-4.00#on-macos-mojave-with-homebrew

Body:
I am having trouble getting the configure script to recognise the pango libraries i have installed via Homebrew, which are dependancies for the training tools. So far, I've followed all steps detailed here:

https://github.com/tesseract-ocr/tesseract/issues/1453

and here:

https://github.com/tesseract-ocr/tesseract/wiki/Compiling#macos

and after running the configure script, I keep on getting these warnings in the output:

checking for pango >= 1.22.0... no

configure: WARNING: pango 1.22.0 or higher is required, but was not
  found.

configure: WARNING: Training tools WILL NOT be built.

configure: WARNING: Try to install libpango1.0-dev package.

checking for cairo... no

configure: WARNING: Training tools WILL NOT be built because of
  missing  cairo library.

configure: WARNING: Try to install libcairo-dev?? package.

The libraries are located where they should be, at /usr/local/Cellar/pango/1.42.4_1

I've tried running the configure script as per the instructions above:

./configure CPPFLAGS=-I/usr/local/opt/icu4c/include LDFLAGS=-L/usr/local/opt/icu4c/lib

as well as trying to add the path to the linking flags:

./configure LDFLAGS="-L/usr/local/opt/icu4c/lib -L/usr/local/Cellar/pango/1.42.4_1/lib" CPPFLAGS="-I/usr/local/opt/icu4c/include"

and I still can't get the script to see the libraries.

Thanks in advance for any advice on how to solve this.

Body:
This is the most elegant solution to the problem I found:

brew install cairo pango icu4c autoconf libffi libarchive libpng
export PKG_CONFIG_PATH=\
$(brew --prefix)/lib/pkgconfig:\
$(brew --prefix)/opt/libarchive/lib/pkgconfig:\
$(brew --prefix)/opt/icu4c/lib/pkgconfig:\
$(brew --prefix)/opt/libffi/lib/pkgconfig:\
$(brew --prefix)/opt/libpng/lib/pkgconfig
./configure

https://github.com/tesseract-ocr/tesseract/wiki/TrainingTesseract-4.00#on-macos-mojave-with-homebrew


问:
ChartKick throwing error "PG::GroupingError: ERROR:"
I've recently migrated my database from sqlite3 to postgreSQL for a rails app I've been working on. On one of my pages, I'm rendering a graph using "ChartKick". Prior to switching to postgreSQL my table and graph were functioning fine. Now the page fails and I get an error:

PG::GroupingError: ERROR:  column "stats.created_at" must appear in the >GROUP BY clause or be used in an aggregate function

I've used the Google and tried troubleshooting it a bit but cannot get my graph to function properly.

"<%= line_chart @stats.group(:date).sum(:weight) %>"

PG::GroupingError: ERROR:  column "stats.created_at" must appear in the GROUP BY clause or be used in an aggregate function
  LINE 1: ..."."user_id" = $1 GROUP BY "stats"."date" ORDER BY created_at...
                                                               ^
  : SELECT  SUM("stats"."weight") AS sum_weight, "stats"."date" AS stats_date FROM "stats" WHERE "stats"."user_id" = $1 GROUP BY "stats"."date" ORDER BY created_at DESC LIMIT $2 OFFSET $3

EDIT
Heres what I have in my controler to query the data:

# GET /stats.json
    def index
      @stats = current_user.stats.paginate(:page => params[:page], per_page: 5 ).order('created_at DESC')

    end

I'm also using the Ruby Gem "Paginate" for my table.

答:
SOLVED:

Postgres wasn't able to group the data because my code did not specify what data to get. by adding "current_user" to my ChartKick code, it was able to SELECT and render the data fine.

would fail

"<%= line_chart @stats.group(:date).sum(:weight) %>"<

Works!

"<%= line_chart current_user.stats.group(:date).sum(:weight), discrete: true %>"


问:
Python convert byte string to list of dictionaries based on newline
I have a string byte

```<code>data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4' # No \n at the end
</code>```

The result should be like

```<code>result = [
{"field1": "ra1", "field2": "rb1", "field3": "rc1"},
{"field1": "ra2", "field2": "rb2", "field3": "rc2"},
{"field1": "ra3", "field2": "rb3", "field3": "rc3"},
{"field1": "ra4", "field2": "rb4", "field3": "rc4"}
]
</code>```

I tried

```<code>result = csv.DictReader(data, fieldnames=('field1', 'field2', 'field3'))
</code>```

Please note that I'm not dealing with any CSV files here.

I know we need to pass file object as the first parameter to the above DictReader method to get the above result.

Is there any similar in-built method in python 3.6 to achieve my result?

Here I don't want to use loop since my data will be very huge.

答:
You can create a list of lists of all the values by splitting on \n and then ,

Then you can zip the keys with each value sublist to create your list of dictionaries

Hence the code will be

```<code>data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4'
keys = ['field1', 'field2', 'field3']

#Create list of lists for values
values  = [ item.split(',') for item in data.decode('utf-8').splitlines() ]
#[['ra1', 'rb1', 'rc1'], ['ra2', 'rb2', 'rc2'], ['ra3', 'rb3', 'rc3'], ['ra4', 'rb4', 'rc4']]

#Create result dictionary by zipping keys and values
result = [dict(zip(keys, value)) for value in values]
print(result)
</code>```

And the output will be

```<code>[{'field1': 'ra1', 'field2': 'rb1', 'field3': 'rc1'},
{'field1': 'ra2', 'field2': 'rb2', 'field3': 'rc2'},
{'field1': 'ra3', 'field2': 'rb3', 'field3': 'rc3'},
{'field1': 'ra4', 'field2': 'rb4', 'field3': 'rc4'}]
</code>```

Body:
I have a string byte

data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4' # No \n at the end

The result should be like

result = [
{"field1": "ra1", "field2": "rb1", "field3": "rc1"},
{"field1": "ra2", "field2": "rb2", "field3": "rc2"},
{"field1": "ra3", "field2": "rb3", "field3": "rc3"},
{"field1": "ra4", "field2": "rb4", "field3": "rc4"}
]

I tried

result = csv.DictReader(data, fieldnames=('field1', 'field2', 'field3'))

Please note that I'm not dealing with any CSV files here.

I know we need to pass file object as the first parameter to the above DictReader method to get the above result.

Is there any similar in-built method in python 3.6 to achieve my result?

Here I don't want to use loop since my data will be very huge.

Body:
You can create a list of lists of all the values by splitting on \n and then ,

Then you can zip the keys with each value sublist to create your list of dictionaries

Hence the code will be

data = b'ra1,rb1,rc1\nra2,rb2,rc2\nra3,rb3,rc3\nra4,rb4,rc4'
keys = ['field1', 'field2', 'field3']

#Create list of lists for values
values  = [ item.split(',') for item in data.decode('utf-8').splitlines() ]
#[['ra1', 'rb1', 'rc1'], ['ra2', 'rb2', 'rc2'], ['ra3', 'rb3', 'rc3'], ['ra4', 'rb4', 'rc4']]

#Create result dictionary by zipping keys and values
result = [dict(zip(keys, value)) for value in values]
print(result)

And the output will be

[{'field1': 'ra1', 'field2': 'rb1', 'field3': 'rc1'},
{'field1': 'ra2', 'field2': 'rb2', 'field3': 'rc2'},
{'field1': 'ra3', 'field2': 'rb3', 'field3': 'rc3'},
{'field1': 'ra4', 'field2': 'rb4', 'field3': 'rc4'}]


问:
How to delete dynamically loaded gameobjects from a List in Untiy?
I have a list that loads its content dynamically. The Elements of the List are buttons that are being transformed into gameobjects. For every object in the user list a new Element is created. Now I want to be able to delete the Element along with the button itself, when the button is pressed, where each Element has its own dynamically created delete button. I tried putting a box collider with an OnMouseDown Event, however onMouseDown is never called.</p>

```<code>public void ShowLectures()
{
    foreach (var course in selectedCourses)
    {
        AddMoreButton();
    }
}

public void AddMoreButton()
{
    GameObject button = (GameObject)Instantiate(prefabButton);
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);
}

public void OnMouseDown()
{
    Destroy(gameObject);
}
</code>```

答:
First of all OnMouseDown is not called on the created Button but in your case rather on the GameObject your script is attached to.

Then

```<code>Destroy(gameObject);
</code>```

the same way would destroy the GameObject your script is attached to, not the instantiated button GameObjects.

Since you commented that you are using a UI.Button component rather add it to the onClick event as a callback when the Button is instantiated :

```<code>public void AddMoreButton()
{
    GameObject button = (GameObject)Instantiate(prefabButton);
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);

    // get the Button on the button object or any child
    var buttonInstance = button.GetComponentInChildren<Button>();

    // add a callback to destroy the button gameObject
    // () => {} is a lambda expression
    buttonInstance.onClick.AddCallback(()=>{ Destroy(button); });
}
</code>```

A little hint: In case the Button is already on the same GameObject anyway you should rather change the prefab type itself to Button like e.g.

```<code>public Button prefabButton;
</code>```

and than simply use

```<code>public void AddMoreButton()
{
    Button button = Instantiate(prefabButton, panel.transform);
    button.gameObject.layer = 5;
    button.gameObject.SetActive(true);

    // add a callback to destroy the button gameObject
    // () => {} is a lambda expression
    button.onClick.AddListener(()=>{ Destroy(button.gameObject); });
}
</code>```

Body:
I have a list that loads its content dynamically. The Elements of the List are buttons that are being transformed into gameobjects. For every object in the user list a new Element is created. Now I want to be able to delete the Element along with the button itself, when the button is pressed, where each Element has its own dynamically created delete button. I tried putting a box collider with an OnMouseDown Event, however onMouseDown is never called.

public void ShowLectures()
{
    foreach (var course in selectedCourses)
    {
        AddMoreButton();
    }
}

public void AddMoreButton()
{
    GameObject button = (GameObject)Instantiate(prefabButton);
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);
}

public void OnMouseDown()
{
    Destroy(gameObject);
}

Body:
First of all OnMouseDown is not called on the created Button but in your case rather on the GameObject your script is attached to.

Then

Destroy(gameObject);

the same way would destroy the GameObject your script is attached to, not the instantiated button GameObjects.

Since you commented that you are using a UI.Button component rather add it to the onClick event as a callback when the Button is instantiated :

public void AddMoreButton()
{
    GameObject button = (GameObject)Instantiate(prefabButton);
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);

    // get the Button on the button object or any child
    var buttonInstance = button.GetComponentInChildren<Button>();

    // add a callback to destroy the button gameObject
    // () => {} is a lambda expression
    buttonInstance.onClick.AddCallback(()=>{ Destroy(button); });
}

A little hint: In case the Button is already on the same GameObject anyway you should rather change the prefab type itself to Button like e.g.

public Button prefabButton;

and than simply use

public void AddMoreButton()
{
    Button button = Instantiate(prefabButton, panel.transform);
    button.gameObject.layer = 5;
    button.gameObject.SetActive(true);

    // add a callback to destroy the button gameObject
    // () => {} is a lambda expression
    button.onClick.AddListener(()=>{ Destroy(button.gameObject); });
}


问:
Why are my variable values being deleted?
I am trying to extract substrings in C. I have an input to my function of a string (char command[]) and am taking out parts of it. Upon debugging my code, I notice that values (condition and accumulate) are being erased when I reach later parts of the function. Why is this? (See code below)

```<code>int multiply(char command[]) {
    char condition[5];
    memmove(condition, command, 4);
    condition[3] = '\0';
    char accumulate[2];
    memmove(accumulate, &command[4], 1);
    accumulate[2] = '\0';
    char set[2];
    memmove(set, &command[5], 1);
    set[2] = '\0';

    return EXIT_SUCCESS;
}
</code>```

According to the debugger, condition is erased when set is defined and accumulate is being erased upon EXIT_SUCCESS.

答:
condition is erased when set is defined because you don't use condition after you've defined set, so your compiler optimizes by storing the two in the same location.

accumulate is erased when you return from the function because it is a local variable.

Body:
I am trying to extract substrings in C. I have an input to my function of a string (char command[]) and am taking out parts of it. Upon debugging my code, I notice that values (condition and accumulate) are being erased when I reach later parts of the function. Why is this? (See code below)

int multiply(char command[]) {
    char condition[5];
    memmove(condition, command, 4);
    condition[3] = '\0';
    char accumulate[2];
    memmove(accumulate, &command[4], 1);
    accumulate[2] = '\0';
    char set[2];
    memmove(set, &command[5], 1);
    set[2] = '\0';

    return EXIT_SUCCESS;
}

According to the debugger, condition is erased when set is defined and accumulate is being erased upon EXIT_SUCCESS.


问:
EditText with bottom border only
I am trying to make a custom edit text that has only a bottom border. I have tried this code and set it as background:

```<code><item android:gravity="bottom">
        <shape android:shape="line">
            <stroke android:width="1dp" android:color="@color/lightGray"/>
            <padding android:left="12dp" android:right="12dp" android:top="12dp" android:bottom="12dp" />
        </shape>
    </item>
</code>```

and the border is exactly how I want it but it is placed in the middle of the edit text and not at the bottom. How can I solve this?

答:
can you check this, modify as per need </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="@dimen/minus10dp"
        android:right="@dimen/minus10dp"
        android:top="@dimen/minus10dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />

            <stroke
                android:width="@dimen/dp2"
                android:color="@color/orangey_red" />
        </shape>
    </item>
</layer-list>
</code>```

Title: EditText with bottom border only

Body:
I am trying to make a custom edit text that has only a bottom border. I have tried this code and set it as background:

<item android:gravity="bottom">
        <shape android:shape="line">
            <stroke android:width="1dp" android:color="@color/lightGray"/>
            <padding android:left="12dp" android:right="12dp" android:top="12dp" android:bottom="12dp" />
        </shape>
    </item>

and the border is exactly how I want it but it is placed in the middle of the edit text and not at the bottom. How can I solve this?

Body:
can you check this, modify as per need

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="@dimen/minus10dp"
        android:right="@dimen/minus10dp"
        android:top="@dimen/minus10dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />

            <stroke
                android:width="@dimen/dp2"
                android:color="@color/orangey_red" />
        </shape>
    </item>
</layer-list>


问:
How to code a if-statement for asking drinking age
I'm writing a code to determine if someone can enter a club and whether or not they can drink at the club. I was wondering if I am doing this right, and if there is a better way to write the code. Thanks.</p>

```<code>public class SoloJava {

    public static void main(String[] agrs) {
        int age = 17;
        if (age >= 18) {
            System.out.println("You can enter");
        }
        if (age < 18) {
            System.out.println("You can not enter");
        }
        if (age >= 21) {
            System.out.println("You can drink");
        } else if (age <= 21) {
            System.out.println("You can not drink");
        }
    }
}
</code>```

答:
noob here, trying to help. From what I understand there are 3 possibilities.

Can't enter (younger than 18 years old)

May enter but can't get a drink (younger than 21 but still over 18)

Can enter and have a drink (over 21 years old)

Therefore I think that it would be best to minimize the number of if statements.

```<code>public static void main(String[] args) {

    int age = 20;

    if (age<18){
        System.out.println("You cannot enter");
    }
    else if(age>=18 && age<=21){ //checks if his/her age is between 18 and 21
        System.out.println("You may enter but you cannot drink");
    }
    else{
        System.out.println("You may enter and have a drink");
    }

}
</code>```

Body:
I'm writing a code to determine if someone can enter a club and whether or not they can drink at the club. I was wondering if I am doing this right, and if there is a better way to write the code. Thanks.

public class SoloJava {

    public static void main(String[] agrs) {
        int age = 17;
        if (age >= 18) {
            System.out.println("You can enter");
        }
        if (age < 18) {
            System.out.println("You can not enter");
        }
        if (age >= 21) {
            System.out.println("You can drink");
        } else if (age <= 21) {
            System.out.println("You can not drink");
        }
    }
}

Body:
noob here, trying to help. From what I understand there are 3 possibilities.

Can't enter (younger than 18 years old)

May enter but can't get a drink (younger than 21 but still over 18)

Can enter and have a drink (over 21 years old)

Therefore I think that it would be best to minimize the number of if statements.

public static void main(String[] args) {

    int age = 20;

    if (age<18){
        System.out.println("You cannot enter");
    }
    else if(age>=18 && age<=21){ //checks if his/her age is between 18 and 21
        System.out.println("You may enter but you cannot drink");
    }
    else{
        System.out.println("You may enter and have a drink");
    }

}


问:
Notarize process for macos application not working
I have developed an application for MacOS. I am including notarization process as part of its distribution. I have followed all the steps and I have run:

```<code>xcrun altool --notarize-app --primary-bundle-id "${APP_BUNDLE_ID}" --username "${APPLE_DEV_ID}" --password "${DEV_APP_SPECIFIC_PASSWORD}" --file "${DMG_PATH}"
</code>```

Then I check notarization progress using:

```<code>xcrun altool --notarization-info "${notarize_uuid}"  -u "${APPLE_DEV_ID}" -p "${DEV_APP_SPECIFIC_PASSWORD}
</code>```

Output of it is:

```<code>RequestUUID: =<Request>
      Date: 2019-05-26 09:40:34 +0000
    Status: success
    LogFileURL: <Log file>
    Status Code: 0
    Status Message: Package Approved =~ success ]]
</code>```

Then I launch staple command:

```<code>xcrun stapler staple -v <dmg file>
</code>```

It also ends with success:

```<code>The staple and validate action worked!
</code>```

However when I extract the .app file and run:

```<code>spctl --assess --verbose ./macos/MyApp.app
./macos/MyApp.app/: accepted
</code>```

According to the docs I have read it should say something like: “source=Notarized Developer ID”, right?

I am running this on MacOS Mojave 10.14.5

What am I missing??

Could someone help me?

Thanks in advance

答:
In case someone faces the same problem I will post the solution to this:

First of all you must staple .app file not the dmg. This means you must extract the binary and staple it

Also in order to check if application has been notarized, in

```<code>`System Preferences - Security and Privacy`
</code>```

Option Allow apps downloaded from: must have Apple Store and identifier developers option checked

Hope this helps

Body:
I have developed an application for MacOS. I am including notarization process as part of its distribution. I have followed all the steps and I have run:

xcrun altool --notarize-app --primary-bundle-id "${APP_BUNDLE_ID}" --username "${APPLE_DEV_ID}" --password "${DEV_APP_SPECIFIC_PASSWORD}" --file "${DMG_PATH}"

Then I check notarization progress using:

xcrun altool --notarization-info "${notarize_uuid}"  -u "${APPLE_DEV_ID}" -p "${DEV_APP_SPECIFIC_PASSWORD}

Output of it is:

RequestUUID: =<Request>
      Date: 2019-05-26 09:40:34 +0000
    Status: success
    LogFileURL: <Log file>
    Status Code: 0
    Status Message: Package Approved =~ success ]]

Then I launch staple command:

xcrun stapler staple -v <dmg file>

It also ends with success:

The staple and validate action worked!

However when I extract the .app file and run:

spctl --assess --verbose ./macos/MyApp.app
./macos/MyApp.app/: accepted

According to the docs I have read it should say something like: “source=Notarized Developer ID”, right?

I am running this on MacOS Mojave 10.14.5

What am I missing??

Could someone help me?

Thanks in advance

Body:
In case someone faces the same problem I will post the solution to this:

First of all you must staple .app file not the dmg. This means you must extract the binary and staple it

Also in order to check if application has been notarized, in

`System Preferences - Security and Privacy`

Option Allow apps downloaded from: must have Apple Store and identifier developers option checked

Hope this helps


问:
Parse combination of command-line arguments and flags in bash
I am trying to write bash script which will read multiple filenames and a target directory, which is optional.

./myfile -t /home/users/ file1 file2

I have tried the following code, but I am not able to handle different scenarios mentioned below:

```<code>while getopts "t:" opt; do
  case $opt in
    t)
      echo "-t was triggered, Parameter: $OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument."
      exit 1
      ;;
  esac
done
</code>```

But the code should handle different scenarios like:
./myfile file1 file2 -t /home/users/,
./myfile file1  -t /home/users/ file2 file3,
./myfile file1 file2 file3 file4
and should be able to read the files.

答:
Using a while loop to read and shift the arguments might be easier in this case.
In the example below the arguments are looped through to look for the string -t in which case the arguments array is shifted one step and the now nr 1 index is supposed to be the optional homedir. In all the other cases the item is moved to another array called files.

```<code>#! /bin/bash

files=()
homedir=
while (( $# > 0 )); do
    case "$1" in
        -t )
            shift
            homedir="$1"
            ;;
        * )
            files+=("$1")
        ;;
    esac
    shift
done
echo "${files[@]}"
echo "$homedir"
</code>```

Body:
I am trying to write bash script which will read multiple filenames and a target directory, which is optional.

./myfile -t /home/users/ file1 file2

I have tried the following code, but I am not able to handle different scenarios mentioned below:

while getopts "t:" opt; do
  case $opt in
    t)
      echo "-t was triggered, Parameter: $OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument."
      exit 1
      ;;
  esac
done

But the code should handle different scenarios like:
./myfile file1 file2 -t /home/users/,
./myfile file1  -t /home/users/ file2 file3,
./myfile file1 file2 file3 file4
and should be able to read the files.

Body:
Using a while loop to read and shift the arguments might be easier in this case.
In the example below the arguments are looped through to look for the string -t in which case the arguments array is shifted one step and the now nr 1 index is supposed to be the optional homedir. In all the other cases the item is moved to another array called files.

#! /bin/bash

files=()
homedir=
while (( $# > 0 )); do
    case "$1" in
        -t )
            shift
            homedir="$1"
            ;;
        * )
            files+=("$1")
        ;;
    esac
    shift
done
echo "${files[@]}"
echo "$homedir"


问:
Using TwilioClient to execute Studio Flow from a Runtime Function
I have created a Twilio Studio Flow to make an outbound call that is triggered via REST API. I'd like to trigger this from a Twilio Runtime Function, but am having encountering errors when using the TwilioClient library.

Triggering the Studio Flow via the command line works successfully as follows:

```<code>curl -X POST "https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions" -d "To=+1XXXXXXXXX" -d "From=+1XXXXXXXXXX" -u ACCOUNT_SID:AUTH_TOKEN
</code>```

But trying to do the equivalent via a Runtime Function fails:

```<code>exports.handler = function(context, event, callback) {
  const twilioClient = context.getTwilioClient();
  console.log(twilioClient.studio);
  twilioClient.studio.flows('FWXXXXXXXXXXXXXXXXXXXXXXXXXX').executions.create({
    to: '+1XXXXXXXXX',
    from: '+1XXXXXXXXXX',
    parameters: JSON.stringify({
      name: "Client"
    })
  })
  .then(function(execution) {
    console.log(execution.sid);
    callback(null, execution.sid);
  })
  .catch(error => {
    console.error(`problem with request: ${error.message}`);
    callback(error.message);
  });
};
</code>```

The error encountered is:

```<code>{ message: 'Cannot read property \'flows\' of undefined',
  name: 'TypeError',
  stack: 'TypeError: Cannot read property \'flows\' of undefined\n    at Object.exports.handler (/var/task/handlers/ZF3ef70f4f38cfdf1c656da43214c01e18.js:6:19)\n    at Object.exports.handler (/var/task/node_modules/enigma-lambda/index.js:306:10)\n    at exports.handler (/var/task/enigma.js:17:9)' }
</code>```

I have been playing around with it for a number of hours and don't seem to be any closer to a solution. Any help in pointing me in the right direction would be super appreciated!

答:
Please make sure you are using a current version of the Twilio helper library. You can view your current versions under Twilio Functions, Configure: https://www.twilio.com/console/runtime/functions/configure (under: twilio), 3.6.3 is old.

The latest version can be found here:
https://github.com/twilio/twilio-node/releases (currently 3.31.0).

Body:
I have created a Twilio Studio Flow to make an outbound call that is triggered via REST API. I'd like to trigger this from a Twilio Runtime Function, but am having encountering errors when using the TwilioClient library.

Triggering the Studio Flow via the command line works successfully as follows:

curl -X POST "https://studio.twilio.com/v1/Flows/FWXXXXXXXXXXXXXXXXXXXXXXXXXX/Executions" -d "To=+1XXXXXXXXX" -d "From=+1XXXXXXXXXX" -u ACCOUNT_SID:AUTH_TOKEN

But trying to do the equivalent via a Runtime Function fails:

exports.handler = function(context, event, callback) {
  const twilioClient = context.getTwilioClient();
  console.log(twilioClient.studio);
  twilioClient.studio.flows('FWXXXXXXXXXXXXXXXXXXXXXXXXXX').executions.create({
    to: '+1XXXXXXXXX',
    from: '+1XXXXXXXXXX',
    parameters: JSON.stringify({
      name: "Client"
    })
  })
  .then(function(execution) {
    console.log(execution.sid);
    callback(null, execution.sid);
  })
  .catch(error => {
    console.error(`problem with request: ${error.message}`);
    callback(error.message);
  });
};

The error encountered is:

{ message: 'Cannot read property \'flows\' of undefined',
  name: 'TypeError',
  stack: 'TypeError: Cannot read property \'flows\' of undefined\n    at Object.exports.handler (/var/task/handlers/ZF3ef70f4f38cfdf1c656da43214c01e18.js:6:19)\n    at Object.exports.handler (/var/task/node_modules/enigma-lambda/index.js:306:10)\n    at exports.handler (/var/task/enigma.js:17:9)' }

I have been playing around with it for a number of hours and don't seem to be any closer to a solution. Any help in pointing me in the right direction would be super appreciated!


问:
What is the Best practice for try catch blocks to create clean code?

Possible Duplicate:

  Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

```<code>import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 * <p>This is a dummy code.</p>
 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown.
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}
</code>```

EDITED:

What I want to avoid is writing lot of catch cases after each other...

答:
Always catch the most specific exception possible--in otherwise never catch throwable.

The most important thing to me is that you NEVER have an empty catch block--one of these can take an amazing amount of time to find if something inside the try actually throws an exception.

I personally like to remove checked exceptions as quickly as possible and replace them with pre/post condition checks if possible.  Same with unchecked exceptions to a lesser degree--however unchecked exceptions are actually a pretty good way to indicate programmer error like parameter checking to ensure object state (Although asserts may be better yet)

Body:
Possible Duplicate:

  Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 *
This is a dummy code.

 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown.
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}

EDITED:

What I want to avoid is writing lot of catch cases after each other...


问:
comparing the value in a register to an int
I am trying to get the value  of a reg and compare it with a number inside and if statement </p>

```<code>  val refill_addr    = Reg(UInt(width = paddrBits))
if ( refill_addr >  20000.U)
   cacheable := true
   else
       cacheable := false
</code>```

<p>but i get this error </p>

```<code>[error] /home/a/i-rocket-chip/src/main/scala/rocket/ICache.scala:365:18: type mismatch;
[error]  found   : chisel3.core.Bool
[error]  required: Boolean
[error] if ( refill_addr >  20000.U)
[error]                  ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed

</code>```

答:
You should be using when/.otherwise here instead of if/else.

when is a Chisel (hardware) construct that will eventually map to one or more multiplexers. if is a Scala construct and can be used for compile-time generation of hardware.

when (refill_addr >  20000.U) {
  cacheable := true
} .otherwise {
  cacheable := false
}
```

For some more info, there was a similar question here.

Body:
I am trying to get the value  of a reg and compare it with a number inside and if statement

  val refill_addr    = Reg(UInt(width = paddrBits))
if ( refill_addr >  20000.U)
   cacheable := true
   else
       cacheable := false

but i get this error

[error] /home/a/i-rocket-chip/src/main/scala/rocket/ICache.scala:365:18: type mismatch;
[error]  found   : chisel3.core.Bool
[error]  required: Boolean
[error] if ( refill_addr >  20000.U)
[error]                  ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed

Body:
You should be using when/.otherwise here instead of if/else.

when is a Chisel (hardware) construct that will eventually map to one or more multiplexers. if is a Scala construct and can be used for compile-time generation of hardware.

when (refill_addr >  20000.U) {
  cacheable := true
} .otherwise {
  cacheable := false
}

For some more info, there was a similar question here.


问:
Is there any way to run Rspec tests on a single Ruby file?
I would like to run some tests on some code kata exercises that I am working on. Is it possible to run Rspec tests on a single Ruby file? I tried adding require 'rspec' to the top of the file and then the command rsepc from the project dir but the following is returned:

```<code>F

Failures:

  1) Sentence reverser reverses the words in a sentence
     Failure/Error: expect(sentence_reverser(test_sentence)).to eq('I am backwards')

     NoMethodError:
       undefined method `sentence_reverser' for #<RSpec::ExampleGroups::SentenceReverser:0x0000559764dc5950>
</code>```

The code I have is:

```<code>require 'rspec'

def sentence_reverser str
  str.split.reverse.join(' ')
end

describe "Sentence reverser" do
  it 'reverses the words in a sentence' do
    test_sentence = "backwards am I"
    expect(sentence_reverser(test_sentence)).to eq('I am backwards')
  end
end
</code>```

答: Try running rspec </path/to/kata.rb>. You shouldn't even require 'rspec' then - just tested your example.

Body:
I would like to run some tests on some code kata exercises that I am working on. Is it possible to run Rspec tests on a single Ruby file? I tried adding require 'rspec' to the top of the file and then the command rsepc from the project dir but the following is returned:

F

Failures:

  1) Sentence reverser reverses the words in a sentence
     Failure/Error: expect(sentence_reverser(test_sentence)).to eq('I am backwards')

     NoMethodError:
       undefined method `sentence_reverser' for #<RSpec::ExampleGroups::SentenceReverser:0x0000559764dc5950>

The code I have is:

require 'rspec'

def sentence_reverser str
  str.split.reverse.join(' ')
end

describe "Sentence reverser" do
  it 'reverses the words in a sentence' do
    test_sentence = "backwards am I"
    expect(sentence_reverser(test_sentence)).to eq('I am backwards')
  end
end


问:
How in R to add lines of text above column names in a dataframe and save as txt file
I'm using R to pull data from Adobe Analytics. The dataframe has column names and I am looking to add the following lines above the column names and save the file as a txt with the previous date: filename_yyyy-mm-dd.

I'm having issues adding the following above the column names:

Product Cost template file (user: 400024375 ds_id: 2)

Products COGS (e102)  Original Price (e103) Sale Price (e104) Purchase ID

These are the column names:
Date    Product Event 102   Event 103   Event 104   transactionID

Here is the final file should look like:

答:
Here is one way to do it (assuming your dataframe is named your_data):

```<code>line1 = '# Product Cost template file (user: 400024375 ds_id: 2)'
line2 = '# Products COGS (e102) Original Price (e103) Sale Price (e104) Purchase ID'
column_names = c( paste( line1, line2, 'Date', sep = '\n'), 'Product', 'Event 102', 'Event 103', 'Event 104', 'transactionID')

output = rbind( column_names, your_data)
write.table( output, "filename_yyyy-mm-dd.txt", sep="\t", quote = F, row.names = F, col.names = F )
</code>```

Note that this assumes you do not yet have the column names in the data, which you seem to imply. If you do have the column names already in the first row, you just write output[1, 1] = paste( line1, line2, output[1, 1], sep = '\n') instead of the rbind line.

Alternatively, you can first write the first lines and then append the table:

```<code>line1 = '# Product Cost template file (user: 400024375 ds_id: 2)'
line2 = '# Products COGS (e102) Original Price (e103) Sale Price (e104) Purchase ID'
column_names = c( 'Date', 'Product', 'Event 102', 'Event 103', 'Event 104', 'transactionID')

names(your_data) = column_names
file_name = "filename_yyyy-mm-dd.txt"
cat( line1, line2, file = file_name, sep="\n")
write.table( your_data, file_name, sep="\t", quote = F, row.names = F, col.names = T, append = T )
</code>```

(Again, if you already have the column names, just remove the column_names parts.)

Body:
Here is one way to do it (assuming your dataframe is named your_data):

line1 = '# Product Cost template file (user: 400024375 ds_id: 2)'
line2 = '# Products COGS (e102) Original Price (e103) Sale Price (e104) Purchase ID'
column_names = c( paste( line1, line2, 'Date', sep = '\n'), 'Product', 'Event 102', 'Event 103', 'Event 104', 'transactionID')

output = rbind( column_names, your_data)
write.table( output, "filename_yyyy-mm-dd.txt", sep="\t", quote = F, row.names = F, col.names = F )

Note that this assumes you do not yet have the column names in the data, which you seem to imply. If you do have the column names already in the first row, you just write output[1, 1] = paste( line1, line2, output[1, 1], sep = '\n') instead of the rbind line.

Alternatively, you can first write the first lines and then append the table:

line1 = '# Product Cost template file (user: 400024375 ds_id: 2)'
line2 = '# Products COGS (e102) Original Price (e103) Sale Price (e104) Purchase ID'
column_names = c( 'Date', 'Product', 'Event 102', 'Event 103', 'Event 104', 'transactionID')

names(your_data) = column_names
file_name = "filename_yyyy-mm-dd.txt"
cat( line1, line2, file = file_name, sep="\n")
write.table( your_data, file_name, sep="\t", quote = F, row.names = F, col.names = T, append = T )

(Again, if you already have the column names, just remove the column_names parts.)


答:
Instead of creating a gameobject with an OnMouseDown, I'd probably create a Button instead and binding an event to it:

```<code> var closeButton = /* Dynamically create button */
 closeButton.GetComponent<Button>().onClick.AddListener(HandleCloseClick);

 void HandleCloseClick() {

     Destroy(gameObject);
 }
</code>```

You can, however, do the architecture you've already implemented - you just need to implement IPointerClickHandler.

Here's an answer describing how to implement & use the interface.

Check the docs for instructions on how to use each event (Mouse Down, Up, Enter, Exit)

Title: How to delete dynamically loaded gameobjects from a List in Untiy?

Body:
I have a list that loads its content dynamically. The Elements of the List are buttons that are being transformed into gameobjects. For every object in the user list a new Element is created. Now I want to be able to delete the Element along with the button itself, when the button is pressed, where each Element has its own dynamically created delete button. I tried putting a box collider with an OnMouseDown Event, however onMouseDown is never called.

public void ShowLectures()
{
    foreach (var course in selectedCourses)
    {
        AddMoreButton();
    }
}

public void AddMoreButton()
{
    GameObject button = (GameObject)Instantiate(prefabButton);
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);
}

public void OnMouseDown()
{
    Destroy(gameObject);
}

Body:
Instead of creating a gameobject with an OnMouseDown, I'd probably create a Button instead and binding an event to it:

 var closeButton = /* Dynamically create button */
 closeButton.GetComponent<Button>().onClick.AddListener(HandleCloseClick);

 void HandleCloseClick() {

     Destroy(gameObject);
 }

You can, however, do the architecture you've already implemented - you just need to implement IPointerClickHandler.

Here's an answer describing how to implement & use the interface.

Check the docs for instructions on how to use each event (Mouse Down, Up, Enter, Exit)


问:
Find the resulting Sum after adding to the previous value in a Python list
I have a random number as input, lets say 5. What I need is the sum of the numbers 5 + 55 + 555 + 5555 + 55555.

Kindly help

答:
You should track the sum and the number to sum separately like:</p>

```<code>i = 0
digits = 5
the_sum = 0
for j in range(digits):
    i = i * 10 + digits
    the_sum += i

print(the_sum)
print(5 + 55 + 555 + 5555 + 55555)
</code>```

Body:
You should track the sum and the number to sum separately like:

i = 0
digits = 5
the_sum = 0
for j in range(digits):
    i = i * 10 + digits
    the_sum += i

print(the_sum)
print(5 + 55 + 555 + 5555 + 55555)


问:
How to create a Word paragraphformat object form an Excel macro
I create a new Word document form an Excel macro and that works fine.
Now I want to create a new ParagraphFormat object to apply to a lot of paragraphs.
Microsoft Office Dev Center gives an example for a macro in word.

```<code>Set oWord_app = CreateObject("Word.Application")
oWord_app.Documents.Add
Set oDoc = oWord_app.Documents(1)

'Micorsoft Def Center:
Dim myParaF As New ParagraphFormat
myParaF.Alignment = wdAlignParagraphCenter
myParaF.Borders.Enable = True
ActiveDocument.Paragraphs(1).Format = myParaF
</code>```

To adapt this Word macro to my Excel macro I think I have to write

```<code>Dim myParaF as new oWord_app.ParagraphFormat
</code>```

but that failed. What’s the right way?

答:
Thank you for your advice. I’m sorry, but I really did not think to check the references.
I had only a reference to Microsoft Office 14.0 Object library, now I also a reference to Microsoft Word 14.0 Object Library. And now it works. The new statement is apparently necessary, otherwise I get the error “variable not known”.
I still wonder why it works only without “Word_app. ParagraphFormat” , but already with “ParagraphFormat”.
Thank you very much.

here my code in shot words:

```<code>    Option Explicit
    Dim Word_app As Object, oDoc As Object, bWordVorhanden As Boolean, pFormat As Object

Sub DocumentCreate()

    Set Word_app = CreateObject("Word.Application")
    Word_app.Visible = True
    Word_app.Documents.Add
    Set oDoc = Word_app.Documents(1)

Set pFormat = New ParagraphFormat
pFormat.Alignment = wdAlignParagraphCenter
pFormat.Borders.Enable = True
ActiveDocument.Paragraphs(1).Format = pFormat

    With oDoc.Paragraphs(1).Range
        .Font.Name = "Arial"
        .Font.Size = 11
        .Font.Bold = True
        .ParagraphFormat.Alignment = 1 'wdAlignParagraphCenter
        .InsertAfter "hello" 'Text:=Str(oDoc.Paragraphs.Count)
        .ParagraphFormat.SpaceBefore = 12
        .ParagraphFormat.SpaceAfter = 6
    End With

End Sub
</code>```

Body:
I create a new Word document form an Excel macro and that works fine.
Now I want to create a new ParagraphFormat object to apply to a lot of paragraphs.
Microsoft Office Dev Center gives an example for a macro in word.

Set oWord_app = CreateObject("Word.Application")
oWord_app.Documents.Add
Set oDoc = oWord_app.Documents(1)

'Micorsoft Def Center:
Dim myParaF As New ParagraphFormat
myParaF.Alignment = wdAlignParagraphCenter
myParaF.Borders.Enable = True
ActiveDocument.Paragraphs(1).Format = myParaF

To adapt this Word macro to my Excel macro I think I have to write

Dim myParaF as new oWord_app.ParagraphFormat

but that failed. What’s the right way?

Body:
Thank you for your advice. I’m sorry, but I really did not think to check the references.
I had only a reference to Microsoft Office 14.0 Object library, now I also a reference to Microsoft Word 14.0 Object Library. And now it works. The new statement is apparently necessary, otherwise I get the error “variable not known”.
I still wonder why it works only without “Word_app. ParagraphFormat” , but already with “ParagraphFormat”.
Thank you very much.

here my code in shot words:

    Option Explicit
    Dim Word_app As Object, oDoc As Object, bWordVorhanden As Boolean, pFormat As Object

Sub DocumentCreate()

    Set Word_app = CreateObject("Word.Application")
    Word_app.Visible = True
    Word_app.Documents.Add
    Set oDoc = Word_app.Documents(1)

Set pFormat = New ParagraphFormat
pFormat.Alignment = wdAlignParagraphCenter
pFormat.Borders.Enable = True
ActiveDocument.Paragraphs(1).Format = pFormat

    With oDoc.Paragraphs(1).Range
        .Font.Name = "Arial"
        .Font.Size = 11
        .Font.Bold = True
        .ParagraphFormat.Alignment = 1 'wdAlignParagraphCenter
        .InsertAfter "hello" 'Text:=Str(oDoc.Paragraphs.Count)
        .ParagraphFormat.SpaceBefore = 12
        .ParagraphFormat.SpaceAfter = 6
    End With

End Sub


问:
How to export a Hive table into a CSV file?
I used this Hive query to export a table into a CSV file.

```<code>INSERT OVERWRITE DIRECTORY '/user/data/output/test' select column1, column2 from table1;
</code>```

The file generated '000000_0' does not have comma separator

Is this the right way to generate CSV file? If no, please let me know how can I generate the CSV file?

答:
Below is the end-to-end solution that I use to export Hive table data to HDFS as a single named CSV file with a header.

(it is unfortunate that it's not possible to do with one HQL statement)

It consists of several commands, but it's quite intuitive, I think, and it does not rely on the internal representation of Hive tables, which may change from time to time.

Replace "DIRECTORY" with "LOCAL DIRECTORY" if you want to export the data to a local filesystem versus HDFS.

```<code># cleanup the existing target HDFS directory, if it exists
sudo -u hdfs hdfs dfs -rm -f -r /tmp/data/my_exported_table_name/*

# export the data using Beeline CLI (it will create a data file with a surrogate name in the target HDFS directory)
beeline -u jdbc:hive2://my_hostname:10000 -n hive -e "INSERT OVERWRITE DIRECTORY '/tmp/data/my_exported_table_name' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' SELECT * FROM my_exported_table_name"

# set the owner of the target HDFS directory to whatever UID you'll be using to run the subsequent commands (root in this case)
sudo -u hdfs hdfs dfs -chown -R root:hdfs /tmp/data/my_exported_table_name

# write the CSV header record to a separate file (make sure that its name is higher in the sort order than for the data file in the target HDFS directory)
# also, obviously, make sure that the number and the order of fields is the same as in the data file
echo 'field_name_1,field_name_2,field_name_3,field_name_4,field_name_5' | hadoop fs -put - /tmp/data/my_exported_table_name/.header.csv

# concatenate all (2) files in the target HDFS directory into the final CSV data file with a header
# (this is where the sort order of the file names is important)
hadoop fs -cat /tmp/data/my_exported_table_name/* | hadoop fs -put - /tmp/data/my_exported_table_name/my_exported_table_name.csv

# give the permissions for the exported data to other users as necessary
sudo -u hdfs hdfs dfs -chmod -R 777 /tmp/data/hive_extr/drivers
</code>```

Body:
I used this Hive query to export a table into a CSV file.

INSERT OVERWRITE DIRECTORY '/user/data/output/test' select column1, column2 from table1;

The file generated '000000_0' does not have comma separator

Is this the right way to generate CSV file? If no, please let me know how can I generate the CSV file?

Body:
Below is the end-to-end solution that I use to export Hive table data to HDFS as a single named CSV file with a header.

(it is unfortunate that it's not possible to do with one HQL statement)

It consists of several commands, but it's quite intuitive, I think, and it does not rely on the internal representation of Hive tables, which may change from time to time.

Replace "DIRECTORY" with "LOCAL DIRECTORY" if you want to export the data to a local filesystem versus HDFS.

# cleanup the existing target HDFS directory, if it exists
sudo -u hdfs hdfs dfs -rm -f -r /tmp/data/my_exported_table_name/*

# export the data using Beeline CLI (it will create a data file with a surrogate name in the target HDFS directory)
beeline -u jdbc:hive2://my_hostname:10000 -n hive -e "INSERT OVERWRITE DIRECTORY '/tmp/data/my_exported_table_name' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' SELECT * FROM my_exported_table_name"

# set the owner of the target HDFS directory to whatever UID you'll be using to run the subsequent commands (root in this case)
sudo -u hdfs hdfs dfs -chown -R root:hdfs /tmp/data/my_exported_table_name

# write the CSV header record to a separate file (make sure that its name is higher in the sort order than for the data file in the target HDFS directory)
# also, obviously, make sure that the number and the order of fields is the same as in the data file
echo 'field_name_1,field_name_2,field_name_3,field_name_4,field_name_5' | hadoop fs -put - /tmp/data/my_exported_table_name/.header.csv

# concatenate all (2) files in the target HDFS directory into the final CSV data file with a header
# (this is where the sort order of the file names is important)
hadoop fs -cat /tmp/data/my_exported_table_name/* | hadoop fs -put - /tmp/data/my_exported_table_name/my_exported_table_name.csv

# give the permissions for the exported data to other users as necessary
sudo -u hdfs hdfs dfs -chmod -R 777 /tmp/data/hive_extr/drivers


问:
PHP - Pack array with binary data
There is a service (php) which sends an image to a client (php).

```<code>header('Content-Type: image/png');
readfile($image);
</code>```

What if it is needed to send not only an image but some data with it.

```<code>$arrayToSend = [
    'image' => file_get_contents($image),
    'some_data' => [
        'a' => 1,
        'b' => 2
    ]
];
</code>```

How the service can pack $arrayToSend so that the client can unpack it?

Without converting image to base64 (because of too large size).

答:
@Danon's header approach is probably the way to go if you're communicating over HTTP, but other transports may not support sending additional headers, so you would need to pack them in with the binary data, then unpack on the receiving side.</p>

```<code><?php
class Codec
{
    /**
     * Pack metadata along with binary data
     *
     * @param $meta
     * @param $data
     * @return false|string
     */
    public static function encode($meta, $data)
    {
        $meta = base64_encode($meta);

        //determine length of metadata
        $metaLength = strlen($meta);

        //The first part of the message is the metadata length
        $output = pack('VA*', $metaLength, $meta);

        //Length and metadata are set, now include the binary data
        $output .= $data;

        return $output;
    }

    /**
     * Unpack data encoded via the encode function.
     * Returns an array with "meta" and "data" elaments
     *
     * @param $content
     * @return array
     */
    public static function decode($content)
    {
        //Get the length of the metadata content
        $metaLength = unpack('V', $content)[1];

        //Slice out the metatdata, offset 4 to account for the length bytes
        $metaPacked = substr($content, 4, $metaLength);

        //Unpack and base64 decode the metadata
        $meta = unpack('A*', $metaPacked)[1];
        $meta = base64_decode($meta);

        //The binary data is everything after the metadata
        $data = substr($content, $metaLength+4);

        return [
            'meta' => $meta,
            'data' => $data
        ];
    }
}

//Load contents of a binary file
$imageFilePath = 'path_to_image.png';
$data = file_get_contents($imageFilePath);

//Arbitrary metadata - could be anything, let's use JSON
$meta = [
    'filename' => 'foo.png',
    'uid' => 12345,
    'md5' => md5_file($imageFilePath)
];

$metaJson = json_encode($meta);

//Encode the message, you can then send this to the receiver
$payload = Codec::encode($metaJson, $data);

//Receiver decodes the message
$result = Codec::decode($payload);

//Decode our JSON string
$resultMeta = json_decode($result['meta'], true);

echo 'Filename: '.$resultMeta['filename'].PHP_EOL;
echo 'UID: '.$resultMeta['uid'].PHP_EOL;

//We included an MD5 hash of the file, so we can verify here
if($resultMeta['md5'] != md5($result['data']))
{
    echo 'MD5 mismatch!';
}
</code>```

Title: PHP - Pack array with binary data

Body:
There is a service (php) which sends an image to a client (php).

header('Content-Type: image/png');
readfile($image);

What if it is needed to send not only an image but some data with it.

$arrayToSend = [
    'image' => file_get_contents($image),
    'some_data' => [
        'a' => 1,
        'b' => 2
    ]
];

How the service can pack $arrayToSend so that the client can unpack it?

Without converting image to base64 (because of too large size).

Body:
@Danon's header approach is probably the way to go if you're communicating over HTTP, but other transports may not support sending additional headers, so you would need to pack them in with the binary data, then unpack on the receiving side.

<?php
class Codec
{
    /**
     * Pack metadata along with binary data
     *
     * @param $meta
     * @param $data
     * @return false|string
     */
    public static function encode($meta, $data)
    {
        $meta = base64_encode($meta);

        //determine length of metadata
        $metaLength = strlen($meta);

        //The first part of the message is the metadata length
        $output = pack('VA*', $metaLength, $meta);

        //Length and metadata are set, now include the binary data
        $output .= $data;

        return $output;
    }

    /**
     * Unpack data encoded via the encode function.
     * Returns an array with "meta" and "data" elaments
     *
     * @param $content
     * @return array
     */
    public static function decode($content)
    {
        //Get the length of the metadata content
        $metaLength = unpack('V', $content)[1];

        //Slice out the metatdata, offset 4 to account for the length bytes
        $metaPacked = substr($content, 4, $metaLength);

        //Unpack and base64 decode the metadata
        $meta = unpack('A*', $metaPacked)[1];
        $meta = base64_decode($meta);

        //The binary data is everything after the metadata
        $data = substr($content, $metaLength+4);

        return [
            'meta' => $meta,
            'data' => $data
        ];
    }
}

//Load contents of a binary file
$imageFilePath = 'path_to_image.png';
$data = file_get_contents($imageFilePath);

//Arbitrary metadata - could be anything, let's use JSON
$meta = [
    'filename' => 'foo.png',
    'uid' => 12345,
    'md5' => md5_file($imageFilePath)
];

$metaJson = json_encode($meta);

//Encode the message, you can then send this to the receiver
$payload = Codec::encode($metaJson, $data);

//Receiver decodes the message
$result = Codec::decode($payload);

//Decode our JSON string
$resultMeta = json_decode($result['meta'], true);

echo 'Filename: '.$resultMeta['filename'].PHP_EOL;
echo 'UID: '.$resultMeta['uid'].PHP_EOL;

//We included an MD5 hash of the file, so we can verify here
if($resultMeta['md5'] != md5($result['data']))
{
    echo 'MD5 mismatch!';
}


问:
RegEx for fulltext search with typos
I have a MySQL table with the following columns:

```<code>City      Country  Continent
New York  States   Noth America
New York  Germany  Europe - considering there's one ;)
Paris     France   Europe
</code>```

If I want to find "New Yokr" with a typo, it's easy with a MySQL stored function:

```<code>$querylev = "select City, Country, Continent FROM table
            WHERE LEVENSHTEIN(`City`,'New Yokr') < 3"
</code>```

But in case there are two New York cities, searching with fulltext you can put "New York States" and you get your desired result.

So the question is, could I search "New Yokr Statse" and get the same results?

Is there any function merging levenshtein and fulltext to make an all in one solution or should I create a new column in MySQL concatenating the 3 columns?

I know there are other solutions such as lucene or Sphinx (also soundex, metaphone, but not valid for this) but I think for me could be kind of hard to implement them.

答:
Great question, and a good example of how we can use char lists and regular expression boundaries to design queries and retrieve the data that we wish.

Depending on the accuracy we might want and the data we are having in the database, we can surely design custom queries based on a variety of expressions, such as this example for New York State with various types:

```<code>([new]+\s+[york]+\s+[stae]+)
</code>```

Here, we have three char lists that we can update with other possible letters.

```<code>[new]
[york]
[stae]
</code>```

We have also added two sets of \s+ as our boundaries here to increase the accuracy.

DEMO

This snippet just shows that how the capturing groups work:

const regex = /([new]+\s+[york]+\s+[stae]+)/gmi;
const str = `Anything we wish to have before followed by a New York Statse then anything we wish to have after. Anything we wish to have before followed by a New  Yokr  State then anything we wish to have after. Anything we wish to have before followed by a New Yokr Stats then anything we wish to have after. Anything we wish to have before followed by a New York Statse then anything we wish to have after. `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```
</div>
</div>
</p>
<h3>PHP</h3>
```$re = '/([new]+\s+[york]+\s+[stae]+)/mi';
$str = 'Anything we wish to have before followed by a New York Statse then anything we wish to have after. Anything we wish to have before followed by a New  Yokr  State then anything we wish to have after. Anything we wish to have before followed by a New Yokr Stats then anything we wish to have after. Anything we wish to have before followed by a New York Statse then anything we wish to have after. ';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);
```

Title: RegEx for fulltext search with typos

Body:
I have a MySQL table with the following columns:

City      Country  Continent
New York  States   Noth America
New York  Germany  Europe - considering there's one ;)
Paris     France   Europe

If I want to find "New Yokr" with a typo, it's easy with a MySQL stored function:

$querylev = "select City, Country, Continent FROM table
            WHERE LEVENSHTEIN(`City`,'New Yokr') < 3"

But in case there are two New York cities, searching with fulltext you can put "New York States" and you get your desired result.

So the question is, could I search "New Yokr Statse" and get the same results?

Is there any function merging levenshtein and fulltext to make an all in one solution or should I create a new column in MySQL concatenating the 3 columns?

I know there are other solutions such as lucene or Sphinx (also soundex, metaphone, but not valid for this) but I think for me could be kind of hard to implement them.

Body:
Great question, and a good example of how we can use char lists and regular expression boundaries to design queries and retrieve the data that we wish.

Depending on the accuracy we might want and the data we are having in the database, we can surely design custom queries based on a variety of expressions, such as this example for New York State with various types:

([new]+\s+[york]+\s+[stae]+)

Here, we have three char lists that we can update with other possible letters.

[new]
[york]
[stae]

We have also added two sets of \s+ as our boundaries here to increase the accuracy.

DEMO

This snippet just shows that how the capturing groups work:

const regex = /([new]+\s+[york]+\s+[stae]+)/gmi;
const str = `Anything we wish to have before followed by a New York Statse then anything we wish to have after. Anything we wish to have before followed by a New  Yokr  State then anything we wish to have after. Anything we wish to have before followed by a New Yokr Stats then anything we wish to have after. Anything we wish to have before followed by a New York Statse then anything we wish to have after. `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

PHP

$re = '/([new]+\s+[york]+\s+[stae]+)/mi';
$str = 'Anything we wish to have before followed by a New York Statse then anything we wish to have after. Anything we wish to have before followed by a New  Yokr  State then anything we wish to have after. Anything we wish to have before followed by a New Yokr Stats then anything we wish to have after. Anything we wish to have before followed by a New York Statse then anything we wish to have after. ';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);