问:
Keeping only certain properties in a JavaScript object
I have an object.  I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this object:

```<code>var myObj={
    p1:123,
    p2:321,
    p3:{p3_1:1231,p3_2:342},
    p4:'23423',
    //....
    p99:{p99_1:'sadf',p99_2:234},
    p100:3434
}
</code>```

and only want properties p1, p2, and p100, how can I obtain this object:

```<code>var myObj={
    p1:123,
    p2:321,
    p100:3434
}
</code>```

I understand how I could do this with brute force, but would like a more elegant solution.

答:
Lodash has a function called pick which does what you're describing. I know that including a library isn't ideal, but you can also cherry-pick functions when using bundles, etc.

```<code>var myObj={
    p1:123,
    p2:321,
    p3:{p3_1:1231,p3_2:342},
    p4:'23423',
    //....
    p99:{p99_1:'sadf',p99_2:234},
    p100:3434
}

var newObj = _.pick(myObj, 'p1', 'p2', 'p100')
</code>```

Body:
I have an object.  I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this object:

var myObj={
    p1:123,
    p2:321,
    p3:{p3_1:1231,p3_2:342},
    p4:'23423',
    //....
    p99:{p99_1:'sadf',p99_2:234},
    p100:3434
}

and only want properties p1, p2, and p100, how can I obtain this object:

var myObj={
    p1:123,
    p2:321,
    p100:3434
}

I understand how I could do this with brute force, but would like a more elegant solution.

Body:
Lodash has a function called pick which does what you're describing. I know that including a library isn't ideal, but you can also cherry-pick functions when using bundles, etc.

var myObj={
    p1:123,
    p2:321,
    p3:{p3_1:1231,p3_2:342},
    p4:'23423',
    //....
    p99:{p99_1:'sadf',p99_2:234},
    p100:3434
}

var newObj = _.pick(myObj, 'p1', 'p2', 'p100')


来源: stackexchange

问:
firebase cloud function API Error with Google Cloud Storage
With the introduction of Firebase Cloud Functions we are looking at moving some of our current node.js server side code to cloud functions.  One issue I am having is with downloading a file from a GCS bucket to a temp file on disk, and then emailing that as an attachment (using mailgun-js).

The piece of code causing me grief is:

```<code>return mkdirp(tempLocalDir).then(() => {
    const bucket = gcs.bucket(gcsBucket);
    const tempFilePath = tempLocalDir + gcsFile;
    return bucket.file(gcsFile).download({
        destination: tempFilePath
    }).then(() => {
        console.log('File downloaded locally to', tempFilePath);
        var messageSubject = "Test";
        var messageBody = "Test with attach";

        var mailgunData = {
            from: ,
            to: agentEmail,
            subject: messageSubject,
            html: messageBody,
            attachment: tempFilePath,
        };
        mailgunAgent.messages().send(mailgunData, function (error, body) {
            console.log(body);
        });

    });

});
</code>```

The error message I'm getting in the Functions Logs is:

```<code>ApiError: Forbidden
    at Object.parseHttpRespMessage (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:156:33)
    at Object.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:131:18)
    at Duplexify.<anonymous> (/user_code/node_modules/@google-cloud/storage/src/file.js:724:21)
    at emitOne (events.js:96:13)
    at Duplexify.emit (events.js:188:7)
    at emitOne (events.js:96:13)
    at DestroyableTransform.emit (events.js:188:7)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at Request.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1108:14)
</code>```

I'm been able to download the file to the /tmp/ folder on disk using request, and this will be the fallback option, but I'd really like to use the GCS tools if possible.  I "think" it's an auth error with GCS, but I'm not sure how to track that down. Do I need to have different auth parameters in the cloud functions .config() for GCS than for Firebase? If so, how do I enter them? Our GCS bucket and project pre-date the introduction of Firebase Storage, but we've successfully used it with the node functions running on our server.

Thanks in advance,
Zach

答:
SOLVED:  Finally solved the above. Issue was the @google-cloud/storage auth needed the GCS project ID as the ID, but the Firebase admin-sdk keyfile, NOT the GCS project keyfile.  Using the Firebase project ID as the ID in the auth for GCS with the Firebase keyfile failed as well.

¯_(ツ)_/¯

Might be a strange behaviour just in our project setup, but thought it relevant to update with what solved the problem for us.

The config that worked using the format provided by grll above is:

```<code>const gcs = require('@google-cloud/storage');
const storageClient = gcs({
    projectId: "this is the GCS project ID,
    keyFilename: 'this is the firebase admin-sdk keyFilename.json'
});
const bucket = storageClient.bucket(gcsBucket);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
With the introduction of Firebase Cloud Functions we are looking at moving some of our current node.js server side code to cloud functions.  One issue I am having is with downloading a file from a GCS bucket to a temp file on disk, and then emailing that as an attachment (using mailgun-js).

The piece of code causing me grief is:

return mkdirp(tempLocalDir).then(() => {
    const bucket = gcs.bucket(gcsBucket);
    const tempFilePath = tempLocalDir + gcsFile;
    return bucket.file(gcsFile).download({
        destination: tempFilePath
    }).then(() => {
        console.log('File downloaded locally to', tempFilePath);
        var messageSubject = "Test";
        var messageBody = "Test with attach";

        var mailgunData = {
            from: ,
            to: agentEmail,
            subject: messageSubject,
            html: messageBody,
            attachment: tempFilePath,
        };
        mailgunAgent.messages().send(mailgunData, function (error, body) {
            console.log(body);
        });

    });

});

The error message I'm getting in the Functions Logs is:

ApiError: Forbidden
    at Object.parseHttpRespMessage (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:156:33)
    at Object.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:131:18)
    at Duplexify.<anonymous> (/user_code/node_modules/@google-cloud/storage/src/file.js:724:21)
    at emitOne (events.js:96:13)
    at Duplexify.emit (events.js:188:7)
    at emitOne (events.js:96:13)
    at DestroyableTransform.emit (events.js:188:7)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at Request.<anonymous> (/user_code/node_modules/@google-cloud/storage/node_modules/request/request.js:1108:14)

I'm been able to download the file to the /tmp/ folder on disk using request, and this will be the fallback option, but I'd really like to use the GCS tools if possible.  I "think" it's an auth error with GCS, but I'm not sure how to track that down. Do I need to have different auth parameters in the cloud functions .config() for GCS than for Firebase? If so, how do I enter them? Our GCS bucket and project pre-date the introduction of Firebase Storage, but we've successfully used it with the node functions running on our server.

Thanks in advance,
Zach

Body:
SOLVED:  Finally solved the above. Issue was the @google-cloud/storage auth needed the GCS project ID as the ID, but the Firebase admin-sdk keyfile, NOT the GCS project keyfile.  Using the Firebase project ID as the ID in the auth for GCS with the Firebase keyfile failed as well.

¯_(ツ)_/¯

Might be a strange behaviour just in our project setup, but thought it relevant to update with what solved the problem for us.

The config that worked using the format provided by grll above is:

const gcs = require('@google-cloud/storage');
const storageClient = gcs({
    projectId: "this is the GCS project ID,
    keyFilename: 'this is the firebase admin-sdk keyFilename.json'
});
const bucket = storageClient.bucket(gcsBucket);


问:
Android problem in setting a bluetooth service name
I'm developing an application which serves as bluetooth server for a bluetooth external device (the communication is started by the external device). This external device request from the bluetooth service I'm deploying a concrete service name ("PWAccessP"), so I initiate the serversocket by the following instruction:

```<code>serversocket = Activa.myBluetoothAdapter.listenUsingRfcommWithServiceRecord("PWAccessP", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
</code>```

But when with a test application which search the bluetooth services offered by my phone, I get the following log:

```<code>search services on 38E7D82E98F8 HTC Desire
service Unknown found btspp://38E7D82E98F8:22;authenticate=false;encrypt=false;master=false
</code>```

With "Unknown" as service name, indicating that the name of the offered service is unknown. I've checked this service is the one I'm deploying.

The phone I'm working is a HTC Desire.

Does anybody know what can be the problem?

Thanks in advance.

答:
maybe the problem is related to android 2.1. I have no problem creating new service with 'PWAccessP' as service name.
maybe you should try with a android 2.2 device. </p>

<p>just to give u a heads up, PWAccessP device will store the RFCOMM channel number from the pervious connection, and will use this number to connect to the SPP server device. so if your Android SPP app is restarted and registers a new RFCOMM chanel number, connection will fail, and  PWAccess device will restart the inquiry process again.. this is a problem on the device. By right, it should perform SDP query first before making RFCOMM connection, but it doesnt. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm developing an application which serves as bluetooth server for a bluetooth external device (the communication is started by the external device). This external device request from the bluetooth service I'm deploying a concrete service name ("PWAccessP"), so I initiate the serversocket by the following instruction:

serversocket = Activa.myBluetoothAdapter.listenUsingRfcommWithServiceRecord("PWAccessP", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

But when with a test application which search the bluetooth services offered by my phone, I get the following log:

search services on 38E7D82E98F8 HTC Desire
service Unknown found btspp://38E7D82E98F8:22;authenticate=false;encrypt=false;master=false

With "Unknown" as service name, indicating that the name of the offered service is unknown. I've checked this service is the one I'm deploying.

The phone I'm working is a HTC Desire.

Does anybody know what can be the problem?

Thanks in advance.

Body:
maybe the problem is related to android 2.1. I have no problem creating new service with 'PWAccessP' as service name.
maybe you should try with a android 2.2 device.

just to give u a heads up, PWAccessP device will store the RFCOMM channel number from the pervious connection, and will use this number to connect to the SPP server device. so if your Android SPP app is restarted and registers a new RFCOMM chanel number, connection will fail, and  PWAccess device will restart the inquiry process again.. this is a problem on the device. By right, it should perform SDP query first before making RFCOMM connection, but it doesnt.


问:
Domain not resolving after transferring to AWS
I transferred my domain ( simplifybits.com) using Route 53 and it successfully transferred.

However my domain is not resolving anymore :(

This is what my setup looks looks like

There are two buckets in S3

simplifybits.com

www.simplifybits.com

Route 53 configuration

```<code>simplifybits.com -  A

s3-website.us-east-2.amazonaws.com.

simplifybits.com - NS

ns-1069.awsdns-05.org.

ns-31.awsdns-03.com.

ns-1556.awsdns-02.co.uk.

ns-535.awsdns-02.net.

simplifybits.com - SOA

ns-1069.awsdns-05.org. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400

www.simplifybits.com - A

d3v4utl52t4eyk.cloudfront.net.
</code>```

答:
I had this same problem.  Right now your domains still have Google as the name servers:

```<code>Tech Email: tech@simplifybits.com.whoisprivacyservice.org
Name Server: ns-cloud-d1.googledomains.com
Name Server: ns-cloud-d2.googledomains.com
Name Server: ns-cloud-d3.googledomains.com
Name Server: ns-cloud-d4.googledomains.com
</code>```

It isn't obvious but go to the "Hosted zones" tab and select your domain.  Then, copy the "NS" records.  Now go to the "Registered domains" and select your domain.  If you look you will likely see to the right that the "Name servers" still have Google.  Click on "Add or edit name servers" and enter your name servers from above.  The popup will keep adding lines for you.

It took me a while to get this right as, like you, I thought I had to only have the NS records correct but that isn't enough.

As @steve-harris points out you will still have to have S3 enabled to serve static content but you'll want to get DNS going first.

Body:
I transferred my domain ( simplifybits.com) using Route 53 and it successfully transferred.

However my domain is not resolving anymore :(

This is what my setup looks looks like

There are two buckets in S3

simplifybits.com

www.simplifybits.com

Route 53 configuration

simplifybits.com -  A

s3-website.us-east-2.amazonaws.com.

simplifybits.com - NS

ns-1069.awsdns-05.org.

ns-31.awsdns-03.com.

ns-1556.awsdns-02.co.uk.

ns-535.awsdns-02.net.

simplifybits.com - SOA

ns-1069.awsdns-05.org. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400

www.simplifybits.com - A

d3v4utl52t4eyk.cloudfront.net.

Body:
I had this same problem.  Right now your domains still have Google as the name servers:

Tech Email: tech@simplifybits.com.whoisprivacyservice.org
Name Server: ns-cloud-d1.googledomains.com
Name Server: ns-cloud-d2.googledomains.com
Name Server: ns-cloud-d3.googledomains.com
Name Server: ns-cloud-d4.googledomains.com

It isn't obvious but go to the "Hosted zones" tab and select your domain.  Then, copy the "NS" records.  Now go to the "Registered domains" and select your domain.  If you look you will likely see to the right that the "Name servers" still have Google.  Click on "Add or edit name servers" and enter your name servers from above.  The popup will keep adding lines for you.

It took me a while to get this right as, like you, I thought I had to only have the NS records correct but that isn't enough.

As @steve-harris points out you will still have to have S3 enabled to serve static content but you'll want to get DNS going first.


问:
HTTP GET within AWS Lambda only works once
I am trying to look up user profile information using the Amazon user profile API, but my GET request only works once. The first time, the profile information is returned no problem, but all subsequent calls to the lambda function cause the GET to return a 400 bad request. Here is my current code:

```<code>exports.handler = (event, context) => {
const alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
// console.log(event);
if (event.session.user.accessToken === undefined) {
    alexa.emit(':tellWithLinkAccountCard',
                  'To start using the app, please use the Alexa companion app to authenticate on Amazon');
} else {
    amazonProfileURL += event.session.user.accessToken;
    console.log(amazonProfileURL);
    http.get(amazonProfileURL, (res) => {
      const statusCode = res.statusCode;
      const contentType = res.headers['content-type'];

      let error;
      if (statusCode !== 200) {
        error = new Error(`Request Failed.\n` +
                          `Status Code: ${statusCode}`);
      } else if (!/^application\/json/.test(contentType)) {
        error = new Error(`Invalid content-type.\n` +
                          `Expected application/json but received ${contentType}`);
      }
      if (error) {
        console.log(error.message);
        // consume response data to free up memory
        res.resume();
        return;
      }

      res.setEncoding('utf8');
      let rawData = '';
      res.on('data', (chunk) => rawData += chunk);
      res.on('end', () => {
        try {
            let parsedData = JSON.parse(rawData);
            user_name = parsedData.name;
            user_email = parsedData.email;
            console.log(user_name);
            console.log(user_email);
            alexa.registerHandlers(handlers);
            alexa.execute();
        } catch (e) {
          console.log(e.message);
        }
      });
    }).on('error', (e) => {
      console.log(`Got error: ${e.message}`);
    });
</code>```

The first time calling the function, the code sucessfully runs the alexa.execute() function, but on all subsequent calls, the following is printed to the console:

```<code>START RequestId: 89a3a696-1442-11e7-9c15-6de8cce4b94d Version: $LATEST
2017-03-29T05:42:46.772Z    89a3a696-1442-11e7-9c15-6de8cce4b94d    https://api.amazon.com/user/profile?access_token=<long user access token>
2017-03-29T05:42:46.888Z    89a3a696-1442-11e7-9c15-6de8cce4b94d    Request Failed.
Status Code: 400
</code>```

I am fairly new to JavaScript and AWS Lambda, so any help is appreciated!

答: I solved the issue. It turns out it was an AWS Lambda problem (feature?) rather than an HTTP GET problem. My amazonProfileURL string was persisting between calls to the lambda function so it was only a valid URL for the first call. The solution was to change that line to requestURL = amazonProfileURL + event.session.user.accessToken so that amazonProfileURL doesn't get overwritten.

Body:
I am trying to look up user profile information using the Amazon user profile API, but my GET request only works once. The first time, the profile information is returned no problem, but all subsequent calls to the lambda function cause the GET to return a 400 bad request. Here is my current code:

exports.handler = (event, context) => {
const alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
// console.log(event);
if (event.session.user.accessToken === undefined) {
    alexa.emit(':tellWithLinkAccountCard',
                  'To start using the app, please use the Alexa companion app to authenticate on Amazon');
} else {
    amazonProfileURL += event.session.user.accessToken;
    console.log(amazonProfileURL);
    http.get(amazonProfileURL, (res) => {
      const statusCode = res.statusCode;
      const contentType = res.headers['content-type'];

      let error;
      if (statusCode !== 200) {
        error = new Error(`Request Failed.\n` +
                          `Status Code: ${statusCode}`);
      } else if (!/^application\/json/.test(contentType)) {
        error = new Error(`Invalid content-type.\n` +
                          `Expected application/json but received ${contentType}`);
      }
      if (error) {
        console.log(error.message);
        // consume response data to free up memory
        res.resume();
        return;
      }

      res.setEncoding('utf8');
      let rawData = '';
      res.on('data', (chunk) => rawData += chunk);
      res.on('end', () => {
        try {
            let parsedData = JSON.parse(rawData);
            user_name = parsedData.name;
            user_email = parsedData.email;
            console.log(user_name);
            console.log(user_email);
            alexa.registerHandlers(handlers);
            alexa.execute();
        } catch (e) {
          console.log(e.message);
        }
      });
    }).on('error', (e) => {
      console.log(`Got error: ${e.message}`);
    });

The first time calling the function, the code sucessfully runs the alexa.execute() function, but on all subsequent calls, the following is printed to the console:

START RequestId: 89a3a696-1442-11e7-9c15-6de8cce4b94d Version: $LATEST
2017-03-29T05:42:46.772Z    89a3a696-1442-11e7-9c15-6de8cce4b94d    https://api.amazon.com/user/profile?access_token=<long user access token>
2017-03-29T05:42:46.888Z    89a3a696-1442-11e7-9c15-6de8cce4b94d    Request Failed.
Status Code: 400

I am fairly new to JavaScript and AWS Lambda, so any help is appreciated!


问:
Azure Virtual Machine not accessible after RDP port changed
I've changed RDP port to 8080 in registry on my Azure Virtual Machine (Windows Server). Now it is not accessible from outside, I cant connect it.

Azure VM is managed by Resource Manager (not Classic VM).

UPDATE:

Turning secuiruty rules so allow all not helped.

答:
I've changed RDP port to 8080 in registry on my Azure Virtual Machine
  (Windows Server)

We can use CustomScriptextension to check if RDP listening on port 8080.

netstat -ant | findstr "8080"

If your port not listening on Port 8080, we may need to restart RDP service.

If RDP listening on port 8080, we can use CustomScriptextension to disable windows firewall.

netsh advfirewall set allprofiles state off

About Extension, we create a ps1 file with the command, and upload it via Azure portal.


问:
How do I find my CPU topology?
I am using Intel(R) Core(TM) i5 CPU M 560 @ 2.67GHz as I found out from cat /proc/cpuinfo. But I want to know exact hierarchy like how many sockets are there, and how many cores are there per socket and threads too, if supported. Any idea?

答: You can use likwid-topology -g to get cpu hierarchy. This is not available by default in linux, you can install in ubuntu with sudo apt-get install likwid

Title: How do I find my CPU topology?


问:
Modify a code snippet and print the result
I'm a web designer but i'm starting to learn some coding.
Probably this question may seem very basic, but I've been pulling my hear out trying to figure out where to begin.
I want to build a small tool for myself that can replace several values in a chunk of code at once.

Let's say I have this:

```<code><!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<iframe src="about:blank" id="myiframe" style="display:none;"></iframe>
</body>
</html>
</code>```

I want to build a form where I can type the values I need to change, submit and then print the resulting code. In this example I'd need to replace about:blank and myiframe.

The printed result must be:

```<code><iframe src="myNewValue" id="anotherNewValue" style="display:none;"></iframe>
</code>```

What would be the best way to proceed?

答:
Hey I think this should do it. No PHP necessary just make a Javascript function like below; and if you want this to run when a button is clicked or something just say onclick="changey()"</p>

```<code>    <script>
function changey() {
        document.getElementById('myiframe').src = 'myNewValue';
        document.getElementById("myiframe").setAttribute("id", "div_top2");
}
    </script>
</code>```

Body:
I'm a web designer but i'm starting to learn some coding.
Probably this question may seem very basic, but I've been pulling my hear out trying to figure out where to begin.
I want to build a small tool for myself that can replace several values in a chunk of code at once.

Let's say I have this:

<!DOCTYPE html>

I want to build a form where I can type the values I need to change, submit and then print the resulting code. In this example I'd need to replace about:blank and myiframe.

The printed result must be:

What would be the best way to proceed?

Body:
Hey I think this should do it. No PHP necessary just make a Javascript function like below; and if you want this to run when a button is clicked or something just say onclick="changey()"

    <script>
function changey() {
        document.getElementById('myiframe').src = 'myNewValue';
        document.getElementById("myiframe").setAttribute("id", "div_top2");
}
    </script>


问:
Can't set focus() on a text field
This is just the weirdest thing. I've got a Sammy.js app, and I want to set focus on a text field right after the HTML loads. I've got this CoffeeScript here:

```<code>this.partial('templates/my-template.jqt').then ->
  i = $('#item')
  debugger
  i.focus()
</code>```

While I'm in the debugger, right on that line, I can inspect "i" and see that it's a JQuery object. I can even call i.val("HI THERE!") and see my text field update. But, calling i.focus() does absolutely nothing. Is there some security feature I'm missing that doesn't let you focus on a text element that was dynamically loaded?

答:
JQuery's focus() doesn't focus on an element, it binds an event handler to focus.
http://api.jquery.com/focus/

Try i.get().focus() instead.

Title: Can't set focus() on a text field

Body:
This is just the weirdest thing. I've got a Sammy.js app, and I want to set focus on a text field right after the HTML loads. I've got this CoffeeScript here:

this.partial('templates/my-template.jqt').then ->
  i = $('#item')
  debugger
  i.focus()

While I'm in the debugger, right on that line, I can inspect "i" and see that it's a JQuery object. I can even call i.val("HI THERE!") and see my text field update. But, calling i.focus() does absolutely nothing. Is there some security feature I'm missing that doesn't let you focus on a text element that was dynamically loaded?


问:
convert two dimensional array to object array without duplicates
I have a two dimensional array of colors:

```<code>var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]
</code>```

I want to turn this into an object array and I've successfully done so using a .map

```<code>obj = colors.map(function(x) {return
{
    "color1": x[0],
    "color2": x[1]
}});
</code>```

However I want the new object array to exclude duplicates and just be a list of the colors mentioned (instead of color1 and color2, combine into one). New array should have the format:

```<code>[{"color": Blue},
 {"color": Red},
 {"color": Green},
 {"color": Black},
 {"color": Orange}]
</code>```

How can I achieve this?

答:
In plain javascript.

```<code>var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]

var map = {};
var result = [];
colors.forEach(
    function (pair) {
      pair.forEach(
          function (color) {
            if (!map.hasOwnProperty(color)) {
              result.push(color);
            }
            map[color] = 1;
          })
    }
);

console.log(result);
</code>```

This is much easier to do in later versions of javascript. You could use a Set type to de-dupe for instance.

Even easier with a nice utility library. In lodash for instance:

```<code>_(colors).flatten().uniq().value();
</code>```

Body:
I have a two dimensional array of colors:

var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]

I want to turn this into an object array and I've successfully done so using a .map

obj = colors.map(function(x) {return
{
    "color1": x[0],
    "color2": x[1]
}});

However I want the new object array to exclude duplicates and just be a list of the colors mentioned (instead of color1 and color2, combine into one). New array should have the format:

[{"color": Blue},
 {"color": Red},
 {"color": Green},
 {"color": Black},
 {"color": Orange}]

How can I achieve this?

Body:
In plain javascript.

var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]

var map = {};
var result = [];
colors.forEach(
    function (pair) {
      pair.forEach(
          function (color) {
            if (!map.hasOwnProperty(color)) {
              result.push(color);
            }
            map[color] = 1;
          })
    }
);

console.log(result);

This is much easier to do in later versions of javascript. You could use a Set type to de-dupe for instance.

Even easier with a nice utility library. In lodash for instance:

_(colors).flatten().uniq().value();


问:
Jump directly to certain parts of a function
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

```<code>#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}
</code>```

答:
I think the idea is that from f3() you have the return addresses on the stack all the way up, and nothing has been printed so far.

You'd have to play with the stack contents so that f3() returns into f1(), which would then return into f2().

Can you take it from here? Depending on the compiler, there will be different ways to accomplish this. Inline assembly might or might not be required.

EDIT: specifically for GCC, see the GCC return address intrinsics.

Body:
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}


问:
What is the best way to hand action sheet action with UITableview Longpress on Ipad
I have a tableview that present an alert when long pressed. It work fine on the iphone but on ipad I get the popover error. The problem is that the table is not a button and i have no button on the cell what is the best way to work around this? Please take a look at my code.</p>

```<code> func ipadPresentationAlert(button:UIButton, alertController:UIAlertController){
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
            if let currentPopoverpresentioncontroller = alertController.popoverPresentationController{
                currentPopoverpresentioncontroller.sourceView = button
                currentPopoverpresentioncontroller.sourceRect = button.bounds;
                currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.up;
                self.present(alertController, animated: true, completion: nil)
            }
        }else{
            self.present(alertController, animated: true, completion: nil)
        }
    }
</code>```

答:
You can replace your button by yourCell.

button:UIButton -> cell: UITableViewCell

On iPad, ActionSheet need a sourceView to be showed, so you can place your cell here as a fulcrum.

```<code>currentPopoverpresentioncontroller.sourceView = cell
</code>```

Body:
I have a tableview that present an alert when long pressed. It work fine on the iphone but on ipad I get the popover error. The problem is that the table is not a button and i have no button on the cell what is the best way to work around this? Please take a look at my code.

 func ipadPresentationAlert(button:UIButton, alertController:UIAlertController){
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
            if let currentPopoverpresentioncontroller = alertController.popoverPresentationController{
                currentPopoverpresentioncontroller.sourceView = button
                currentPopoverpresentioncontroller.sourceRect = button.bounds;
                currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.up;
                self.present(alertController, animated: true, completion: nil)
            }
        }else{
            self.present(alertController, animated: true, completion: nil)
        }
    }

Body:
You can replace your button by yourCell.

button:UIButton -> cell: UITableViewCell

On iPad, ActionSheet need a sourceView to be showed, so you can place your cell here as a fulcrum.

currentPopoverpresentioncontroller.sourceView = cell


问:
In express when reading cookies, it returns an empty object as {}
I'm trying to set cookie using res.cookie or res.append('Set-Cookie',...) on express.js, but when I use req.cookies, it return {}(which is the default value of res.cookies). I've searched many web pages but it still can't return the right value. PS: Express is 4.15.2

in server.js:

```<code>var express = require('express');

var session = require('express-session');//设置session

var cookieParser = require('cookie-parser');//解析cookie

var bodyParser = require('body-parser');

var app = express();

app.use(express.static('public'));

app.use(session({

  secret: 'keyboard cat',

  cookie: { maxAge: 60000 },

  resave: false,

  saveUninitialized: true

}));

app.use(bodyParser.urlencoded({extended: true}));

app.use(bodyParser.json());

app.use(cookieParser());

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
// 查询所有博客数据
app.get('/getAll',function(req,res){
    var pageNum = req.query.pageNum;
    //连接数据库
    query("some sql",function(err,vals,fields) {
      console.dir(req.session.id);
      // Cookies that have not been signed
      console.log('Cookies: ', req.cookies)
      // Cookies that have been signed
      console.log('Signed Cookies: ', req.signedCookies)
      res.send(vals);
    });
});
//登陆验证
app.post('/login',function(req,res){
var username = req.body.username;
var password = req.body.password;
//过滤
var sql = "some sql";
query(sql,function(err,vals,fields) {
  if(vals.length == 1){
    //登录成功
    //res.cookie('mycookie', '1234567890', { domain:'localhost',secure:false, maxAage:120000, httpOnly: true });
    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
    //   req.cookie('sid',req.session.id,{ maxAge: 900000, httpOnly: false});
    res.send("ok");
  }else{
    //登陆失败
    res.send("false");
  }
});
});

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/"+ "index_prod.html" );
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
})
</code>```

When I login in, the result is as following:
cookie

but when I request for /getAll ,the console for cookies are: { }. (the default value, NOT the value we just write).

答:
If the cookies and session have been correctly used, the reasons may be :

Make sure the client and the server obey the Same-origin policy. If not, make some changes.

Make sure your websites have no errors. (In the code above, there exit other errors such as 404 (Not Found) in the process of images fetching)

Body:
I'm trying to set cookie using res.cookie or res.append('Set-Cookie',...) on express.js, but when I use req.cookies, it return {}(which is the default value of res.cookies). I've searched many web pages but it still can't return the right value. PS: Express is 4.15.2

in server.js:

var express = require('express');

var session = require('express-session');//设置session

var cookieParser = require('cookie-parser');//解析cookie

var bodyParser = require('body-parser');

var app = express();

app.use(express.static('public'));

app.use(session({

  secret: 'keyboard cat',

  cookie: { maxAge: 60000 },

  resave: false,

  saveUninitialized: true

}));

app.use(bodyParser.urlencoded({extended: true}));

app.use(bodyParser.json());

app.use(cookieParser());

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
// 查询所有博客数据
app.get('/getAll',function(req,res){
    var pageNum = req.query.pageNum;
    //连接数据库
    query("some sql",function(err,vals,fields) {
      console.dir(req.session.id);
      // Cookies that have not been signed
      console.log('Cookies: ', req.cookies)
      // Cookies that have been signed
      console.log('Signed Cookies: ', req.signedCookies)
      res.send(vals);
    });
});
//登陆验证
app.post('/login',function(req,res){
var username = req.body.username;
var password = req.body.password;
//过滤
var sql = "some sql";
query(sql,function(err,vals,fields) {
  if(vals.length == 1){
    //登录成功
    //res.cookie('mycookie', '1234567890', { domain:'localhost',secure:false, maxAage:120000, httpOnly: true });
    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
    //   req.cookie('sid',req.session.id,{ maxAge: 900000, httpOnly: false});
    res.send("ok");
  }else{
    //登陆失败
    res.send("false");
  }
});
});

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/"+ "index_prod.html" );
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
})

When I login in, the result is as following:
cookie

but when I request for /getAll ,the console for cookies are: { }. (the default value, NOT the value we just write).


问:
limit python input to int
How can i make the code limit the input of the user to integers. The code right now works perfect but i want it to instead of giving me an error when it inputs a String, it will just make an exception. </p>

```<code>def miles_to_km():
        miles=eval(input('Amount of miles: '))
        result= float(miles*1.609344)
        print(miles, 'Miles are equivalent to ', result, 'Kilometers')
        print('----------------------------------------------------------------')
def km_to_miles():
        km=eval(input('Amount of kilometers: '))
        result= float(km*0.62137119)
        print(km, 'Kilometers are equivalent to ', result, 'Miles')
        print('----------------------------------------------------------------')
def pounds_to_kg():
        pounds=eval(input('Amount of pounds: '))
        result=float(pounds/2.2046226218)
        print(pounds, 'Pounds are equivalent to ', result, 'Kilograms')
        print('----------------------------------------------------------------')
def kg_to_pounds():
        kg=eval(input('Amount of kilograms: '))
        result=float(kg*2.2046226218)
        print(kg, 'Kilograms are equivalent to ', result, 'Pounds')
        print('----------------------------------------------------------------')
def C_to_F():
    temp=eval(input('Temperature in Celsius: '))
    result= float((temp*1.8)+32)
    print(temp, '°C are equivalent to ', result, '°F')
    print('----------------------------------------------------------------')
def F_to_C():
    temp=eval(input('Temperature in Fahrenheit '))
    result= float((temp-32)/1.8)
    print(temp, '°F are equivalent to ', result, '°C')
    print('----------------------------------------------------------------')
def mph_to_kph():
        mph=eval(input('Amount of Miles per hour: '))
        result= float(mph*1.609344)
        print(mph, 'Miles/Hour are equivalent to ', result, 'Kilometers/Hour')
        print('----------------------------------------------------------------')
def kph_to_mph():
        kph=eval(input('Amount of Kiometers per hour: '))
        result= float(kph*0.62137119)
        print(kph, 'Kilometers/Hour are equivalent to ', result, 'Miles/Hour')
        print('----------------------------------------------------------------')
def exit_function():
    print('Thanks for using the conversion program.')
    print('----------------------------------------------------------------')
    import sys
    sys.exit()

def menu():
    print('----------------------------------------------------------------')
    print('Welcome to the unit conversion program. Please select an option.')
    print('1. Miles to Kilometers')
    print('2. Kilometers to miles')
    print('3. Pounds to Kilograms')
    print('4. Kilograms to Pounds')
    print('5. Celsius to Fahrenheit')
    print('6. Fahrenheit to Celsius')
    print('7. Miles/hour to Kilometers/hour')
    print('8. Kilometers/hour to Miles/Hour')
    print('9. Exit')

screen=True

while screen:
    menu()
    choice=eval(input('Enter option: '))
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')
</code>```

答:
```<code>while screen:
    menu()
while True:
       try:

    choice=eval(input('Enter option: '))
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')
</code>```

Title: limit python input to int

Body:
How can i make the code limit the input of the user to integers. The code right now works perfect but i want it to instead of giving me an error when it inputs a String, it will just make an exception.

def miles_to_km():
        miles=eval(input('Amount of miles: '))
        result= float(miles*1.609344)
        print(miles, 'Miles are equivalent to ', result, 'Kilometers')
        print('----------------------------------------------------------------')
def km_to_miles():
        km=eval(input('Amount of kilometers: '))
        result= float(km*0.62137119)
        print(km, 'Kilometers are equivalent to ', result, 'Miles')
        print('----------------------------------------------------------------')
def pounds_to_kg():
        pounds=eval(input('Amount of pounds: '))
        result=float(pounds/2.2046226218)
        print(pounds, 'Pounds are equivalent to ', result, 'Kilograms')
        print('----------------------------------------------------------------')
def kg_to_pounds():
        kg=eval(input('Amount of kilograms: '))
        result=float(kg*2.2046226218)
        print(kg, 'Kilograms are equivalent to ', result, 'Pounds')
        print('----------------------------------------------------------------')
def C_to_F():
    temp=eval(input('Temperature in Celsius: '))
    result= float((temp*1.8)+32)
    print(temp, '°C are equivalent to ', result, '°F')
    print('----------------------------------------------------------------')
def F_to_C():
    temp=eval(input('Temperature in Fahrenheit '))
    result= float((temp-32)/1.8)
    print(temp, '°F are equivalent to ', result, '°C')
    print('----------------------------------------------------------------')
def mph_to_kph():
        mph=eval(input('Amount of Miles per hour: '))
        result= float(mph*1.609344)
        print(mph, 'Miles/Hour are equivalent to ', result, 'Kilometers/Hour')
        print('----------------------------------------------------------------')
def kph_to_mph():
        kph=eval(input('Amount of Kiometers per hour: '))
        result= float(kph*0.62137119)
        print(kph, 'Kilometers/Hour are equivalent to ', result, 'Miles/Hour')
        print('----------------------------------------------------------------')
def exit_function():
    print('Thanks for using the conversion program.')
    print('----------------------------------------------------------------')
    import sys
    sys.exit()

def menu():
    print('----------------------------------------------------------------')
    print('Welcome to the unit conversion program. Please select an option.')
    print('1. Miles to Kilometers')
    print('2. Kilometers to miles')
    print('3. Pounds to Kilograms')
    print('4. Kilograms to Pounds')
    print('5. Celsius to Fahrenheit')
    print('6. Fahrenheit to Celsius')
    print('7. Miles/hour to Kilometers/hour')
    print('8. Kilometers/hour to Miles/Hour')
    print('9. Exit')

screen=True

while screen:
    menu()
    choice=eval(input('Enter option: '))
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')


问:
MSDN Licensing?
Simple question, but one I can't find an answer to on the MSDN subscriber site: As an MSDN Professional Subscriber, can I install the same copy of Windows 2008 in multiple VMs at the same time?

The MSDN keys state that they can be used for "multiple activations", but they don't state whether these are sequential or concurrent. I seem to recall that Windows 2008 Enterprise has its own "you can run multiple instances in VMs" terms. Did I remember that right, and does that apply to MSDN subscriptions?

答:
I believe that each key is allotted 10 activations without regard to concurrence or sequence of the installations.  If the 10 activations are used up, Microsoft can be contacted to request additional keys.

A while back (I haven't checked recently), msdn subscribers also had access to an "online concierge" chat room, of sorts.  While the microsoft personnel who worked in that chat room couldn't answer technical questions (clearly, considering the breadth of technical questions that would be asked), they could answer real questions about msdn subscriptions and the licenses and rules associated with the software.  I asked them if I could use my MSDN license key to install a copy of an OS to work @home, per the agreement, e.g.

OwnerDisplayName: Roger Lipscombe

Title: MSDN Licensing?

LastEditorDisplayName: moocha

OwnerDisplayName: Greg D


问:
Zipkin with elasticsearch storage (QueryParsingException)
I have a question regarding Zipkin with elasticsearch storage.

After updating spring-cloud-sleuth to 1.1.1.RELEASE(because we updated spring boot from 1.3.8 to 1.4.4 and spring cloud from Brixton.SR6 to Camden.SR4) we also updated zipkin-storage-elasticsearch and zipkin-autoconfigure-storage-elasticsearch to version 1.16.2 in the pom.xml of our zipkin service. We are using elasticsearch version 2.4.1.
When we boot up the service we get an
error on zipkin's ui and a stacktrace:

```<code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is Failed to execute phase [query], all shards failed; shardFailures {[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][0]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][1]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][2]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][3]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][4]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }] with root cause

org.elasticsearch.index.query.QueryParsingException: [nested] nested object under path [annotations] is not of nested type
at org.elasticsearch.index.query.support.NestedInnerQueryParseSupport.setPath(NestedInnerQueryParseSupport.java:162)
at org.elasticsearch.index.query.NestedQueryParser.parse(NestedQueryParser.java:82)
at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
at org.elasticsearch.index.query.BoolQueryParser.parse(BoolQueryParser.java:120)
at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
at org.elasticsearch.index.query.QueryParseContext.parseInnerFilter(QueryParseContext.java:263)
at org.elasticsearch.index.query.BoolQueryParser.parse(BoolQueryParser.java:91)
at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
at org.elasticsearch.index.query.IndexQueryParserService.innerParse(IndexQueryParserService.java:320)
at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:223)
at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:218)
at org.elasticsearch.search.query.QueryParseElement.parse(QueryParseElement.java:33)
at org.elasticsearch.search.SearchService.parseSource(SearchService.java:856)
at org.elasticsearch.search.SearchService.createContext(SearchService.java:667)
at org.elasticsearch.search.SearchService.createAndPutContext(SearchService.java:633)
at org.elasticsearch.search.SearchService.executeQueryPhase(SearchService.java:377)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:368)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:365)
at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33)
at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:77)
at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

Zipkin was working with spring-cloud-sleuth 1.0.0.RELEASE, zipkin-storage-elasticsearch, zipkin-autoconfigure-storage-elasticsearch 1.7.0 and elasticsearch 2.3.5. What am I missing here? Which versions should work together?

答:
In general it is better to use the zipkin's http variant of Elasticsearch as it cannot conflict with Spring Boot's elasticsearch library versions.

I would set everything in zipkin's group id to latest (currently 1.21.0 which is Spring Boot 1.4.x) and use zipkin-autoconfigure-storage-elasticsearch-http (plus.. the one you are using will be dropped)

Make sure your es hosts is specified in url syntax ex. http://host1:9200

Body:
I have a question regarding Zipkin with elasticsearch storage.

After updating spring-cloud-sleuth to 1.1.1.RELEASE(because we updated spring boot from 1.3.8 to 1.4.4 and spring cloud from Brixton.SR6 to Camden.SR4) we also updated zipkin-storage-elasticsearch and zipkin-autoconfigure-storage-elasticsearch to version 1.16.2 in the pom.xml of our zipkin service. We are using elasticsearch version 2.4.1.
When we boot up the service we get an
error on zipkin's ui and a stacktrace:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is Failed to execute phase [query], all shards failed; shardFailures {[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][0]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][1]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][2]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][3]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }{[cAMggVueTv67tHV7aykwlg][zipkin-2017-03-29][4]: RemoteTransportException[[Infamnia][172.18.0.20:9300][indices:data/read/search[phase/query]]]; nested: SearchParseException[failed to parse search source [{"size":0,"query":{"bool":{"must":{"match_all":{}},"filter":{"bool":{"should":[{"nested":{"query":{"term":{"annotations.endpoint.serviceName":"xxx"}},"path":"annotations"}},{"nested":{"query":{"term":{"binaryAnnotations.endpoint.serviceName":"xxx"}},"path":"binaryAnnotations"}}]}}}},"aggregations":{"name_agg":{"terms":{"field":"name","size":2147483647,"order":{"_term":"asc"}}}}}]]; nested: QueryParsingException[[nested] nested object under path [annotations] is not of nested type]; }] with root cause

org.elasticsearch.index.query.QueryParsingException: [nested] nested object under path [annotations] is not of nested type
at org.elasticsearch.index.query.support.NestedInnerQueryParseSupport.setPath(NestedInnerQueryParseSupport.java:162)
at org.elasticsearch.index.query.NestedQueryParser.parse(NestedQueryParser.java:82)
at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
at org.elasticsearch.index.query.BoolQueryParser.parse(BoolQueryParser.java:120)
at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
at org.elasticsearch.index.query.QueryParseContext.parseInnerFilter(QueryParseContext.java:263)
at org.elasticsearch.index.query.BoolQueryParser.parse(BoolQueryParser.java:91)
at org.elasticsearch.index.query.QueryParseContext.parseInnerQuery(QueryParseContext.java:250)
at org.elasticsearch.index.query.IndexQueryParserService.innerParse(IndexQueryParserService.java:320)
at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:223)
at org.elasticsearch.index.query.IndexQueryParserService.parse(IndexQueryParserService.java:218)
at org.elasticsearch.search.query.QueryParseElement.parse(QueryParseElement.java:33)
at org.elasticsearch.search.SearchService.parseSource(SearchService.java:856)
at org.elasticsearch.search.SearchService.createContext(SearchService.java:667)
at org.elasticsearch.search.SearchService.createAndPutContext(SearchService.java:633)
at org.elasticsearch.search.SearchService.executeQueryPhase(SearchService.java:377)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:368)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:365)
at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33)
at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:77)
at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Zipkin was working with spring-cloud-sleuth 1.0.0.RELEASE, zipkin-storage-elasticsearch, zipkin-autoconfigure-storage-elasticsearch 1.7.0 and elasticsearch 2.3.5. What am I missing here? Which versions should work together?


问:
Unit Testing No provider for ChangeDetectorRef
version: Angular 4.

I am injecting a parent component into child component to access parent method through child component.

In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.

Now code is working fine but child-component spec is throwing error for "ChangeDetectorRef" which is injected in parent component.

Error: No provider for ChangeDetectorRef!

Parent Component

```<code>import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {

  stageWidth: number;

  constructor(private ref: ChangeDetectorRef) {
    this.ref = ref;
  }

  //call this function as many times as number of child components within parent-component.
  parentMethod(childInterface: ChildInterface) {
    this.childInterfaces.push(childInterface);
  }

  ngAfterViewChecked() {
    this.elementWidth = this.updateElementWidthRuntime();
    this.ref.detectChanges();
  }
}
</code>```

Child Component

```<code>import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';

@Component({
  selector: 'child-component',
  templateUrl: './carousel-slide.component.html',
  styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {

  constructor(private parentComponent: ParentComponent) {
  }

  ngAfterViewInit() {
    this.parentComponent.parentMethod(this);
  }
}
</code>```

app.html

```<code><parent-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
    <child-component>
      <div class="box">Content of any height and width</div>
    </child-component>
</parent-component>
</code>```

Unit test for Child Component

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';

describe('ChildComponent', () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent],
      providers: [ParentComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create \'ChildComponent\'', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.

Failed: Encountered undefined provider! Usually this means you have a
  circular dependencies (might be caused by using 'barrel' index.ts
  files.)

After googling and trying many things I am unable to find solution. Any help appreciated.

答:
You are using a component as a provider, which is probably not your intention. Change your test module to declare both your parent and child components.</p>

```<code>TestBed.configureTestingModule({
  declarations: [ChildComponent, ParentComponent],
  providers: []
})
</code>```

Body:
version: Angular 4.

I am injecting a parent component into child component to access parent method through child component.

In parent-component I had to use ChangeDetectorRef because it has a property which will update runtime.

Now code is working fine but child-component spec is throwing error for "ChangeDetectorRef" which is injected in parent component.

Error: No provider for ChangeDetectorRef!

Parent Component

import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {

  stageWidth: number;

  constructor(private ref: ChangeDetectorRef) {
    this.ref = ref;
  }

  //call this function as many times as number of child components within parent-component.
  parentMethod(childInterface: ChildInterface) {
    this.childInterfaces.push(childInterface);
  }

  ngAfterViewChecked() {
    this.elementWidth = this.updateElementWidthRuntime();
    this.ref.detectChanges();
  }
}

Child Component

import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';

@Component({
  selector: 'child-component',
  templateUrl: './carousel-slide.component.html',
  styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {

  constructor(private parentComponent: ParentComponent) {
  }

  ngAfterViewInit() {
    this.parentComponent.parentMethod(this);
  }
}

app.html

<parent-component>
    <child-component>

Content of any height and width

    </child-component>
    <child-component>

Content of any height and width

    </child-component>
    <child-component>

Content of any height and width

    </child-component>
</parent-component>

Unit test for Child Component

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';

describe('ChildComponent', () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent],
      providers: [ParentComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create \'ChildComponent\'', () => {
    expect(component).toBeTruthy();
  });
});

When I am trying to add ChangeDetectorRef in providers in child spec, I am getting following error.

Failed: Encountered undefined provider! Usually this means you have a
  circular dependencies (might be caused by using 'barrel' index.ts
  files.)

After googling and trying many things I am unable to find solution. Any help appreciated.

Body:
You are using a component as a provider, which is probably not your intention. Change your test module to declare both your parent and child components.

TestBed.configureTestingModule({
  declarations: [ChildComponent, ParentComponent],
  providers: []
})


问:
DDD: where do persistence-entity update logic?
I have two domain entities:

```<code>class Foo {
   int Id {get;}
   string Name {get;}
}
class FooBar : Foo {
   RuleEnum Rule {get;}
   string NewName {get;}
   int OrderId {get;}
}
</code>```

And single persistence model for them:

```<code>class FooInDb {
   int Id {get;set;}
   int Rule {get;set;}
   string Name {get;set;}
   string NewName {get;set;}
   int? OrderId {get;set;}
}
</code>```

I have application service, converting api-binding models to domains models (from IEnumarable<Api.Foo> to IEnumarable<FooBar>). Validation of some business rules occures in FooBar ctor. What I need next: load all FooInDbs from db and update its fields, according to:

```<code>void Update(FooBar fooBar, FooInDb fooInDb)
{
   fooInDb.Rule = fooBar.Rule;

   if (fooBar.Rule == RuleEnum.New){
     fooInDb.NewName = fooBar.NewName;
     fooInDb.OrderId = null;
   }
   else {
     fooInDb.NewName = null;
     fooInDb.OrderId = fooBar.OrderId;
   }
}
</code>```

Should this decision be placed in some domain-service? (Personally I do not want domain-service project to reference persistence-models project.) If not, how fine will be to place it in repository and call from application-service?

答:
Your domain model seems quite CRUD-oriented and anemic, but that is another story.

The persistence layer shouldn't be making decisions about the model's state. If the state should change based on the Rule then the model is responsible to reflect that.

The only thing the persistency layer should know here is how to persist the various representations of the same kind of entity, by mapping the model state as is to the persistence model.

E.g. where persistenceFramework is assumed to be anything that handles the persistence of your persistence model. Also not that I'm not a C# programmer.

```<code>    public void Save(Foo foo) {
        FooInDb dbFoo = persistenceFramework.FindById(foo.Id);

        Map(dbFoo, foo as dynamic);

        persistenceFramework.Save(dbFoo);
    }

   private void Map(FooInDb dbFoo, Foo foo) {
       //Foo mapping logic
   }

   private void Map(FooInDb dbFoo, FooBar foo) {
       //FooBar mapping logic
   }
</code>```

Body:
I have two domain entities:

class Foo {
   int Id {get;}
   string Name {get;}
}
class FooBar : Foo {
   RuleEnum Rule {get;}
   string NewName {get;}
   int OrderId {get;}
}

And single persistence model for them:

class FooInDb {
   int Id {get;set;}
   int Rule {get;set;}
   string Name {get;set;}
   string NewName {get;set;}
   int? OrderId {get;set;}
}

I have application service, converting api-binding models to domains models (from IEnumarable<Api.Foo> to IEnumarable<FooBar>). Validation of some business rules occures in FooBar ctor. What I need next: load all FooInDbs from db and update its fields, according to:

void Update(FooBar fooBar, FooInDb fooInDb)
{
   fooInDb.Rule = fooBar.Rule;

   if (fooBar.Rule == RuleEnum.New){
     fooInDb.NewName = fooBar.NewName;
     fooInDb.OrderId = null;
   }
   else {
     fooInDb.NewName = null;
     fooInDb.OrderId = fooBar.OrderId;
   }
}

Should this decision be placed in some domain-service? (Personally I do not want domain-service project to reference persistence-models project.) If not, how fine will be to place it in repository and call from application-service?

Body:
Your domain model seems quite CRUD-oriented and anemic, but that is another story.

The persistence layer shouldn't be making decisions about the model's state. If the state should change based on the Rule then the model is responsible to reflect that.

The only thing the persistency layer should know here is how to persist the various representations of the same kind of entity, by mapping the model state as is to the persistence model.

E.g. where persistenceFramework is assumed to be anything that handles the persistence of your persistence model. Also not that I'm not a C# programmer.

    public void Save(Foo foo) {
        FooInDb dbFoo = persistenceFramework.FindById(foo.Id);

        Map(dbFoo, foo as dynamic);

        persistenceFramework.Save(dbFoo);
    }

   private void Map(FooInDb dbFoo, Foo foo) {
       //Foo mapping logic
   }

   private void Map(FooInDb dbFoo, FooBar foo) {
       //FooBar mapping logic
   }


问:
SQL UPDATE WITH CONCATENE FIELD
Hy Everyone,

I have the follwing table

```<code>mysql> select * from recipes;
+------+-------+
| id   | direct|
+------+-------+
|    1 | max   |
|    2 | linda |
|    3 | sam   |
|    4 | henry |
+------+-------+
</code>```

But a need to update all direct field and put {{  }} at the beginning and at the end of the field.

```<code>+------+-----------+
| id   | direct    |
+------+-----------+
|    1 | {{max}}   |
|    2 | {{linda}} |
|    3 | {{sam}}   |
|    4 | {{henry}} |
+------+-----------+
</code>```

How can I do that?

I tried UPDATE recipes SET direct = '{"step": [{ "description": "'+direct+'","image": ""}]}', but it does not work for me.

Please help me!!!

答:
Here is one method that should work in any database:</p>

```<code>UPDATE recipes
    SET direct = REPLACE('{{x}}', 'x', direct);
</code>```

Title: SQL UPDATE WITH CONCATENE FIELD

Body:
Hy Everyone,

I have the follwing table

mysql> select * from recipes;
+------+-------+
| id   | direct|
+------+-------+
|    1 | max   |
|    2 | linda |
|    3 | sam   |
|    4 | henry |
+------+-------+

But a need to update all direct field and put {{  }} at the beginning and at the end of the field.

+------+-----------+
| id   | direct    |
+------+-----------+
|    1 | {{max}}   |
|    2 | {{linda}} |
|    3 | {{sam}}   |
|    4 | {{henry}} |
+------+-----------+

How can I do that?

I tried UPDATE recipes SET direct = '{"step": [{ "description": "'+direct+'","image": ""}]}', but it does not work for me.

Please help me!!!

Body:
Here is one method that should work in any database:

UPDATE recipes
    SET direct = REPLACE('{{x}}', 'x', direct);


问:
Adapt translation method from django to my function
I am working on a django project. I have created a function that will display the current date in french or english.

We have to install

```<code>sudo locale-gen fr_FR.utf8
</code>```

and then

```<code>from datetime import datetime
import locale

def set_locale(locale_):
    locale.setlocale(category=locale.LC_ALL, locale=locale_)

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        set_locale('en_US.utf8')
        date_ = now_.strftime("%A %B %d %Y")
    else:
        set_locale('fr_FR.utf8')
        date_ = now_.strftime("%A %B %d %Y")
</code>```

I know it works well, but I would like to use the django translation method. There are good informations here : https://docs.djangoproject.com/fr/1.10/topics/i18n/translation/ and in particular here : https://www.technomancy.org/python/django-i18n-manually-turn-on-a-language/.

Could anyone be able to adapt the last website method to my function?

I tried something but that doesn't work :

```<code>from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    old_lang = 'en'
    if language == 'English':
        import ipdb; ipdb.set_trace()
        translation.activate('en')
        date_ = now_.strftime("%A, %B %d %Y")
    else :
        translation.activate('fr')
        date_ = now_.strftime("%A, %d %B %Y")
        translation.activate(old_lang)
    return date_
</code>```

In fact, my main purpose is to create a function which will display the current date of the form Mercredi, 29 mars 2017 when I select 'French' and the form 'Wednesday, March 29, 2017'. Could anyone have an idea how to do that with a django method?

Thanks!

P.S. Please let me know if the question is unclear.

答:
datetime.strftime() is a method from the Python standard library and doesn't know anything about your Django language. You can use the builtin date template filter which does respect the Django language.

```<code>from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')
</code>```

Seems to give the results you want:

```<code>>>> date_customerprofile('English')
u'Thursday, March 30, 2017'
>>> date_customerprofile('French')
u'jeudi, 30 mars 2017'
</code>```

Some notes:

If this is used in the context of one user who has one language, it would be better to set the language on the user's sessions rather than switch it around just within this function.

If you were really serious about localization you would put your custom date formats in format files but it may be overkill for your use case.

Body:
I am working on a django project. I have created a function that will display the current date in french or english.

We have to install

sudo locale-gen fr_FR.utf8

and then

from datetime import datetime
import locale

def set_locale(locale_):
    locale.setlocale(category=locale.LC_ALL, locale=locale_)

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        set_locale('en_US.utf8')
        date_ = now_.strftime("%A %B %d %Y")
    else:
        set_locale('fr_FR.utf8')
        date_ = now_.strftime("%A %B %d %Y")

I know it works well, but I would like to use the django translation method. There are good informations here : https://docs.djangoproject.com/fr/1.10/topics/i18n/translation/ and in particular here : https://www.technomancy.org/python/django-i18n-manually-turn-on-a-language/.

Could anyone be able to adapt the last website method to my function?

I tried something but that doesn't work :

from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    old_lang = 'en'
    if language == 'English':
        import ipdb; ipdb.set_trace()
        translation.activate('en')
        date_ = now_.strftime("%A, %B %d %Y")
    else :
        translation.activate('fr')
        date_ = now_.strftime("%A, %d %B %Y")
        translation.activate(old_lang)
    return date_

In fact, my main purpose is to create a function which will display the current date of the form Mercredi, 29 mars 2017 when I select 'French' and the form 'Wednesday, March 29, 2017'. Could anyone have an idea how to do that with a django method?

Thanks!

P.S. Please let me know if the question is unclear.

Body:
datetime.strftime() is a method from the Python standard library and doesn't know anything about your Django language. You can use the builtin date template filter which does respect the Django language.

from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')

Seems to give the results you want:

>>> date_customerprofile('English')
u'Thursday, March 30, 2017'
>>> date_customerprofile('French')
u'jeudi, 30 mars 2017'

Some notes:

If this is used in the context of one user who has one language, it would be better to set the language on the user's sessions rather than switch it around just within this function.

If you were really serious about localization you would put your custom date formats in format files but it may be overkill for your use case.


问:
Illegal attempt to establish a relationship in core data
I'm trying to build a relationship between two objects on a background thread and Core Data keeps firing off "llegal attempt to establish a relationship"

Here is some basic code of what is happening:

```<code>- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
 @synchronized(self) {
  return persistentStoreCoordinator;
 }
 return nil;
}
- (void)startBackgroundTask {
 [self performSelectorInBackground:@selector(backgroundTask:) withObject:managedObjectID];
}
- (void)backgroundTask:(NSManagedObjectID *)pManagedObjectID {
 NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init];
 [managedObjectContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
 NSManagedObject *object = [managedObjectContext objectWithID:pManagedObjectID];
 NSManagedObject *childObject = [NSEntityDescription insertNewObjectForEntityForName:@"ChildObject" inManagedObjectContext:managedObjectContext];
 [object setValue:childObject forKey:@"childObject"];
 [managedObjectContext save:nil];
}
</code>```

I'm correctly creating a "thread-safe" background thread managed object context and fetching the object via the object id so unsure why it's not working.

Also compare the [object managedObjectContext] contexts results in a "true" equal condition.

Any help greatly appreciated,

-Robert

答:
This was rather stupid.

In my code versus this example I put up I was creating a Transient Object and not inserting it into the background managed object context.

Body:
I'm trying to build a relationship between two objects on a background thread and Core Data keeps firing off "llegal attempt to establish a relationship"

Here is some basic code of what is happening:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
 @synchronized(self) {
  return persistentStoreCoordinator;
 }
 return nil;
}
- (void)startBackgroundTask {
 [self performSelectorInBackground:@selector(backgroundTask:) withObject:managedObjectID];
}
- (void)backgroundTask:(NSManagedObjectID *)pManagedObjectID {
 NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init];
 [managedObjectContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
 NSManagedObject *object = [managedObjectContext objectWithID:pManagedObjectID];
 NSManagedObject *childObject = [NSEntityDescription insertNewObjectForEntityForName:@"ChildObject" inManagedObjectContext:managedObjectContext];
 [object setValue:childObject forKey:@"childObject"];
 [managedObjectContext save:nil];
}

I'm correctly creating a "thread-safe" background thread managed object context and fetching the object via the object id so unsure why it's not working.

Also compare the [object managedObjectContext] contexts results in a "true" equal condition.

Any help greatly appreciated,

-Robert


问:
Creating a custom Table Model to provide data from ArrayList
I'm trying create a JTable that creates the table based on information from an ArrayList.  The ArrayList is filled with information that the user enters in the GUI.  Every time the user presses a JButton it should add a new row of data to the table.

After googling it seems that the best way to do this is to create a custom table model.  I cannot find a decent tutorial on how to do this.  I've looked at the official documentation, and a few random sites and other postings.  Hopefully one of you can point me in the right direction.

Here's a picture of my current GUI.  The JTable should populate the center region:

And here is some of my code:

```<code> class dataModel extends AbstractTableModel
{
    private String[] columnName = {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"};

    public int getColumnCount()
    {
        return 4;
    }

    public int getRowCount()
    {
        return empData.size();
    }

    public Object getValueAt(int row, int col)
    {
        return new Integer(row*col);
    }
}
</code>```

The class that occurs on button click.

```<code>class listener implements ActionListener
{
    @SuppressWarnings("unchecked")
    public void actionPerformed(ActionEvent e)
    {
        ArrayList empData = new ArrayList();

        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;
        try
        {
            empNum = Integer.parseInt(empNumField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Employee ID.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hourlyRate = Double.parseDouble(basePayField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hourly Pay Rate.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hoursWorked = Double.parseDouble(hrsField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hours Worked.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }

        double payAMT = calculatePay(hourlyRate, hoursWorked);

        empData.add(empNum);
        empData.add(hourlyRate);
        empData.add(hoursWorked);
        empData.add(payAMT);

    }
</code>```

答:
You could...

Use a DefaultTableModel, which should cover your basic needs

```<code>private DefaultTableModel model;
//...
model = new DefaultTableModel(new String[] {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"}, 0);
table.setModel(model);
</code>```

Then you could just add new data directly to it

```<code>class listener implements ActionListener {

    private DefaultTableModel model;

    listener(DefaultTableModel model) {
        this.model = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;
        double payAMT = calculatePay(hourlyRate, hoursWorked);

        model.addRow(new Object[]{empNum, hourlyRate, hoursWorked, payAMT});
    }
}
</code>```

This is okay, it's simple, but it does mean you need to understand the structure of the data you are presenting and doesn't allow you to manage objects which might have more you might want to use later

Now, if you want something that's more customisable...

You could...

Use a custom TableModel, first, let's start with a requirement

```<code>public interface Employee {
    public int getNumber();
    public double getHourlyRate();
    public double getHoursWorked();
    public double getPay();
}
</code>```

This defines the basic expectations of the data our model can manage.  Why? Because you might have different types of employees or employee implementations which have more information, which is irrelevant to this table model

Next, we implement the TableModel...

```<code>public class DefaultWorkSheetTableModel extends AbstractTableModel {

    private List<Employee> items;

    public DefaultWorkSheetTableModel() {
        items = new ArrayList<>(25);
    }

    public DefaultWorkSheetTableModel(List<Employee> items) {
        this.items = items;
    }

    @Override
    public int getRowCount() {
        return items.size();
    }

    @Override
    public int getColumnCount() {
        return 4;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0: return Integer.class;
            case 1:
            case 2:
            case 3: return Double.class;
        }
        return Object.class;
    }

    @Override
    public String getColumnName(int column) {
        switch (column) {
            case 0: return "Emp Num";
            case 1: return "Base Pay";
            case 2: return "Hours Worked";
            case 3: return "Pay Amount";
        }
        return null;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Employee item = items.get(rowIndex);
        switch (columnIndex) {
            case 0: return item.getNumber();
            case 1: return item.getHourlyRate();
            case 2: return item.getHoursWorked();
            case 3: return item.getPay();
        }
        return null;
    }

    public void add(Employee item) {
        items.add(item);
        int row = items.indexOf(item);
        fireTableRowsInserted(row, row);
    }

    public void remove(Employee item) {
        if (items.contains(item)) {
            int row = items.indexOf(item);
            items.remove(row);
            fireTableRowsDeleted(row, row);
        }
    }

}
</code>```

There's a lot going on here, but this covers all the basic requirements for allow the JTable to present the data we want.

Now when you want to add data, you create a new instance of Employee and simply add it to the model...

```<code>class listener implements ActionListener {

    private DefaultWorkSheetTableModel model;

    listener(DefaultWorkSheetTableModel model) {
        this.model = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;
        //...
        DefaultEmployee employee = new DefaultEmployee(empNum, hourlyRate, hoursWorked);
        model.add(employee);
    }
}
</code>```

Yes, I know I didn't pass payRate, that's because it's a calculated field specific to the implementation of Employee ;)

Body:
I'm trying create a JTable that creates the table based on information from an ArrayList.  The ArrayList is filled with information that the user enters in the GUI.  Every time the user presses a JButton it should add a new row of data to the table.

After googling it seems that the best way to do this is to create a custom table model.  I cannot find a decent tutorial on how to do this.  I've looked at the official documentation, and a few random sites and other postings.  Hopefully one of you can point me in the right direction.

Here's a picture of my current GUI.  The JTable should populate the center region:

And here is some of my code:

 class dataModel extends AbstractTableModel
{
    private String[] columnName = {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"};

    public int getColumnCount()
    {
        return 4;
    }

    public int getRowCount()
    {
        return empData.size();
    }

    public Object getValueAt(int row, int col)
    {
        return new Integer(row*col);
    }
}

The class that occurs on button click.

class listener implements ActionListener
{
    @SuppressWarnings("unchecked")
    public void actionPerformed(ActionEvent e)
    {
        ArrayList empData = new ArrayList();

        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;
        try
        {
            empNum = Integer.parseInt(empNumField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Employee ID.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hourlyRate = Double.parseDouble(basePayField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hourly Pay Rate.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try
        {
            hoursWorked = Double.parseDouble(hrsField.getText());
        }
        catch(NumberFormatException event)
        {
            JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hours Worked.", "Error", JOptionPane.WARNING_MESSAGE);
            return;
        }

        double payAMT = calculatePay(hourlyRate, hoursWorked);

        empData.add(empNum);
        empData.add(hourlyRate);
        empData.add(hoursWorked);
        empData.add(payAMT);

    }

Body:
You could...

Use a DefaultTableModel, which should cover your basic needs

private DefaultTableModel model;
//...
model = new DefaultTableModel(new String[] {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"}, 0);
table.setModel(model);

Then you could just add new data directly to it

class listener implements ActionListener {

    private DefaultTableModel model;

    listener(DefaultTableModel model) {
        this.model = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;
        double payAMT = calculatePay(hourlyRate, hoursWorked);

        model.addRow(new Object[]{empNum, hourlyRate, hoursWorked, payAMT});
    }
}

This is okay, it's simple, but it does mean you need to understand the structure of the data you are presenting and doesn't allow you to manage objects which might have more you might want to use later

Now, if you want something that's more customisable...

You could...

Use a custom TableModel, first, let's start with a requirement

public interface Employee {
    public int getNumber();
    public double getHourlyRate();
    public double getHoursWorked();
    public double getPay();
}

This defines the basic expectations of the data our model can manage.  Why? Because you might have different types of employees or employee implementations which have more information, which is irrelevant to this table model

Next, we implement the TableModel...

public class DefaultWorkSheetTableModel extends AbstractTableModel {

    private List<Employee> items;

    public DefaultWorkSheetTableModel() {
        items = new ArrayList<>(25);
    }

    public DefaultWorkSheetTableModel(List<Employee> items) {
        this.items = items;
    }

    @Override
    public int getRowCount() {
        return items.size();
    }

    @Override
    public int getColumnCount() {
        return 4;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0: return Integer.class;
            case 1:
            case 2:
            case 3: return Double.class;
        }
        return Object.class;
    }

    @Override
    public String getColumnName(int column) {
        switch (column) {
            case 0: return "Emp Num";
            case 1: return "Base Pay";
            case 2: return "Hours Worked";
            case 3: return "Pay Amount";
        }
        return null;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Employee item = items.get(rowIndex);
        switch (columnIndex) {
            case 0: return item.getNumber();
            case 1: return item.getHourlyRate();
            case 2: return item.getHoursWorked();
            case 3: return item.getPay();
        }
        return null;
    }

    public void add(Employee item) {
        items.add(item);
        int row = items.indexOf(item);
        fireTableRowsInserted(row, row);
    }

    public void remove(Employee item) {
        if (items.contains(item)) {
            int row = items.indexOf(item);
            items.remove(row);
            fireTableRowsDeleted(row, row);
        }
    }

}

There's a lot going on here, but this covers all the basic requirements for allow the JTable to present the data we want.

Now when you want to add data, you create a new instance of Employee and simply add it to the model...

class listener implements ActionListener {

    private DefaultWorkSheetTableModel model;

    listener(DefaultWorkSheetTableModel model) {
        this.model = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int empNum = 0;
        double hourlyRate = 0;
        double hoursWorked = 0;
        //...
        DefaultEmployee employee = new DefaultEmployee(empNum, hourlyRate, hoursWorked);
        model.add(employee);
    }
}

Yes, I know I didn't pass payRate, that's because it's a calculated field specific to the implementation of Employee ;)


问:
Trying to override Django User model username validation
I am trying to override the django default User model username field to allow hashtags in usernames.

I know the model itself will let me do this but the standard form registration doesn't seem to allow it. I'm using django-allauth as well.

How do I replace the regex in the default User model form to allow a hashtag in the username?

答:
I found that I was actually hitting a bug in the software.

https://github.com/pennersr/django-allauth/pull/1648

For anyone else that happens by.


答:
input() will always return a string. So you could write a helper function like this:

```<code>def input_int(message):
    while True:
        try:
            number = int(input(message))
            return number
        except ValueError:
            print('Invalid number string, try again')
            continue
</code>```

An analogous helper could input_float, etc.

There is no doubt a Python package with more bells and whistles, if you need them.

Title: limit python input to int

Body:
input() will always return a string. So you could write a helper function like this:

def input_int(message):
    while True:
        try:
            number = int(input(message))
            return number
        except ValueError:
            print('Invalid number string, try again')
            continue

An analogous helper could input_float, etc.

There is no doubt a Python package with more bells and whistles, if you need them.