问:
upload gzip file in api request express server nodejs
I want to upload 'content-encoding:gzip' gzip file using express server in nodejs. I want to know what is the npm module I can use for better performance to receive and uncompress gzip file in request.</p>

答:
there are two methods to handle this. first

```<code>npm i compression --save
</code>```

then in your server.js

```<code>const compression = require("compression");
server.use(compression());//make sure you use this  on top of the middlewares
</code>```

Express middleware will compress your files at the point of request.
Another solution is to let Webpack compress your files and create .gz versions of your uncompressed files.

```<code>npm i --save compression-webpack-plugin
</code>```

this package uses "gzip" algorithm by default

in your webpack.config.js for production

```<code>const CompressionPlugin = require("compression-webpack-plugin");

plugins: [
      new CompressionPlugin(),
    ]
</code>```

this will compress your assets files except jpeg images. because jpeg is already a compressed file type. now you need to tell express how to handle compressed files.
for this install

```<code>  npm i express-static-gzip
</code>```

in your server.js

```<code> const expressStaticGzip = require("express-static-gzip");
    server.use(expressStaticGzip("dist"));//make sure you use this middleware first.
</code>```

Webpack compression will compress your files one-time - during your build run. Those compressed versions are then saved to disk

Body:
there are two methods to handle this. first

npm i compression --save

then in your server.js

const compression = require("compression");
server.use(compression());//make sure you use this  on top of the middlewares

Express middleware will compress your files at the point of request.
Another solution is to let Webpack compress your files and create .gz versions of your uncompressed files.

npm i --save compression-webpack-plugin

this package uses "gzip" algorithm by default

in your webpack.config.js for production

const CompressionPlugin = require("compression-webpack-plugin");

plugins: [
      new CompressionPlugin(),
    ]

this will compress your assets files except jpeg images. because jpeg is already a compressed file type. now you need to tell express how to handle compressed files.
for this install

  npm i express-static-gzip

in your server.js

 const expressStaticGzip = require("express-static-gzip");
    server.use(expressStaticGzip("dist"));//make sure you use this middleware first.

Webpack compression will compress your files one-time - during your build run. Those compressed versions are then saved to disk


来源: stackexchange

问:
How to use tail.select in VueJS
I am relatively new in VueJS. I am having trouble in using tail.select plugin in vueJS

I am done importing the plugin on my main.js import 'tail.select'

but upon calling the tail.select(".select") on my mounted it gives me an error that says Uncaught ReferenceError: tail is not defined.

HTML

<select class="form-control form-control-sm select">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>
```

<p>Script</p>

<pre class="lang-js prettyprint-override"><code>export default {
  mounted(){
    flatpickr('.datepicker',{
      altFormat: "F j, Y",
      dateFormat: "Y-m-d",
    })
    tail.select(".select")
  }
}
</code>```

答:
Tail.Select has prototype method called reload that contains this function:

```<code>        /*
         |  PUBLIC :: RELOAD SELECT
         |  @since  0.5.0 [0.3.0]
         */
        reload: function(){
            return this.remove().init();
        },
</code>```

Which basically calls remove() and init(), which results in re-populating the data into:

div.tail-select.no-classes.deselect which is the container of tail.select in HTML document.

To use it with Vue JS apply the reload method in Vue updated method to a new instance of Tail.Select like this example, where document.querySelectorAll is used to target all select input in HTML document based on unique class name js-select:

This function activates tail.select

```<code>/**
* Activates Tail.select third party library for select options
*/
function activateTailSelect() {
    var sel = document.querySelectorAll('.js-select');
    var options = {
        deselect: true,
        search: true,
        width: "100%",
        openAbove: false
    };
    if (sel.length > 0) {
        sel.forEach(function (s) {
            var tSelect = tail.select(s, options);
            tSelect.reload(true);
        });
    }
}
</code>```

Calling previous function on Vue update event

```<code>// Vue App Instance
    new Vue({
        el: "#app",
        data: {
          message: "Vue loaded"
        },
        updated() {
        // this phase is after re-render virtual DOM and patch and before destroy
        activateTailSelect();

        }
    });
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use tail.select in VueJS

Body:
I am relatively new in VueJS. I am having trouble in using tail.select plugin in vueJS

I am done importing the plugin on my main.js import 'tail.select'

but upon calling the tail.select(".select") on my mounted it gives me an error that says Uncaught ReferenceError: tail is not defined.

HTML

<select class="form-control form-control-sm select">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

Script

export default {
  mounted(){
    flatpickr('.datepicker',{
      altFormat: "F j, Y",
      dateFormat: "Y-m-d",
    })
    tail.select(".select")
  }
}

Body:
Tail.Select has prototype method called reload that contains this function:

        /*
         |  PUBLIC :: RELOAD SELECT
         |  @since  0.5.0 [0.3.0]
         */
        reload: function(){
            return this.remove().init();
        },

Which basically calls remove() and init(), which results in re-populating the data into:

div.tail-select.no-classes.deselect which is the container of tail.select in HTML document.

To use it with Vue JS apply the reload method in Vue updated method to a new instance of Tail.Select like this example, where document.querySelectorAll is used to target all select input in HTML document based on unique class name js-select:

This function activates tail.select

/**
* Activates Tail.select third party library for select options
*/
function activateTailSelect() {
    var sel = document.querySelectorAll('.js-select');
    var options = {
        deselect: true,
        search: true,
        width: "100%",
        openAbove: false
    };
    if (sel.length > 0) {
        sel.forEach(function (s) {
            var tSelect = tail.select(s, options);
            tSelect.reload(true);
        });
    }
}

Calling previous function on Vue update event

// Vue App Instance
    new Vue({
        el: "#app",
        data: {
          message: "Vue loaded"
        },
        updated() {
        // this phase is after re-render virtual DOM and patch and before destroy
        activateTailSelect();

        }
    });


问:
wkwebview: find out if loaded content in web view is PDF and give download button
I am using wkWebView to load research papers published on IEEE, Science Direct, etc. so when I click on any PDF in the research papers, PDF gets loaded into webview, so is there a way to detect and enable a download icon in wkWebView.

Tried Solution:
I have tried to get the pdf from URLs via URLSession and this is working for like 95% of the times but sometimes I don't get the content of PDF via URLSession and pdf gets loaded into webview because of dynamic URL/PDF creation.

In research, I came across: Get already loaded PDF directly from WKWebView without downloading again But in my case first I need to check if the loaded content is PDF.

A relevant question: add download button for pdf in wkwebview in swift 4 But no answer!!!

To test: open URL: https://www.sciencedirect.com/science/article/pii/S0946672X17308763 in wkWebView and click on the "Download PDF" button this will load the pdf into webview.

In short: Any way to detect if the loaded content is PDF and give a download button to download the pdf content into the documents folder.

Any help appreciated...Thanks

答:
You can detect if the content of the current page is a PDF by checking its mime/content type via the DOM Document.contentType API. If it's application/pdf, we know the web view is currently displaying a PDF, and can show a download button:

func isCurrentDocumentPDF(_ onCompletion: (Bool) -> Void) {
    webView.evaluateJavascript("document.contentType") {
        _, result in

        if let contentType = result as? String, contentType == "application/pdf" {
            onCompletion(true)
        } else {
            onCompletion(false)
        }
    }
}

isCurrentDocumentPDF() {
    isPDF in

    if isPDF {
        pdfDownloadButton.isHidden = false
    }
}
```


问:
Android: Widget takes too much place
I faced with a strange problem with my widget size.
I decided to develop one simple widget with supporting of ldpi, mdpi, large-mdpi and hdpi screens.
At first I created xml/widget.xml where I defined the following:

```<code><appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minHeight="146dip"
    android:minWidth="220dip"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/widget"/></code>```

So I expect that my widget will take 3x2 cells for all supported screens.
Then I designed several layouts, one for each screen type - ldpi, mdpi, large-mdpi and hdpi - where:

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Widget"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    ...
</RelativeLayout></code>```

So I expect that the widget size will fit 3x2 cells for all screens, not more, not less.
But currently when I run it on emulator (and real device too) I see that my widget takes
more than a half of a screen for all supporting screens - 4x3 cells if
to talk that the max size is 4x4 cells (as it described here:
http://developer.android.com/guide/practices/ui_guidelines/widget_design.html#sizes).
Even if I'll define exact layout_width and layout_height in my widget
layouts in dip it will still take 4x3 cells, just it's visible part
will have another size.

答: Well, looks like emulator not always refresh my app and that is why I saw my old dimensions instead of new. My friend also said that emulator usually doesn't update apps if using startActivityForResult. So in that case it is better to restart widget manually. Hope that will be helpfull for someone else :) </p>

ContentLicense: CC BY-SA 3.0

Title: Android: Widget takes too much place

Body:
I faced with a strange problem with my widget size.
I decided to develop one simple widget with supporting of ldpi, mdpi, large-mdpi and hdpi screens.
At first I created xml/widget.xml where I defined the following:

<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minHeight="146dip"
    android:minWidth="220dip"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/widget"/>

So I expect that my widget will take 3x2 cells for all supported screens.
Then I designed several layouts, one for each screen type - ldpi, mdpi, large-mdpi and hdpi - where:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Widget"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    ...
</RelativeLayout>

So I expect that the widget size will fit 3x2 cells for all screens, not more, not less.
But currently when I run it on emulator (and real device too) I see that my widget takes
more than a half of a screen for all supporting screens - 4x3 cells if
to talk that the max size is 4x4 cells (as it described here:
http://developer.android.com/guide/practices/ui_guidelines/widget_design.html#sizes).
Even if I'll define exact layout_width and layout_height in my widget
layouts in dip it will still take 4x3 cells, just it's visible part
will have another size.


问:
Centralized Python Logging - Unable to import logging file
I found an example online of a config file to build on the base logging and colorlog.

File Structure

```<code>main.py
directory.py
client.py
/utils/log.py
</code>```

main, directory and client all have from utils.log import init_logger which is the function inside my log.py.

For processing,
main.py imports a function from directory.py which imports a function from client.py.

VSCODE complains that the modules can't be imported, but the script runs fine with no errors except vscode complaining.

I think I have a circular dependency issue going on, but can't figure out how I should share the logging config between all my files without importing it.

main.py

```<code>"""
Setup Trusts Between Directories
"""
import json
from utils.log import init_logger
from directory import stage

###############
def main():
    """
    MAIN TRUST FUNCTION
    """

    ## Initialize Logger
    if __name__ == "__main__":
        logger = init_logger(__name__, testing_mode=False)
        logger.info("Running Creator")

    ## Get Outputs
    new_dirs = get_output("newDirectoryIds")
    config_dirs = get_output("configDirectories")

    ## Get Directory Stage
    stage(new_dirs, config_dirs)

###############

## Run Main Function
main()

</code>```

directory.py

```<code>"""
directory.py
- Loops Through List of Directories
- Returns back when stage is Active or Failed
"""
import time
from utils.log import init_logger
from get_client import get_new_client

###########
def stage(new_dirs, config_dirs):
    """
    Returns Directory Stage Value
    - Loops until Directory is Failed or Active
    """

    ## Initialize Logger
    logger = init_logger(__name__, testing_mode=True)

     for config_dir in config_dirs:

        ## Get Describe Directory Services Client
        ds_client = get_new_client(config_dir["account"], "ds", "us-west-
           2")
        ## Get All Directories in Account
        temp_dirs = ds_client.describe_directories()

</code>```

答:
This is what worked for me per Pylint "unresolved import" error in visual studio code

"The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:"

PYTHONPATH=YOUR/MODULES/PATH
and in your settings.json add

"python.envFile": ".env"

Body:
I found an example online of a config file to build on the base logging and colorlog.

File Structure

main.py
directory.py
client.py
/utils/log.py

main, directory and client all have from utils.log import init_logger which is the function inside my log.py.

For processing,
main.py imports a function from directory.py which imports a function from client.py.

VSCODE complains that the modules can't be imported, but the script runs fine with no errors except vscode complaining.

I think I have a circular dependency issue going on, but can't figure out how I should share the logging config between all my files without importing it.

main.py

"""
Setup Trusts Between Directories
"""
import json
from utils.log import init_logger
from directory import stage

###############
def main():
    """
    MAIN TRUST FUNCTION
    """

    ## Initialize Logger
    if __name__ == "__main__":
        logger = init_logger(__name__, testing_mode=False)
        logger.info("Running Creator")

    ## Get Outputs
    new_dirs = get_output("newDirectoryIds")
    config_dirs = get_output("configDirectories")

    ## Get Directory Stage
    stage(new_dirs, config_dirs)

###############

## Run Main Function
main()

directory.py

"""
directory.py
- Loops Through List of Directories
- Returns back when stage is Active or Failed
"""
import time
from utils.log import init_logger
from get_client import get_new_client

###########
def stage(new_dirs, config_dirs):
    """
    Returns Directory Stage Value
    - Loops until Directory is Failed or Active
    """

    ## Initialize Logger
    logger = init_logger(__name__, testing_mode=True)

     for config_dir in config_dirs:

        ## Get Describe Directory Services Client
        ds_client = get_new_client(config_dir["account"], "ds", "us-west-
           2")
        ## Get All Directories in Account
        temp_dirs = ds_client.describe_directories()


问:
kubernetes multi domain dynamic routing
Hello I would like to know how to dynamically route multiple domains to different services in Kubernetes, I'm trying to let my users add a domain to their accounts and based on that domain route to a specific service to render their webpage but with their domain. I have no idea where to start and would like to know if this is possible with Kubernetes.</p>

答:
You can create ingress object to route the traffic based on host URL.</p>

```<code> Ex:
 apiVersion: networking.k8s.io/v1beta1
 kind: Ingress
 metadata:
   name: name-virtual-host-ingress
 spec:
    rules:
    - host: foo.bar.com
      http:
        paths:
        - backend:
            serviceName: service1
            servicePort: 80
    - host: bar.foo.com
      http:
        paths:
          - backend:
              serviceName: service2
              servicePort: 80
</code>```

Title: kubernetes multi domain dynamic routing

Body:
You can create ingress object to route the traffic based on host URL.

 Ex:
 apiVersion: networking.k8s.io/v1beta1
 kind: Ingress
 metadata:
   name: name-virtual-host-ingress
 spec:
    rules:
    - host: foo.bar.com
      http:
        paths:
        - backend:
            serviceName: service1
            servicePort: 80
    - host: bar.foo.com
      http:
        paths:
          - backend:
              serviceName: service2
              servicePort: 80


问:
mysql C++ connector [mysql-connector-c++-8.0.19-linux-glibc2.12-x86-64bit]
My application crashes:

```<code>static sql::Driver *driver=get_driver_instance();
shared_ptr<sql::Connection> con(driver->connect("127.0.0.1:3306","asif", "password"));
con->setSchema("asif");  //it crashes here (segv)
</code>```

The code is straight from the sample provided on mysql C++ connector related site

I have the schema asif

```<code>mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| CREBACO            |
| asif               |
| asif1              |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
8 rows in set (0.00 sec)

mysql> use asif;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------+
| Tables_in_asif |
+----------------+
| tab1           |
| tab2           |
+----------------+
2 rows in set (0.00 sec)
</code>```

on debugging:

```<code>#0  __memmove_sse2_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:371
#1  0x00007ffff7301c80 in std::string::append(std::string const&) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007ffff7634efe in sql::SQLString::append (str=..., this=0x7fffffffdc10)
    at /export/home/pb2/build/sb_0-32258110-1547655664.03/mysql-connector-c++-1.1.12/cppconn/sqlstring.h:155
#3  sql::mysql::MySQL_Connection::setSchema (this=0x55555578bed0, catalog=...)
    at /export/home/pb2/build/sb_0-32258110-1547655664.03/mysql-connector-c++-1.1.12/driver/mysql_connection.cpp:1345
#4  0x000055555555585d in main () at ../Crebaco/main.cpp:25
</code>```

call stack from GDB , I get the same error with mysql-connector-c++-1.1.12

答:
the code is pretty simple (This is not the answer), could you try this code to connect to your instance of MYSQL</p>

```<code>//export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/asif/Desktop/QT/Crebaco/mysql-connector-c++-8.0.19-linux-glibc2.12-x86-64bit/lib64

#include <iostream>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

using namespace std;

#define SERVERSTRING "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "password"
#define DATABASE "test"

int main()
{
    cout<<"Content-Type: application/txt\r\n\r\n";

    try {
      static sql::Driver *driver=get_driver_instance();
      shared_ptr<sql::Connection> con(driver->connect("127.0.0.1:3306","asif", "password"));
      con->setSchema("asif");

      shared_ptr<sql::Statement> stmt(con->createStatement());
      shared_ptr<sql::ResultSet> res(stmt->executeQuery("select * from tab1"));

      while (res->next()) {
          cout << res->getString("name") << endl;
      }

    }catch(sql::SQLException &e)
    {
        cout << "# ERR: " << e.what()<<endl;
        cout << "MySQL error code: " << e.getErrorCode()<<endl;
          //cout << ", SQLState: " << e.getSQLState()<<endl;
    }

    return 0;
}
</code>```

Body:
My application crashes:

static sql::Driver *driver=get_driver_instance();
shared_ptr<sql::Connection> con(driver->connect("127.0.0.1:3306","asif", "password"));
con->setSchema("asif");  //it crashes here (segv)

The code is straight from the sample provided on mysql C++ connector related site

I have the schema asif

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| CREBACO            |
| asif               |
| asif1              |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
8 rows in set (0.00 sec)

mysql> use asif;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------+
| Tables_in_asif |
+----------------+
| tab1           |
| tab2           |
+----------------+
2 rows in set (0.00 sec)

on debugging:

#0  __memmove_sse2_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:371
#1  0x00007ffff7301c80 in std::string::append(std::string const&) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007ffff7634efe in sql::SQLString::append (str=..., this=0x7fffffffdc10)
    at /export/home/pb2/build/sb_0-32258110-1547655664.03/mysql-connector-c++-1.1.12/cppconn/sqlstring.h:155
#3  sql::mysql::MySQL_Connection::setSchema (this=0x55555578bed0, catalog=...)
    at /export/home/pb2/build/sb_0-32258110-1547655664.03/mysql-connector-c++-1.1.12/driver/mysql_connection.cpp:1345
#4  0x000055555555585d in main () at ../Crebaco/main.cpp:25

call stack from GDB , I get the same error with mysql-connector-c++-1.1.12

Body:
the code is pretty simple (This is not the answer), could you try this code to connect to your instance of MYSQL

//export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/asif/Desktop/QT/Crebaco/mysql-connector-c++-8.0.19-linux-glibc2.12-x86-64bit/lib64

#include <iostream>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

using namespace std;

#define SERVERSTRING "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "password"
#define DATABASE "test"

int main()
{
    cout<<"Content-Type: application/txt\r\n\r\n";

    try {
      static sql::Driver *driver=get_driver_instance();
      shared_ptr<sql::Connection> con(driver->connect("127.0.0.1:3306","asif", "password"));
      con->setSchema("asif");

      shared_ptr<sql::Statement> stmt(con->createStatement());
      shared_ptr<sql::ResultSet> res(stmt->executeQuery("select * from tab1"));

      while (res->next()) {
          cout << res->getString("name") << endl;
      }

    }catch(sql::SQLException &e)
    {
        cout << "# ERR: " << e.what()<<endl;
        cout << "MySQL error code: " << e.getErrorCode()<<endl;
          //cout << ", SQLState: " << e.getSQLState()<<endl;
    }

    return 0;
}


问:
How to I fix this visual studio bug for my c++ program?
I have written this program in C++ and when I run it in visual studio my output is:

```<code>[Running] cd "c:\Users\Me\OneDrive\Desktop\c++\" && g++ main.cpp -o main && "c:\Users\Me\OneDrive\Desktop\c++\"main
Access is denied.

[Done] exited with code=1 in 0.636 seconds
</code>```

The 'cout' does work when I output an integer and floats, it seems it just wont output strings but the printf function does. How do I solve this>?

Here is my code

```<code>#include <iostream>

using namespace std;

int main() {

    cout << "Hello, world!" << endl;
    return 0;
}
</code>```

答:
Access is denied may be a permission issue. Ensure you have permission to run in the directory you are in and the compiled code can output libs correctly.

In the folder this class is in, right click and go to security and add your account with read and write access.

Let me know if this works for your environment. Do feel free to elaborate on your G++ reference however. The code below compiles and has no real difference to your approach.

```<code>#include <iostream>
using namespace std;

int main() {
        cout << "Hello, World!";
        return 0;
    }
</code>```

Body:
I have written this program in C++ and when I run it in visual studio my output is:

[Running] cd "c:\Users\Me\OneDrive\Desktop\c++\" && g++ main.cpp -o main && "c:\Users\Me\OneDrive\Desktop\c++\"main
Access is denied.

[Done] exited with code=1 in 0.636 seconds

The 'cout' does work when I output an integer and floats, it seems it just wont output strings but the printf function does. How do I solve this>?

Here is my code

#include <iostream>

using namespace std;

int main() {

    cout << "Hello, world!" << endl;
    return 0;
}

Body:
Access is denied may be a permission issue. Ensure you have permission to run in the directory you are in and the compiled code can output libs correctly.

In the folder this class is in, right click and go to security and add your account with read and write access.

Let me know if this works for your environment. Do feel free to elaborate on your G++ reference however. The code below compiles and has no real difference to your approach.

#include <iostream>
using namespace std;

int main() {
        cout << "Hello, World!";
        return 0;
    }


问:
*.bat that save path folder as variable
I try to do a little tool in *.bat but I didn't found an answer like I am looking for.
The idea is by double clicking to the script, a window popup to select a folder and save the path folder as a kind of "variable" and put it inside a string as shown as below.
I would like to unzip recursively from multiple directory and sub-directory.

```<code>@echo off
Title unzip_bz2
for /r "%Location%" %I IN (*.bz2) DO 7z x %I -o"%~dpI"
</code>```

to have something like:

```<code>FOR /R C:\Users\steph\Desktop\my_bz2_file\ %I IN (*.bz2) DO 7z x %I -o"%~dpI"
</code>```

Thanks in advance for your advise and help.

答:
If I understand your question correctly, you could utilise jscript from your batch-file to help you with this task:

0</* :
@For /F "Delims=" %%G In (
    '""%__APPDIR__%cscript.exe" //E:JScript //NoLogo "%~f0" 2>Nul|Find /V """'
)Do @For /F "Delims=" %%H In ('Dir /B/S/A-D "%%G\*.bz2" 2^>NUL')Do @7z.exe x "%%H" -o"%%~dpH"
@Exit /B */0;
var Folder=new ActiveXObject('Shell.Application').BrowseForFolder(0,'Select your directory.',1,'0');
try{new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(Folder.Self.Path)};catch(e){};close();
```

Obviously for this to work using your provided 7z command, 7z.exe must be in the current directory, located within %PATH%, or its location specified in the relevant registry key. If not you'd need to provide the full path to 7z.exe

Title: *.bat that save path folder as variable

Body:
I try to do a little tool in *.bat but I didn't found an answer like I am looking for.
The idea is by double clicking to the script, a window popup to select a folder and save the path folder as a kind of "variable" and put it inside a string as shown as below.
I would like to unzip recursively from multiple directory and sub-directory.

@echo off
Title unzip_bz2
for /r "%Location%" %I IN (*.bz2) DO 7z x %I -o"%~dpI"

to have something like:

FOR /R C:\Users\steph\Desktop\my_bz2_file\ %I IN (*.bz2) DO 7z x %I -o"%~dpI"

Thanks in advance for your advise and help.

Body:
If I understand your question correctly, you could utilise jscript from your batch-file to help you with this task:

0</* :
@For /F "Delims=" %%G In (
    '""%__APPDIR__%cscript.exe" //E:JScript //NoLogo "%~f0" 2>Nul|Find /V """'
)Do @For /F "Delims=" %%H In ('Dir /B/S/A-D "%%G\*.bz2" 2^>NUL')Do @7z.exe x "%%H" -o"%%~dpH"
@Exit /B */0;
var Folder=new ActiveXObject('Shell.Application').BrowseForFolder(0,'Select your directory.',1,'0');
try{new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(Folder.Self.Path)};catch(e){};close();

Obviously for this to work using your provided 7z command, 7z.exe must be in the current directory, located within %PATH%, or its location specified in the relevant registry key. If not you'd need to provide the full path to 7z.exe


问:
How to set global variable in ndoe js that can be accessible in all twig page
I need to create some variable that can be accessible in all twig template , without add him to all render object in express.

Or i need a methode that add this variable after the controller has finish his traitement.

答:
try use app.locals

http://expressjs.com/en/5x/api.html#app.locals

app.locals
The app.locals object has properties that are local variables within the application.

```<code>console.dir(app.locals.title)
// => 'My App'

console.dir(app.locals.email)
// => 'me@myapp.com'
</code>```

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app)

```<code>app.locals.title = 'My App'
app.locals.strftime = require('strftime')
app.locals.email = 'me@myapp.com'
</code>```

Body:
try use app.locals

http://expressjs.com/en/5x/api.html#app.locals

app.locals
The app.locals object has properties that are local variables within the application.

console.dir(app.locals.title)
// => 'My App'

console.dir(app.locals.email)
// => 'me@myapp.com'

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app)

app.locals.title = 'My App'
app.locals.strftime = require('strftime')
app.locals.email = 'me@myapp.com'


问:
Keras CNN for Image transformation, NAN loss
I am writing a CNN for for an image transformation (usually done with fourier transform and set of parameters)

I am having trouble with my loss function returning NAN from the first epoch, I've tried changing my optimizers, adjusting learning rate, adding dropout and batch normalization, changing the design of my model but nothing seems to be working.

I've also ensure my data has no nan of inf in itself. My data set does contain a large amount of zeros so im not sure if this is affecting it. I have normalized the data to be in range [0,1]

even if I simplify it to only have this layer the loss is nan right away (# channels = 1, image size 1024x1024):

```<code>model.add(Conv2D(1, 1 , activation = 'relu', input_shape = (1,1024, 1024),
                 kernel_regularizer=regularizers.l2(0.01),
                 bias_regularizer=regularizers.l2(0.01)))

opt = Adagrad(learning_rate = 0.0001, clipvalue = .5)
model.compile(optimizer = opt, loss = 'mean_squared_error',
          metrics= ['acc', 'mse'])

history = model.fit_generator(generator=training_generator,
                steps_per_epoch = 30, verbose = 2,
                epochs = 20)
</code>```

I am using my own generator to feed batches of the image data to the model. I'm currently using a batch size of only 2.

The output is currently just:

```<code>    Epoch 1/20
    - 62s - loss: nan - acc: 0.2009 - mse: nan
    Epoch 2/20
   - 61s - loss: nan - acc: 0.2007 - mse: nan
   Epoch 3/20
   - 62s - loss: 9.5592 - acc: 0.1675 - mse: 0.2778
   Epoch 4/20
   - 61s - loss: nan - acc: 0.2340 - mse: nan
   Epoch 5/20
   - 61s - loss: nan - acc: 0.1172 - mse: nan
   Epoch 6/20
   - 61s - loss: nan - acc: 0.1173 - mse: nan
</code>```

and so on

The problem I am trying to model is am image transformation to a hologram using fourier transform and phase shift, the output image should have the same dimensions as the input (1, 1024, 1024)

Any help or insight would be greatly appreciated, maybe I am just missing a very obvious step!

答:
I think your problem comes from the way you defined your model :

You are using the mean_squarred_error loss, so you are calculating the squarred error of every pixel on your image !

Moreover, your are using relu activation, so your model can predict values between 0 and inf.

Those two point combinated : image of 1024 * 1024 with a mean error of 50 makes you a loss so hudge that it goes NaN.

Give us more precisions about what you are trying to predicting if you want more help on what kind of activation/loss using !

Body:
I am writing a CNN for for an image transformation (usually done with fourier transform and set of parameters)

I am having trouble with my loss function returning NAN from the first epoch, I've tried changing my optimizers, adjusting learning rate, adding dropout and batch normalization, changing the design of my model but nothing seems to be working.

I've also ensure my data has no nan of inf in itself. My data set does contain a large amount of zeros so im not sure if this is affecting it. I have normalized the data to be in range [0,1]

even if I simplify it to only have this layer the loss is nan right away (# channels = 1, image size 1024x1024):

model.add(Conv2D(1, 1 , activation = 'relu', input_shape = (1,1024, 1024),
                 kernel_regularizer=regularizers.l2(0.01),
                 bias_regularizer=regularizers.l2(0.01)))

opt = Adagrad(learning_rate = 0.0001, clipvalue = .5)
model.compile(optimizer = opt, loss = 'mean_squared_error',
          metrics= ['acc', 'mse'])

history = model.fit_generator(generator=training_generator,
                steps_per_epoch = 30, verbose = 2,
                epochs = 20)

I am using my own generator to feed batches of the image data to the model. I'm currently using a batch size of only 2.

The output is currently just:

    Epoch 1/20
    - 62s - loss: nan - acc: 0.2009 - mse: nan
    Epoch 2/20
   - 61s - loss: nan - acc: 0.2007 - mse: nan
   Epoch 3/20
   - 62s - loss: 9.5592 - acc: 0.1675 - mse: 0.2778
   Epoch 4/20
   - 61s - loss: nan - acc: 0.2340 - mse: nan
   Epoch 5/20
   - 61s - loss: nan - acc: 0.1172 - mse: nan
   Epoch 6/20
   - 61s - loss: nan - acc: 0.1173 - mse: nan

and so on

The problem I am trying to model is am image transformation to a hologram using fourier transform and phase shift, the output image should have the same dimensions as the input (1, 1024, 1024)

Any help or insight would be greatly appreciated, maybe I am just missing a very obvious step!


问:
AWS API Gateway Response Mapping Template not working
I'm sure I'm missing something really simple here but is driving me mad! Thanks in advance!

I am setting up a really simple test Api Gateway with a single GET method which triggers an Lambda which returns the following JSON:

```<code>    {
     "coaches": [
       {
         "name": "Coach1",
         "id": "5"
       },
       {
          "name": "Coach2",
          "id": "7"
       }
    ]
   }
</code>```

When I test the method (in AWS Console) I can see the following log line:

Wed Feb 05 15:22:48 UTC 2020 : Endpoint response body before transformations: "{\"coaches\":[{\"name\":\"Coach1\",\"id\":\"5\"},{\"name\":\"Coach2\",\"id\":\"7\"}]}"

Which seems fine.

Now I simply want to reformat the output to make it look a bit prettier, so am trying to configure a Integration Response Mapping Template as so:

[1]: https://i.stack.imgur.com/5I4Lg.png

Code below:

```<code>#set($inputRoot = $input.path('$'))
{
  "coaches": [
#foreach($elem in $inputRoot.coaches)
    {
      "id": "$elem.id",
      "coach": "$elem.name",
    }#if($foreach.hasNext),#end

#end
  ]
}
</code>```

However the next log line in the output is:

Wed Feb 05 15:22:48 UTC 2020 : Method response body after
  transformations: {   "coaches": [   ] }

So transformation doesn't seem to have worked. Not sure what I'm doing wrong though?

答:
It seems the problem is with the collection you try to iterate on, and thus the array is empty. There is no $inputRoot.coaches collection, as opposed to params collection, which is defined under $input object.

An example of extracting the whole query string parameters:

```<code>{
  "queryStringParameters": {
  #foreach($key in
   $input.params().querystring.keySet())#if($foreach.index >0),#end
  "$key":"$input.params().querystring.get($key)"#end
   }
}
</code>```

Nevertheless, you can try to extract your $coaches collection from the JSON input with the method $input.json(x); this function evaluates a JSON expression, for example: $input.json('$.coaches') returns a JSON string representing the coaches structure.

For more details, please refer to API Gateway Mapping Template documentation

I also invite you to read my blog-post about API Gateway request parameters:
Controlling and Manipulating AWS API Gateway Request Parameters

Body:
I'm sure I'm missing something really simple here but is driving me mad! Thanks in advance!

I am setting up a really simple test Api Gateway with a single GET method which triggers an Lambda which returns the following JSON:

    {
     "coaches": [
       {
         "name": "Coach1",
         "id": "5"
       },
       {
          "name": "Coach2",
          "id": "7"
       }
    ]
   }

When I test the method (in AWS Console) I can see the following log line:

Wed Feb 05 15:22:48 UTC 2020 : Endpoint response body before transformations: "{\"coaches\":[{\"name\":\"Coach1\",\"id\":\"5\"},{\"name\":\"Coach2\",\"id\":\"7\"}]}"

Which seems fine.

Now I simply want to reformat the output to make it look a bit prettier, so am trying to configure a Integration Response Mapping Template as so:

[1]: https://i.stack.imgur.com/5I4Lg.png

Code below:

#set($inputRoot = $input.path('$'))
{
  "coaches": [
#foreach($elem in $inputRoot.coaches)
    {
      "id": "$elem.id",
      "coach": "$elem.name",
    }#if($foreach.hasNext),#end

#end
  ]
}

However the next log line in the output is:

Wed Feb 05 15:22:48 UTC 2020 : Method response body after
  transformations: {   "coaches": [   ] }

So transformation doesn't seem to have worked. Not sure what I'm doing wrong though?

Body:
It seems the problem is with the collection you try to iterate on, and thus the array is empty. There is no $inputRoot.coaches collection, as opposed to params collection, which is defined under $input object.

An example of extracting the whole query string parameters:

{
  "queryStringParameters": {
  #foreach($key in
   $input.params().querystring.keySet())#if($foreach.index >0),#end
  "$key":"$input.params().querystring.get($key)"#end
   }
}

Nevertheless, you can try to extract your $coaches collection from the JSON input with the method $input.json(x); this function evaluates a JSON expression, for example: $input.json('$.coaches') returns a JSON string representing the coaches structure.

For more details, please refer to API Gateway Mapping Template documentation

I also invite you to read my blog-post about API Gateway request parameters:
Controlling and Manipulating AWS API Gateway Request Parameters


问:
Why am I getting a reversed NFC Tag ID (Hex)?
I want my app to scan an NFC tag and get its ID and tag type. But somehow my code reads a reversed tag ID.

For instance my app reads the following tag ID (hex): 80 65 69 e2 f5 fe 04
while 4 other similar apps from Google Play Store read the following ID: 4 fe f5 e2 69 65 80 (where the first zero is also missing)

I want my app to read the tag ID without reverting the bytes, how can I achieve that? Here is my complete code:

```<code>package com.asetnfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import static android.content.ContentValues.TAG;

//public class MainActivity extends AppCompatActivity {

public class InfoNFC extends Activity {
    private TextView mTextView; //ECP 2017-01-16

    // list of NFC technologies detected:
    private final String[][] techList = new String[][] {
            new String[] {
                    NfcA.class.getName(),
                    NfcB.class.getName(),
                    NfcF.class.getName(),
                    NfcV.class.getName(),
                    IsoDep.class.getName(),
                    MifareClassic.class.getName(),
                    MifareUltralight.class.getName(), Ndef.class.getName()
            }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.infonfc);

        mTextView = (TextView) findViewById(R.id.infonfctype);
        mTextView.setText("Data Tampil Disini");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("onResume", "1");

        //mTextView.setText("onResume:");
        // creating pending intent:
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        // creating intent receiver for NFC events:
        IntentFilter filter = new IntentFilter();
        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
        // enabling foreground dispatch for getting intent from NFC event:
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
    }

    @Override
    protected void onPause() {
        super.onPause();

        Log.d("onPause", "1");

        // disabling foreground dispatch:
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d("onNewIntent", "1");

        if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
            Log.d("onNewIntent", "2");
            mTextView.setText( "NFC Tag\n" + ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));

            //if(getIntent().hasExtra(NfcAdapter.EXTRA_TAG)){

            Parcelable tagN = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tagN != null) {
                Log.d(TAG, "Parcelable OK");
                NdefMessage[] msgs;
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                byte[] payload = dumpTagData(tagN).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };

                //Log.d(TAG, msgs[0].toString());

            }
            else {
                Log.d(TAG, "Parcelable NULL");
            }

            Parcelable[] messages1 = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (messages1 != null) {
                Log.d(TAG, "Found " + messages1.length + " NDEF messages");
            }
            else {
                Log.d(TAG, "Not EXTRA_NDEF_MESSAGES");
            }

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Ndef ndef = Ndef.get(tag);
            if(ndef != null) {

                Log.d("onNewIntent:", "NfcAdapter.EXTRA_TAG");

                Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                if (messages != null) {
                    Log.d(TAG, "Found " + messages.length + " NDEF messages");
                }
            }
            else {
                Log.d(TAG, "Write to an unformatted tag not implemented");
            }

            //mTextView.setText( "NFC Tag\n" + ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_TAG)));
        }
    }

    private String dumpTagData(Parcelable p) {
        StringBuilder sb = new StringBuilder();
        Tag tag = (Tag) p;
        byte[] id = tag.getId();
        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                MifareClassic mifareTag = MifareClassic.get(tag);
                String type = "Unknown";
                switch (mifareTag.getType()) {
                    case MifareClassic.TYPE_CLASSIC:
                        type = "Classic";
                        break;
                    case MifareClassic.TYPE_PLUS:
                        type = "Plus";
                        break;
                    case MifareClassic.TYPE_PRO:
                        type = "Pro";
                        break;
                }
                sb.append("Mifare Classic type: ");
                sb.append(type);
                sb.append('\n');

                sb.append("Mifare size: ");
                sb.append(mifareTag.getSize() + " bytes");
                sb.append('\n');

                sb.append("Mifare sectors: ");
                sb.append(mifareTag.getSectorCount());
                sb.append('\n');

                sb.append("Mifare blocks: ");
                sb.append(mifareTag.getBlockCount());
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }
        Log.d("Datos: ", sb.toString());

        mTextView.setText('\n' + sb.toString());
        return sb.toString();
    }

    private String getHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private String ByteArrayToHexString(byte [] inarray) {

        Log.d("ByteArrayToHexString", inarray.toString());

        int i, j, in;
        String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        String out= "";

        for(j = 0 ; j < inarray.length ; ++j)
        {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
//CE7AEED4
//EE7BEED4
        Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));

        return out;
    }

}

</code>```

答:
In your function getHex() you are starting from last byte and then decrementing the i counter.
try to use this function:

```<code>private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHexString(byte[] bytes) {
    if (bytes == null) {
        return null;
    }
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}
</code>```

Body:
I want my app to scan an NFC tag and get its ID and tag type. But somehow my code reads a reversed tag ID.

For instance my app reads the following tag ID (hex): 80 65 69 e2 f5 fe 04
while 4 other similar apps from Google Play Store read the following ID: 4 fe f5 e2 69 65 80 (where the first zero is also missing)

I want my app to read the tag ID without reverting the bytes, how can I achieve that? Here is my complete code:

package com.asetnfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import static android.content.ContentValues.TAG;

//public class MainActivity extends AppCompatActivity {

public class InfoNFC extends Activity {
    private TextView mTextView; //ECP 2017-01-16

    // list of NFC technologies detected:
    private final String[][] techList = new String[][] {
            new String[] {
                    NfcA.class.getName(),
                    NfcB.class.getName(),
                    NfcF.class.getName(),
                    NfcV.class.getName(),
                    IsoDep.class.getName(),
                    MifareClassic.class.getName(),
                    MifareUltralight.class.getName(), Ndef.class.getName()
            }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.infonfc);

        mTextView = (TextView) findViewById(R.id.infonfctype);
        mTextView.setText("Data Tampil Disini");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("onResume", "1");

        //mTextView.setText("onResume:");
        // creating pending intent:
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        // creating intent receiver for NFC events:
        IntentFilter filter = new IntentFilter();
        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
        // enabling foreground dispatch for getting intent from NFC event:
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
    }

    @Override
    protected void onPause() {
        super.onPause();

        Log.d("onPause", "1");

        // disabling foreground dispatch:
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d("onNewIntent", "1");

        if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
            Log.d("onNewIntent", "2");
            mTextView.setText( "NFC Tag\n" + ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));

            //if(getIntent().hasExtra(NfcAdapter.EXTRA_TAG)){

            Parcelable tagN = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tagN != null) {
                Log.d(TAG, "Parcelable OK");
                NdefMessage[] msgs;
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                byte[] payload = dumpTagData(tagN).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };

                //Log.d(TAG, msgs[0].toString());

            }
            else {
                Log.d(TAG, "Parcelable NULL");
            }

            Parcelable[] messages1 = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (messages1 != null) {
                Log.d(TAG, "Found " + messages1.length + " NDEF messages");
            }
            else {
                Log.d(TAG, "Not EXTRA_NDEF_MESSAGES");
            }

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Ndef ndef = Ndef.get(tag);
            if(ndef != null) {

                Log.d("onNewIntent:", "NfcAdapter.EXTRA_TAG");

                Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                if (messages != null) {
                    Log.d(TAG, "Found " + messages.length + " NDEF messages");
                }
            }
            else {
                Log.d(TAG, "Write to an unformatted tag not implemented");
            }

            //mTextView.setText( "NFC Tag\n" + ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_TAG)));
        }
    }

    private String dumpTagData(Parcelable p) {
        StringBuilder sb = new StringBuilder();
        Tag tag = (Tag) p;
        byte[] id = tag.getId();
        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                MifareClassic mifareTag = MifareClassic.get(tag);
                String type = "Unknown";
                switch (mifareTag.getType()) {
                    case MifareClassic.TYPE_CLASSIC:
                        type = "Classic";
                        break;
                    case MifareClassic.TYPE_PLUS:
                        type = "Plus";
                        break;
                    case MifareClassic.TYPE_PRO:
                        type = "Pro";
                        break;
                }
                sb.append("Mifare Classic type: ");
                sb.append(type);
                sb.append('\n');

                sb.append("Mifare size: ");
                sb.append(mifareTag.getSize() + " bytes");
                sb.append('\n');

                sb.append("Mifare sectors: ");
                sb.append(mifareTag.getSectorCount());
                sb.append('\n');

                sb.append("Mifare blocks: ");
                sb.append(mifareTag.getBlockCount());
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }
        Log.d("Datos: ", sb.toString());

        mTextView.setText('\n' + sb.toString());
        return sb.toString();
    }

    private String getHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private String ByteArrayToHexString(byte [] inarray) {

        Log.d("ByteArrayToHexString", inarray.toString());

        int i, j, in;
        String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        String out= "";

        for(j = 0 ; j < inarray.length ; ++j)
        {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
//CE7AEED4
//EE7BEED4
        Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));

        return out;
    }

}

Body:
In your function getHex() you are starting from last byte and then decrementing the i counter.
try to use this function:

private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHexString(byte[] bytes) {
    if (bytes == null) {
        return null;
    }
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}


问:
Jquery Cookie plugin, check to see if cookie is unset
So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:

```<code>if ($.cookie('language')==null) {

}
</code>```

This doesn't seem to work. Any ideas why?

答:
Line #90 in the source looks like that SHOULD be the result you want. Check for any errors and test what happens if the cookie is set.

https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

Body:
So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:

if ($.cookie('language')==null) {

}

This doesn't seem to work. Any ideas why?


问:
Curl / php Empty response from PayPal IPN url
In the past couple of days, our PayPal IPN has stopped working and receiving a empty response from PayPal.  Nothing has changed on the server or in our code.

Attempting to cUrl to the PayPal IPN url simply returns an empty response.

```<code>$url = "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

$data = curl_exec($ch);
curl_close($ch);

print $data;
</code>```

The above should return "INVALID" and works as expected on my localhost and from other servers.
Changing the url to any other domain other then PayPal also works without issues.

So it seems it only received the empty response from paypal.com

I wonder if any one has run into the issue or could give pointers where to look in the hope to- resolve it?

Kind Regards
Musaffar

答:
I would perhaps start checking if curl gave you any errors. PHP gives you in this case curl_errno($ch) and curl_error($ch) which will return a message or respectively the error code to it.

In case there is nothing suspicious to it. I would perhaps try to validate if you're able to run the above from your CLI on the server. (requires SSH access to it)

```<code>curl -H "User-Agent: ..." "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate"
</code>```

I hope this gives you a good starting point. Please let me know if this helps or if you need more ideas.

Edit#2: After comments where added from the author:

cUrl does indeed return an error : error 35 and the error message is as follows:

```<code>error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
</code>```

In this case I would guess that your system is outdated and does not support the SSL ciphers from paypal. You could try to force a specific TLS version. As of today paypal webservers support only TLS1.2 or TLS1.3. This is how you can force it:

```<code>curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
</code>```

or

```<code>curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_3);
</code>```

Additionaly @Preston PHX mentioned in a comment a good refernces for this issue coming from paypal:

https://github.com/paypal/TLS-update#php

https://developer.paypal.com/docs/api/info-security-guidelines/

Body:
In the past couple of days, our PayPal IPN has stopped working and receiving a empty response from PayPal.  Nothing has changed on the server or in our code.

Attempting to cUrl to the PayPal IPN url simply returns an empty response.

$url = "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

$data = curl_exec($ch);
curl_close($ch);

print $data;

The above should return "INVALID" and works as expected on my localhost and from other servers.
Changing the url to any other domain other then PayPal also works without issues.

So it seems it only received the empty response from paypal.com

I wonder if any one has run into the issue or could give pointers where to look in the hope to- resolve it?

Kind Regards
Musaffar

Body:
I would perhaps start checking if curl gave you any errors. PHP gives you in this case curl_errno($ch) and curl_error($ch) which will return a message or respectively the error code to it.

In case there is nothing suspicious to it. I would perhaps try to validate if you're able to run the above from your CLI on the server. (requires SSH access to it)

curl -H "User-Agent: ..." "https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate"

I hope this gives you a good starting point. Please let me know if this helps or if you need more ideas.

Edit#2: After comments where added from the author:

cUrl does indeed return an error : error 35 and the error message is as follows:

error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version

In this case I would guess that your system is outdated and does not support the SSL ciphers from paypal. You could try to force a specific TLS version. As of today paypal webservers support only TLS1.2 or TLS1.3. This is how you can force it:

curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);

or

curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_3);

Additionaly @Preston PHX mentioned in a comment a good refernces for this issue coming from paypal:

https://github.com/paypal/TLS-update#php

https://developer.paypal.com/docs/api/info-security-guidelines/


问:
NGINX 404 when requesting non root location
I have this basic conf file:

```<code>server {

    root /usr/share/nginx/html/default/public;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass my-php:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;

        fastcgi_param SERVER_PORT $server_port;
    }

    location ~ \.php$ {
      return 404;
    }

    location ~ /\.ht {
         deny  all;
    }
}
</code>```

located in the Nginx docker conteainer:/etc/nginx/conf.d/default.conf

it works well if I request website

127.0.0.1:8080

but fails with 404 if I want to access from a browser a file:
127.0.0.1:8080/check.php

even the file exists in the public dir and if I rename it to index.php it loads wihtout any problem by requesting 127.0.0.1:8080 but what needs to be changed in nginx conf so the check.php file would be available by 127.0.0.1:8080/check.php?

Issue2:
I can request 127.0.0.1:8080 with 200 OK and BODY as expected but I get:

```<code>http://127.0.0.1:8080/index.php 404 Not Found
http://127.0.0.1:8080/check.php 404 Not Found
</code>```

and if I turn off this block:

```<code>location / {
    try_files $uri /index.php$is_args$args;
}
</code>```

i get access.log "GET / HTTP/1.1" 403
and request-response

```<code>http://127.0.0.1:8080/ 403 Forbidden
</code>```

but this matching seems to work:

```<code>location ~ ^/index\.php(/|$) { ... }
</code>```

for php because if I make fastcgi_pass invalid

```<code>fastcgi_pass wrong-containername:9000;
</code>```

i get errors instead of 200 OK.

1.How to make a pattern for php-fpm location that will work with

```<code>http(s)://127.0.0.1:8080/
http(s)://127.0.0.1:8080/index.php
http(s)://127.0.0.1:8080/check.php
</code>```

2.And additional that handles all other requests with php-fpm to dirs where could be index.php, or check.php or whatever.php

```<code>http(s)://127.0.0.1:8080/*
</code>```

答:
You config allows for execution of only the index.php. It is a secure config, so I recommend keeping it in place with adjustment to list any additional scripts, e.g. change:

```<code>location ~ ^/index\.php(/|$) {
</code>```

to

```<code>location ~ ^/(index|check)\.php(/|$) {
</code>```

Will allow executing only /index.php and /check.php.

Body:
I have this basic conf file:

server {

    root /usr/share/nginx/html/default/public;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass my-php:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;

        fastcgi_param SERVER_PORT $server_port;
    }

    location ~ \.php$ {
      return 404;
    }

    location ~ /\.ht {
         deny  all;
    }
}

located in the Nginx docker conteainer:/etc/nginx/conf.d/default.conf

it works well if I request website

127.0.0.1:8080

but fails with 404 if I want to access from a browser a file:
127.0.0.1:8080/check.php

even the file exists in the public dir and if I rename it to index.php it loads wihtout any problem by requesting 127.0.0.1:8080 but what needs to be changed in nginx conf so the check.php file would be available by 127.0.0.1:8080/check.php?

Issue2:
I can request 127.0.0.1:8080 with 200 OK and BODY as expected but I get:

http://127.0.0.1:8080/index.php 404 Not Found
http://127.0.0.1:8080/check.php 404 Not Found

and if I turn off this block:

location / {
    try_files $uri /index.php$is_args$args;
}

i get access.log "GET / HTTP/1.1" 403
and request-response

http://127.0.0.1:8080/ 403 Forbidden

but this matching seems to work:

location ~ ^/index\.php(/|$) { ... }

for php because if I make fastcgi_pass invalid

fastcgi_pass wrong-containername:9000;

i get errors instead of 200 OK.

1.How to make a pattern for php-fpm location that will work with

http(s)://127.0.0.1:8080/
http(s)://127.0.0.1:8080/index.php
http(s)://127.0.0.1:8080/check.php

2.And additional that handles all other requests with php-fpm to dirs where could be index.php, or check.php or whatever.php

http(s)://127.0.0.1:8080/*

Body:
You config allows for execution of only the index.php. It is a secure config, so I recommend keeping it in place with adjustment to list any additional scripts, e.g. change:

location ~ ^/index\.php(/|$) {

to

location ~ ^/(index|check)\.php(/|$) {

Will allow executing only /index.php and /check.php.


问:
Docker swarm service port not exposed
I cannot connect to a service running on docker swarm. The swarm seems ok because I can connect to other containers running on it. I running the service with docker stack deploy -c docker-compose.yaml nifi and the docker compose file is:

```<code>version: "3.3"
services:
  registry:
    image: apache/nifi-registry:0.3.0
    ports:
      - "18080:18080"
  deploy:
    replicas: 1
    restart_policy:
      condition: on-failure
</code>```

When I run this without the swarm i.e. docker-compose -f docker-compose.yaml up it works fine and I can browse to it. When I run it with docker stack deploy -c docker-compose.yaml nifi I see the same log entries for the service but cannot browse to it.

```<code>$ docker version

Client:
  Version:      18.03.1-ce
  API version:  1.37
  Go version:   go1.9.5
  Git commit:   9ee9f40
  Built:        Wed Jun 20 21:43:51 2018
  OS/Arch:      linux/amd64
  Experimental: false
  Orchestrator: swarm

Server:
  Engine:
    Version:      18.03.1-ce
    API version:  1.37 (minimum version 1.12)
    Go version:   go1.9.5
    Git commit:   9ee9f40
    Built:        Wed Jun 20 21:42:00 2018
    OS/Arch:      linux/amd64
    Experimental: false
</code>```

Does anyone have suggestions for fixing or troubleshooting this?

答:
In swarm

```<code>ports:
  - "18080:18080"
</code>```

will expose port on all swarm nodes and in case of use of the port on some of the nodes by another service you can have problems

you can expose port only on host with container

```<code>services:
  registry:
    ports:
      - target: 18080
        published: 18080
        mode: host
</code>```

Title: Docker swarm service port not exposed

Body:
I cannot connect to a service running on docker swarm. The swarm seems ok because I can connect to other containers running on it. I running the service with docker stack deploy -c docker-compose.yaml nifi and the docker compose file is:

version: "3.3"
services:
  registry:
    image: apache/nifi-registry:0.3.0
    ports:
      - "18080:18080"
  deploy:
    replicas: 1
    restart_policy:
      condition: on-failure

When I run this without the swarm i.e. docker-compose -f docker-compose.yaml up it works fine and I can browse to it. When I run it with docker stack deploy -c docker-compose.yaml nifi I see the same log entries for the service but cannot browse to it.

$ docker version

Client:
  Version:      18.03.1-ce
  API version:  1.37
  Go version:   go1.9.5
  Git commit:   9ee9f40
  Built:        Wed Jun 20 21:43:51 2018
  OS/Arch:      linux/amd64
  Experimental: false
  Orchestrator: swarm

Server:
  Engine:
    Version:      18.03.1-ce
    API version:  1.37 (minimum version 1.12)
    Go version:   go1.9.5
    Git commit:   9ee9f40
    Built:        Wed Jun 20 21:42:00 2018
    OS/Arch:      linux/amd64
    Experimental: false

Does anyone have suggestions for fixing or troubleshooting this?

Body:
In swarm

ports:
  - "18080:18080"

will expose port on all swarm nodes and in case of use of the port on some of the nodes by another service you can have problems

you can expose port only on host with container

services:
  registry:
    ports:
      - target: 18080
        published: 18080
        mode: host


问:
partition function in SQL Server 2005
In MSDN about partition function from here, $PARTITION(Transact-SQL).

I am confused about what the below sample is doing underlying. My understanding is, this SQL statement will iterate all rows in table Production.TransactionHistory, and since for all the rows which will mapping to the same partition, $PARTITION.TransactionRangePF1(TransactionDate) will return the same value, i.e. the partition number for all such rows. So, for example, all rows in partition 1 will result in one row in returning result since they all of the same value of $PARTITION.TransactionRangePF1(TransactionDate). My understanding correct?

```<code>USE AdventureWorks ;
GO
SELECT $PARTITION.TransactionRangePF1(TransactionDate) AS Partition,
COUNT(*) AS [COUNT] FROM Production.TransactionHistory
GROUP BY $PARTITION.TransactionRangePF1(TransactionDate)
ORDER BY Partition ;
GO
</code>```

答:
Have you tried generating an execution plan for the statement? That might give you some insight into what it's actually doing underneath the cover.

Press "Control-L" to generate an execution plan and post it here if you'd like some interpretation.

ContentLicense: CC BY-SA 2.5

Title: partition function in SQL Server 2005

Body:
In MSDN about partition function from here, $PARTITION(Transact-SQL).

I am confused about what the below sample is doing underlying. My understanding is, this SQL statement will iterate all rows in table Production.TransactionHistory, and since for all the rows which will mapping to the same partition, $PARTITION.TransactionRangePF1(TransactionDate) will return the same value, i.e. the partition number for all such rows. So, for example, all rows in partition 1 will result in one row in returning result since they all of the same value of $PARTITION.TransactionRangePF1(TransactionDate). My understanding correct?

USE AdventureWorks ;
GO
SELECT $PARTITION.TransactionRangePF1(TransactionDate) AS Partition,
COUNT(*) AS [COUNT] FROM Production.TransactionHistory
GROUP BY $PARTITION.TransactionRangePF1(TransactionDate)
ORDER BY Partition ;
GO

LastEditorDisplayName: gbn

OwnerDisplayName: rwmnau


问:
while trying to execute r package using java getting Exited with error code 2
A small issue while trying to execute R package using Java.

```<code>Runtime run = Runtime.getRuntime();
Process pr = null;
String line = null;
BufferedReader input = null;

try {
    pr = run.exec("cmd /c R");
    input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

    while((line = input.readLine()) != null) {
      System.out.println(line);
    }

    int exitVal = pr.waitFor();
    System.out.println("Exited with error code " + exitVal);
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

I'm getting Exited with error code 2. Could any one help me?

答: On Windows exit code 2 generally means "file not found". Check in which folder are you are running the "cmd /c R". You can test this by creating a new file and then search your computer where it was created, or by executing the dir.exe command and then checking the result.</p>

Body:
A small issue while trying to execute R package using Java.

Runtime run = Runtime.getRuntime();
Process pr = null;
String line = null;
BufferedReader input = null;

try {
    pr = run.exec("cmd /c R");
    input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

    while((line = input.readLine()) != null) {
      System.out.println(line);
    }

    int exitVal = pr.waitFor();
    System.out.println("Exited with error code " + exitVal);
} catch (Exception e) {
    e.printStackTrace();
}

I'm getting Exited with error code 2. Could any one help me?


问:
Any Springfox alternatives out there?
Last two years I worked on Spring Boot Applications with Springfox. Springfox generate a documentation and a test ui for your REST API. This was awesome.

But actually Springfox project is dead and do not support the newest Spring. I have three questions

Is there any other way to generate Swagger UI directly? Any other library/project?

How do you implement swagger ui into your Spring Boot project?

答:
Spring doc Open API is alternative going forward.

SpringDoc OpenAPI supports OAS 3.0

Supports more annotations like  @MatrixParam which was not supported
in springfox.

Spring boot 2.2.x works only with springdoc.

Refer the below link

https://techsparx.com/software-development/openapi/spring-boot-rest-api-docs.html

Title: Any Springfox alternatives out there?


问:
Live console input/output for a gameserver using JavaScript or PHP
General information: I have a Minecraft server running in the basement for some friends that is running for a couple months now. We were using TeamViewer to input commands into the console and view possible errors while the server was running. The console of a Minecraft server basically shows you a log of events with timestamps as well as a command input line at the bottom that enables you to execute in-game commands with administrator rights.

The console is started via a batch file:

```<code>:startup
@echo off
set v1=6
cls
Java -Xmx%v1%G -jar spigot.jar nogui
goto startup
</code>```

The spigot.jar file is the file that basically runs the server.

Because we manage multiple servers and the TeamViewer process is quite insecure and slow, i wanted to find other ways to access the console.

Target: I want to create a HTML webinterface that uses JavaScript or PHP to communicate with the server console. It should be able to show the live console log as well as being able to type commands in the browser that are then executed in the commandline on the server.

Problems:

Is there any way to send a JavaScript/PHP input to the console so that I can execute commands from a webinterface?

Can I save the live console output to a .txt file that the JavaScript/PHP script can then display live on the webinterface?

答:
I suppose you could show the log on a website like this:

first gameserver script:

```<code>:startup
@echo off
set v1=6
cls
Java -Xmx%v1%G -jar spigot.jar nogui > log.txt
fileup log.txt
goto startup
</code>```

second gameserver script(called fileup.bat){replace myusername, mypassword and servername.com with the credentials if your php server}:

```<code>@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat
</code>```

php-server side script:

```<code><?php
$filename = "log.txt";
$fp = fopen($filename, "r");

$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
fclose($fp);
print_r($lines);
?>
</code>```

by the way: I have not tested any of these scripts and they might not work, I just based this on my knowledge of php and batch. Also, the second batch script needs to be in the same directory as the first batch script and you do not have to run the second batch script

Note:
I am an experienced PHP user but I do not know very much about batch(I use linux) but I suppose this will work and I have used batch very often in the past. Also I recommend using the PHP script on an external hosted php server from 000webhost.com or infinityfree.net because they are free and save you a lot of time + they have all the needed ftp things preconfigured.

Please let me know if this worked

Body:
General information: I have a Minecraft server running in the basement for some friends that is running for a couple months now. We were using TeamViewer to input commands into the console and view possible errors while the server was running. The console of a Minecraft server basically shows you a log of events with timestamps as well as a command input line at the bottom that enables you to execute in-game commands with administrator rights.

The console is started via a batch file:

:startup
@echo off
set v1=6
cls
Java -Xmx%v1%G -jar spigot.jar nogui
goto startup

The spigot.jar file is the file that basically runs the server.

Because we manage multiple servers and the TeamViewer process is quite insecure and slow, i wanted to find other ways to access the console.

Target: I want to create a HTML webinterface that uses JavaScript or PHP to communicate with the server console. It should be able to show the live console log as well as being able to type commands in the browser that are then executed in the commandline on the server.

Problems:

Is there any way to send a JavaScript/PHP input to the console so that I can execute commands from a webinterface?

Can I save the live console output to a .txt file that the JavaScript/PHP script can then display live on the webinterface?

Body:
I suppose you could show the log on a website like this:

first gameserver script:

:startup
@echo off
set v1=6
cls
Java -Xmx%v1%G -jar spigot.jar nogui > log.txt
fileup log.txt
goto startup

second gameserver script(called fileup.bat){replace myusername, mypassword and servername.com with the credentials if your php server}:

@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat

php-server side script:

<?php
$filename = "log.txt";
$fp = fopen($filename, "r");

$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
fclose($fp);
print_r($lines);
?>

by the way: I have not tested any of these scripts and they might not work, I just based this on my knowledge of php and batch. Also, the second batch script needs to be in the same directory as the first batch script and you do not have to run the second batch script

Note:
I am an experienced PHP user but I do not know very much about batch(I use linux) but I suppose this will work and I have used batch very often in the past. Also I recommend using the PHP script on an external hosted php server from 000webhost.com or infinityfree.net because they are free and save you a lot of time + they have all the needed ftp things preconfigured.

Please let me know if this worked


问:
Kafka connect worker missing AbstractConfig and AvroConverterConfig classes
I am trying to use a kafka connect JDBC sink connector with avro. But when i try to start the connector i keep getting the two following errors :

java.lang.NoClassDefFoundError: io/confluent/connect/avro/AvroConverterConfig

and

java.lang.NoClassDefFoundError: io/confluent/common/config/AbstractConfig.

I am a little but confused here because my plugin path is /app/confluent-5.0.0/share/java

confluent-5.0.0/share/java

And we can see the jar corresponding to the missing class is there.

Anyone has an idea about what is causing this missing class ?

Thanks a lot !

答:
basically i have just pulled the binaries for confluent-5.0.0 from confluent, i have a custom script getting the env variable and setting them to the worker variables like that :

if [ "$1" = 'bash' ]; then
    exec "$@"
else
  if [ -z "$KAFKA_CONNECT_BOOTSTRAP_SERVERS" ]; then
    export KAFKA_CONNECT_BOOTSTRAP_SERVERS="kafka:9092"
  fi

if [ -z "$KAFKA_CONNECT_GROUP_ID" ]; then
    export KAFKA_CONNECT_GROUP_ID="connect-cluster"
  fi

and then calling at the end :

exec $SCRIPTS/connect_distributed.sh /tmp/temp.properties


问:
Laravel parameterBag as array issues when inserting
I am trying to insert mass data but i get this error when i iterate through the request:

Symfony\Component\Debug\Exception\FatalThrowableError Cannot use
  object of type Symfony\Component\HttpFoundation\ParameterBag as array

Request example:

```<code>    request: Symfony\Component\HttpFoundation\ParameterBag {#52 ▼
        #parameters: array:4 [▼
        "_token" => "Z1sF2K5LHU1bsQ4l3JRaOLCTQDmJ47qakigmrfI5"
        "name" => "Rousaddasd 1"
        "secsaddsans" => array:1 [▼
            "secsdfs1" => array:2 [▼
            "name" => "Sectdfs 1"

            ]
        ]
        "submit" => "Submit"
        ]
    }
</code>```

Loop to go through the request and insert:

```<code>$abc = new abc;
$abc->create(['user_id' => 1, 'name' => $request->name, 'description' => 'test description']);
foreach($request as $item){
    $asd = new asd;
    $asd->name = $item['name'];
    $asd->description = 'test description';
    $abc->asds()->create([$asd]);

}
</code>```

Im adding some data "inline" because i didnt handle them in the form yet, thats why the added duration and duration_unit for example.

答:
You can use $request as array like this:

```<code>$request = $request->all();
</code>```

And loop like:

```<code>foreach($request['sections'] as $item) {
   ....

   foreach($item['exercises'] as $item2) {
     ....
   }

}
</code>```

Body:
I am trying to insert mass data but i get this error when i iterate through the request:

Symfony\Component\Debug\Exception\FatalThrowableError Cannot use
  object of type Symfony\Component\HttpFoundation\ParameterBag as array

Request example:

    request: Symfony\Component\HttpFoundation\ParameterBag {#52 ▼
        #parameters: array:4 [▼
        "_token" => "Z1sF2K5LHU1bsQ4l3JRaOLCTQDmJ47qakigmrfI5"
        "name" => "Rousaddasd 1"
        "secsaddsans" => array:1 [▼
            "secsdfs1" => array:2 [▼
            "name" => "Sectdfs 1"

            ]
        ]
        "submit" => "Submit"
        ]
    }

Loop to go through the request and insert:

$abc = new abc;
$abc->create(['user_id' => 1, 'name' => $request->name, 'description' => 'test description']);
foreach($request as $item){
    $asd = new asd;
    $asd->name = $item['name'];
    $asd->description = 'test description';
    $abc->asds()->create([$asd]);

}

Im adding some data "inline" because i didnt handle them in the form yet, thats why the added duration and duration_unit for example.

Body:
You can use $request as array like this:

$request = $request->all();

And loop like:

foreach($request['sections'] as $item) {
   ....

   foreach($item['exercises'] as $item2) {
     ....
   }

}


问:
Brew clang++ issue with cmath in OSX Catalina
Having a recurring issue with cmath upon compiling the source R package in OSX 10.15, as follows;

```<code>In file included from /usr/local/opt/llvm/bin/../include/c++/v1/complex:245:
/usr/local/opt/llvm/bin/../include/c++/v1/cmath:313:9: error: no member named 'signbit' in the global namespace
using ::signbit;
      ~~^
/usr/local/opt/llvm/bin/../include/c++/v1/cmath:314:9: error: no member named 'fpclassify' in the global namespace
using ::fpclassify;
      ~~^
/usr/local/opt/llvm/bin/../include/c++/v1/cmath:315:9: error: no member named 'isfinite' in the global namespace; did you mean 'finite'?
using ::isfinite;
      ~~^
/usr/local/include/math.h:749:12: note: 'finite' declared here
extern int finite(double)
</code>```

Installation output from R shows clang++ with following arguments;

```<code>clang++ -fopenmp -std=gnu++11 -I"/usr/local/Cellar/r/3.6.2/lib/R/include" -DNDEBUG  -I"/Volumes/Documents/Library/R/3.x/library/BH/include" -I"/Volumes/Documents/Library/R/3.x/library/Rcpp/include" -I/usr/local/opt/gettext/include -I/usr/local/opt/llvm/include  -fPIC  -g -O3 -Wall -pipe -Wno-nonnull -pedantic -std=c++11 -mtune=native -c AlphaProcedure.cpp -o AlphaProcedure.o
</code>```

I've read several similar posting having the similar issues but none of workaround has worked on my system so far. I'd really appreciate any input on this.

My system:

sw_vers
   ProductName: Mac OS X
   ProductVersion:  10.15.2
   BuildVersion:    19C57

```<code>xcodebuild -version
Xcode 11.3
Build version 11C29

clang -v
clang version 9.0.0 (tags/RELEASE_900/final)
Target: x86_64-apple-darwin19.2.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin

gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/9.2.0_3/libexec/gcc/x86_64-apple-darwin19/9.2.0/lto-wrapper
Target: x86_64-apple-darwin19
Configured with: ../configure --build=x86_64-apple-darwin19 --prefix=/usr/local/Cellar/gcc/9.2.0_3 --libdir=/usr/local/Cellar/gcc/9.2.0_3/lib/gcc/9 --disable-nls --enable-checking=release --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-9 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --with-pkgversion='Homebrew GCC 9.2.0_3' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --disable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk
Thread model: posix
gcc version 9.2.0 (Homebrew GCC 9.2.0_3)
</code>```

C complier flags in zshrc

```<code>CPATH=/usr/local/include
CPPFLAGS=-I/usr/local/opt/gettext/include -I/usr/local/opt/llvm/include
SDKROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk
LDFLAGS=-L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib
</code>```

Makevars (for R)

```<code>LLVM_LOC = /usr/local/opt/llvm
CC=clang -fopenmp
CXX=clang++ -foropenmp
CXX11=clang++ -fopenmp
CFLAGS = -g -O3 -Wall -pipe -pedantic -Wno-nonnull -std=gnu99 -mtune=native -pipe
CXXFLAGS = -g -O3 -Wall -pipe -Wno-nonnull -pedantic -std=c++11 -mtune=native
CXX11FLAGS = -g -O3 -Wall -pipe -Wno-nonnull -pedantic -std=c++11 -mtune=native

LDFLAGS=-L/usr/local/opt/gettext/lib -L$(LLVM_LOC)/lib -Wl,-rpath,$(LLVM_LOC)/lib
CPPFLAGS=-I/usr/local/opt/gettext/include -I$(LLVM_LOC)/include
</code>```

答: I took the nuclear option (clean install Catalina) and used llvm provided by Apple with Brew installation of some required apps.  All of this fixed the issue.  One minor fix is in Makevars with CPPFLAGS=-I/usr/local/opt/gettext/include -I$(LLVM_LOC)/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include

Body:
Having a recurring issue with cmath upon compiling the source R package in OSX 10.15, as follows;

In file included from /usr/local/opt/llvm/bin/../include/c++/v1/complex:245:
/usr/local/opt/llvm/bin/../include/c++/v1/cmath:313:9: error: no member named 'signbit' in the global namespace
using ::signbit;
      ~~^
/usr/local/opt/llvm/bin/../include/c++/v1/cmath:314:9: error: no member named 'fpclassify' in the global namespace
using ::fpclassify;
      ~~^
/usr/local/opt/llvm/bin/../include/c++/v1/cmath:315:9: error: no member named 'isfinite' in the global namespace; did you mean 'finite'?
using ::isfinite;
      ~~^
/usr/local/include/math.h:749:12: note: 'finite' declared here
extern int finite(double)

Installation output from R shows clang++ with following arguments;

clang++ -fopenmp -std=gnu++11 -I"/usr/local/Cellar/r/3.6.2/lib/R/include" -DNDEBUG  -I"/Volumes/Documents/Library/R/3.x/library/BH/include" -I"/Volumes/Documents/Library/R/3.x/library/Rcpp/include" -I/usr/local/opt/gettext/include -I/usr/local/opt/llvm/include  -fPIC  -g -O3 -Wall -pipe -Wno-nonnull -pedantic -std=c++11 -mtune=native -c AlphaProcedure.cpp -o AlphaProcedure.o

I've read several similar posting having the similar issues but none of workaround has worked on my system so far. I'd really appreciate any input on this.

My system:

sw_vers
   ProductName: Mac OS X
   ProductVersion:  10.15.2
   BuildVersion:    19C57

xcodebuild -version
Xcode 11.3
Build version 11C29

clang -v
clang version 9.0.0 (tags/RELEASE_900/final)
Target: x86_64-apple-darwin19.2.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin

gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/9.2.0_3/libexec/gcc/x86_64-apple-darwin19/9.2.0/lto-wrapper
Target: x86_64-apple-darwin19
Configured with: ../configure --build=x86_64-apple-darwin19 --prefix=/usr/local/Cellar/gcc/9.2.0_3 --libdir=/usr/local/Cellar/gcc/9.2.0_3/lib/gcc/9 --disable-nls --enable-checking=release --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-9 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --with-pkgversion='Homebrew GCC 9.2.0_3' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --disable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk
Thread model: posix
gcc version 9.2.0 (Homebrew GCC 9.2.0_3)

C complier flags in zshrc

CPATH=/usr/local/include
CPPFLAGS=-I/usr/local/opt/gettext/include -I/usr/local/opt/llvm/include
SDKROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk
LDFLAGS=-L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib

Makevars (for R)

LLVM_LOC = /usr/local/opt/llvm
CC=clang -fopenmp
CXX=clang++ -foropenmp
CXX11=clang++ -fopenmp
CFLAGS = -g -O3 -Wall -pipe -pedantic -Wno-nonnull -std=gnu99 -mtune=native -pipe
CXXFLAGS = -g -O3 -Wall -pipe -Wno-nonnull -pedantic -std=c++11 -mtune=native
CXX11FLAGS = -g -O3 -Wall -pipe -Wno-nonnull -pedantic -std=c++11 -mtune=native

LDFLAGS=-L/usr/local/opt/gettext/lib -L$(LLVM_LOC)/lib -Wl,-rpath,$(LLVM_LOC)/lib
CPPFLAGS=-I/usr/local/opt/gettext/include -I$(LLVM_LOC)/include


问:
Remove all cocoapod dependencies from a project
So I have a large Xcode project with Obj-C and Swift code, with many many cocoapods dependencies.

But my developer of choice doesn't work with cocoapod dependencies.
I know this is a bit strange but he just doesn't want to set up his Mac with pods and it's not negotiable with him (also switching devs is not an option).

So...my question.
Is it possible to remove all cocoapod dependencies and still have the project compile and run as it currently does?
I have a feeling people will say - it depends on your project.
But if I could just get a rough "Yes it is possible" or "No it is always impossible" that would be great.
And if it is possible, how does one go about starting such a task?

I don't know if this will help but here's a list of all the current Cocoapod dependencies in the project:

pod 'Countly'

pod 'CocoaLumberjack'

pod 'Fabric'

pod 'Crashlytics'

pod 'AFNetworking', '~> 2.0'

pod 'MBProgressHUD'

pod 'CHTCollectionViewWaterfallLayout', '~> 0.9'

pod 'pop', '~> 1.0'

pod 'TwitterKit'

pod 'FBSDKCoreKit'

pod 'FBSDKLoginKit'

pod 'FBSDKShareKit'

pod 'FBSDKMessengerShareKit'

pod 'Inapptics'

pod 'Firebase/Core'

pod 'Firebase/Auth'

pod 'Firebase/Storage'

pod 'FirebaseUI/Storage'

pod 'Firebase/Database'

pod 'Firebase/Messaging'

pod 'SwiftKeychainWrapper'

pod 'DeviceKit', '~> 1.0'

pod 'WSCoachMarksView'

pod 'IQKeyboardManagerSwift'

pod 'FLAnimatedImage', '~> 1.0'

pod 'GBDeviceInfo'

pod 'SDWebImage', '~> 4.0'

pod 'SDWebImage/GIF'

pod 'MagazineLayout'

pod 'Toucan'

答:
It's not recommended, but as you said it's not possible to switch developer at this stage. Just deintegrate the project from cocoapods, and then after manually copy paste your require files/library to your project.

To Deintegrate Pod just go to your project folder using Terminal. and Type

pod deintegrate

after that Manually copy/paste library files to your project in Xcode.


问:
How to synchronize data between 2 EBS volumes in AWS?
I have 2 EBS volumes in 2 availability zones in the same region, one is primary and another is backup. Generally, I just read and write data from primary volume. Is it possible to synchronize data from primary to back up EBS volume? if yes, how can I do that?

Thanks

答:
1 year after this question has been posted but I hope it helps anyone looking into this.

Amazon EFS is a great solution. An alternative for what you require is using Snapshots. With AWS Backup you can schedule Amazon EBS snapshots and have them shared across AZ or even different accounts.

As very well proposed in the previous answer, you should first try to understand your performance requirements for the workload and also the RPO and RTO requirements.

Comparing EFS and EBS, I could say that:
A. EFS (Elastic File System) is a managed parallel NFS (based on NFSv4). You are going to mount it as a directory. EFS leverages the same technology as EBS, and the disks are replicated in the AZ and also between AZ. You don’t chose or control the disks, just what performance you expect from the managed service.

B. EBS (Elastic Block Storage) is also network attached but is a block storage, which means that your OS will see it as a disk and not a directory. You have to format it as a file system (or group it with other EBS and create LVM, RAID, etc) before you can use it. EBS are replicated within the same AZ but bot across AZ. You can have snapshots of your EBS and copy them to the other AZ, for example.

So you have to take into account not only the performance you require but also what type of storage (block or file) your application need.