问:
What is ES6 equivalent of module.exports = { key: "value" }?
I have the following code:

```<code>module.exports  = {
    key: "value",
    key2: 1234
}
</code>```

If I change it to:

```<code>export default {
    key: "value",
    key2: 1234
}
</code>```

Then the following import stops working:

```<code>import {key, key2} from 'module.js';
</code>```

What is an ES6 equivalent of exporting an object?

答:
You can first define the variables and export them:

```<code>const key = 'value';
const key2 = 1234;

export { key, key2 };
</code>```

Or you can export them in the same line in which you define them:

```<code>export const key = 'value';
export const key2 = 1234;
</code>```

Body:
I have the following code:

module.exports  = {
    key: "value",
    key2: 1234
}

If I change it to:

export default {
    key: "value",
    key2: 1234
}

Then the following import stops working:

import {key, key2} from 'module.js';

What is an ES6 equivalent of exporting an object?

Body:
You can first define the variables and export them:

const key = 'value';
const key2 = 1234;

export { key, key2 };

Or you can export them in the same line in which you define them:

export const key = 'value';
export const key2 = 1234;


来源: stackexchange

答:
If you use export default, then you need not use the bracket. So you import the module like this:

import module from 'module.js';

// access key property
console.log(module.key)```

If you want to import your module like import {key, key2} from 'module.js';, refer to @Michał Perłakowski answer.

ContentLicense: CC BY-SA 3.0

Title: What is ES6 equivalent of module.exports = { key: "value" }?

Body:
If you use export default, then you need not use the bracket. So you import the module like this:

import module from 'module.js';

// access key property
console.log(module.key)

If you want to import your module like import {key, key2} from 'module.js';, refer to @Michał Perłakowski answer.


问:
Encoding newline in VB.NET for HMAC SHA1
I'm having a problem authenticating an API with OAuth. I can get it work fine in Python, but not in VB.Net. I realised the issue is that SHA1 algorithm is returning a different value in Python and VB.NET for the what I thought was the same message. This only seems to be the case when there is a newline character "\n" in the message (which there has to be for the API call). Using Environment.NewLine doesn't seem to help.

The code I'm using (based on this answer) is here, with the expected values I get from my Python program:

```<code>Public Sub Main()
    ' Expect D/5B78PD9pFhmqZQi3eenPBy6ks=
    ' Get    D/5B78PD9pFhmqZQi3eenPBy6ks=
    console.writeline(getHash("a", "msg"))

    ' Expect yuuq6RwtwkoJ6n3PquGFx60MLas=
    ' Get    uv4AwQjvYeCTajhHw7EFtPlJfCE=
    console.writeline(getHash("a", "msg\n"))

    ' Expect yuuq6RwtwkoJ6n3PquGFx60MLas=
    ' Get efRfAnmIN/C/YX/UPHVPFY5VjJg=
    console.writeline(getHash("a", "msg" + Environment.NewLine))

End Sub

Public Function getHash(ByVal key As String, ByVal msg As String) As String
    Dim myEncoder As New System.Text.UTF8Encoding
    Dim keyBytes() As Byte = myEncoder.GetBytes(key)
    Dim msgBytes() As Byte = myEncoder.GetBytes(msg)

    Dim myHMACSHA1 As New System.Security.Cryptography.HMACSHA1(keyBytes)
    Dim HashCode As Byte() = myHMACSHA1.ComputeHash(msgBytes)

    Return Convert.ToBase64String(HashCode)
End Function
</code>```

In case it's useful, my Python program is:

```<code>import base64
import hashlib
import hmac

key = "a"
msg = "msg\n"
key_byte = key.encode('utf-8')
msg_byte = msg.encode('utf-8')

h = hmac.new(key_byte, msg_byte, hashlib.sha1)
print base64.b64encode(h.digest())   # yuuq6RwtwkoJ6n3PquGFx60MLas=
</code>```

My guess is it's something to do with how the newline character is encoded, but I can't figure out how to solve it.

答:
To start with I'd just like to point out that \n in VB.NET does not represent a new line character. It will literally just become \n.

Environment.NewLine adapts to the current OS. Different operating systems use different line endings. The issue here is that the Python code is using a Line Feed character (\n) as a new line indicator, but since Environment.NewLine adapts to the OS it will return Windows' line ending, which is Carriage Return + Line Feed (\r\n).

Therefore if you want it to match the Python code you've got to be sure to insert a Line Feed only. For instance:

```<code>Console.WriteLine(getHash("a", "msg" & vbLf))
</code>```

Body:
I'm having a problem authenticating an API with OAuth. I can get it work fine in Python, but not in VB.Net. I realised the issue is that SHA1 algorithm is returning a different value in Python and VB.NET for the what I thought was the same message. This only seems to be the case when there is a newline character "\n" in the message (which there has to be for the API call). Using Environment.NewLine doesn't seem to help.

The code I'm using (based on this answer) is here, with the expected values I get from my Python program:

Public Sub Main()
    ' Expect D/5B78PD9pFhmqZQi3eenPBy6ks=
    ' Get    D/5B78PD9pFhmqZQi3eenPBy6ks=
    console.writeline(getHash("a", "msg"))

    ' Expect yuuq6RwtwkoJ6n3PquGFx60MLas=
    ' Get    uv4AwQjvYeCTajhHw7EFtPlJfCE=
    console.writeline(getHash("a", "msg\n"))

    ' Expect yuuq6RwtwkoJ6n3PquGFx60MLas=
    ' Get efRfAnmIN/C/YX/UPHVPFY5VjJg=
    console.writeline(getHash("a", "msg" + Environment.NewLine))

End Sub

Public Function getHash(ByVal key As String, ByVal msg As String) As String
    Dim myEncoder As New System.Text.UTF8Encoding
    Dim keyBytes() As Byte = myEncoder.GetBytes(key)
    Dim msgBytes() As Byte = myEncoder.GetBytes(msg)

    Dim myHMACSHA1 As New System.Security.Cryptography.HMACSHA1(keyBytes)
    Dim HashCode As Byte() = myHMACSHA1.ComputeHash(msgBytes)

    Return Convert.ToBase64String(HashCode)
End Function

In case it's useful, my Python program is:

import base64
import hashlib
import hmac

key = "a"
msg = "msg\n"
key_byte = key.encode('utf-8')
msg_byte = msg.encode('utf-8')

h = hmac.new(key_byte, msg_byte, hashlib.sha1)
print base64.b64encode(h.digest())   # yuuq6RwtwkoJ6n3PquGFx60MLas=

My guess is it's something to do with how the newline character is encoded, but I can't figure out how to solve it.

Body:
To start with I'd just like to point out that \n in VB.NET does not represent a new line character. It will literally just become \n.

Environment.NewLine adapts to the current OS. Different operating systems use different line endings. The issue here is that the Python code is using a Line Feed character (\n) as a new line indicator, but since Environment.NewLine adapts to the OS it will return Windows' line ending, which is Carriage Return + Line Feed (\r\n).

Therefore if you want it to match the Python code you've got to be sure to insert a Line Feed only. For instance:

Console.WriteLine(getHash("a", "msg" & vbLf))


问:
Convert Perl regex to PHP
I have the following Perl code:

```<code>$url=~s/\W//g;
</code>```

I'd like to translate this to PHP preg_replace.

```<code>preg_replace("/[\W]/", "", $url);
</code>```

I'm not sure this is correct. I don't really know what it does.

It comes from this function, which formats a URL to a canonical format:

```<code>sub formatcanonical {
    my $url = lc(shift);

    $url =~ s/-/ /g;
    $url =~ s/\s+/_/g;
    $url =~ s/\W//g;

    return $url;
}
</code>```

答:
The Perl code

```<code>$url=~s/\W//g;
</code>```

replaces all characters in $url matching \W (non-word character) with emptiness and assigns the result back to $url variable.

Equivalent PHP code:

```<code>$url = preg_replace('/\W/', '', $url);
</code>```

The number of maximum possible replacements can be set via the 4th argument ($limit). By default, $limit is equal to -1 (no limit). So the replacement is performed globally (the Perl code uses the g modifier to achieve that).

Note, the definition of "word" depends on the current locale settings (see Escape Sequences):

A "word" character is any letter or digit or the underscore character,
  that is, any character which can be part of a Perl "word". The
  definition of letters and digits is controlled by PCRE's character
  tables, and may vary if locale-specific matching is taking place. For
  example, in the "fr" (French) locale, some character codes greater
  than 128 are used for accented letters, and these are matched by \w.

Title: Convert Perl regex to PHP

Body:
I have the following Perl code:

$url=~s/\W//g;

I'd like to translate this to PHP preg_replace.

preg_replace("/[\W]/", "", $url);

I'm not sure this is correct. I don't really know what it does.

It comes from this function, which formats a URL to a canonical format:

sub formatcanonical {
    my $url = lc(shift);

    $url =~ s/-/ /g;
    $url =~ s/\s+/_/g;
    $url =~ s/\W//g;

    return $url;
}

Body:
The Perl code

$url=~s/\W//g;

replaces all characters in $url matching \W (non-word character) with emptiness and assigns the result back to $url variable.

Equivalent PHP code:

$url = preg_replace('/\W/', '', $url);

The number of maximum possible replacements can be set via the 4th argument ($limit). By default, $limit is equal to -1 (no limit). So the replacement is performed globally (the Perl code uses the g modifier to achieve that).

Note, the definition of "word" depends on the current locale settings (see Escape Sequences):

A "word" character is any letter or digit or the underscore character,
  that is, any character which can be part of a Perl "word". The
  definition of letters and digits is controlled by PCRE's character
  tables, and may vary if locale-specific matching is taking place. For
  example, in the "fr" (French) locale, some character codes greater
  than 128 are used for accented letters, and these are matched by \w.


问:
Can't set @IBInspectable computed property in UIView
I'm trying to add an IBInspectable color to UIView, so that I can set it in the storyboard and later use it in code. In this post regarding UITextField I've seen that I can take advantage of extensions and adding a computed property, but I can't make it work for UIView.

I get a crash: Failed to set (additionalColor1) user defined inspected property on (UIView): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key additionalColor1.

Any idea what's causing the crash and how to fix it?

Here's my code:

```<code>extension UIView {
    @IBInspectable var additionalColor1: UIColor? {
        return self.additionalColor1
    }
}
</code>```

For the reference, I'm pasting the code that can be used to set the placeholder color for UITextField (same as the above url). This works ok:

```<code>extension UITextField {
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }
}
</code>```

答:
How is your additionalColor going to be used?

I had to do something similar to this recently, but in my case I was always applying the extra value right away.

For example, I wanted to create a button that looked like a parallelogram. So, I wanted a way to put in a value in the Storyboard, which would apply a CGAffineTransform. I'm not really storing the skew value, just using to change what the thing looks like. Then, in the get, I'm passing back the value from the view's affineTransform routine.

```<code>@IBInspectable var skewOffset: Float {
    set(newSkewOffset) {
        let affineTransform : CGAffineTransform = CGAffineTransform(a: 1.0, b: 0.0, c: CGFloat(newSkewOffset), d: 1.0, tx: 0.0, ty: 0.0)
        layer.setAffineTransform(affineTransform)
    }
    get {
        return Float(layer.affineTransform().c)
    }
}
</code>```

So, I'm not storing skewOffset, I'm applying it, and I know how I can look it up later, if I need to get it.

Body:
I'm trying to add an IBInspectable color to UIView, so that I can set it in the storyboard and later use it in code. In this post regarding UITextField I've seen that I can take advantage of extensions and adding a computed property, but I can't make it work for UIView.

I get a crash: Failed to set (additionalColor1) user defined inspected property on (UIView): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key additionalColor1.

Any idea what's causing the crash and how to fix it?

Here's my code:

extension UIView {
    @IBInspectable var additionalColor1: UIColor? {
        return self.additionalColor1
    }
}

For the reference, I'm pasting the code that can be used to set the placeholder color for UITextField (same as the above url). This works ok:

extension UITextField {
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }
}

Body:
How is your additionalColor going to be used?

I had to do something similar to this recently, but in my case I was always applying the extra value right away.

For example, I wanted to create a button that looked like a parallelogram. So, I wanted a way to put in a value in the Storyboard, which would apply a CGAffineTransform. I'm not really storing the skew value, just using to change what the thing looks like. Then, in the get, I'm passing back the value from the view's affineTransform routine.

@IBInspectable var skewOffset: Float {
    set(newSkewOffset) {
        let affineTransform : CGAffineTransform = CGAffineTransform(a: 1.0, b: 0.0, c: CGFloat(newSkewOffset), d: 1.0, tx: 0.0, ty: 0.0)
        layer.setAffineTransform(affineTransform)
    }
    get {
        return Float(layer.affineTransform().c)
    }
}

So, I'm not storing skewOffset, I'm applying it, and I know how I can look it up later, if I need to get it.


问:
Webhook URL - Facebook integration of an IBM Watson app
I'm a beginner in IBM environment. I'm working on a Watson Conversation chatbot developed in the IBM Bluemix environment. My IBM app is synchronized with a Github repository through the IBM toolchain service. My app and my chatbot work in the web page given by Bluemix.

But, when it comes to integrating my bot to Facebook messenger, I'm stuck with the Webhook thing. I have no idea which URL I should fill in and where this URL must point.

BTW my env variables are set (MESSENGER_PAGE_TOKEN, MESSENGER_APP_SECRET, MESSENGER_VERIFY_TOKEN, MESSENGER_WEBHOOKENDPOINT). The last 2 are not generated; I've set them myself.

If anyone could help me to create/find the webhook URL, it would be really nice as I'm so lost.

答:
You will have to create a call back URL(which will be your Bluemix app that has chatbot) at first and then update it in the Webhook URL input

You can refer these:

https://developers.facebook.com/docs/messenger-platform/guides/quick-start

https://www.ibm.com/blogs/bluemix/.../bot-for-facebook-messenger-using-bluemix/


问:
How to install latest production-level Kubernetes in Ubuntu 14
1. Followed -> https://kubernetes.io/docs/getting-started-guides/ubuntu/manual/

After I clone as they mentioned in doc. git clone --depth 1 https://github.com/kubernetes/kubernetes.git. I could not find the file cluster/ubuntu/config-default.sh to configure cluster.

Ok, I left it default and try to run KUBERNETES_PROVIDER=ubuntu ./kube-up.sh but there is no verify-kube-binaries.sh file

```<code>root@ultron:/home/veeru# KUBERNETES_PROVIDER=ubuntu ./kube-up.sh
... Starting cluster using provider: ubuntu
... calling verify-prereqs
Skeleton Provider: verify-prereqs not implemented
... calling verify-kube-binaries
./kube-up.sh: line 44: verify-kube-binaries: command not found
</code>```

Outdated Documentation?

2. From official git repo, I have downloaded 1.6.4 version (Branch->Tag->v1.6.4)
After cluster/ubuntu/config-default.sh configuration I ran KUBERNETES_PROVIDER=ubuntu ./kube-up.sh in cluster directory. But some of the links are outdated!

3. Finally I tried in Ubuntu 16 with kubeadm.https://kubernetes.io/docs/getting-started-guides/kubeadm/

The kubeadm init command successfully completed without any problem, but when I try to kubectl cluster-info, it is showing The connection to the server localhost:8080 was refused

Any help?(Mainly I want to install K8 in Ubuntu 14)

UPDATE 1

Point 3(K8 on Ubuntu 16 with kubeadm) is resolved by running

```<code>  sudo cp /etc/kubernetes/admin.conf $HOME/
  sudo chown $(id -u):$(id -g) $HOME/admin.conf
  export KUBECONFIG=$HOME/admin.conf
</code>```

答:
kubeadm is the way to go. kube-up.sh has been deprecated long back.
https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/

You may also want to try https://www.ubuntu.com/containers/kubernetes

Body:
1. Followed -> https://kubernetes.io/docs/getting-started-guides/ubuntu/manual/

After I clone as they mentioned in doc. git clone --depth 1 https://github.com/kubernetes/kubernetes.git. I could not find the file cluster/ubuntu/config-default.sh to configure cluster.

Ok, I left it default and try to run KUBERNETES_PROVIDER=ubuntu ./kube-up.sh but there is no verify-kube-binaries.sh file

root@ultron:/home/veeru# KUBERNETES_PROVIDER=ubuntu ./kube-up.sh
... Starting cluster using provider: ubuntu
... calling verify-prereqs
Skeleton Provider: verify-prereqs not implemented
... calling verify-kube-binaries
./kube-up.sh: line 44: verify-kube-binaries: command not found

Outdated Documentation?

2. From official git repo, I have downloaded 1.6.4 version (Branch->Tag->v1.6.4)
After cluster/ubuntu/config-default.sh configuration I ran KUBERNETES_PROVIDER=ubuntu ./kube-up.sh in cluster directory. But some of the links are outdated!

3. Finally I tried in Ubuntu 16 with kubeadm.https://kubernetes.io/docs/getting-started-guides/kubeadm/

The kubeadm init command successfully completed without any problem, but when I try to kubectl cluster-info, it is showing The connection to the server localhost:8080 was refused

Any help?(Mainly I want to install K8 in Ubuntu 14)

UPDATE 1

Point 3(K8 on Ubuntu 16 with kubeadm) is resolved by running

  sudo cp /etc/kubernetes/admin.conf $HOME/
  sudo chown $(id -u):$(id -g) $HOME/admin.conf
  export KUBECONFIG=$HOME/admin.conf


问:
JMeter error : java.net.SocketException: Unexpected end of file from server
I have read and tried the solutions shared in the previous posts for this error but nothing helped me to fix this. Kindly help.

I am making a HTTPS API call. A very simple call which accepts a 2 KB JSON message via POST method and sends a one word acknowledgement. It works perfectly fine in Postman tool. In JMeter, no. of threads (users) is kept as 25. It works perfectly fine one time with all 25 success response and at times getting few failure  response as

Response code: Non HTTP response code: java.net.SocketException

Response message: Non HTTP response message: Unexpected end of file from server

No consistency at all. I have also tried with both enabling and disabling "use keepalive" checkbox. Both giving me all success one time ; few/all failure at another time with the above error. Please help. Thank you.

Below are the JMeter settings:

HTTP Header Manager : Content-Type - application/json

HTTPRequest sampler : protocol - HTTPS

Server Name or IP : project server name

Method : POST

PATH : The required path with https authentication details passed as parameters

IMPLEMENTATION : Set to JAVA (HTTPCLIENT4 was giving me “443 failed to respond” error)

答:
Add header
Connection Keep-Alive</p>

Body:
Add header
Connection Keep-Alive


问:
I want to send a form to another website using php
I've been trying to send a form my website to another website using this code

$jumlah = $query1->jumlah;
$postdata = http_build_query(
    array(
        'url' => $url,
        'jumlah' => $jumlah
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('http://insta.kingdompanel.xyz/addlikes.php', false, $context);
```

<p>Before I send it to that website, I'm trying to send the form to my own website, and it works. I change this code to try send a form there.</p>

<pre class="lang-php prettyprint-override"><code>file_get_contents('http://insta.kingdompanel.xyz/addlikes.php', false, $context);
</code>```

After I change that, it doesn't send anything.

update :
here is it the network tab

my goal is to post this data

to this form which is different website, without opening this page

答:
```<code>$jumlah = $query1->jumlah;
$postdata = http_build_query(
    array(
        'url' => $url,
        'jumlah' => $jumlah
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'header'  => 'Access-Control-Allow-Origin: *',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('http://insta.kingdompanel.xyz/addlikes.php', false, $context);
</code>```

Try the above modified code, if it works fine otherwise, Other server may not allowing CORS requests

Body:
I've been trying to send a form my website to another website using this code

$jumlah = $query1->jumlah;
$postdata = http_build_query(
    array(
        'url' => $url,
        'jumlah' => $jumlah
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('http://insta.kingdompanel.xyz/addlikes.php', false, $context);

Before I send it to that website, I'm trying to send the form to my own website, and it works. I change this code to try send a form there.

file_get_contents('http://insta.kingdompanel.xyz/addlikes.php', false, $context);

After I change that, it doesn't send anything.

update :
here is it the network tab

my goal is to post this data

to this form which is different website, without opening this page

Body:
$jumlah = $query1->jumlah;
$postdata = http_build_query(
    array(
        'url' => $url,
        'jumlah' => $jumlah
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'header'  => 'Access-Control-Allow-Origin: *',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('http://insta.kingdompanel.xyz/addlikes.php', false, $context);

Try the above modified code, if it works fine otherwise, Other server may not allowing CORS requests


问:
Give Google Service Account access to all my Google Analytics Accounts
My work email has access to around 100 analytic accounts. Is there anyway give a google service account to all of the analytics I have access to with out needing to manually add it to every account?</p>

答:
Working off of Eike's comment, it seems to be possible from Google Apps Scripts:

```<code>function listAccounts() {
  var accounts = Analytics.Management.Accounts.list();
  if (accounts.items && accounts.items.length) {
    for (var i = 0; i < accounts.items.length; i++) {
      var account = accounts.items[i];
      var body =
      {
        permissions:
        {
          local: ['READ_AND_ANALYZE'] //or whatever permissions you need
        },
        userRef:
        {
          email: 'theemailaddressyouneed'
        }
      };
      Analytics.Management.AccountUserLinks.insert(body, account.id);
    }
  } else {
    Logger.log('No accounts found.');
  }
}
</code>```

You will have to add the "Advanced Google Service" resource: Google Analytics API.

When you run it, you will also need to allow as a user who actually has permissions to add users to GA accounts.

Edit: I forgot to add, this seemed to create a new project for me in the developer console. I got an error message the first time about the project not having the API enabled. Click details or go to the dev console and find this project and enable the Google Analytics API.

Body:
Working off of Eike's comment, it seems to be possible from Google Apps Scripts:

function listAccounts() {
  var accounts = Analytics.Management.Accounts.list();
  if (accounts.items && accounts.items.length) {
    for (var i = 0; i < accounts.items.length; i++) {
      var account = accounts.items[i];
      var body =
      {
        permissions:
        {
          local: ['READ_AND_ANALYZE'] //or whatever permissions you need
        },
        userRef:
        {
          email: 'theemailaddressyouneed'
        }
      };
      Analytics.Management.AccountUserLinks.insert(body, account.id);
    }
  } else {
    Logger.log('No accounts found.');
  }
}

You will have to add the "Advanced Google Service" resource: Google Analytics API.

When you run it, you will also need to allow as a user who actually has permissions to add users to GA accounts.

Edit: I forgot to add, this seemed to create a new project for me in the developer console. I got an error message the first time about the project not having the API enabled. Click details or go to the dev console and find this project and enable the Google Analytics API.


问:
ASP.NET Identity rollback unverified email change
At the moment this is a general question with no code as I am looking for a BEST practices example to my question:

User issues an email change request. (done)

A link is sent to the new address to confirm the new email. (done)

User clicks the confirmation link and the DB update is complete. (done)

What also needs to happen is when the confirmation link is sent for the change, an email should also be sent to the original email address where the user can click a link to reverse the process for whatever reason. I would think also that even if the new email address was accepted, if the original link denies the change it reverts and 2) if the original email reverts and then the new email link is confirmed, that the request would then be denied.

Any direction or code on this matter would be greatly appreciated.

答:
Seems like a simple bit field in the database user record would suffice, or an associated database record would work too.  When both emails are sent, mark the field for that user, let's call it "ChangeEmailSent" to 1.  When either email is clicked, the field should be updated to 0.  The actual changing of the email should only occur if the field is 1.

Some pseudo-code if you like

```<code>private void CancelEmailChange(email)
{
    var user = Database.GetUser(email);
    user.ChangeEmailSent = false;
    Database.Save();
}

private void ProcessEmailChange(email)
{
    var user = Database.GetUser(email);
if (user.ChangeEmailSent)
{
    user.email = getNewEmailAddress();  //whatever logic for a new email
    user.ChangeEmailSent = false;
    Database.Save();
}

}
</code>```

Body:
Seems like a simple bit field in the database user record would suffice, or an associated database record would work too.  When both emails are sent, mark the field for that user, let's call it "ChangeEmailSent" to 1.  When either email is clicked, the field should be updated to 0.  The actual changing of the email should only occur if the field is 1.

Some pseudo-code if you like

private void CancelEmailChange(email)
{
    var user = Database.GetUser(email);
    user.ChangeEmailSent = false;
    Database.Save();
}

private void ProcessEmailChange(email)
{
    var user = Database.GetUser(email);
if (user.ChangeEmailSent)
{
    user.email = getNewEmailAddress();  //whatever logic for a new email
    user.ChangeEmailSent = false;
    Database.Save();
}

}


问:
NotifyDataSetChanged refreshes RecyclerView but scrolls as well.
I have a RecyclerView and one item row needs to be updated like every second (SeekBar). So I call NotifyDataSetChanged once I update the data in the list. UI gets updated but the issue is that the RecyclerView scrolls so that this particular item is either at top or bottom of the screen.
I don't want RecyclerView to scroll.</p>

```<code>// Update Data
    mData.set(mData.indexOf(cardData), cardData);
    // RefreshView
    refreshView() {
       runOnUiThread(new Runnable(){
          notifyDataSetChanged();
         }
     );
</code>```

答: I got it working. I was having a card view above the recycler view.I just removed it. Now the whole screen is a recyclerView and I cannot see any auto scrolls.</p>

Body:
I have a RecyclerView and one item row needs to be updated like every second (SeekBar). So I call NotifyDataSetChanged once I update the data in the list. UI gets updated but the issue is that the RecyclerView scrolls so that this particular item is either at top or bottom of the screen.
I don't want RecyclerView to scroll.

// Update Data
    mData.set(mData.indexOf(cardData), cardData);
    // RefreshView
    refreshView() {
       runOnUiThread(new Runnable(){
          notifyDataSetChanged();
         }
     );


问:
Converting LPSTR to LPCTSTR
I have a program I am modifying to take command line argument as a variable of the type LPSTR. Currently the value is hardcoded in the program and passes to the desired function in the form _T("program.exe"). The function expects the type LPCTSTR. I have tried to cast my command line argument from a LPSTR to a LPCTSTR to no avail. Similar attempts using a char* as an intermediary have also failed. I know I am probably missing something stupidly simple, but at this point I would appreciate the help.

答:
If your project is using Unicode by default, _T("String") will become L"String", which is a wide-character string.  You cannot convert between wide-character strings and 8-bit character strings using a type-cast.

Your options:

Change your project settings to not use the Unicode character set.

Use the Unicode functions instead of the ANSI ones. Define your application entry point to be wWinMain instead of WinMain, and the command-line parameter to be LPWSTR lpCmdLine.

Title: Converting LPSTR to LPCTSTR


问:
SELECT Query fails because of restrictions or so it says
I'm running a query against a MySQL database, and its statement is simply

```<code>SELECT * FROM tableOperationsHistory;
</code>```

However, it fails and I get this exception (I translated it into English):

Fail activating restrictions.  One or more rows contain values that
  violate non-null, unique or foreign-key restrictions.

This is the routine where the error happens:

Public Function RetrieveTable(ByVal command_text As String, Optional ByVal parameters As ParameterSet = Nothing) As DataTable
    Dim dt As New DataTable, retry = False
    Do
        Using comm = conn.CreateCommand
            comm.CommandText = command_text
            If parameters IsNot Nothing Then
                Dim par As DbParameter
                For Each pair In parameters
                    par = comm.CreateParameter
                    par.ParameterName = pair.Key
                    par.Value = pair.Value
                    comm.Parameters.Add(par)
                Next
            End If
            Dim rdr As DbDataReader
            RequestConnection()
            Try
                rdr = comm.ExecuteReader
                dt.Load(rdr)
                retry = False
            Catch ex As Exception
                retry = ShouldRetry(ex) 'EXCEPTION IS CAUGHT HERE
            End Try
            DismissConnection()
        End Using
    Loop While retry
    Return dt
End Function
```

<p>And this is the table definition statement:</p>

```CREATE TABLE `tableOperationsHistory` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numero` varchar(45) DEFAULT NULL,
  `pasta_id` int(11) DEFAULT NULL,
  `dataHoraInicioPrazo` datetime DEFAULT NULL,
  `dataHoraFinalPrazo` datetime DEFAULT NULL,
  `urgente` tinyint(4) DEFAULT NULL,
  `setorOrigem_id` int(11) DEFAULT NULL,
  `unidade_id` int(11) DEFAULT NULL,
  `setor_id` int(11) DEFAULT NULL,
  `usuario_id` int(11) DEFAULT NULL,
  `modalidadeComunicacaoJudicial_id` int(11) DEFAULT NULL,
  `modalidadeRepercussao_id` int(11) DEFAULT NULL,
  `especieTarefa_id` int(11) DEFAULT NULL,
  `postIt` varchar(255) DEFAULT NULL,
  `teor_observacao` varchar(255) DEFAULT NULL,
  `comunicacaoJudicial_id` int(11) DEFAULT NULL,
  `tarefa_id` int(11) DEFAULT NULL,
  `mensagens` text,
  `criadoPor_id` int(11) DEFAULT NULL,
  `criadoEm` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=92 DEFAULT CHARSET=latin1;
```

How can this happen in a SELECT statement? What should I do?

答:
This great community helped me to realize that such an error can be caused by "a mismatch in column definition (e.g. size of char fields) between the database and the dataset", and pointed me to another thread: https://stackoverflow.com/a/7029713/3718031

Possible relation with this, too: Column longtext exceeds the MaxLength limit

In my case, there are columns with "TEXT" datatype and it seems that might be the problem.

I thank deeply to all those who commented in my question and helped me to learn this.

EDIT: Since this question was voted-to-close and my problem remained, I tried to investigate a little further and made another question, I hope that one is properly exposed.

Body:
I'm running a query against a MySQL database, and its statement is simply

SELECT * FROM tableOperationsHistory;

However, it fails and I get this exception (I translated it into English):

Fail activating restrictions.  One or more rows contain values that
  violate non-null, unique or foreign-key restrictions.

This is the routine where the error happens:

Public Function RetrieveTable(ByVal command_text As String, Optional ByVal parameters As ParameterSet = Nothing) As DataTable
    Dim dt As New DataTable, retry = False
    Do
        Using comm = conn.CreateCommand
            comm.CommandText = command_text
            If parameters IsNot Nothing Then
                Dim par As DbParameter
                For Each pair In parameters
                    par = comm.CreateParameter
                    par.ParameterName = pair.Key
                    par.Value = pair.Value
                    comm.Parameters.Add(par)
                Next
            End If
            Dim rdr As DbDataReader
            RequestConnection()
            Try
                rdr = comm.ExecuteReader
                dt.Load(rdr)
                retry = False
            Catch ex As Exception
                retry = ShouldRetry(ex) 'EXCEPTION IS CAUGHT HERE
            End Try
            DismissConnection()
        End Using
    Loop While retry
    Return dt
End Function

And this is the table definition statement:

CREATE TABLE `tableOperationsHistory` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numero` varchar(45) DEFAULT NULL,
  `pasta_id` int(11) DEFAULT NULL,
  `dataHoraInicioPrazo` datetime DEFAULT NULL,
  `dataHoraFinalPrazo` datetime DEFAULT NULL,
  `urgente` tinyint(4) DEFAULT NULL,
  `setorOrigem_id` int(11) DEFAULT NULL,
  `unidade_id` int(11) DEFAULT NULL,
  `setor_id` int(11) DEFAULT NULL,
  `usuario_id` int(11) DEFAULT NULL,
  `modalidadeComunicacaoJudicial_id` int(11) DEFAULT NULL,
  `modalidadeRepercussao_id` int(11) DEFAULT NULL,
  `especieTarefa_id` int(11) DEFAULT NULL,
  `postIt` varchar(255) DEFAULT NULL,
  `teor_observacao` varchar(255) DEFAULT NULL,
  `comunicacaoJudicial_id` int(11) DEFAULT NULL,
  `tarefa_id` int(11) DEFAULT NULL,
  `mensagens` text,
  `criadoPor_id` int(11) DEFAULT NULL,
  `criadoEm` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=92 DEFAULT CHARSET=latin1;

How can this happen in a SELECT statement? What should I do?


问:
Cordova plugin Android Activity - accessing resources
I am developing a Cordova plugin for Android and I am having difficulty overcoming accessing project resources from within an activity - the plugin should be project independent, but accessing the resources (e.g. R.java) is proving tricky.

My plugin, for now, is made up of two very simple classes: RedLaser.java and RedLaserScanner.java.

RedLaser.java

Inherits from CordovaPlugin and so contains the execute method and looks similar to the following.

```<code>public class RedLaser extends CordovaPlugin {
    private static final string SCAN_ACTION = "scan";

    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if (action.equals(SCAN_ACTION)) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    scan(args, callbackContext);
                }
            });

            return true;
        }

        return false;
    }

    private void scan(JSONArray args, CallbackContext callbackContext) {
        Intent intent = new Intent(this.cordova.getActivity().getApplicationContext(), RedLaserScanner.class);
        this.cordova.startActivityForResult((CordovaPlugin) this, intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Do something with the result
    }
}
</code>```

RedLaserScanner.java

The RedLaserScanner contains the Android Activity logic and inherits from BarcodeScanActivity (which is a RedLaser SDK class, presumably itself inherits from Activity);

A very simple structure is as follows:

```<code>public class RedLaserScanner extends BarcodeScanActivity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.preview_overlay_new_portrait);
    }
}
</code>```

I am having trouble because I need to access the project's resources to access R.layout.preview_overlay_new_portrait (which are scatted in the Eclipse project) - but I cannot do this unless I import com.myProject.myApp.R - which makes my plugin have a dependency on the project itself.

I did some investigation and found cordova.getActivity().getResources() which seems useful, but this is not accessible from within my RedLaserScanner - because it does not inherit from CordovaPlugin.

Can somebody please help me with some pointers?

Thanks

答:
Hooks can be used to replace source file contents to remove wrong imports and/or add the right imports of resources.

I created a script that do it without needing to specify the files. It tries to find source files (with .java extension), removes any resource import already in it and then put the right resources import (if needed), using the Cordova application package name.

This is the script:

```<code>#!/usr/bin/env node

/*
 * A hook to add resources class (R.java) import to Android classes which uses it.
 */

function getRegexGroupMatches(string, regex, index) {
    index || (index = 1)

    var matches = [];
    var match;
    if (regex.global) {
        while (match = regex.exec(string)) {
            matches.push(match[index]);
            console.log('Match:', match);
        }
    }
    else {
        if (match = regex.exec(string)) {
            matches.push(match[index]);
        }
    }

    return matches;
}

module.exports = function (ctx) {
    // If Android platform is not installed, don't even execute
    if (ctx.opts.cordova.platforms.indexOf('android') < 0)
        return;

    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        Q = ctx.requireCordovaModule('q');

    var deferral = Q.defer();

    var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
    var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

    var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
    var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

    fs.readdir(pluginSourcesRoot, function (err, files) {
        if (err) {
            console.error('Error when reading file:', err)
            deferral.reject();
            return
        }

        var deferrals = [];

        files.filter(function (file) { return path.extname(file) === '.java'; })
            .forEach(function (file) {
                var deferral = Q.defer();

                var filename = path.basename(file);
                var file = path.join(pluginSourcesRoot, filename);
                fs.readFile(file, 'utf-8', function (err, contents) {
                    if (err) {
                        console.error('Error when reading file:', err)
                        deferral.reject();
                        return
                    }

                    if (contents.match(/[^\.\w]R\./)) {
                        console.log('Trying to get packages from file:', filename);
                        var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
                        for (var p = 0; p < packages.length; p++) {
                            try {
                                var package = packages[p];

                                var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
                                if (!fs.existsSync(sourceFile))
                                    throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

                                var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
                                if (!sourceFileContents)
                                    throw 'Can\'t read file contents.';

                                var newContents = sourceFileContents
                                    .replace(/(import ([^;]+).R;)/g, '')
                                    .replace(/(package ([^;]+);)/g, '$1 import ' + appPackage + '.R;');

                                fs.writeFileSync(sourceFile, newContents, 'utf8');
                                break;
                            }
                            catch (ex) {
                                console.log('Could not add import to "' +  filename + '" using package "' + package + '". ' + ex);
                            }
                        }
                    }
                });

                deferrals.push(deferral.promise);
            });

        Q.all(deferrals)
            .then(function() {
                console.log('Done with the hook!');
                deferral.resolve();
            })
    });

    return deferral.promise;
}
</code>```

Just add as an after_plugin_install hook (for Android platform) in your plugin.xml:

```<code><hook type="after_plugin_install" src="scripts/android/addResourcesClassImport.js" />
</code>```

Hope it helps someone!

Body:
I am developing a Cordova plugin for Android and I am having difficulty overcoming accessing project resources from within an activity - the plugin should be project independent, but accessing the resources (e.g. R.java) is proving tricky.

My plugin, for now, is made up of two very simple classes: RedLaser.java and RedLaserScanner.java.

RedLaser.java

Inherits from CordovaPlugin and so contains the execute method and looks similar to the following.

public class RedLaser extends CordovaPlugin {
    private static final string SCAN_ACTION = "scan";

    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if (action.equals(SCAN_ACTION)) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    scan(args, callbackContext);
                }
            });

            return true;
        }

        return false;
    }

    private void scan(JSONArray args, CallbackContext callbackContext) {
        Intent intent = new Intent(this.cordova.getActivity().getApplicationContext(), RedLaserScanner.class);
        this.cordova.startActivityForResult((CordovaPlugin) this, intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Do something with the result
    }
}

RedLaserScanner.java

The RedLaserScanner contains the Android Activity logic and inherits from BarcodeScanActivity (which is a RedLaser SDK class, presumably itself inherits from Activity);

A very simple structure is as follows:

public class RedLaserScanner extends BarcodeScanActivity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.preview_overlay_new_portrait);
    }
}

I am having trouble because I need to access the project's resources to access R.layout.preview_overlay_new_portrait (which are scatted in the Eclipse project) - but I cannot do this unless I import com.myProject.myApp.R - which makes my plugin have a dependency on the project itself.

I did some investigation and found cordova.getActivity().getResources() which seems useful, but this is not accessible from within my RedLaserScanner - because it does not inherit from CordovaPlugin.

Can somebody please help me with some pointers?

Thanks

Body:
Hooks can be used to replace source file contents to remove wrong imports and/or add the right imports of resources.

I created a script that do it without needing to specify the files. It tries to find source files (with .java extension), removes any resource import already in it and then put the right resources import (if needed), using the Cordova application package name.

This is the script:

#!/usr/bin/env node

/*
 * A hook to add resources class (R.java) import to Android classes which uses it.
 */

function getRegexGroupMatches(string, regex, index) {
    index || (index = 1)

    var matches = [];
    var match;
    if (regex.global) {
        while (match = regex.exec(string)) {
            matches.push(match[index]);
            console.log('Match:', match);
        }
    }
    else {
        if (match = regex.exec(string)) {
            matches.push(match[index]);
        }
    }

    return matches;
}

module.exports = function (ctx) {
    // If Android platform is not installed, don't even execute
    if (ctx.opts.cordova.platforms.indexOf('android') < 0)
        return;

    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        Q = ctx.requireCordovaModule('q');

    var deferral = Q.defer();

    var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
    var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

    var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
    var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

    fs.readdir(pluginSourcesRoot, function (err, files) {
        if (err) {
            console.error('Error when reading file:', err)
            deferral.reject();
            return
        }

        var deferrals = [];

        files.filter(function (file) { return path.extname(file) === '.java'; })
            .forEach(function (file) {
                var deferral = Q.defer();

                var filename = path.basename(file);
                var file = path.join(pluginSourcesRoot, filename);
                fs.readFile(file, 'utf-8', function (err, contents) {
                    if (err) {
                        console.error('Error when reading file:', err)
                        deferral.reject();
                        return
                    }

                    if (contents.match(/[^\.\w]R\./)) {
                        console.log('Trying to get packages from file:', filename);
                        var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
                        for (var p = 0; p < packages.length; p++) {
                            try {
                                var package = packages[p];

                                var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
                                if (!fs.existsSync(sourceFile))
                                    throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

                                var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
                                if (!sourceFileContents)
                                    throw 'Can\'t read file contents.';

                                var newContents = sourceFileContents
                                    .replace(/(import ([^;]+).R;)/g, '')
                                    .replace(/(package ([^;]+);)/g, '$1 import ' + appPackage + '.R;');

                                fs.writeFileSync(sourceFile, newContents, 'utf8');
                                break;
                            }
                            catch (ex) {
                                console.log('Could not add import to "' +  filename + '" using package "' + package + '". ' + ex);
                            }
                        }
                    }
                });

                deferrals.push(deferral.promise);
            });

        Q.all(deferrals)
            .then(function() {
                console.log('Done with the hook!');
                deferral.resolve();
            })
    });

    return deferral.promise;
}

Just add as an after_plugin_install hook (for Android platform) in your plugin.xml:

<hook type="after_plugin_install" src="scripts/android/addResourcesClassImport.js" />

Hope it helps someone!


问:
Including third-party libraries in C applications
I'm a bit naive when it comes to application development in C. I've been writing a lot of code for a programming language I'm working on and I want to include stuff from ICU (for internationalization and unicode support).

The problem is, I'm just not sure if there are any conventions for including a third party library. for something like readline where lots of systems are probably going to have it installed already, it's safe to just link to it (I think). But what about if I wanted to include a version of the library in my own code? Is this common or am I thinking about this all wrong?

答: The problem with shipping a copy of the library with your code is that you don't get the benefit of the library's maintainers' bug fixes for free. Obscure, small, and unsupported libraries are generally worth linking statically.  Otherwise I'd just add the dependency and ensure that whatever packages you ship indicate it appropriately.</p>

ContentLicense: CC BY-SA 2.5


问:
Adding an inherited entity to the DBContext
I've this entity

```<code>public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
}
</code>```

I need to extend FooEntity with new fields like this

```<code>public class FooExtended : FooEntity
{
  public int Age {get; set;}
}
</code>```

but I don't want to persist the Age value in the database, it's used only temporarily in the model of the view.

When I try to add an instance of FooExtended to the DBContext

```<code>context.FooEntity.Add(xxx);
</code>```

I get the following exception

"Mapping and metadata information could not be found for EntityType
  'FooExtended'."

I tried adding the attribute [NotMapped] to the field Age but I get the same exception.

Is it possible to achieve what I'm trying to do with Entity Framework 6.1.3?

答:
Hi Its seems to be any of the one below reasons could cause your problem. these are :

```<code>   Misspelled properties (case-sensitive!)

   Properties missing in the POCO class

   Type mismatches between the POCO and entity-type (e.g.,int instead of long)

   Enums in the POCO (EF doesn't support enums right now as I understand)
</code>```

Source: https://stackoverflow.com/a/3439550/3397630

Hope It may redirect you to the correct direction

Thanks

Karthik

Body:
I've this entity

public class FooEntity
{
   public int ID {get; set;}
   public string Name {get; set;}
}

I need to extend FooEntity with new fields like this

public class FooExtended : FooEntity
{
  public int Age {get; set;}
}

but I don't want to persist the Age value in the database, it's used only temporarily in the model of the view.

When I try to add an instance of FooExtended to the DBContext

context.FooEntity.Add(xxx);

I get the following exception

"Mapping and metadata information could not be found for EntityType
  'FooExtended'."

I tried adding the attribute [NotMapped] to the field Age but I get the same exception.

Is it possible to achieve what I'm trying to do with Entity Framework 6.1.3?

Body:
Hi Its seems to be any of the one below reasons could cause your problem. these are :

   Misspelled properties (case-sensitive!)

   Properties missing in the POCO class

   Type mismatches between the POCO and entity-type (e.g.,int instead of long)

   Enums in the POCO (EF doesn't support enums right now as I understand)

Source: https://stackoverflow.com/a/3439550/3397630

Hope It may redirect you to the correct direction

Thanks

Karthik


问:
Doctrine: How to get auto generated id after a merge ?
I'm working on a legacy project in Symfony2, where mappings of entities are not correctly defined, but I would prefer not to touch them...

I got an entity with several ManyToOne relationships, but no cascade persist has been defined on these associations. And the associated entities also have relationships, and so on (the project is quite big)...

So, when I need to write a new entity to database, I usually use merge to avoid persisting all related entities:

```<code>$myObject = new Object();
...
$em->merge($myObject);
$em->flush();
</code>```

But this time, I need to get the id of the inserted object. This id is auto generated by Doctrine (I also prefer not to change this).

I know that with persist, I can do:

```<code>$em->persist($object);
$em->flush();
$id = $object->getId();
</code>```

But how can I do with merge ? Obviously this won't work:

```<code>$em->merge($object);
$em->flush();
$id = $object->getId(); // $id is null...
</code>```

Thanks.

答:
Ok, so I ended doing:

```<code>$myObject = new Object();
...
$em->merge($myObject);
$em->flush();

// Get back object from db (merge doesn't give access to auto-generated id)
$query = $this->getDoctrine()
    ->getRepository('MyBundle:Object')
    ->createQueryBuilder('o')
    ->orderBy('o.id', 'DESC')
    ->getQuery();
$object = $query->setMaxResults(1)->getOneOrNullResult();

$id = $object->getId();
</code>```

If someone has a better solution, please post it!

Body:
I'm working on a legacy project in Symfony2, where mappings of entities are not correctly defined, but I would prefer not to touch them...

I got an entity with several ManyToOne relationships, but no cascade persist has been defined on these associations. And the associated entities also have relationships, and so on (the project is quite big)...

So, when I need to write a new entity to database, I usually use merge to avoid persisting all related entities:

$myObject = new Object();
...
$em->merge($myObject);
$em->flush();

But this time, I need to get the id of the inserted object. This id is auto generated by Doctrine (I also prefer not to change this).

I know that with persist, I can do:

$em->persist($object);
$em->flush();
$id = $object->getId();

But how can I do with merge ? Obviously this won't work:

$em->merge($object);
$em->flush();
$id = $object->getId(); // $id is null...

Thanks.

Body:
Ok, so I ended doing:

$myObject = new Object();
...
$em->merge($myObject);
$em->flush();

// Get back object from db (merge doesn't give access to auto-generated id)
$query = $this->getDoctrine()
    ->getRepository('MyBundle:Object')
    ->createQueryBuilder('o')
    ->orderBy('o.id', 'DESC')
    ->getQuery();
$object = $query->setMaxResults(1)->getOneOrNullResult();

$id = $object->getId();

If someone has a better solution, please post it!


问:
How to get a self-closing xml tag in Oracle PLSQL?
The Requested output is should be as follows:

```<code><Consignment id="123" date="2017-06-08">
    <Box id="321" />
</Consignment>
</code>```

where the <box> tag should be self-closing as above.

I am using the following code:

```<code>SELECT XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
            XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
                 ).getstringval() as xxx FROM DUAL;
</code>```

but it always return the following results (where the tag <box> has a separated closing tag </box>):

```<code><Consignment id="123" date="2017-06-08">
    <Box id="321"></Box>
</Consignment>
</code>```

how to get the above <box> tag self-closed?

答:
If you only need to do this with "box", then you can use :

```<code>SELECT REPLACE(XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
            XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
                 ).getstringval(),'></Box>',' />') as xxx FROM DUAL;
</code>```

If you have other tags that need to be processed this way, you will need to use REGEXP_REPLACE using the same logic.

Semantically though, both forms represent the exact same data, which is why you can't do what you want to do "easily" with some parameter given to the XML generator (and why maybe you should not do that in the first place!).

Body:
The Requested output is should be as follows:

<Consignment id="123" date="2017-06-08">
    <Box id="321" />
</Consignment>

where the <box> tag should be self-closing as above.

I am using the following code:

SELECT XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
            XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
                 ).getstringval() as xxx FROM DUAL;

but it always return the following results (where the tag <box> has a separated closing tag </box>):

<Consignment id="123" date="2017-06-08">
    <Box id="321"></Box>
</Consignment>

how to get the above <box> tag self-closed?

Body:
If you only need to do this with "box", then you can use :

SELECT REPLACE(XMLELEMENT( "Consignment", XMLATTRIBUTES('123' AS "id",sysdate AS "date" ),
            XMLELEMENT( "Box", xmlattributes( '321' as "id" ))
                 ).getstringval(),'></Box>',' />') as xxx FROM DUAL;

If you have other tags that need to be processed this way, you will need to use REGEXP_REPLACE using the same logic.

Semantically though, both forms represent the exact same data, which is why you can't do what you want to do "easily" with some parameter given to the XML generator (and why maybe you should not do that in the first place!).


问:
How to run python program on my windows system after installation using notepad++ or dreamviewer
I'm new for python i installed python 3.6.1 on my windows 7 system after that i searched a lot but i cannot understand.please help me how to create a new python program using notepad++ or adobe dream viewer...</p>

答:
You can use Pycharm IDE to code python. It is easy and user friendly. Download it using following link. use community edition.
Pycharm Download
Since you have alredy installed python, you can use that interpreter for pycharm.</p>


问:
wordpress admin-ajax return always 0
I know that my question was asked many other times and I read all discussions about that but I don't have found the right answer.

My problem is that admin-ajax request with ajax call return always 0 on wordpress.
My codes are:

Front End call

```<code>$.ajax({
   url: cubetechform_ajax.ajax_url,
   type: "POST",
    data: {
        action: 'cubetech_contact_form_send_email',
        name: name,
        phone: phone,
        email: email,
        message: message
    },
    cache: false,
    success: function(response) {
        console.log(response);
    },
    error: function(XMLHttpRequest, ajaxOptions, thrownError) {
        //console.log(XMLHttpRequest.status + '<br/>' + ajaxOptions + '<br/>' + thrownError);
    },
});
</code>```

Back End

```<code>/*
 * Action hooks
 */
function __construct() {

    // Enqueue plugin styles and scripts
    add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_cubetech_form_scripts' ) );

    // Setup Ajax action hook
    add_action( 'wp_ajax_cubetech_send_email', array( $this, 'cubetech_send_email' ) );
    add_action( 'wp_ajax_nopriv_cubetech_send_email', array( $this, 'cubetech_send_email' ) );

    //$this->cubetech_send_email();
}

/**
 * Register plugin styles and scripts
 */
public function register_contactme_scripts() {
    wp_register_script( 'contactme_script', get_template_directory_uri() . '/js/contact_me.js', array('jquery','bootstrapValidationScript'), '', true);
}
/**
 * Enqueues plugin-specific scripts.
 */
public function enqueue_cubetech_form_scripts() {
    wp_enqueue_script( 'contactme_script', plugins_url( '/js/contact_me.js', __FILE__ ), array('jquery','bootstrapValidationScript'), '', true);
    //wp_enqueue_script( 'contactme-script' );
    wp_localize_script( 'contactme_script', 'cubetechform_ajax', array( 'ajax_url' => admin_url('admin-ajax.php')) );
}

public function cubetech_send_email() {
    require_once ABSPATH . WPINC . '/class-phpmailer.php';
    require_once ABSPATH . WPINC . '/class-smtp.php';

    $name = strip_tags(htmlspecialchars($_POST['name']));
    $email_address = strip_tags(htmlspecialchars($_POST['email']));
    $phone = strip_tags(htmlspecialchars($_POST['phone']));
    $message = strip_tags(htmlspecialchars($_POST['message']));

    // definisco il messaggio formattato in HTML
    $email_body = '<html><body>';
    $email_body .= '<p>Nome: '.$name.'<br>';
    $email_body .= 'N. Telefono: '.$phone.'<br>';
    $email_body .= 'Richiesta: '.$message.'</p>'.'<br>';
    $email_body .= '</body></html>';

    // definisco il messaggio formattato in HTML
    $email_body = '<html><body>';
    $email_body .= '<p>Nome: '.$name.'<br>';
    $email_body .= 'N. Telefono: '.$phone.'<br>';
    $email_body .= 'Richiesta: '.$message.'</p>'.'<br>';
    $email_body .= '</body></html>';

    $to = get_option('admin_email');
    $subject = "Richiesta da: ". $email_address;

    $mail = new PHPMailer();

    $mail->IsSMTP(); // set mailer to use SMTP
    $mail->Host = "smtps.aruba.it";  // specify main and backup server
    //$mail->SMTPDebug = 3;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;     // turn on SMTP authentication
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->Username = "info@cubetech.it";  // SMTP username
    $mail->Password = "*******"; // SMTP password

    $mail->From = "info@cubetech.it";
    $mail->FromName = "Cube Tech Bologna";
    $mail->AddAddress("info@cubetech.it", "Cube Tech Bologna" );  // name is optional
    $mail->AddReplyTo("info@cubetech.it", "Reply");
    $mail->AddCC($email_address);

    $mail->IsHTML(true);  // set email format to HTML

    $mail->SetFrom("info@cubetech.it", "Cube Tech Bologna");
    $mail->Subject = $subject;
    $mail->Body = $email_body;

    $mail->AddAddress("info@cubetech.it");

    $error = '';

    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo;
        echo $error;
        exit();
        die();
    } else {
        $error = 'ok';
        echo $error;
        exit();
        die();
    }
}
</code>```

I tried everything I read about die(); exit(); $mail = new PHPMailer(); $mail = new PHPMailer(true); and so much other. The problem is always with ajax call because if I try to call direct the function cubetech_send_email() it's work perfectly and return ok and phpmailer send it. I try all this on localhost with server email and all works perfect.. Someone can help me to resolve it? Thank you

答:
Your hooks should be like so:

```<code>// Setup Ajax action hook
add_action( 'wp_ajax_cubetech_contact_form_send_email', array( $this, 'cubetech_send_email' ) );
add_action( 'wp_ajax_nopriv_cubetech_contact_form_send_email', array( $this, 'cubetech_send_email' ) );
</code>```

In your data object when doing the ajax refers to "cubetech_contact_form_send_email" as the action. The hooks works like so: wp_ajax_(action)
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Title: wordpress admin-ajax return always 0

Body:
I know that my question was asked many other times and I read all discussions about that but I don't have found the right answer.

My problem is that admin-ajax request with ajax call return always 0 on wordpress.
My codes are:

Front End call

$.ajax({
   url: cubetechform_ajax.ajax_url,
   type: "POST",
    data: {
        action: 'cubetech_contact_form_send_email',
        name: name,
        phone: phone,
        email: email,
        message: message
    },
    cache: false,
    success: function(response) {
        console.log(response);
    },
    error: function(XMLHttpRequest, ajaxOptions, thrownError) {
        //console.log(XMLHttpRequest.status + '
' + ajaxOptions + '
' + thrownError);
    },
});

Back End

/*
 * Action hooks
 */
function __construct() {

    // Enqueue plugin styles and scripts
    add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_cubetech_form_scripts' ) );

    // Setup Ajax action hook
    add_action( 'wp_ajax_cubetech_send_email', array( $this, 'cubetech_send_email' ) );
    add_action( 'wp_ajax_nopriv_cubetech_send_email', array( $this, 'cubetech_send_email' ) );

    //$this->cubetech_send_email();
}

/**
 * Register plugin styles and scripts
 */
public function register_contactme_scripts() {
    wp_register_script( 'contactme_script', get_template_directory_uri() . '/js/contact_me.js', array('jquery','bootstrapValidationScript'), '', true);
}
/**
 * Enqueues plugin-specific scripts.
 */
public function enqueue_cubetech_form_scripts() {
    wp_enqueue_script( 'contactme_script', plugins_url( '/js/contact_me.js', __FILE__ ), array('jquery','bootstrapValidationScript'), '', true);
    //wp_enqueue_script( 'contactme-script' );
    wp_localize_script( 'contactme_script', 'cubetechform_ajax', array( 'ajax_url' => admin_url('admin-ajax.php')) );
}

public function cubetech_send_email() {
    require_once ABSPATH . WPINC . '/class-phpmailer.php';
    require_once ABSPATH . WPINC . '/class-smtp.php';

    $name = strip_tags(htmlspecialchars($_POST['name']));
    $email_address = strip_tags(htmlspecialchars($_POST['email']));
    $phone = strip_tags(htmlspecialchars($_POST['phone']));
    $message = strip_tags(htmlspecialchars($_POST['message']));

    // definisco il messaggio formattato in HTML
    $email_body = '';
    $email_body .= '
Nome: '.$name.'
';
    $email_body .= 'N. Telefono: '.$phone.'
';
    $email_body .= 'Richiesta: '.$message.'
'.'
';
    $email_body .= '';

    // definisco il messaggio formattato in HTML
    $email_body = '';
    $email_body .= '
Nome: '.$name.'
';
    $email_body .= 'N. Telefono: '.$phone.'
';
    $email_body .= 'Richiesta: '.$message.'
'.'
';
    $email_body .= '';

    $to = get_option('admin_email');
    $subject = "Richiesta da: ". $email_address;

    $mail = new PHPMailer();

    $mail->IsSMTP(); // set mailer to use SMTP
    $mail->Host = "smtps.aruba.it";  // specify main and backup server
    //$mail->SMTPDebug = 3;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;     // turn on SMTP authentication
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->Username = "info@cubetech.it";  // SMTP username
    $mail->Password = "*******"; // SMTP password

    $mail->From = "info@cubetech.it";
    $mail->FromName = "Cube Tech Bologna";
    $mail->AddAddress("info@cubetech.it", "Cube Tech Bologna" );  // name is optional
    $mail->AddReplyTo("info@cubetech.it", "Reply");
    $mail->AddCC($email_address);

    $mail->IsHTML(true);  // set email format to HTML

    $mail->SetFrom("info@cubetech.it", "Cube Tech Bologna");
    $mail->Subject = $subject;
    $mail->Body = $email_body;

    $mail->AddAddress("info@cubetech.it");

    $error = '';

    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo;
        echo $error;
        exit();
        die();
    } else {
        $error = 'ok';
        echo $error;
        exit();
        die();
    }
}

I tried everything I read about die(); exit(); $mail = new PHPMailer(); $mail = new PHPMailer(true); and so much other. The problem is always with ajax call because if I try to call direct the function cubetech_send_email() it's work perfectly and return ok and phpmailer send it. I try all this on localhost with server email and all works perfect.. Someone can help me to resolve it? Thank you

Body:
Your hooks should be like so:

// Setup Ajax action hook
add_action( 'wp_ajax_cubetech_contact_form_send_email', array( $this, 'cubetech_send_email' ) );
add_action( 'wp_ajax_nopriv_cubetech_contact_form_send_email', array( $this, 'cubetech_send_email' ) );

In your data object when doing the ajax refers to "cubetech_contact_form_send_email" as the action. The hooks works like so: wp_ajax_(action)
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)


问:
VB6: ShellExecute an EXE inside AppData
I have the following sub:

```<code>Public Sub ShellApp(URL As String)

        Dim vResult As Long
        vResult = ShellExecute(0, "open", URL, vbNullString, vbNullString, vbMinimizedFocus)

   End If
End Sub
</code>```

This is on a layer that cannot be changed due to several functionality needed on that sub.

Now, on our Main() sub for example, we check a list of added plugins saved in a text file beside the EXE, and call the above Sub in for loop with the path of the plugins to run them. So if I have 3 plugins as below in the text file:

C:\App1.EXE

C:\App2.EXE

C:\Users\AhmadMusa\AppData\Roaming\App3.exe

First two apps will run fine on all PCs (Static path), but third app will not work on any PC except mine which is not ok... Note that App3 always installed on AppData on any PC, so how to dynamically access it to run the app from any PC without adjustments on the sub.

What will be the path placed in the text file for third app so it can work on all PCs?

I tried (AppData\Roaming\App3.exe) but it does not work... I found on a thread (http://www.vbforums.com/showthread.php?529776-RESOLVED-Open-a-folder-in-AppData) that I can call something like (shell:AppData\Roaming\App3.exe) it did not work to run the App3.exe, but if I call (shell:AppData\Roaming) it will open the Roaming folder very well. But cannot run the EXE.

Any ideas ?

Thanks.

答:
You need to expand the Environment variable (this is what the %...% does):

```<code>Debug.Print Environ("APPDATA") ' will print the expanded %appdata%
</code>```

So, in your text file you should put:

%APPDATA%\App3.exe

How to expand the path? You can loop over the environment variables provided by the VB Environ function and do a string replace by yourself (the VB way) or you can profit from the ExpandEnvironmentStrings function (the Win32 API way).

Below a snippet using this second option:

```<code>Private Declare Function ExpandEnvironmentStrings Lib "kernel32.dll" _
                Alias "ExpandEnvironmentStringsA" ( _
                ByVal lpSrc As String, _
                ByVal lpDst As String, _
                ByVal nSize As Long) As Long

Public Function ExpandEnvironString(ByVal URL As String) As String
    Dim buf As String, bufSize As Long
    bufSize = ExpandEnvironmentStrings(URL, ByVal 0&, 0&)
    buf = String(bufSize + 1, vbNullChar)
    bufSize = ExpandEnvironmentStrings(URL, buf, Len(buf))
    ExpandEnvironString = Left$(buf, InStr(1, buf, vbNullChar) - 1)
End Function
</code>```

Before you call ShellApp(URL As String) you should expand the path:

```<code>URL = ExpandEnvironString(URL)
</code>```

ShellExecute will receive the expanded path: C:\Users\AhmadMusa\AppData\Roaming\App3.exe

This is a non-breaking change, because if your initial default setting will be later changed to a custom fixed path, the ExpandEnvironmentStrings function will simply ignore it.

Example:

ExpandEnvironString("C:\App1.EXE ") will return C:\App1.EXE

More info:

you can get all your environment variables with following procedure:

```<code>Private Sub EnvironmentEntries()
    Dim Entry As String, i As Long
    i = 1
    Do
        Entry = Environ(i)
        i = i + 1
        If Entry = "" Then Exit Do
        Debug.Print Entry
    Loop
End Sub
</code>```

... and check some additional info here:

Why are there directories called Local, LocalLow, and Roaming under \Users\?

Title: VB6: ShellExecute an EXE inside AppData

Body:
I have the following sub:

Public Sub ShellApp(URL As String)

        Dim vResult As Long
        vResult = ShellExecute(0, "open", URL, vbNullString, vbNullString, vbMinimizedFocus)

   End If
End Sub

This is on a layer that cannot be changed due to several functionality needed on that sub.

Now, on our Main() sub for example, we check a list of added plugins saved in a text file beside the EXE, and call the above Sub in for loop with the path of the plugins to run them. So if I have 3 plugins as below in the text file:

C:\App1.EXE

C:\App2.EXE

C:\Users\AhmadMusa\AppData\Roaming\App3.exe

First two apps will run fine on all PCs (Static path), but third app will not work on any PC except mine which is not ok... Note that App3 always installed on AppData on any PC, so how to dynamically access it to run the app from any PC without adjustments on the sub.

What will be the path placed in the text file for third app so it can work on all PCs?

I tried (AppData\Roaming\App3.exe) but it does not work... I found on a thread (http://www.vbforums.com/showthread.php?529776-RESOLVED-Open-a-folder-in-AppData) that I can call something like (shell:AppData\Roaming\App3.exe) it did not work to run the App3.exe, but if I call (shell:AppData\Roaming) it will open the Roaming folder very well. But cannot run the EXE.

Any ideas ?

Thanks.

Body:
You need to expand the Environment variable (this is what the %...% does):

Debug.Print Environ("APPDATA") ' will print the expanded %appdata%

So, in your text file you should put:

%APPDATA%\App3.exe

How to expand the path? You can loop over the environment variables provided by the VB Environ function and do a string replace by yourself (the VB way) or you can profit from the ExpandEnvironmentStrings function (the Win32 API way).

Below a snippet using this second option:

Private Declare Function ExpandEnvironmentStrings Lib "kernel32.dll" _
                Alias "ExpandEnvironmentStringsA" ( _
                ByVal lpSrc As String, _
                ByVal lpDst As String, _
                ByVal nSize As Long) As Long

Public Function ExpandEnvironString(ByVal URL As String) As String
    Dim buf As String, bufSize As Long
    bufSize = ExpandEnvironmentStrings(URL, ByVal 0&, 0&)
    buf = String(bufSize + 1, vbNullChar)
    bufSize = ExpandEnvironmentStrings(URL, buf, Len(buf))
    ExpandEnvironString = Left$(buf, InStr(1, buf, vbNullChar) - 1)
End Function

Before you call ShellApp(URL As String) you should expand the path:

URL = ExpandEnvironString(URL)

ShellExecute will receive the expanded path: C:\Users\AhmadMusa\AppData\Roaming\App3.exe

This is a non-breaking change, because if your initial default setting will be later changed to a custom fixed path, the ExpandEnvironmentStrings function will simply ignore it.

Example:

ExpandEnvironString("C:\App1.EXE ") will return C:\App1.EXE

More info:

you can get all your environment variables with following procedure:

Private Sub EnvironmentEntries()
    Dim Entry As String, i As Long
    i = 1
    Do
        Entry = Environ(i)
        i = i + 1
        If Entry = "" Then Exit Do
        Debug.Print Entry
    Loop
End Sub

... and check some additional info here:

Why are there directories called Local, LocalLow, and Roaming under \Users\?


问:
How to add a chatbot widget that uses Watson Conversation in my website?
I want to add a chatbot in my web page like this one
chatbot

it should be at the bottom right of the web page.

i read a lot of guides:
https://github.com/watson-developer-cloud/text-bot?cm_mc_uid=55864532344114098377155&cm_mc_sid_50200000=

and a lot more, but i still can't figure out how to add Watson conversation as a chatbot widget in my website.

答:
You can use Watson Conversation, but, try to read  the official documentation and get started with this Service.

Summary: You need to create one Conversation Service inside IBM Bluemix, and after, create one Workspace and teach you Chatbot.

And for add your chatbot in your Website, you need build one custom code for calling the Watson Conversation and creates one front-end for the conversation.

You can see this project from IBM Developers here using Watson Conversation, this example uses Node.js and are developed by IBM.

See this documentation about the API Reference (How to call, how to send message, etc)

See this documentation about Watson Conversation Service.


问:
Parsing mysql date to ZonedDateTime
I'm trying to parse data coming from MySql in the following format:

```<code>DATE_FORMAT(datetime,'%m-%d-%Y %H:%i')
</code>```

Java parser code looks like this:

```<code>ZonedDateTime datetime = ZonedDateTime
                    .parse(
                            row[1].toString(),
                            DateTimeFormatter
                                    .ofPattern("MM-dd-YYYY hh:mm")
                                    .withZone(ZoneId.of("Etc/GMT"))
                    );
</code>```

Exception in thread "AWT-EventQueue-0" java.time.format.DateTimeParseException: Text '06-08-2017 04:15' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MinuteOfHour=15, DayOfMonth=8, WeekBasedYear[WeekFields[SUNDAY,1]]=2017, MonthOfYear=6, HourOfAmPm=4},ISO,Etc/GMT of type java.time.format.Parsed

Is there a better/shorter way to get this done?

答:
The local repair to your problem is:

```<code>    ZonedDateTime datetime = LocalDateTime.parse(row[1].toString(),
                    DateTimeFormatter.ofPattern("MM-dd-uuuu HH:mm"))
            .atZone(ZoneOffset.UTC);
</code>```

Please note that I have changed YYYY to uuuu and hh to uppercase HH in your format pattern. Y is used for week-based-year, and h is used for clock-hour-of-am-pm (1-12) which does not make sense without a (the symbol for am/pm marker). Learn more about these symbols from documentation.

Edit: I was taking my mouth too full here. Your own Java code works nicely with just these two changes to your format pattern. I will let my version of the code stand in case anyone can take inspiration from it.

That said, the best solution is to get for example an Instant object from your JDBC driver rather than a string that is formatted on the database side and parsed back on the Java side. A JDBC 4.2 compliant driver should be able to give you that.

Title: Parsing mysql date to ZonedDateTime

Body:
I'm trying to parse data coming from MySql in the following format:

DATE_FORMAT(datetime,'%m-%d-%Y %H:%i')

Java parser code looks like this:

ZonedDateTime datetime = ZonedDateTime
                    .parse(
                            row[1].toString(),
                            DateTimeFormatter
                                    .ofPattern("MM-dd-YYYY hh:mm")
                                    .withZone(ZoneId.of("Etc/GMT"))
                    );

Exception in thread "AWT-EventQueue-0" java.time.format.DateTimeParseException: Text '06-08-2017 04:15' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MinuteOfHour=15, DayOfMonth=8, WeekBasedYear[WeekFields[SUNDAY,1]]=2017, MonthOfYear=6, HourOfAmPm=4},ISO,Etc/GMT of type java.time.format.Parsed

Is there a better/shorter way to get this done?

Body:
The local repair to your problem is:

    ZonedDateTime datetime = LocalDateTime.parse(row[1].toString(),
                    DateTimeFormatter.ofPattern("MM-dd-uuuu HH:mm"))
            .atZone(ZoneOffset.UTC);

Please note that I have changed YYYY to uuuu and hh to uppercase HH in your format pattern. Y is used for week-based-year, and h is used for clock-hour-of-am-pm (1-12) which does not make sense without a (the symbol for am/pm marker). Learn more about these symbols from documentation.

Edit: I was taking my mouth too full here. Your own Java code works nicely with just these two changes to your format pattern. I will let my version of the code stand in case anyone can take inspiration from it.

That said, the best solution is to get for example an Instant object from your JDBC driver rather than a string that is formatted on the database side and parsed back on the Java side. A JDBC 4.2 compliant driver should be able to give you that.

ContentLicense: CC BY-SA 4.0


问:
PyQt4 to PyQt5 migration
For the last days i read a lot about new and old style of signals and slots. It seems now it's easier, but I stuck on one issue.

In my project old code generate dynamic signals based on name passed to it.

Example:

```<code>self.netlink.connect(self.netlink,SIGNAL(self.modelName + "_gotCommand"),self.processCommand)
</code>```

and here is emit

```<code>self.emit(SIGNAL(model + "_gotCommand"), cmd, data)
</code>```

data can be diffrenet type (list , tuple, string , etc) again based on model

So how can I move this code into Qt5 as we need describe each signal with pyqtSignal definition.

答:
It is not possible to dynamically emit arbitrary signals using the new-style syntax. All signals must be pre-defined in the class.

Your example does not make it clear why you need to use a different signal-name for each model, since you are always connecting to the same slot. It would seem to make more sense to have each model emit the same signal, perhaps also sending the model name, if necessary:

```<code>class SomeModel(QObject):
    gotCommand = pyqtSignal(str, str, object)

    def doSomething(self):
        ...
        self.gotCommand.emit(model, cmd, data)

...

self.netlink.gotCommand.connect(self.processCommand)
</code>```

But if you still need to connect/emit signals by key, you can use getattr:

```<code>getattr(self.netlink, self.modelName + "_gotCommand")).connect(self.processCommand)
</code>```

and:

```<code>getattr(self, model + "_gotCommand").emit(cmd, data)
</code>```

Title: PyQt4 to PyQt5 migration

Body:
For the last days i read a lot about new and old style of signals and slots. It seems now it's easier, but I stuck on one issue.

In my project old code generate dynamic signals based on name passed to it.

Example:

self.netlink.connect(self.netlink,SIGNAL(self.modelName + "_gotCommand"),self.processCommand)

and here is emit

self.emit(SIGNAL(model + "_gotCommand"), cmd, data)

data can be diffrenet type (list , tuple, string , etc) again based on model

So how can I move this code into Qt5 as we need describe each signal with pyqtSignal definition.

Body:
It is not possible to dynamically emit arbitrary signals using the new-style syntax. All signals must be pre-defined in the class.

Your example does not make it clear why you need to use a different signal-name for each model, since you are always connecting to the same slot. It would seem to make more sense to have each model emit the same signal, perhaps also sending the model name, if necessary:

class SomeModel(QObject):
    gotCommand = pyqtSignal(str, str, object)

    def doSomething(self):
        ...
        self.gotCommand.emit(model, cmd, data)

...

self.netlink.gotCommand.connect(self.processCommand)

But if you still need to connect/emit signals by key, you can use getattr:

getattr(self.netlink, self.modelName + "_gotCommand")).connect(self.processCommand)

and:

getattr(self, model + "_gotCommand").emit(cmd, data)


问:
How can I render one partial twice in jbuilder?
I want to render a jbuilder template like this:

```<code>json.author do
  json.partial! 'user', user: @user
end
json.owner do
  json.partial! 'user', user: @user
end
</code>```

It seems a waste to render one partial twice, can I render like this?

```<code>user_json = json.some_render_partial! 'user', user: @user
json.author { user_json }
json.owner { user_json }
</code>```

答:
It seems a waste to render one partial twice, can I render like this?

If your concern is to minimize code then yes, you can using procs.

```<code>user_json = proc { json.partial! 'user', user: @user }

json.author &user_json
json.owner &user_json
</code>```

Also, if your concern is to boost performance, then one way is to cache your partial. Try this

```<code>user_json = proc {
  json.cache! @user, expires_in: 10.minutes do
    json.partial! 'user', user: @user
  end
}

json.author &user_json
json.owner &user_json
</code>```

But, sometimes caching can be slower instead. So, keep in mind if it meets the following criteria:

Partial encompasses hefty computation that are on average more expensive than accessing cache. like WEB API Calls or AR queries

The size of the JSON blob produced is small

See this for more info [ Jbuilder Rails caching is slower ]

Body:
I want to render a jbuilder template like this:

json.author do
  json.partial! 'user', user: @user
end
json.owner do
  json.partial! 'user', user: @user
end

It seems a waste to render one partial twice, can I render like this?

user_json = json.some_render_partial! 'user', user: @user
json.author { user_json }
json.owner { user_json }

Body:
It seems a waste to render one partial twice, can I render like this?

If your concern is to minimize code then yes, you can using procs.

user_json = proc { json.partial! 'user', user: @user }

json.author &user_json
json.owner &user_json

Also, if your concern is to boost performance, then one way is to cache your partial. Try this

user_json = proc {
  json.cache! @user, expires_in: 10.minutes do
    json.partial! 'user', user: @user
  end
}

json.author &user_json
json.owner &user_json

But, sometimes caching can be slower instead. So, keep in mind if it meets the following criteria:

Partial encompasses hefty computation that are on average more expensive than accessing cache. like WEB API Calls or AR queries

The size of the JSON blob produced is small

See this for more info [ Jbuilder Rails caching is slower ]


问:
java.util.zip.ZipException: duplicate entry: org/apache/http/ConnectionClosedException.class
I am getting error like this when i run the application.I am using HttpClient,HttpEntity,HttpResponse and HttpPost in my MainActivity..so i made some modifications to gradle file.After that i am getting error like this.

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/http/ConnectionClosedException.class
</code>```

i have also included multidex library and org.apache.http.legacy.jar in my app.but then also i am getting the same error.

build.gradle

```<code>apply plugin: 'com.android.application'

android {

    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.test1"
        minSdkVersion 15
        targetSdkVersion 23
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:multidex:1.0.1'
    compile files('libs/org.apache.http.legacy.jar')
    compile 'org.apache.httpcomponents:httpmime:4.5.1'
}
</code>```

I Know this question has been asked many times,but none of the solutions worked for me..
Can anyone please help me to resolve this one.

答:
I too faced the same issue. The problem is Since you are using

```<code>compile files('libs/org.apache.http.legacy.jar') and
compile 'org.apache.httpcomponents:httpmime:4.5.1'
</code>```

You need to remove the two libs which I mentioned below. Which contains duplication of the above.

```<code>if you are adding legacy and httpmime you don't need this
        compile 'org.apache.httpcomponents:httpcore:4.4.1'//remove this
        compile 'org.apache.httpcomponents:httpclient:4.5' // remove this too
</code>```

Also add this inside android section in gradle

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    useLibrary 'org.apache.http.legacy'
</code>```

Body:
I am getting error like this when i run the application.I am using HttpClient,HttpEntity,HttpResponse and HttpPost in my MainActivity..so i made some modifications to gradle file.After that i am getting error like this.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/http/ConnectionClosedException.class

i have also included multidex library and org.apache.http.legacy.jar in my app.but then also i am getting the same error.

build.gradle

apply plugin: 'com.android.application'

android {

    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.test1"
        minSdkVersion 15
        targetSdkVersion 23
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:multidex:1.0.1'
    compile files('libs/org.apache.http.legacy.jar')
    compile 'org.apache.httpcomponents:httpmime:4.5.1'
}

I Know this question has been asked many times,but none of the solutions worked for me..
Can anyone please help me to resolve this one.

Body:
I too faced the same issue. The problem is Since you are using

compile files('libs/org.apache.http.legacy.jar') and
compile 'org.apache.httpcomponents:httpmime:4.5.1'

You need to remove the two libs which I mentioned below. Which contains duplication of the above.

if you are adding legacy and httpmime you don't need this
        compile 'org.apache.httpcomponents:httpcore:4.4.1'//remove this
        compile 'org.apache.httpcomponents:httpclient:4.5' // remove this too

Also add this inside android section in gradle

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    useLibrary 'org.apache.http.legacy'


问:
Invalid Apple Watch icon file names must match pattern "*<dimension>@<scale>x.png"
I'm trying to submit an update to my App to include Apple Watch capabilities, however whenever I validate the build I get the errors detailed in the screenshot below. Looking at the bottom error my file name seems to be matching the pattern so I don't see what the issue is. If I can get the pattern right for 1 icon then I can apply the same logic across the board, however I'm not having much luck with it.

Has anyone else had this issue?

答: I had the same error but it ended up that my 27.5x27.5@sx.png image was 56x56 but apple needed it to be 55x55</p>


问:
RESTful HTTP Examples of Server <-> Client
So I'm looking up how to do POST, PUT, etc... in REST but I'm having a problem trying to find a simple example of using POST to send an XML example to a server say Tomcat and show the results.

Is there a correct way to connect? I've seen some people use sockets but is that the way I want to do?

答: You might want to check out cURL and libcurl.  They'll cover all your http needs</p>


问:
How to make 3 phone calls sequentially one after another programatically?
I am newbie to android.i write this code for make a call

```<code>Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + bundle.getString("mobilePhone")));
context.startActivity(intent);
</code>```

I know there is a listener to find the state of the phone using this code.

```<code>  private PhoneStateListener mPhoneListener = new PhoneStateListener() {
  public void onCallStateChanged(int state, String incomingNumber) {
  try {
  switch (state) {
  case TelephonyManager.CALL_STATE_RINGING:
  Toast.makeText(CaptureCall.this, "CALL_STATE_RINGING", Toast.LENGTH_SHORT).show();
  break;
  case TelephonyManager.CALL_STATE_OFFHOOK:
  Toast.makeText(CaptureCall.this, "CALL_STATE_OFFHOOK", Toast.LENGTH_SHORT).show();
  break;
  case TelephonyManager.CALL_STATE_IDLE:
  Toast.makeText(CaptureCall.this, "CALL_STATE_IDLE", Toast.LENGTH_SHORT).show();
  break;
  default:
  Toast.makeText(CaptureCall.this, "default", Toast.LENGTH_SHORT).show();
  Log.i("Default", "Unknown phone state=" + state);
   }
  } catch (Exception e) {
   Log.i("Exception", "PhoneStateListener() e = " + e);
  }
 }
};
</code>```

Actually I call the first number and listen for the state of the phone. If the phone state changes to IDLE I call the second number. But it is not working.

Any one plz suggest me how to do that task.

答:
If I understand your question properly, You are trying to call a number after completion of previous call.

Here is Algorithm for calling n numbers sequentially

Make Queue of numbers to call

Create and register Broadcast Receiver for PhoneState

Dequeue element and fire Intent for Call

Broadcast receiver created at point 2 will listen for call drop state
which is IDLE state,

if theres more element in queue repeat step 3-4

else, unregister broadcast receiver.

C# Code Snippet:

```<code>                Queue phoneNumbers = new Queue();

                foreach (var contact in emergencyContacts)
                    phoneNumbers.Enqueue(contact.contactNo);

                ShareUtils.CallToNumber(context, phoneNumbers.Dequeue().ToString());
                var callReceiver = new CallReceiver();
                callReceiver.onReceive += (intent) =>
                {
                    if (intent.Extras.GetString(TelephonyManager.ExtraState).Equals(TelephonyManager.ExtraStateIdle))
                    {
                        if (phoneNumbers.Count > 0)
                        {
                            var phNumber = phoneNumbers.Dequeue().ToString();
                            ShareUtils.CallToNumber(context, phNumber);
                            Toast.MakeText(this.Activity, $"Calling {phNumber}", ToastLength.Long).Show();
                        }
                        else
                        {
                            context.UnregisterReceiver(callReceiver);
                            ((LandingActivityNew)this.Activity)?.LoadSOS_SuccessFragment();
                        }
                    }
                };
                context.RegisterReceiver(callReceiver, new IntentFilter("android.intent.action.PHONE_STATE"));
</code>```

Body:
I am newbie to android.i write this code for make a call

Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + bundle.getString("mobilePhone")));
context.startActivity(intent);

I know there is a listener to find the state of the phone using this code.

  private PhoneStateListener mPhoneListener = new PhoneStateListener() {
  public void onCallStateChanged(int state, String incomingNumber) {
  try {
  switch (state) {
  case TelephonyManager.CALL_STATE_RINGING:
  Toast.makeText(CaptureCall.this, "CALL_STATE_RINGING", Toast.LENGTH_SHORT).show();
  break;
  case TelephonyManager.CALL_STATE_OFFHOOK:
  Toast.makeText(CaptureCall.this, "CALL_STATE_OFFHOOK", Toast.LENGTH_SHORT).show();
  break;
  case TelephonyManager.CALL_STATE_IDLE:
  Toast.makeText(CaptureCall.this, "CALL_STATE_IDLE", Toast.LENGTH_SHORT).show();
  break;
  default:
  Toast.makeText(CaptureCall.this, "default", Toast.LENGTH_SHORT).show();
  Log.i("Default", "Unknown phone state=" + state);
   }
  } catch (Exception e) {
   Log.i("Exception", "PhoneStateListener() e = " + e);
  }
 }
};

Actually I call the first number and listen for the state of the phone. If the phone state changes to IDLE I call the second number. But it is not working.

Any one plz suggest me how to do that task.

Body:
If I understand your question properly, You are trying to call a number after completion of previous call.

Here is Algorithm for calling n numbers sequentially

Make Queue of numbers to call

Create and register Broadcast Receiver for PhoneState

Dequeue element and fire Intent for Call

Broadcast receiver created at point 2 will listen for call drop state
which is IDLE state,

if theres more element in queue repeat step 3-4

else, unregister broadcast receiver.

C# Code Snippet:

                Queue phoneNumbers = new Queue();

                foreach (var contact in emergencyContacts)
                    phoneNumbers.Enqueue(contact.contactNo);

                ShareUtils.CallToNumber(context, phoneNumbers.Dequeue().ToString());
                var callReceiver = new CallReceiver();
                callReceiver.onReceive += (intent) =>
                {
                    if (intent.Extras.GetString(TelephonyManager.ExtraState).Equals(TelephonyManager.ExtraStateIdle))
                    {
                        if (phoneNumbers.Count > 0)
                        {
                            var phNumber = phoneNumbers.Dequeue().ToString();
                            ShareUtils.CallToNumber(context, phNumber);
                            Toast.MakeText(this.Activity, $"Calling {phNumber}", ToastLength.Long).Show();
                        }
                        else
                        {
                            context.UnregisterReceiver(callReceiver);
                            ((LandingActivityNew)this.Activity)?.LoadSOS_SuccessFragment();
                        }
                    }
                };
                context.RegisterReceiver(callReceiver, new IntentFilter("android.intent.action.PHONE_STATE"));