答:
just change by this

```<code> var jsonData = JSON.parse(data);
</code>```

var data ='[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"Geeks Help","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]';
var jsonData = JSON.parse(data);

console.log(jsonData[0].checkNo)
console.log(jsonData[0].routingNo)```

Title: json data not working on server

Body:
just change by this

 var jsonData = JSON.parse(data);

var data ='[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"Geeks Help","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]';
var jsonData = JSON.parse(data);

console.log(jsonData[0].checkNo)
console.log(jsonData[0].routingNo)


来源: stackexchange

问:
Calculating the time complexity of recursive algorithm T(n) = T(k) + T(n-k)
I want to calculate the time complexity of the following recursive algorithm, where,

```<code>n = j - i (size of array)
i ≤ k ≤ j
process(A, i, j) takes Θ(n) time

Algo(Array A[], int i, int j)
    if (i<j)
        k = process(A, i, j)
        Algo(A, i, k)
        Algo(A, k+1, j)
</code>```

I came up with the following:

```<code>T(n) = Θ(n) + T(k) + T(n-k)
</code>```

I'm not sure if that is correct and if it is, how to proceed from that?

Update:

Is the following correct?

The worst case value for k is i or j,

```<code>T(n) = Θ(n) + T(0) + T(n)
</code>```

答:
This recursive structure is more like quick sort whose worst-case running time  is O(n^2).

```<code>algorithm quicksort(A, lo, hi) is
    if lo < hi then
        p := partition(A, lo, hi)
        quicksort(A, lo, p – 1)
        quicksort(A, p + 1, hi)
</code>```

The partition algorithm takes O(N) time. For analysis please refer Quick-Sort. I can't explain any better.

ContentLicense: CC BY-SA 3.0

Body:
I want to calculate the time complexity of the following recursive algorithm, where,

n = j - i (size of array)
i ≤ k ≤ j
process(A, i, j) takes Θ(n) time

Algo(Array A[], int i, int j)
    if (i<j)
        k = process(A, i, j)
        Algo(A, i, k)
        Algo(A, k+1, j)

I came up with the following:

T(n) = Θ(n) + T(k) + T(n-k)

I'm not sure if that is correct and if it is, how to proceed from that?

Update:

Is the following correct?

The worst case value for k is i or j,

T(n) = Θ(n) + T(0) + T(n)

Body:
This recursive structure is more like quick sort whose worst-case running time  is O(n^2).

algorithm quicksort(A, lo, hi) is
    if lo < hi then
        p := partition(A, lo, hi)
        quicksort(A, lo, p – 1)
        quicksort(A, p + 1, hi)

The partition algorithm takes O(N) time. For analysis please refer Quick-Sort. I can't explain any better.


问:
How to extract the data from JSON file to write test case
How to extract the required parent/child node value from JSON output in postman.

I need to extract model.ConfirmPassword from the below JSON file.

```<code>{
  "Message": "The request is invalid.",
  "ModelState": {
  "model.ConfirmPassword": [
  "The password and confirmation password do not match."
  ]
}
</code>```

What is the property to be passed in order to get that. jsonData.value is not working as I mentioned below.

```<code>var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.value;
</code>```

答:
Edit Before I missed that model.ConfirmPassword is nested in ModelState.

This is how can read the property:

```<code>var x = jsonData.ModelState['model.ConfirmPassword'];
console.log(x);
</code>```

Here is the plunk: http://plnkr.co/edit/rCtVijwWpPgX7SdnP2ja

Body:
How to extract the required parent/child node value from JSON output in postman.

I need to extract model.ConfirmPassword from the below JSON file.

{
  "Message": "The request is invalid.",
  "ModelState": {
  "model.ConfirmPassword": [
  "The password and confirmation password do not match."
  ]
}

What is the property to be passed in order to get that. jsonData.value is not working as I mentioned below.

var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.value;

Body:
Edit Before I missed that model.ConfirmPassword is nested in ModelState.

This is how can read the property:

var x = jsonData.ModelState['model.ConfirmPassword'];
console.log(x);

Here is the plunk: http://plnkr.co/edit/rCtVijwWpPgX7SdnP2ja


问:
Full statement from ISO 8583
I would like to know if it is possible to do a full statement (between a date range) through ISO 8583, I have seen ATMs which do full statements and was wondering what method they used.  I know balance inquiry and mini statements are possible on a POS devise over 8583.

If it is possible does anyone have an information on the structure of the message, ideally for FLexcube.

答: The mini-statement is not part of ISO 8583 (or MVA). It is usually implemented as a proprietary extension. Hence you need to go to an ATM owned by your bank, or, is part of a consortium of banks that share an ATM infrastructure with your bank. </p>

ContentLicense: CC BY-SA 2.5

Title: Full statement from ISO 8583


问:
How to sense when configured wifi security changes in android
I need to handle a case when desired SSID is connected or configured in list, but meanwhile if its security changes, how should I get notified

currently, I am getting the Supplicant State as "Disconnected" when the desired network is connected and meanwhile if its security changes.

答:
using this method you can sense when any changes....</p>

```<code>/**
 * Uppsala University
 *
 * Project CS course, Fall 2012
 *
 * Projekt DV/Project CS, is a course in which the students develop software for
 * distributed systems. The aim of the course is to give insights into how a big
 * project is run (from planning to realization), how to construct a complex
 * distributed system and to give hands-on experience on modern construction
 * principles and programming methods.
 *
 * All rights reserved.
 *
 * Copyright (C) 2012 LISA team
 */
package project.cs.lisa.networksettings;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiHandler {
    //constants
    public static final int WEP = 1;
    public static final int WAP = 2;
    public static final int OPEN_NETWORK = 3;

    public static final String TAG = "LISA_Network";

    /** dfsdfsdfsdf. */
    WifiConfiguration wifiConf;             /* WifiConfiguration object */

    /** dfsdfsdfsdf. */
    WifiManager wifiMgr;                            /* WifiManager object */

    /** dfsdfsdfsdf. */
    WifiInfo wifiInfo;                              /* WifiInfo object */

    /** dfsdfsdfsdf. */
    List<ScanResult> wifiScan;              /* List of ScanResult objects */

    /**
     * Constructor initializes WifiManager and WifiInfo.
     * @param context
     */
    public WifiHandler(Context context) {
        wifiMgr  = getWifiManager(context);     // gets wifiMgr in the current context
        wifiInfo = getWifiInfo(context);            // gets wifiInfo in the current context
        wifiConf = getWifiConf(context);            // gets wifiConf in the current context
        wifiScan = getWifiInRange();                    // gets wifiScan in the current context
    }

    /**
     * Function checkWifiEnabled checks if the WiFi connection
     * is enabled on the device.
     * @param wifiMgr
     * @return true  if the WiFi connection is enabled,
     *               false if the WiFi connection is disabled
     */
    public boolean checkWifiEnabled() {
        // checks if WiFi is enabled
        return (wifiMgr != null && wifiMgr.isWifiEnabled());
    }

    /**
     * Function enableWifi enables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if the attempt to enable WiFi succeeded,
     *               false if the attempt to enable WiFi failed.
     */
    public boolean enableWifi() {
        // enables WiFi connection
        return wifiMgr.setWifiEnabled(true);
    }

    /**
     * Function disableWifi disables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if WiFi connection was disabled,
     *               false if attempt to disable WiFi failed.
     */
    public boolean disableWifi() {
        // disables WiFi connection
        return wifiMgr.setWifiEnabled(false);
    }

    /**
     * Function getWifiManager gets the WiFiManager object from the device.
     * @param context
     * @return WifiManager object. Also sets the class variable
     *               wifiMgr as the WifiManager object returned.
     */
    public WifiManager getWifiManager(Context context) {
        WifiManager wifiMgr = null;

        // gets WifiManager obj from the system
        wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiMgr == null) {
            Log.d("TAG", "WIFI_SERVICE is the wrong service name.");
        }

        return wifiMgr;
    }

    /**
     * Function getWifiInfo gets the current WiFi connection information in a
     * WifiInfo object from the device.
     * @param context
     * @return wifiInfo created object or
     *               null       if wifi is not enabled.
     */
    public WifiInfo getWifiInfo(Context context) {
        WifiInfo wifiInfo = null;

        // gets WiFi network info of the current connection
        if (checkWifiEnabled()) {
            wifiInfo = (WifiInfo) wifiMgr.getConnectionInfo();
        }

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty.");
        }

        return wifiInfo;
    }

    /**
     * Function that returns a WifiConfiguration object from the WifiInfo
     * object from the class. If wifiInfo exists, then we are able to retrieve
     * information from the current connection
     * @param context
     * @return WifiConfiguration object created.
     */
    public WifiConfiguration getWifiConf(Context context) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty");
            return null;
        }

        wifiConfiguration.SSID = wifiInfo.getSSID();
        wifiConfiguration.networkId = wifiInfo.getNetworkId();

        return wifiConfiguration;
    }

    /**
     * Creates a new WifiConfiguration object for wifiConf.
     */
    public void clearWifiConfig() {
        wifiConf = new WifiConfiguration();
    }

    /**
     * Function getWifiInRange returns all the WiFi networks that are
     * accessible through the access point (device AP) found during the
     * last scan.
     * @param wifi
     * @return List of ScanResult containing information on all WiFi networks
     *               discovered in the range.
     */
    public List<ScanResult> getWifiInRange() {
        // gets ~last~ list of WiFi networks accessible through the access point.
        return (wifiScan = (List<ScanResult>) wifiMgr.getScanResults());
    }

    /**
     * Function that scans for wifi networks available in the devices range.
     * @return true  if scan started
     *               false if scan could not be started
     */
    public boolean scanWifiInRange() {
        if (!checkWifiEnabled()) {
            return false;
        }

        if (!wifiMgr.startScan()) {
            Log.d("TAG", "Failed to scan wifi's in range.");
            return false;
        }

        return true;
    }

    /**
     * Function to disconnect from the currently connected WiFi AP.
     * @return true  if disconnection succeeded
     *               false if disconnection failed
     */
    public boolean disconnectFromWifi() {
        return (wifiMgr.disconnect());
    }

    /**
     * Function to connect to a selected network
     * @param networkSSID         network SSID name
     * @param   networkPassword     network password
     * @param networkId           network ID from WifiManager
     * @param SecurityProtocol    network security protocol
     * @return true  if connection to selected network succeeded
     *               false if connection to selected network failed
     */
    public boolean connectToSelectedNetwork(String networkSSID, String networkPassword) {
        int networkId;
        int SecurityProtocol = WEP;

        // Clear wifi configuration variable
        clearWifiConfig();

        // Sets network SSID name on wifiConf
        wifiConf.SSID = "\"" + networkSSID + "\"";
        Log.d(TAG, "SSID Received: " + wifiConf.SSID);
        switch(SecurityProtocol) {
            // WEP "security".
            case WEP:
                wifiConf.wepKeys[0] = "\"" + networkPassword + "\"";
                wifiConf.wepTxKeyIndex = 0;
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;

                // WAP security. We have to set preSharedKey.
            case WAP:
                wifiConf.preSharedKey = "\""+ networkPassword +"\"";
                break;

                // Network without security.
            case OPEN_NETWORK:
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }

        // Add WiFi configuration to list of recognizable networks
        if ((networkId = wifiMgr.addNetwork(wifiConf)) == -1) {
            Log.d("TAG", "Failed to add network configuration!");
            return false;
        }

        // Disconnect from current WiFi connection
        if (!disconnectFromWifi()) {
            Log.d("TAG", "Failed to disconnect from network!");
            return false;
        }

        // Enable network to be connected
        if (!wifiMgr.enableNetwork(networkId, true)) {
            Log.d("TAG", "Failed to enable network!");
            return false;
        }

        // Connect to network
        if (!wifiMgr.reconnect()) {
            Log.d("TAG", "Failed to connect!");
            return false;
        }

        return true;
    }
}
</code>```

Body:
using this method you can sense when any changes....

/**
 * Uppsala University
 *
 * Project CS course, Fall 2012
 *
 * Projekt DV/Project CS, is a course in which the students develop software for
 * distributed systems. The aim of the course is to give insights into how a big
 * project is run (from planning to realization), how to construct a complex
 * distributed system and to give hands-on experience on modern construction
 * principles and programming methods.
 *
 * All rights reserved.
 *
 * Copyright (C) 2012 LISA team
 */
package project.cs.lisa.networksettings;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiHandler {
    //constants
    public static final int WEP = 1;
    public static final int WAP = 2;
    public static final int OPEN_NETWORK = 3;

    public static final String TAG = "LISA_Network";

    /** dfsdfsdfsdf. */
    WifiConfiguration wifiConf;             /* WifiConfiguration object */

    /** dfsdfsdfsdf. */
    WifiManager wifiMgr;                            /* WifiManager object */

    /** dfsdfsdfsdf. */
    WifiInfo wifiInfo;                              /* WifiInfo object */

    /** dfsdfsdfsdf. */
    List<ScanResult> wifiScan;              /* List of ScanResult objects */

    /**
     * Constructor initializes WifiManager and WifiInfo.
     * @param context
     */
    public WifiHandler(Context context) {
        wifiMgr  = getWifiManager(context);     // gets wifiMgr in the current context
        wifiInfo = getWifiInfo(context);            // gets wifiInfo in the current context
        wifiConf = getWifiConf(context);            // gets wifiConf in the current context
        wifiScan = getWifiInRange();                    // gets wifiScan in the current context
    }

    /**
     * Function checkWifiEnabled checks if the WiFi connection
     * is enabled on the device.
     * @param wifiMgr
     * @return true  if the WiFi connection is enabled,
     *               false if the WiFi connection is disabled
     */
    public boolean checkWifiEnabled() {
        // checks if WiFi is enabled
        return (wifiMgr != null && wifiMgr.isWifiEnabled());
    }

    /**
     * Function enableWifi enables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if the attempt to enable WiFi succeeded,
     *               false if the attempt to enable WiFi failed.
     */
    public boolean enableWifi() {
        // enables WiFi connection
        return wifiMgr.setWifiEnabled(true);
    }

    /**
     * Function disableWifi disables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if WiFi connection was disabled,
     *               false if attempt to disable WiFi failed.
     */
    public boolean disableWifi() {
        // disables WiFi connection
        return wifiMgr.setWifiEnabled(false);
    }

    /**
     * Function getWifiManager gets the WiFiManager object from the device.
     * @param context
     * @return WifiManager object. Also sets the class variable
     *               wifiMgr as the WifiManager object returned.
     */
    public WifiManager getWifiManager(Context context) {
        WifiManager wifiMgr = null;

        // gets WifiManager obj from the system
        wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiMgr == null) {
            Log.d("TAG", "WIFI_SERVICE is the wrong service name.");
        }

        return wifiMgr;
    }

    /**
     * Function getWifiInfo gets the current WiFi connection information in a
     * WifiInfo object from the device.
     * @param context
     * @return wifiInfo created object or
     *               null       if wifi is not enabled.
     */
    public WifiInfo getWifiInfo(Context context) {
        WifiInfo wifiInfo = null;

        // gets WiFi network info of the current connection
        if (checkWifiEnabled()) {
            wifiInfo = (WifiInfo) wifiMgr.getConnectionInfo();
        }

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty.");
        }

        return wifiInfo;
    }

    /**
     * Function that returns a WifiConfiguration object from the WifiInfo
     * object from the class. If wifiInfo exists, then we are able to retrieve
     * information from the current connection
     * @param context
     * @return WifiConfiguration object created.
     */
    public WifiConfiguration getWifiConf(Context context) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty");
            return null;
        }

        wifiConfiguration.SSID = wifiInfo.getSSID();
        wifiConfiguration.networkId = wifiInfo.getNetworkId();

        return wifiConfiguration;
    }

    /**
     * Creates a new WifiConfiguration object for wifiConf.
     */
    public void clearWifiConfig() {
        wifiConf = new WifiConfiguration();
    }

    /**
     * Function getWifiInRange returns all the WiFi networks that are
     * accessible through the access point (device AP) found during the
     * last scan.
     * @param wifi
     * @return List of ScanResult containing information on all WiFi networks
     *               discovered in the range.
     */
    public List<ScanResult> getWifiInRange() {
        // gets ~last~ list of WiFi networks accessible through the access point.
        return (wifiScan = (List<ScanResult>) wifiMgr.getScanResults());
    }

    /**
     * Function that scans for wifi networks available in the devices range.
     * @return true  if scan started
     *               false if scan could not be started
     */
    public boolean scanWifiInRange() {
        if (!checkWifiEnabled()) {
            return false;
        }

        if (!wifiMgr.startScan()) {
            Log.d("TAG", "Failed to scan wifi's in range.");
            return false;
        }

        return true;
    }

    /**
     * Function to disconnect from the currently connected WiFi AP.
     * @return true  if disconnection succeeded
     *               false if disconnection failed
     */
    public boolean disconnectFromWifi() {
        return (wifiMgr.disconnect());
    }

    /**
     * Function to connect to a selected network
     * @param networkSSID         network SSID name
     * @param   networkPassword     network password
     * @param networkId           network ID from WifiManager
     * @param SecurityProtocol    network security protocol
     * @return true  if connection to selected network succeeded
     *               false if connection to selected network failed
     */
    public boolean connectToSelectedNetwork(String networkSSID, String networkPassword) {
        int networkId;
        int SecurityProtocol = WEP;

        // Clear wifi configuration variable
        clearWifiConfig();

        // Sets network SSID name on wifiConf
        wifiConf.SSID = "\"" + networkSSID + "\"";
        Log.d(TAG, "SSID Received: " + wifiConf.SSID);
        switch(SecurityProtocol) {
            // WEP "security".
            case WEP:
                wifiConf.wepKeys[0] = "\"" + networkPassword + "\"";
                wifiConf.wepTxKeyIndex = 0;
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;

                // WAP security. We have to set preSharedKey.
            case WAP:
                wifiConf.preSharedKey = "\""+ networkPassword +"\"";
                break;

                // Network without security.
            case OPEN_NETWORK:
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }

        // Add WiFi configuration to list of recognizable networks
        if ((networkId = wifiMgr.addNetwork(wifiConf)) == -1) {
            Log.d("TAG", "Failed to add network configuration!");
            return false;
        }

        // Disconnect from current WiFi connection
        if (!disconnectFromWifi()) {
            Log.d("TAG", "Failed to disconnect from network!");
            return false;
        }

        // Enable network to be connected
        if (!wifiMgr.enableNetwork(networkId, true)) {
            Log.d("TAG", "Failed to enable network!");
            return false;
        }

        // Connect to network
        if (!wifiMgr.reconnect()) {
            Log.d("TAG", "Failed to connect!");
            return false;
        }

        return true;
    }
}


问:
How macOS .app's are executable vs .exe's?
I am a hardcore Windows user, and I know a LOT about Windows. But one thing I still don't really get... how are .app's on macOS executable when they are just a folder with that extension, like .exe's on Windows?? That's what I don't get.

Thanks.

答: As you've noticed, the .app itself is not an executable. It's a standardized folder structure which contains the real executable in one of the subfolders: Contents/MacOS. There's also a bunch of metadata and perhaps additional libraries the app needs in several subfolders within Contents. The metadata defines the icon, the application name, version number and so on. It is stored in Contents/Info.plist. The program on macOS that is responsible for showing you files and folders (Windows Explorer on Windows) is called Finder. Finder simply handles making a folder structure with the .app extension and an Info.plist present appear like a single executable file. There's more examples of folder structures that appear to be files in Finder, for example with .sparsebundle Disk Images or the Photo Libraries stored by Apple's Photos app. You can right click those "files" and choose "Show package contents" in Finder to look inside the folder structures.


问:
How to make an API proxy with Node.js?
Since GFW blocks some ip including flickr's, I like to make a API proxy with Node.js, but I am having trouble to open a GET request within the http server. Here is my code:

```<code>var http = require('http');
var qs = require('querystring');
var curl = require('request');
var serverPort = 3000;
http.createServer(function (request, response) {
  if(request.method === "GET") {
    response.writeHead(401, {'Content-Type': 'text/html'});
    response.write('<!doctype html><html><head><title>401</title></head><body>401: Unauthorized</body></html>');
    response.end();
  } else if(request.method === "POST") {
    if (request.url === "/") {
      var requestBody = '';
      request.on('data', function(data) {
        requestBody += data;
        if(requestBody.length > 1e7) {
          response.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
          response.end('413: Request Entity Too Large');
        }
      });
      request.on('end', function() {
        var body = getrequest();
        if (body === false) {
          response.writeHead(502, 'Bad Gateway', {'Content-Type': 'text/html'});
          response.end('502: Bad Gateway');
        } else {
          response.writeHead(200, {'Content-Type': 'text/html'});
          response.write(body);
          response.end();
        }
      });
    } else {
      response.writeHead(404, 'Resource Not Found', {'Content-Type': 'text/html'});
      response.end('<!doctype html><html><head><title>404</title></head><body>404: Resource Not Found</body></html>');
    }
  } else {
    response.writeHead(405, 'Method Not Supported', {'Content-Type': 'text/html'});
    return response.end('<!doctype html><html><head><title>405</title></head><body>405: Method Not Supported</body></html>');
  }
}).listen(serverPort);
function getrequest(){
  return curl('https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key={{insert_ur_api_key}}&user_id={{insert_ur_user_id}}&format=json', function (error, response, body) {
    if (error) {
      return false;
    } else {
      return body;
    }
  });
}
console.log('Server running at localhost:'+serverPort);
</code>```

In this example I used the request package (use npm install request to install).

Here is the error message:

```<code>_http_outgoing.js:655
    throw new TypeError('First argument must be a string or Buffer');
    ^

TypeError: First argument must be a string or Buffer
    at write_ (_http_outgoing.js:655:11)
    at ServerResponse.write (_http_outgoing.js:630:10)
    at IncomingMessage.<anonymous> (/Users/aero/Documents/Design/0522-aerofotea api/www/index.js:28:20)
    at emitNone (events.js:105:13)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1045:12)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
</code>```

答:
I think the problem is response.write(getrequest());

getrequest is an async action, you should use callback or promisify it. If you use callback, the getrequest function should be like this:

```<code>function getrequest(callback){
    curl('https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key={{insert_ur_api_key}}&user_id={{insert_ur_user_id}}&format=json', (error, response, body)=> {
      if (error) {
          callback(error);
          return;
      }
      callback(null, body);
    });
}
</code>```

And then use it like this:

```<code>request.on('end', function() {
    getrequest((err, body)=>{
       if (err) {
           response.writeHead(502, 'Bad Gateway', {'Content-Type': 'text/html'});
           response.end('502: Bad Gateway');
       } else {
           response.writeHead(200, {'Content-Type': 'text/html'});
           response.write(body);
           response.end();
       }
    })
})
</code>```

Title: How to make an API proxy with Node.js?

Body:
Since GFW blocks some ip including flickr's, I like to make a API proxy with Node.js, but I am having trouble to open a GET request within the http server. Here is my code:

var http = require('http');
var qs = require('querystring');
var curl = require('request');
var serverPort = 3000;
http.createServer(function (request, response) {
  if(request.method === "GET") {
    response.writeHead(401, {'Content-Type': 'text/html'});
    response.write('<!doctype html><title>401</title>401: Unauthorized');
    response.end();
  } else if(request.method === "POST") {
    if (request.url === "/") {
      var requestBody = '';
      request.on('data', function(data) {
        requestBody += data;
        if(requestBody.length > 1e7) {
          response.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
          response.end('413: Request Entity Too Large');
        }
      });
      request.on('end', function() {
        var body = getrequest();
        if (body === false) {
          response.writeHead(502, 'Bad Gateway', {'Content-Type': 'text/html'});
          response.end('502: Bad Gateway');
        } else {
          response.writeHead(200, {'Content-Type': 'text/html'});
          response.write(body);
          response.end();
        }
      });
    } else {
      response.writeHead(404, 'Resource Not Found', {'Content-Type': 'text/html'});
      response.end('<!doctype html><title>404</title>404: Resource Not Found');
    }
  } else {
    response.writeHead(405, 'Method Not Supported', {'Content-Type': 'text/html'});
    return response.end('<!doctype html><title>405</title>405: Method Not Supported');
  }
}).listen(serverPort);
function getrequest(){
  return curl('https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key={{insert_ur_api_key}}&user_id={{insert_ur_user_id}}&format=json', function (error, response, body) {
    if (error) {
      return false;
    } else {
      return body;
    }
  });
}
console.log('Server running at localhost:'+serverPort);

In this example I used the request package (use npm install request to install).

Here is the error message:

_http_outgoing.js:655
    throw new TypeError('First argument must be a string or Buffer');
    ^

TypeError: First argument must be a string or Buffer
    at write_ (_http_outgoing.js:655:11)
    at ServerResponse.write (_http_outgoing.js:630:10)
    at IncomingMessage.<anonymous> (/Users/aero/Documents/Design/0522-aerofotea api/www/index.js:28:20)
    at emitNone (events.js:105:13)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1045:12)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)

Body:
I think the problem is response.write(getrequest());

getrequest is an async action, you should use callback or promisify it. If you use callback, the getrequest function should be like this:

function getrequest(callback){
    curl('https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key={{insert_ur_api_key}}&user_id={{insert_ur_user_id}}&format=json', (error, response, body)=> {
      if (error) {
          callback(error);
          return;
      }
      callback(null, body);
    });
}

And then use it like this:

request.on('end', function() {
    getrequest((err, body)=>{
       if (err) {
           response.writeHead(502, 'Bad Gateway', {'Content-Type': 'text/html'});
           response.end('502: Bad Gateway');
       } else {
           response.writeHead(200, {'Content-Type': 'text/html'});
           response.write(body);
           response.end();
       }
    })
})


问:
How to send notification from iPhone to apple watch?
I want to send notification from iOS App to the apple watch app.

I will receive push notification on iPhone. When I receive the push notification I want to send a notification to my apple watch app along with some data like name,time, and just plain text. I am new to the apple watch. I have seen an example MMWormable, but that does not send notifications. It sends only data from iOS App when both the apps are running, but i want to send notification even if app is closed on both the iPhone & Apple watch.

EDIT:
I have read https://support.apple.com/en-in/HT204791 it says it will show notifications to apple watch when if iPhone is locked & it will not show notifications on apple watch if iPhone is not locked.

How can i show notifications to both the iPhone & apple watch.

答: If you want than you can add it on local notification an also on watch to fetch the data.</p>


问:
Excel - If cell value matches column header, copy data to column
I have string data in Column A, I have number values in Column B. I also have Columns O to Z which are currently blank - these columns have headers 1, 2, 3 etc. (i.e. cell references O2=1, P2=2, Q2=3 etc.)

There is a number value in cell C1.

If C1 = matches any of the column headers (O-Z) then copy the data from Column B to the corresponding column.

Example: If C1 = 4 and cell R2 is 4, the data from Column B would populate in Column R.

How do I achieve this with VBA? Thanks in advance.

答:
Try something like this...

```<code>Sub CopyDataDynamically()
Dim lr As Long, num As Long
Dim rng As Range
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set rng = Range("O2")
num = Range("C1").Value
If num > 0 And num <= 12 Then
    Range("B2:B" & lr).Copy
    rng.Offset(0, num - 1).PasteSpecial xlPasteValues
End If
End Sub
</code>```

If you want to achieve this with the help of a formula, try this...

In O2

```<code>=IF($B2="","",IF(O$1=$C$1,$B2,""))
</code>```

and then copy it across and down as far as there is data in column B.

Body:
Try something like this...

Sub CopyDataDynamically()
Dim lr As Long, num As Long
Dim rng As Range
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set rng = Range("O2")
num = Range("C1").Value
If num > 0 And num <= 12 Then
    Range("B2:B" & lr).Copy
    rng.Offset(0, num - 1).PasteSpecial xlPasteValues
End If
End Sub

If you want to achieve this with the help of a formula, try this...

In O2

=IF($B2="","",IF(O$1=$C$1,$B2,""))

and then copy it across and down as far as there is data in column B.


问:
Django: flatpages/default.html not found when usign flatepages
I completed Django's 7 part tutorial and am now reading both the official documentation about flat pages as well as this other site.

in

my_project/settings.py

I have added the sites and flatpages apps as well as the SITE_ID.

in

my_project/urls.py

I have added

```<code>urlpatterns += [url(r'^pages/', include('django.contrib.flatpages.urls')),]
</code>```

and because I also need to have flatpages/default.html as a template, in

my_project/templates/flatpages/

there is a file named default.html

to make sure it is found back in

my_projects/settings.py

I updated templates to look like:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

So I went onto the admin page and added a flatpage named "test" and then went to ...8000:/pages/test/

to get an error message TemplateDoesNotExist.

So where did I go wrong?

答: In order for your current DIRS in your TEMPLATES setting to work, make sure that your templates/flatpages/ directory is in your outer my_project directory (the one that contains manage.py), not the inner directory (the one that contains settings.py).

Body:
I completed Django's 7 part tutorial and am now reading both the official documentation about flat pages as well as this other site.

in

my_project/settings.py

I have added the sites and flatpages apps as well as the SITE_ID.

in

my_project/urls.py

I have added

urlpatterns += [url(r'^pages/', include('django.contrib.flatpages.urls')),]

and because I also need to have flatpages/default.html as a template, in

my_project/templates/flatpages/

there is a file named default.html

to make sure it is found back in

my_projects/settings.py

I updated templates to look like:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

So I went onto the admin page and added a flatpage named "test" and then went to ...8000:/pages/test/

to get an error message TemplateDoesNotExist.

So where did I go wrong?


问:
Excel VBA: Looping through a combo box's items from another user form
I want to loop through a combo box's items but not get their values. I just want to loop through how many items there are. Here is how I add items to it.

```<code>Private Sub UserForm_Initialize()

    Chapter.AddItem "Chapter 1"
    Chapter.AddItem "Chapter 2"
    Chapter.AddItem "Chapter 3"
    Chapter.AddItem "No　Chapter"

End Sub
</code>```

And this is what I tried on looping through it.

```<code>        Dim itm As Object

        For Each itm In UserForm.ComboBox1.Items.Count

        Next
</code>```

But error prompt; Compile error: Method or data member not found

Does it matter that these codes aren't on one user form? I have two user forms and the adding of items to the combo box is on the second and the looping through the combo box is on the first one. Does that matter?

答:
Try this (without declaration as object):</p>

```<code>For Each itm In ComboBox1.List
'for example display in messagebox
MsgBox itm

Next
</code>```

Body:
I want to loop through a combo box's items but not get their values. I just want to loop through how many items there are. Here is how I add items to it.

Private Sub UserForm_Initialize()

    Chapter.AddItem "Chapter 1"
    Chapter.AddItem "Chapter 2"
    Chapter.AddItem "Chapter 3"
    Chapter.AddItem "No　Chapter"

End Sub

And this is what I tried on looping through it.

        Dim itm As Object

        For Each itm In UserForm.ComboBox1.Items.Count

        Next

But error prompt; Compile error: Method or data member not found

Does it matter that these codes aren't on one user form? I have two user forms and the adding of items to the combo box is on the second and the looping through the combo box is on the first one. Does that matter?

Body:
Try this (without declaration as object):

For Each itm In ComboBox1.List
'for example display in messagebox
MsgBox itm

Next


问:
file_get_contents - getting real complete HTTP answer (not just headers)
I'm trying to get full HTTP answer over a call to file_get_contents function. I'm doing an HTTP POST call, putting credentials to login to my website, process some work, then return a HTTP answer to the caller.

When credentials are not good, i send a HTTP 403 return code, with a message as follow (Raw HTTP response as shown in SoapUI) :

```<code>HTTP/1.1 403 Forbidden
Server: Apache-Coyote/1.1
X-UA-Compatible: IE=edge
Pragma: no-cache
Cache-Control: no-cache
Expires: Mon, 05 Jun 2017 09:02:13 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 515
Date: Mon, 05 Jun 2017 09:02:13 GMT

L'authentification user/password n'est pas autorisée pour le login 'sebastien' depuis l'adresse '127.0.0.1'.
</code>```

How can i get the message at bottom after calling file_get_contents in php ? Message is not in the headers, so $http_response_header won't work. Is there a way to do so ?

答:
A HTTP response body should be separated from headers by an empty line: https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

Then the body should be available as a result of file_get_contents call.

Body:
I'm trying to get full HTTP answer over a call to file_get_contents function. I'm doing an HTTP POST call, putting credentials to login to my website, process some work, then return a HTTP answer to the caller.

When credentials are not good, i send a HTTP 403 return code, with a message as follow (Raw HTTP response as shown in SoapUI) :

HTTP/1.1 403 Forbidden
Server: Apache-Coyote/1.1
X-UA-Compatible: IE=edge
Pragma: no-cache
Cache-Control: no-cache
Expires: Mon, 05 Jun 2017 09:02:13 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 515
Date: Mon, 05 Jun 2017 09:02:13 GMT

L'authentification user/password n'est pas autorisée pour le login 'sebastien' depuis l'adresse '127.0.0.1'.

How can i get the message at bottom after calling file_get_contents in php ? Message is not in the headers, so $http_response_header won't work. Is there a way to do so ?


问:
Setting dynamic velocity properties for archetype maven projects
I am creating an archetype and want to create a project wide available property containing things like the current date and an all lower case variant of the artifact id. I found the following post on Stackoverflow, that shows how it normally should be possible.

I tried adding this to the archetype-metadata.xml like so:

```<code>    ...
    <requiredProperty key="artifactIdLower">
        <defaultValue>${artifactId.toLowerCase()}</defaultValue>
    </requiredProperty>
    <requiredProperty key="ldt">
        <defaultValue>${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null)}</defaultValue>
    </requiredProperty>
    <requiredProperty key="dtf">
        <defaultValue>${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")}</defaultValue>
    </requiredProperty>
    <requiredProperty key="date">
        <defaultValue>${ldt.format($dtf)}</defaultValue>
    </requiredProperty>
    ...
</code>```

The property artifactIdLower works like a charm, but the ldt, dtf and date don't seem to work, giving the error:

```<code>Null reference [template 'dtf', line 1, column 1] : ${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")} cannot be resolved.
</code>```

After that I tried to see where in the chain this null reference comes from. I was able to set pkgClass to $package.getClass() (or to $package.Class),

but after that I was unable to set $strClass to $package.getClass().forName("java.lang.String") or to $pkgClass.forName("java.lang.String") (funnily enough, both pkgClass and strClass should be a Class object).

This made me wonder if there is a restriction on using reflection inside the archetype-metadata.xml.

My question is: how can I set dynamically generated property values (like above) that can be used project wide?

I don't want to have to define these properties in every file that I create, because there might be more properties that I want to add later.

Edit:
I tried to instead create a generalproperties.vm file that contained the #set directives. This file would then be loaded by every file on the first line using #parse("generalproperties.vm"). While I did get the file to be parsed from within the pom.xml file, it didnt behave as I wanted.

The following input

```<code>test
$null
#set( $ldtClass = $package.getClass().forName("java.time.LocalDateTime") )
$ldtClass.Name
$ldtClass.getMethod("now")
#set( $ldtNowMethod = $ldtClass.getMethod("now") )
$ldtNowMethod.Name
#set( $clsLoader = $package.getClass().getClassLoader() )
$clsLoader
#set( $ldtClass2 = $clsLoader.loadClass("java.time.LocalDateTime") )
$ldtClass2.Name
$ldtClass2.getMethod("now")
#set( $ldtNowMethod2 = $ldtClass2.getMethod("now") )
$ldtNowMethod2.Name
#set( $ldt = $ldtNowMethod2.invoke($null) )
$ldt
#set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke($null, "yyyy/MM/dd HH:mm:ss") )
$dtf
</code>```

Generated the following output:

```<code>test
$null
java.time.LocalDateTime
$ldtClass.getMethod("now")
$ldtNowMethod.Name
$clsLoader
$ldtClass2.Name
$ldtClass2.getMethod("now")
$ldtNowMethod2.Name
$ldt
$dtf
</code>```

The first 3 outputs are as expected, but after that I don't get the results I want. If someone is able to solve either of the above issues (with the metadata file or the generalproperties file), it would be highly appreciated.

答:
The only restriction I could think of is if you are using the SecureUberspector instead of the standard Uberspector in your Velocity configuration properties. But you wouldn't be able to get the java.time.LocalDateTime class, so it's not the case, unless maybe if you are using an old Velocity version. With Velocity 1.7 I am able to get a reference to the now() method and to call it.

Also, are you sure that the direct Java version is working properly? For instance, I read in the Class.getClassLoader() javadoc that "some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader."

Body:
I am creating an archetype and want to create a project wide available property containing things like the current date and an all lower case variant of the artifact id. I found the following post on Stackoverflow, that shows how it normally should be possible.

I tried adding this to the archetype-metadata.xml like so:

    ...
    <requiredProperty key="artifactIdLower">
        <defaultValue>${artifactId.toLowerCase()}</defaultValue>
    </requiredProperty>
    <requiredProperty key="ldt">
        <defaultValue>${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null)}</defaultValue>
    </requiredProperty>
    <requiredProperty key="dtf">
        <defaultValue>${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")}</defaultValue>
    </requiredProperty>
    <requiredProperty key="date">
        <defaultValue>${ldt.format($dtf)}</defaultValue>
    </requiredProperty>
    ...

The property artifactIdLower works like a charm, but the ldt, dtf and date don't seem to work, giving the error:

Null reference [template 'dtf', line 1, column 1] : ${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")} cannot be resolved.

After that I tried to see where in the chain this null reference comes from. I was able to set pkgClass to $package.getClass() (or to $package.Class),

but after that I was unable to set $strClass to $package.getClass().forName("java.lang.String") or to $pkgClass.forName("java.lang.String") (funnily enough, both pkgClass and strClass should be a Class object).

This made me wonder if there is a restriction on using reflection inside the archetype-metadata.xml.

My question is: how can I set dynamically generated property values (like above) that can be used project wide?

I don't want to have to define these properties in every file that I create, because there might be more properties that I want to add later.

Edit:
I tried to instead create a generalproperties.vm file that contained the #set directives. This file would then be loaded by every file on the first line using #parse("generalproperties.vm"). While I did get the file to be parsed from within the pom.xml file, it didnt behave as I wanted.

The following input

test
$null
#set( $ldtClass = $package.getClass().forName("java.time.LocalDateTime") )
$ldtClass.Name
$ldtClass.getMethod("now")
#set( $ldtNowMethod = $ldtClass.getMethod("now") )
$ldtNowMethod.Name
#set( $clsLoader = $package.getClass().getClassLoader() )
$clsLoader
#set( $ldtClass2 = $clsLoader.loadClass("java.time.LocalDateTime") )
$ldtClass2.Name
$ldtClass2.getMethod("now")
#set( $ldtNowMethod2 = $ldtClass2.getMethod("now") )
$ldtNowMethod2.Name
#set( $ldt = $ldtNowMethod2.invoke($null) )
$ldt
#set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke($null, "yyyy/MM/dd HH:mm:ss") )
$dtf

Generated the following output:

test
$null
java.time.LocalDateTime
$ldtClass.getMethod("now")
$ldtNowMethod.Name
$clsLoader
$ldtClass2.Name
$ldtClass2.getMethod("now")
$ldtNowMethod2.Name
$ldt
$dtf

The first 3 outputs are as expected, but after that I don't get the results I want. If someone is able to solve either of the above issues (with the metadata file or the generalproperties file), it would be highly appreciated.


问:
url with % doesn't get to api
Hi trying to get a signUrl from S3, for some reason making the call with % isn't parse correctly by my code. I get a 404 not found.

This is the ajax request:

https://stage.musicmarkers.com/website/api/admin/get-signed-url/thumbnail/magazine%2F2BE.gif/image%2Fgif

My API:

```<code>app.get('/website/api/admin/get-signed-url/thumbnail/:key/:type', auth.getMember, directives.noCache, getThumbnailSingedUrl);
</code>```

My function:

```<code>function getThumbnailSingedUrl(req, res) {

    if (!isAdmin(req, res)) {
        return;
    }

    var key = req.params.key || '';
    var type = req.params.type || '';

    ThumbnailBucketFacade.getSignedUrl(
        'putObject',
        key,
        type,
        function onGotSignedUrl(error, result) {
            if (error) {
                RestResponse.serverError(res, error);
            } else {
                RestResponse.ok(res, result);
            }
        }
    );
}
</code>```

Making the call in a dev environment works.

Making the call without % environment works.

Same code exactly in a different project works.

Any ideas?

答:
So eventually it was a configuration issue at 'nginx', the 'nginx' router

was configured to add '/' at the end of the site name. That made all the

other slashes scrambled and ultimately to the call not to be recognise.

Thank's for those helping.

Title: url with % doesn't get to api

Body:
Hi trying to get a signUrl from S3, for some reason making the call with % isn't parse correctly by my code. I get a 404 not found.

This is the ajax request:

https://stage.musicmarkers.com/website/api/admin/get-signed-url/thumbnail/magazine%2F2BE.gif/image%2Fgif

My API:

app.get('/website/api/admin/get-signed-url/thumbnail/:key/:type', auth.getMember, directives.noCache, getThumbnailSingedUrl);

My function:

function getThumbnailSingedUrl(req, res) {

    if (!isAdmin(req, res)) {
        return;
    }

    var key = req.params.key || '';
    var type = req.params.type || '';

    ThumbnailBucketFacade.getSignedUrl(
        'putObject',
        key,
        type,
        function onGotSignedUrl(error, result) {
            if (error) {
                RestResponse.serverError(res, error);
            } else {
                RestResponse.ok(res, result);
            }
        }
    );
}

Making the call in a dev environment works.

Making the call without % environment works.

Same code exactly in a different project works.

Any ideas?


问:
Create multiple files based on user input in python
i am new to python and I've written a code which create configuration files for my application. I've created the code which works for 2 IP's but it may happen that user may input more IP's and for each increase in Ip the config file will be changed. There are authentication servers and they can be either 1 or 2 only.

I am passing input to python code by a file name "inputfile", below is how it look like:

```<code>EnterIp_list: ip_1 ip_2
authentication_server: as_1 as_2
</code>```

Below is how the final configuration files are created:

```<code>configfile1:                  configfile2:
App_ip: ip_1                  App_ip: ip_2
app_number: 1                 app_number: 2
authen_server: as_1           authen_server: as_2
</code>```

Below is how python3 code looks:

```<code>def createconfig(filename, app_ip, app_number, authen_server)
     with open(filename, 'w') as inf:
          inf.write("App_ip=" + app_ip + "\n")
          inf.write("app_numbber=" + app_number)
          inf.write("authen_server="+ authen_server)

with open("inputfile") as f:
     for line in f:
       if EnterIP_list in line:
          a= line.split("=")
          b = a[1].split()
       if authentiation_server in line:
          c= line.split("=")
          d=c[1].split()

createconfig(configfile1, b[0], 1, d[0])
createconfig(configfile2, b[1], 2, d[1])
</code>```

Users has freedom to input as many IP's as they wish for. Can someone please suggest what need to be done to make code more generic and robust so that it will work for any number of input ip's ??? also value for app_number increases with each new ip added.

There will always be two authentication server and they go in round robin e.g. the third app ip will be associated to "as_1" again.

答:
You just need to iterate over your ip list in b, be aware that your current code only works for the last line of your "inputfile". As long as there is only one line, thats ok.

```<code>with open("inputfile") as f:
     for line in f:
        a= line.split("=")
        b = a[1].split()

app_count = 1
for ip in b:
    createconfig("configfile%s" % app_count , ip, app_count)
    app_count += 1
</code>```

Edit: Solution updated regarding your code change.

```<code>with open("inputfile") as f:
     for line in f:
       if EnterIP_list in line:
          ips = line.split("=")[1].split()
       if authentiation_server in line:
          auth_servers = line.split("=")[1].split()

app_count = 1
for ip, auth_server in zip(ips, auth_servers):
    createconfig("configfile%s" % app_count , ip, app_count, auth_server)
    app_count += 1
</code>```

Body:
i am new to python and I've written a code which create configuration files for my application. I've created the code which works for 2 IP's but it may happen that user may input more IP's and for each increase in Ip the config file will be changed. There are authentication servers and they can be either 1 or 2 only.

I am passing input to python code by a file name "inputfile", below is how it look like:

EnterIp_list: ip_1 ip_2
authentication_server: as_1 as_2

Below is how the final configuration files are created:

configfile1:                  configfile2:
App_ip: ip_1                  App_ip: ip_2
app_number: 1                 app_number: 2
authen_server: as_1           authen_server: as_2

Below is how python3 code looks:

def createconfig(filename, app_ip, app_number, authen_server)
     with open(filename, 'w') as inf:
          inf.write("App_ip=" + app_ip + "\n")
          inf.write("app_numbber=" + app_number)
          inf.write("authen_server="+ authen_server)

with open("inputfile") as f:
     for line in f:
       if EnterIP_list in line:
          a= line.split("=")
          b = a[1].split()
       if authentiation_server in line:
          c= line.split("=")
          d=c[1].split()

createconfig(configfile1, b[0], 1, d[0])
createconfig(configfile2, b[1], 2, d[1])

Users has freedom to input as many IP's as they wish for. Can someone please suggest what need to be done to make code more generic and robust so that it will work for any number of input ip's ??? also value for app_number increases with each new ip added.

There will always be two authentication server and they go in round robin e.g. the third app ip will be associated to "as_1" again.

Body:
You just need to iterate over your ip list in b, be aware that your current code only works for the last line of your "inputfile". As long as there is only one line, thats ok.

with open("inputfile") as f:
     for line in f:
        a= line.split("=")
        b = a[1].split()

app_count = 1
for ip in b:
    createconfig("configfile%s" % app_count , ip, app_count)
    app_count += 1

Edit: Solution updated regarding your code change.

with open("inputfile") as f:
     for line in f:
       if EnterIP_list in line:
          ips = line.split("=")[1].split()
       if authentiation_server in line:
          auth_servers = line.split("=")[1].split()

app_count = 1
for ip, auth_server in zip(ips, auth_servers):
    createconfig("configfile%s" % app_count , ip, app_count, auth_server)
    app_count += 1


问:
Iphone vs ipad mobile phone site redirection
We have an issue, with our mobile banking site.

Users with iphone and other mobile phones are re-directed correctly to the mobile vesrion of our internet banking
The issue is with users that have Ipads they get redirect to the mobile banking site aswell instead of the the normal internet banking site.

How do we fix this problem?

答:
Whether or not someone is visiting your webpage on an iPad can be done like so

via JavaScript:

```<code>var userHasiPad = navigator.userAgent.match(/iPad/i) != null;
</code>```

PHP:

```<code>$userHasiPad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');
</code>```

Both of these are essentially checking the User Agent string for the existence of the string "iPad".

Body:
Whether or not someone is visiting your webpage on an iPad can be done like so

via JavaScript:

var userHasiPad = navigator.userAgent.match(/iPad/i) != null;

PHP:

$userHasiPad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');

Both of these are essentially checking the User Agent string for the existence of the string "iPad".


问:
How to install g++ in Cygwin?
I'm trying to compile a piece of MATLAB code containing a makefile. For the reason that I'm using Windows, I need to use Cygwin.

I have downloaded and installed Cygwin. When I tried to compile the code using make, there was an error that g++ is not found.

I searched for Cygwin package manager on the net and I installed apt-cyg but when I search for g++ using apt-cyg search g++, there is no result there!

I have updated package list (apt-cyg update) but finally I could not find c++ compiler for Cygwin!

How can I do it by apt-cyg package manager or any other way?

答:
Finally I could find the answer in this link.

If one uses the MinGW installation file again, one can add some other packages.

I installed all Devel packages for MinGW and followed this tutorial which helped me to solve the problem.

Title: How to install g++ in Cygwin?

ContentLicense: CC BY-SA 4.0


问:
Hbase Table from HBase query
Is there anyway we can create a Hbase table as an output of hbase query? Suppose I have a huge hbase table and then I query the hbase table using filter. I want to store the result back into Hbase table. Is it possible?</p>

答:
You can take snapshot of your running Hbase table and export it to the HDFS .
Write Mapreduce to get data as you want in a file and then Bulk Load to new Hbase table .
You can directly write data into Hbase table also .
In that way running MapReduce on Snapshot will not impact the actual Hbase table also .
This is how you can do all steps are mentioned below

Create snapshot

```<code>snapshot 'HbaseTable','HbaseTableSnapshot'
</code>```

Export Snapshot to local hdfs

```<code>hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot HbaseTableSnapshot-copy-to /tmp -mappers 16
</code>```

Driver Job Configuration to rum mapreduce on Hbase snapshot

```<code>    String snapshotName="HbaseTableSnapshot";
    Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
    String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                    scan, // Scan instance to control CF and attribute selection
                    DefaultMapper.class, // mapper class
                    NullWritable.class, // mapper output key
                    Text.class, // mapper output value
                    job,
                    true,
                    restoreDir);
</code>```

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.

Title: Hbase Table from HBase query

Body:
You can take snapshot of your running Hbase table and export it to the HDFS .
Write Mapreduce to get data as you want in a file and then Bulk Load to new Hbase table .
You can directly write data into Hbase table also .
In that way running MapReduce on Snapshot will not impact the actual Hbase table also .
This is how you can do all steps are mentioned below

Create snapshot

snapshot 'HbaseTable','HbaseTableSnapshot'

Export Snapshot to local hdfs

hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot HbaseTableSnapshot-copy-to /tmp -mappers 16

Driver Job Configuration to rum mapreduce on Hbase snapshot

    String snapshotName="HbaseTableSnapshot";
    Path restoreDir = new Path("hdfs://quickstart.cloudera:8020/tmp");
    String  hbaseRootDir =  "hdfs://quickstart.cloudera:8020/hbase";

TableMapReduceUtil.initTableSnapshotMapperJob(snapshotName, // Snapshot name
                    scan, // Scan instance to control CF and attribute selection
                    DefaultMapper.class, // mapper class
                    NullWritable.class, // mapper output key
                    Text.class, // mapper output value
                    job,
                    true,
                    restoreDir);

Also running mapreduce on Hbase snapshot will skip scan on Hbase table and also there will be no impact on region server.


问:
Put DropDownList's value to @Ajax.ActionLink
I have a Partial View, with DropDownList. And I have Main View, with menu, where I can call this Partial View. I am trying to make filtering in Partial View, with parameters from it. To do this, I need to put selected value of ddl to @Ajax.ActionLink. I am trying to do it with js, but the page just reloads without calling my Partial View.

ActionLink from Main View:

```<code>@Ajax.ActionLink(
"Parts",
"PartsPartial",
new
{
    categorie = "add"
},
new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "content"
}, new { @class = "button" }
)
</code>```

Form method get in Partial View to make filtering:

```<code><form method="get">
    <div>
        <label>Category: </label>
        @Html.DropDownList("categorie", Model.Categories as SelectList,
        htmlAttributes: new { @class="form-control"})

        <label>Brand: </label>
        @Html.DropDownList("brand", Model.Brands as SelectList,
        htmlAttributes: new { @class="form-control" })
        <input type="submit" name="add" value="Filter" />

    </div>
</form>
</code>```

And my controller:

```<code>public ActionResult PartsPartial(string categorie, int? brand)
    {
        string str = "add";
        List<bs_categories> categoriesList = _db.bs_categories.ToList();
        List<bs_brands> brandsList = _db.bs_brands.ToList();

        if (categorie == str)
        {
            IQueryable<bs_parts> prts = _db.bs_parts;

            PartsViewModel pViewModel = new PartsViewModel
            {
                Parts = prts.ToList(),
                Categories = new SelectList(categoriesList, "categories_id", "categories_name"),
                Brands = new SelectList(brandsList, "brands_id", "brands_name")
            };
            return PartialView(pViewModel);
        }

        decimal categoryId = Convert.ToDecimal(categorie);

        var parts = _db.bs_parts.Where(x => x.parts_category_id == categoryId).OrderBy(x => x.parts_id);

        PartsViewModel pvm = new PartsViewModel
        {
            Parts = parts.ToList(),
            Categories = new SelectList(categoriesList, "categories_id", "categories_name"),
            Brands = new SelectList(brandsList, "brands_id", "brands_name")
        };
        return PartialView(pvm);
    }
</code>```

And here is js to make replace:

```<code><script>
    $(function () {
        $('#add').click(function () {
            var type = $('#categorie').val();

            $.ajax({
                url: this.href,
                type: 'GET',
                data: { type: type },
                cache: false,
                success: function (result) {
                    $('#content').prepend(result);
                }
            });
            return false;
        });
    });
</script>
</code>```

May be I missed something?

答:
you need to change the type of input to button :

```<code><form method="get">
    <div>
        <label>Category: </label>
        @Html.DropDownList("categorie", Model.Categories as SelectList,
        htmlAttributes: new { @class="form-control"})

        <label>Brand: </label>
        @Html.DropDownList("brand", Model.Brands as SelectList,
        htmlAttributes: new { @class="form-control" })
        <input type="button" id="add" name="add" value="Filter" />

    </div>
</form>
</code>```

when you make the type submit your ajax code will never called

Body:
I have a Partial View, with DropDownList. And I have Main View, with menu, where I can call this Partial View. I am trying to make filtering in Partial View, with parameters from it. To do this, I need to put selected value of ddl to @Ajax.ActionLink. I am trying to do it with js, but the page just reloads without calling my Partial View.

ActionLink from Main View:

@Ajax.ActionLink(
"Parts",
"PartsPartial",
new
{
    categorie = "add"
},
new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "content"
}, new { @class = "button" }
)

Form method get in Partial View to make filtering:

<form method="get">

        Category:
        @Html.DropDownList("categorie", Model.Categories as SelectList,
        htmlAttributes: new { @class="form-control"})

        Brand:
        @Html.DropDownList("brand", Model.Brands as SelectList,
        htmlAttributes: new { @class="form-control" })
        <input type="submit" name="add" value="Filter" />

</form>

And my controller:

public ActionResult PartsPartial(string categorie, int? brand)
    {
        string str = "add";
        List<bs_categories> categoriesList = _db.bs_categories.ToList();
        List<bs_brands> brandsList = _db.bs_brands.ToList();

        if (categorie == str)
        {
            IQueryable<bs_parts> prts = _db.bs_parts;

            PartsViewModel pViewModel = new PartsViewModel
            {
                Parts = prts.ToList(),
                Categories = new SelectList(categoriesList, "categories_id", "categories_name"),
                Brands = new SelectList(brandsList, "brands_id", "brands_name")
            };
            return PartialView(pViewModel);
        }

        decimal categoryId = Convert.ToDecimal(categorie);

        var parts = _db.bs_parts.Where(x => x.parts_category_id == categoryId).OrderBy(x => x.parts_id);

        PartsViewModel pvm = new PartsViewModel
        {
            Parts = parts.ToList(),
            Categories = new SelectList(categoriesList, "categories_id", "categories_name"),
            Brands = new SelectList(brandsList, "brands_id", "brands_name")
        };
        return PartialView(pvm);
    }

And here is js to make replace:

May be I missed something?

Body:
you need to change the type of input to button :

<form method="get">
    <div>
        <label>Category: </label>
        @Html.DropDownList("categorie", Model.Categories as SelectList,
        htmlAttributes: new { @class="form-control"})

        <label>Brand: </label>
        @Html.DropDownList("brand", Model.Brands as SelectList,
        htmlAttributes: new { @class="form-control" })
        <input type="button" id="add" name="add" value="Filter" />

    </div>
</form>

when you make the type submit your ajax code will never called


问:
Java generic understanding Type
I am learning Java generic from: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html and I have some doubts on the code sample below:

```<code>public class Box<T> {

    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public <U extends Number> void inspect(U u) {
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}
</code>```

Why wasnt the inspect() method to be written as shown below instead it was ?

```<code> public <T extends Number> void inspect(T t) { }
</code>```

There are some other code samples which has the following syntax. What does the 1st pair  stands for?

```<code>public <K,V> SomeClass<K,V>
</code>```

What does static  stands for?

```<code>public static <T> int countGreaterThan(T[] anArray, T elem)
</code>```

答:
The method Box.inspect() expects a type that extends Number so it is not applicable when the argument is a String.

Box.inspect() is just an example of generic type applied to a method.

On other hand you have a class Box with generic type T, but you can also have a method that accepts another type U which is broader (upper bounded) than T.

The class itself does not say how to use inspect and why, it just give you the possibility to handle different types. Don't put great expectations by this sample.

Consider that it is a just a sample that explain how to use Generics (not great logic behind).

Regarding public class SomeClass<K,V> declaration, this a declaration with multiple generics types.

The class HashMap<K,V>() is a real sample of this case, K is the type for the key value and V is the type for the value.

Title: Java generic understanding Type

Body:
I am learning Java generic from: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html and I have some doubts on the code sample below:

public class Box<T> {

    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public  void inspect(U u) {
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}

Why wasnt the inspect() method to be written as shown below instead it was ?

 public <T extends Number> void inspect(T t) { }

There are some other code samples which has the following syntax. What does the 1st pair  stands for?

public <K,V> SomeClass<K,V>

What does static  stands for?

public static <T> int countGreaterThan(T[] anArray, T elem)


问:
Why is this C++ code execution so slow compared to java?
I recently wrote a computation-intensive algorithm in Java, and then translated it to C++. To my surprise the C++ executed considerably slower. I have now written a much shorter Java test program, and a corresponding C++ program - see below. My original code featured a lot of array access, as does the test code. The C++ takes 5.5 times longer to execute (see comment at end of each program).

Conclusions after 1st 21 comments below ...

Test code:

g++ -o ... Java 5.5 times faster

g++ -O3 -o ... Java 2.9 times faster

g++ -fprofile-generate -march=native -O3 -o ... (run, then g++ -fprofile-use etc) Java 1.07 times faster.

My original project (much more complex than test code):

Java 1.8 times faster

C++ 1.9 times faster

C++ 2 times faster

```<code>Software environment:
    Ubuntu 16.04 (64 bit).
    Netbeans 8.2 / jdk 8u121 (java code executed inside netbeans)
    g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
    Compilation: g++ -o cpp_test cpp_test.cpp
</code>```

Java code:

public class JavaTest {
    public static void main(String[] args) {
        final int ARRAY_LENGTH = 100;
        final int FINISH_TRIGGER = 100000000;
        int[] intArray = new int[ARRAY_LENGTH];
        for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
        int i = 0;
        boolean finished = false;
        long loopCount = 0;
        System.out.println("Start");
        long startTime = System.nanoTime();
        while (!finished) {
            loopCount++;
            intArray[i]++;
            if (intArray[i] >= FINISH_TRIGGER) finished = true;
            else if (i <(ARRAY_LENGTH - 1)) i++;
            else i = 0;
        }
        System.out.println("Finish: " + loopCount + " loops; " +
            ((System.nanoTime() - startTime)/1e9) + " secs");
        // 5 executions in range 5.98 - 6.17 secs (each 9999999801 loops)
    }
}
```

<p>C++ code:</p>

<pre class="lang-cpp prettyprint-override"><code>//cpp_test.cpp:
#include <iostream>
#include <sys/time.h>
int main() {
    const int ARRAY_LENGTH = 100;
    const int FINISH_TRIGGER = 100000000;
    int *intArray = new int[ARRAY_LENGTH];
    for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
    int i = 0;
    bool finished = false;
    long long loopCount = 0;
    std::cout << "Start\n";
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    long long startTime = (1000000000*ts.tv_sec) + ts.tv_nsec;
    while (!finished) {
        loopCount++;
        intArray[i]++;
        if (intArray[i] >= FINISH_TRIGGER) finished = true;
        else if (i < (ARRAY_LENGTH - 1)) i++;
        else i = 0;
    }
    clock_gettime(CLOCK_REALTIME, &ts);
    double elapsedTime =
        ((1000000000*ts.tv_sec) + ts.tv_nsec - startTime)/1e9;
    std::cout << "Finish: " << loopCount << " loops; ";
    std::cout << elapsedTime << " secs\n";
    // 5 executions in range 33.07 - 33.45 secs (each 9999999801 loops)
}
</code>```

答:
Somehow both GCC and clang fail to unroll this loop and pull out the invariants even in -O3 and -Os, but Java does.

Java's final JITted assembly code is similar to this (in reality repeated twice):

```<code>    while (true) {
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) break;
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) break;
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) break;
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) { if (i >= ARRAY_LENGTH) i = 0; break; }
        if (i >= ARRAY_LENGTH) i = 0;
    }
</code>```

With this loop I'm getting exact same timings (6.4s) between C++ and Java.

Why is this legal to do? Because ARRAY_LENGTH is 100, which is a multiple of 4. So i can only exceed 100 and be reset to 0 every 4 iterations.

This looks like an opportunity for improvement for GCC and clang; they fail to unroll loops for which the total number of iterations is unknown, but even if unrolling is forced, they fail to recognize parts of the loop that apply to only certain iterations.

Regarding your findings in a more complex code (a.k.a. real life): Java's optimizer is exceptionally good for small loops, a lot of thought has been put into that, but Java loses a lot of time on virtual calls and GC.

In the end it comes down to machine instructions running on a concrete architecture, whoever comes up with the best set, wins. Don't assume the compiler will "do the right thing", look and the generated code, profile, repeat.

For example, if you restructure your loop just a bit:

```<code>    while (!finished) {
        for (i=0; i<ARRAY_LENGTH; ++i) {
            loopCount++;
            if (++intArray[i] >= FINISH_TRIGGER) {
                finished=true;
                break;
            }
        }
    }
</code>```

Then C++ will outperform Java (5.9s vs 6.4s). (revised C++ assembly)

And if you can allow a slight overrun (increment more intArray elements after reaching the exit condition):

```<code>    while (!finished) {
        for (int i=0; i<ARRAY_LENGTH; ++i) {
            ++intArray[i];
        }
        loopCount+=ARRAY_LENGTH;
        for (int i=0; i<ARRAY_LENGTH; ++i) {
            if (intArray[i] >= FINISH_TRIGGER) {
                loopCount-=ARRAY_LENGTH-i-1;
                finished=true;
                break;
            }
        }
    }
</code>```

Now clang is able to vectorize the loop and reaches the speed of 3.5s vs. Java's 4.8s (GCC is unfortunately still not able to vectorize it).

Body:
I recently wrote a computation-intensive algorithm in Java, and then translated it to C++. To my surprise the C++ executed considerably slower. I have now written a much shorter Java test program, and a corresponding C++ program - see below. My original code featured a lot of array access, as does the test code. The C++ takes 5.5 times longer to execute (see comment at end of each program).

Conclusions after 1st 21 comments below ...

Test code:

g++ -o ... Java 5.5 times faster

g++ -O3 -o ... Java 2.9 times faster

g++ -fprofile-generate -march=native -O3 -o ... (run, then g++ -fprofile-use etc) Java 1.07 times faster.

My original project (much more complex than test code):

Java 1.8 times faster

C++ 1.9 times faster

C++ 2 times faster

Software environment:
    Ubuntu 16.04 (64 bit).
    Netbeans 8.2 / jdk 8u121 (java code executed inside netbeans)
    g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
    Compilation: g++ -o cpp_test cpp_test.cpp

Java code:

public class JavaTest {
    public static void main(String[] args) {
        final int ARRAY_LENGTH = 100;
        final int FINISH_TRIGGER = 100000000;
        int[] intArray = new int[ARRAY_LENGTH];
        for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
        int i = 0;
        boolean finished = false;
        long loopCount = 0;
        System.out.println("Start");
        long startTime = System.nanoTime();
        while (!finished) {
            loopCount++;
            intArray[i]++;
            if (intArray[i] >= FINISH_TRIGGER) finished = true;
            else if (i <(ARRAY_LENGTH - 1)) i++;
            else i = 0;
        }
        System.out.println("Finish: " + loopCount + " loops; " +
            ((System.nanoTime() - startTime)/1e9) + " secs");
        // 5 executions in range 5.98 - 6.17 secs (each 9999999801 loops)
    }
}

C++ code:

//cpp_test.cpp:
#include <iostream>
#include <sys/time.h>
int main() {
    const int ARRAY_LENGTH = 100;
    const int FINISH_TRIGGER = 100000000;
    int *intArray = new int[ARRAY_LENGTH];
    for (int i = 0; i < ARRAY_LENGTH; i++) intArray[i] = 1;
    int i = 0;
    bool finished = false;
    long long loopCount = 0;
    std::cout << "Start\n";
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    long long startTime = (1000000000*ts.tv_sec) + ts.tv_nsec;
    while (!finished) {
        loopCount++;
        intArray[i]++;
        if (intArray[i] >= FINISH_TRIGGER) finished = true;
        else if (i < (ARRAY_LENGTH - 1)) i++;
        else i = 0;
    }
    clock_gettime(CLOCK_REALTIME, &ts);
    double elapsedTime =
        ((1000000000*ts.tv_sec) + ts.tv_nsec - startTime)/1e9;
    std::cout << "Finish: " << loopCount << " loops; ";
    std::cout << elapsedTime << " secs\n";
    // 5 executions in range 33.07 - 33.45 secs (each 9999999801 loops)
}

Body:
Somehow both GCC and clang fail to unroll this loop and pull out the invariants even in -O3 and -Os, but Java does.

Java's final JITted assembly code is similar to this (in reality repeated twice):

    while (true) {
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) break;
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) break;
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) break;
        loopCount++;
        if (++intArray[i++] >= FINISH_TRIGGER) { if (i >= ARRAY_LENGTH) i = 0; break; }
        if (i >= ARRAY_LENGTH) i = 0;
    }

With this loop I'm getting exact same timings (6.4s) between C++ and Java.

Why is this legal to do? Because ARRAY_LENGTH is 100, which is a multiple of 4. So i can only exceed 100 and be reset to 0 every 4 iterations.

This looks like an opportunity for improvement for GCC and clang; they fail to unroll loops for which the total number of iterations is unknown, but even if unrolling is forced, they fail to recognize parts of the loop that apply to only certain iterations.

Regarding your findings in a more complex code (a.k.a. real life): Java's optimizer is exceptionally good for small loops, a lot of thought has been put into that, but Java loses a lot of time on virtual calls and GC.

In the end it comes down to machine instructions running on a concrete architecture, whoever comes up with the best set, wins. Don't assume the compiler will "do the right thing", look and the generated code, profile, repeat.

For example, if you restructure your loop just a bit:

    while (!finished) {
        for (i=0; i<ARRAY_LENGTH; ++i) {
            loopCount++;
            if (++intArray[i] >= FINISH_TRIGGER) {
                finished=true;
                break;
            }
        }
    }

Then C++ will outperform Java (5.9s vs 6.4s). (revised C++ assembly)

And if you can allow a slight overrun (increment more intArray elements after reaching the exit condition):

    while (!finished) {
        for (int i=0; i<ARRAY_LENGTH; ++i) {
            ++intArray[i];
        }
        loopCount+=ARRAY_LENGTH;
        for (int i=0; i<ARRAY_LENGTH; ++i) {
            if (intArray[i] >= FINISH_TRIGGER) {
                loopCount-=ARRAY_LENGTH-i-1;
                finished=true;
                break;
            }
        }
    }

Now clang is able to vectorize the loop and reaches the speed of 3.5s vs. Java's 4.8s (GCC is unfortunately still not able to vectorize it).


问:
Display a form in Qt
This should be very easy.

I'm using Qt Creator and I have made a Qt Gui Application (That had main.h, main.ui and main.cpp)

I just created a Qt Designer Form Class that also has a header file, ui, and a class.
I have made an action inside my main.cpp called ShowSecondForm:

```<code>void Main::ShowSecondForm()
{

}
</code>```

Everytime I execute ShowSecondForm(); I want the second form to be displayed.

What do I put inside so my form will open?

Also, is is possible to pass a string to the form while opening it? Like ShowSecondForm(const QString&)?

Some notes that may help you:

I would like to have 2 forms opened at the same time.

It will also be a class as it will compute different things.

答:
I suspect this tutorial might be helpful. Presumably you have a main.ui, a main.h and a main.cpp.

Run the uic program over your main.ui file, to generate your ui_main.h header (if you're not using qmake), but otherwise the basic setup is in that tutorial.

Title: Display a form in Qt

Body:
This should be very easy.

I'm using Qt Creator and I have made a Qt Gui Application (That had main.h, main.ui and main.cpp)

I just created a Qt Designer Form Class that also has a header file, ui, and a class.
I have made an action inside my main.cpp called ShowSecondForm:

void Main::ShowSecondForm()
{

}

Everytime I execute ShowSecondForm(); I want the second form to be displayed.

What do I put inside so my form will open?

Also, is is possible to pass a string to the form while opening it? Like ShowSecondForm(const QString&)?

Some notes that may help you:

I would like to have 2 forms opened at the same time.

It will also be a class as it will compute different things.


问:
Twilio Phone Number Masking Using C#/mvc
I'm developing a cab service app where I provide drivers to call on clients cellphone. Here for some privacy reason I want is to mask my clients actual cellphone with the masked number so the privacy regarding personal number will be fulfilled.

Is there any twilio rest API through which i can accomplish my job regarding masking of cellphone numbers?

答:
Twilio developer evangelist here.

If you are interested, we have just released a preview of an API that performs number masking and maintains sessions between two users that are proxying through a number to each other. It's a declarative API specifically for these private communications between two users of your system.

The API is called Twilio Proxy. You can read about what Twilio Proxy can do for your application in this blog post.

You can request access to Twilio Proxy with this form.


问:
Forward message to another dialog from custom prompt
I'm using this custom class to make custom prompt.

I modified tryParse method. I would like to forward message to the first Dialog if user does not choose any option.

Code :

```<code>   var promptOptions = new CancelablePromptOptions<string>(MyDictionary.ChooseOneOfTheFollowingOptions, cancelPrompt: "cancel", options: MyHelper.GetOptios(), promptStyler: PromptStyler);
            CancelablePromptChoice<string>.Choice(context, OptionSelected, promptOptions);
</code>```

I'm trying to override TryParse function in CancelablePromptOptions class :

```<code>   protected override bool TryParse(IMessageActivity message, out T result)
        {
            if (IsCancel(message.Text))
            {
                result = default(T);
                return true;
            }

            bool b =  base.TryParse(message, out result);
            if (!b)
                Conversation.SendAsync(message, () => new MyFirstDialog());
                return base.TryParse(message, out result);
        }
</code>```

Notice MyFirstDialog from code. I would like to recreate first dialog with the current message.

Goal : If user choose some Dialog where more options are stored and if the first "choose" is not valid, i would like to recreate MyFirstDialog.

Any idea ?

Edit :

MyFirstDialog is the first IDialog i'm calling from Messages controller.

```<code>await Conversation.SendAsync(activity, () => new MyFirstDialog());
</code>```

I'm calling current IDialog from MyFirstDialog :

context.Call(new CurrentDialog(), CurrentDialog.HandleOptions);

答:
Here is an example on how to go back to your initial dialog, starting for the lowest level.

CancelablePromptChoice code:

Here you let the basic implementation do the "TryParse", but if it's not matching you will handle it (by returning true and keeping the value), avoiding the retry

```<code>protected override bool TryParse(IMessageActivity message, out T result)
{
    if (IsCancel(message.Text))
    {
        result = default(T);
        return true;
    }

    var parsingTriedSucceeded = base.TryParse(message, out result);

    // here you know if you found one of the options or not, and if not you override
    if (!parsingTriedSucceeded)
    {
        result = (T)Convert.ChangeType(message.Text, typeof(T));
        return true;
    }
    else
    {
        return parsingTriedSucceeded;
    }
}
</code>```

CurrentDialog code:

In this code you will handle your default(T) reply in the OptionSelected (which is the method called when this dialog is resuming after your prompt). By doing a context.Done<string>(null); you will end this dialog and go back to MyFirstDialog

```<code>[Serializable]
public class CurrentDialog : IDialog<string>
{
    public async Task StartAsync(IDialogContext context)
    {
        var promptOptions = new CancelablePromptOptions<string>(MyDictionary.ChooseOneOfTheFollowingOptions, cancelPrompt: "cancel", options: MyHelper.GetOptions(), promptStyler: PromptStyler);
        CancelablePromptChoice<string>.Choice(context, OptionSelected, promptOptions);
    }

    private async Task OptionSelected(IDialogContext context, IAwaitable<string> result)
    {
        var chose = await result;
        string answer = chose.ToString();

        switch (answer)
        {
            case HelpEnumerator.Agenda:
                await EventHelper.GetEventAgenda(context);
                context.Done<string>(null);
                break;
            case HelpEnumerator.Register:
                context.Call(new RegistrationDialog(), RegistrationDialog.Resume);
                context.Done<string>(null);
                break;
            case HelpEnumerator.Speakers:
                await EventHelper.GetSpeakers(context);
                context.Done<string>(null);
                break;
            case HelpEnumerator.Tickets:
                await EventHelper.GetTickets(context);
                context.Done<string>(null);
                break;
            default:
                context.Done(answer);
                break;
        }
    }
}
</code>```

MyFirstDialog code:

So finally in your MyFirstDialog you have to handle this return from the CurrentDialog, using the resume method:

```<code>// Somewhere in your logic...
context.Call(new CurrentDialog(), ResumeAfterCurrentDialog);

// On your class:
private async Task ResumeAfterCurrentDialog(IDialogContext context, IAwaitable<string> result)
{
    // You are entering here after "context.Done(...)" in the CurrentDialog. To know the "result" value, take a look at what in the OptionSelected in CurrentDialog => it can be null for the options of the list, or the value in "answer" if it's not one of the options
    // So we only have to test if it's not null, and then send the message again to the bot by using the "context.Activity" value

    var resultText = await result;

    if (resultText != null)
    {
        // Send the message again. It's already the message stored in context.Activity ;)
        IMessageActivity msg = (IMessageActivity)context.Activity;
        await this.MessageReceivedAsync(context, new AwaitableFromItem<IMessageActivity>(msg));
    }
}
</code>```

Body:
I'm using this custom class to make custom prompt.

I modified tryParse method. I would like to forward message to the first Dialog if user does not choose any option.

Code :

   var promptOptions = new CancelablePromptOptions<string>(MyDictionary.ChooseOneOfTheFollowingOptions, cancelPrompt: "cancel", options: MyHelper.GetOptios(), promptStyler: PromptStyler);
            CancelablePromptChoice<string>.Choice(context, OptionSelected, promptOptions);

I'm trying to override TryParse function in CancelablePromptOptions class :

   protected override bool TryParse(IMessageActivity message, out T result)
        {
            if (IsCancel(message.Text))
            {
                result = default(T);
                return true;
            }

            bool b =  base.TryParse(message, out result);
            if (!b)
                Conversation.SendAsync(message, () => new MyFirstDialog());
                return base.TryParse(message, out result);
        }

Notice MyFirstDialog from code. I would like to recreate first dialog with the current message.

Goal : If user choose some Dialog where more options are stored and if the first "choose" is not valid, i would like to recreate MyFirstDialog.

Any idea ?

Edit :

MyFirstDialog is the first IDialog i'm calling from Messages controller.

await Conversation.SendAsync(activity, () => new MyFirstDialog());

I'm calling current IDialog from MyFirstDialog :

context.Call(new CurrentDialog(), CurrentDialog.HandleOptions);

Body:
Here is an example on how to go back to your initial dialog, starting for the lowest level.

CancelablePromptChoice code:

Here you let the basic implementation do the "TryParse", but if it's not matching you will handle it (by returning true and keeping the value), avoiding the retry

protected override bool TryParse(IMessageActivity message, out T result)
{
    if (IsCancel(message.Text))
    {
        result = default(T);
        return true;
    }

    var parsingTriedSucceeded = base.TryParse(message, out result);

    // here you know if you found one of the options or not, and if not you override
    if (!parsingTriedSucceeded)
    {
        result = (T)Convert.ChangeType(message.Text, typeof(T));
        return true;
    }
    else
    {
        return parsingTriedSucceeded;
    }
}

CurrentDialog code:

In this code you will handle your default(T) reply in the OptionSelected (which is the method called when this dialog is resuming after your prompt). By doing a context.Done<string>(null); you will end this dialog and go back to MyFirstDialog

[Serializable]
public class CurrentDialog : IDialog<string>
{
    public async Task StartAsync(IDialogContext context)
    {
        var promptOptions = new CancelablePromptOptions<string>(MyDictionary.ChooseOneOfTheFollowingOptions, cancelPrompt: "cancel", options: MyHelper.GetOptions(), promptStyler: PromptStyler);
        CancelablePromptChoice<string>.Choice(context, OptionSelected, promptOptions);
    }

    private async Task OptionSelected(IDialogContext context, IAwaitable<string> result)
    {
        var chose = await result;
        string answer = chose.ToString();

        switch (answer)
        {
            case HelpEnumerator.Agenda:
                await EventHelper.GetEventAgenda(context);
                context.Done<string>(null);
                break;
            case HelpEnumerator.Register:
                context.Call(new RegistrationDialog(), RegistrationDialog.Resume);
                context.Done<string>(null);
                break;
            case HelpEnumerator.Speakers:
                await EventHelper.GetSpeakers(context);
                context.Done<string>(null);
                break;
            case HelpEnumerator.Tickets:
                await EventHelper.GetTickets(context);
                context.Done<string>(null);
                break;
            default:
                context.Done(answer);
                break;
        }
    }
}

MyFirstDialog code:

So finally in your MyFirstDialog you have to handle this return from the CurrentDialog, using the resume method:

// Somewhere in your logic...
context.Call(new CurrentDialog(), ResumeAfterCurrentDialog);

// On your class:
private async Task ResumeAfterCurrentDialog(IDialogContext context, IAwaitable<string> result)
{
    // You are entering here after "context.Done(...)" in the CurrentDialog. To know the "result" value, take a look at what in the OptionSelected in CurrentDialog => it can be null for the options of the list, or the value in "answer" if it's not one of the options
    // So we only have to test if it's not null, and then send the message again to the bot by using the "context.Activity" value

    var resultText = await result;

    if (resultText != null)
    {
        // Send the message again. It's already the message stored in context.Activity ;)
        IMessageActivity msg = (IMessageActivity)context.Activity;
        await this.MessageReceivedAsync(context, new AwaitableFromItem<IMessageActivity>(msg));
    }
}


问:
dtd and mixed content
Does someone know way a mixet content element (in dtd) there is a need to add the "*" at the end?

For example:<!ELEMENT note (#PCDATA|to|from|header|message)*>

I'm reffering to the case where I don't want to repeat anything again... I just want to be able to choose between #PCDATA and other elements.

I know that if I drop the "*" in the end of the decleration I will get a bad DTD decleration...
But - I have no idea what is the reason of that...

Anyone know why?

答:
You're hitting this restriction because the mixed content model is only allowed to constrain which elements occur not their order or the number of them. This is, I'm afraid, required by the XML Specification itself.

Mixed content is hard I'm afraid. The model was designed with documents in mind - it makes sense when you think of inline text but not in many other cases. If you have a choice, best practice would suggest that you create an element to contain your PCDATA. If you can't then I'm afraid you are stuck with the limits of mixed content models (using another schema language doesn't help much either I'm afraid).

Title: dtd and mixed content


问:
Now that Redis Cluster comes with sharding, replication and automatic failover, do i still need to use Sentinel for failover handling?
Now that Redis Cluster comes with sharding, replication and automatic failover, do i still need to use Sentinel for failover handling ?</p>

答: No. Sentinel is for managing the availability and providing service discovery when using Redis in single instance mode (single-master/one-or-more-slaves). When using Redis in cluster mode, Sentinel isn't needed.</p>