问:
Simple HTTP login via REST in an AsyncTask
I'm new to programming and Android and it is my first attempt to program an app but I'm already stuck with the login. The login has to be connected with an server and with the help of an get request, I'll get json data which I can use to verify the login data (username). The persons who are allowed to use the app are already in the database. It is supposed to be simple. In this forum, I could only find solutions with HTTPClient etc. but it doesn't work anymore only with HTTPURLConnection. I used the LoginActivity template

This is my code (I don't also have any experience to use JSON Data). This is the structure of our JSON DATA:

```<code>{
  "id": "1234",
  "firstName": "xx",
  "lastName": "xy",
  "fullName": "xx xy"
}

public class UserLoginTask extends AsyncTask<String, Void, Boolean> {

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(String... params) {

       final String REQUEST_METHOD = "GET";
       final int READ_TIMEOUT = 15000;
       final int CONNECTION_TIMEOUT = 15000;
        // attempt authentication against a network service.
        //InputStream is;

        URL url = null;
        try {
            String username = params[0];
            String password = params[1];
            String inputLine;
            String result;

            url = new URL("URL//");
            //Connection with database
            urlConnection=(HttpURLConnection) url.openConnection();
            //Connect with database
            //urlConnection.connect();
            //Open stream;
            //is=urlConnection.getInputStream();

            //Set methods and timeouts
            urlConnection.setRequestMethod(REQUEST_METHOD);
            urlConnection.setReadTimeout(READ_TIMEOUT);
            urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);

            //Connect to our URL
            urlConnection.connect();

            //TODO
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);

            //Create a new InputStreamReader
            InputStreamReader streamReader = new
                    InputStreamReader(urlConnection.getInputStream());
            //Create a new buffered reader and String Builder
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();

            //Check if the line we are reading is not null
            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            //Close our InputStream and Buffered reader
            reader.close();
            streamReader.close();

            //Set our result equal to our stringBuilder
            result = stringBuilder.toString();

            //Proceed in function of status code response
            int status = urlConnection.getResponseCode();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    return false;

        /*for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.
        return true;*/
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }
</code>```

I also have this in a Http Service Class:
I have these methods in my class httpservice: How can I use this?

private HttpURLConnection setUpConnection(String url, Credentials credentials) throws IOException {
        URL reqUrl = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection) reqUrl.openConnection();

```<code>    if (credentials != null && !credentials.getPassword().isEmpty() && !credentials.getUsername().isEmpty()) {
        urlConnection.setRequestProperty("Authorization", createBasicAuthString(credentials.getUsername(), credentials.getPassword()));
    }
    return urlConnection;
}

/**
 * Creates the String for the Authorization Header
 *
 * @param user
 * @param password
 * @return
 */
private String createBasicAuthString(String user, String password) {
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.encodeToString(notEncoded.getBytes(), Base64.DEFAULT);
    return "Basic " + encodedAuth;
}
</code>```

答:
Parse Your JSON Data like this,

```<code> JSONObject jsonObject = new JSONObject(Your_Sring_data);
 String  id= jsonObject.getJsonString("id");
 String firstName= jsonObject.getJsonString("firstName");
 String lastName= jsonObject.getJsonString("lastName");
 String fullName= jsonObject.getJsonString("fullName");
</code>```

and Return Response string instead of boolean success variable in doInBackground() method and parse that string through above code

Body:
I'm new to programming and Android and it is my first attempt to program an app but I'm already stuck with the login. The login has to be connected with an server and with the help of an get request, I'll get json data which I can use to verify the login data (username). The persons who are allowed to use the app are already in the database. It is supposed to be simple. In this forum, I could only find solutions with HTTPClient etc. but it doesn't work anymore only with HTTPURLConnection. I used the LoginActivity template

This is my code (I don't also have any experience to use JSON Data). This is the structure of our JSON DATA:

{
  "id": "1234",
  "firstName": "xx",
  "lastName": "xy",
  "fullName": "xx xy"
}

public class UserLoginTask extends AsyncTask<String, Void, Boolean> {

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(String... params) {

       final String REQUEST_METHOD = "GET";
       final int READ_TIMEOUT = 15000;
       final int CONNECTION_TIMEOUT = 15000;
        // attempt authentication against a network service.
        //InputStream is;

        URL url = null;
        try {
            String username = params[0];
            String password = params[1];
            String inputLine;
            String result;

            url = new URL("URL//");
            //Connection with database
            urlConnection=(HttpURLConnection) url.openConnection();
            //Connect with database
            //urlConnection.connect();
            //Open stream;
            //is=urlConnection.getInputStream();

            //Set methods and timeouts
            urlConnection.setRequestMethod(REQUEST_METHOD);
            urlConnection.setReadTimeout(READ_TIMEOUT);
            urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);

            //Connect to our URL
            urlConnection.connect();

            //TODO
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);

            //Create a new InputStreamReader
            InputStreamReader streamReader = new
                    InputStreamReader(urlConnection.getInputStream());
            //Create a new buffered reader and String Builder
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();

            //Check if the line we are reading is not null
            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            //Close our InputStream and Buffered reader
            reader.close();
            streamReader.close();

            //Set our result equal to our stringBuilder
            result = stringBuilder.toString();

            //Proceed in function of status code response
            int status = urlConnection.getResponseCode();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    return false;

        /*for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.
        return true;*/
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

I also have this in a Http Service Class:
I have these methods in my class httpservice: How can I use this?

private HttpURLConnection setUpConnection(String url, Credentials credentials) throws IOException {
        URL reqUrl = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection) reqUrl.openConnection();

    if (credentials != null && !credentials.getPassword().isEmpty() && !credentials.getUsername().isEmpty()) {
        urlConnection.setRequestProperty("Authorization", createBasicAuthString(credentials.getUsername(), credentials.getPassword()));
    }
    return urlConnection;
}

/**
 * Creates the String for the Authorization Header
 *
 * @param user
 * @param password
 * @return
 */
private String createBasicAuthString(String user, String password) {
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.encodeToString(notEncoded.getBytes(), Base64.DEFAULT);
    return "Basic " + encodedAuth;
}

Body:
Parse Your JSON Data like this,

 JSONObject jsonObject = new JSONObject(Your_Sring_data);
 String  id= jsonObject.getJsonString("id");
 String firstName= jsonObject.getJsonString("firstName");
 String lastName= jsonObject.getJsonString("lastName");
 String fullName= jsonObject.getJsonString("fullName");

and Return Response string instead of boolean success variable in doInBackground() method and parse that string through above code


来源: stackexchange

问:
UILabel Over UISlider Thumb
How can i put an UILabel over the thumb of UISlider...so that when i move the thumb....UILabel will also move....as it is on the thumb...

Any idea??

答:
Same answer with swift3:

```<code>    let trackRect: CGRect  = slider.trackRect(forBounds: slider.bounds)
    let thumbRect: CGRect  = slider.thumbRect(forBounds: slider.bounds , trackRect: trackRect, value: slider.value)
    let x = thumbRect.origin.x + slider.frame.origin.x
    let y = slider.frame.origin.y - 20
    sliderLabel.center = CGPoint(x: x, y: y)
</code>```

ContentLicense: CC BY-SA 2.5

Title: UILabel Over UISlider Thumb

Body:
Same answer with swift3:

    let trackRect: CGRect  = slider.trackRect(forBounds: slider.bounds)
    let thumbRect: CGRect  = slider.thumbRect(forBounds: slider.bounds , trackRect: trackRect, value: slider.value)
    let x = thumbRect.origin.x + slider.frame.origin.x
    let y = slider.frame.origin.y - 20
    sliderLabel.center = CGPoint(x: x, y: y)

ContentLicense: CC BY-SA 3.0


问:
How to execute awk command inside python
I am trying to run the following awk command inside python but I get a syntax error related to the quotes:

```<code>import subprocess
COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"

subprocess.call(COMMAND, shell=True)
</code>```

I tried to escape the quotes but I am still getting the same error.

答:
You may want to put ''' or """ around the string since you have both ' and ".

```<code>import subprocess
COMMAND = '''"df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"'''

subprocess.call(COMMAND, shell=True)
</code>```

There also seems to be a relevant answer already for this as well: awk commands within python script

Body:
I am trying to run the following awk command inside python but I get a syntax error related to the quotes:

import subprocess
COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"

subprocess.call(COMMAND, shell=True)

I tried to escape the quotes but I am still getting the same error.

Body:
You may want to put ''' or """ around the string since you have both ' and ".

import subprocess
COMMAND = '''"df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"'''

subprocess.call(COMMAND, shell=True)

There also seems to be a relevant answer already for this as well: awk commands within python script


问:
get 419 error when posting from axios to laravel
I have the csrf which it's already attached to the axios header at bootstap.js,
I get always this response from server when try to post simple post (they are three pictures below explaining my situation)

axios post from vue file:

Route at web.php:

result 1:

result 2:

答:
Try this, it works for me so far but you'll be without CSRF, go to 'App\Http\Middleware\VerifyCsrfToken' then edit the protected variable to this

```<code> protected $except = [
     "/*"
 ];
</code>```

the '/*' says to exclude CSRF from all routes, although this isn't ideal it should fix the problem, Maybe just exclude those specific routes that are throwing you the error?

e.g. "/specificRoute"

ContentLicense: CC BY-SA 4.0

Body:
Try this, it works for me so far but you'll be without CSRF, go to 'App\Http\Middleware\VerifyCsrfToken' then edit the protected variable to this

 protected $except = [
     "/*"
 ];

the '/*' says to exclude CSRF from all routes, although this isn't ideal it should fix the problem, Maybe just exclude those specific routes that are throwing you the error?

e.g. "/specificRoute"


问:
Python 3.6 and paramiko
Trying to use paramiko library with Python 3.6 and I get stuck at the simple code snippet possible. Trying to connect from my Linux host to my Windows host (ssh server is running and I can connect via terminal) I get this error:

```<code>SSHException: Channel closed.
</code>```

Code:

```<code>@keyword('Open Connection And Log In ${host} ${port} ${username} ${pwd}')
def open_connection_and_login(host, port, username, pwd):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host, port=22, username='root', password='root')
    command = 'dir'
    (stdin, stdout, stderr) = client.exec_command(command)

    print(stdout.read())
    client.close()
</code>```

Traceback:

```<code>  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 13, in open_connection_and_login
    (stdin, stdout, stderr) = client.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 478, in exec_command
    chan.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 241, in exec_command
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 13, in open_connection_and_login
    (stdin, stdout, stderr) = client.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 478, in exec_command
    chan.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 241, in exec_command
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
</code>```

More log:

```<code>DEBUG:paramiko.transport:starting thread (client mode): 0x10223668
DEBUG:paramiko.transport:Local version/idstring: SSH-2.0-paramiko_2.3.1
DEBUG:paramiko.transport:Remote version/idstring: SSH-2.0-WeOnlyDo 2.4.3
INFO:paramiko.transport:Connected (version 2.0, client WeOnlyDo)
DEBUG:paramiko.transport:kex algos:['ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-cbc', 'aes128-ctr', '3des-cbc', 'blowfish-cbc', 'aes192-cbc', 'aes192-ctr', 'aes256-cbc', 'aes256-ctr', 'rijndael128-cbc', 'rijndael192-cbc', 'rijndael256-cbc', 'rijndael-cbc@lysator.liu.se', 'cast128-cbc'] server encrypt:['aes128-cbc', 'aes128-ctr', '3des-cbc', 'blowfish-cbc', 'aes192-cbc', 'aes192-ctr', 'aes256-cbc', 'aes256-ctr', 'rijndael128-cbc', 'rijndael192-cbc', 'rijndael256-cbc', 'rijndael-cbc@lysator.liu.se', 'cast128-cbc'] client mac:['hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'none'] server mac:['hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'none'] client compress:['none', 'none'] server compress:['none', 'none'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Kex agreed: ecdh-sha2-nistp256
DEBUG:paramiko.transport:HostKey agreed: ssh-rsa
DEBUG:paramiko.transport:Cipher agreed: aes128-ctr
DEBUG:paramiko.transport:MAC agreed: hmac-sha2-256
DEBUG:paramiko.transport:Compression agreed: none
DEBUG:paramiko.transport:kex engine KexNistp256 specified hash_algo <built-in function openssl_sha256>
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Adding ssh-rsa host key for 10.99.2.20: b'eea39f0acdfb5c2b7d042887e668ebac'
DEBUG:paramiko.transport:Trying SSH agent key b'e440c2d0b5fb98ab3951ddc52c4ba86b'
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (publickey) failed.
DEBUG:paramiko.transport:Trying discovered key b'e440c2d0b5fb98ab3951ddc52c4ba86b' in /home/matejb/.ssh/id_rsa
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (publickey) failed.
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (password) successful!
<function basicConfig at 0x7f9311f11950>
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 98304 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 0] EOF sent (0)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 17, in open_connection_and_login
    client.open_sftp()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 513, in open_sftp
    return self._transport.open_sftp_client()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/transport.py", line 978, in open_sftp_client
    return SFTPClient.from_transport(self)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/sftp_client.py", line 138, in from_transport
    chan.invoke_subsystem('sftp')
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 267, in invoke_subsystem
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 17, in open_connection_and_login
    client.open_sftp()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 513, in open_sftp
    return self._transport.open_sftp_client()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/transport.py", line 978, in open_sftp_client
    return SFTPClient.from_transport(self)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/sftp_client.py", line 138, in from_transport
    chan.invoke_subsystem('sftp')
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 267, in invoke_subsystem
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
</code>```

答:
Did you install the missing package throwing the ModuleNotFoundError: No module named 'apt_pkg' ?

Otherwise, if the problem is located on the server not allowing specific command executions, you might have to take a look there at the error code..

Title: Python 3.6 and paramiko

Body:
Trying to use paramiko library with Python 3.6 and I get stuck at the simple code snippet possible. Trying to connect from my Linux host to my Windows host (ssh server is running and I can connect via terminal) I get this error:

SSHException: Channel closed.

Code:

@keyword('Open Connection And Log In ${host} ${port} ${username} ${pwd}')
def open_connection_and_login(host, port, username, pwd):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host, port=22, username='root', password='root')
    command = 'dir'
    (stdin, stdout, stderr) = client.exec_command(command)

    print(stdout.read())
    client.close()

Traceback:

  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 13, in open_connection_and_login
    (stdin, stdout, stderr) = client.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 478, in exec_command
    chan.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 241, in exec_command
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 13, in open_connection_and_login
    (stdin, stdout, stderr) = client.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 478, in exec_command
    chan.exec_command(command)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 241, in exec_command
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.

More log:

DEBUG:paramiko.transport:starting thread (client mode): 0x10223668
DEBUG:paramiko.transport:Local version/idstring: SSH-2.0-paramiko_2.3.1
DEBUG:paramiko.transport:Remote version/idstring: SSH-2.0-WeOnlyDo 2.4.3
INFO:paramiko.transport:Connected (version 2.0, client WeOnlyDo)
DEBUG:paramiko.transport:kex algos:['ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1'] server key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-cbc', 'aes128-ctr', '3des-cbc', 'blowfish-cbc', 'aes192-cbc', 'aes192-ctr', 'aes256-cbc', 'aes256-ctr', 'rijndael128-cbc', 'rijndael192-cbc', 'rijndael256-cbc', 'rijndael-cbc@lysator.liu.se', 'cast128-cbc'] server encrypt:['aes128-cbc', 'aes128-ctr', '3des-cbc', 'blowfish-cbc', 'aes192-cbc', 'aes192-ctr', 'aes256-cbc', 'aes256-ctr', 'rijndael128-cbc', 'rijndael192-cbc', 'rijndael256-cbc', 'rijndael-cbc@lysator.liu.se', 'cast128-cbc'] client mac:['hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'none'] server mac:['hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'none'] client compress:['none', 'none'] server compress:['none', 'none'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Kex agreed: ecdh-sha2-nistp256
DEBUG:paramiko.transport:HostKey agreed: ssh-rsa
DEBUG:paramiko.transport:Cipher agreed: aes128-ctr
DEBUG:paramiko.transport:MAC agreed: hmac-sha2-256
DEBUG:paramiko.transport:Compression agreed: none
DEBUG:paramiko.transport:kex engine KexNistp256 specified hash_algo <built-in function openssl_sha256>
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Adding ssh-rsa host key for 10.99.2.20: b'eea39f0acdfb5c2b7d042887e668ebac'
DEBUG:paramiko.transport:Trying SSH agent key b'e440c2d0b5fb98ab3951ddc52c4ba86b'
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (publickey) failed.
DEBUG:paramiko.transport:Trying discovered key b'e440c2d0b5fb98ab3951ddc52c4ba86b' in /home/matejb/.ssh/id_rsa
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (publickey) failed.
DEBUG:paramiko.transport:userauth is OK
INFO:paramiko.transport:Authentication (password) successful!
<function basicConfig at 0x7f9311f11950>
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 98304 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 0] EOF sent (0)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 17, in open_connection_and_login
    client.open_sftp()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 513, in open_sftp
    return self._transport.open_sftp_client()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/transport.py", line 978, in open_sftp_client
    return SFTPClient.from_transport(self)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/sftp_client.py", line 138, in from_transport
    chan.invoke_subsystem('sftp')
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 267, in invoke_subsystem
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/matejb/Development/automated-testing/python_libs/topit/ssh/basicOperations.py", line 17, in open_connection_and_login
    client.open_sftp()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/client.py", line 513, in open_sftp
    return self._transport.open_sftp_client()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/transport.py", line 978, in open_sftp_client
    return SFTPClient.from_transport(self)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/sftp_client.py", line 138, in from_transport
    chan.invoke_subsystem('sftp')
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 63, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 267, in invoke_subsystem
    self._wait_for_event()
  File "/usr/local/lib/python3.6/dist-packages/paramiko/channel.py", line 1197, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.


问:
How to redirect https to http in Wordpress
I want to redirect my WordPress site from https to http, because the SSL certificate is expired. I've asked my host (strato) to extend the certificate, but they haven't fix it yet.

What I tried:

changed the site url

Installed plugin to force http

Deactivate all related SSl plugins

Does someone have a solution?

答:
Try This Code,

Redirect from HTTPS to HTTP:

You want to redirect particular website to be opened through HTTP instead of HTTPS. To do so you can add the following directives in your website's .htaccess file:

# Redirect HTTPS to HTTP
RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]```


问:
Python Flask App with MQTT
I'm trying to use my Flask app as a subscriber, but it does not call the on_message callback when receiving a message. Instead, I get about like the following:

```<code>Connected with result code 0
Closing data file...
Connected with result code 0
Closing data file...
</code>```

This is how I am running the Flask app:

```<code>main.py:

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
import paho.mqtt.client as mqtt
import time

broker_address = <broker_ip>
port = 1883
timeout = 60
username = "first"
password = "last"
uuid = "1234"
topic = "mytopic"
qos = 0

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload) + '\n')

def on_disconnect(client, userdata, rc):
    print("Closing data file...")

client = mqtt.Client(client_id=uuid)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.username_pw_set(username, password)

client.connect(broker_address, port, 60)
client.loop_start()

<other Flask code>

if __name__ == "__main__":
    app.run(debug=True)
</code>```

I've tried using a another Python script to generate some fake data to publish to the topic, but only when that script is running to I get the output above. If that script is not running, then the main.py seems to wait for messages. This is the other script:

```<code>fake_data.py:

import paho.mqtt.client as mqtt
import time

broker_address = <broker_ip>
port = 1883
timeout = 60
username = "first"
password = "last"
uuid = "1234"
topic = "mytopic"
qos = 0

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

client = mqtt.Client(client_id=uuid, clean_session=True)
client.on_connect = on_connect

client.username_pw_set(username, password)

client.connect(broker_address, port, 60)

client.loop_start()

while True:
    count = 0
    while count != 30:
        print("Publishing {0}".format(count))
        client.publish(topic, count, qos=0)
        count += 1
        time.sleep(1)
</code>```

My question is why the Flask app keeps connecting and disconnecting endlessly without actually processing a message.

答:
The client id needs to be different for all clients connected to a broker. In the code you've posted both the subscriber and the publisher are using the same client id (uuid=1234).

When 2 clients with the same client id connect to the broker, the broker will kick the oldest off. If this is then set to reconnect it will then kick the second one off.

Set uuid to different values.

Title: Python Flask App with MQTT

Body:
I'm trying to use my Flask app as a subscriber, but it does not call the on_message callback when receiving a message. Instead, I get about like the following:

Connected with result code 0
Closing data file...
Connected with result code 0
Closing data file...

This is how I am running the Flask app:

main.py:

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
import paho.mqtt.client as mqtt
import time

broker_address = <broker_ip>
port = 1883
timeout = 60
username = "first"
password = "last"
uuid = "1234"
topic = "mytopic"
qos = 0

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload) + '\n')

def on_disconnect(client, userdata, rc):
    print("Closing data file...")

client = mqtt.Client(client_id=uuid)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.username_pw_set(username, password)

client.connect(broker_address, port, 60)
client.loop_start()

<other Flask code>

if __name__ == "__main__":
    app.run(debug=True)

I've tried using a another Python script to generate some fake data to publish to the topic, but only when that script is running to I get the output above. If that script is not running, then the main.py seems to wait for messages. This is the other script:

fake_data.py:

import paho.mqtt.client as mqtt
import time

broker_address = <broker_ip>
port = 1883
timeout = 60
username = "first"
password = "last"
uuid = "1234"
topic = "mytopic"
qos = 0

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

client = mqtt.Client(client_id=uuid, clean_session=True)
client.on_connect = on_connect

client.username_pw_set(username, password)

client.connect(broker_address, port, 60)

client.loop_start()

while True:
    count = 0
    while count != 30:
        print("Publishing {0}".format(count))
        client.publish(topic, count, qos=0)
        count += 1
        time.sleep(1)

My question is why the Flask app keeps connecting and disconnecting endlessly without actually processing a message.


问:
js best practice to name class methods/properties of an extendable class
I am writing a package that provides an abstract class that will later be extended by the users. I want to avoid any naming conflicts between the base class properties/methods and the ones assigned by the users. Specifically, I have the properties collection and schema:

```<code>abstract class BaseClass {
    collection
    schema
}
</code>```

This way it is not unlikely that the extending class will also implement those properties, but with another purpose (i.e. they are not supposed to be overrides).

Option A, prefixwith _:

```<code>abstract class BaseClass {
    _collection
    _schema
}
</code>```

Now it is a lot less likely the there will be name collisions. But I don't really like the _

Option B, prefix with _ but expose through methods:

```<code>abstract class BaseClass {
    _collection
    _schema

    getCollection() { return this._collection }
    setCollection(collection) { this._collection = collection }
    ...
}
</code>```

I prefer it to A, but it seems a little "oldschool" since I would normally rather use getters setters:

```<code>abstract class BaseClass {
    _collection
    _schema

    get collection() { return this._collection }
    set collection(collection) { this._collection = collection }
    ...
}
</code>```

but this way I am back to the naming problem.

So what are commonly used solutions for building a 3rd party package?

答:
it is not unlikely that the extending class will also implement those properties, but with another purpose

No. Anyone extending your abstract class will know its public properties and not override them. If they do, it's their problem not yours; this is nothing you can guard against.

If you want to use "private" properties (to be used in the public methods of your class) that cannot collide with properties defined by the subclasses, ES6 symbols are the way to go.

Body:
I am writing a package that provides an abstract class that will later be extended by the users. I want to avoid any naming conflicts between the base class properties/methods and the ones assigned by the users. Specifically, I have the properties collection and schema:

abstract class BaseClass {
    collection
    schema
}

This way it is not unlikely that the extending class will also implement those properties, but with another purpose (i.e. they are not supposed to be overrides).

Option A, prefixwith _:

abstract class BaseClass {
    _collection
    _schema
}

Now it is a lot less likely the there will be name collisions. But I don't really like the _

Option B, prefix with _ but expose through methods:

abstract class BaseClass {
    _collection
    _schema

    getCollection() { return this._collection }
    setCollection(collection) { this._collection = collection }
    ...
}

I prefer it to A, but it seems a little "oldschool" since I would normally rather use getters setters:

abstract class BaseClass {
    _collection
    _schema

    get collection() { return this._collection }
    set collection(collection) { this._collection = collection }
    ...
}

but this way I am back to the naming problem.

So what are commonly used solutions for building a 3rd party package?


问:
Unable to create a blank working bridge.net project via visual studio template
Everytime I try to create a bridge.net new project I get the following error:

Could not add all required packages to the project. The following
  packages failed to install from [the user appdata local
  folder]\Microsoft\VisualStudio\14\extensions\IJHDC25V.XOU\Packages.

Bridge.1.10.0 : Solution is not opened or not saved. Please ensure you
  have an open and saved solution.

Trying to build the project leads to the 'Bridge' namespace missing.

I did the following:

Download the bridge.net .vsix package from
https://visualstudiogallery.msdn.microsoft.com/dca5c80f-a0df-4944-8343-9c905db84757

Run the package

Create a new project -> Bridge.net -> Class Library

Named the project 'Demo'

I verified the folder exists and is populated. I've tried running Visual studio as an administrator and as a standard user.

How do I get a working blank Bridge.net project with the visual studio template?

答:
The project needs to be saved to disk.

In Visual Studio under Tools / Options / Projects and Solutions tick the Save new projects when created checkbox.

Then create a new project.


问:
How can i use accordion to show collections documents?
My requirement:

1. Get the data from the mongo collection and display into accordion

2. Set the active ID of the selected html accordion tag same as that of the document from collection.

3. Get the dropdown transition when we click in any one accordion entry in UI.

sample.html

```<code>     {{#each listjobs}}
        <button class="accordion">{{platform}}</button>
        <div class="panel">
            <ul class="panel_elements">
                  <li><input type="submit" name="delete" value="Delete" /></li>
                  <li><input type="checkbox" name="abc" value="abc" />{{abc}}</li>
                  <li><input type="checkbox" name="def" value="def" />{{def}}</li>
                  <li><input type="checkbox" name="ghi" value="ghi" />{{ghi}}</li>
                  <li><input type="submit" name="trigger" value="Trigger" /></li>
                  <li id="status">SUCCESS / FAIL</li>
            </ul>
        </div>
    {{/each}}
</code>```

sample.css

```<code>    button.accordion {
        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
        transition: 0.4s;
    }

    button.accordion.active, button.accordion:hover {
        background-color: #ccc;
        border: 1px solid black;
    }

    button.accordion:after {
        content: '\002B';
        color: #777;
        font-weight: bold;
        float: right;
        margin-left: 5px;
    }

    button.accordion.active:after {
        content: "\2212";
    }

    div.panel {
        padding: 0 18px;
        background-color: white;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.2s ease-out;
    }
    ul.panel_elements{
      list-style-type:none;
    }
    ul.panel_elements li{
      display:inline-block;

    }
</code>```

sample.js

```<code>Template.trigger.events({
    'click .accordion':function(){
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
    },

});
</code>```

The list is displayed by fetching entry mongo collections, but when i click on the job in UI the accordion drop-down doesn't comes up!!.

Can anyone please help me to solve this? or is there any other way to do this?

答:
I've reused what's already available here:

Template:

```<code>{{#each listjobs}}
<button class="accordion">{{platform}}</button>
<div class="panel">
   <ul class="panel_elements">
              <li><input type="submit" name="delete" value="Delete" /></li>
              <li><input type="checkbox" name="abc" value="abc" />{{abc}}</li>
              <li><input type="checkbox" name="def" value="def" />{{def}}</li>
              <li><input type="checkbox" name="ghi" value="ghi" />{{ghi}}</li>
              <li><input type="submit" name="trigger" value="Trigger" /></li>
              <li id="status">SUCCESS / FAIL</li>
        </ul>
{{/each}}
</code>```

CSS:

```<code>button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ccc;
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
</code>```

Body:
My requirement:

1. Get the data from the mongo collection and display into accordion

2. Set the active ID of the selected html accordion tag same as that of the document from collection.

3. Get the dropdown transition when we click in any one accordion entry in UI.

sample.html

     {{#each listjobs}}
        <button class="accordion">{{platform}}</button>

<input type="submit" name="delete" value="Delete" />

<input type="checkbox" name="abc" value="abc" />{{abc}}

<input type="checkbox" name="def" value="def" />{{def}}

<input type="checkbox" name="ghi" value="ghi" />{{ghi}}

<input type="submit" name="trigger" value="Trigger" />

SUCCESS / FAIL

    {{/each}}

sample.css

    button.accordion {
        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
        transition: 0.4s;
    }

    button.accordion.active, button.accordion:hover {
        background-color: #ccc;
        border: 1px solid black;
    }

    button.accordion:after {
        content: '\002B';
        color: #777;
        font-weight: bold;
        float: right;
        margin-left: 5px;
    }

    button.accordion.active:after {
        content: "\2212";
    }

    div.panel {
        padding: 0 18px;
        background-color: white;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.2s ease-out;
    }
    ul.panel_elements{
      list-style-type:none;
    }
    ul.panel_elements li{
      display:inline-block;

    }

sample.js

Template.trigger.events({
    'click .accordion':function(){
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight){
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
    },

});

The list is displayed by fetching entry mongo collections, but when i click on the job in UI the accordion drop-down doesn't comes up!!.

Can anyone please help me to solve this? or is there any other way to do this?

Body:
I've reused what's already available here:

Template:

{{#each listjobs}}
<button class="accordion">{{platform}}</button>
<div class="panel">
   <ul class="panel_elements">
              <li><input type="submit" name="delete" value="Delete" /></li>
              <li><input type="checkbox" name="abc" value="abc" />{{abc}}</li>
              <li><input type="checkbox" name="def" value="def" />{{def}}</li>
              <li><input type="checkbox" name="ghi" value="ghi" />{{ghi}}</li>
              <li><input type="submit" name="trigger" value="Trigger" /></li>
              <li id="status">SUCCESS / FAIL</li>
        </ul>
{{/each}}

CSS:

button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ccc;
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}


问:
query in mongoDb using JavaScript
This is my sample documents in DB.

```<code>{
    "_id":1,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":2,
    "object":{
        "featureOne":false,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":3,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}
</code>```

I want to get one object with "featureOne": true and another with "featureOne": false in a single query. I have knowledge on finding data using a particular key and value. But how can I get the data using same key of true and false values in a single query. Present I am using this code

```<code>db.collection(collectionName).find({"featureOne":true, {limit:1}).toArray(function(err, results) {
    db.collection(collectionName).find("featureOne":,false{limit:2}).toArray(function(err,res {
        console.log(results,res);
    });
});
</code>```

Is there any better way to achieve this?

答:
You can achieve it with aggregation framework.

You can use $group and $project stages (as mentioned in the Clement Amarnath answer), but if you need a more control over the data collection stage then you can use:

$facet - collects data by sub aggregation pipelines.

$match - sets the criterias for the documents filter.

$limit - defines the maximum amount of documents which can be taken (use $sample if you want to randomize a result).

$addFields -
merge results into one element (array).

$unwind - splits the results
array into seperated documents.

$replaceRoot - changes the document
root element.

Example code:

```<code>db.collection.aggregate([
    {
        $facet: {
            "result1": [
                {$match: {"object.featureOne": true}},
                {$limit: 1}
            ],
            "result2": [
                {$match: {"object.featureOne": false}},
                {$limit: 1}
            ]
        }
    },
    {$addFields: {"results": [{$arrayElemAt: ["$result1", 0]}, {$arrayElemAt: ["$result2", 0]}]}},
    {$unwind: "$results"},
    {$replaceRoot: {newRoot: "$results"}}
])
</code>```

Title: query in mongoDb using JavaScript

Body:
This is my sample documents in DB.

{
    "_id":1,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":2,
    "object":{
        "featureOne":false,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":3,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}

I want to get one object with "featureOne": true and another with "featureOne": false in a single query. I have knowledge on finding data using a particular key and value. But how can I get the data using same key of true and false values in a single query. Present I am using this code

db.collection(collectionName).find({"featureOne":true, {limit:1}).toArray(function(err, results) {
    db.collection(collectionName).find("featureOne":,false{limit:2}).toArray(function(err,res {
        console.log(results,res);
    });
});

Is there any better way to achieve this?

Body:
You can achieve it with aggregation framework.

You can use $group and $project stages (as mentioned in the Clement Amarnath answer), but if you need a more control over the data collection stage then you can use:

$facet - collects data by sub aggregation pipelines.

$match - sets the criterias for the documents filter.

$limit - defines the maximum amount of documents which can be taken (use $sample if you want to randomize a result).

$addFields -
merge results into one element (array).

$unwind - splits the results
array into seperated documents.

$replaceRoot - changes the document
root element.

Example code:

db.collection.aggregate([
    {
        $facet: {
            "result1": [
                {$match: {"object.featureOne": true}},
                {$limit: 1}
            ],
            "result2": [
                {$match: {"object.featureOne": false}},
                {$limit: 1}
            ]
        }
    },
    {$addFields: {"results": [{$arrayElemAt: ["$result1", 0]}, {$arrayElemAt: ["$result2", 0]}]}},
    {$unwind: "$results"},
    {$replaceRoot: {newRoot: "$results"}}
])


问:
How to determine whether Right Ctrl/Shift/Alt or Left is being clicked in C#?
I want to use Right or Left Control/Shift/Alt in C#
but When I type

```<code> private void Form1_KeyDown(or KeyPress)(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.RControlKey) //(or e.KeyCode)
        {
            //Code
        }
    }
</code>```

but it doesn't work...same with Shift and Alt

So what is the wrong here?

答:
E.g., if you press RControlKey+A, it creates several events.

```<code>private void watcher_keyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("keyDown: " + e.KeyData.ToString());
}

private void watcher_KeyPress(object sender, KeyPressEventArgs e)
{
    Console.WriteLine("keyPress: " + e.KeyChar.ToString());
}

public void watcher_KeyUp(object sender, KeyEventArgs e)
{
    Console.WriteLine("keyUp: " + e.KeyData.ToString());
}

keyDown: RControlKey
keyDown: A, Control
keyPress:
keyUp: A, Control
keyUp: RControlKey, Control
</code>```

From the 1st or the last event you can know which one (left or right) was clicked. This means you may need to cache the key code as there are 2 keyUp/keyDown events.

Body:
I want to use Right or Left Control/Shift/Alt in C#
but When I type

 private void Form1_KeyDown(or KeyPress)(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.RControlKey) //(or e.KeyCode)
        {
            //Code
        }
    }

but it doesn't work...same with Shift and Alt

So what is the wrong here?

Body:
E.g., if you press RControlKey+A, it creates several events.

private void watcher_keyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("keyDown: " + e.KeyData.ToString());
}

private void watcher_KeyPress(object sender, KeyPressEventArgs e)
{
    Console.WriteLine("keyPress: " + e.KeyChar.ToString());
}

public void watcher_KeyUp(object sender, KeyEventArgs e)
{
    Console.WriteLine("keyUp: " + e.KeyData.ToString());
}

keyDown: RControlKey
keyDown: A, Control
keyPress:
keyUp: A, Control
keyUp: RControlKey, Control

From the 1st or the last event you can know which one (left or right) was clicked. This means you may need to cache the key code as there are 2 keyUp/keyDown events.


问:
Google Map Marker is showing at the left-top side
I am trying to display a google map with draggable marker in bootstrap modal. It works perfectly but the problem is the marker is showing at the left top side of div as shown below in image.

I wants to show in center of div

It will shown at left top of modal. Here is my code for showing google map.

```<code>function init() {
      var mapCanvas = document.getElementById('map_canvas');

      $('.mapModal').on('shown.bs.modal', function () {
          google.maps.event.trigger(mapCanvas, "resize");
      });

        //var myLatlng = new google.maps.LatLng(23.0203135, 72.5561606);
        var myLatlng = {lat: 23.019523540982888, lng: 72.55628934603271};
        /*
          23.019523540982888
          72.55628934603271
          23.0203135
          72.5561606
        */
        var myOptions = {
            zoom: 15,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            map: map,
            position: myLatlng,
            title: "Your location"
        });
        //To Fill Lat Long
        google.maps.event.addListener(marker, 'dragend', function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
}
</code>```

答:
First, I'd suggest that you put your Google Maps logic and all code that creates the map inside bootstrap modal event; after it has been created, like this:

```<code>$('#myModal').on('show.bs.modal', function (e) {
  // .. put you map code here or just hook your custom function
});
</code>```

then see if your map is centered. Also make sure that you give your div or element explicit height for ex:

Body:
I am trying to display a google map with draggable marker in bootstrap modal. It works perfectly but the problem is the marker is showing at the left top side of div as shown below in image.

I wants to show in center of div

It will shown at left top of modal. Here is my code for showing google map.

function init() {
      var mapCanvas = document.getElementById('map_canvas');

      $('.mapModal').on('shown.bs.modal', function () {
          google.maps.event.trigger(mapCanvas, "resize");
      });

        //var myLatlng = new google.maps.LatLng(23.0203135, 72.5561606);
        var myLatlng = {lat: 23.019523540982888, lng: 72.55628934603271};
        /*
          23.019523540982888
          72.55628934603271
          23.0203135
          72.5561606
        */
        var myOptions = {
            zoom: 15,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            draggable: true,
            map: map,
            position: myLatlng,
            title: "Your location"
        });
        //To Fill Lat Long
        google.maps.event.addListener(marker, 'dragend', function (event) {
            document.getElementById("lat").value = event.latLng.lat();
            document.getElementById("lng").value = event.latLng.lng();
        });
}

Body:
First, I'd suggest that you put your Google Maps logic and all code that creates the map inside bootstrap modal event; after it has been created, like this:

$('#myModal').on('show.bs.modal', function (e) {
  // .. put you map code here or just hook your custom function
});

then see if your map is centered. Also make sure that you give your div or element explicit height for ex: <div id="map_canvas" style="height: 500px;"></div>


问:
How to use feedable iterator from Tensorflow Dataset API along with MonitoredTrainingSession?
Tensorflow programmer's guide recommends using feedable iterator to switch between training and validation dataset without reinitializing the iterator. It mainly requires to feed the handle to choose between them.

How to use it along with tf.train.MonitoredTrainingSession?

The following method fails with "RuntimeError: Graph is finalized and cannot be modified." error.

```<code>with tf.train.MonitoredTrainingSession() as sess:
    training_handle = sess.run(training_iterator.string_handle())
    validation_handle = sess.run(validation_iterator.string_handle())
</code>```

How to achieve both the convenience of MonitoredTrainingSession and iterating training and validation datasets simultaneously?

答:
@Michael Jaison G answer is correct. However, it does not work when you also want to use certain session_run_hooks that need to evaluate parts of the graph, like e.g. LoggingTensorHook or SummarySaverHook.
The example below will cause an error:

```<code>import tensorflow as tf

dataset_train = tf.data.Dataset.range(10)
dataset_val = tf.data.Dataset.range(90, 100)

iter_train_handle = dataset_train.make_one_shot_iterator().string_handle()
iter_val_handle = dataset_val.make_one_shot_iterator().string_handle()

handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(
    handle, dataset_train.output_types, dataset_train.output_shapes)
feature = iterator.get_next()

pred = feature * feature
tf.summary.scalar('pred', pred)
global_step = tf.train.create_global_step()

summary_hook = tf.train.SummarySaverHook(save_steps=5,
                                         output_dir="summaries", summary_op=tf.summary.merge_all())

with tf.train.MonitoredTrainingSession(hooks=[summary_hook]) as sess:
    handle_train, handle_val = sess.run([iter_train_handle, iter_val_handle])

    for step in range(10):
        feat = sess.run(feature, feed_dict={handle: handle_train})
        pred_ = sess.run(pred, feed_dict={handle: handle_train})
        print('train: ', feat)
        print('pred: ', pred_)

        if step % 3 == 0:
            print('val', sess.run(feature, feed_dict={handle: handle_val}))
</code>```

This will fail with error:

```<code>InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype string
     [[Node: Placeholder = Placeholder[dtype=DT_STRING, shape=[], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
     [[Node: cond/Switch_1/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_18_cond/Switch_1", tensor_type=DT_INT64, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
</code>```

The reason being that the hook will try to evaluate the graph already upon the first session.run([iter_train_handle, iter_val_handle]) which obviously does not contain a handle in the feed_dict yet.

The workaround solution being to overwrite the hooks that cause the problem and changing the code in before_run and after_run to only evaluate on session.run calls containing the handle in the feed_dict (you can access the feed_dict of the current session.run call via the run_context argument of before_run and after_run)

Or you can use the latest master of Tensorflow (post-1.4) which adds a run_step_fn function to MonitoredSession which allows you to specify the following step_fn which will avoid the error (on the expense of evaluating the if statement TrainingIteration number of times ...)

```<code>def step_fn(step_context):
  if handle_train is None:
    handle_train, handle_val = sess.run([iter_train_handle, iter_val_handle])
  return step_context.run_with_hooks(fetches=..., feed_dict=...)
</code>```

Body:
Tensorflow programmer's guide recommends using feedable iterator to switch between training and validation dataset without reinitializing the iterator. It mainly requires to feed the handle to choose between them.

How to use it along with tf.train.MonitoredTrainingSession?

The following method fails with "RuntimeError: Graph is finalized and cannot be modified." error.

with tf.train.MonitoredTrainingSession() as sess:
    training_handle = sess.run(training_iterator.string_handle())
    validation_handle = sess.run(validation_iterator.string_handle())

How to achieve both the convenience of MonitoredTrainingSession and iterating training and validation datasets simultaneously?

Body:
@Michael Jaison G answer is correct. However, it does not work when you also want to use certain session_run_hooks that need to evaluate parts of the graph, like e.g. LoggingTensorHook or SummarySaverHook.
The example below will cause an error:

import tensorflow as tf

dataset_train = tf.data.Dataset.range(10)
dataset_val = tf.data.Dataset.range(90, 100)

iter_train_handle = dataset_train.make_one_shot_iterator().string_handle()
iter_val_handle = dataset_val.make_one_shot_iterator().string_handle()

handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(
    handle, dataset_train.output_types, dataset_train.output_shapes)
feature = iterator.get_next()

pred = feature * feature
tf.summary.scalar('pred', pred)
global_step = tf.train.create_global_step()

summary_hook = tf.train.SummarySaverHook(save_steps=5,
                                         output_dir="summaries", summary_op=tf.summary.merge_all())

with tf.train.MonitoredTrainingSession(hooks=[summary_hook]) as sess:
    handle_train, handle_val = sess.run([iter_train_handle, iter_val_handle])

    for step in range(10):
        feat = sess.run(feature, feed_dict={handle: handle_train})
        pred_ = sess.run(pred, feed_dict={handle: handle_train})
        print('train: ', feat)
        print('pred: ', pred_)

        if step % 3 == 0:
            print('val', sess.run(feature, feed_dict={handle: handle_val}))

This will fail with error:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype string
     [[Node: Placeholder = Placeholder[dtype=DT_STRING, shape=[], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
     [[Node: cond/Switch_1/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_18_cond/Switch_1", tensor_type=DT_INT64, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]

The reason being that the hook will try to evaluate the graph already upon the first session.run([iter_train_handle, iter_val_handle]) which obviously does not contain a handle in the feed_dict yet.

The workaround solution being to overwrite the hooks that cause the problem and changing the code in before_run and after_run to only evaluate on session.run calls containing the handle in the feed_dict (you can access the feed_dict of the current session.run call via the run_context argument of before_run and after_run)

Or you can use the latest master of Tensorflow (post-1.4) which adds a run_step_fn function to MonitoredSession which allows you to specify the following step_fn which will avoid the error (on the expense of evaluating the if statement TrainingIteration number of times ...)

def step_fn(step_context):
  if handle_train is None:
    handle_train, handle_val = sess.run([iter_train_handle, iter_val_handle])
  return step_context.run_with_hooks(fetches=..., feed_dict=...)


问:
Deeplinking to Spotify Playlist without Starting the Music on Android?
When a user presses a button in my Android app, I'd like to deeplink them to a specified playlist on Spotify and NOT start the playlist. Or, if necessary, have the playlist start music and then immediately Pause/Stop the music.

I have most of it figured out below:

```<code>String spotifyPackageName = "com.spotify.music";
String viewAction = Intent.ACTION_VIEW;
String spotifyUriString = "spotify:user:" + userId + ":playlist:" + playlistId + ":play";
Uri spotifyUri = Uri.parse(spotifyUriString);

Intent spotifyIntent = new Intent(viewAction, spotifyUri);
spotifyIntent.setPackage(spotifyPackageName);

startActivity(spotifyIntent);
</code>```

I am unsure about the correct Intent action to use to open up the playlist without automatically starting the music. Thanks!

答:
The music starts playing automatically since there is a ":play" at the end of the Spotify Uri you are providing.

If you would like to open the playlist but not have it start playing automatically you should change the Uri to following.

```<code>String spotifyUriString = "spotify:user:" + userId + ":playlist:" + playlistId;
</code>```

Body:
When a user presses a button in my Android app, I'd like to deeplink them to a specified playlist on Spotify and NOT start the playlist. Or, if necessary, have the playlist start music and then immediately Pause/Stop the music.

I have most of it figured out below:

String spotifyPackageName = "com.spotify.music";
String viewAction = Intent.ACTION_VIEW;
String spotifyUriString = "spotify:user:" + userId + ":playlist:" + playlistId + ":play";
Uri spotifyUri = Uri.parse(spotifyUriString);

Intent spotifyIntent = new Intent(viewAction, spotifyUri);
spotifyIntent.setPackage(spotifyPackageName);

startActivity(spotifyIntent);

I am unsure about the correct Intent action to use to open up the playlist without automatically starting the music. Thanks!

Body:
The music starts playing automatically since there is a ":play" at the end of the Spotify Uri you are providing.

If you would like to open the playlist but not have it start playing automatically you should change the Uri to following.

String spotifyUriString = "spotify:user:" + userId + ":playlist:" + playlistId;


问:
How to implements secure connections (No | SSL | STARTTLS) in SmtpClient to send mail?
I use class SmtpClient of namespace System.Net.Mail to send mail:
I create SmtpClient to send mail:

```<code>private static SmtpClient CreateSmtpClient (string host, string user, string password, int port)
        {
            var smtpClient = new SmtpClient (host, port);
            smtpClient.Credentials = new NetworkCredential (user, password);
            return smtpClient;
        }
</code>```

and use it:

```<code>var mailMessage = new MailMessage ();
var smtpClient = CreateSmtpClient (host, user, password, port);
smtpClient.Send (mailMessage);
</code>```

How to implements secure email transfer when I have 3 option secure connection is: No | STARTTLS | SSL ?
Many thanks !

答:
.NET built-in mail class doesn't support the needed SSL method (implicit SSL) and there's nothing to do with this: the reason is explained here.

There exist third-party SMTP client components that do both explicit and implicit SSL , for example, AIM(Aegis Implicit Mail), or you should consider sending email through Gmail, Yahoo, Outlook, etc.

Body:
I use class SmtpClient of namespace System.Net.Mail to send mail:
I create SmtpClient to send mail:

private static SmtpClient CreateSmtpClient (string host, string user, string password, int port)
        {
            var smtpClient = new SmtpClient (host, port);
            smtpClient.Credentials = new NetworkCredential (user, password);
            return smtpClient;
        }

and use it:

var mailMessage = new MailMessage ();
var smtpClient = CreateSmtpClient (host, user, password, port);
smtpClient.Send (mailMessage);

How to implements secure email transfer when I have 3 option secure connection is: No | STARTTLS | SSL ?
Many thanks !


问:
centered time window in apache flink
Is it possible to collect windows whose center is a particular event of interest?

Imagine a stream of events:

```<code>....e...........e...E........e......
</code>```

In particular I'm interested in a trigger event E and its surroundings (+- a few minutes):

```<code>....e..........|e...E....|....e......
</code>```

答:
Implementing this logic with Flink's window operators (incl. custom Trigger and Evictor implementations) should be possible but quite challenging in my opinion.

I think a better approach would be a ProcessFunction. A ProcessFunction can register timers (processing time or event time) that call a callback function. For the given use case, a ProcessFunction would collect all records in managed state. When a trigger event is received, a timer is registered to wait for more events to arrive until the window boundary around the trigger event expired. Moreover, the ProcessFunction needs to periodically remove all elements that arrived too early to be associated with a trigger event. This can also be done by registering a timer.

Title: centered time window in apache flink

Body:
Is it possible to collect windows whose center is a particular event of interest?

Imagine a stream of events:

....e...........e...E........e......

In particular I'm interested in a trigger event E and its surroundings (+- a few minutes):

....e..........|e...E....|....e......


问:
Editable text not working in Angular js
Using angular js on click of text, text should be editable. Currently not working. Used this library. Following code is in view page.

JS:

var app = angular.module('virVenturesAPP', ['angularUtils.directives.dirPagination','720kb.datepicker','xeditable']);//'720kb.datepicker'
var site_url = 'http://localhost/vv/';

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';
});
```

<p>HTML:</p>

<pre class="lang-html prettyprint-override"><code><table id="table_id" class="table table-striped table-hover table-bordered" ng-show="numberLoad">
    <thead>
        <tr>
            <th>#</th>
            <th>RRD Track No</th>
            <th>Order Primary Key</th>
            <th>Order Id</th>
            <th>Mapped Date</th>
            </tr>
    </thead>
    <tbody>
        <tr dir-paginate="rrd in getRrdList |  itemsPerPage:rrdinfo.itemsPerPage" current-page="rrdinfo.currentPage" total-items="total_count">
            <td>{{rrd.id}}</td>
            <td>{{rrd.rrd_track_no}}</td>
            <td >{{rrd.ord_primary_key}}</td>
            <!-- <td editable-text="rrd.order_id" ng-if="rrd.order_id==='' "> <p contenteditable="true"> enter order</p></td>-->
            <td ng-if="rrd.order_id==='' ">  enter order id</td>
            <td ng-if="rrd.order_id!=='' ">{{rrd.order_id}}</td>
            <td>{{rrd.mapped_date}}</td>
        </tr>
    </tbody>
</table>
</code>```

答:
I removed the following code:

ng-show="numberLoad" line 2

ng-if="rrd.order_id==='' " line 18

['angularUtils.directives.dirPagination','720kb.datepicker'] I think this line of code is the real problem

and it works:

jsfiddle

try to investigate better

```<code>   <div ng-app="virVenturesAPP" ng-controller="Ctrl">
      <table id="table_id" class="table table-striped table-hover table-bordered" >
                <thead>
                    <tr>
                        <th>#</th>
                        <th>RRD Track No</th>
                        <th>Order Primary Key</th>
                        <th>Order Id</th>
                        <th>Mapped Date</th>
                        </tr>
                </thead>
                <tbody>
                    <tr dir-paginate="rrd in getRrdList |  itemsPerPage:rrdinfo.itemsPerPage" current-page="rrdinfo.currentPage" total-items="total_count">
                        <td>{{rrd.id}}</td>
                        <td>{{rrd.rrd_track_no}}</td>
                        <td >{{rrd.ord_primary_key}}</td>
                        <!-- <td editable-text="rrd.order_id" ng-if="rrd.order_id==='' "> <p contenteditable="true"> enter order</p></td>-->
                        <td >  <a data-title="Enter username" editable-text="rrd.order_id" data-pk="1" data-type="text" id="usernameaa" href="#" class="editable editable-click edit_text" data-original-title="" title="">enter order id</a></td>
                        <td ng-if="rrd.order_id!=='' ">{{rrd.order_id}}</td>
                        <td>{{rrd.mapped_date}}</td>
                    </tr>
                </tbody>
            </table>
 </div>
</code>```

//script

```<code>var app = angular.module('virVenturesAPP', ['xeditable']);

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';

});

app.controller('Ctrl', function($scope) {
  $scope.rrd = {
    order_id: 'awesome user'
  };
});
</code>```

Title: Editable text not working in Angular js

Body:
Using angular js on click of text, text should be editable. Currently not working. Used this library. Following code is in view page.

JS:

var app = angular.module('virVenturesAPP', ['angularUtils.directives.dirPagination','720kb.datepicker','xeditable']);//'720kb.datepicker'
var site_url = 'http://localhost/vv/';

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';
});

HTML:

            #
            RRD Track No
            Order Primary Key
            Order Id
            Mapped Date

            {{rrd.id}}
            {{rrd.rrd_track_no}}
            {{rrd.ord_primary_key}}

              enter order id
            {{rrd.order_id}}
            {{rrd.mapped_date}}

Body:
I removed the following code:

ng-show="numberLoad" line 2

ng-if="rrd.order_id==='' " line 18

['angularUtils.directives.dirPagination','720kb.datepicker'] I think this line of code is the real problem

and it works:

jsfiddle

try to investigate better

   <div ng-app="virVenturesAPP" ng-controller="Ctrl">
      <table id="table_id" class="table table-striped table-hover table-bordered" >
                <thead>
                    <tr>
                        <th>#</th>
                        <th>RRD Track No</th>
                        <th>Order Primary Key</th>
                        <th>Order Id</th>
                        <th>Mapped Date</th>
                        </tr>
                </thead>
                <tbody>
                    <tr dir-paginate="rrd in getRrdList |  itemsPerPage:rrdinfo.itemsPerPage" current-page="rrdinfo.currentPage" total-items="total_count">
                        <td>{{rrd.id}}</td>
                        <td>{{rrd.rrd_track_no}}</td>
                        <td >{{rrd.ord_primary_key}}</td>
                        <!-- <td editable-text="rrd.order_id" ng-if="rrd.order_id==='' "> <p contenteditable="true"> enter order</p></td>-->
                        <td >  <a data-title="Enter username" editable-text="rrd.order_id" data-pk="1" data-type="text" id="usernameaa" href="#" class="editable editable-click edit_text" data-original-title="" title="">enter order id</a></td>
                        <td ng-if="rrd.order_id!=='' ">{{rrd.order_id}}</td>
                        <td>{{rrd.mapped_date}}</td>
                    </tr>
                </tbody>
            </table>
 </div>

//script

var app = angular.module('virVenturesAPP', ['xeditable']);

app.run(function(editableOptions) {
  editableOptions.theme = 'bs3';

});

app.controller('Ctrl', function($scope) {
  $scope.rrd = {
    order_id: 'awesome user'
  };
});


问:
Abnormal behaviour of "ng-click" angularjs
I'm trying to create a button that will call a function in the controller. My controller is called with VM...

```<code><md-content class="md-padding">
    <form name="loginForm">
        <md-input-container class="md-block">
            <label>Username</label>
            <input required name="username" ng-model="vm.user.username">
            <div ng-messages="loginForm.username.$error">
                <div ng-message="required">This is required.</div>
            </div>
        </md-input-container>
    </form>
    <md-card-actions layout="row" layout-align="end center">
        <md-button class="md-primary" ng-click="vm.userLogin(username)" ng-disabled="loginForm.$invalid">Login
        </md-button>

        <md-button class="md-primary md-raised" ng-click="registerme=true" >Register
        </md-button>
    </md-card-actions>
</md-content>
</code>```

the problem is with the "userLogin" function that is not called. The rest of the HTML part has others ng-click call like:

```<code>   <md-card-actions layout="row" layout-align="end center">
<md-button class="md-primary md-raised" ng-click="vm.submitUserData()" ng-disabled="userForm.$invalid">Submit
</md-button>
</code>```

and this works fine.
Those are the functions called in the controller

```<code>function submitUserData() {
    alert(vm.user.username);
    // POST /users
    baseUsers.post(vm.user).then(function (resp,newUser) {
        var pref = vm.preferenze;
        // Ridirigo la navigazione alla pagina "recommendation" passando come parametri le raccomandazioni calcolate e l' id dell utente
        $state.go('form.recommendation',{recommendations:resp,userId: vm.user.id,preferences: pref,iteration: 1});
        }, function (){//resp)
        });
}

function userLogin(username) {
    alert("dbdbdb");
    alert(username);
}
</code>```

I'm losing my head trying to figure it out why it doesn't call the alert function. I tryied either to move the button in the page but nothing change.
Thanks to everyone who is gonna help me.

答:
The syntax is simply confusing you. If you have "controller as" syntax, then make sure that all inner functions are part of that controller.

Firstly, your function vm.userLogin(username) should be vm.userLogin(vm.user.username)

Secondly, the function within the controller should be written differently:

```<code>vm.userLogin = function(username) {
    alert("dbdbdb");
    alert(username);
}
</code>```

Where vm is your scope assignment, e.g. var vm = this;, but you can replace it with $scope.userLogin = function(username){...}

Body:
I'm trying to create a button that will call a function in the controller. My controller is called with VM...

<md-content class="md-padding">
    <form name="loginForm">
        <md-input-container class="md-block">
            Username
            <input required name="username" ng-model="vm.user.username">

This is required.

        </md-input-container>
    </form>
    <md-card-actions layout="row" layout-align="end center">
        <md-button class="md-primary" ng-click="vm.userLogin(username)" ng-disabled="loginForm.$invalid">Login
        </md-button>

        <md-button class="md-primary md-raised" ng-click="registerme=true" >Register
        </md-button>
    </md-card-actions>
</md-content>

the problem is with the "userLogin" function that is not called. The rest of the HTML part has others ng-click call like:

   <md-card-actions layout="row" layout-align="end center">
<md-button class="md-primary md-raised" ng-click="vm.submitUserData()" ng-disabled="userForm.$invalid">Submit
</md-button>

and this works fine.
Those are the functions called in the controller

function submitUserData() {
    alert(vm.user.username);
    // POST /users
    baseUsers.post(vm.user).then(function (resp,newUser) {
        var pref = vm.preferenze;
        // Ridirigo la navigazione alla pagina "recommendation" passando come parametri le raccomandazioni calcolate e l' id dell utente
        $state.go('form.recommendation',{recommendations:resp,userId: vm.user.id,preferences: pref,iteration: 1});
        }, function (){//resp)
        });
}

function userLogin(username) {
    alert("dbdbdb");
    alert(username);
}

I'm losing my head trying to figure it out why it doesn't call the alert function. I tryied either to move the button in the page but nothing change.
Thanks to everyone who is gonna help me.

Body:
The syntax is simply confusing you. If you have "controller as" syntax, then make sure that all inner functions are part of that controller.

Firstly, your function vm.userLogin(username) should be vm.userLogin(vm.user.username)

Secondly, the function within the controller should be written differently:

vm.userLogin = function(username) {
    alert("dbdbdb");
    alert(username);
}

Where vm is your scope assignment, e.g. var vm = this;, but you can replace it with $scope.userLogin = function(username){...}


问:
How parsing works for unix commands: "rm" and "cp"
We are executing below commands

```<code>rm -f $folder_name/filename*

cp $folder_name1/filename1* $folder_name/
</code>```

After checking the execution log we get following command executions

```<code>rm -f '/home/user/file*'

cp /home1/user1/file1* /home/user/
</code>```

Why rm executes with a single quote and not cp command?

答:
Chances are you are examining the output of bash -x which adds single quotes around arguments just for disambiguation. But the code you are showing could not result in the output you describe.

```<code>rm wildcard*
</code>```

will expand to rm and the matching files if the wildcard has matches.  If it doesn't, though, the expansion will be the equivalent of

```<code>'rm' 'wildcard*'
</code>```

where I have added quotes just to indicate that no further evaluation will take place, similary to what bash -x (and at least some variants of sh -x) does.

Body:
We are executing below commands

rm -f $folder_name/filename*

cp $folder_name1/filename1* $folder_name/

After checking the execution log we get following command executions

rm -f '/home/user/file*'

cp /home1/user1/file1* /home/user/

Why rm executes with a single quote and not cp command?

Body:
Chances are you are examining the output of bash -x which adds single quotes around arguments just for disambiguation. But the code you are showing could not result in the output you describe.

rm wildcard*

will expand to rm and the matching files if the wildcard has matches.  If it doesn't, though, the expansion will be the equivalent of

'rm' 'wildcard*'

where I have added quotes just to indicate that no further evaluation will take place, similary to what bash -x (and at least some variants of sh -x) does.


问:
AWS DynamoDB list distinct ID
I am developing something with nodejs and I have a table on DynamoDB. Therefore, I am using aws-sdk for nodejs to work with these two things.

Here is an example. ID and name are the combined key to the table.

```<code>ID    name   otherData
----------------------
1     Matt   123
1     Mary   1234
2     Mary   2312
4     Mary    3123
4     Pet    3123
</code>```

What I want is to get a list of distinct ID. So, the expected output is

```<code>ID = [1, 2, 4]
</code>```

How to do this?

答:
1) Do a DynamoDB scan to get all (non-unique) ID values. The ProjectionExpression limits the result attributes returned, in this case to ID only. Note this doesn't make your scan any faster. When you execute the scan you will get a JSON object back containing your results. You can use JMES to get the ID array (data.Items.ID).

2) Make the array unique in your nodejs code (e.g. using the ArrNoDupe code function below)

```<code>var params = {
 ProjectionExpression: "ID",
 TableName: "YOUR_TABLE"
};

ddb.scan(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
      console.log(ArrNoDupe(data.Items.ID));
    });
  }
});

function ArrNoDupe(a) {
    var temp = {};
    for (var i = 0; i < a.length; i++)
        temp[a[i]] = true;
    var r = [];
    for (var k in temp)
        r.push(k);
    return r;
}
</code>```

Title: AWS DynamoDB list distinct ID

Body:
I am developing something with nodejs and I have a table on DynamoDB. Therefore, I am using aws-sdk for nodejs to work with these two things.

Here is an example. ID and name are the combined key to the table.

ID    name   otherData
----------------------
1     Matt   123
1     Mary   1234
2     Mary   2312
4     Mary    3123
4     Pet    3123

What I want is to get a list of distinct ID. So, the expected output is

ID = [1, 2, 4]

How to do this?

Body:
1) Do a DynamoDB scan to get all (non-unique) ID values. The ProjectionExpression limits the result attributes returned, in this case to ID only. Note this doesn't make your scan any faster. When you execute the scan you will get a JSON object back containing your results. You can use JMES to get the ID array (data.Items.ID).

2) Make the array unique in your nodejs code (e.g. using the ArrNoDupe code function below)

var params = {
 ProjectionExpression: "ID",
 TableName: "YOUR_TABLE"
};

ddb.scan(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
      console.log(ArrNoDupe(data.Items.ID));
    });
  }
});

function ArrNoDupe(a) {
    var temp = {};
    for (var i = 0; i < a.length; i++)
        temp[a[i]] = true;
    var r = [];
    for (var k in temp)
        r.push(k);
    return r;
}


问:
'More than one file was found with OS independent path project.properties' Error in android
I'm getting this error after I added google translate api on my project. I am using Android Studio 3.0, Gradle 3.0.0.

```<code> Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
 More than one file was found with OS independent path 'project.properties'
</code>```

I have tried the solution presented here and here, but with no success.
Also I tried downgrading gradle to version 2.3 but that didn't solve the problem either.

My build.gradle file :

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.aim.fjalortest"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/project.properties'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'

    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
    compile 'com.android.support:recyclerview-v7:25.4.0'
    compile 'com.google.android.gms:play-services-vision:9.0.0+'
    compile 'com.android.support:design:25.4.0'
    compile 'com.google.cloud:google-cloud-translate:1.12.0'
    //annotationProcessor 'com.google.cloud:google-cloud-translate:1.12.0'

    //jackson
    compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
    compile 'com.fasterxml.jackson.core:jackson-core:2.8.5'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'

}
</code>```

Can anyone help me figuring out what's causing this error?

答:
Try adding multidexEnabled to your app-level build.gradle,  as follows : </p>

```<code> defaultConfig {
    multiDexEnabled true
 }
</code>```

Body:
I'm getting this error after I added google translate api on my project. I am using Android Studio 3.0, Gradle 3.0.0.

 Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
 More than one file was found with OS independent path 'project.properties'

I have tried the solution presented here and here, but with no success.
Also I tried downgrading gradle to version 2.3 but that didn't solve the problem either.

My build.gradle file :

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.aim.fjalortest"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/project.properties'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'

    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
    compile 'com.android.support:recyclerview-v7:25.4.0'
    compile 'com.google.android.gms:play-services-vision:9.0.0+'
    compile 'com.android.support:design:25.4.0'
    compile 'com.google.cloud:google-cloud-translate:1.12.0'
    //annotationProcessor 'com.google.cloud:google-cloud-translate:1.12.0'

    //jackson
    compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
    compile 'com.fasterxml.jackson.core:jackson-core:2.8.5'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'

}

Can anyone help me figuring out what's causing this error?

Body:
Try adding multidexEnabled to your app-level build.gradle,  as follows :

 defaultConfig {
    multiDexEnabled true
 }


问:
How to call another variable inside ngFor loop
Need your help:

```<code>//ts file
export class SettingsPage {
  pays: [string] = [];
  gateways: string = '';
</code>```

I can successfully call both individually but when i call gateways inside pays loop it doesn't work:

```<code><ion-row>

  <ion-item *ngFor="let pay of pays">
  <ion-icon name="image" item-start></ion-icon>
  <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}">
  {{gateways.desc}}   // doesn't work inside the loop
  </ion-input>

{{gateways.desc}} // works fine outside the loop

</ion-row>
</code>```

答:
It's not being shown because it's not valid to add anything inside of the ion-input (check the docs).

You can definitely add that inside of the loop, like this:

```<code><ion-row>
  <ion-item *ngFor="let pay of pays">
    <ion-icon name="image" item-start></ion-icon>
    <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}"></ion-input>
    <ion-note item-end>{{ gateways.desc }}</ion-note>
  </ion-item>
</ion-row>
</code>```

I'm using an ion-note just to add another valid Ionic layout, but you could add whatever you want if it's valid in Ionic.

Body:
Need your help:

//ts file
export class SettingsPage {
  pays: [string] = [];
  gateways: string = '';

I can successfully call both individually but when i call gateways inside pays loop it doesn't work:

<ion-row>

  <ion-item *ngFor="let pay of pays">
  <ion-icon name="image" item-start></ion-icon>
  <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}">
  {{gateways.desc}}   // doesn't work inside the loop
  </ion-input>

{{gateways.desc}} // works fine outside the loop

</ion-row>

Body:
It's not being shown because it's not valid to add anything inside of the ion-input (check the docs).

You can definitely add that inside of the loop, like this:

<ion-row>
  <ion-item *ngFor="let pay of pays">
    <ion-icon name="image" item-start></ion-icon>
    <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}"></ion-input>
    <ion-note item-end>{{ gateways.desc }}</ion-note>
  </ion-item>
</ion-row>

I'm using an ion-note just to add another valid Ionic layout, but you could add whatever you want if it's valid in Ionic.


问:
F# - Return Float Array to Excel Using Excel-DNA - Only First Value Displayed

I am trying to display (using an array formula) an F# and Excel-DNA returned float array but, though I can see the correct result in the "Function Arguments" dialog box, only the first value is displayed in the selected range. What am I missing?

答: It looks like Excel-DNA is returning a row array so to convert it to a column array, I need to use TRANSPOSE() in Excel.


问:
Any way to get old field name in one query on UPDATE with MySQL?
Say you were going to run an update query & update a field, however you wanted to also retrieve the prior value before the value is updated to the new value. Is there a way to do this in one query? Or do you have to run a SELECT before you run the UPDATE to get the value?</p>

答: If you were to add a BEFORE UPDATE trigger to the table, during the processing of the trigger both the old and the new values of the affected column(s) would be available. See here for more... http://dev.mysql.com/doc/refman/5.0/en/triggers.html .